diff --git a/.gitignore b/.gitignore index 4fff675801f..f1ea04e3efb 100644 --- a/.gitignore +++ b/.gitignore @@ -41,7 +41,9 @@ tests/cases/**/*.js.map scripts/debug.bat scripts/run.bat scripts/word2md.js +scripts/buildProtocol.js scripts/ior.js +scripts/buildProtocol.js scripts/*.js.map scripts/typings/ coverage/ diff --git a/.mailmap b/.mailmap index e66f669b8ee..ede478c8a18 100644 --- a/.mailmap +++ b/.mailmap @@ -1,32 +1,38 @@  -Alexander # Alexander Kuvaev AbubakerB # Abubaker Bashir +Alexander # Alexander Kuvaev Adam Freidin Adam Freidin Adi Dahiya Adi Dahiya Ahmad Farid ahmad-farid +Alexander Rusakov Alex Eagle +Anatoly Ressin Anders Hejlsberg unknown unknown +Andrej Baran Andrew Z Allen Andy Hanson Andy Anil Anar Anton Tolmachev Arnavion # Arnav Singh -Arthur Ozga Arthur Ozga +Arthur Ozga Arthur Ozga Arthur Ozga Arthur Ozga Arthur Ozga Asad Saeeduddin Schmavery # Avery Morin Basarat Ali Syed Basarat Syed basarat Bill Ticehurst Bill Ticehurst Ben Duffield +Ben Mosher Blake Embrey Bowden Kelly Brett Mayen Bryan Forbes Caitlin Potter ChrisBubernak unknown # Chris Bubernak +Christophe Vidal Chuck Jazdzewski Colby Russell Colin Snover Cyrus Najmabadi CyrusNajmabadi unknown +Dafrok # Dafrok Zhang Dan Corder Dan Quirk Dan Quirk nknown Daniel Rosenwasser Daniel Rosenwasser Daniel Rosenwasser Daniel Rosenwasser Daniel Rosenwasser @@ -36,17 +42,22 @@ Denis Nedelyaev Dick van den Brink unknown unknown Dirk Baeumer Dirk Bäumer # Dirk Bäumer Dirk Holtwick +Dom Chen Doug Ilijev Erik Edrosa +erictsangx # Eric Tsang Ethan Rubio Evan Martin Evan Sebastian Eyas # Eyas Sharaiha +Fabian Cook falsandtru # @falsandtru Frank Wallis -František Žiačik František Žiačik +František Žiacik František Žiacik +Gabe Moothart Gabriel Isenberg Gilad Peleg +Godfrey Chan Graeme Wicksted Guillaume Salles Guy Bedford guybedford @@ -55,6 +66,7 @@ Iain Monro Ingvar Stepanyan impinball # Isiah Meadows Ivo Gabe de Wolff +Jakub Młokosiewicz James Whitney Jason Freeman Jason Freeman Jason Killian @@ -69,11 +81,14 @@ Jonathan Park Jonathan Turner Jonathan Turner Jonathan Toland Jesse Schalken +Josh Abernathy joshaber Josh Kalderimis Josh Soref Juan Luis Boya García Julian Williams -Herrington Darkholme +Justin Bay +Justin Johansson +Herrington Darkholme (´·?·`) # Herrington Darkholme Kagami Sascha Rosylight SaschaNaz Kanchalai Tanglertsampan Yui Kanchalai Tanglertsampan Yui T @@ -82,23 +97,29 @@ Kanchalai Tanglertsampan Yui Kanchalai Tanglertsampan yui T Keith Mashinter kmashint Ken Howard +Kevin Lang kimamula # Kenji Imamula Kyle Kelley Lorant Pinter Lucien Greathouse +Lukas Elmer Lukas Elmer Martin Vseticka Martin Všeticka MartyIX +gcnew # Marin Marinov vvakame # Masahiro Wakame Matt McCutchen Max Deepfield Micah Zoltu +Michael Mohamed Hegazy Nathan Shively-Sanders Nathan Yee Nima Zahedi +Noah Chen Noj Vek mihailik # Oleg Mihailik Oleksandr Chekhovskyi Paul van Brenk Paul van Brenk unknown unknown unknown +Omer Sheikh Oskar Segersva¨rd pcan # Piero Cangianiello pcbro <2bux89+dk3zspjmuh16o@sharklasers.com> # @pcbro @@ -109,21 +130,26 @@ progre # @progre Prayag Verma Punya Biswal Rado Kirov -Ron Buckton Ron Buckton +Ron Buckton Ron Buckton rbuckton +Rostislav Galimsky Richard Knoll Richard Knoll Rowan Wyborn Ryan Cavanaugh Ryan Cavanaugh Ryan Cavanaugh Ryohei Ikegami Sarangan Rajamanickam Sébastien Arod +Sergey Shandar Sheetal Nandi Shengping Zhong shyyko.serhiy@gmail.com # Shyyko Serhiy +Sam El-Husseini Simon Hürlimann +Slawomir Sadziak Solal Pirelli Stan Thomas Stanislav Sysoev Steve Lucco steveluc +Sudheesh Singanamalla Tarik # Tarik Ozket Tetsuharu OHZEKI # Tetsuharu Ohzeki Tien Nguyen tien unknown #Tien Hoanhtien @@ -133,6 +159,7 @@ Tingan Ho togru # togru Tomas Grubliauskas ToddThomson # Todd Thomson +Torben Fitschen TruongSinh Tran-Nguyen vilicvane # Vilic Vane Vladimir Matveev vladima v2m @@ -140,7 +167,50 @@ Wesley Wigham Wesley Wigham York Yao york yao yaoyao Yuichi Nukiyama YuichiNukiyama Zev Spitz -Zhengbo Li zhengbli Zhengbo Li Zhengbo Li tinza123 unknown Zhengbo Li +Zhengbo Li zhengbli Zhengbo Li Zhengbo Li tinza123 unknown Zhengbo Li zhengbli zhongsp # Patrick Zhong T18970237136 # @T18970237136 -JBerger \ No newline at end of file +JBerger +bootstraponline # @bootstraponline +yortus # @yortus +András Parditka +Anton Khlynovskiy +Charly POLY +Cotton Hou +Ethan Resnick +Marius Schulz +Mattias Buelens +Myles Megyesi +Tim Lancina +Aaron Holmes Aaron Holmes +Akshar Patel +Ali Sabzevari +Aliaksandr Radzivanovich +BuildTools # Franklin Tse +ChogyDan # Daniel Hollocher +Daniel Rosenwasser Daniel Rosenwasser +David Kmenta +E020873 # Nicolas Henry +Elisée Maurer +Emilio García-Pumarino dashaus +Guilherme Oenning +Herrington Darkholme +Ivo Gabe de Wolff +Joey Wilson +Jonathon Smith +Juan Luis Boya García +Kagami Sascha Rosylight +Lucien Greathouse +Martin Vseticka +Mattias Buelens +Michael Bromley +Paul Jolly +Perry Jiang +Peter Burns +Robert Coie +Thomas Loubiou +Tim Perry +Vidar Tonaas Fauske +Viktor Zozulyak +rix # Richard Sentino +rohitverma007 # Rohit Verma \ No newline at end of file diff --git a/.npmignore b/.npmignore index 02d8fe428f9..d3c27afeff4 100644 --- a/.npmignore +++ b/.npmignore @@ -1,8 +1,11 @@ built doc +Gulpfile.ts internal issue_template.md +jenkins.sh lib/README.md +netci.groovy pull_request_template.md scripts src diff --git a/.travis.yml b/.travis.yml index c16ae086448..08bd7817c79 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ language: node_js node_js: - 'stable' + - '6' - '4' sudo: false @@ -15,7 +16,7 @@ matrix: branches: only: - master - - release-2.0 + - release-2.1 install: - npm uninstall typescript diff --git a/AUTHORS.md b/AUTHORS.md index 08039127d9d..ae7832176ea 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -1,14 +1,23 @@ TypeScript is authored by: +* Aaron Holmes * Abubaker Bashir * Adam Freidin * Adi Dahiya * Ahmad Farid +* Akshar Patel * Alex Eagle * Alexander Kuvaev +* Alexander Rusakov +* Ali Sabzevari +* Aliaksandr Radzivanovich +* Anatoly Ressin * Anders Hejlsberg +* Andrej Baran * Andrew Z Allen +* András Parditka * Andy Hanson * Anil Anar +* Anton Khlynovskiy * Anton Tolmachev * Arnav Singh * Arthur Ozga @@ -16,38 +25,56 @@ TypeScript is authored by: * Avery Morin * Basarat Ali Syed * Ben Duffield +* Ben Mosher * Bill Ticehurst * Blake Embrey +* @bootstraponline * Bowden Kelly * Brett Mayen * Bryan Forbes * Caitlin Potter +* Charly POLY * Chris Bubernak +* Christophe Vidal * Chuck Jazdzewski * Colby Russell * Colin Snover +* Cotton Hou * Cyrus Najmabadi +* Dafrok Zhang * Dan Corder * Dan Quirk +* Daniel Hollocher * Daniel Rosenwasser +* David Kmenta * David Li * David Souther * Denis Nedelyaev * Dick van den Brink * Dirk Bäumer * Dirk Holtwick +* Dom Chen * Doug Ilijev +* Elisée Maurer +* Emilio García-Pumarino +* Eric Tsang * Erik Edrosa +* Ethan Resnick * Ethan Rubio * Evan Martin * Evan Sebastian * Eyas Sharaiha +* Fabian Cook * @falsandtru * Frank Wallis -* František Žiačik +* Franklin Tse +* František Žiacik +* Gabe Moothart * Gabriel Isenberg * Gilad Peleg +* Godfrey Chan * Graeme Wicksted +* Guilherme Oenning * Guillaume Salles * Guy Bedford * Harald Niesche @@ -56,6 +83,7 @@ TypeScript is authored by: * Ingvar Stepanyan * Isiah Meadows * Ivo Gabe de Wolff +* Jakub Młokosiewicz * James Whitney * Jason Freeman * Jason Killian @@ -65,41 +93,61 @@ TypeScript is authored by: * Jeffrey Morlan * Jesse Schalken * Jiri Tobisek +* Joey Wilson * Johannes Rieken * John Vilk * Jonathan Bond-Caron * Jonathan Park * Jonathan Toland * Jonathan Turner +* Jonathon Smith +* Josh Abernathy * Josh Kalderimis * Josh Soref * Juan Luis Boya García * Julian Williams +* Justin Bay +* Justin Johansson * Kagami Sascha Rosylight * Kanchalai Tanglertsampan * Keith Mashinter * Ken Howard * Kenji Imamula +* Kevin Lang * Kyle Kelley * Lorant Pinter * Lucien Greathouse +* Lukas Elmer +* Marin Marinov +* Marius Schulz * Martin Vseticka * Masahiro Wakame * Matt McCutchen +* Mattias Buelens +* Mattias Buelens * Max Deepfield * Micah Zoltu +* Michael +* Michael Bromley * Mohamed Hegazy +* Myles Megyesi * Nathan Shively-Sanders * Nathan Yee +* Nicolas Henry * Nima Zahedi +* Noah Chen * Noj Vek * Oleg Mihailik * Oleksandr Chekhovskyi +* Omer Sheikh * Oskar Segersva¨rd * Patrick Zhong +* Paul Jolly * Paul van Brenk * @pcbro * Pedro Maltez +* Perry Jiang +* Peter Burns * Philip Bulley * Piero Cangianiello * @piloopin @@ -108,34 +156,49 @@ TypeScript is authored by: * Punya Biswal * Rado Kirov * Richard Knoll +* Richard Sentino +* Robert Coie +* Rohit Verma * Ron Buckton +* Rostislav Galimsky * Rowan Wyborn * Ryan Cavanaugh * Ryohei Ikegami +* Sam El-Husseini * Sarangan Rajamanickam +* Sergey Shandar * Sheetal Nandi * Shengping Zhong * Shyyko Serhiy * Simon Hürlimann +* Slawomir Sadziak * Solal Pirelli * Stan Thomas * Stanislav Sysoev * Steve Lucco +* Sudheesh Singanamalla * Sébastien Arod * @T18970237136 * Tarik Ozket +* Tetsuharu Ohzeki +* Thomas Loubiou * Tien Hoanhtien +* Tim Lancina * Tim Perry * Tim Viiding-Spader * Tingan Ho * Todd Thomson * togru * Tomas Grubliauskas +* Torben Fitschen * TruongSinh Tran-Nguyen +* Vidar Tonaas Fauske +* Viktor Zozulyak * Vilic Vane * Vladimir Matveev * Wesley Wigham * York Yao +* @yortus * Yuichi Nukiyama * Zev Spitz * Zhengbo Li \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c242022979..6dbb7e514a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -183,5 +183,3 @@ jake baseline-accept ``` to establish the new baselines as the desired behavior. This will change the files in `tests\baselines\reference`, which should be included as part of your commit. It's important to carefully validate changes in the baselines. - -**Note** that `baseline-accept` should only be run after a full test run! Accepting baselines after running a subset of tests will delete baseline files for the tests that didn't run. diff --git a/Gulpfile.ts b/Gulpfile.ts index ebedfd43c23..054e99c8003 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -128,7 +128,8 @@ const es2016LibrarySourceMap = es2016LibrarySource.map(function(source) { const es2017LibrarySource = [ "es2017.object.d.ts", - "es2017.sharedmemory.d.ts" + "es2017.sharedmemory.d.ts", + "es2017.string.d.ts", ]; const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) { @@ -176,7 +177,7 @@ for (const i in libraryTargets) { 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"); +const versionFile = path.join(compilerDirectory, "core.ts"); function needsUpdate(source: string | string[], dest: string | string[]): boolean { if (typeof source === "string" && typeof dest === "string") { @@ -284,7 +285,7 @@ gulp.task(configureNightlyJs, false, [], () => { // 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); + exec(host, [configureNightlyJs, packageJson, versionFile], 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) => { diff --git a/Jakefile.js b/Jakefile.js index 64a8553ef39..275303dda13 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -70,13 +70,16 @@ var compilerSources = [ "visitor.ts", "transformers/destructuring.ts", "transformers/ts.ts", - "transformers/module/es6.ts", + "transformers/jsx.ts", + "transformers/esnext.ts", + "transformers/es2017.ts", + "transformers/es2016.ts", + "transformers/es2015.ts", + "transformers/generators.ts", + "transformers/es5.ts", + "transformers/module/es2015.ts", "transformers/module/system.ts", "transformers/module/module.ts", - "transformers/jsx.ts", - "transformers/es7.ts", - "transformers/generators.ts", - "transformers/es6.ts", "transformer.ts", "sourcemap.ts", "comments.ts", @@ -104,13 +107,16 @@ var servicesSources = [ "visitor.ts", "transformers/destructuring.ts", "transformers/ts.ts", - "transformers/module/es6.ts", + "transformers/jsx.ts", + "transformers/esnext.ts", + "transformers/es2017.ts", + "transformers/es2016.ts", + "transformers/es2015.ts", + "transformers/generators.ts", + "transformers/es5.ts", + "transformers/module/es2015.ts", "transformers/module/system.ts", "transformers/module/module.ts", - "transformers/jsx.ts", - "transformers/es7.ts", - "transformers/generators.ts", - "transformers/es6.ts", "transformer.ts", "sourcemap.ts", "comments.ts", @@ -167,6 +173,7 @@ var servicesSources = [ var serverCoreSources = [ "types.d.ts", + "shared.ts", "utilities.ts", "scriptVersionCache.ts", "typingsCache.ts", @@ -174,7 +181,7 @@ var serverCoreSources = [ "lsHost.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", + "protocol.ts", "session.ts", "server.ts" ].map(function (f) { @@ -189,6 +196,7 @@ var cancellationTokenSources = [ var typingsInstallerSources = [ "../types.d.ts", + "../shared.ts", "typingsInstaller.ts", "nodeTypingsInstaller.ts" ].map(function (f) { @@ -198,14 +206,13 @@ var typingsInstallerSources = [ var serverSources = serverCoreSources.concat(servicesSources); var languageServiceLibrarySources = [ - "protocol.d.ts", + "protocol.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", "lsHost.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", "session.ts", ].map(function (f) { @@ -243,13 +250,14 @@ var harnessSources = harnessCoreSources.concat([ "convertToBase64.ts", "transpile.ts", "reuseProgramStructure.ts", + "textStorage.ts", "cachingInServerLSHost.ts", "moduleResolution.ts", "tsconfigParsing.ts", "commandLineParsing.ts", "configurationExtension.ts", "convertCompilerOptionsFromJson.ts", - "convertTypingOptionsFromJson.ts", + "convertTypeAcquisitionFromJson.ts", "tsserverProjectSystem.ts", "compileOnSave.ts", "typingsInstaller.ts", @@ -259,7 +267,7 @@ var harnessSources = harnessCoreSources.concat([ ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ - "protocol.d.ts", + "protocol.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", @@ -267,7 +275,6 @@ var harnessSources = harnessCoreSources.concat([ "project.ts", "typingsCache.ts", "editorServices.ts", - "protocol.d.ts", "session.ts", ].map(function (f) { return path.join(serverDirectory, f); @@ -297,7 +304,8 @@ var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) { var es2017LibrarySource = [ "es2017.object.d.ts", - "es2017.sharedmemory.d.ts" + "es2017.sharedmemory.d.ts", + "es2017.string.d.ts", ]; var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { @@ -345,18 +353,16 @@ function prependFile(prefixFile, destinationFile) { // concatenate a list of sourceFiles to a destinationFile function concatenateFiles(destinationFile, sourceFiles) { var temp = "temptemp"; - // Copy the first file to temp - if (!fs.existsSync(sourceFiles[0])) { - fail(sourceFiles[0] + " does not exist!"); - } - jake.cpR(sourceFiles[0], temp, { silent: true }); // append all files in sequence - for (var i = 1; i < sourceFiles.length; i++) { + var text = ""; + for (var i = 0; i < sourceFiles.length; i++) { if (!fs.existsSync(sourceFiles[i])) { fail(sourceFiles[i] + " does not exist!"); } - fs.appendFileSync(temp, fs.readFileSync(sourceFiles[i])); + if (i > 0) { text += "\n\n"; } + text += fs.readFileSync(sourceFiles[i]).toString().replace(/\r?\n/g, "\n"); } + fs.writeFileSync(temp, text); // Move the file to the final destination fs.renameSync(temp, destinationFile); } @@ -445,6 +451,8 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts options += " --stripInternal"; } + options += " --target es5 --noUnusedLocals --noUnusedParameters"; + var cmd = host + " " + compilerPath + " " + options + " "; cmd = cmd + sources.join(" "); console.log(cmd + "\n"); @@ -518,6 +526,40 @@ compileFile(processDiagnosticMessagesJs, [], /*useBuiltCompiler*/ false); +var buildProtocolTs = path.join(scriptsDirectory, "buildProtocol.ts"); +var buildProtocolJs = path.join(scriptsDirectory, "buildProtocol.js"); +var buildProtocolDts = path.join(builtLocalDirectory, "protocol.d.ts"); +var typescriptServicesDts = path.join(builtLocalDirectory, "typescriptServices.d.ts"); + +file(buildProtocolTs); + +compileFile(buildProtocolJs, + [buildProtocolTs], + [buildProtocolTs], + [], + /*useBuiltCompiler*/ false, + {noOutFile: true}); + +file(buildProtocolDts, [buildProtocolTs, buildProtocolJs, typescriptServicesDts], function() { + + var protocolTs = path.join(serverDirectory, "protocol.ts"); + + var cmd = host + " " + buildProtocolJs + " "+ protocolTs + " " + typescriptServicesDts + " " + buildProtocolDts; + console.log(cmd); + var ex = jake.createExec([cmd]); + // Add listeners for output and error + ex.addListener("stdout", function (output) { + process.stdout.write(output); + }); + ex.addListener("stderr", function (error) { + process.stderr.write(error); + }); + ex.addListener("cmdEnd", function () { + complete(); + }); + ex.run(); +}, { async: true }) + // The generated diagnostics map; built for the compiler and for the 'generate-diagnostics' task file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson], function () { var cmd = host + " " + processDiagnosticMessagesJs + " " + diagnosticMessagesJson; @@ -549,7 +591,7 @@ task("generate-diagnostics", [diagnosticInfoMapTs]); var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js"); var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts"); var packageJson = "package.json"; -var programTs = path.join(compilerDirectory, "program.ts"); +var versionFile = path.join(compilerDirectory, "core.ts"); file(configureNightlyTs); @@ -565,7 +607,7 @@ task("setDebugMode", function () { }); task("configure-nightly", [configureNightlyJs], function () { - var cmd = host + " " + configureNightlyJs + " " + packageJson + " " + programTs; + var cmd = host + " " + configureNightlyJs + " " + packageJson + " " + versionFile; console.log(cmd); exec(cmd); }, { async: true }); @@ -596,7 +638,7 @@ task("importDefinitelyTypedTests", [importDefinitelyTypedTestsJs], function () { // Local target to build the compiler and services var tscFile = path.join(builtLocalDirectory, compilerFilename); -compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false); +compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false, { noMapRoot: true }); var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js"); @@ -655,6 +697,8 @@ compileFile( inlineSourceMap: true }); +file(typescriptServicesDts, [servicesFile]); + var cancellationTokenFile = path.join(builtLocalDirectory, "cancellationToken.js"); compileFile(cancellationTokenFile, cancellationTokenSources, [builtLocalDirectory].concat(cancellationTokenSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { outDir: builtLocalDirectory, noOutFile: true }); @@ -689,7 +733,7 @@ task("build-fold-end", [], function () { // Local target to build the compiler and services desc("Builds the full compiler and services"); -task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]); +task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, buildProtocolDts, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]); // Local target to build only tsc.js desc("Builds only the compiler"); @@ -745,7 +789,7 @@ task("generate-spec", [specMd]); // Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory desc("Makes a new LKG out of the built js files"); task("LKG", ["clean", "release", "local"].concat(libraryTargets), function () { - var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile].concat(libraryTargets); + var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile, buildProtocolDts].concat(libraryTargets); var missingFiles = expectedFiles.filter(function (f) { return !fs.existsSync(f); }); @@ -884,7 +928,7 @@ function runConsoleTests(defaultReporter, runInParallel) { } if (tests && tests.toLocaleLowerCase() === "rwc") { - testTimeout = 400000; + testTimeout = 800000; } colors = process.env.colors || process.env.color; @@ -1040,12 +1084,10 @@ task("tests-debug", ["setDebugMode", "tests"]); // Makes the test results the new baseline desc("Makes the most recent test results the new baseline, overwriting the old baseline"); task("baseline-accept", function () { - acceptBaseline(""); + acceptBaseline(localBaseline, refBaseline); }); -function acceptBaseline(containerFolder) { - var sourceFolder = path.join(localBaseline, containerFolder); - var targetFolder = path.join(refBaseline, containerFolder); +function acceptBaseline(sourceFolder, targetFolder) { console.log('Accept baselines from ' + sourceFolder + ' to ' + targetFolder); var files = fs.readdirSync(sourceFolder); var deleteEnding = '.delete'; @@ -1069,12 +1111,12 @@ function acceptBaseline(containerFolder) { desc("Makes the most recent rwc test results the new baseline, overwriting the old baseline"); task("baseline-accept-rwc", function () { - acceptBaseline("rwc"); + acceptBaseline(localRwcBaseline, refRwcBaseline); }); desc("Makes the most recent test262 test results the new baseline, overwriting the old baseline"); task("baseline-accept-test262", function () { - acceptBaseline("test262"); + acceptBaseline(localTest262Baseline, refTest262Baseline); }); diff --git a/issue_template.md b/issue_template.md index 7799960ec78..4d397a0afd6 100644 --- a/issue_template.md +++ b/issue_template.md @@ -2,7 +2,7 @@ -**TypeScript Version:** 1.8.0 / nightly (2.0.0-dev.201xxxxx) +**TypeScript Version:** 2.1.1 / nightly (2.2.0-dev.201xxxxx) **Code** @@ -13,4 +13,4 @@ **Expected behavior:** -**Actual behavior:** +**Actual behavior:** diff --git a/jenkins.sh b/jenkins.sh new file mode 100755 index 00000000000..377a44b7bf7 --- /dev/null +++ b/jenkins.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# Set up NVM +export NVM_DIR="/home/dotnet-bot/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" + +nvm install $1 + +npm uninstall typescript +npm uninstall tslint +npm install +npm update +npm test diff --git a/lib/.gitattributes b/lib/.gitattributes new file mode 100644 index 00000000000..fcadb2cf979 --- /dev/null +++ b/lib/.gitattributes @@ -0,0 +1 @@ +* text eol=lf diff --git a/lib/README.md b/lib/README.md index 852d449f1e5..0a85a9e7b5c 100644 --- a/lib/README.md +++ b/lib/README.md @@ -1,5 +1,5 @@ -# Read This! - -**These files are not meant to be edited by hand.** -If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. -Running `jake LKG` will then appropriately update the files in this directory. +# Read This! + +**These files are not meant to be edited by hand.** +If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. +Running `jake LKG` will then appropriately update the files in this directory. diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 8af21172df4..003999d2e8a 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + "use strict"; var fs = require("fs"); function createCancellationToken(args) { diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 586b3675305..5b1f3d7c393 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1,19045 +1,18215 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -///////////////////////////// -/// ECMAScript APIs -///////////////////////////// - -declare const NaN: number; -declare const Infinity: number; - -/** - * Evaluates JavaScript code and executes it. - * @param x A String value that contains valid JavaScript code. - */ -declare function eval(x: string): any; - -/** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ -declare function parseInt(s: string, radix?: number): number; - -/** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ -declare function parseFloat(string: string): number; - -/** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). - * @param number A numeric value. - */ -declare function isNaN(number: number): boolean; - -/** - * Determines whether a supplied number is finite. - * @param number Any numeric value. - */ -declare function isFinite(number: number): boolean; - -/** - * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). - * @param encodedURI A value representing an encoded URI. - */ -declare function decodeURI(encodedURI: string): string; - -/** - * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). - * @param encodedURIComponent A value representing an encoded URI component. - */ -declare function decodeURIComponent(encodedURIComponent: string): string; - -/** - * Encodes a text string as a valid Uniform Resource Identifier (URI) - * @param uri A value representing an encoded URI. - */ -declare function encodeURI(uri: string): string; - -/** - * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). - * @param uriComponent A value representing an encoded URI component. - */ -declare function encodeURIComponent(uriComponent: string): string; - -interface PropertyDescriptor { - configurable?: boolean; - enumerable?: boolean; - value?: any; - writable?: boolean; - get? (): any; - set? (v: any): void; -} - -interface PropertyDescriptorMap { - [s: string]: PropertyDescriptor; -} - -interface Object { - /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ - constructor: Function; - - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns a date converted to a string using the current locale. */ - toLocaleString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; - - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: string): boolean; - - /** - * Determines whether an object exists in another object's prototype chain. - * @param v Another object whose prototype chain is to be checked. - */ - isPrototypeOf(v: Object): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: string): boolean; -} - -interface ObjectConstructor { - new (value?: any): Object; - (): any; - (value: any): any; - - /** A reference to the prototype for a class of objects. */ - readonly prototype: Object; - - /** - * Returns the prototype of an object. - * @param o The object that references the prototype. - */ - getPrototypeOf(o: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; - - /** - * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly - * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. - * @param o Object that contains the own properties. - */ - getOwnPropertyNames(o: any): string[]; - - /** - * Creates an object that has null prototype. - * @param o Object to use as a prototype. May be null - */ - create(o: null): any; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - */ - create(o: T): T; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - * @param properties JavaScript object that contains one or more property descriptors. - */ - create(o: any, properties: PropertyDescriptorMap): any; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor property. - */ - defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; - - /** - * Adds one or more properties to an object, and/or modifies attributes of existing properties. - * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. - * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. - */ - defineProperties(o: any, properties: PropertyDescriptorMap): any; - - /** - * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - seal(o: T): T; - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(o: T): T; - - /** - * Prevents the addition of new properties to an object. - * @param o Object to make non-extensible. - */ - preventExtensions(o: T): T; - - /** - * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. - * @param o Object to test. - */ - isSealed(o: any): boolean; - - /** - * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. - * @param o Object to test. - */ - isFrozen(o: any): boolean; - - /** - * Returns a value that indicates whether new properties can be added to an object. - * @param o Object to test. - */ - isExtensible(o: any): boolean; - - /** - * Returns the names of the enumerable properties and methods of an object. - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - keys(o: any): string[]; -} - -/** - * Provides functionality common to all JavaScript objects. - */ -declare const Object: ObjectConstructor; - -/** - * Creates a new function. - */ -interface Function { - /** - * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. - * @param thisArg The object to be used as the this object. - * @param argArray A set of arguments to be passed to the function. - */ - apply(this: Function, thisArg: any, argArray?: any): any; - - /** - * Calls a method of an object, substituting another object for the current object. - * @param thisArg The object to be used as the current object. - * @param argArray A list of arguments to be passed to the method. - */ - call(this: Function, thisArg: any, ...argArray: any[]): any; - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg An object to which the this keyword can refer inside the new function. - * @param argArray A list of arguments to be passed to the new function. - */ - bind(this: Function, thisArg: any, ...argArray: any[]): any; - - prototype: any; - readonly length: number; - - // Non-standard extensions - arguments: any; - caller: Function; -} - -interface FunctionConstructor { - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - readonly prototype: Function; -} - -declare const Function: FunctionConstructor; - -interface IArguments { - [index: number]: any; - length: number; - callee: Function; -} - -interface String { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): RegExpMatchArray | null; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): RegExpMatchArray | null; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Removes the leading and trailing white space and line terminator characters from a string. */ - trim(): string; - - /** Returns the length of a String object. */ - readonly length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): string; - - readonly [index: number]: string; -} - -interface StringConstructor { - new (value?: any): String; - (value?: any): string; - readonly prototype: String; - fromCharCode(...codes: number[]): string; -} - -/** - * Allows manipulation and formatting of text strings and determination and location of substrings within strings. - */ -declare const String: StringConstructor; - -interface Boolean { - /** Returns the primitive value of the specified object. */ - valueOf(): boolean; -} - -interface BooleanConstructor { - new (value?: any): Boolean; - (value?: any): boolean; - readonly prototype: Boolean; -} - -declare const Boolean: BooleanConstructor; - -interface Number { - /** - * Returns a string representation of an object. - * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. - */ - toString(radix?: number): string; - - /** - * Returns a string representing a number in fixed-point notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toFixed(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented in exponential notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toExponential(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. - * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. - */ - toPrecision(precision?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): number; -} - -interface NumberConstructor { - new (value?: any): Number; - (value?: any): number; - readonly prototype: Number; - - /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - readonly MAX_VALUE: number; - - /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - readonly MIN_VALUE: number; - - /** - * A value that is not a number. - * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. - */ - readonly NaN: number; - - /** - * A value that is less than the largest negative number that can be represented in JavaScript. - * JavaScript displays NEGATIVE_INFINITY values as -infinity. - */ - readonly NEGATIVE_INFINITY: number; - - /** - * A value greater than the largest number that can be represented in JavaScript. - * JavaScript displays POSITIVE_INFINITY values as infinity. - */ - readonly POSITIVE_INFINITY: number; -} - -/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare const Number: NumberConstructor; - -interface TemplateStringsArray extends ReadonlyArray { - readonly raw: ReadonlyArray -} - -interface Math { - /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - readonly E: number; - /** The natural logarithm of 10. */ - readonly LN10: number; - /** The natural logarithm of 2. */ - readonly LN2: number; - /** The base-2 logarithm of e. */ - readonly LOG2E: number; - /** The base-10 logarithm of e. */ - readonly LOG10E: number; - /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - readonly PI: number; - /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - readonly SQRT1_2: number; - /** The square root of 2. */ - readonly SQRT2: number; - /** - * Returns the absolute value of a number (the value without regard to whether it is positive or negative). - * For example, the absolute value of -5 is the same as the absolute value of 5. - * @param x A numeric expression for which the absolute value is needed. - */ - abs(x: number): number; - /** - * Returns the arc cosine (or inverse cosine) of a number. - * @param x A numeric expression. - */ - acos(x: number): number; - /** - * Returns the arcsine of a number. - * @param x A numeric expression. - */ - asin(x: number): number; - /** - * Returns the arctangent of a number. - * @param x A numeric expression for which the arctangent is needed. - */ - atan(x: number): number; - /** - * Returns the angle (in radians) from the X axis to a point. - * @param y A numeric expression representing the cartesian y-coordinate. - * @param x A numeric expression representing the cartesian x-coordinate. - */ - atan2(y: number, x: number): number; - /** - * Returns the smallest number greater than or equal to its numeric argument. - * @param x A numeric expression. - */ - ceil(x: number): number; - /** - * Returns the cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cos(x: number): number; - /** - * Returns e (the base of natural logarithms) raised to a power. - * @param x A numeric expression representing the power of e. - */ - exp(x: number): number; - /** - * Returns the greatest number less than or equal to its numeric argument. - * @param x A numeric expression. - */ - floor(x: number): number; - /** - * Returns the natural logarithm (base e) of a number. - * @param x A numeric expression. - */ - log(x: number): number; - /** - * Returns the larger of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - max(...values: number[]): number; - /** - * Returns the smaller of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - min(...values: number[]): number; - /** - * Returns the value of a base expression taken to a specified power. - * @param x The base value of the expression. - * @param y The exponent value of the expression. - */ - pow(x: number, y: number): number; - /** Returns a pseudorandom number between 0 and 1. */ - random(): number; - /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. - */ - round(x: number): number; - /** - * Returns the sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sin(x: number): number; - /** - * Returns the square root of a number. - * @param x A numeric expression. - */ - sqrt(x: number): number; - /** - * Returns the tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tan(x: number): number; -} -/** An intrinsic object that provides basic mathematics functionality and constants. */ -declare const Math: Math; - -/** Enables basic storage and retrieval of dates and times. */ -interface Date { - /** Returns a string representation of a date. The format of the string depends on the locale. */ - toString(): string; - /** Returns a date as a string value. */ - toDateString(): string; - /** Returns a time as a string value. */ - toTimeString(): string; - /** Returns a value as a string value appropriate to the host environment's current locale. */ - toLocaleString(): string; - /** Returns a date as a string value appropriate to the host environment's current locale. */ - toLocaleDateString(): string; - /** Returns a time as a string value appropriate to the host environment's current locale. */ - toLocaleTimeString(): string; - /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ - valueOf(): number; - /** Gets the time value in milliseconds. */ - getTime(): number; - /** Gets the year, using local time. */ - getFullYear(): number; - /** Gets the year using Universal Coordinated Time (UTC). */ - getUTCFullYear(): number; - /** Gets the month, using local time. */ - getMonth(): number; - /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ - getUTCMonth(): number; - /** Gets the day-of-the-month, using local time. */ - getDate(): number; - /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ - getUTCDate(): number; - /** Gets the day of the week, using local time. */ - getDay(): number; - /** Gets the day of the week using Universal Coordinated Time (UTC). */ - getUTCDay(): number; - /** Gets the hours in a date, using local time. */ - getHours(): number; - /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ - getUTCHours(): number; - /** Gets the minutes of a Date object, using local time. */ - getMinutes(): number; - /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ - getUTCMinutes(): number; - /** Gets the seconds of a Date object, using local time. */ - getSeconds(): number; - /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCSeconds(): number; - /** Gets the milliseconds of a Date, using local time. */ - getMilliseconds(): number; - /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCMilliseconds(): number; - /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ - getTimezoneOffset(): number; - /** - * Sets the date and time value in the Date object. - * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. - */ - setTime(time: number): number; - /** - * Sets the milliseconds value in the Date object using local time. - * @param ms A numeric value equal to the millisecond value. - */ - setMilliseconds(ms: number): number; - /** - * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). - * @param ms A numeric value equal to the millisecond value. - */ - setUTCMilliseconds(ms: number): number; - - /** - * Sets the seconds value in the Date object using local time. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setSeconds(sec: number, ms?: number): number; - /** - * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCSeconds(sec: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using local time. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the hour value in the Date object using local time. - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the hours value in the Date object using Universal Coordinated Time (UTC). - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the numeric day-of-the-month value of the Date object using local time. - * @param date A numeric value equal to the day of the month. - */ - setDate(date: number): number; - /** - * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). - * @param date A numeric value equal to the day of the month. - */ - setUTCDate(date: number): number; - /** - * Sets the month value in the Date object using local time. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. - */ - setMonth(month: number, date?: number): number; - /** - * Sets the month value in the Date object using Universal Coordinated Time (UTC). - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. - */ - setUTCMonth(month: number, date?: number): number; - /** - * Sets the year of the Date object using local time. - * @param year A numeric value for the year. - * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. - * @param date A numeric value equal for the day of the month. - */ - setFullYear(year: number, month?: number, date?: number): number; - /** - * Sets the year value in the Date object using Universal Coordinated Time (UTC). - * @param year A numeric value equal to the year. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. - * @param date A numeric value equal to the day of the month. - */ - setUTCFullYear(year: number, month?: number, date?: number): number; - /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ - toUTCString(): string; - /** Returns a date as a string value in ISO format. */ - toISOString(): string; - /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ - toJSON(key?: any): string; -} - -interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; - (): string; - readonly prototype: Date; - /** - * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. - * @param s A date string - */ - parse(s: string): number; - /** - * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. - * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. - */ - UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; - now(): number; -} - -declare const Date: DateConstructor; - -interface RegExpMatchArray extends Array { - index?: number; - input?: string; -} - -interface RegExpExecArray extends Array { - index: number; - input: string; -} - -interface RegExp { - /** - * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. - * @param string The String object or string literal on which to perform the search. - */ - exec(string: string): RegExpExecArray | null; - - /** - * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. - * @param string String on which to perform the search. - */ - test(string: string): boolean; - - /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - readonly source: string; - - /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - readonly global: boolean; - - /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - readonly ignoreCase: boolean; - - /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - readonly multiline: boolean; - - lastIndex: number; - - // Non-standard extensions - compile(): this; -} - -interface RegExpConstructor { - new (pattern: RegExp): RegExp; - new (pattern: string, flags?: string): RegExp; - (pattern: RegExp): RegExp; - (pattern: string, flags?: string): RegExp; - readonly prototype: RegExp; - - // Non-standard extensions - $1: string; - $2: string; - $3: string; - $4: string; - $5: string; - $6: string; - $7: string; - $8: string; - $9: string; - lastMatch: string; -} - -declare const RegExp: RegExpConstructor; - -interface Error { - name: string; - message: string; - stack?: string; -} - -interface ErrorConstructor { - new (message?: string): Error; - (message?: string): Error; - readonly prototype: Error; -} - -declare const Error: ErrorConstructor; - -interface EvalError extends Error { -} - -interface EvalErrorConstructor { - new (message?: string): EvalError; - (message?: string): EvalError; - readonly prototype: EvalError; -} - -declare const EvalError: EvalErrorConstructor; - -interface RangeError extends Error { -} - -interface RangeErrorConstructor { - new (message?: string): RangeError; - (message?: string): RangeError; - readonly prototype: RangeError; -} - -declare const RangeError: RangeErrorConstructor; - -interface ReferenceError extends Error { -} - -interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; - (message?: string): ReferenceError; - readonly prototype: ReferenceError; -} - -declare const ReferenceError: ReferenceErrorConstructor; - -interface SyntaxError extends Error { -} - -interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; - (message?: string): SyntaxError; - readonly prototype: SyntaxError; -} - -declare const SyntaxError: SyntaxErrorConstructor; - -interface TypeError extends Error { -} - -interface TypeErrorConstructor { - new (message?: string): TypeError; - (message?: string): TypeError; - readonly prototype: TypeError; -} - -declare const TypeError: TypeErrorConstructor; - -interface URIError extends Error { -} - -interface URIErrorConstructor { - new (message?: string): URIError; - (message?: string): URIError; - readonly prototype: URIError; -} - -declare const URIError: URIErrorConstructor; - -interface JSON { - /** - * Converts a JavaScript Object Notation (JSON) string into an object. - * @param text A valid JSON string. - * @param reviver A function that transforms the results. This function is called for each member of the object. - * If a member contains nested objects, the nested objects are transformed before the parent object is. - */ - parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; -} - -/** - * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. - */ -declare const JSON: JSON; - - -///////////////////////////// -/// ECMAScript Array API (specially handled by compiler) -///////////////////////////// - -interface ReadonlyArray { - /** - * Gets the length of the array. This is a number one higher than the highest element defined in an array. - */ - readonly length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat>(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - - readonly [n: number]: T; -} - -interface Array { - /** - * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - */ - length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Appends new elements to an array, and returns the new length of the array. - * @param items New elements of the Array. - */ - push(...items: T[]): number; - /** - * Removes the last element from an array and returns it. - */ - pop(): T | undefined; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Reverses the elements in an Array. - */ - reverse(): T[]; - /** - * Removes the first element from an array and returns it. - */ - shift(): T | undefined; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: T, b: T) => number): this; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - */ - splice(start: number): T[]; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** - * Inserts new elements at the start of an array. - * @param items Elements to insert at the start of the Array. - */ - unshift(...items: T[]): number; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - [n: number]: T; -} - -interface ArrayConstructor { - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): arg is Array; - readonly prototype: Array; -} - -declare const Array: ArrayConstructor; - -interface TypedPropertyDescriptor { - enumerable?: boolean; - configurable?: boolean; - writable?: boolean; - value?: T; - get?: () => T; - set?: (value: T) => void; -} - -declare type ClassDecorator = (target: TFunction) => TFunction | void; -declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; -declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; -declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; - -declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; - -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) => T | PromiseLike) | undefined | null, - onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, - 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. - * @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) | undefined | null): 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; -} - -interface ArrayLike { - readonly length: number; - readonly [n: number]: T; -} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - /** - * Read-only. The length of the ArrayBuffer (in bytes). - */ - readonly byteLength: number; - - /** - * Returns a section of an ArrayBuffer. - */ - slice(begin:number, end?:number): ArrayBuffer; -} - -interface ArrayBufferConstructor { - readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; - isView(arg: any): arg is ArrayBufferView; -} -declare const ArrayBuffer: ArrayBufferConstructor; - -interface ArrayBufferView { - /** - * The ArrayBuffer instance referenced by the array. - */ - buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - byteLength: number; - - /** - * The offset in bytes of the array. - */ - byteOffset: number; -} - -interface DataView { - readonly buffer: ArrayBuffer; - readonly byteLength: number; - readonly byteOffset: number; - /** - * Gets the Float32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Float64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat64(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Int8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt8(byteOffset: number): number; - - /** - * Gets the Int16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt16(byteOffset: number, littleEndian?: boolean): number; - /** - * Gets the Int32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint8(byteOffset: number): number; - - /** - * Gets the Uint16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint16(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Stores an Float32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Float64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setInt8(byteOffset: number, value: number): void; - - /** - * Stores an Int16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setUint8(byteOffset: number, value: number): void; - - /** - * Stores an Uint16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; -} - -interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; -} -declare const DataView: DataViewConstructor; - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} -interface Int8ArrayConstructor { - readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - -} -declare const Int8Array: Int8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ArrayConstructor { - readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; - -} -declare const Uint8Array: Uint8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8ClampedArray; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: Uint8ClampedArray, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8ClampedArray; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8ClampedArray; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ClampedArrayConstructor { - readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8ClampedArray; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} -declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int16ArrayConstructor { - readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - -} -declare const Int16Array: Int16ArrayConstructor; - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint16ArrayConstructor { - readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - -} -declare const Uint16Array: Uint16ArrayConstructor; -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int32ArrayConstructor { - readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} -declare const Int32Array: Int32ArrayConstructor; - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint32ArrayConstructor { - readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} -declare const Uint32Array: Uint32ArrayConstructor; - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float32ArrayConstructor { - readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - -} -declare const Float32Array: Float32ArrayConstructor; - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float64Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float64Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float64Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float64ArrayConstructor { - readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} -declare const Float64Array: Float64ArrayConstructor; - -///////////////////////////// -/// ECMAScript Internationalization API -///////////////////////////// - -declare module Intl { - interface CollatorOptions { - usage?: string; - localeMatcher?: string; - numeric?: boolean; - caseFirst?: string; - sensitivity?: string; - ignorePunctuation?: boolean; - } - - interface ResolvedCollatorOptions { - locale: string; - usage: string; - sensitivity: string; - ignorePunctuation: boolean; - collation: string; - caseFirst: string; - numeric: boolean; - } - - interface Collator { - compare(x: string, y: string): number; - resolvedOptions(): ResolvedCollatorOptions; - } - var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; - (locales?: string | string[], options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; - } - - interface NumberFormatOptions { - localeMatcher?: string; - style?: string; - currency?: string; - currencyDisplay?: string; - useGrouping?: boolean; - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - } - - interface ResolvedNumberFormatOptions { - locale: string; - numberingSystem: string; - style: string; - currency?: string; - currencyDisplay?: string; - minimumIntegerDigits: number; - minimumFractionDigits: number; - maximumFractionDigits: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - useGrouping: boolean; - } - - interface NumberFormat { - format(value: number): string; - resolvedOptions(): ResolvedNumberFormatOptions; - } - var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; - } - - interface DateTimeFormatOptions { - localeMatcher?: string; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - formatMatcher?: string; - hour12?: boolean; - timeZone?: string; - } - - interface ResolvedDateTimeFormatOptions { - locale: string; - calendar: string; - numberingSystem: string; - timeZone: string; - hour12?: boolean; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - } - - interface DateTimeFormat { - format(date?: Date | number): string; - resolvedOptions(): ResolvedDateTimeFormatOptions; - } - var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; - } -} - -interface String { - /** - * Determines whether two strings are equivalent in the current or specified locale. - * @param that String to compare to target string - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; -} - -interface Number { - /** - * Converts a number to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; -} - -interface Date { - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - /** - * Converts a date to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; -} - -///////////////////////////// -/// IE DOM APIs -///////////////////////////// - -interface Algorithm { - name: string; -} - -interface AriaRequestEventInit extends EventInit { - attributeName?: string; - attributeValue?: string; -} - -interface CommandEventInit extends EventInit { - commandName?: string; - detail?: string; -} - -interface CompositionEventInit extends UIEventInit { - data?: string; -} - -interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { - arrayOfDomainStrings?: string[]; -} - -interface ConstrainBooleanParameters { - exact?: boolean; - ideal?: boolean; -} - -interface ConstrainDOMStringParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface ConstrainDoubleRange extends DoubleRange { - exact?: number; - ideal?: number; -} - -interface ConstrainLongRange extends LongRange { - exact?: number; - ideal?: number; -} - -interface ConstrainVideoFacingModeParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface CustomEventInit extends EventInit { - detail?: any; -} - -interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; -} - -interface DeviceLightEventInit extends EventInit { - value?: number; -} - -interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; -} - -interface DoubleRange { - max?: number; - min?: number; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; -} - -interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; - altKey?: boolean; - metaKey?: boolean; - modifierAltGraph?: boolean; - modifierCapsLock?: boolean; - modifierFn?: boolean; - modifierFnLock?: boolean; - modifierHyper?: boolean; - modifierNumLock?: boolean; - modifierOS?: boolean; - modifierScrollLock?: boolean; - modifierSuper?: boolean; - modifierSymbol?: boolean; - modifierSymbolLock?: boolean; -} - -interface ExceptionInformation { - domain?: string; -} - -interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; -} - -interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; -} - -interface IDBIndexParameters { - multiEntry?: boolean; - unique?: boolean; -} - -interface IDBObjectStoreParameters { - autoIncrement?: boolean; - keyPath?: IDBKeyPath; -} - -interface KeyAlgorithm { - name?: string; -} - -interface KeyboardEventInit extends EventModifierInit { - code?: string; - key?: string; - location?: number; - repeat?: boolean; -} - -interface LongRange { - max?: number; - min?: number; -} - -interface MSAccountInfo { - rpDisplayName?: string; - userDisplayName?: string; - accountName?: string; - userId?: string; - accountImageUri?: string; -} - -interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; - cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; - deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; - deviceClippingEventRatio?: number; - deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; - deviceHowlingEventCount?: number; -} - -interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; - burstLossLength1?: number; - burstLossLength2?: number; - burstLossLength3?: number; - burstLossLength4?: number; - burstLossLength5?: number; - burstLossLength6?: number; - burstLossLength7?: number; - burstLossLength8OrHigher?: number; - fecRecvDistance1?: number; - fecRecvDistance2?: number; - fecRecvDistance3?: number; - ratioConcealedSamplesAvg?: number; - ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; -} - -interface MSAudioRecvSignal { - initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; - recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; - renderLoopbackSignalLevel?: number; -} - -interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; - audioFECUsed?: boolean; - sendMutePercent?: number; -} - -interface MSAudioSendSignal { - noiseLevel?: number; - sendSignalLevelCh1?: number; - sendNoiseLevelCh1?: number; -} - -interface MSConnectivity { - iceType?: string; - iceWarningFlags?: MSIceWarningFlags; - relayAddress?: MSRelayAddress; -} - -interface MSCredentialFilter { - accept?: MSCredentialSpec[]; -} - -interface MSCredentialParameters { - type?: string; -} - -interface MSCredentialSpec { - type?: string; - id?: string; -} - -interface MSDelay { - roundTrip?: number; - roundTripMax?: number; -} - -interface MSDescription extends RTCStats { - connectivity?: MSConnectivity; - transport?: string; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; - deviceDevName?: string; - reflexiveLocalIPAddr?: MSIPAddressInfo; -} - -interface MSFIDOCredentialParameters extends MSCredentialParameters { - algorithm?: string | Algorithm; - authenticators?: AAGUID[]; -} - -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - -interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; - turnTcpAllocateFailed?: boolean; - turnTcpSendFailed?: boolean; - udpLocalConnectivityFailed?: boolean; - udpNatConnectivityFailed?: boolean; - udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; - useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; -} - -interface MSJitter { - interArrival?: number; - interArrivalMax?: number; - interArrivalSD?: number; -} - -interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; - networkBandwidthLowEventRatio?: number; -} - -interface MSNetwork extends RTCStats { - jitter?: MSJitter; - delay?: MSDelay; - packetLoss?: MSPacketLoss; - utilization?: MSUtilization; -} - -interface MSNetworkConnectivityInfo { - vpn?: boolean; - linkspeed?: number; - networkConnectionDetails?: string; -} - -interface MSNetworkInterfaceType { - interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; - interfaceTypePPP?: boolean; - interfaceTypeTunnel?: boolean; - interfaceTypeWWAN?: boolean; -} - -interface MSOutboundNetwork extends MSNetwork { - appliedBandwidthLimit?: number; -} - -interface MSPacketLoss { - lossRate?: number; - lossRateMax?: number; -} - -interface MSPayloadBase extends RTCStats { - payloadDescription?: string; -} - -interface MSRelayAddress { - relayAddress?: string; - port?: number; -} - -interface MSSignatureParameters { - userPrompt?: string; -} - -interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: string; - localInterface?: MSNetworkInterfaceType; - localAddrType?: string; - remoteAddrType?: string; - iceRole?: string; - rtpRtcpMux?: boolean; - allocationTimeInMs?: number; - msRtcEngineVersion?: string; -} - -interface MSUtilization { - packets?: number; - bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; - bandwidthEstimationAvg?: number; -} - -interface MSVideoPayload extends MSPayloadBase { - resoluton?: string; - videoBitRateAvg?: number; - videoBitRateMax?: number; - videoFrameRateAvg?: number; - videoPacketLossRate?: number; - durationSeconds?: number; -} - -interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; - recvBitRateAverage?: number; - recvVideoStreamsMax?: number; - recvVideoStreamsMin?: number; - recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; - reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; -} - -interface MSVideoResolutionDistribution { - cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; - h1080Quality?: number; - h1440Quality?: number; - h2160Quality?: number; -} - -interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; - sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; - sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: string; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: string; - persistentState?: string; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; -} - -interface MsZoomToOptions { - contentX?: number; - contentY?: number; - viewportX?: string; - viewportY?: string; - scaleFactor?: number; - animate?: string; -} - -interface MutationObserverInit { - childList?: boolean; - attributes?: boolean; - characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; - characterDataOldValue?: boolean; - attributeFilter?: string[]; -} - -interface ObjectURLOptions { - oneTimeOnly?: boolean; -} - -interface PeriodicWaveConstraints { - disableNormalization?: boolean; -} - -interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; - height?: number; - pressure?: number; - tiltX?: number; - tiltY?: number; - pointerType?: string; - isPrimary?: boolean; -} - -interface PositionOptions { - enableHighAccuracy?: boolean; - timeout?: number; - maximumAge?: number; -} - -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - -interface RTCDtlsFingerprint { - algorithm?: string; - value?: string; -} - -interface RTCDtlsParameters { - role?: string; - fingerprints?: RTCDtlsFingerprint[]; -} - -interface RTCIceCandidate { - foundation?: string; - priority?: number; - ip?: string; - protocol?: string; - port?: number; - type?: string; - tcpType?: string; - relatedAddress?: string; - relatedPort?: number; -} - -interface RTCIceCandidateAttributes extends RTCStats { - ipAddress?: string; - portNumber?: number; - transport?: string; - candidateType?: string; - priority?: number; - addressSourceUrl?: string; -} - -interface RTCIceCandidateComplete { -} - -interface RTCIceCandidatePair { - local?: RTCIceCandidate; - remote?: RTCIceCandidate; -} - -interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: string; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; - availableIncomingBitrate?: number; -} - -interface RTCIceGatherOptions { - gatherPolicy?: string; - iceservers?: RTCIceServer[]; -} - -interface RTCIceParameters { - usernameFragment?: string; - password?: string; -} - -interface RTCIceServer { - urls?: any; - username?: string; - credential?: string; -} - -interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; - bytesReceived?: number; - packetsLost?: number; - jitter?: number; - fractionLost?: number; -} - -interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; - audioLevel?: number; - echoReturnLoss?: number; - echoReturnLossEnhancement?: number; -} - -interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; - bytesSent?: number; - targetBitrate?: number; - roundTripTime?: number; -} - -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - -interface RTCRtcpFeedback { - type?: string; - parameter?: string; -} - -interface RTCRtcpParameters { - ssrc?: number; - cname?: string; - reducedSize?: boolean; - mux?: boolean; -} - -interface RTCRtpCapabilities { - codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; - fecMechanisms?: string[]; -} - -interface RTCRtpCodecCapability { - name?: string; - kind?: string; - clockRate?: number; - preferredPayloadType?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; - maxSpatialLayers?: number; - svcMultiStreamSupport?: boolean; -} - -interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; - clockRate?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; -} - -interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; - audioLevel?: number; -} - -interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - framerateBias?: number; - resolutionScale?: number; - framerateScale?: number; - active?: boolean; - encodingId?: string; - dependencyEncodingIds?: string[]; - ssrcRange?: RTCSsrcRange; -} - -interface RTCRtpFecParameters { - ssrc?: number; - mechanism?: string; -} - -interface RTCRtpHeaderExtension { - kind?: string; - uri?: string; - preferredId?: number; - preferredEncrypt?: boolean; -} - -interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; - encrypt?: boolean; -} - -interface RTCRtpParameters { - muxId?: string; - codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; -} - -interface RTCRtpRtxParameters { - ssrc?: number; -} - -interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; - muxId?: string; -} - -interface RTCSrtpKeyParam { - keyMethod?: string; - keySalt?: string; - lifetime?: string; - mkiValue?: number; - mkiLength?: number; -} - -interface RTCSrtpSdesParameters { - tag?: number; - cryptoSuite?: string; - keyParams?: RTCSrtpKeyParam[]; - sessionParams?: string[]; -} - -interface RTCSsrcRange { - min?: number; - max?: number; -} - -interface RTCStats { - timestamp?: number; - type?: string; - id?: string; - msType?: string; -} - -interface RTCStatsReport { -} - -interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; - activeConnection?: boolean; - selectedCandidatePairId?: string; - localCertificateId?: string; - remoteCertificateId?: string; -} - -interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; - detailURI?: string; -} - -interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { - arrayOfDomainStrings?: string[]; -} - -interface UIEventInit extends EventInit { - view?: Window; - detail?: number; -} - -interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; - alpha?: boolean; - depth?: boolean; - stencil?: boolean; - antialias?: boolean; - premultipliedAlpha?: boolean; - preserveDrawingBuffer?: boolean; -} - -interface WebGLContextEventInit extends EventInit { - statusMessage?: string; -} - -interface WheelEventInit extends MouseEventInit { - deltaX?: number; - deltaY?: number; - deltaZ?: number; - deltaMode?: number; -} - -interface EventListener { - (evt: Event): void; -} - -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -interface AnalyserNode extends AudioNode { - fftSize: number; - readonly frequencyBinCount: number; - maxDecibels: number; - minDecibels: number; - smoothingTimeConstant: number; - getByteFrequencyData(array: Uint8Array): void; - getByteTimeDomainData(array: Uint8Array): void; - getFloatFrequencyData(array: Float32Array): void; - getFloatTimeDomainData(array: Float32Array): void; -} - -declare var AnalyserNode: { - prototype: AnalyserNode; - new(): AnalyserNode; -} - -interface AnimationEvent extends Event { - readonly animationName: string; - readonly elapsedTime: number; - initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; -} - -declare var AnimationEvent: { - prototype: AnimationEvent; - new(): AnimationEvent; -} - -interface ApplicationCache extends EventTarget { - oncached: (this: this, ev: Event) => any; - onchecking: (this: this, ev: Event) => any; - ondownloading: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onnoupdate: (this: this, ev: Event) => any; - onobsolete: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onupdateready: (this: this, ev: Event) => any; - readonly status: number; - abort(): void; - swapCache(): void; - update(): void; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; - addEventListener(type: "cached", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "checking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "downloading", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "noupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "obsolete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "updateready", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ApplicationCache: { - prototype: ApplicationCache; - new(): ApplicationCache; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; -} - -interface AriaRequestEvent extends Event { - readonly attributeName: string; - attributeValue: string | null; -} - -declare var AriaRequestEvent: { - prototype: AriaRequestEvent; - new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; -} - -interface Attr extends Node { - readonly name: string; - readonly ownerElement: Element; - readonly prefix: string | null; - readonly specified: boolean; - value: string; -} - -declare var Attr: { - prototype: Attr; - new(): Attr; -} - -interface AudioBuffer { - readonly duration: number; - readonly length: number; - readonly numberOfChannels: number; - readonly sampleRate: number; - copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; - copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; - getChannelData(channel: number): Float32Array; -} - -declare var AudioBuffer: { - prototype: AudioBuffer; - new(): AudioBuffer; -} - -interface AudioBufferSourceNode extends AudioNode { - buffer: AudioBuffer | null; - readonly detune: AudioParam; - loop: boolean; - loopEnd: number; - loopStart: number; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - readonly playbackRate: AudioParam; - start(when?: number, offset?: number, duration?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var AudioBufferSourceNode: { - prototype: AudioBufferSourceNode; - new(): AudioBufferSourceNode; -} - -interface AudioContext extends EventTarget { - readonly currentTime: number; - readonly destination: AudioDestinationNode; - readonly listener: AudioListener; - readonly sampleRate: number; - state: string; - createAnalyser(): AnalyserNode; - createBiquadFilter(): BiquadFilterNode; - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - createBufferSource(): AudioBufferSourceNode; - createChannelMerger(numberOfInputs?: number): ChannelMergerNode; - createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; - createConvolver(): ConvolverNode; - createDelay(maxDelayTime?: number): DelayNode; - createDynamicsCompressor(): DynamicsCompressorNode; - createGain(): GainNode; - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; - createOscillator(): OscillatorNode; - createPanner(): PannerNode; - createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; - createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; - createStereoPanner(): StereoPannerNode; - createWaveShaper(): WaveShaperNode; - decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; -} - -declare var AudioContext: { - prototype: AudioContext; - new(): AudioContext; -} - -interface AudioDestinationNode extends AudioNode { - readonly maxChannelCount: number; -} - -declare var AudioDestinationNode: { - prototype: AudioDestinationNode; - new(): AudioDestinationNode; -} - -interface AudioListener { - dopplerFactor: number; - speedOfSound: number; - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var AudioListener: { - prototype: AudioListener; - new(): AudioListener; -} - -interface AudioNode extends EventTarget { - channelCount: number; - channelCountMode: string; - channelInterpretation: string; - readonly context: AudioContext; - readonly numberOfInputs: number; - readonly numberOfOutputs: number; - connect(destination: AudioNode, output?: number, input?: number): void; - disconnect(output?: number): void; - disconnect(destination: AudioNode, output?: number, input?: number): void; - disconnect(destination: AudioParam, output?: number): void; -} - -declare var AudioNode: { - prototype: AudioNode; - new(): AudioNode; -} - -interface AudioParam { - readonly defaultValue: number; - value: number; - cancelScheduledValues(startTime: number): void; - exponentialRampToValueAtTime(value: number, endTime: number): void; - linearRampToValueAtTime(value: number, endTime: number): void; - setTargetAtTime(target: number, startTime: number, timeConstant: number): void; - setValueAtTime(value: number, startTime: number): void; - setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; -} - -declare var AudioParam: { - prototype: AudioParam; - new(): AudioParam; -} - -interface AudioProcessingEvent extends Event { - readonly inputBuffer: AudioBuffer; - readonly outputBuffer: AudioBuffer; - readonly playbackTime: number; -} - -declare var AudioProcessingEvent: { - prototype: AudioProcessingEvent; - new(): AudioProcessingEvent; -} - -interface AudioTrack { - enabled: boolean; - readonly id: string; - kind: string; - readonly label: string; - language: string; - readonly sourceBuffer: SourceBuffer; -} - -declare var AudioTrack: { - prototype: AudioTrack; - new(): AudioTrack; -} - -interface AudioTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - getTrackById(id: string): AudioTrack | null; - item(index: number): AudioTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: AudioTrack; -} - -declare var AudioTrackList: { - prototype: AudioTrackList; - new(): AudioTrackList; -} - -interface BarProp { - readonly visible: boolean; -} - -declare var BarProp: { - prototype: BarProp; - new(): BarProp; -} - -interface BeforeUnloadEvent extends Event { - returnValue: any; -} - -declare var BeforeUnloadEvent: { - prototype: BeforeUnloadEvent; - new(): BeforeUnloadEvent; -} - -interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; - readonly detune: AudioParam; - readonly frequency: AudioParam; - readonly gain: AudioParam; - type: string; - getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; -} - -declare var BiquadFilterNode: { - prototype: BiquadFilterNode; - new(): BiquadFilterNode; -} - -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -declare var Blob: { - prototype: Blob; - new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} - -interface CDATASection extends Text { -} - -declare var CDATASection: { - prototype: CDATASection; - new(): CDATASection; -} - -interface CSS { - supports(property: string, value?: string): boolean; -} -declare var CSS: CSS; - -interface CSSConditionRule extends CSSGroupingRule { - conditionText: string; -} - -declare var CSSConditionRule: { - prototype: CSSConditionRule; - new(): CSSConditionRule; -} - -interface CSSFontFaceRule extends CSSRule { - readonly style: CSSStyleDeclaration; -} - -declare var CSSFontFaceRule: { - prototype: CSSFontFaceRule; - new(): CSSFontFaceRule; -} - -interface CSSGroupingRule extends CSSRule { - readonly cssRules: CSSRuleList; - deleteRule(index: number): void; - insertRule(rule: string, index: number): number; -} - -declare var CSSGroupingRule: { - prototype: CSSGroupingRule; - new(): CSSGroupingRule; -} - -interface CSSImportRule extends CSSRule { - readonly href: string; - readonly media: MediaList; - readonly styleSheet: CSSStyleSheet; -} - -declare var CSSImportRule: { - prototype: CSSImportRule; - new(): CSSImportRule; -} - -interface CSSKeyframeRule extends CSSRule { - keyText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSKeyframeRule: { - prototype: CSSKeyframeRule; - new(): CSSKeyframeRule; -} - -interface CSSKeyframesRule extends CSSRule { - readonly cssRules: CSSRuleList; - name: string; - appendRule(rule: string): void; - deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; -} - -declare var CSSKeyframesRule: { - prototype: CSSKeyframesRule; - new(): CSSKeyframesRule; -} - -interface CSSMediaRule extends CSSConditionRule { - readonly media: MediaList; -} - -declare var CSSMediaRule: { - prototype: CSSMediaRule; - new(): CSSMediaRule; -} - -interface CSSNamespaceRule extends CSSRule { - readonly namespaceURI: string; - readonly prefix: string; -} - -declare var CSSNamespaceRule: { - prototype: CSSNamespaceRule; - new(): CSSNamespaceRule; -} - -interface CSSPageRule extends CSSRule { - readonly pseudoClass: string; - readonly selector: string; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSPageRule: { - prototype: CSSPageRule; - new(): CSSPageRule; -} - -interface CSSRule { - cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; - readonly type: number; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -declare var CSSRule: { - prototype: CSSRule; - new(): CSSRule; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -interface CSSRuleList { - readonly length: number; - item(index: number): CSSRule; - [index: number]: CSSRule; -} - -declare var CSSRuleList: { - prototype: CSSRuleList; - new(): CSSRuleList; -} - -interface CSSStyleDeclaration { - alignContent: string | null; - alignItems: string | null; - alignSelf: string | null; - alignmentBaseline: string | null; - animation: string | null; - animationDelay: string | null; - animationDirection: string | null; - animationDuration: string | null; - animationFillMode: string | null; - animationIterationCount: string | null; - animationName: string | null; - animationPlayState: string | null; - animationTimingFunction: string | null; - backfaceVisibility: string | null; - background: string | null; - backgroundAttachment: string | null; - backgroundClip: string | null; - backgroundColor: string | null; - backgroundImage: string | null; - backgroundOrigin: string | null; - backgroundPosition: string | null; - backgroundPositionX: string | null; - backgroundPositionY: string | null; - backgroundRepeat: string | null; - backgroundSize: string | null; - baselineShift: string | null; - border: string | null; - borderBottom: string | null; - borderBottomColor: string | null; - borderBottomLeftRadius: string | null; - borderBottomRightRadius: string | null; - borderBottomStyle: string | null; - borderBottomWidth: string | null; - borderCollapse: string | null; - borderColor: string | null; - borderImage: string | null; - borderImageOutset: string | null; - borderImageRepeat: string | null; - borderImageSlice: string | null; - borderImageSource: string | null; - borderImageWidth: string | null; - borderLeft: string | null; - borderLeftColor: string | null; - borderLeftStyle: string | null; - borderLeftWidth: string | null; - borderRadius: string | null; - borderRight: string | null; - borderRightColor: string | null; - borderRightStyle: string | null; - borderRightWidth: string | null; - borderSpacing: string | null; - borderStyle: string | null; - borderTop: string | null; - borderTopColor: string | null; - borderTopLeftRadius: string | null; - borderTopRightRadius: string | null; - borderTopStyle: string | null; - borderTopWidth: string | null; - borderWidth: string | null; - bottom: string | null; - boxShadow: string | null; - boxSizing: string | null; - breakAfter: string | null; - breakBefore: string | null; - breakInside: string | null; - captionSide: string | null; - clear: string | null; - clip: string | null; - clipPath: string | null; - clipRule: string | null; - color: string | null; - colorInterpolationFilters: string | null; - columnCount: any; - columnFill: string | null; - columnGap: any; - columnRule: string | null; - columnRuleColor: any; - columnRuleStyle: string | null; - columnRuleWidth: any; - columnSpan: string | null; - columnWidth: any; - columns: string | null; - content: string | null; - counterIncrement: string | null; - counterReset: string | null; - cssFloat: string | null; - cssText: string; - cursor: string | null; - direction: string | null; - display: string | null; - dominantBaseline: string | null; - emptyCells: string | null; - enableBackground: string | null; - fill: string | null; - fillOpacity: string | null; - fillRule: string | null; - filter: string | null; - flex: string | null; - flexBasis: string | null; - flexDirection: string | null; - flexFlow: string | null; - flexGrow: string | null; - flexShrink: string | null; - flexWrap: string | null; - floodColor: string | null; - floodOpacity: string | null; - font: string | null; - fontFamily: string | null; - fontFeatureSettings: string | null; - fontSize: string | null; - fontSizeAdjust: string | null; - fontStretch: string | null; - fontStyle: string | null; - fontVariant: string | null; - fontWeight: string | null; - glyphOrientationHorizontal: string | null; - glyphOrientationVertical: string | null; - height: string | null; - imeMode: string | null; - justifyContent: string | null; - kerning: string | null; - left: string | null; - readonly length: number; - letterSpacing: string | null; - lightingColor: string | null; - lineHeight: string | null; - listStyle: string | null; - listStyleImage: string | null; - listStylePosition: string | null; - listStyleType: string | null; - margin: string | null; - marginBottom: string | null; - marginLeft: string | null; - marginRight: string | null; - marginTop: string | null; - marker: string | null; - markerEnd: string | null; - markerMid: string | null; - markerStart: string | null; - mask: string | null; - maxHeight: string | null; - maxWidth: string | null; - minHeight: string | null; - minWidth: string | null; - msContentZoomChaining: string | null; - msContentZoomLimit: string | null; - msContentZoomLimitMax: any; - msContentZoomLimitMin: any; - msContentZoomSnap: string | null; - msContentZoomSnapPoints: string | null; - msContentZoomSnapType: string | null; - msContentZooming: string | null; - msFlowFrom: string | null; - msFlowInto: string | null; - msFontFeatureSettings: string | null; - msGridColumn: any; - msGridColumnAlign: string | null; - msGridColumnSpan: any; - msGridColumns: string | null; - msGridRow: any; - msGridRowAlign: string | null; - msGridRowSpan: any; - msGridRows: string | null; - msHighContrastAdjust: string | null; - msHyphenateLimitChars: string | null; - msHyphenateLimitLines: any; - msHyphenateLimitZone: any; - msHyphens: string | null; - msImeAlign: string | null; - msOverflowStyle: string | null; - msScrollChaining: string | null; - msScrollLimit: string | null; - msScrollLimitXMax: any; - msScrollLimitXMin: any; - msScrollLimitYMax: any; - msScrollLimitYMin: any; - msScrollRails: string | null; - msScrollSnapPointsX: string | null; - msScrollSnapPointsY: string | null; - msScrollSnapType: string | null; - msScrollSnapX: string | null; - msScrollSnapY: string | null; - msScrollTranslation: string | null; - msTextCombineHorizontal: string | null; - msTextSizeAdjust: any; - msTouchAction: string | null; - msTouchSelect: string | null; - msUserSelect: string | null; - msWrapFlow: string; - msWrapMargin: any; - msWrapThrough: string; - opacity: string | null; - order: string | null; - orphans: string | null; - outline: string | null; - outlineColor: string | null; - outlineStyle: string | null; - outlineWidth: string | null; - overflow: string | null; - overflowX: string | null; - overflowY: string | null; - padding: string | null; - paddingBottom: string | null; - paddingLeft: string | null; - paddingRight: string | null; - paddingTop: string | null; - pageBreakAfter: string | null; - pageBreakBefore: string | null; - pageBreakInside: string | null; - readonly parentRule: CSSRule; - perspective: string | null; - perspectiveOrigin: string | null; - pointerEvents: string | null; - position: string | null; - quotes: string | null; - right: string | null; - rubyAlign: string | null; - rubyOverhang: string | null; - rubyPosition: string | null; - stopColor: string | null; - stopOpacity: string | null; - stroke: string | null; - strokeDasharray: string | null; - strokeDashoffset: string | null; - strokeLinecap: string | null; - strokeLinejoin: string | null; - strokeMiterlimit: string | null; - strokeOpacity: string | null; - strokeWidth: string | null; - tableLayout: string | null; - textAlign: string | null; - textAlignLast: string | null; - textAnchor: string | null; - textDecoration: string | null; - textIndent: string | null; - textJustify: string | null; - textKashida: string | null; - textKashidaSpace: string | null; - textOverflow: string | null; - textShadow: string | null; - textTransform: string | null; - textUnderlinePosition: string | null; - top: string | null; - touchAction: string | null; - transform: string | null; - transformOrigin: string | null; - transformStyle: string | null; - transition: string | null; - transitionDelay: string | null; - transitionDuration: string | null; - transitionProperty: string | null; - transitionTimingFunction: string | null; - unicodeBidi: string | null; - verticalAlign: string | null; - visibility: string | null; - webkitAlignContent: string | null; - webkitAlignItems: string | null; - webkitAlignSelf: string | null; - webkitAnimation: string | null; - webkitAnimationDelay: string | null; - webkitAnimationDirection: string | null; - webkitAnimationDuration: string | null; - webkitAnimationFillMode: string | null; - webkitAnimationIterationCount: string | null; - webkitAnimationName: string | null; - webkitAnimationPlayState: string | null; - webkitAnimationTimingFunction: string | null; - webkitAppearance: string | null; - webkitBackfaceVisibility: string | null; - webkitBackgroundClip: string | null; - webkitBackgroundOrigin: string | null; - webkitBackgroundSize: string | null; - webkitBorderBottomLeftRadius: string | null; - webkitBorderBottomRightRadius: string | null; - webkitBorderImage: string | null; - webkitBorderRadius: string | null; - webkitBorderTopLeftRadius: string | null; - webkitBorderTopRightRadius: string | null; - webkitBoxAlign: string | null; - webkitBoxDirection: string | null; - webkitBoxFlex: string | null; - webkitBoxOrdinalGroup: string | null; - webkitBoxOrient: string | null; - webkitBoxPack: string | null; - webkitBoxSizing: string | null; - webkitColumnBreakAfter: string | null; - webkitColumnBreakBefore: string | null; - webkitColumnBreakInside: string | null; - webkitColumnCount: any; - webkitColumnGap: any; - webkitColumnRule: string | null; - webkitColumnRuleColor: any; - webkitColumnRuleStyle: string | null; - webkitColumnRuleWidth: any; - webkitColumnSpan: string | null; - webkitColumnWidth: any; - webkitColumns: string | null; - webkitFilter: string | null; - webkitFlex: string | null; - webkitFlexBasis: string | null; - webkitFlexDirection: string | null; - webkitFlexFlow: string | null; - webkitFlexGrow: string | null; - webkitFlexShrink: string | null; - webkitFlexWrap: string | null; - webkitJustifyContent: string | null; - webkitOrder: string | null; - webkitPerspective: string | null; - webkitPerspectiveOrigin: string | null; - webkitTapHighlightColor: string | null; - webkitTextFillColor: string | null; - webkitTextSizeAdjust: any; - webkitTransform: string | null; - webkitTransformOrigin: string | null; - webkitTransformStyle: string | null; - webkitTransition: string | null; - webkitTransitionDelay: string | null; - webkitTransitionDuration: string | null; - webkitTransitionProperty: string | null; - webkitTransitionTimingFunction: string | null; - webkitUserModify: string | null; - webkitUserSelect: string | null; - webkitWritingMode: string | null; - whiteSpace: string | null; - widows: string | null; - width: string | null; - wordBreak: string | null; - wordSpacing: string | null; - wordWrap: string | null; - writingMode: string | null; - zIndex: string | null; - zoom: string | null; - getPropertyPriority(propertyName: string): string; - getPropertyValue(propertyName: string): string; - item(index: number): string; - removeProperty(propertyName: string): string; - setProperty(propertyName: string, value: string | null, priority?: string): void; - [index: number]: string; -} - -declare var CSSStyleDeclaration: { - prototype: CSSStyleDeclaration; - new(): CSSStyleDeclaration; -} - -interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSStyleRule: { - prototype: CSSStyleRule; - new(): CSSStyleRule; -} - -interface CSSStyleSheet extends StyleSheet { - readonly cssRules: CSSRuleList; - cssText: string; - readonly href: string; - readonly id: string; - readonly imports: StyleSheetList; - readonly isAlternate: boolean; - readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; - readonly owningElement: Element; - readonly pages: StyleSheetPageList; - readonly readOnly: boolean; - readonly rules: CSSRuleList; - addImport(bstrURL: string, lIndex?: number): number; - addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; - addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; - deleteRule(index?: number): void; - insertRule(rule: string, index?: number): number; - removeImport(lIndex: number): void; - removeRule(lIndex: number): void; -} - -declare var CSSStyleSheet: { - prototype: CSSStyleSheet; - new(): CSSStyleSheet; -} - -interface CSSSupportsRule extends CSSConditionRule { -} - -declare var CSSSupportsRule: { - prototype: CSSSupportsRule; - new(): CSSSupportsRule; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: string; - msImageSmoothingEnabled: boolean; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: string): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; - fill(fillRule?: string): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: string): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(): CloseEvent; -} - -interface CommandEvent extends Event { - readonly commandName: string; - readonly detail: string | null; -} - -declare var CommandEvent: { - prototype: CommandEvent; - new(type: string, eventInitDict?: CommandEventInit): CommandEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: string, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} - -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; -} - -declare var CustomEvent: { - prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; - createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} - -interface DataCue extends TextTrackCue { - data: ArrayBuffer; -} - -declare var DataCue: { - prototype: DataCue; - new(): DataCue; -} - -interface DataTransfer { - dropEffect: string; - effectAllowed: string; - readonly files: FileList; - readonly items: DataTransferItemList; - readonly types: DOMStringList; - clearData(format?: string): boolean; - getData(format: string): string; - setData(format: string, data: string): boolean; -} - -declare var DataTransfer: { - prototype: DataTransfer; - new(): DataTransfer; -} - -interface DataTransferItem { - readonly kind: string; - readonly type: string; - getAsFile(): File | null; - getAsString(_callback: FunctionStringCallback | null): void; -} - -declare var DataTransferItem: { - prototype: DataTransferItem; - new(): DataTransferItem; -} - -interface DataTransferItemList { - readonly length: number; - add(data: File): DataTransferItem | null; - clear(): void; - item(index: number): DataTransferItem; - remove(index: number): void; - [index: number]: DataTransferItem; -} - -declare var DataTransferItemList: { - prototype: DataTransferItemList; - new(): DataTransferItemList; -} - -interface DeferredPermissionRequest { - readonly id: number; - readonly type: string; - readonly uri: string; - allow(): void; - deny(): void; -} - -declare var DeferredPermissionRequest: { - prototype: DeferredPermissionRequest; - new(): DeferredPermissionRequest; -} - -interface DelayNode extends AudioNode { - readonly delayTime: AudioParam; -} - -declare var DelayNode: { - prototype: DelayNode; - new(): DelayNode; -} - -interface DeviceAcceleration { - readonly x: number | null; - readonly y: number | null; - readonly z: number | null; -} - -declare var DeviceAcceleration: { - prototype: DeviceAcceleration; - new(): DeviceAcceleration; -} - -interface DeviceLightEvent extends Event { - readonly value: number; -} - -declare var DeviceLightEvent: { - prototype: DeviceLightEvent; - new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} - -interface DeviceMotionEvent extends Event { - readonly acceleration: DeviceAcceleration | null; - readonly accelerationIncludingGravity: DeviceAcceleration | null; - readonly interval: number | null; - readonly rotationRate: DeviceRotationRate | null; - initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; -} - -declare var DeviceMotionEvent: { - prototype: DeviceMotionEvent; - new(): DeviceMotionEvent; -} - -interface DeviceOrientationEvent extends Event { - readonly absolute: boolean; - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; - initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; -} - -declare var DeviceOrientationEvent: { - prototype: DeviceOrientationEvent; - new(): DeviceOrientationEvent; -} - -interface DeviceRotationRate { - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; -} - -declare var DeviceRotationRate: { - prototype: DeviceRotationRate; - new(): DeviceRotationRate; -} - -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { - /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ - readonly activeElement: Element; - /** - * Sets or gets the color of all active links in the document. - */ - alinkColor: string; - /** - * Returns a reference to the collection of elements contained by the object. - */ - readonly all: HTMLAllCollection; - /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ - anchors: HTMLCollectionOf; - /** - * Retrieves a collection of all applet objects in the document. - */ - applets: HTMLCollectionOf; - /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ - bgColor: string; - /** - * Specifies the beginning and end of the document body. - */ - body: HTMLElement; - readonly characterSet: string; - /** - * Gets or sets the character set used to encode the object. - */ - charset: string; - /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ - readonly compatMode: string; - cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; - /** - * Gets the default character set from the current regional language settings. - */ - readonly defaultCharset: string; - readonly defaultView: Window; - /** - * Sets or gets a value that indicates whether the document can be edited. - */ - designMode: string; - /** - * 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. - */ - readonly doctype: DocumentType; - /** - * Gets a reference to the root node of the document. - */ - documentElement: HTMLElement; - /** - * Sets or gets the security domain of the document. - */ - domain: string; - /** - * Retrieves a collection of all embed objects in the document. - */ - embeds: HTMLCollectionOf; - /** - * Sets or gets the foreground (text) color of the document. - */ - fgColor: string; - /** - * Retrieves a collection, in source order, of all form objects in the document. - */ - forms: HTMLCollectionOf; - readonly fullscreenElement: Element | null; - readonly fullscreenEnabled: boolean; - readonly head: HTMLHeadElement; - readonly hidden: boolean; - /** - * Retrieves a collection, in source order, of img objects in the document. - */ - images: HTMLCollectionOf; - /** - * Gets the implementation object of the current document. - */ - readonly implementation: DOMImplementation; - /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ - readonly inputEncoding: string | null; - /** - * 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. - */ - linkColor: string; - /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ - links: HTMLCollectionOf; - /** - * Contains information about the current URL. - */ - readonly location: Location; - msCSSOMElementFloatMetrics: boolean; - msCapsLockWarningOff: boolean; - /** - * Fires when the user aborts the download. - * @param ev The event. - */ - onabort: (this: this, ev: UIEvent) => any; - /** - * Fires when the object is set as the active element. - * @param ev The event. - */ - onactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ - onbeforeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ - onbeforedeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ - onblur: (this: this, ev: FocusEvent) => any; - /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ - onchange: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ - onclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ - oncontextmenu: (this: this, ev: PointerEvent) => any; - /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ - ondblclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ - ondeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ - ondrag: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ - ondragend: (this: this, 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: (this: this, 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. - */ - ondragleave: (this: this, ev: DragEvent) => any; - /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ - ondragover: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ - ondurationchange: (this: this, ev: Event) => any; - /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ - onemptied: (this: this, ev: Event) => any; - /** - * Occurs when the end of playback is reached. - * @param ev The event - */ - onended: (this: this, ev: MediaStreamErrorEvent) => any; - /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - * @param ev The event. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onfullscreenchange: (this: this, ev: Event) => any; - onfullscreenerror: (this: this, ev: Event) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ - onkeydown: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ - onkeypress: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ - onkeyup: (this: this, ev: KeyboardEvent) => any; - /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ - onload: (this: this, ev: Event) => any; - /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ - onloadeddata: (this: this, ev: Event) => any; - /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ - onloadedmetadata: (this: this, ev: Event) => any; - /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ - onloadstart: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ - onmousedown: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ - onmousemove: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ - onmouseout: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ - onmouseover: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ - onmouseup: (this: this, ev: MouseEvent) => any; - /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ - onmssitemodejumplistitemremoved: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ - onmsthumbnailclick: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when playback is paused. - * @param ev The event. - */ - onpause: (this: this, ev: Event) => any; - /** - * Occurs when the play method is requested. - * @param ev The event. - */ - onplay: (this: this, ev: Event) => any; - /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ - onplaying: (this: this, ev: Event) => any; - onpointerlockchange: (this: this, ev: Event) => any; - onpointerlockerror: (this: this, ev: Event) => any; - /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ - onprogress: (this: this, ev: ProgressEvent) => any; - /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ - onratechange: (this: this, ev: Event) => any; - /** - * Fires when the state of the object has changed. - * @param ev The event - */ - onreadystatechange: (this: this, ev: ProgressEvent) => any; - /** - * Fires when the user resets a form. - * @param ev The event. - */ - onreset: (this: this, ev: Event) => any; - /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ - onscroll: (this: this, ev: UIEvent) => any; - /** - * Occurs when the seek operation ends. - * @param ev The event. - */ - onseeked: (this: this, ev: Event) => any; - /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ - onseeking: (this: this, ev: Event) => any; - /** - * Fires when the current selection changes. - * @param ev The event. - */ - onselect: (this: this, ev: UIEvent) => any; - /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ - onselectionchange: (this: this, ev: Event) => any; - onselectstart: (this: this, ev: Event) => any; - /** - * Occurs when the download has stopped. - * @param ev The event. - */ - onstalled: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ - onstop: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ - onsuspend: (this: this, ev: Event) => any; - /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ - onvolumechange: (this: this, ev: Event) => any; - /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ - onwaiting: (this: this, ev: Event) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - plugins: HTMLCollectionOf; - readonly pointerLockElement: Element; - /** - * Retrieves a value that indicates the current state of the object. - */ - readonly readyState: string; - /** - * Gets the URL of the location that referred the user to the current page. - */ - readonly referrer: string; - /** - * Gets the root svg element in the document hierarchy. - */ - readonly rootElement: SVGSVGElement; - /** - * Retrieves a collection of all script objects in the document. - */ - scripts: HTMLCollectionOf; - readonly scrollingElement: Element | null; - /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ - readonly styleSheets: StyleSheetList; - /** - * Contains the title of the document. - */ - title: string; - readonly visibilityState: string; - /** - * Sets or gets the color of the links that the user has visited. - */ - vlinkColor: string; - readonly webkitCurrentFullScreenElement: Element | null; - readonly webkitFullscreenElement: Element | null; - readonly webkitFullscreenEnabled: boolean; - readonly webkitIsFullScreen: boolean; - readonly xmlEncoding: string | null; - xmlStandalone: boolean; - /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ - xmlVersion: string | null; - adoptNode(source: Node): Node; - captureEvents(): void; - caretRangeFromPoint(x: number, y: number): Range; - clear(): void; - /** - * Closes an output stream and forces the sent data to display. - */ - close(): void; - /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ - createAttribute(name: string): Attr; - createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; - createCDATASection(data: string): CDATASection; - /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ - createComment(data: string): Comment; - /** - * Creates a new document. - */ - createDocumentFragment(): DocumentFragment; - /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ - createElement(tagName: "a"): HTMLAnchorElement; - createElement(tagName: "applet"): HTMLAppletElement; - createElement(tagName: "area"): HTMLAreaElement; - createElement(tagName: "audio"): HTMLAudioElement; - createElement(tagName: "base"): HTMLBaseElement; - createElement(tagName: "basefont"): HTMLBaseFontElement; - createElement(tagName: "blockquote"): HTMLQuoteElement; - createElement(tagName: "body"): HTMLBodyElement; - createElement(tagName: "br"): HTMLBRElement; - createElement(tagName: "button"): HTMLButtonElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: "caption"): HTMLTableCaptionElement; - createElement(tagName: "col"): HTMLTableColElement; - createElement(tagName: "colgroup"): HTMLTableColElement; - createElement(tagName: "datalist"): HTMLDataListElement; - createElement(tagName: "del"): HTMLModElement; - createElement(tagName: "dir"): HTMLDirectoryElement; - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "dl"): HTMLDListElement; - createElement(tagName: "embed"): HTMLEmbedElement; - createElement(tagName: "fieldset"): HTMLFieldSetElement; - createElement(tagName: "font"): HTMLFontElement; - createElement(tagName: "form"): HTMLFormElement; - createElement(tagName: "frame"): HTMLFrameElement; - createElement(tagName: "frameset"): HTMLFrameSetElement; - createElement(tagName: "h1"): HTMLHeadingElement; - createElement(tagName: "h2"): HTMLHeadingElement; - createElement(tagName: "h3"): HTMLHeadingElement; - createElement(tagName: "h4"): HTMLHeadingElement; - createElement(tagName: "h5"): HTMLHeadingElement; - createElement(tagName: "h6"): HTMLHeadingElement; - createElement(tagName: "head"): HTMLHeadElement; - createElement(tagName: "hr"): HTMLHRElement; - createElement(tagName: "html"): HTMLHtmlElement; - createElement(tagName: "iframe"): HTMLIFrameElement; - createElement(tagName: "img"): HTMLImageElement; - createElement(tagName: "input"): HTMLInputElement; - createElement(tagName: "ins"): HTMLModElement; - createElement(tagName: "isindex"): HTMLUnknownElement; - createElement(tagName: "label"): HTMLLabelElement; - createElement(tagName: "legend"): HTMLLegendElement; - createElement(tagName: "li"): HTMLLIElement; - createElement(tagName: "link"): HTMLLinkElement; - createElement(tagName: "listing"): HTMLPreElement; - createElement(tagName: "map"): HTMLMapElement; - createElement(tagName: "marquee"): HTMLMarqueeElement; - createElement(tagName: "menu"): HTMLMenuElement; - createElement(tagName: "meta"): HTMLMetaElement; - createElement(tagName: "meter"): HTMLMeterElement; - createElement(tagName: "nextid"): HTMLUnknownElement; - createElement(tagName: "object"): HTMLObjectElement; - createElement(tagName: "ol"): HTMLOListElement; - createElement(tagName: "optgroup"): HTMLOptGroupElement; - createElement(tagName: "option"): HTMLOptionElement; - createElement(tagName: "p"): HTMLParagraphElement; - createElement(tagName: "param"): HTMLParamElement; - createElement(tagName: "picture"): HTMLPictureElement; - createElement(tagName: "pre"): HTMLPreElement; - createElement(tagName: "progress"): HTMLProgressElement; - createElement(tagName: "q"): HTMLQuoteElement; - createElement(tagName: "script"): HTMLScriptElement; - createElement(tagName: "select"): HTMLSelectElement; - createElement(tagName: "source"): HTMLSourceElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "style"): HTMLStyleElement; - createElement(tagName: "table"): HTMLTableElement; - createElement(tagName: "tbody"): HTMLTableSectionElement; - createElement(tagName: "td"): HTMLTableDataCellElement; - createElement(tagName: "template"): HTMLTemplateElement; - createElement(tagName: "textarea"): HTMLTextAreaElement; - createElement(tagName: "tfoot"): HTMLTableSectionElement; - createElement(tagName: "th"): HTMLTableHeaderCellElement; - createElement(tagName: "thead"): HTMLTableSectionElement; - createElement(tagName: "title"): HTMLTitleElement; - createElement(tagName: "tr"): HTMLTableRowElement; - createElement(tagName: "track"): HTMLTrackElement; - createElement(tagName: "ul"): HTMLUListElement; - createElement(tagName: "video"): HTMLVideoElement; - createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; - createElement(tagName: "xmp"): HTMLPreElement; - createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement - createElementNS(namespaceURI: string | null, qualifiedName: string): Element; - 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. - * @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. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - 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. - */ - createRange(): Range; - /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ - createTextNode(data: string): Text; - createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; - createTouchList(...touches: Touch[]): TouchList; - /** - * Creates a TreeWalker 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. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; - /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ - elementFromPoint(x: number, y: number): Element; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; - /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ - execCommand(commandId: string, showUI?: boolean, value?: any): boolean; - /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ - execCommandShowHelp(commandId: string): boolean; - exitFullscreen(): void; - exitPointerLock(): void; - /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ - focus(): void; - /** - * 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 | null; - getElementsByClassName(classNames: string): HTMLCollectionOf; - /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ - getElementsByName(elementName: string): NodeListOf; - /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ - getElementsByTagName(tagname: "a"): NodeListOf; - getElementsByTagName(tagname: "abbr"): NodeListOf; - getElementsByTagName(tagname: "acronym"): NodeListOf; - getElementsByTagName(tagname: "address"): NodeListOf; - getElementsByTagName(tagname: "applet"): NodeListOf; - getElementsByTagName(tagname: "area"): NodeListOf; - getElementsByTagName(tagname: "article"): NodeListOf; - getElementsByTagName(tagname: "aside"): NodeListOf; - getElementsByTagName(tagname: "audio"): NodeListOf; - getElementsByTagName(tagname: "b"): NodeListOf; - getElementsByTagName(tagname: "base"): NodeListOf; - getElementsByTagName(tagname: "basefont"): NodeListOf; - getElementsByTagName(tagname: "bdo"): NodeListOf; - getElementsByTagName(tagname: "big"): NodeListOf; - getElementsByTagName(tagname: "blockquote"): NodeListOf; - getElementsByTagName(tagname: "body"): NodeListOf; - getElementsByTagName(tagname: "br"): NodeListOf; - getElementsByTagName(tagname: "button"): NodeListOf; - getElementsByTagName(tagname: "canvas"): NodeListOf; - getElementsByTagName(tagname: "caption"): NodeListOf; - getElementsByTagName(tagname: "center"): NodeListOf; - getElementsByTagName(tagname: "circle"): NodeListOf; - getElementsByTagName(tagname: "cite"): NodeListOf; - getElementsByTagName(tagname: "clippath"): NodeListOf; - getElementsByTagName(tagname: "code"): NodeListOf; - getElementsByTagName(tagname: "col"): NodeListOf; - getElementsByTagName(tagname: "colgroup"): NodeListOf; - getElementsByTagName(tagname: "datalist"): NodeListOf; - getElementsByTagName(tagname: "dd"): NodeListOf; - getElementsByTagName(tagname: "defs"): NodeListOf; - getElementsByTagName(tagname: "del"): NodeListOf; - getElementsByTagName(tagname: "desc"): NodeListOf; - getElementsByTagName(tagname: "dfn"): NodeListOf; - getElementsByTagName(tagname: "dir"): NodeListOf; - getElementsByTagName(tagname: "div"): NodeListOf; - getElementsByTagName(tagname: "dl"): NodeListOf; - getElementsByTagName(tagname: "dt"): NodeListOf; - getElementsByTagName(tagname: "ellipse"): NodeListOf; - getElementsByTagName(tagname: "em"): NodeListOf; - getElementsByTagName(tagname: "embed"): NodeListOf; - getElementsByTagName(tagname: "feblend"): NodeListOf; - getElementsByTagName(tagname: "fecolormatrix"): NodeListOf; - getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(tagname: "fecomposite"): NodeListOf; - getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf; - getElementsByTagName(tagname: "fediffuselighting"): NodeListOf; - getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf; - getElementsByTagName(tagname: "fedistantlight"): NodeListOf; - getElementsByTagName(tagname: "feflood"): NodeListOf; - getElementsByTagName(tagname: "fefunca"): NodeListOf; - getElementsByTagName(tagname: "fefuncb"): NodeListOf; - getElementsByTagName(tagname: "fefuncg"): NodeListOf; - getElementsByTagName(tagname: "fefuncr"): NodeListOf; - getElementsByTagName(tagname: "fegaussianblur"): NodeListOf; - getElementsByTagName(tagname: "feimage"): NodeListOf; - getElementsByTagName(tagname: "femerge"): NodeListOf; - getElementsByTagName(tagname: "femergenode"): NodeListOf; - getElementsByTagName(tagname: "femorphology"): NodeListOf; - getElementsByTagName(tagname: "feoffset"): NodeListOf; - getElementsByTagName(tagname: "fepointlight"): NodeListOf; - getElementsByTagName(tagname: "fespecularlighting"): NodeListOf; - getElementsByTagName(tagname: "fespotlight"): NodeListOf; - getElementsByTagName(tagname: "fetile"): NodeListOf; - getElementsByTagName(tagname: "feturbulence"): NodeListOf; - getElementsByTagName(tagname: "fieldset"): NodeListOf; - getElementsByTagName(tagname: "figcaption"): NodeListOf; - getElementsByTagName(tagname: "figure"): NodeListOf; - getElementsByTagName(tagname: "filter"): NodeListOf; - getElementsByTagName(tagname: "font"): NodeListOf; - getElementsByTagName(tagname: "footer"): NodeListOf; - getElementsByTagName(tagname: "foreignobject"): NodeListOf; - getElementsByTagName(tagname: "form"): NodeListOf; - getElementsByTagName(tagname: "frame"): NodeListOf; - getElementsByTagName(tagname: "frameset"): NodeListOf; - getElementsByTagName(tagname: "g"): NodeListOf; - getElementsByTagName(tagname: "h1"): NodeListOf; - getElementsByTagName(tagname: "h2"): NodeListOf; - getElementsByTagName(tagname: "h3"): NodeListOf; - getElementsByTagName(tagname: "h4"): NodeListOf; - getElementsByTagName(tagname: "h5"): NodeListOf; - getElementsByTagName(tagname: "h6"): NodeListOf; - getElementsByTagName(tagname: "head"): NodeListOf; - getElementsByTagName(tagname: "header"): NodeListOf; - getElementsByTagName(tagname: "hgroup"): NodeListOf; - getElementsByTagName(tagname: "hr"): NodeListOf; - getElementsByTagName(tagname: "html"): NodeListOf; - getElementsByTagName(tagname: "i"): NodeListOf; - getElementsByTagName(tagname: "iframe"): NodeListOf; - getElementsByTagName(tagname: "image"): NodeListOf; - getElementsByTagName(tagname: "img"): NodeListOf; - getElementsByTagName(tagname: "input"): NodeListOf; - getElementsByTagName(tagname: "ins"): NodeListOf; - getElementsByTagName(tagname: "isindex"): NodeListOf; - getElementsByTagName(tagname: "kbd"): NodeListOf; - getElementsByTagName(tagname: "keygen"): NodeListOf; - getElementsByTagName(tagname: "label"): NodeListOf; - getElementsByTagName(tagname: "legend"): NodeListOf; - getElementsByTagName(tagname: "li"): NodeListOf; - getElementsByTagName(tagname: "line"): NodeListOf; - getElementsByTagName(tagname: "lineargradient"): NodeListOf; - getElementsByTagName(tagname: "link"): NodeListOf; - getElementsByTagName(tagname: "listing"): NodeListOf; - getElementsByTagName(tagname: "map"): NodeListOf; - getElementsByTagName(tagname: "mark"): NodeListOf; - getElementsByTagName(tagname: "marker"): NodeListOf; - getElementsByTagName(tagname: "marquee"): NodeListOf; - getElementsByTagName(tagname: "mask"): NodeListOf; - getElementsByTagName(tagname: "menu"): NodeListOf; - getElementsByTagName(tagname: "meta"): NodeListOf; - getElementsByTagName(tagname: "metadata"): NodeListOf; - getElementsByTagName(tagname: "meter"): NodeListOf; - getElementsByTagName(tagname: "nav"): NodeListOf; - getElementsByTagName(tagname: "nextid"): NodeListOf; - getElementsByTagName(tagname: "nobr"): NodeListOf; - getElementsByTagName(tagname: "noframes"): NodeListOf; - getElementsByTagName(tagname: "noscript"): NodeListOf; - getElementsByTagName(tagname: "object"): NodeListOf; - getElementsByTagName(tagname: "ol"): NodeListOf; - getElementsByTagName(tagname: "optgroup"): NodeListOf; - getElementsByTagName(tagname: "option"): NodeListOf; - getElementsByTagName(tagname: "p"): NodeListOf; - getElementsByTagName(tagname: "param"): NodeListOf; - getElementsByTagName(tagname: "path"): NodeListOf; - getElementsByTagName(tagname: "pattern"): NodeListOf; - getElementsByTagName(tagname: "picture"): NodeListOf; - getElementsByTagName(tagname: "plaintext"): NodeListOf; - getElementsByTagName(tagname: "polygon"): NodeListOf; - getElementsByTagName(tagname: "polyline"): NodeListOf; - getElementsByTagName(tagname: "pre"): NodeListOf; - getElementsByTagName(tagname: "progress"): NodeListOf; - getElementsByTagName(tagname: "q"): NodeListOf; - getElementsByTagName(tagname: "radialgradient"): NodeListOf; - getElementsByTagName(tagname: "rect"): NodeListOf; - getElementsByTagName(tagname: "rt"): NodeListOf; - getElementsByTagName(tagname: "ruby"): NodeListOf; - getElementsByTagName(tagname: "s"): NodeListOf; - getElementsByTagName(tagname: "samp"): NodeListOf; - getElementsByTagName(tagname: "script"): NodeListOf; - getElementsByTagName(tagname: "section"): NodeListOf; - getElementsByTagName(tagname: "select"): NodeListOf; - getElementsByTagName(tagname: "small"): NodeListOf; - getElementsByTagName(tagname: "source"): NodeListOf; - getElementsByTagName(tagname: "span"): NodeListOf; - getElementsByTagName(tagname: "stop"): NodeListOf; - getElementsByTagName(tagname: "strike"): NodeListOf; - getElementsByTagName(tagname: "strong"): NodeListOf; - getElementsByTagName(tagname: "style"): NodeListOf; - getElementsByTagName(tagname: "sub"): NodeListOf; - getElementsByTagName(tagname: "sup"): NodeListOf; - getElementsByTagName(tagname: "svg"): NodeListOf; - getElementsByTagName(tagname: "switch"): NodeListOf; - getElementsByTagName(tagname: "symbol"): NodeListOf; - getElementsByTagName(tagname: "table"): NodeListOf; - getElementsByTagName(tagname: "tbody"): NodeListOf; - getElementsByTagName(tagname: "td"): NodeListOf; - getElementsByTagName(tagname: "template"): NodeListOf; - getElementsByTagName(tagname: "text"): NodeListOf; - getElementsByTagName(tagname: "textpath"): NodeListOf; - getElementsByTagName(tagname: "textarea"): NodeListOf; - getElementsByTagName(tagname: "tfoot"): NodeListOf; - getElementsByTagName(tagname: "th"): NodeListOf; - getElementsByTagName(tagname: "thead"): NodeListOf; - getElementsByTagName(tagname: "title"): NodeListOf; - getElementsByTagName(tagname: "tr"): NodeListOf; - getElementsByTagName(tagname: "track"): NodeListOf; - getElementsByTagName(tagname: "tspan"): NodeListOf; - getElementsByTagName(tagname: "tt"): NodeListOf; - getElementsByTagName(tagname: "u"): NodeListOf; - getElementsByTagName(tagname: "ul"): NodeListOf; - getElementsByTagName(tagname: "use"): NodeListOf; - getElementsByTagName(tagname: "var"): NodeListOf; - getElementsByTagName(tagname: "video"): NodeListOf; - getElementsByTagName(tagname: "view"): NodeListOf; - getElementsByTagName(tagname: "wbr"): NodeListOf; - getElementsByTagName(tagname: "x-ms-webview"): NodeListOf; - getElementsByTagName(tagname: "xmp"): NodeListOf; - getElementsByTagName(tagname: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ - getSelection(): Selection; - /** - * Gets a value indicating whether the object currently has focus. - */ - hasFocus(): boolean; - importNode(importedNode: Node, deep: boolean): Node; - msElementsFromPoint(x: number, y: number): NodeListOf; - msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; - /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @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. - */ - queryCommandEnabled(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ - queryCommandIndeterm(commandId: string): boolean; - /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ - queryCommandState(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ - 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. - */ - queryCommandText(commandId: string): string; - /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ - queryCommandValue(commandId: string): string; - releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; - webkitCancelFullScreen(): void; - webkitExitFullscreen(): void; - /** - * 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. - * @param content The text and HTML tags to write. - */ - writeln(...content: string[]): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mssitemodejumplistitemremoved", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msthumbnailclick", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectionchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stop", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Document: { - prototype: Document; - new(): Document; -} - -interface DocumentFragment extends Node, NodeSelector, ParentNode { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentFragment: { - prototype: DocumentFragment; - new(): DocumentFragment; -} - -interface DocumentType extends Node, ChildNode { - readonly entities: NamedNodeMap; - readonly internalSubset: string | null; - readonly name: string; - readonly notations: NamedNodeMap; - readonly publicId: string | null; - readonly systemId: string | null; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentType: { - prototype: DocumentType; - new(): DocumentType; -} - -interface DragEvent extends MouseEvent { - readonly dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; - msConvertURL(file: File, targetType: string, targetURL?: string): void; -} - -declare var DragEvent: { - prototype: DragEvent; - new(): DragEvent; -} - -interface DynamicsCompressorNode extends AudioNode { - readonly attack: AudioParam; - readonly knee: AudioParam; - readonly ratio: AudioParam; - readonly reduction: AudioParam; - readonly release: AudioParam; - readonly threshold: AudioParam; -} - -declare var DynamicsCompressorNode: { - prototype: DynamicsCompressorNode; - new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { - readonly classList: DOMTokenList; - className: string; - readonly clientHeight: number; - readonly clientLeft: number; - readonly clientTop: number; - readonly clientWidth: number; - id: string; - msContentZoomFactor: number; - readonly msRegionOverflow: string; - onariarequest: (this: this, ev: AriaRequestEvent) => any; - oncommand: (this: this, ev: CommandEvent) => any; - ongotpointercapture: (this: this, ev: PointerEvent) => any; - onlostpointercapture: (this: this, ev: PointerEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsgotpointercapture: (this: this, ev: MSPointerEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmslostpointercapture: (this: this, ev: MSPointerEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - readonly prefix: string | null; - readonly scrollHeight: number; - scrollLeft: number; - scrollTop: number; - readonly scrollWidth: number; - readonly tagName: string; - innerHTML: string; - getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - getElementsByTagName(name: "a"): NodeListOf; - getElementsByTagName(name: "abbr"): NodeListOf; - getElementsByTagName(name: "acronym"): NodeListOf; - getElementsByTagName(name: "address"): NodeListOf; - getElementsByTagName(name: "applet"): NodeListOf; - getElementsByTagName(name: "area"): NodeListOf; - getElementsByTagName(name: "article"): NodeListOf; - getElementsByTagName(name: "aside"): NodeListOf; - getElementsByTagName(name: "audio"): NodeListOf; - getElementsByTagName(name: "b"): NodeListOf; - getElementsByTagName(name: "base"): NodeListOf; - getElementsByTagName(name: "basefont"): NodeListOf; - getElementsByTagName(name: "bdo"): NodeListOf; - getElementsByTagName(name: "big"): NodeListOf; - getElementsByTagName(name: "blockquote"): NodeListOf; - getElementsByTagName(name: "body"): NodeListOf; - getElementsByTagName(name: "br"): NodeListOf; - getElementsByTagName(name: "button"): NodeListOf; - getElementsByTagName(name: "canvas"): NodeListOf; - getElementsByTagName(name: "caption"): NodeListOf; - getElementsByTagName(name: "center"): NodeListOf; - getElementsByTagName(name: "circle"): NodeListOf; - getElementsByTagName(name: "cite"): NodeListOf; - getElementsByTagName(name: "clippath"): NodeListOf; - getElementsByTagName(name: "code"): NodeListOf; - getElementsByTagName(name: "col"): NodeListOf; - getElementsByTagName(name: "colgroup"): NodeListOf; - getElementsByTagName(name: "datalist"): NodeListOf; - getElementsByTagName(name: "dd"): NodeListOf; - getElementsByTagName(name: "defs"): NodeListOf; - getElementsByTagName(name: "del"): NodeListOf; - getElementsByTagName(name: "desc"): NodeListOf; - getElementsByTagName(name: "dfn"): NodeListOf; - getElementsByTagName(name: "dir"): NodeListOf; - getElementsByTagName(name: "div"): NodeListOf; - getElementsByTagName(name: "dl"): NodeListOf; - getElementsByTagName(name: "dt"): NodeListOf; - getElementsByTagName(name: "ellipse"): NodeListOf; - getElementsByTagName(name: "em"): NodeListOf; - getElementsByTagName(name: "embed"): NodeListOf; - getElementsByTagName(name: "feblend"): NodeListOf; - getElementsByTagName(name: "fecolormatrix"): NodeListOf; - getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(name: "fecomposite"): NodeListOf; - getElementsByTagName(name: "feconvolvematrix"): NodeListOf; - getElementsByTagName(name: "fediffuselighting"): NodeListOf; - getElementsByTagName(name: "fedisplacementmap"): NodeListOf; - getElementsByTagName(name: "fedistantlight"): NodeListOf; - getElementsByTagName(name: "feflood"): NodeListOf; - getElementsByTagName(name: "fefunca"): NodeListOf; - getElementsByTagName(name: "fefuncb"): NodeListOf; - getElementsByTagName(name: "fefuncg"): NodeListOf; - getElementsByTagName(name: "fefuncr"): NodeListOf; - getElementsByTagName(name: "fegaussianblur"): NodeListOf; - getElementsByTagName(name: "feimage"): NodeListOf; - getElementsByTagName(name: "femerge"): NodeListOf; - getElementsByTagName(name: "femergenode"): NodeListOf; - getElementsByTagName(name: "femorphology"): NodeListOf; - getElementsByTagName(name: "feoffset"): NodeListOf; - getElementsByTagName(name: "fepointlight"): NodeListOf; - getElementsByTagName(name: "fespecularlighting"): NodeListOf; - getElementsByTagName(name: "fespotlight"): NodeListOf; - getElementsByTagName(name: "fetile"): NodeListOf; - getElementsByTagName(name: "feturbulence"): NodeListOf; - getElementsByTagName(name: "fieldset"): NodeListOf; - getElementsByTagName(name: "figcaption"): NodeListOf; - getElementsByTagName(name: "figure"): NodeListOf; - getElementsByTagName(name: "filter"): NodeListOf; - getElementsByTagName(name: "font"): NodeListOf; - getElementsByTagName(name: "footer"): NodeListOf; - getElementsByTagName(name: "foreignobject"): NodeListOf; - getElementsByTagName(name: "form"): NodeListOf; - getElementsByTagName(name: "frame"): NodeListOf; - getElementsByTagName(name: "frameset"): NodeListOf; - getElementsByTagName(name: "g"): NodeListOf; - getElementsByTagName(name: "h1"): NodeListOf; - getElementsByTagName(name: "h2"): NodeListOf; - getElementsByTagName(name: "h3"): NodeListOf; - getElementsByTagName(name: "h4"): NodeListOf; - getElementsByTagName(name: "h5"): NodeListOf; - getElementsByTagName(name: "h6"): NodeListOf; - getElementsByTagName(name: "head"): NodeListOf; - getElementsByTagName(name: "header"): NodeListOf; - getElementsByTagName(name: "hgroup"): NodeListOf; - getElementsByTagName(name: "hr"): NodeListOf; - getElementsByTagName(name: "html"): NodeListOf; - getElementsByTagName(name: "i"): NodeListOf; - getElementsByTagName(name: "iframe"): NodeListOf; - getElementsByTagName(name: "image"): NodeListOf; - getElementsByTagName(name: "img"): NodeListOf; - getElementsByTagName(name: "input"): NodeListOf; - getElementsByTagName(name: "ins"): NodeListOf; - getElementsByTagName(name: "isindex"): NodeListOf; - getElementsByTagName(name: "kbd"): NodeListOf; - getElementsByTagName(name: "keygen"): NodeListOf; - getElementsByTagName(name: "label"): NodeListOf; - getElementsByTagName(name: "legend"): NodeListOf; - getElementsByTagName(name: "li"): NodeListOf; - getElementsByTagName(name: "line"): NodeListOf; - getElementsByTagName(name: "lineargradient"): NodeListOf; - getElementsByTagName(name: "link"): NodeListOf; - getElementsByTagName(name: "listing"): NodeListOf; - getElementsByTagName(name: "map"): NodeListOf; - getElementsByTagName(name: "mark"): NodeListOf; - getElementsByTagName(name: "marker"): NodeListOf; - getElementsByTagName(name: "marquee"): NodeListOf; - getElementsByTagName(name: "mask"): NodeListOf; - getElementsByTagName(name: "menu"): NodeListOf; - getElementsByTagName(name: "meta"): NodeListOf; - getElementsByTagName(name: "metadata"): NodeListOf; - getElementsByTagName(name: "meter"): NodeListOf; - getElementsByTagName(name: "nav"): NodeListOf; - getElementsByTagName(name: "nextid"): NodeListOf; - getElementsByTagName(name: "nobr"): NodeListOf; - getElementsByTagName(name: "noframes"): NodeListOf; - getElementsByTagName(name: "noscript"): NodeListOf; - getElementsByTagName(name: "object"): NodeListOf; - getElementsByTagName(name: "ol"): NodeListOf; - getElementsByTagName(name: "optgroup"): NodeListOf; - getElementsByTagName(name: "option"): NodeListOf; - getElementsByTagName(name: "p"): NodeListOf; - getElementsByTagName(name: "param"): NodeListOf; - getElementsByTagName(name: "path"): NodeListOf; - getElementsByTagName(name: "pattern"): NodeListOf; - getElementsByTagName(name: "picture"): NodeListOf; - getElementsByTagName(name: "plaintext"): NodeListOf; - getElementsByTagName(name: "polygon"): NodeListOf; - getElementsByTagName(name: "polyline"): NodeListOf; - getElementsByTagName(name: "pre"): NodeListOf; - getElementsByTagName(name: "progress"): NodeListOf; - getElementsByTagName(name: "q"): NodeListOf; - getElementsByTagName(name: "radialgradient"): NodeListOf; - getElementsByTagName(name: "rect"): NodeListOf; - getElementsByTagName(name: "rt"): NodeListOf; - getElementsByTagName(name: "ruby"): NodeListOf; - getElementsByTagName(name: "s"): NodeListOf; - getElementsByTagName(name: "samp"): NodeListOf; - getElementsByTagName(name: "script"): NodeListOf; - getElementsByTagName(name: "section"): NodeListOf; - getElementsByTagName(name: "select"): NodeListOf; - getElementsByTagName(name: "small"): NodeListOf; - getElementsByTagName(name: "source"): NodeListOf; - getElementsByTagName(name: "span"): NodeListOf; - getElementsByTagName(name: "stop"): NodeListOf; - getElementsByTagName(name: "strike"): NodeListOf; - getElementsByTagName(name: "strong"): NodeListOf; - getElementsByTagName(name: "style"): NodeListOf; - getElementsByTagName(name: "sub"): NodeListOf; - getElementsByTagName(name: "sup"): NodeListOf; - getElementsByTagName(name: "svg"): NodeListOf; - getElementsByTagName(name: "switch"): NodeListOf; - getElementsByTagName(name: "symbol"): NodeListOf; - getElementsByTagName(name: "table"): NodeListOf; - getElementsByTagName(name: "tbody"): NodeListOf; - getElementsByTagName(name: "td"): NodeListOf; - getElementsByTagName(name: "template"): NodeListOf; - getElementsByTagName(name: "text"): NodeListOf; - getElementsByTagName(name: "textpath"): NodeListOf; - getElementsByTagName(name: "textarea"): NodeListOf; - getElementsByTagName(name: "tfoot"): NodeListOf; - getElementsByTagName(name: "th"): NodeListOf; - getElementsByTagName(name: "thead"): NodeListOf; - getElementsByTagName(name: "title"): NodeListOf; - getElementsByTagName(name: "tr"): NodeListOf; - getElementsByTagName(name: "track"): NodeListOf; - getElementsByTagName(name: "tspan"): NodeListOf; - getElementsByTagName(name: "tt"): NodeListOf; - getElementsByTagName(name: "u"): NodeListOf; - getElementsByTagName(name: "ul"): NodeListOf; - getElementsByTagName(name: "use"): NodeListOf; - getElementsByTagName(name: "var"): NodeListOf; - getElementsByTagName(name: "video"): NodeListOf; - getElementsByTagName(name: "view"): NodeListOf; - getElementsByTagName(name: "wbr"): NodeListOf; - getElementsByTagName(name: "x-ms-webview"): NodeListOf; - getElementsByTagName(name: "xmp"): NodeListOf; - getElementsByTagName(name: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - hasAttribute(name: string): boolean; - hasAttributeNS(namespaceURI: string, localName: string): boolean; - msGetRegionContent(): MSRangeCollection; - msGetUntransformedBounds(): ClientRect; - msMatchesSelector(selectors: string): boolean; - msReleasePointerCapture(pointerId: number): void; - msSetPointerCapture(pointerId: number): void; - msZoomTo(args: MsZoomToOptions): void; - releasePointerCapture(pointerId: number): void; - removeAttribute(name?: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; - removeAttributeNode(oldAttr: Attr): Attr; - requestFullscreen(): void; - requestPointerLock(): void; - setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; - setAttributeNode(newAttr: Attr): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; - setPointerCapture(pointerId: number): void; - webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; - webkitRequestFullscreen(): void; - getElementsByClassName(classNames: string): NodeListOf; - matches(selector: string): boolean; - closest(selector: string): Element | null; - scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; - scroll(options?: ScrollToOptions): void; - scroll(x: number, y: number): void; - scrollTo(options?: ScrollToOptions): void; - scrollTo(x: number, y: number): void; - scrollBy(options?: ScrollToOptions): void; - scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Element: { - prototype: Element; - new(): Element; -} - -interface ErrorEvent extends Event { - readonly colno: number; - readonly error: any; - readonly filename: string; - readonly lineno: number; - readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; -} - -declare var ErrorEvent: { - prototype: ErrorEvent; - new(): ErrorEvent; -} - -interface Event { - readonly bubbles: boolean; - cancelBubble: boolean; - readonly cancelable: boolean; - readonly currentTarget: EventTarget; - readonly defaultPrevented: boolean; - readonly eventPhase: number; - readonly isTrusted: boolean; - returnValue: boolean; - readonly srcElement: Element | null; - readonly target: EventTarget; - readonly timeStamp: number; - readonly type: string; - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; - preventDefault(): void; - stopImmediatePropagation(): void; - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -declare var Event: { - prototype: Event; - new(type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -interface EventTarget { - addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var EventTarget: { - prototype: EventTarget; - new(): EventTarget; -} - -interface External { -} - -declare var External: { - prototype: External; - new(): External; -} - -interface File extends Blob { - readonly lastModifiedDate: any; - readonly name: string; - readonly webkitRelativePath: string; -} - -declare var File: { - prototype: File; - new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} - -interface FileList { - readonly length: number; - item(index: number): File; - [index: number]: File; -} - -declare var FileList: { - prototype: FileList; - new(): FileList; -} - -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(blob: Blob): void; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var FileReader: { - prototype: FileReader; - new(): FileReader; -} - -interface FocusEvent extends UIEvent { - readonly relatedTarget: EventTarget; - initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; -} - -declare var FocusEvent: { - prototype: FocusEvent; - new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} - -interface FormData { - append(name: any, value: any, blobName?: string): void; -} - -declare var FormData: { - prototype: FormData; - new (form?: HTMLFormElement): FormData; -} - -interface GainNode extends AudioNode { - readonly gain: AudioParam; -} - -declare var GainNode: { - prototype: GainNode; - new(): GainNode; -} - -interface Gamepad { - readonly axes: number[]; - readonly buttons: GamepadButton[]; - readonly connected: boolean; - readonly id: string; - readonly index: number; - readonly mapping: string; - readonly timestamp: number; -} - -declare var Gamepad: { - prototype: Gamepad; - new(): Gamepad; -} - -interface GamepadButton { - readonly pressed: boolean; - readonly value: number; -} - -declare var GamepadButton: { - prototype: GamepadButton; - new(): GamepadButton; -} - -interface GamepadEvent extends Event { - readonly gamepad: Gamepad; -} - -declare var GamepadEvent: { - prototype: GamepadEvent; - new(): GamepadEvent; -} - -interface Geolocation { - clearWatch(watchId: number): void; - getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; - watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; -} - -declare var Geolocation: { - prototype: Geolocation; - new(): Geolocation; -} - -interface HTMLAllCollection extends HTMLCollection { - namedItem(name: string): Element; -} - -declare var HTMLAllCollection: { - prototype: HTMLAllCollection; - new(): HTMLAllCollection; -} - -interface HTMLAnchorElement extends HTMLElement { - Methods: string; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Contains the anchor portion of the URL including the hash sign (#). - */ - hash: string; - /** - * Contains the hostname and port values of the URL. - */ - host: string; - /** - * Contains the hostname of a URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - readonly mimeType: string; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - readonly nameProp: string; - /** - * Contains the pathname of the URL. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Contains the protocol of the URL. - */ - protocol: string; - readonly protocolLong: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: 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; -} - -declare var HTMLAnchorElement: { - prototype: HTMLAnchorElement; - new(): HTMLAnchorElement; -} - -interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ - declare: boolean; - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - object: string | null; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - vspace: number; - width: number; -} - -declare var HTMLAppletElement: { - prototype: HTMLAppletElement; - new(): HTMLAppletElement; -} - -interface HTMLAreaElement extends HTMLElement { - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ - hash: string; - /** - * Sets or retrieves the hostname and port number of the location or URL. - */ - host: string; - /** - * Sets or retrieves the host name part of the location or URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or gets whether clicks in this region cause action. - */ - noHref: boolean; - /** - * Sets or retrieves the file name or path specified by the object. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Sets or retrieves the protocol portion of a URL. - */ - protocol: string; - rel: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns a string representation of an object. - */ - toString(): string; -} - -declare var HTMLAreaElement: { - prototype: HTMLAreaElement; - new(): HTMLAreaElement; -} - -interface HTMLAreasCollection extends HTMLCollection { - /** - * Adds an element to the areas, controlRange, or options collection. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Removes an element from the collection. - */ - remove(index?: number): void; -} - -declare var HTMLAreasCollection: { - prototype: HTMLAreasCollection; - new(): HTMLAreasCollection; -} - -interface HTMLAudioElement extends HTMLMediaElement { -} - -declare var HTMLAudioElement: { - prototype: HTMLAudioElement; - new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} - -interface HTMLBaseElement extends HTMLElement { - /** - * Gets or sets the baseline URL on which relative links are based. - */ - href: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; -} - -declare var HTMLBaseElement: { - prototype: HTMLBaseElement; - new(): HTMLBaseElement; -} - -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - /** - * Sets or retrieves the font size of the object. - */ - size: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -} - -interface HTMLBodyElement extends HTMLElement { - aLink: any; - background: string; - bgColor: any; - bgProperties: string; - link: any; - noWrap: boolean; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - text: any; - vLink: any; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBodyElement: { - prototype: HTMLBodyElement; - new(): HTMLBodyElement; -} - -interface HTMLButtonElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - status: any; - /** - * Gets the classification and default behavior of the button. - */ - type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * 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; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLButtonElement: { - prototype: HTMLButtonElement; - new(): HTMLButtonElement; -} - -interface HTMLCanvasElement extends HTMLElement { - /** - * Gets or sets the height of a canvas element on a document. - */ - height: number; - /** - * Gets or sets the width of a canvas element on a document. - */ - width: number; - /** - * 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", 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. - */ - msToBlob(): Blob; - /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; -} - -declare var HTMLCanvasElement: { - prototype: HTMLCanvasElement; - new(): HTMLCanvasElement; -} - -interface HTMLCollection { - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Retrieves an object from various collections. - */ - item(index: number): Element; - /** - * Retrieves a select object or an object from an options collection. - */ - namedItem(name: string): Element; - [index: number]: Element; -} - -declare var HTMLCollection: { - prototype: HTMLCollection; - new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} - -interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; -} - -declare var HTMLDataListElement: { - prototype: HTMLDataListElement; - new(): HTMLDataListElement; -} - -interface HTMLDirectoryElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDirectoryElement: { - prototype: HTMLDirectoryElement; - new(): HTMLDirectoryElement; -} - -interface HTMLDivElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; -} - -declare var HTMLDivElement: { - prototype: HTMLDivElement; - new(): HTMLDivElement; -} - -interface HTMLDocument extends Document { -} - -declare var HTMLDocument: { - prototype: HTMLDocument; - new(): HTMLDocument; -} - -interface HTMLElement extends Element { - accessKey: string; - readonly children: HTMLCollection; - contentEditable: string; - readonly dataset: DOMStringMap; - dir: string; - draggable: boolean; - hidden: boolean; - hideFocus: boolean; - innerHTML: string; - innerText: string; - readonly isContentEditable: boolean; - lang: string; - readonly offsetHeight: number; - readonly offsetLeft: number; - readonly offsetParent: Element; - readonly offsetTop: number; - readonly offsetWidth: number; - onabort: (this: this, ev: UIEvent) => any; - onactivate: (this: this, ev: UIEvent) => any; - onbeforeactivate: (this: this, ev: UIEvent) => any; - onbeforecopy: (this: this, ev: ClipboardEvent) => any; - onbeforecut: (this: this, ev: ClipboardEvent) => any; - onbeforedeactivate: (this: this, ev: UIEvent) => any; - onbeforepaste: (this: this, ev: ClipboardEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - oncopy: (this: this, ev: ClipboardEvent) => any; - oncuechange: (this: this, ev: Event) => any; - oncut: (this: this, ev: ClipboardEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondeactivate: (this: this, ev: UIEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onpaste: (this: this, ev: ClipboardEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreset: (this: this, ev: Event) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onselectstart: (this: this, ev: Event) => any; - onstalled: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - outerHTML: string; - outerText: string; - spellcheck: boolean; - readonly style: CSSStyleDeclaration; - tabIndex: number; - title: string; - blur(): void; - click(): void; - dragDrop(): boolean; - focus(): void; - msGetInputContext(): MSInputMethodContext; - setActive(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLElement: { - prototype: HTMLElement; - new(): HTMLElement; -} - -interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves the height of the object. - */ - height: string; - hidden: any; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the palette used for the embedded document. - */ - readonly palette: string; - /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ - readonly pluginspage: string; - readonly readyState: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the height and width units of the embed object. - */ - units: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLEmbedElement: { - prototype: HTMLEmbedElement; - new(): HTMLEmbedElement; -} - -interface HTMLFieldSetElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLFieldSetElement: { - prototype: HTMLFieldSetElement; - new(): HTMLFieldSetElement; -} - -interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFontElement: { - prototype: HTMLFontElement; - new(): HTMLFontElement; -} - -interface HTMLFormElement extends HTMLElement { - /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ - acceptCharset: string; - /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ - action: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Retrieves a collection, in source order, of all controls in a given form. - */ - readonly elements: HTMLCollection; - /** - * Sets or retrieves the MIME encoding for the form. - */ - encoding: string; - /** - * Sets or retrieves the encoding type for the form. - */ - enctype: string; - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Sets or retrieves how to send the form data to the server. - */ - method: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Designates a form that is not validated when submitted. - */ - noValidate: boolean; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a form object or an object from an elements collection. - */ - namedItem(name: string): any; - /** - * Fires when the user resets a form. - */ - reset(): void; - /** - * Fires when a FORM is about to be submitted. - */ - submit(): void; - [name: string]: any; -} - -declare var HTMLFormElement: { - prototype: HTMLFormElement; - new(): HTMLFormElement; -} - -interface HTMLFrameElement extends HTMLElement, GetSVGDocument { - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string | number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the width of the object. - */ - width: string | number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameElement: { - prototype: HTMLFrameElement; - new(): HTMLFrameElement; -} - -interface HTMLFrameSetElement extends HTMLElement { - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Sets or retrieves the frame widths of the object. - */ - cols: string; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - name: string; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - /** - * Sets or retrieves the frame heights of the object. - */ - rows: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameSetElement: { - prototype: HTMLFrameSetElement; - new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} - -interface HTMLHeadElement extends HTMLElement { - profile: string; -} - -declare var HTMLHeadElement: { - prototype: HTMLHeadElement; - new(): HTMLHeadElement; -} - -interface HTMLHeadingElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; -} - -declare var HTMLHeadingElement: { - prototype: HTMLHeadingElement; - new(): HTMLHeadingElement; -} - -interface HTMLHtmlElement extends HTMLElement { - /** - * Sets or retrieves the DTD version that governs the current document. - */ - version: string; -} - -declare var HTMLHtmlElement: { - prototype: HTMLHtmlElement; - new(): HTMLHtmlElement; -} - -interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - allowFullscreen: boolean; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the horizontal margin for the object. - */ - hspace: number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - readonly sandbox: DOMSettableTokenList; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLIFrameElement: { - prototype: HTMLIFrameElement; - new(): HTMLIFrameElement; -} - -interface HTMLImageElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - crossOrigin: string; - readonly currentSrc: string; - /** - * Sets or retrieves the height of the object. - */ - height: number; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - /** - * Sets or retrieves whether the image is a server-side image map. - */ - isMap: boolean; - /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ - longDesc: string; - lowsrc: string; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * The original height of the image resource before sizing. - */ - readonly naturalHeight: number; - /** - * The original width of the image resource before sizing. - */ - readonly naturalWidth: number; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: number; - readonly x: number; - readonly y: number; - msGetAsCastingSource(): any; -} - -declare var HTMLImageElement: { - prototype: HTMLImageElement; - new(): HTMLImageElement; - create(): HTMLImageElement; -} - -interface HTMLInputElement extends HTMLElement { - /** - * Sets or retrieves a comma-separated list of content types. - */ - accept: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the state of the check box or radio button. - */ - checked: boolean; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - /** - * Sets or retrieves the state of the check box or radio button. - */ - defaultChecked: boolean; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Returns a FileList object on a file type input object. - */ - readonly files: FileList | null; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - indeterminate: boolean; - /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ - readonly list: HTMLElement; - /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ - max: string; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ - min: string; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ - pattern: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - selectionDirection: string; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - size: number; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - status: boolean; - /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ - step: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns the value of the data at the cursor's current position. - */ - value: string; - valueAsDate: Date; - /** - * Returns the input field value as a number. - */ - valueAsNumber: number; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - webkitdirectory: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Makes the selection equal to the current object. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start?: number, end?: number, direction?: string): void; - /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ - stepDown(n?: number): void; - /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ - stepUp(n?: number): void; -} - -declare var HTMLInputElement: { - prototype: HTMLInputElement; - new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} - -interface HTMLLabelElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the object to which the given label object is assigned. - */ - htmlFor: string; -} - -declare var HTMLLabelElement: { - prototype: HTMLLabelElement; - new(): HTMLLabelElement; -} - -interface HTMLLegendElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - align: string; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; -} - -declare var HTMLLegendElement: { - prototype: HTMLLegendElement; - new(): HTMLLegendElement; -} - -interface HTMLLinkElement extends HTMLElement, LinkStyle { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - disabled: boolean; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - import?: Document; - integrity: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLinkElement: { - prototype: HTMLLinkElement; - new(): HTMLLinkElement; -} - -interface HTMLMapElement extends HTMLElement { - /** - * Retrieves a collection of the area objects defined for the given map object. - */ - readonly areas: HTMLAreasCollection; - /** - * Sets or retrieves the name of the object. - */ - name: string; -} - -declare var HTMLMapElement: { - prototype: HTMLMapElement; - new(): HTMLMapElement; -} - -interface HTMLMarqueeElement extends HTMLElement { - behavior: string; - bgColor: any; - direction: string; - height: string; - hspace: number; - loop: number; - onbounce: (this: this, ev: Event) => any; - onfinish: (this: this, ev: Event) => any; - onstart: (this: this, ev: Event) => any; - scrollAmount: number; - scrollDelay: number; - trueSpeed: boolean; - vspace: number; - width: string; - start(): void; - stop(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "bounce", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "finish", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "start", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMarqueeElement: { - prototype: HTMLMarqueeElement; - new(): HTMLMarqueeElement; -} - -interface HTMLMediaElement extends HTMLElement { - /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ - readonly audioTracks: AudioTrackList; - /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ - autoplay: boolean; - /** - * Gets a collection of buffered time ranges. - */ - readonly buffered: TimeRanges; - /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ - controls: boolean; - crossOrigin: string; - /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ - readonly currentSrc: string; - /** - * Gets or sets the current playback position, in seconds. - */ - currentTime: number; - defaultMuted: boolean; - /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ - defaultPlaybackRate: number; - /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ - readonly duration: number; - /** - * Gets information about whether the playback has ended or not. - */ - readonly ended: boolean; - /** - * Returns an object representing the current error state of the audio or video element. - */ - readonly error: MediaError; - /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ - loop: boolean; - readonly mediaKeys: MediaKeys | null; - /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ - msAudioCategory: string; - /** - * Specifies the output device id that the audio will be sent to. - */ - msAudioDeviceType: string; - readonly msGraphicsTrustStatus: MSGraphicsTrust; - /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ - readonly msKeys: MSMediaKeys; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Specifies whether or not to enable low-latency playback on the media element. - */ - msRealTime: boolean; - /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ - muted: boolean; - /** - * Gets the current network activity for the element. - */ - readonly networkState: number; - onencrypted: (this: this, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: this, ev: MSMediaKeyNeededEvent) => any; - /** - * Gets a flag that specifies whether playback is paused. - */ - readonly paused: boolean; - /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ - playbackRate: number; - /** - * Gets TimeRanges for the current media resource that has been played. - */ - readonly played: TimeRanges; - /** - * Gets or sets the current playback position, in seconds. - */ - preload: string; - readyState: number; - /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ - readonly seekable: TimeRanges; - /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ - readonly seeking: boolean; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcObject: MediaStream | null; - readonly textTracks: TextTrackList; - readonly videoTracks: VideoTrackList; - /** - * Gets or sets the volume level for audio portions of the media element. - */ - volume: number; - addTextTrack(kind: string, label?: string, language?: string): TextTrack; - /** - * Returns a string that specifies whether the client can play a given media resource type. - */ - canPlayType(type: string): string; - /** - * Resets the audio or video object and loads a new media resource. - */ - load(): void; - /** - * Clears all effects from the media pipeline. - */ - msClearEffects(): void; - msGetAsCastingSource(): any; - /** - * Inserts the specified audio effect into media pipeline. - */ - msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetMediaKeys(mediaKeys: MSMediaKeys): void; - /** - * Specifies the media protection manager for a given media pipeline. - */ - msSetMediaProtectionManager(mediaProtectionManager?: any): void; - /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ - pause(): void; - /** - * Loads and starts playback of a media resource. - */ - play(): void; - setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMediaElement: { - prototype: HTMLMediaElement; - new(): HTMLMediaElement; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; -} - -interface HTMLMenuElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLMenuElement: { - prototype: HTMLMenuElement; - new(): HTMLMenuElement; -} - -interface HTMLMetaElement extends HTMLElement { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ - content: string; - /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ - httpEquiv: string; - /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ - name: string; - /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ - scheme: string; - /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ - url: string; -} - -declare var HTMLMetaElement: { - prototype: HTMLMetaElement; - new(): HTMLMetaElement; -} - -interface HTMLMeterElement extends HTMLElement { - high: number; - low: number; - max: number; - min: number; - optimum: number; - value: number; -} - -declare var HTMLMeterElement: { - prototype: HTMLMeterElement; - new(): HTMLMeterElement; -} - -interface HTMLModElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; - /** - * Sets or retrieves the date and time of a modification to the object. - */ - dateTime: string; -} - -declare var HTMLModElement: { - prototype: HTMLModElement; - new(): HTMLModElement; -} - -interface HTMLOListElement extends HTMLElement { - compact: boolean; - /** - * The starting number. - */ - start: number; - type: string; -} - -declare var HTMLOListElement: { - prototype: HTMLOListElement; - new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the contained object. - */ - readonly object: any; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} - -interface HTMLOptGroupElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - readonly text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptGroupElement: { - prototype: HTMLOptGroupElement; - new(): HTMLOptGroupElement; -} - -interface HTMLOptionElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptionElement: { - prototype: HTMLOptionElement; - new(): HTMLOptionElement; - create(): HTMLOptionElement; -} - -interface HTMLOptionsCollection extends HTMLCollectionOf { - length: number; - selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; - remove(index: number): void; -} - -declare var HTMLOptionsCollection: { - prototype: HTMLOptionsCollection; - new(): HTMLOptionsCollection; -} - -interface HTMLParagraphElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - clear: string; -} - -declare var HTMLParagraphElement: { - prototype: HTMLParagraphElement; - new(): HTMLParagraphElement; -} - -interface HTMLParamElement extends HTMLElement { - /** - * Sets or retrieves the name of an input parameter for an element. - */ - name: string; - /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ - type: string; - /** - * Sets or retrieves the value of an input parameter for an element. - */ - value: string; - /** - * Sets or retrieves the data type of the value attribute. - */ - valueType: string; -} - -declare var HTMLParamElement: { - prototype: HTMLParamElement; - new(): HTMLParamElement; -} - -interface HTMLPictureElement extends HTMLElement { -} - -declare var HTMLPictureElement: { - prototype: HTMLPictureElement; - new(): HTMLPictureElement; -} - -interface HTMLPreElement extends HTMLElement { - /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ - width: number; -} - -declare var HTMLPreElement: { - prototype: HTMLPreElement; - new(): HTMLPreElement; -} - -interface HTMLProgressElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Defines the maximum, or "done" value for a progress element. - */ - max: number; - /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ - readonly position: number; - /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ - value: number; -} - -declare var HTMLProgressElement: { - prototype: HTMLProgressElement; - new(): HTMLProgressElement; -} - -interface HTMLQuoteElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; -} - -declare var HTMLQuoteElement: { - prototype: HTMLQuoteElement; - new(): HTMLQuoteElement; -} - -interface HTMLScriptElement extends HTMLElement { - async: boolean; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the status of the script. - */ - defer: boolean; - /** - * 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; - /** - * Retrieves the URL to an external file that contains the source code or data. - */ - src: string; - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; - /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ - type: string; - integrity: string; -} - -declare var HTMLScriptElement: { - prototype: HTMLScriptElement; - new(): HTMLScriptElement; -} - -interface HTMLSelectElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the number of objects in a collection. - */ - length: number; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly options: HTMLOptionsCollection; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the index of the selected option in a select object. - */ - selectedIndex: number; - selectedOptions: HTMLCollectionOf; - /** - * Sets or retrieves the number of rows in the list box. - */ - size: number; - /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * 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. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ - namedItem(name: string): any; - /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ - remove(index?: number): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - [name: string]: any; -} - -declare var HTMLSelectElement: { - prototype: HTMLSelectElement; - new(): HTMLSelectElement; -} - -interface HTMLSourceElement extends HTMLElement { - /** - * Gets or sets the intended media type of the media source. - */ - media: string; - msKeySystem: string; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Gets or sets the MIME type of a media resource. - */ - type: string; -} - -declare var HTMLSourceElement: { - prototype: HTMLSourceElement; - new(): HTMLSourceElement; -} - -interface HTMLSpanElement extends HTMLElement { -} - -declare var HTMLSpanElement: { - prototype: HTMLSpanElement; - new(): HTMLSpanElement; -} - -interface HTMLStyleElement extends HTMLElement, LinkStyle { - disabled: boolean; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Retrieves the CSS language in which the style sheet is written. - */ - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLStyleElement: { - prototype: HTMLStyleElement; - new(): HTMLStyleElement; -} - -interface HTMLTableCaptionElement extends HTMLElement { - /** - * Sets or retrieves the alignment of the caption or legend. - */ - align: string; - /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ - vAlign: string; -} - -declare var HTMLTableCaptionElement: { - prototype: HTMLTableCaptionElement; - new(): HTMLTableCaptionElement; -} - -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves abbreviated text for the object. - */ - abbr: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ - axis: string; - bgColor: any; - /** - * Retrieves the position of the object in the cells collection of a row. - */ - readonly cellIndex: number; - /** - * Sets or retrieves the number columns in the table that the object should span. - */ - colSpan: number; - /** - * Sets or retrieves a list of header cells that provide information for the object. - */ - headers: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; - /** - * Sets or retrieves how many rows in a table the cell should span. - */ - rowSpan: number; - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableCellElement: { - prototype: HTMLTableCellElement; - new(): HTMLTableCellElement; -} - -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ - align: string; - /** - * Sets or retrieves the number of columns in the group. - */ - span: number; - /** - * Sets or retrieves the width of the object. - */ - width: any; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableColElement: { - prototype: HTMLTableColElement; - new(): HTMLTableColElement; -} - -interface HTMLTableDataCellElement extends HTMLTableCellElement { -} - -declare var HTMLTableDataCellElement: { - prototype: HTMLTableDataCellElement; - new(): HTMLTableDataCellElement; -} - -interface HTMLTableElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - bgColor: any; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the caption object of a table. - */ - caption: HTMLTableCaptionElement; - /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ - cellPadding: string; - /** - * Sets or retrieves the amount of space between cells in a table. - */ - cellSpacing: string; - /** - * Sets or retrieves the number of columns in the table. - */ - cols: number; - /** - * Sets or retrieves the way the border frame around the table is displayed. - */ - frame: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ - rules: string; - /** - * Sets or retrieves a description and/or structure of the object. - */ - summary: string; - /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ - tBodies: HTMLCollectionOf; - /** - * Retrieves the tFoot object of the table. - */ - tFoot: HTMLTableSectionElement; - /** - * Retrieves the tHead object of the table. - */ - tHead: HTMLTableSectionElement; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Creates an empty caption element in the table. - */ - createCaption(): HTMLTableCaptionElement; - /** - * Creates an empty tBody element in the table. - */ - createTBody(): HTMLTableSectionElement; - /** - * Creates an empty tFoot element in the table. - */ - createTFoot(): HTMLTableSectionElement; - /** - * Returns the tHead element object if successful, or null otherwise. - */ - createTHead(): HTMLTableSectionElement; - /** - * Deletes the caption element and its contents from the table. - */ - deleteCaption(): void; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Deletes the tFoot element and its contents from the table. - */ - deleteTFoot(): void; - /** - * Deletes the tHead element and its contents from the table. - */ - deleteTHead(): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; -} - -declare var HTMLTableElement: { - prototype: HTMLTableElement; - new(): HTMLTableElement; -} - -interface HTMLTableHeaderCellElement extends HTMLTableCellElement { - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; -} - -declare var HTMLTableHeaderCellElement: { - prototype: HTMLTableHeaderCellElement; - new(): HTMLTableHeaderCellElement; -} - -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - bgColor: any; - /** - * Retrieves a collection of all cells in the table row. - */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Retrieves the position of the object in the rows collection for the table. - */ - readonly rowIndex: number; - /** - * Retrieves the position of the object in the collection. - */ - readonly sectionRowIndex: number; - /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ - deleteCell(index?: number): void; - /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ - insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableRowElement: { - prototype: HTMLTableRowElement; - new(): HTMLTableRowElement; -} - -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableSectionElement: { - prototype: HTMLTableSectionElement; - new(): HTMLTableSectionElement; -} - -interface HTMLTemplateElement extends HTMLElement { - readonly content: DocumentFragment; -} - -declare var HTMLTemplateElement: { - prototype: HTMLTemplateElement; - new(): HTMLTemplateElement; -} - -interface HTMLTextAreaElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the object. - */ - cols: number; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: number; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - /** - * Sets or retrieves the value indicating whether the control is selected. - */ - status: any; - /** - * Retrieves the type of control. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Retrieves or sets the text in the entry field of the textArea element. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Sets or retrieves how to handle wordwrapping in the object. - */ - wrap: string; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Highlights the input area of a form element. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start: number, end: number): void; -} - -declare var HTMLTextAreaElement: { - prototype: HTMLTextAreaElement; - new(): HTMLTextAreaElement; -} - -interface HTMLTitleElement extends HTMLElement { - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; -} - -declare var HTMLTitleElement: { - prototype: HTMLTitleElement; - new(): HTMLTitleElement; -} - -interface HTMLTrackElement extends HTMLElement { - default: boolean; - kind: string; - label: string; - readonly readyState: number; - src: string; - srclang: string; - readonly track: TextTrack; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -declare var HTMLTrackElement: { - prototype: HTMLTrackElement; - new(): HTMLTrackElement; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -interface HTMLUListElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLUListElement: { - prototype: HTMLUListElement; - new(): HTMLUListElement; -} - -interface HTMLUnknownElement extends HTMLElement { -} - -declare var HTMLUnknownElement: { - prototype: HTMLUnknownElement; - new(): HTMLUnknownElement; -} - -interface HTMLVideoElement extends HTMLMediaElement { - /** - * Gets or sets the height of the video element. - */ - height: number; - msHorizontalMirror: boolean; - readonly msIsLayoutOptimalForPlayback: boolean; - readonly msIsStereo3D: boolean; - msStereo3DPackingMode: string; - msStereo3DRenderMode: string; - msZoom: boolean; - onMSVideoFormatChanged: (this: this, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: this, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: this, ev: Event) => any; - /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ - poster: string; - /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoHeight: number; - /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoWidth: number; - readonly webkitDisplayingFullscreen: boolean; - readonly webkitSupportsFullscreen: boolean; - /** - * Gets or sets the width of the video element. - */ - width: number; - getVideoPlaybackQuality(): VideoPlaybackQuality; - msFrameStep(forward: boolean): void; - msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; - webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; - webkitExitFullscreen(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFormatChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFrameStepCompleted", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLVideoElement: { - prototype: HTMLVideoElement; - new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface History { - readonly length: number; - readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; -} - -declare var History: { - prototype: History; - new(): History; -} - -interface IDBCursor { - readonly direction: string; - key: IDBKeyRange | IDBValidKey; - readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; - advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; - delete(): IDBRequest; - update(value: any): IDBRequest; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -declare var IDBCursor: { - prototype: IDBCursor; - new(): IDBCursor; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -interface IDBCursorWithValue extends IDBCursor { - readonly value: any; -} - -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new(): IDBCursorWithValue; -} - -interface IDBDatabase extends EventTarget { - readonly name: string; - readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - version: number; - onversionchange: (ev: IDBVersionChangeEvent) => any; - close(): void; - createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; - deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBDatabase: { - prototype: IDBDatabase; - new(): IDBDatabase; -} - -interface IDBFactory { - cmp(first: any, second: any): number; - deleteDatabase(name: string): IDBOpenDBRequest; - open(name: string, version?: number): IDBOpenDBRequest; -} - -declare var IDBFactory: { - prototype: IDBFactory; - new(): IDBFactory; -} - -interface IDBIndex { - keyPath: string | string[]; - readonly name: string; - readonly objectStore: IDBObjectStore; - readonly unique: boolean; - multiEntry: boolean; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - get(key: IDBKeyRange | IDBValidKey): IDBRequest; - getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; -} - -declare var IDBIndex: { - prototype: IDBIndex; - new(): IDBIndex; -} - -interface IDBKeyRange { - readonly lower: any; - readonly lowerOpen: boolean; - readonly upper: any; - readonly upperOpen: boolean; -} - -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new(): IDBKeyRange; - bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; - lowerBound(lower: any, open?: boolean): IDBKeyRange; - only(value: any): IDBKeyRange; - upperBound(upper: any, open?: boolean): IDBKeyRange; -} - -interface IDBObjectStore { - readonly indexNames: DOMStringList; - keyPath: string | string[]; - readonly name: string; - readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; - clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; - deleteIndex(indexName: string): void; - get(key: any): IDBRequest; - index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; -} - -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new(): IDBObjectStore; -} - -interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new(): IDBOpenDBRequest; -} - -interface IDBRequest extends EventTarget { - readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; - readonly readyState: string; - readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; - readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBRequest: { - prototype: IDBRequest; - new(): IDBRequest; -} - -interface IDBTransaction extends EventTarget { - readonly db: IDBDatabase; - readonly error: DOMError; - readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - abort(): void; - objectStore(name: string): IDBObjectStore; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBTransaction: { - prototype: IDBTransaction; - new(): IDBTransaction; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; -} - -interface IDBVersionChangeEvent extends Event { - readonly newVersion: number | null; - readonly oldVersion: number; -} - -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new(): IDBVersionChangeEvent; -} - -interface ImageData { - data: Uint8ClampedArray; - readonly height: number; - readonly width: number; -} - -declare var ImageData: { - prototype: ImageData; - new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} - -interface KeyboardEvent extends UIEvent { - readonly altKey: boolean; - readonly char: string | null; - readonly charCode: number; - readonly ctrlKey: boolean; - readonly key: string; - readonly keyCode: number; - readonly locale: string; - readonly location: number; - readonly metaKey: boolean; - readonly repeat: boolean; - readonly shiftKey: boolean; - readonly which: number; - readonly code: string; - getModifierState(keyArg: string): boolean; - initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -declare var KeyboardEvent: { - prototype: KeyboardEvent; - new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -interface ListeningStateChangedEvent extends Event { - readonly label: string; - readonly state: string; -} - -declare var ListeningStateChangedEvent: { - prototype: ListeningStateChangedEvent; - new(): ListeningStateChangedEvent; -} - -interface Location { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - pathname: string; - port: string; - protocol: string; - search: string; - assign(url: string): void; - reload(forcedReload?: boolean): void; - replace(url: string): void; - toString(): string; -} - -declare var Location: { - prototype: Location; - new(): Location; -} - -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; -} - -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; -} - -interface MSApp { - clearTemporaryWebDataAsync(): MSAppAsyncOperation; - createBlobFromRandomAccessStream(type: string, seeker: any): Blob; - createDataPackage(object: any): any; - createDataPackageFromSelection(): any; - createFileFromStorageFile(storageFile: any): File; - createStreamFromInputStream(type: string, inputStream: any): MSStream; - execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; - execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; - getCurrentPriority(): string; - getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; - getViewId(view: any): any; - isTaskScheduledAtPriorityOrHigher(priority: string): boolean; - pageHandlesAllApplicationActivations(enabled: boolean): void; - suppressSubdownloadCredentialPrompts(suppress: boolean): void; - terminateApp(exceptionObject: any): void; - readonly CURRENT: string; - readonly HIGH: string; - readonly IDLE: string; - readonly NORMAL: string; -} -declare var MSApp: MSApp; - -interface MSAppAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSAppAsyncOperation: { - prototype: MSAppAsyncOperation; - new(): MSAppAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; -} - -interface MSAssertion { - readonly id: string; - readonly type: string; -} - -declare var MSAssertion: { - prototype: MSAssertion; - new(): MSAssertion; -} - -interface MSBlobBuilder { - append(data: any, endings?: string): void; - getBlob(contentType?: string): Blob; -} - -declare var MSBlobBuilder: { - prototype: MSBlobBuilder; - new(): MSBlobBuilder; -} - -interface MSCredentials { - getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; - makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; -} - -declare var MSCredentials: { - prototype: MSCredentials; - new(): MSCredentials; -} - -interface MSFIDOCredentialAssertion extends MSAssertion { - readonly algorithm: string | Algorithm; - readonly attestation: any; - readonly publicKey: string; - readonly transportHints: string[]; -} - -declare var MSFIDOCredentialAssertion: { - prototype: MSFIDOCredentialAssertion; - new(): MSFIDOCredentialAssertion; -} - -interface MSFIDOSignature { - readonly authnrData: string; - readonly clientData: string; - readonly signature: string; -} - -declare var MSFIDOSignature: { - prototype: MSFIDOSignature; - new(): MSFIDOSignature; -} - -interface MSFIDOSignatureAssertion extends MSAssertion { - readonly signature: MSFIDOSignature; -} - -declare var MSFIDOSignatureAssertion: { - prototype: MSFIDOSignatureAssertion; - new(): MSFIDOSignatureAssertion; -} - -interface MSGesture { - target: Element; - addPointer(pointerId: number): void; - stop(): void; -} - -declare var MSGesture: { - prototype: MSGesture; - new(): MSGesture; -} - -interface MSGestureEvent extends UIEvent { - readonly clientX: number; - readonly clientY: number; - readonly expansion: number; - readonly gestureObject: any; - readonly hwTimestamp: number; - readonly offsetX: number; - readonly offsetY: number; - readonly rotation: number; - readonly scale: number; - readonly screenX: number; - readonly screenY: number; - readonly translationX: number; - readonly translationY: number; - readonly velocityAngular: number; - readonly velocityExpansion: number; - readonly velocityX: number; - readonly velocityY: number; - initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -interface MSGraphicsTrust { - readonly constrictionActive: boolean; - readonly status: string; -} - -declare var MSGraphicsTrust: { - prototype: MSGraphicsTrust; - new(): MSGraphicsTrust; -} - -interface MSHTMLWebViewElement extends HTMLElement { - readonly canGoBack: boolean; - readonly canGoForward: boolean; - readonly containsFullScreenElement: boolean; - readonly documentTitle: string; - height: number; - readonly settings: MSWebViewSettings; - src: string; - width: number; - addWebAllowedObject(name: string, applicationObject: any): void; - buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; - capturePreviewToBlobAsync(): MSWebViewAsyncOperation; - captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; - getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; - getDeferredPermissionRequests(): DeferredPermissionRequest[]; - goBack(): void; - goForward(): void; - invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; - navigate(uri: string): void; - navigateToLocalStreamUri(source: string, streamResolver: any): void; - navigateToString(contents: string): void; - navigateWithHttpRequestMessage(requestMessage: any): void; - refresh(): void; - stop(): void; -} - -declare var MSHTMLWebViewElement: { - prototype: MSHTMLWebViewElement; - new(): MSHTMLWebViewElement; -} - -interface MSInputMethodContext extends EventTarget { - readonly compositionEndOffset: number; - readonly compositionStartOffset: number; - oncandidatewindowhide: (this: this, ev: Event) => any; - oncandidatewindowshow: (this: this, ev: Event) => any; - oncandidatewindowupdate: (this: this, ev: Event) => any; - readonly target: HTMLElement; - getCandidateWindowClientRect(): ClientRect; - getCompositionAlternatives(): string[]; - hasComposition(): boolean; - isCandidateWindowVisible(): boolean; - addEventListener(type: "MSCandidateWindowHide", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowShow", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowUpdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSInputMethodContext: { - prototype: MSInputMethodContext; - new(): MSInputMethodContext; -} - -interface MSManipulationEvent extends UIEvent { - readonly currentState: number; - readonly inertiaDestinationX: number; - readonly inertiaDestinationY: number; - readonly lastState: number; - initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -declare var MSManipulationEvent: { - prototype: MSManipulationEvent; - new(): MSManipulationEvent; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -interface MSMediaKeyError { - readonly code: number; - readonly systemCode: number; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -declare var MSMediaKeyError: { - prototype: MSMediaKeyError; - new(): MSMediaKeyError; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -interface MSMediaKeyMessageEvent extends Event { - readonly destinationURL: string | null; - readonly message: Uint8Array; -} - -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new(): MSMediaKeyMessageEvent; -} - -interface MSMediaKeyNeededEvent extends Event { - readonly initData: Uint8Array | null; -} - -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new(): MSMediaKeyNeededEvent; -} - -interface MSMediaKeySession extends EventTarget { - readonly error: MSMediaKeyError | null; - readonly keySystem: string; - readonly sessionId: string; - close(): void; - update(key: Uint8Array): void; -} - -declare var MSMediaKeySession: { - prototype: MSMediaKeySession; - new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} - -interface MSPointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} - -interface MSRangeCollection { - readonly length: number; - item(index: number): Range; - [index: number]: Range; -} - -declare var MSRangeCollection: { - prototype: MSRangeCollection; - new(): MSRangeCollection; -} - -interface MSSiteModeEvent extends Event { - readonly actionURL: string; - readonly buttonID: number; -} - -declare var MSSiteModeEvent: { - prototype: MSSiteModeEvent; - new(): MSSiteModeEvent; -} - -interface MSStream { - readonly type: string; - msClose(): void; - msDetachStream(): any; -} - -declare var MSStream: { - prototype: MSStream; - new(): MSStream; -} - -interface MSStreamReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(stream: MSStream, size?: number): void; - readAsBinaryString(stream: MSStream, size?: number): void; - readAsBlob(stream: MSStream, size?: number): void; - readAsDataURL(stream: MSStream, size?: number): void; - readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSStreamReader: { - prototype: MSStreamReader; - new(): MSStreamReader; -} - -interface MSWebViewAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - readonly target: MSHTMLWebViewElement; - readonly type: number; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSWebViewAsyncOperation: { - prototype: MSWebViewAsyncOperation; - new(): MSWebViewAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; -} - -interface MSWebViewSettings { - isIndexedDBEnabled: boolean; - isJavaScriptEnabled: boolean; -} - -declare var MSWebViewSettings: { - prototype: MSWebViewSettings; - new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: string; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: this, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): PromiseLike; - addEventListener(type: "devicechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: string; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: PromiseLike; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): PromiseLike; - generateRequest(initDataType: string, initData: any): PromiseLike; - load(sessionId: string): PromiseLike; - remove(): PromiseLike; - update(response: any): PromiseLike; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): string; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): PromiseLike; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: string): MediaKeySession; - setServerCertificate(serverCertificate: any): PromiseLike; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: this, ev: Event) => any; - onaddtrack: (this: this, ev: TrackEvent) => any; - oninactive: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: "active", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "inactive", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onmute: (this: this, ev: Event) => any; - onoverconstrained: (this: this, ev: MediaStreamErrorEvent) => any; - onunmute: (this: this, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: string; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): PromiseLike; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "overconstrained", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unmute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, ports?: any): void; - start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} - -interface MutationEvent extends Event { - readonly attrChange: number; - readonly attrName: string; - readonly newValue: string; - readonly prevValue: string; - readonly relatedNode: Node; - initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -declare var MutationEvent: { - prototype: MutationEvent; - new(): MutationEvent; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -interface MutationObserver { - disconnect(): void; - observe(target: Node, options: MutationObserverInit): void; - takeRecords(): MutationRecord[]; -} - -declare var MutationObserver: { - prototype: MutationObserver; - new(callback: MutationCallback): MutationObserver; -} - -interface MutationRecord { - readonly addedNodes: NodeList; - readonly attributeName: string | null; - readonly attributeNamespace: string | null; - readonly nextSibling: Node | null; - readonly oldValue: string | null; - readonly previousSibling: Node | null; - readonly removedNodes: NodeList; - readonly target: Node; - readonly type: string; -} - -declare var MutationRecord: { - prototype: MutationRecord; - new(): MutationRecord; -} - -interface NamedNodeMap { - readonly length: number; - getNamedItem(name: string): Attr; - getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - item(index: number): Attr; - removeNamedItem(name: string): Attr; - removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - setNamedItem(arg: Attr): Attr; - setNamedItemNS(arg: Attr): Attr; - [index: number]: Attr; -} - -declare var NamedNodeMap: { - prototype: NamedNodeMap; - new(): NamedNodeMap; -} - -interface NavigationCompletedEvent extends NavigationEvent { - readonly isSuccess: boolean; - readonly webErrorStatus: number; -} - -declare var NavigationCompletedEvent: { - prototype: NavigationCompletedEvent; - new(): NavigationCompletedEvent; -} - -interface NavigationEvent extends Event { - readonly uri: string; -} - -declare var NavigationEvent: { - prototype: NavigationEvent; - new(): NavigationEvent; -} - -interface NavigationEventWithReferrer extends NavigationEvent { - readonly referer: string; -} - -declare var NavigationEventWithReferrer: { - prototype: NavigationEventWithReferrer; - new(): NavigationEventWithReferrer; -} - -interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { - readonly appCodeName: string; - readonly cookieEnabled: boolean; - readonly language: string; - readonly maxTouchPoints: number; - readonly mimeTypes: MimeTypeArray; - readonly msManipulationViewsEnabled: boolean; - readonly msMaxTouchPoints: number; - readonly msPointerEnabled: boolean; - readonly plugins: PluginArray; - readonly pointerEnabled: boolean; - readonly webdriver: boolean; - getGamepads(): Gamepad[]; - javaEnabled(): boolean; - msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; - requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; - vibrate(pattern: number | number[]): boolean; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Navigator: { - prototype: Navigator; - new(): Navigator; -} - -interface Node extends EventTarget { - readonly attributes: NamedNodeMap; - readonly baseURI: string | null; - readonly childNodes: NodeList; - readonly firstChild: Node; - readonly lastChild: Node; - readonly localName: string | null; - readonly namespaceURI: string | null; - readonly nextSibling: Node; - readonly nodeName: string; - readonly nodeType: number; - nodeValue: string | null; - readonly ownerDocument: Document; - readonly parentElement: HTMLElement; - readonly parentNode: Node; - readonly previousSibling: Node; - textContent: string | null; - appendChild(newChild: Node): Node; - cloneNode(deep?: boolean): Node; - compareDocumentPosition(other: Node): number; - contains(child: Node): boolean; - hasAttributes(): boolean; - hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node | null): Node; - isDefaultNamespace(namespaceURI: string | null): boolean; - isEqualNode(arg: Node): boolean; - isSameNode(other: Node): boolean; - lookupNamespaceURI(prefix: string | null): string | null; - lookupPrefix(namespaceURI: string | null): string | null; - normalize(): void; - removeChild(oldChild: Node): Node; - replaceChild(newChild: Node, oldChild: Node): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -declare var Node: { - prototype: Node; - new(): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -interface NodeFilter { - acceptNode(n: Node): number; -} - -declare var NodeFilter: { - readonly FILTER_ACCEPT: number; - readonly FILTER_REJECT: number; - readonly FILTER_SKIP: number; - readonly SHOW_ALL: number; - readonly SHOW_ATTRIBUTE: number; - readonly SHOW_CDATA_SECTION: number; - readonly SHOW_COMMENT: number; - readonly SHOW_DOCUMENT: number; - readonly SHOW_DOCUMENT_FRAGMENT: number; - readonly SHOW_DOCUMENT_TYPE: number; - readonly SHOW_ELEMENT: number; - readonly SHOW_ENTITY: number; - readonly SHOW_ENTITY_REFERENCE: number; - readonly SHOW_NOTATION: number; - readonly SHOW_PROCESSING_INSTRUCTION: number; - readonly SHOW_TEXT: number; -} - -interface NodeIterator { - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - detach(): void; - nextNode(): Node; - previousNode(): Node; -} - -declare var NodeIterator: { - prototype: NodeIterator; - new(): NodeIterator; -} - -interface NodeList { - readonly length: number; - item(index: number): Node; - [index: number]: Node; -} - -declare var NodeList: { - prototype: NodeList; - new(): NodeList; -} - -interface OES_element_index_uint { -} - -declare var OES_element_index_uint: { - prototype: OES_element_index_uint; - new(): OES_element_index_uint; -} - -interface OES_standard_derivatives { - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -declare var OES_standard_derivatives: { - prototype: OES_standard_derivatives; - new(): OES_standard_derivatives; - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -interface OES_texture_float { -} - -declare var OES_texture_float: { - prototype: OES_texture_float; - new(): OES_texture_float; -} - -interface OES_texture_float_linear { -} - -declare var OES_texture_float_linear: { - prototype: OES_texture_float_linear; - new(): OES_texture_float_linear; -} - -interface OfflineAudioCompletionEvent extends Event { - readonly renderedBuffer: AudioBuffer; -} - -declare var OfflineAudioCompletionEvent: { - prototype: OfflineAudioCompletionEvent; - new(): OfflineAudioCompletionEvent; -} - -interface OfflineAudioContext extends AudioContext { - oncomplete: (this: this, ev: Event) => any; - startRendering(): PromiseLike; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OfflineAudioContext: { - prototype: OfflineAudioContext; - new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} - -interface OscillatorNode extends AudioNode { - readonly detune: AudioParam; - readonly frequency: AudioParam; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - type: string; - setPeriodicWave(periodicWave: PeriodicWave): void; - start(when?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OscillatorNode: { - prototype: OscillatorNode; - new(): OscillatorNode; -} - -interface OverflowEvent extends UIEvent { - readonly horizontalOverflow: boolean; - readonly orient: number; - readonly verticalOverflow: boolean; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -declare var OverflowEvent: { - prototype: OverflowEvent; - new(): OverflowEvent; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -interface PageTransitionEvent extends Event { - readonly persisted: boolean; -} - -declare var PageTransitionEvent: { - prototype: PageTransitionEvent; - new(): PageTransitionEvent; -} - -interface PannerNode extends AudioNode { - coneInnerAngle: number; - coneOuterAngle: number; - coneOuterGain: number; - distanceModel: string; - maxDistance: number; - panningModel: string; - refDistance: number; - rolloffFactor: number; - setOrientation(x: number, y: number, z: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var PannerNode: { - prototype: PannerNode; - new(): PannerNode; -} - -interface PerfWidgetExternal { - readonly activeNetworkRequestCount: number; - readonly averageFrameTime: number; - readonly averagePaintTime: number; - readonly extraInformationEnabled: boolean; - readonly independentRenderingEnabled: boolean; - readonly irDisablingContentString: string; - readonly irStatusAvailable: boolean; - readonly maxCpuSpeed: number; - readonly paintRequestsPerSecond: number; - readonly performanceCounter: number; - readonly performanceCounterFrequency: number; - addEventListener(eventType: string, callback: Function): void; - getMemoryUsage(): number; - getProcessCpuUsage(): number; - getRecentCpuUsage(last: number | null): any; - getRecentFrames(last: number | null): any; - getRecentMemoryUsage(last: number | null): any; - getRecentPaintRequests(last: number | null): any; - removeEventListener(eventType: string, callback: Function): void; - repositionWindow(x: number, y: number): void; - resizeWindow(width: number, height: number): void; -} - -declare var PerfWidgetExternal: { - prototype: PerfWidgetExternal; - new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: string; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} - -interface PeriodicWave { -} - -declare var PeriodicWave: { - prototype: PeriodicWave; - new(): PeriodicWave; -} - -interface PermissionRequest extends DeferredPermissionRequest { - readonly state: string; - defer(): void; -} - -declare var PermissionRequest: { - prototype: PermissionRequest; - new(): PermissionRequest; -} - -interface PermissionRequestedEvent extends Event { - readonly permissionRequest: PermissionRequest; -} - -declare var PermissionRequestedEvent: { - prototype: PermissionRequestedEvent; - new(): PermissionRequestedEvent; -} - -interface Plugin { - readonly description: string; - readonly filename: string; - readonly length: number; - readonly name: string; - readonly version: string; - item(index: number): MimeType; - namedItem(type: string): MimeType; - [index: number]: MimeType; -} - -declare var Plugin: { - prototype: Plugin; - new(): Plugin; -} - -interface PluginArray { - readonly length: number; - item(index: number): Plugin; - namedItem(name: string): Plugin; - refresh(reload?: boolean): void; - [index: number]: Plugin; -} - -declare var PluginArray: { - prototype: PluginArray; - new(): PluginArray; -} - -interface PointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var PointerEvent: { - prototype: PointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} - -interface PopStateEvent extends Event { - readonly state: any; - initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; -} - -declare var PopStateEvent: { - prototype: PopStateEvent; - new(): PopStateEvent; -} - -interface Position { - readonly coords: Coordinates; - readonly timestamp: number; -} - -declare var Position: { - prototype: Position; - new(): Position; -} - -interface PositionError { - readonly code: number; - readonly message: string; - toString(): string; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -declare var PositionError: { - prototype: PositionError; - new(): PositionError; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -interface ProcessingInstruction extends CharacterData { - readonly target: string; -} - -declare var ProcessingInstruction: { - prototype: ProcessingInstruction; - new(): ProcessingInstruction; -} - -interface ProgressEvent extends Event { - readonly lengthComputable: boolean; - readonly loaded: number; - readonly total: number; - initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; -} - -declare var ProgressEvent: { - prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} - -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; -} - -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; -} - -interface RTCDtlsTransport extends RTCStatsProvider { - ondtlsstatechange: ((this: this, ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly state: string; - readonly transport: RTCIceTransport; - getLocalParameters(): RTCDtlsParameters; - getRemoteCertificates(): ArrayBuffer[]; - getRemoteParameters(): RTCDtlsParameters | null; - start(remoteParameters: RTCDtlsParameters): void; - stop(): void; - addEventListener(type: "dtlsstatechange", listener: (this: this, ev: RTCDtlsTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtlsTransport: { - prototype: RTCDtlsTransport; - new(transport: RTCIceTransport): RTCDtlsTransport; -} - -interface RTCDtlsTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCDtlsTransportStateChangedEvent: { - prototype: RTCDtlsTransportStateChangedEvent; - new(): RTCDtlsTransportStateChangedEvent; -} - -interface RTCDtmfSender extends EventTarget { - readonly canInsertDTMF: boolean; - readonly duration: number; - readonly interToneGap: number; - ontonechange: (this: this, ev: RTCDTMFToneChangeEvent) => any; - readonly sender: RTCRtpSender; - readonly toneBuffer: string; - insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: "tonechange", listener: (this: this, ev: RTCDTMFToneChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtmfSender: { - prototype: RTCDtmfSender; - new(sender: RTCRtpSender): RTCDtmfSender; -} - -interface RTCIceCandidatePairChangedEvent extends Event { - readonly pair: RTCIceCandidatePair; -} - -declare var RTCIceCandidatePairChangedEvent: { - prototype: RTCIceCandidatePairChangedEvent; - new(): RTCIceCandidatePairChangedEvent; -} - -interface RTCIceGatherer extends RTCStatsProvider { - readonly component: string; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onlocalcandidate: ((this: this, ev: RTCIceGathererEvent) => any) | null; - createAssociatedGatherer(): RTCIceGatherer; - getLocalCandidates(): RTCIceCandidate[]; - getLocalParameters(): RTCIceParameters; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "localcandidate", listener: (this: this, ev: RTCIceGathererEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceGatherer: { - prototype: RTCIceGatherer; - new(options: RTCIceGatherOptions): RTCIceGatherer; -} - -interface RTCIceGathererEvent extends Event { - readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; -} - -declare var RTCIceGathererEvent: { - prototype: RTCIceGathererEvent; - new(): RTCIceGathererEvent; -} - -interface RTCIceTransport extends RTCStatsProvider { - readonly component: string; - readonly iceGatherer: RTCIceGatherer | null; - oncandidatepairchange: ((this: this, ev: RTCIceCandidatePairChangedEvent) => any) | null; - onicestatechange: ((this: this, ev: RTCIceTransportStateChangedEvent) => any) | null; - readonly role: string; - readonly state: string; - addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; - createAssociatedTransport(): RTCIceTransport; - getNominatedCandidatePair(): RTCIceCandidatePair | null; - getRemoteCandidates(): RTCIceCandidate[]; - getRemoteParameters(): RTCIceParameters | null; - setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; - start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; - stop(): void; - addEventListener(type: "candidatepairchange", listener: (this: this, ev: RTCIceCandidatePairChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "icestatechange", listener: (this: this, ev: RTCIceTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceTransport: { - prototype: RTCIceTransport; - new(): RTCIceTransport; -} - -interface RTCIceTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCIceTransportStateChangedEvent: { - prototype: RTCIceTransportStateChangedEvent; - new(): RTCIceTransportStateChangedEvent; -} - -interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack | null; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - getContributingSources(): RTCRtpContributingSource[]; - receive(parameters: RTCRtpParameters): void; - requestSendCSRC(csrc: number): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpReceiver: { - prototype: RTCRtpReceiver; - new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCRtpSender extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onssrcconflict: ((this: this, ev: RTCSsrcConflictEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - send(parameters: RTCRtpParameters): void; - setTrack(track: MediaStreamTrack): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ssrcconflict", listener: (this: this, ev: RTCSsrcConflictEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpSender: { - prototype: RTCRtpSender; - new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly transport: RTCIceTransport; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCSrtpSdesTransport: { - prototype: RTCSrtpSdesTransport; - new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; - getLocalParameters(): RTCSrtpSdesParameters[]; -} - -interface RTCSsrcConflictEvent extends Event { - readonly ssrc: number; -} - -declare var RTCSsrcConflictEvent: { - prototype: RTCSsrcConflictEvent; - new(): RTCSsrcConflictEvent; -} - -interface RTCStatsProvider extends EventTarget { - getStats(): PromiseLike; - msGetStats(): PromiseLike; -} - -declare var RTCStatsProvider: { - prototype: RTCStatsProvider; - new(): RTCStatsProvider; -} - -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: string): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; - toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly target: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGAElement: { - prototype: SVGAElement; - new(): SVGAElement; -} - -interface SVGAngle { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -declare var SVGAngle: { - prototype: SVGAngle; - new(): SVGAngle; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -interface SVGAnimatedAngle { - readonly animVal: SVGAngle; - readonly baseVal: SVGAngle; -} - -declare var SVGAnimatedAngle: { - prototype: SVGAnimatedAngle; - new(): SVGAnimatedAngle; -} - -interface SVGAnimatedBoolean { - readonly animVal: boolean; - baseVal: boolean; -} - -declare var SVGAnimatedBoolean: { - prototype: SVGAnimatedBoolean; - new(): SVGAnimatedBoolean; -} - -interface SVGAnimatedEnumeration { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedEnumeration: { - prototype: SVGAnimatedEnumeration; - new(): SVGAnimatedEnumeration; -} - -interface SVGAnimatedInteger { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedInteger: { - prototype: SVGAnimatedInteger; - new(): SVGAnimatedInteger; -} - -interface SVGAnimatedLength { - readonly animVal: SVGLength; - readonly baseVal: SVGLength; -} - -declare var SVGAnimatedLength: { - prototype: SVGAnimatedLength; - new(): SVGAnimatedLength; -} - -interface SVGAnimatedLengthList { - readonly animVal: SVGLengthList; - readonly baseVal: SVGLengthList; -} - -declare var SVGAnimatedLengthList: { - prototype: SVGAnimatedLengthList; - new(): SVGAnimatedLengthList; -} - -interface SVGAnimatedNumber { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedNumber: { - prototype: SVGAnimatedNumber; - new(): SVGAnimatedNumber; -} - -interface SVGAnimatedNumberList { - readonly animVal: SVGNumberList; - readonly baseVal: SVGNumberList; -} - -declare var SVGAnimatedNumberList: { - prototype: SVGAnimatedNumberList; - new(): SVGAnimatedNumberList; -} - -interface SVGAnimatedPreserveAspectRatio { - readonly animVal: SVGPreserveAspectRatio; - readonly baseVal: SVGPreserveAspectRatio; -} - -declare var SVGAnimatedPreserveAspectRatio: { - prototype: SVGAnimatedPreserveAspectRatio; - new(): SVGAnimatedPreserveAspectRatio; -} - -interface SVGAnimatedRect { - readonly animVal: SVGRect; - readonly baseVal: SVGRect; -} - -declare var SVGAnimatedRect: { - prototype: SVGAnimatedRect; - new(): SVGAnimatedRect; -} - -interface SVGAnimatedString { - readonly animVal: string; - baseVal: string; -} - -declare var SVGAnimatedString: { - prototype: SVGAnimatedString; - new(): SVGAnimatedString; -} - -interface SVGAnimatedTransformList { - readonly animVal: SVGTransformList; - readonly baseVal: SVGTransformList; -} - -declare var SVGAnimatedTransformList: { - prototype: SVGAnimatedTransformList; - new(): SVGAnimatedTransformList; -} - -interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGCircleElement: { - prototype: SVGCircleElement; - new(): SVGCircleElement; -} - -interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGClipPathElement: { - prototype: SVGClipPathElement; - new(): SVGClipPathElement; -} - -interface SVGComponentTransferFunctionElement extends SVGElement { - readonly amplitude: SVGAnimatedNumber; - readonly exponent: SVGAnimatedNumber; - readonly intercept: SVGAnimatedNumber; - readonly offset: SVGAnimatedNumber; - readonly slope: SVGAnimatedNumber; - readonly tableValues: SVGAnimatedNumberList; - readonly type: SVGAnimatedEnumeration; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -declare var SVGComponentTransferFunctionElement: { - prototype: SVGComponentTransferFunctionElement; - new(): SVGComponentTransferFunctionElement; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDefsElement: { - prototype: SVGDefsElement; - new(): SVGDefsElement; -} - -interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDescElement: { - prototype: SVGDescElement; - new(): SVGDescElement; -} - -interface SVGElement extends Element { - onclick: (this: this, ev: MouseEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - onfocusin: (this: this, ev: FocusEvent) => any; - onfocusout: (this: this, ev: FocusEvent) => any; - onload: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - readonly ownerSVGElement: SVGSVGElement; - readonly viewportElement: SVGElement; - xmlbase: string; - className: any; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGElement: { - prototype: SVGElement; - new(): SVGElement; -} - -interface SVGElementInstance extends EventTarget { - readonly childNodes: SVGElementInstanceList; - readonly correspondingElement: SVGElement; - readonly correspondingUseElement: SVGUseElement; - readonly firstChild: SVGElementInstance; - readonly lastChild: SVGElementInstance; - readonly nextSibling: SVGElementInstance; - readonly parentNode: SVGElementInstance; - readonly previousSibling: SVGElementInstance; -} - -declare var SVGElementInstance: { - prototype: SVGElementInstance; - new(): SVGElementInstance; -} - -interface SVGElementInstanceList { - readonly length: number; - item(index: number): SVGElementInstance; -} - -declare var SVGElementInstanceList: { - prototype: SVGElementInstanceList; - new(): SVGElementInstanceList; -} - -interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGEllipseElement: { - prototype: SVGEllipseElement; - new(): SVGEllipseElement; -} - -interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly mode: SVGAnimatedEnumeration; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEBlendElement: { - prototype: SVGFEBlendElement; - new(): SVGFEBlendElement; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} - -interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly type: SVGAnimatedEnumeration; - readonly values: SVGAnimatedNumberList; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEColorMatrixElement: { - prototype: SVGFEColorMatrixElement; - new(): SVGFEColorMatrixElement; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} - -interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEComponentTransferElement: { - prototype: SVGFEComponentTransferElement; - new(): SVGFEComponentTransferElement; -} - -interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly k1: SVGAnimatedNumber; - readonly k2: SVGAnimatedNumber; - readonly k3: SVGAnimatedNumber; - readonly k4: SVGAnimatedNumber; - readonly operator: SVGAnimatedEnumeration; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFECompositeElement: { - prototype: SVGFECompositeElement; - new(): SVGFECompositeElement; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} - -interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly bias: SVGAnimatedNumber; - readonly divisor: SVGAnimatedNumber; - readonly edgeMode: SVGAnimatedEnumeration; - readonly in1: SVGAnimatedString; - readonly kernelMatrix: SVGAnimatedNumberList; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly orderX: SVGAnimatedInteger; - readonly orderY: SVGAnimatedInteger; - readonly preserveAlpha: SVGAnimatedBoolean; - readonly targetX: SVGAnimatedInteger; - readonly targetY: SVGAnimatedInteger; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEConvolveMatrixElement: { - prototype: SVGFEConvolveMatrixElement; - new(): SVGFEConvolveMatrixElement; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; -} - -interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly diffuseConstant: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDiffuseLightingElement: { - prototype: SVGFEDiffuseLightingElement; - new(): SVGFEDiffuseLightingElement; -} - -interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly scale: SVGAnimatedNumber; - readonly xChannelSelector: SVGAnimatedEnumeration; - readonly yChannelSelector: SVGAnimatedEnumeration; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDisplacementMapElement: { - prototype: SVGFEDisplacementMapElement; - new(): SVGFEDisplacementMapElement; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; -} - -interface SVGFEDistantLightElement extends SVGElement { - readonly azimuth: SVGAnimatedNumber; - readonly elevation: SVGAnimatedNumber; -} - -declare var SVGFEDistantLightElement: { - prototype: SVGFEDistantLightElement; - new(): SVGFEDistantLightElement; -} - -interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEFloodElement: { - prototype: SVGFEFloodElement; - new(): SVGFEFloodElement; -} - -interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncAElement: { - prototype: SVGFEFuncAElement; - new(): SVGFEFuncAElement; -} - -interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncBElement: { - prototype: SVGFEFuncBElement; - new(): SVGFEFuncBElement; -} - -interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncGElement: { - prototype: SVGFEFuncGElement; - new(): SVGFEFuncGElement; -} - -interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncRElement: { - prototype: SVGFEFuncRElement; - new(): SVGFEFuncRElement; -} - -interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly stdDeviationX: SVGAnimatedNumber; - readonly stdDeviationY: SVGAnimatedNumber; - setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEGaussianBlurElement: { - prototype: SVGFEGaussianBlurElement; - new(): SVGFEGaussianBlurElement; -} - -interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEImageElement: { - prototype: SVGFEImageElement; - new(): SVGFEImageElement; -} - -interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMergeElement: { - prototype: SVGFEMergeElement; - new(): SVGFEMergeElement; -} - -interface SVGFEMergeNodeElement extends SVGElement { - readonly in1: SVGAnimatedString; -} - -declare var SVGFEMergeNodeElement: { - prototype: SVGFEMergeNodeElement; - new(): SVGFEMergeNodeElement; -} - -interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly operator: SVGAnimatedEnumeration; - readonly radiusX: SVGAnimatedNumber; - readonly radiusY: SVGAnimatedNumber; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMorphologyElement: { - prototype: SVGFEMorphologyElement; - new(): SVGFEMorphologyElement; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} - -interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly dx: SVGAnimatedNumber; - readonly dy: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEOffsetElement: { - prototype: SVGFEOffsetElement; - new(): SVGFEOffsetElement; -} - -interface SVGFEPointLightElement extends SVGElement { - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFEPointLightElement: { - prototype: SVGFEPointLightElement; - new(): SVGFEPointLightElement; -} - -interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly specularConstant: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFESpecularLightingElement: { - prototype: SVGFESpecularLightingElement; - new(): SVGFESpecularLightingElement; -} - -interface SVGFESpotLightElement extends SVGElement { - readonly limitingConeAngle: SVGAnimatedNumber; - readonly pointsAtX: SVGAnimatedNumber; - readonly pointsAtY: SVGAnimatedNumber; - readonly pointsAtZ: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFESpotLightElement: { - prototype: SVGFESpotLightElement; - new(): SVGFESpotLightElement; -} - -interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETileElement: { - prototype: SVGFETileElement; - new(): SVGFETileElement; -} - -interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly baseFrequencyX: SVGAnimatedNumber; - readonly baseFrequencyY: SVGAnimatedNumber; - readonly numOctaves: SVGAnimatedInteger; - readonly seed: SVGAnimatedNumber; - readonly stitchTiles: SVGAnimatedEnumeration; - readonly type: SVGAnimatedEnumeration; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETurbulenceElement: { - prototype: SVGFETurbulenceElement; - new(): SVGFETurbulenceElement; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} - -interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly filterResX: SVGAnimatedInteger; - readonly filterResY: SVGAnimatedInteger; - readonly filterUnits: SVGAnimatedEnumeration; - readonly height: SVGAnimatedLength; - readonly primitiveUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFilterElement: { - prototype: SVGFilterElement; - new(): SVGFilterElement; -} - -interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGForeignObjectElement: { - prototype: SVGForeignObjectElement; - new(): SVGForeignObjectElement; -} - -interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGElement: { - prototype: SVGGElement; - new(): SVGGElement; -} - -interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { - readonly gradientTransform: SVGAnimatedTransformList; - readonly gradientUnits: SVGAnimatedEnumeration; - readonly spreadMethod: SVGAnimatedEnumeration; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGradientElement: { - prototype: SVGGradientElement; - new(): SVGGradientElement; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; -} - -interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly height: SVGAnimatedLength; - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGImageElement: { - prototype: SVGImageElement; - new(): SVGImageElement; -} - -interface SVGLength { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -declare var SVGLength: { - prototype: SVGLength; - new(): SVGLength; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -interface SVGLengthList { - readonly numberOfItems: number; - appendItem(newItem: SVGLength): SVGLength; - clear(): void; - getItem(index: number): SVGLength; - initialize(newItem: SVGLength): SVGLength; - insertItemBefore(newItem: SVGLength, index: number): SVGLength; - removeItem(index: number): SVGLength; - replaceItem(newItem: SVGLength, index: number): SVGLength; -} - -declare var SVGLengthList: { - prototype: SVGLengthList; - new(): SVGLengthList; -} - -interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} - -interface SVGLinearGradientElement extends SVGGradientElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; -} - -declare var SVGLinearGradientElement: { - prototype: SVGLinearGradientElement; - new(): SVGLinearGradientElement; -} - -interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - readonly markerHeight: SVGAnimatedLength; - readonly markerUnits: SVGAnimatedEnumeration; - readonly markerWidth: SVGAnimatedLength; - readonly orientAngle: SVGAnimatedAngle; - readonly orientType: SVGAnimatedEnumeration; - readonly refX: SVGAnimatedLength; - readonly refY: SVGAnimatedLength; - setOrientToAngle(angle: SVGAngle): void; - setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMarkerElement: { - prototype: SVGMarkerElement; - new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} - -interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly maskContentUnits: SVGAnimatedEnumeration; - readonly maskUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMaskElement: { - prototype: SVGMaskElement; - new(): SVGMaskElement; -} - -interface SVGMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - flipX(): SVGMatrix; - flipY(): SVGMatrix; - inverse(): SVGMatrix; - multiply(secondMatrix: SVGMatrix): SVGMatrix; - rotate(angle: number): SVGMatrix; - rotateFromVector(x: number, y: number): SVGMatrix; - scale(scaleFactor: number): SVGMatrix; - scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; - skewX(angle: number): SVGMatrix; - skewY(angle: number): SVGMatrix; - translate(x: number, y: number): SVGMatrix; -} - -declare var SVGMatrix: { - prototype: SVGMatrix; - new(): SVGMatrix; -} - -interface SVGMetadataElement extends SVGElement { -} - -declare var SVGMetadataElement: { - prototype: SVGMetadataElement; - new(): SVGMetadataElement; -} - -interface SVGNumber { - value: number; -} - -declare var SVGNumber: { - prototype: SVGNumber; - new(): SVGNumber; -} - -interface SVGNumberList { - readonly numberOfItems: number; - appendItem(newItem: SVGNumber): SVGNumber; - clear(): void; - getItem(index: number): SVGNumber; - initialize(newItem: SVGNumber): SVGNumber; - insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; - removeItem(index: number): SVGNumber; - replaceItem(newItem: SVGNumber, index: number): SVGNumber; -} - -declare var SVGNumberList: { - prototype: SVGNumberList; - new(): SVGNumberList; -} - -interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; - createSVGPathSegClosePath(): SVGPathSegClosePath; - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - getPathSegAtLength(distance: number): number; - getPointAtLength(distance: number): SVGPoint; - getTotalLength(): number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPathElement: { - prototype: SVGPathElement; - new(): SVGPathElement; -} - -interface SVGPathSeg { - readonly pathSegType: number; - readonly pathSegTypeAsLetter: string; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -declare var SVGPathSeg: { - prototype: SVGPathSeg; - new(): SVGPathSeg; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -interface SVGPathSegArcAbs extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcAbs: { - prototype: SVGPathSegArcAbs; - new(): SVGPathSegArcAbs; -} - -interface SVGPathSegArcRel extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcRel: { - prototype: SVGPathSegArcRel; - new(): SVGPathSegArcRel; -} - -interface SVGPathSegClosePath extends SVGPathSeg { -} - -declare var SVGPathSegClosePath: { - prototype: SVGPathSegClosePath; - new(): SVGPathSegClosePath; -} - -interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicAbs: { - prototype: SVGPathSegCurvetoCubicAbs; - new(): SVGPathSegCurvetoCubicAbs; -} - -interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicRel: { - prototype: SVGPathSegCurvetoCubicRel; - new(): SVGPathSegCurvetoCubicRel; -} - -interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothAbs: { - prototype: SVGPathSegCurvetoCubicSmoothAbs; - new(): SVGPathSegCurvetoCubicSmoothAbs; -} - -interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothRel: { - prototype: SVGPathSegCurvetoCubicSmoothRel; - new(): SVGPathSegCurvetoCubicSmoothRel; -} - -interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticAbs: { - prototype: SVGPathSegCurvetoQuadraticAbs; - new(): SVGPathSegCurvetoQuadraticAbs; -} - -interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticRel: { - prototype: SVGPathSegCurvetoQuadraticRel; - new(): SVGPathSegCurvetoQuadraticRel; -} - -interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothAbs: { - prototype: SVGPathSegCurvetoQuadraticSmoothAbs; - new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} - -interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothRel: { - prototype: SVGPathSegCurvetoQuadraticSmoothRel; - new(): SVGPathSegCurvetoQuadraticSmoothRel; -} - -interface SVGPathSegLinetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoAbs: { - prototype: SVGPathSegLinetoAbs; - new(): SVGPathSegLinetoAbs; -} - -interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalAbs: { - prototype: SVGPathSegLinetoHorizontalAbs; - new(): SVGPathSegLinetoHorizontalAbs; -} - -interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalRel: { - prototype: SVGPathSegLinetoHorizontalRel; - new(): SVGPathSegLinetoHorizontalRel; -} - -interface SVGPathSegLinetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoRel: { - prototype: SVGPathSegLinetoRel; - new(): SVGPathSegLinetoRel; -} - -interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalAbs: { - prototype: SVGPathSegLinetoVerticalAbs; - new(): SVGPathSegLinetoVerticalAbs; -} - -interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalRel: { - prototype: SVGPathSegLinetoVerticalRel; - new(): SVGPathSegLinetoVerticalRel; -} - -interface SVGPathSegList { - readonly numberOfItems: number; - appendItem(newItem: SVGPathSeg): SVGPathSeg; - clear(): void; - getItem(index: number): SVGPathSeg; - initialize(newItem: SVGPathSeg): SVGPathSeg; - insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; - removeItem(index: number): SVGPathSeg; - replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; -} - -declare var SVGPathSegList: { - prototype: SVGPathSegList; - new(): SVGPathSegList; -} - -interface SVGPathSegMovetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoAbs: { - prototype: SVGPathSegMovetoAbs; - new(): SVGPathSegMovetoAbs; -} - -interface SVGPathSegMovetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoRel: { - prototype: SVGPathSegMovetoRel; - new(): SVGPathSegMovetoRel; -} - -interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly patternContentUnits: SVGAnimatedEnumeration; - readonly patternTransform: SVGAnimatedTransformList; - readonly patternUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPatternElement: { - prototype: SVGPatternElement; - new(): SVGPatternElement; -} - -interface SVGPoint { - x: number; - y: number; - matrixTransform(matrix: SVGMatrix): SVGPoint; -} - -declare var SVGPoint: { - prototype: SVGPoint; - new(): SVGPoint; -} - -interface SVGPointList { - readonly numberOfItems: number; - appendItem(newItem: SVGPoint): SVGPoint; - clear(): void; - getItem(index: number): SVGPoint; - initialize(newItem: SVGPoint): SVGPoint; - insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; - removeItem(index: number): SVGPoint; - replaceItem(newItem: SVGPoint, index: number): SVGPoint; -} - -declare var SVGPointList: { - prototype: SVGPointList; - new(): SVGPointList; -} - -interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolygonElement: { - prototype: SVGPolygonElement; - new(): SVGPolygonElement; -} - -interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolylineElement: { - prototype: SVGPolylineElement; - new(): SVGPolylineElement; -} - -interface SVGPreserveAspectRatio { - align: number; - meetOrSlice: number; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -declare var SVGPreserveAspectRatio: { - prototype: SVGPreserveAspectRatio; - new(): SVGPreserveAspectRatio; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -interface SVGRadialGradientElement extends SVGGradientElement { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly fx: SVGAnimatedLength; - readonly fy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; -} - -declare var SVGRadialGradientElement: { - prototype: SVGRadialGradientElement; - new(): SVGRadialGradientElement; -} - -interface SVGRect { - height: number; - width: number; - x: number; - y: number; -} - -declare var SVGRect: { - prototype: SVGRect; - new(): SVGRect; -} - -interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGRectElement: { - prototype: SVGRectElement; - new(): SVGRectElement; -} - -interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - contentScriptType: string; - contentStyleType: string; - currentScale: number; - readonly currentTranslate: SVGPoint; - readonly height: SVGAnimatedLength; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onunload: (this: this, ev: Event) => any; - onzoom: (this: this, ev: SVGZoomEvent) => any; - readonly pixelUnitToMillimeterX: number; - readonly pixelUnitToMillimeterY: number; - readonly screenPixelToMillimeterX: number; - readonly screenPixelToMillimeterY: number; - readonly viewport: SVGRect; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - checkEnclosure(element: SVGElement, rect: SVGRect): boolean; - checkIntersection(element: SVGElement, rect: SVGRect): boolean; - createSVGAngle(): SVGAngle; - createSVGLength(): SVGLength; - createSVGMatrix(): SVGMatrix; - createSVGNumber(): SVGNumber; - createSVGPoint(): SVGPoint; - createSVGRect(): SVGRect; - createSVGTransform(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - deselectAll(): void; - forceRedraw(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getCurrentTime(): number; - getElementById(elementId: string): Element; - getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - pauseAnimations(): void; - setCurrentTime(seconds: number): void; - suspendRedraw(maxWaitMilliseconds: number): number; - unpauseAnimations(): void; - unsuspendRedraw(suspendHandleID: number): void; - unsuspendRedrawAll(): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "SVGAbort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGError", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGUnload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGZoom", listener: (this: this, ev: SVGZoomEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSVGElement: { - prototype: SVGSVGElement; - new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement, SVGStylable { - readonly offset: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement, SVGLangSpace { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} - -interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSwitchElement: { - prototype: SVGSwitchElement; - new(): SVGSwitchElement; -} - -interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSymbolElement: { - prototype: SVGSymbolElement; - new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} - -interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly lengthAdjust: SVGAnimatedEnumeration; - readonly textLength: SVGAnimatedLength; - getCharNumAtPosition(point: SVGPoint): number; - getComputedTextLength(): number; - getEndPositionOfChar(charnum: number): SVGPoint; - getExtentOfChar(charnum: number): SVGRect; - getNumberOfChars(): number; - getRotationOfChar(charnum: number): number; - getStartPositionOfChar(charnum: number): SVGPoint; - getSubStringLength(charnum: number, nchars: number): number; - selectSubString(charnum: number, nchars: number): void; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextContentElement: { - prototype: SVGTextContentElement; - new(): SVGTextContentElement; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; -} - -interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextElement: { - prototype: SVGTextElement; - new(): SVGTextElement; -} - -interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { - readonly method: SVGAnimatedEnumeration; - readonly spacing: SVGAnimatedEnumeration; - readonly startOffset: SVGAnimatedLength; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextPathElement: { - prototype: SVGTextPathElement; - new(): SVGTextPathElement; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} - -interface SVGTextPositioningElement extends SVGTextContentElement { - readonly dx: SVGAnimatedLengthList; - readonly dy: SVGAnimatedLengthList; - readonly rotate: SVGAnimatedNumberList; - readonly x: SVGAnimatedLengthList; - readonly y: SVGAnimatedLengthList; -} - -declare var SVGTextPositioningElement: { - prototype: SVGTextPositioningElement; - new(): SVGTextPositioningElement; -} - -interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTitleElement: { - prototype: SVGTitleElement; - new(): SVGTitleElement; -} - -interface SVGTransform { - readonly angle: number; - readonly matrix: SVGMatrix; - readonly type: number; - setMatrix(matrix: SVGMatrix): void; - setRotate(angle: number, cx: number, cy: number): void; - setScale(sx: number, sy: number): void; - setSkewX(angle: number): void; - setSkewY(angle: number): void; - setTranslate(tx: number, ty: number): void; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -declare var SVGTransform: { - prototype: SVGTransform; - new(): SVGTransform; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -interface SVGTransformList { - readonly numberOfItems: number; - appendItem(newItem: SVGTransform): SVGTransform; - clear(): void; - consolidate(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - getItem(index: number): SVGTransform; - initialize(newItem: SVGTransform): SVGTransform; - insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; - removeItem(index: number): SVGTransform; - replaceItem(newItem: SVGTransform, index: number): SVGTransform; -} - -declare var SVGTransformList: { - prototype: SVGTransformList; - new(): SVGTransformList; -} - -interface SVGUnitTypes { - readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; - readonly SVG_UNIT_TYPE_UNKNOWN: number; - readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; -} -declare var SVGUnitTypes: SVGUnitTypes; - -interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; - readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGUseElement: { - prototype: SVGUseElement; - new(): SVGUseElement; -} - -interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - readonly viewTarget: SVGStringList; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGViewElement: { - prototype: SVGViewElement; - new(): SVGViewElement; -} - -interface SVGZoomAndPan { - readonly zoomAndPan: number; -} - -declare var SVGZoomAndPan: { - readonly SVG_ZOOMANDPAN_DISABLE: number; - readonly SVG_ZOOMANDPAN_MAGNIFY: number; - readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} - -interface SVGZoomEvent extends UIEvent { - readonly newScale: number; - readonly newTranslate: SVGPoint; - readonly previousScale: number; - readonly previousTranslate: SVGPoint; - readonly zoomRectScreen: SVGRect; -} - -declare var SVGZoomEvent: { - prototype: SVGZoomEvent; - new(): SVGZoomEvent; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: this, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: "MSOrientationChange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: this, ev: AudioProcessingEvent) => any; - addEventListener(type: "audioprocess", listener: (this: this, ev: AudioProcessingEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: string; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - 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: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} - -interface Text extends CharacterData { - readonly wholeText: string; - splitText(offset: number): Text; -} - -declare var Text: { - prototype: Text; - new(): Text; -} - -interface TextEvent extends UIEvent { - readonly data: string; - readonly inputMethod: number; - readonly locale: string; - initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -declare var TextEvent: { - prototype: TextEvent; - new(): TextEvent; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -interface TextMetrics { - readonly width: number; -} - -declare var TextMetrics: { - prototype: TextMetrics; - new(): TextMetrics; -} - -interface TextTrack extends EventTarget { - readonly activeCues: TextTrackCueList; - readonly cues: TextTrackCueList; - readonly inBandMetadataTrackDispatchType: string; - readonly kind: string; - readonly label: string; - readonly language: string; - mode: any; - oncuechange: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - readonly readyState: number; - addCue(cue: TextTrackCue): void; - removeCue(cue: TextTrackCue): void; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrack: { - prototype: TextTrack; - new(): TextTrack; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; -} - -interface TextTrackCue extends EventTarget { - endTime: number; - id: string; - onenter: (this: this, ev: Event) => any; - onexit: (this: this, ev: Event) => any; - pauseOnExit: boolean; - startTime: number; - text: string; - readonly track: TextTrack; - getCueAsHTML(): DocumentFragment; - addEventListener(type: "enter", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "exit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrackCue: { - prototype: TextTrackCue; - new(startTime: number, endTime: number, text: string): TextTrackCue; -} - -interface TextTrackCueList { - readonly length: number; - getCueById(id: string): TextTrackCue; - item(index: number): TextTrackCue; - [index: number]: TextTrackCue; -} - -declare var TextTrackCueList: { - prototype: TextTrackCueList; - new(): TextTrackCueList; -} - -interface TextTrackList extends EventTarget { - readonly length: number; - onaddtrack: ((this: this, ev: TrackEvent) => any) | null; - item(index: number): TextTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: TextTrack; -} - -declare var TextTrackList: { - prototype: TextTrackList; - new(): TextTrackList; -} - -interface TimeRanges { - readonly length: number; - end(index: number): number; - start(index: number): number; -} - -declare var TimeRanges: { - prototype: TimeRanges; - new(): TimeRanges; -} - -interface Touch { - readonly clientX: number; - readonly clientY: number; - readonly identifier: number; - readonly pageX: number; - readonly pageY: number; - readonly screenX: number; - readonly screenY: number; - readonly target: EventTarget; -} - -declare var Touch: { - prototype: Touch; - new(): Touch; -} - -interface TouchEvent extends UIEvent { - readonly altKey: boolean; - readonly changedTouches: TouchList; - readonly ctrlKey: boolean; - readonly metaKey: boolean; - readonly shiftKey: boolean; - readonly targetTouches: TouchList; - readonly touches: TouchList; -} - -declare var TouchEvent: { - prototype: TouchEvent; - new(): TouchEvent; -} - -interface TouchList { - readonly length: number; - item(index: number): Touch | null; - [index: number]: Touch; -} - -declare var TouchList: { - prototype: TouchList; - new(): TouchList; -} - -interface TrackEvent extends Event { - readonly track: any; -} - -declare var TrackEvent: { - prototype: TrackEvent; - new(): TrackEvent; -} - -interface TransitionEvent extends Event { - readonly elapsedTime: number; - readonly propertyName: string; - initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; -} - -declare var TransitionEvent: { - prototype: TransitionEvent; - new(): TransitionEvent; -} - -interface TreeWalker { - currentNode: Node; - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; -} - -declare var TreeWalker: { - prototype: TreeWalker; - new(): TreeWalker; -} - -interface UIEvent extends Event { - readonly detail: number; - readonly view: Window; - initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; -} - -declare var UIEvent: { - prototype: UIEvent; - new(type: string, eventInitDict?: UIEventInit): UIEvent; -} - -interface URL { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - username: string; - toString(): string; -} - -declare var URL: { - prototype: URL; - new(url: string, base?: string): URL; - createObjectURL(object: any, options?: ObjectURLOptions): string; - revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} - -interface ValidityState { - readonly badInput: boolean; - readonly customError: boolean; - readonly patternMismatch: boolean; - readonly rangeOverflow: boolean; - readonly rangeUnderflow: boolean; - readonly stepMismatch: boolean; - readonly tooLong: boolean; - readonly typeMismatch: boolean; - readonly valid: boolean; - readonly valueMissing: boolean; -} - -declare var ValidityState: { - prototype: ValidityState; - new(): ValidityState; -} - -interface VideoPlaybackQuality { - readonly corruptedVideoFrames: number; - readonly creationTime: number; - readonly droppedVideoFrames: number; - readonly totalFrameDelay: number; - readonly totalVideoFrames: number; -} - -declare var VideoPlaybackQuality: { - prototype: VideoPlaybackQuality; - new(): VideoPlaybackQuality; -} - -interface VideoTrack { - readonly id: string; - kind: string; - readonly label: string; - language: string; - selected: boolean; - readonly sourceBuffer: SourceBuffer; -} - -declare var VideoTrack: { - prototype: VideoTrack; - new(): VideoTrack; -} - -interface VideoTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - readonly selectedIndex: number; - getTrackById(id: string): VideoTrack | null; - item(index: number): VideoTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: VideoTrack; -} - -declare var VideoTrackList: { - prototype: VideoTrackList; - new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -interface WaveShaperNode extends AudioNode { - curve: Float32Array | null; - oversample: string; -} - -declare var WaveShaperNode: { - prototype: WaveShaperNode; - new(): WaveShaperNode; -} - -interface WebGLActiveInfo { - readonly name: string; - readonly size: number; - readonly type: number; -} - -declare var WebGLActiveInfo: { - prototype: WebGLActiveInfo; - new(): WebGLActiveInfo; -} - -interface WebGLBuffer extends WebGLObject { -} - -declare var WebGLBuffer: { - prototype: WebGLBuffer; - new(): WebGLBuffer; -} - -interface WebGLContextEvent extends Event { - readonly statusMessage: string; -} - -declare var WebGLContextEvent: { - prototype: WebGLContextEvent; - new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} - -interface WebGLFramebuffer extends WebGLObject { -} - -declare var WebGLFramebuffer: { - prototype: WebGLFramebuffer; - new(): WebGLFramebuffer; -} - -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -} - -interface WebGLProgram extends WebGLObject { -} - -declare var WebGLProgram: { - prototype: WebGLProgram; - new(): WebGLProgram; -} - -interface WebGLRenderbuffer extends WebGLObject { -} - -declare var WebGLRenderbuffer: { - prototype: WebGLRenderbuffer; - new(): WebGLRenderbuffer; -} - -interface WebGLRenderingContext { - readonly canvas: HTMLCanvasElement; - readonly drawingBufferHeight: number; - readonly drawingBufferWidth: number; - activeTexture(texture: number): void; - attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; - bindBuffer(target: number, buffer: WebGLBuffer | null): void; - bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; - bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; - bindTexture(target: number, texture: WebGLTexture | null): void; - blendColor(red: number, green: number, blue: number, alpha: number): void; - blendEquation(mode: number): void; - blendEquationSeparate(modeRGB: number, modeAlpha: number): void; - blendFunc(sfactor: number, dfactor: number): void; - blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; - bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; - bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; - checkFramebufferStatus(target: number): number; - clear(mask: number): void; - clearColor(red: number, green: number, blue: number, alpha: number): void; - clearDepth(depth: number): void; - clearStencil(s: number): void; - colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; - compileShader(shader: WebGLShader | null): void; - compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; - compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; - copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; - copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; - createBuffer(): WebGLBuffer | null; - createFramebuffer(): WebGLFramebuffer | null; - createProgram(): WebGLProgram | null; - createRenderbuffer(): WebGLRenderbuffer | null; - createShader(type: number): WebGLShader | null; - createTexture(): WebGLTexture | null; - cullFace(mode: number): void; - deleteBuffer(buffer: WebGLBuffer | null): void; - deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; - deleteProgram(program: WebGLProgram | null): void; - deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; - deleteShader(shader: WebGLShader | null): void; - deleteTexture(texture: WebGLTexture | null): void; - depthFunc(func: number): void; - depthMask(flag: boolean): void; - depthRange(zNear: number, zFar: number): void; - detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - disable(cap: number): void; - disableVertexAttribArray(index: number): void; - drawArrays(mode: number, first: number, count: number): void; - drawElements(mode: number, count: number, type: number, offset: number): void; - enable(cap: number): void; - enableVertexAttribArray(index: number): void; - finish(): void; - flush(): void; - framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; - framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; - frontFace(mode: number): void; - generateMipmap(target: number): void; - getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; - getAttribLocation(program: WebGLProgram | null, name: string): number; - getBufferParameter(target: number, pname: number): any; - getContextAttributes(): WebGLContextAttributes; - getError(): number; - getExtension(name: string): any; - getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; - getParameter(pname: number): any; - getProgramInfoLog(program: WebGLProgram | null): string | null; - getProgramParameter(program: WebGLProgram | null, pname: number): any; - getRenderbufferParameter(target: number, pname: number): any; - getShaderInfoLog(shader: WebGLShader | null): string | null; - getShaderParameter(shader: WebGLShader | null, pname: number): any; - getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; - getShaderSource(shader: WebGLShader | null): string | null; - getSupportedExtensions(): string[] | null; - getTexParameter(target: number, pname: number): any; - getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; - getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; - getVertexAttrib(index: number, pname: number): any; - getVertexAttribOffset(index: number, pname: number): number; - hint(target: number, mode: number): void; - isBuffer(buffer: WebGLBuffer | null): boolean; - isContextLost(): boolean; - isEnabled(cap: number): boolean; - isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; - isProgram(program: WebGLProgram | null): boolean; - isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; - isShader(shader: WebGLShader | null): boolean; - isTexture(texture: WebGLTexture | null): boolean; - lineWidth(width: number): void; - linkProgram(program: WebGLProgram | null): void; - pixelStorei(pname: number, param: number): void; - polygonOffset(factor: number, units: number): void; - readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; - renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; - sampleCoverage(value: number, invert: boolean): void; - scissor(x: number, y: number, width: number, height: number): void; - shaderSource(shader: WebGLShader | null, source: string): void; - stencilFunc(func: number, ref: number, mask: number): void; - stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; - stencilMask(mask: number): void; - 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, 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, 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; - uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - useProgram(program: WebGLProgram | null): void; - validateProgram(program: WebGLProgram | null): void; - vertexAttrib1f(indx: number, x: number): void; - vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib2f(indx: number, x: number, y: number): void; - vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib3f(indx: number, x: number, y: number, z: number): void; - vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; - vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; - vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; - viewport(x: number, y: number, width: number, height: number): void; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -declare var WebGLRenderingContext: { - prototype: WebGLRenderingContext; - new(): WebGLRenderingContext; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -interface WebGLShader extends WebGLObject { -} - -declare var WebGLShader: { - prototype: WebGLShader; - new(): WebGLShader; -} - -interface WebGLShaderPrecisionFormat { - readonly precision: number; - readonly rangeMax: number; - readonly rangeMin: number; -} - -declare var WebGLShaderPrecisionFormat: { - prototype: WebGLShaderPrecisionFormat; - new(): WebGLShaderPrecisionFormat; -} - -interface WebGLTexture extends WebGLObject { -} - -declare var WebGLTexture: { - prototype: WebGLTexture; - new(): WebGLTexture; -} - -interface WebGLUniformLocation { -} - -declare var WebGLUniformLocation: { - prototype: WebGLUniformLocation; - new(): WebGLUniformLocation; -} - -interface WebKitCSSMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - m11: number; - m12: number; - m13: number; - m14: number; - m21: number; - m22: number; - m23: number; - m24: number; - m31: number; - m32: number; - m33: number; - m34: number; - m41: number; - m42: number; - m43: number; - m44: number; - inverse(): WebKitCSSMatrix; - multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; - rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; - rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; - scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; - setMatrixValue(value: string): void; - skewX(angle: number): WebKitCSSMatrix; - skewY(angle: number): WebKitCSSMatrix; - toString(): string; - translate(x: number, y: number, z?: number): WebKitCSSMatrix; -} - -declare var WebKitCSSMatrix: { - prototype: WebKitCSSMatrix; - new(text?: string): WebKitCSSMatrix; -} - -interface WebKitPoint { - x: number; - y: number; -} - -declare var WebKitPoint: { - prototype: WebKitPoint; - new(x?: number, y?: number): WebKitPoint; -} - -interface WebSocket extends EventTarget { - binaryType: string; - readonly bufferedAmount: number; - readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; - readonly protocol: string; - readonly readyState: number; - readonly url: string; - close(code?: number, reason?: string): void; - send(data: any): void; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WebSocket: { - prototype: WebSocket; - new(url: string, protocols?: string | string[]): WebSocket; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; -} - -interface WheelEvent extends MouseEvent { - readonly deltaMode: number; - readonly deltaX: number; - readonly deltaY: number; - readonly deltaZ: number; - readonly wheelDelta: number; - readonly wheelDeltaX: number; - readonly wheelDeltaY: number; - getCurrentPoint(element: Element): void; - initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -declare var WheelEvent: { - prototype: WheelEvent; - new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { - readonly applicationCache: ApplicationCache; - readonly clientInformation: Navigator; - readonly closed: boolean; - readonly crypto: Crypto; - defaultStatus: string; - readonly devicePixelRatio: number; - readonly doNotTrack: string; - readonly document: Document; - event: Event; - readonly external: External; - readonly frameElement: Element; - readonly frames: Window; - readonly history: History; - readonly innerHeight: number; - readonly innerWidth: number; - readonly length: number; - readonly location: Location; - readonly locationbar: BarProp; - readonly menubar: BarProp; - readonly msCredentials: MSCredentials; - name: string; - readonly navigator: Navigator; - offscreenBuffering: string | boolean; - onabort: (this: this, ev: UIEvent) => any; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncompassneedscalibration: (this: this, ev: Event) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondevicelight: (this: this, ev: DeviceLightEvent) => any; - ondevicemotion: (this: this, ev: DeviceMotionEvent) => any; - ondeviceorientation: (this: this, ev: DeviceOrientationEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: ErrorEventHandler; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreadystatechange: (this: this, ev: ProgressEvent) => any; - onreset: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onstalled: (this: this, ev: Event) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onunload: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - opener: any; - orientation: string | number; - readonly outerHeight: number; - readonly outerWidth: number; - readonly pageXOffset: number; - readonly pageYOffset: number; - readonly parent: Window; - readonly performance: Performance; - readonly personalbar: BarProp; - readonly screen: Screen; - readonly screenLeft: number; - readonly screenTop: number; - readonly screenX: number; - readonly screenY: number; - readonly scrollX: number; - readonly scrollY: number; - readonly scrollbars: BarProp; - readonly self: Window; - status: string; - readonly statusbar: BarProp; - readonly styleMedia: StyleMedia; - readonly toolbar: BarProp; - readonly top: Window; - readonly window: Window; - URL: typeof URL; - Blob: typeof Blob; - alert(message?: any): void; - blur(): void; - cancelAnimationFrame(handle: number): void; - captureEvents(): void; - close(): void; - confirm(message?: string): boolean; - focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; - getSelection(): Selection; - matchMedia(mediaQuery: string): MediaQueryList; - moveBy(x?: number, y?: number): void; - moveTo(x?: number, y?: number): void; - msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; - postMessage(message: any, targetOrigin: string, transfer?: any[]): void; - print(): void; - prompt(message?: string, _default?: string): string | null; - releaseEvents(): void; - requestAnimationFrame(callback: FrameRequestCallback): number; - resizeBy(x?: number, y?: number): void; - resizeTo(x?: number, y?: number): void; - scroll(x?: number, y?: number): void; - scrollBy(x?: number, y?: number): void; - scrollTo(x?: number, y?: number): void; - webkitCancelAnimationFrame(handle: number): void; - webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; - webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; - webkitRequestAnimationFrame(callback: FrameRequestCallback): number; - scroll(options?: ScrollToOptions): void; - scrollTo(options?: ScrollToOptions): void; - scrollBy(options?: ScrollToOptions): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "compassneedscalibration", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicelight", listener: (this: this, ev: DeviceLightEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicemotion", listener: (this: this, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deviceorientation", listener: (this: this, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; -} - -declare var Window: { - prototype: Window; - new(): Window; -} - -interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; - postMessage(message: any, ports?: any): void; - terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Worker: { - prototype: Worker; - new(stringUrl: string): Worker; -} - -interface XMLDocument extends Document { -} - -declare var XMLDocument: { - prototype: XMLDocument; - new(): XMLDocument; -} - -interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly response: any; - readonly responseText: string; - responseType: string; - readonly responseXML: any; - readonly status: number; - readonly statusText: string; - timeout: number; - readonly upload: XMLHttpRequestUpload; - withCredentials: boolean; - msCaching?: string; - abort(): void; - getAllResponseHeaders(): string; - getResponseHeader(header: string): string | null; - msCachingEnabled(): boolean; - open(method: string, url: string, async?: boolean, user?: string, password?: string): void; - overrideMimeType(mime: string): void; - send(data?: Document): void; - send(data?: string): void; - send(data?: any): void; - setRequestHeader(header: string, value: string): void; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequest: { - prototype: XMLHttpRequest; - new(): XMLHttpRequest; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - create(): XMLHttpRequest; -} - -interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequestUpload: { - prototype: XMLHttpRequestUpload; - new(): XMLHttpRequestUpload; -} - -interface XMLSerializer { - serializeToString(target: Node): string; -} - -declare var XMLSerializer: { - prototype: XMLSerializer; - new(): XMLSerializer; -} - -interface XPathEvaluator { - createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; -} - -declare var XPathEvaluator: { - prototype: XPathEvaluator; - new(): XPathEvaluator; -} - -interface XPathExpression { - evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; -} - -declare var XPathExpression: { - prototype: XPathExpression; - new(): XPathExpression; -} - -interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; -} - -declare var XPathNSResolver: { - prototype: XPathNSResolver; - new(): XPathNSResolver; -} - -interface XPathResult { - readonly booleanValue: boolean; - readonly invalidIteratorState: boolean; - readonly numberValue: number; - readonly resultType: number; - readonly singleNodeValue: Node; - readonly snapshotLength: number; - readonly stringValue: string; - iterateNext(): Node; - snapshotItem(index: number): Node; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -declare var XPathResult: { - prototype: XPathResult; - new(): XPathResult; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -interface XSLTProcessor { - clearParameters(): void; - getParameter(namespaceURI: string, localName: string): any; - importStylesheet(style: Node): void; - removeParameter(namespaceURI: string, localName: string): void; - reset(): void; - setParameter(namespaceURI: string, localName: string, value: any): void; - transformToDocument(source: Node): Document; - transformToFragment(source: Node, document: Document): DocumentFragment; -} - -declare var XSLTProcessor: { - prototype: XSLTProcessor; - new(): XSLTProcessor; -} - -interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface CanvasPathMethods { - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; - bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; - closePath(): void; - ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; - rect(x: number, y: number, w: number, h: number): void; -} - -interface ChildNode { - remove(): void; -} - -interface DOML2DeprecatedColorProperty { - color: string; -} - -interface DOML2DeprecatedSizeProperty { - size: number; -} - -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CommandEvent"): CommandEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - -interface ElementTraversal { - readonly childElementCount: number; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly nextElementSibling: Element; - readonly previousElementSibling: Element; -} - -interface GetSVGDocument { - getSVGDocument(): Document; -} - -interface GlobalEventHandlers { - onpointercancel: (this: this, ev: PointerEvent) => any; - onpointerdown: (this: this, ev: PointerEvent) => any; - onpointerenter: (this: this, ev: PointerEvent) => any; - onpointerleave: (this: this, ev: PointerEvent) => any; - onpointermove: (this: this, ev: PointerEvent) => any; - onpointerout: (this: this, ev: PointerEvent) => any; - onpointerover: (this: this, ev: PointerEvent) => any; - onpointerup: (this: this, ev: PointerEvent) => any; - onwheel: (this: this, ev: WheelEvent) => any; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface HTMLTableAlignment { - /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ - ch: string; - /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ - chOff: string; - /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ - vAlign: string; -} - -interface IDBEnvironment { - readonly indexedDB: IDBFactory; -} - -interface LinkStyle { - readonly sheet: StyleSheet; -} - -interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly result: any; - abort(): void; - readonly DONE: number; - readonly EMPTY: number; - readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface MSFileSaver { - msSaveBlob(blob: any, defaultName?: string): boolean; - msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; -} - -interface MSNavigatorDoNotTrack { - confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; - confirmWebWideTrackingException(args: ExceptionInformation): boolean; - removeSiteSpecificTrackingException(args: ExceptionInformation): void; - removeWebWideTrackingException(args: ExceptionInformation): void; - storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; - storeWebWideTrackingException(args: StoreExceptionsInformation): void; -} - -interface NavigatorContentUtils { -} - -interface NavigatorGeolocation { - readonly geolocation: Geolocation; -} - -interface NavigatorID { - readonly appName: string; - readonly appVersion: string; - readonly platform: string; - readonly product: string; - readonly productSub: string; - readonly userAgent: string; - readonly vendor: string; - readonly vendorSub: string; -} - -interface NavigatorOnLine { - readonly onLine: boolean; -} - -interface NavigatorStorageUtils { -} - -interface NavigatorUserMedia { - readonly mediaDevices: MediaDevices; - getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; -} - -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; -} - -interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; -} - -interface SVGAnimatedPathData { - readonly pathSegList: SVGPathSegList; -} - -interface SVGAnimatedPoints { - readonly animatedPoints: SVGPointList; - readonly points: SVGPointList; -} - -interface SVGExternalResourcesRequired { - readonly externalResourcesRequired: SVGAnimatedBoolean; -} - -interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { - readonly height: SVGAnimatedLength; - readonly result: SVGAnimatedString; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; -} - -interface SVGFitToViewBox { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly viewBox: SVGAnimatedRect; -} - -interface SVGLangSpace { - xmllang: string; - xmlspace: string; -} - -interface SVGLocatable { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; - getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; - getTransformToElement(element: SVGElement): SVGMatrix; -} - -interface SVGStylable { - className: any; - readonly style: CSSStyleDeclaration; -} - -interface SVGTests { - readonly requiredExtensions: SVGStringList; - readonly requiredFeatures: SVGStringList; - readonly systemLanguage: SVGStringList; - hasExtension(extension: string): boolean; -} - -interface SVGTransformable extends SVGLocatable { - readonly transform: SVGAnimatedTransformList; -} - -interface SVGURIReference { - readonly href: SVGAnimatedString; -} - -interface WindowBase64 { - atob(encodedString: string): string; - btoa(rawString: string): string; -} - -interface WindowConsole { - readonly console: Console; -} - -interface WindowLocalStorage { - readonly localStorage: Storage; -} - -interface WindowSessionStorage { - readonly sessionStorage: Storage; -} - -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(handler: (...args: any[]) => void): number; - setImmediate(handler: any, ...args: any[]): number; -} - -interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface StorageEventInit extends EventInit { - key?: string; - oldValue?: string; - newValue?: string; - url: string; - 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; - [index: number]: TNode; -} - -interface HTMLCollectionOf extends HTMLCollection { - item(index: number): T; - namedItem(name: string): T; - [index: number]: T; -} - -interface BlobPropertyBag { - type?: string; - endings?: string; -} - -interface FilePropertyBag { - type?: string; - lastModified?: number; -} - -interface EventListenerObject { - handleEvent(evt: Event): void; -} - -interface MessageEventInit extends EventInit { - data?: any; - origin?: string; - lastEventId?: string; - channel?: string; - source?: any; - ports?: MessagePort[]; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -interface ScrollOptions { - behavior?: ScrollBehavior; -} - -interface ScrollToOptions extends ScrollOptions { - left?: number; - top?: number; -} - -interface ScrollIntoViewOptions extends ScrollOptions { - block?: ScrollLogicalPosition; - inline?: ScrollLogicalPosition; -} - -interface ClipboardEventInit extends EventInit { - data?: string; - dataType?: string; -} - -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 { - namedCurve: 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; -} - -interface ParentNode { - readonly children: HTMLCollection; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly childElementCount: number; -} - -declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; - -interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; -} -interface PositionCallback { - (position: Position): void; -} -interface PositionErrorCallback { - (error: PositionError): void; -} -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: string): void; -} -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; -declare var applicationCache: ApplicationCache; -declare var clientInformation: Navigator; -declare var closed: boolean; -declare var crypto: Crypto; -declare var defaultStatus: string; -declare var devicePixelRatio: number; -declare var doNotTrack: string; -declare var document: Document; -declare var event: Event; -declare var external: External; -declare var frameElement: Element; -declare var frames: Window; -declare var history: History; -declare var innerHeight: number; -declare var innerWidth: number; -declare var length: number; -declare var location: Location; -declare var locationbar: BarProp; -declare var menubar: BarProp; -declare var msCredentials: MSCredentials; -declare const name: never; -declare var navigator: Navigator; -declare var offscreenBuffering: string | boolean; -declare var onabort: (this: Window, ev: UIEvent) => any; -declare var onafterprint: (this: Window, ev: Event) => any; -declare var onbeforeprint: (this: Window, ev: Event) => any; -declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; -declare var onblur: (this: Window, ev: FocusEvent) => any; -declare var oncanplay: (this: Window, ev: Event) => any; -declare var oncanplaythrough: (this: Window, ev: Event) => any; -declare var onchange: (this: Window, ev: Event) => any; -declare var onclick: (this: Window, ev: MouseEvent) => any; -declare var oncompassneedscalibration: (this: Window, ev: Event) => any; -declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; -declare var ondblclick: (this: Window, ev: MouseEvent) => any; -declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; -declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; -declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; -declare var ondrag: (this: Window, ev: DragEvent) => any; -declare var ondragend: (this: Window, ev: DragEvent) => any; -declare var ondragenter: (this: Window, ev: DragEvent) => any; -declare var ondragleave: (this: Window, ev: DragEvent) => any; -declare var ondragover: (this: Window, ev: DragEvent) => any; -declare var ondragstart: (this: Window, ev: DragEvent) => any; -declare var ondrop: (this: Window, ev: DragEvent) => any; -declare var ondurationchange: (this: Window, ev: Event) => any; -declare var onemptied: (this: Window, ev: Event) => any; -declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; -declare var onerror: ErrorEventHandler; -declare var onfocus: (this: Window, ev: FocusEvent) => any; -declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; -declare var oninput: (this: Window, ev: Event) => any; -declare var oninvalid: (this: Window, ev: Event) => any; -declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; -declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; -declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; -declare var onload: (this: Window, ev: Event) => any; -declare var onloadeddata: (this: Window, ev: Event) => any; -declare var onloadedmetadata: (this: Window, ev: Event) => any; -declare var onloadstart: (this: Window, ev: Event) => any; -declare var onmessage: (this: Window, ev: MessageEvent) => any; -declare var onmousedown: (this: Window, ev: MouseEvent) => any; -declare var onmouseenter: (this: Window, ev: MouseEvent) => any; -declare var onmouseleave: (this: Window, ev: MouseEvent) => any; -declare var onmousemove: (this: Window, ev: MouseEvent) => any; -declare var onmouseout: (this: Window, ev: MouseEvent) => any; -declare var onmouseover: (this: Window, ev: MouseEvent) => any; -declare var onmouseup: (this: Window, ev: MouseEvent) => any; -declare var onmousewheel: (this: Window, ev: WheelEvent) => any; -declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; -declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; -declare var onoffline: (this: Window, ev: Event) => any; -declare var ononline: (this: Window, ev: Event) => any; -declare var onorientationchange: (this: Window, ev: Event) => any; -declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; -declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; -declare var onpause: (this: Window, ev: Event) => any; -declare var onplay: (this: Window, ev: Event) => any; -declare var onplaying: (this: Window, ev: Event) => any; -declare var onpopstate: (this: Window, ev: PopStateEvent) => any; -declare var onprogress: (this: Window, ev: ProgressEvent) => any; -declare var onratechange: (this: Window, ev: Event) => any; -declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; -declare var onreset: (this: Window, ev: Event) => any; -declare var onresize: (this: Window, ev: UIEvent) => any; -declare var onscroll: (this: Window, ev: UIEvent) => any; -declare var onseeked: (this: Window, ev: Event) => any; -declare var onseeking: (this: Window, ev: Event) => any; -declare var onselect: (this: Window, ev: UIEvent) => any; -declare var onstalled: (this: Window, ev: Event) => any; -declare var onstorage: (this: Window, ev: StorageEvent) => any; -declare var onsubmit: (this: Window, ev: Event) => any; -declare var onsuspend: (this: Window, ev: Event) => any; -declare var ontimeupdate: (this: Window, ev: Event) => any; -declare var ontouchcancel: (ev: TouchEvent) => any; -declare var ontouchend: (ev: TouchEvent) => any; -declare var ontouchmove: (ev: TouchEvent) => any; -declare var ontouchstart: (ev: TouchEvent) => any; -declare var onunload: (this: Window, ev: Event) => any; -declare var onvolumechange: (this: Window, ev: Event) => any; -declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: any; -declare var orientation: string | number; -declare var outerHeight: number; -declare var outerWidth: number; -declare var pageXOffset: number; -declare var pageYOffset: number; -declare var parent: Window; -declare var performance: Performance; -declare var personalbar: BarProp; -declare var screen: Screen; -declare var screenLeft: number; -declare var screenTop: number; -declare var screenX: number; -declare var screenY: number; -declare var scrollX: number; -declare var scrollY: number; -declare var scrollbars: BarProp; -declare var self: Window; -declare var status: string; -declare var statusbar: BarProp; -declare var styleMedia: StyleMedia; -declare var toolbar: BarProp; -declare var top: Window; -declare var window: Window; -declare function alert(message?: any): void; -declare function blur(): void; -declare function cancelAnimationFrame(handle: number): void; -declare function captureEvents(): void; -declare function close(): void; -declare function confirm(message?: string): boolean; -declare function focus(): void; -declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; -declare function getSelection(): Selection; -declare function matchMedia(mediaQuery: string): MediaQueryList; -declare function moveBy(x?: number, y?: number): void; -declare function moveTo(x?: number, y?: number): void; -declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; -declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; -declare function print(): void; -declare function prompt(message?: string, _default?: string): string | null; -declare function releaseEvents(): void; -declare function requestAnimationFrame(callback: FrameRequestCallback): number; -declare function resizeBy(x?: number, y?: number): void; -declare function resizeTo(x?: number, y?: number): void; -declare function scroll(x?: number, y?: number): void; -declare function scrollBy(x?: number, y?: number): void; -declare function scrollTo(x?: number, y?: number): void; -declare function webkitCancelAnimationFrame(handle: number): void; -declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; -declare function scroll(options?: ScrollToOptions): void; -declare function scrollTo(options?: ScrollToOptions): void; -declare function scrollBy(options?: ScrollToOptions): void; -declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -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(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; -declare var onpointercancel: (this: Window, ev: PointerEvent) => any; -declare var onpointerdown: (this: Window, ev: PointerEvent) => any; -declare var onpointerenter: (this: Window, ev: PointerEvent) => any; -declare var onpointerleave: (this: Window, ev: PointerEvent) => any; -declare var onpointermove: (this: Window, ev: PointerEvent) => any; -declare var onpointerout: (this: Window, ev: PointerEvent) => any; -declare var onpointerover: (this: Window, ev: PointerEvent) => any; -declare var onpointerup: (this: Window, ev: PointerEvent) => any; -declare var onwheel: (this: Window, ev: WheelEvent) => any; -declare var indexedDB: IDBFactory; -declare function atob(encodedString: string): string; -declare function btoa(rawString: string): string; -declare function addEventListener(type: "MSGestureChange", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureDoubleTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureEnd", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureHold", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSInertiaStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerCancel", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerDown", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerEnter", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerLeave", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerMove", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOut", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOver", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerUp", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "abort", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "afterprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeunload", listener: (this: Window, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "blur", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplay", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplaythrough", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "change", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "click", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "compassneedscalibration", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "contextmenu", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dblclick", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicelight", listener: (this: Window, ev: DeviceLightEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicemotion", listener: (this: Window, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "deviceorientation", listener: (this: Window, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drag", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragend", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragenter", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragleave", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragover", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragstart", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drop", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "durationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "emptied", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ended", listener: (this: Window, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "focus", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "hashchange", listener: (this: Window, ev: HashChangeEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "input", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "invalid", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keydown", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keypress", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keyup", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "load", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadeddata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadedmetadata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadstart", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: Window, ev: MessageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousedown", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseenter", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseleave", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseout", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseover", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseup", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousewheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "offline", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "online", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "orientationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pagehide", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pageshow", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pause", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "play", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "playing", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointercancel", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerdown", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerenter", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerleave", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointermove", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerout", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerover", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerup", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "popstate", listener: (this: Window, ev: PopStateEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "progress", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ratechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "readystatechange", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "reset", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "resize", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "scroll", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeked", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeking", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "select", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "stalled", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "storage", listener: (this: Window, ev: StorageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "submit", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "suspend", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "timeupdate", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "unload", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "volumechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "waiting", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "wheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -type AAGUID = string; -type AlgorithmIdentifier = string | Algorithm; -type ConstrainBoolean = boolean | ConstrainBooleanParameters; -type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; -type ConstrainDouble = number | ConstrainDoubleRange; -type ConstrainLong = number | ConstrainLongRange; -type CryptoOperationData = ArrayBufferView; -type GLbitfield = number; -type GLboolean = boolean; -type GLbyte = number; -type GLclampf = number; -type GLenum = number; -type GLfloat = number; -type GLint = number; -type GLintptr = number; -type GLshort = number; -type GLsizei = number; -type GLsizeiptr = number; -type GLubyte = number; -type GLuint = number; -type GLushort = number; -type IDBKeyPath = string; -type KeyFormat = string; -type KeyType = string; -type KeyUsage = string; -type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; -type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; -type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; -type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; -type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; -type payloadtype = number; -type ScrollBehavior = "auto" | "instant" | "smooth"; -type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; -type IDBValidKey = number | string | Date | IDBArrayKey; -type BufferSource = ArrayBuffer | ArrayBufferView; -type MouseWheelEvent = WheelEvent; -///////////////////////////// -/// WorkerGlobalScope APIs -///////////////////////////// -// These are only available in a Web Worker -declare function importScripts(...urls: string[]): void; - - -///////////////////////////// -/// Windows Script Host APIS -///////////////////////////// - - -interface ActiveXObject { - new (s: string): any; -} -declare var ActiveXObject: ActiveXObject; - -interface ITextWriter { - Write(s: string): void; - WriteLine(s: string): void; - Close(): void; -} - -interface TextStreamBase { - /** - * The column number of the current character position in an input stream. - */ - Column: number; - - /** - * The current line number in an input stream. - */ - Line: number; - - /** - * Closes a text stream. - * It is not necessary to close standard streams; they close automatically when the process ends. If - * you close a standard stream, be aware that any other pointers to that standard stream become invalid. - */ - Close(): void; -} - -interface TextStreamWriter extends TextStreamBase { - /** - * Sends a string to an output stream. - */ - Write(s: string): void; - - /** - * Sends a specified number of blank lines (newline characters) to an output stream. - */ - WriteBlankLines(intLines: number): void; - - /** - * Sends a string followed by a newline character to an output stream. - */ - WriteLine(s: string): void; -} - -interface TextStreamReader extends TextStreamBase { - /** - * Returns a specified number of characters from an input stream, starting at the current pointer position. - * Does not return until the ENTER key is pressed. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - Read(characters: number): string; - - /** - * Returns all characters from an input stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadAll(): string; - - /** - * Returns an entire line from an input stream. - * Although this method extracts the newline character, it does not add it to the returned string. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadLine(): string; - - /** - * Skips a specified number of characters when reading from an input text stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) - */ - Skip(characters: number): void; - - /** - * Skips the next line when reading from an input text stream. - * Can only be used on a stream in reading mode, not writing or appending mode. - */ - SkipLine(): void; - - /** - * Indicates whether the stream pointer position is at the end of a line. - */ - AtEndOfLine: boolean; - - /** - * Indicates whether the stream pointer position is at the end of a stream. - */ - AtEndOfStream: boolean; -} - -declare var WScript: { - /** - * Outputs text to either a message box (under WScript.exe) or the command console window followed by - * a newline (under CScript.exe). - */ - Echo(s: any): void; - - /** - * Exposes the write-only error output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdErr: TextStreamWriter; - - /** - * Exposes the write-only output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdOut: TextStreamWriter; - Arguments: { length: number; Item(n: number): string; }; - - /** - * The full path of the currently running script. - */ - ScriptFullName: string; - - /** - * Forces the script to stop immediately, with an optional exit code. - */ - Quit(exitCode?: number): number; - - /** - * The Windows Script Host build version number. - */ - BuildVersion: number; - - /** - * Fully qualified path of the host executable. - */ - FullName: string; - - /** - * Gets/sets the script mode - interactive(true) or batch(false). - */ - Interactive: boolean; - - /** - * The name of the host executable (WScript.exe or CScript.exe). - */ - Name: string; - - /** - * Path of the directory containing the host executable. - */ - Path: string; - - /** - * The filename of the currently running script. - */ - ScriptName: string; - - /** - * Exposes the read-only input stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdIn: TextStreamReader; - - /** - * Windows Script Host version - */ - Version: string; - - /** - * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. - */ - ConnectObject(objEventSource: any, strPrefix: string): void; - - /** - * Creates a COM object. - * @param strProgiID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - CreateObject(strProgID: string, strPrefix?: string): any; - - /** - * Disconnects a COM object from its event sources. - */ - DisconnectObject(obj: any): void; - - /** - * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. - * @param strPathname Fully qualified path to the file containing the object persisted to disk. - * For objects in memory, pass a zero-length string. - * @param strProgID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; - - /** - * Suspends script execution for a specified length of time, then continues execution. - * @param intTime Interval (in milliseconds) to suspend script execution. - */ - Sleep(intTime: number): void; -}; - -/** - * Allows enumerating over a COM collection, which may not have indexed item access. - */ -interface Enumerator { - /** - * Returns true if the current item is the last one in the collection, or the collection is empty, - * or the current item is undefined. - */ - atEnd(): boolean; - - /** - * Returns the current item in the collection - */ - item(): T; - - /** - * Resets the current item in the collection to the first item. If there are no items in the collection, - * the current item is set to undefined. - */ - moveFirst(): void; - - /** - * Moves the current item to the next item in the collection. If the enumerator is at the end of - * the collection or the collection is empty, the current item is set to undefined. - */ - moveNext(): void; -} - -interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; -} - -declare var Enumerator: EnumeratorConstructor; - -/** - * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. - */ -interface VBArray { - /** - * Returns the number of dimensions (1-based). - */ - dimensions(): number; - - /** - * Takes an index for each dimension in the array, and returns the item at the corresponding location. - */ - getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; - - /** - * Returns the smallest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - lbound(dimension?: number): number; - - /** - * Returns the largest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - ubound(dimension?: number): number; - - /** - * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, - * each successive dimension is appended to the end of the array. - * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] - */ - toArray(): T[]; -} - -interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; -} - -declare var VBArray: VBArrayConstructor; - -/** - * Automation date (VT_DATE) - */ -interface VarDate { } - -interface DateConstructor { - new (vd: VarDate): Date; -} - -interface Date { - getVarDate: () => VarDate; -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has null prototype. + * @param o Object to use as a prototype. May be null + */ + create(o: null): any; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + */ + create(o: T): T; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(a: T[]): ReadonlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(this: Function, thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(this: Function, thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(this: Function, thisArg: any, ...argArray: any[]): any; + + /** Returns a string representation of a function. */ + toString(): string; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): RegExpMatchArray | null; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): RegExpMatchArray | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new (value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new (value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new (value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest number greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest number less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray | null; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): this; +} + +interface RegExpConstructor { + new (pattern: RegExp): RegExp; + new (pattern: string, flags?: string): RegExp; + (pattern: RegExp): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; + stack?: string; +} + +interface ErrorConstructor { + new (message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new (message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new (message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new (message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new (message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T | undefined; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): this; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +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) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, + 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. + * @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) | undefined | null): 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; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T pick a set of properties K + */ +type Pick = { + [P in K]: T[P]; +} + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8ClampedArray, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} +declare const Float64Array: Float64ArrayConstructor; + +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare module Intl { + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12?: boolean; + timeZone?: string; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; + } +} + +interface String { + /** + * Determines whether two strings are equivalent in the current or specified locale. + * @param that String to compare to target string + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; +} + +interface Number { + /** + * Converts a number to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; +} + +interface Date { + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + /** + * Converts a date to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; +} + + + +///////////////////////////// +/// IE DOM APIs +///////////////////////////// + +interface Algorithm { + name: string; +} + +interface AriaRequestEventInit extends EventInit { + attributeName?: string; + attributeValue?: string; +} + +interface CommandEventInit extends EventInit { + commandName?: string; + detail?: string; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainLongRange extends LongRange { + exact?: number; + ideal?: number; +} + +interface ConstrainVideoFacingModeParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface CustomEventInit extends EventInit { + detail?: any; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface EventInit { + scoped?: boolean; + bubbles?: boolean; + cancelable?: boolean; +} + +interface EventModifierInit extends UIEventInit { + ctrlKey?: boolean; + shiftKey?: boolean; + altKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierOS?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; +} + +interface ExceptionInformation { + domain?: string; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: IDBKeyPath; +} + +interface KeyAlgorithm { + name?: string; +} + +interface KeyboardEventInit extends EventModifierInit { + code?: string; + key?: string; + location?: number; + repeat?: boolean; +} + +interface LongRange { + max?: number; + min?: number; +} + +interface MSAccountInfo { + rpDisplayName?: string; + userDisplayName?: string; + accountName?: string; + userId?: string; + accountImageUri?: string; +} + +interface MSAudioLocalClientEvent extends MSLocalClientEventBase { + networkSendQualityEventRatio?: number; + networkDelayEventRatio?: number; + cpuInsufficientEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceCaptureNotFunctioningEventRatio?: number; + deviceGlitchesEventRatio?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceClippingEventRatio?: number; + deviceEchoEventRatio?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceHowlingEventCount?: number; +} + +interface MSAudioRecvPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioRecvSignal; + packetReorderRatio?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + burstLossLength1?: number; + burstLossLength2?: number; + burstLossLength3?: number; + burstLossLength4?: number; + burstLossLength5?: number; + burstLossLength6?: number; + burstLossLength7?: number; + burstLossLength8OrHigher?: number; + fecRecvDistance1?: number; + fecRecvDistance2?: number; + fecRecvDistance3?: number; + ratioConcealedSamplesAvg?: number; + ratioStretchedSamplesAvg?: number; + ratioCompressedSamplesAvg?: number; +} + +interface MSAudioRecvSignal { + initialSignalLevelRMS?: number; + recvSignalLevelCh1?: number; + recvNoiseLevelCh1?: number; + renderSignalLevel?: number; + renderNoiseLevel?: number; + renderLoopbackSignalLevel?: number; +} + +interface MSAudioSendPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioSendSignal; + audioFECUsed?: boolean; + sendMutePercent?: number; +} + +interface MSAudioSendSignal { + noiseLevel?: number; + sendSignalLevelCh1?: number; + sendNoiseLevelCh1?: number; +} + +interface MSConnectivity { + iceType?: string; + iceWarningFlags?: MSIceWarningFlags; + relayAddress?: MSRelayAddress; +} + +interface MSCredentialFilter { + accept?: MSCredentialSpec[]; +} + +interface MSCredentialParameters { + type?: string; +} + +interface MSCredentialSpec { + type?: string; + id?: string; +} + +interface MSDelay { + roundTrip?: number; + roundTripMax?: number; +} + +interface MSDescription extends RTCStats { + connectivity?: MSConnectivity; + transport?: string; + networkconnectivity?: MSNetworkConnectivityInfo; + localAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + deviceDevName?: string; + reflexiveLocalIPAddr?: MSIPAddressInfo; +} + +interface MSFIDOCredentialParameters extends MSCredentialParameters { + algorithm?: string | Algorithm; + authenticators?: AAGUID[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + port?: number; + manufacturerMacAddrMask?: string; +} + +interface MSIceWarningFlags { + turnTcpTimedOut?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; + turnTcpAllocateFailed?: boolean; + turnTcpSendFailed?: boolean; + udpLocalConnectivityFailed?: boolean; + udpNatConnectivityFailed?: boolean; + udpRelayConnectivityFailed?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + connCheckMessageIntegrityFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + turnAuthUnknownUsernameError?: boolean; + noRelayServersConfigured?: boolean; + multipleRelayServersAttempted?: boolean; + portRangeExhausted?: boolean; + alternateServerReceived?: boolean; + pseudoTLSFailure?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + useCandidateChecksFailed?: boolean; + fipsAllocationFailure?: boolean; +} + +interface MSJitter { + interArrival?: number; + interArrivalMax?: number; + interArrivalSD?: number; +} + +interface MSLocalClientEventBase extends RTCStats { + networkReceiveQualityEventRatio?: number; + networkBandwidthLowEventRatio?: number; +} + +interface MSNetwork extends RTCStats { + jitter?: MSJitter; + delay?: MSDelay; + packetLoss?: MSPacketLoss; + utilization?: MSUtilization; +} + +interface MSNetworkConnectivityInfo { + vpn?: boolean; + linkspeed?: number; + networkConnectionDetails?: string; +} + +interface MSNetworkInterfaceType { + interfaceTypeEthernet?: boolean; + interfaceTypeWireless?: boolean; + interfaceTypePPP?: boolean; + interfaceTypeTunnel?: boolean; + interfaceTypeWWAN?: boolean; +} + +interface MSOutboundNetwork extends MSNetwork { + appliedBandwidthLimit?: number; +} + +interface MSPacketLoss { + lossRate?: number; + lossRateMax?: number; +} + +interface MSPayloadBase extends RTCStats { + payloadDescription?: string; +} + +interface MSRelayAddress { + relayAddress?: string; + port?: number; +} + +interface MSSignatureParameters { + userPrompt?: string; +} + +interface MSTransportDiagnosticsStats extends RTCStats { + baseAddress?: string; + localAddress?: string; + localSite?: string; + networkName?: string; + remoteAddress?: string; + remoteSite?: string; + localMR?: string; + remoteMR?: string; + iceWarningFlags?: MSIceWarningFlags; + portRangeMin?: number; + portRangeMax?: number; + localMRTCPPort?: number; + remoteMRTCPPort?: number; + stunVer?: number; + numConsentReqSent?: number; + numConsentReqReceived?: number; + numConsentRespSent?: number; + numConsentRespReceived?: number; + interfaces?: MSNetworkInterfaceType; + baseInterface?: MSNetworkInterfaceType; + protocol?: string; + localInterface?: MSNetworkInterfaceType; + localAddrType?: string; + remoteAddrType?: string; + iceRole?: string; + rtpRtcpMux?: boolean; + allocationTimeInMs?: number; + msRtcEngineVersion?: string; +} + +interface MSUtilization { + packets?: number; + bandwidthEstimation?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationStdDev?: number; + bandwidthEstimationAvg?: number; +} + +interface MSVideoPayload extends MSPayloadBase { + resoluton?: string; + videoBitRateAvg?: number; + videoBitRateMax?: number; + videoFrameRateAvg?: number; + videoPacketLossRate?: number; + durationSeconds?: number; +} + +interface MSVideoRecvPayload extends MSVideoPayload { + videoFrameLossRate?: number; + recvCodecType?: string; + recvResolutionWidth?: number; + recvResolutionHeight?: number; + videoResolutions?: MSVideoResolutionDistribution; + recvFrameRateAverage?: number; + recvBitRateMaximum?: number; + recvBitRateAverage?: number; + recvVideoStreamsMax?: number; + recvVideoStreamsMin?: number; + recvVideoStreamsMode?: number; + videoPostFECPLR?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; + reorderBufferTotalPackets?: number; + recvReorderBufferReorderedPackets?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvFpsHarmonicAverage?: number; + recvNumResSwitches?: number; +} + +interface MSVideoResolutionDistribution { + cifQuality?: number; + vgaQuality?: number; + h720Quality?: number; + h1080Quality?: number; + h1440Quality?: number; + h2160Quality?: number; +} + +interface MSVideoSendPayload extends MSVideoPayload { + sendFrameRateAverage?: number; + sendBitRateMaximum?: number; + sendBitRateAverage?: number; + sendVideoStreamsMax?: number; + sendResolutionWidth?: number; + sendResolutionHeight?: number; +} + +interface MediaEncryptedEventInit extends EventInit { + initDataType?: string; + initData?: ArrayBuffer; +} + +interface MediaKeyMessageEventInit extends EventInit { + messageType?: string; + message?: ArrayBuffer; +} + +interface MediaKeySystemConfiguration { + initDataTypes?: string[]; + audioCapabilities?: MediaKeySystemMediaCapability[]; + videoCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: string; + persistentState?: string; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + width?: number | LongRange; + height?: number | LongRange; + aspectRatio?: number | DoubleRange; + frameRate?: number | DoubleRange; + facingMode?: string; + volume?: number | DoubleRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + echoCancellation?: boolean[]; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackConstraintSet { + width?: number | ConstrainLongRange; + height?: number | ConstrainLongRange; + aspectRatio?: number | ConstrainDoubleRange; + frameRate?: number | ConstrainDoubleRange; + facingMode?: string | string[] | ConstrainDOMStringParameters; + volume?: number | ConstrainDoubleRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + echoCancelation?: boolean | ConstrainBooleanParameters; + deviceId?: string | string[] | ConstrainDOMStringParameters; + groupId?: string | string[] | ConstrainDOMStringParameters; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackSettings { + width?: number; + height?: number; + aspectRatio?: number; + frameRate?: number; + facingMode?: string; + volume?: number; + sampleRate?: number; + sampleSize?: number; + echoCancellation?: boolean; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackSupportedConstraints { + width?: boolean; + height?: boolean; + aspectRatio?: boolean; + frameRate?: boolean; + facingMode?: boolean; + volume?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + echoCancellation?: boolean; + deviceId?: boolean; + groupId?: boolean; +} + +interface MouseEventInit extends EventModifierInit { + screenX?: number; + screenY?: number; + clientX?: number; + clientY?: number; + button?: number; + buttons?: number; + relatedTarget?: EventTarget; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: string[]; +} + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + pointerId?: number; + width?: number; + height?: number; + pressure?: number; + tiltX?: number; + tiltY?: number; + pointerType?: string; + isPrimary?: boolean; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCDtlsParameters { + role?: string; + fingerprints?: RTCDtlsFingerprint[]; +} + +interface RTCIceCandidate { + foundation?: string; + priority?: number; + ip?: string; + protocol?: string; + port?: number; + type?: string; + tcpType?: string; + relatedAddress?: string; + relatedPort?: number; +} + +interface RTCIceCandidateAttributes extends RTCStats { + ipAddress?: string; + portNumber?: number; + transport?: string; + candidateType?: string; + priority?: number; + addressSourceUrl?: string; +} + +interface RTCIceCandidateComplete { +} + +interface RTCIceCandidatePair { + local?: RTCIceCandidate; + remote?: RTCIceCandidate; +} + +interface RTCIceCandidatePairStats extends RTCStats { + transportId?: string; + localCandidateId?: string; + remoteCandidateId?: string; + state?: string; + priority?: number; + nominated?: boolean; + writable?: boolean; + readable?: boolean; + bytesSent?: number; + bytesReceived?: number; + roundTripTime?: number; + availableOutgoingBitrate?: number; + availableIncomingBitrate?: number; +} + +interface RTCIceGatherOptions { + gatherPolicy?: string; + iceservers?: RTCIceServer[]; +} + +interface RTCIceParameters { + usernameFragment?: string; + password?: string; +} + +interface RTCIceServer { + urls?: any; + username?: string; + credential?: string; +} + +interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { + packetsReceived?: number; + bytesReceived?: number; + packetsLost?: number; + jitter?: number; + fractionLost?: number; +} + +interface RTCMediaStreamTrackStats extends RTCStats { + trackIdentifier?: string; + remoteSource?: boolean; + ssrcIds?: string[]; + frameWidth?: number; + frameHeight?: number; + framesPerSecond?: number; + framesSent?: number; + framesReceived?: number; + framesDecoded?: number; + framesDropped?: number; + framesCorrupted?: number; + audioLevel?: number; + echoReturnLoss?: number; + echoReturnLossEnhancement?: number; +} + +interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { + packetsSent?: number; + bytesSent?: number; + targetBitrate?: number; + roundTripTime?: number; +} + +interface RTCRTPStreamStats extends RTCStats { + ssrc?: string; + associateStatsId?: string; + isRemote?: boolean; + mediaTrackId?: string; + transportId?: string; + codecId?: string; + firCount?: number; + pliCount?: number; + nackCount?: number; + sliCount?: number; +} + +interface RTCRtcpFeedback { + type?: string; + parameter?: string; +} + +interface RTCRtcpParameters { + ssrc?: number; + cname?: string; + reducedSize?: boolean; + mux?: boolean; +} + +interface RTCRtpCapabilities { + codecs?: RTCRtpCodecCapability[]; + headerExtensions?: RTCRtpHeaderExtension[]; + fecMechanisms?: string[]; +} + +interface RTCRtpCodecCapability { + name?: string; + kind?: string; + clockRate?: number; + preferredPayloadType?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; + options?: any; + maxTemporalLayers?: number; + maxSpatialLayers?: number; + svcMultiStreamSupport?: boolean; +} + +interface RTCRtpCodecParameters { + name?: string; + payloadType?: any; + clockRate?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; +} + +interface RTCRtpContributingSource { + timestamp?: number; + csrc?: number; + audioLevel?: number; +} + +interface RTCRtpEncodingParameters { + ssrc?: number; + codecPayloadType?: number; + fec?: RTCRtpFecParameters; + rtx?: RTCRtpRtxParameters; + priority?: number; + maxBitrate?: number; + minQuality?: number; + framerateBias?: number; + resolutionScale?: number; + framerateScale?: number; + active?: boolean; + encodingId?: string; + dependencyEncodingIds?: string[]; + ssrcRange?: RTCSsrcRange; +} + +interface RTCRtpFecParameters { + ssrc?: number; + mechanism?: string; +} + +interface RTCRtpHeaderExtension { + kind?: string; + uri?: string; + preferredId?: number; + preferredEncrypt?: boolean; +} + +interface RTCRtpHeaderExtensionParameters { + uri?: string; + id?: number; + encrypt?: boolean; +} + +interface RTCRtpParameters { + muxId?: string; + codecs?: RTCRtpCodecParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + encodings?: RTCRtpEncodingParameters[]; + rtcp?: RTCRtcpParameters; +} + +interface RTCRtpRtxParameters { + ssrc?: number; +} + +interface RTCRtpUnhandled { + ssrc?: number; + payloadType?: number; + muxId?: string; +} + +interface RTCSrtpKeyParam { + keyMethod?: string; + keySalt?: string; + lifetime?: string; + mkiValue?: number; + mkiLength?: number; +} + +interface RTCSrtpSdesParameters { + tag?: number; + cryptoSuite?: string; + keyParams?: RTCSrtpKeyParam[]; + sessionParams?: string[]; +} + +interface RTCSsrcRange { + min?: number; + max?: number; +} + +interface RTCStats { + timestamp?: number; + type?: string; + id?: string; + msType?: string; +} + +interface RTCStatsReport { +} + +interface RTCTransportStats extends RTCStats { + bytesSent?: number; + bytesReceived?: number; + rtcpTransportStatsId?: string; + activeConnection?: boolean; + selectedCandidatePairId?: string; + localCertificateId?: string; + remoteCertificateId?: string; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface UIEventInit extends EventInit { + view?: Window; + detail?: number; +} + +interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; + alpha?: boolean; + depth?: boolean; + stencil?: boolean; + antialias?: boolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaX?: number; + deltaY?: number; + deltaZ?: number; + deltaMode?: number; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + readonly frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(): AnalyserNode; +} + +interface AnimationEvent extends Event { + readonly animationName: string; + readonly elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": ErrorEvent; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + +interface ApplicationCache extends EventTarget { + oncached: (this: ApplicationCache, ev: Event) => any; + onchecking: (this: ApplicationCache, ev: Event) => any; + ondownloading: (this: ApplicationCache, ev: Event) => any; + onerror: (this: ApplicationCache, ev: ErrorEvent) => any; + onnoupdate: (this: ApplicationCache, ev: Event) => any; + onobsolete: (this: ApplicationCache, ev: Event) => any; + onprogress: (this: ApplicationCache, ev: ProgressEvent) => any; + onupdateready: (this: ApplicationCache, ev: Event) => any; + readonly status: number; + abort(): void; + swapCache(): void; + update(): void; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; +} + +interface AriaRequestEvent extends Event { + readonly attributeName: string; + attributeValue: string | null; +} + +declare var AriaRequestEvent: { + prototype: AriaRequestEvent; + new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; +} + +interface Attr extends Node { + readonly name: string; + readonly ownerElement: Element; + readonly prefix: string | null; + readonly specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +} + +interface AudioBufferSourceNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface AudioBufferSourceNode extends AudioNode { + buffer: AudioBuffer | null; + readonly detune: AudioParam; + loop: boolean; + loopEnd: number; + loopStart: number; + onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + readonly playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(): AudioBufferSourceNode; +} + +interface AudioContext extends EventTarget { + readonly currentTime: number; + readonly destination: AudioDestinationNode; + readonly listener: AudioListener; + readonly sampleRate: number; + state: string; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; +} + +declare var AudioContext: { + prototype: AudioContext; + new(): AudioContext; +} + +interface AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +} + +interface AudioListener { + dopplerFactor: number; + speedOfSound: number; + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +} + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: string; + channelInterpretation: string; + readonly context: AudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + connect(destination: AudioNode, output?: number, input?: number): void; + disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +} + +interface AudioParam { + readonly defaultValue: number; + value: number; + cancelScheduledValues(startTime: number): void; + exponentialRampToValueAtTime(value: number, endTime: number): void; + linearRampToValueAtTime(value: number, endTime: number): void; + setTargetAtTime(target: number, startTime: number, timeConstant: number): void; + setValueAtTime(value: number, startTime: number): void; + setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +} + +interface AudioProcessingEvent extends Event { + readonly inputBuffer: AudioBuffer; + readonly outputBuffer: AudioBuffer; + readonly playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(): AudioProcessingEvent; +} + +interface AudioTrack { + enabled: boolean; + readonly id: string; + kind: string; + readonly label: string; + language: string; + readonly sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface AudioTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: AudioTrackList, ev: TrackEvent) => any; + onchange: (this: AudioTrackList, ev: Event) => any; + onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack | null; + item(index: number): AudioTrack; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface BarProp { + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +} + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; + readonly detune: AudioParam; + readonly frequency: AudioParam; + readonly gain: AudioParam; + type: string; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(): BiquadFilterNode; +} + +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface CSS { + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +} + +interface CSSFontFaceRule extends CSSRule { + readonly style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface CSSGroupingRule extends CSSRule { + readonly cssRules: CSSRuleList; + deleteRule(index: number): void; + insertRule(rule: string, index: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +} + +interface CSSImportRule extends CSSRule { + readonly href: string; + readonly media: MediaList; + readonly styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSKeyframesRule extends CSSRule { + readonly cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(rule: string): void; + findRule(rule: string): CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface CSSMediaRule extends CSSConditionRule { + readonly media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface CSSNamespaceRule extends CSSRule { + readonly namespaceURI: string; + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface CSSPageRule extends CSSRule { + readonly pseudoClass: string; + readonly selector: string; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface CSSRule { + cssText: string; + readonly parentRule: CSSRule; + readonly parentStyleSheet: CSSStyleSheet; + readonly type: number; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +interface CSSRuleList { + readonly length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface CSSStyleDeclaration { + alignContent: string | null; + alignItems: string | null; + alignSelf: string | null; + alignmentBaseline: string | null; + animation: string | null; + animationDelay: string | null; + animationDirection: string | null; + animationDuration: string | null; + animationFillMode: string | null; + animationIterationCount: string | null; + animationName: string | null; + animationPlayState: string | null; + animationTimingFunction: string | null; + backfaceVisibility: string | null; + background: string | null; + backgroundAttachment: string | null; + backgroundClip: string | null; + backgroundColor: string | null; + backgroundImage: string | null; + backgroundOrigin: string | null; + backgroundPosition: string | null; + backgroundPositionX: string | null; + backgroundPositionY: string | null; + backgroundRepeat: string | null; + backgroundSize: string | null; + baselineShift: string | null; + border: string | null; + borderBottom: string | null; + borderBottomColor: string | null; + borderBottomLeftRadius: string | null; + borderBottomRightRadius: string | null; + borderBottomStyle: string | null; + borderBottomWidth: string | null; + borderCollapse: string | null; + borderColor: string | null; + borderImage: string | null; + borderImageOutset: string | null; + borderImageRepeat: string | null; + borderImageSlice: string | null; + borderImageSource: string | null; + borderImageWidth: string | null; + borderLeft: string | null; + borderLeftColor: string | null; + borderLeftStyle: string | null; + borderLeftWidth: string | null; + borderRadius: string | null; + borderRight: string | null; + borderRightColor: string | null; + borderRightStyle: string | null; + borderRightWidth: string | null; + borderSpacing: string | null; + borderStyle: string | null; + borderTop: string | null; + borderTopColor: string | null; + borderTopLeftRadius: string | null; + borderTopRightRadius: string | null; + borderTopStyle: string | null; + borderTopWidth: string | null; + borderWidth: string | null; + bottom: string | null; + boxShadow: string | null; + boxSizing: string | null; + breakAfter: string | null; + breakBefore: string | null; + breakInside: string | null; + captionSide: string | null; + clear: string | null; + clip: string | null; + clipPath: string | null; + clipRule: string | null; + color: string | null; + colorInterpolationFilters: string | null; + columnCount: any; + columnFill: string | null; + columnGap: any; + columnRule: string | null; + columnRuleColor: any; + columnRuleStyle: string | null; + columnRuleWidth: any; + columnSpan: string | null; + columnWidth: any; + columns: string | null; + content: string | null; + counterIncrement: string | null; + counterReset: string | null; + cssFloat: string | null; + cssText: string; + cursor: string | null; + direction: string | null; + display: string | null; + dominantBaseline: string | null; + emptyCells: string | null; + enableBackground: string | null; + fill: string | null; + fillOpacity: string | null; + fillRule: string | null; + filter: string | null; + flex: string | null; + flexBasis: string | null; + flexDirection: string | null; + flexFlow: string | null; + flexGrow: string | null; + flexShrink: string | null; + flexWrap: string | null; + floodColor: string | null; + floodOpacity: string | null; + font: string | null; + fontFamily: string | null; + fontFeatureSettings: string | null; + fontSize: string | null; + fontSizeAdjust: string | null; + fontStretch: string | null; + fontStyle: string | null; + fontVariant: string | null; + fontWeight: string | null; + glyphOrientationHorizontal: string | null; + glyphOrientationVertical: string | null; + height: string | null; + imeMode: string | null; + justifyContent: string | null; + kerning: string | null; + left: string | null; + readonly length: number; + letterSpacing: string | null; + lightingColor: string | null; + lineHeight: string | null; + listStyle: string | null; + listStyleImage: string | null; + listStylePosition: string | null; + listStyleType: string | null; + margin: string | null; + marginBottom: string | null; + marginLeft: string | null; + marginRight: string | null; + marginTop: string | null; + marker: string | null; + markerEnd: string | null; + markerMid: string | null; + markerStart: string | null; + mask: string | null; + maxHeight: string | null; + maxWidth: string | null; + minHeight: string | null; + minWidth: string | null; + msContentZoomChaining: string | null; + msContentZoomLimit: string | null; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string | null; + msContentZoomSnapPoints: string | null; + msContentZoomSnapType: string | null; + msContentZooming: string | null; + msFlowFrom: string | null; + msFlowInto: string | null; + msFontFeatureSettings: string | null; + msGridColumn: any; + msGridColumnAlign: string | null; + msGridColumnSpan: any; + msGridColumns: string | null; + msGridRow: any; + msGridRowAlign: string | null; + msGridRowSpan: any; + msGridRows: string | null; + msHighContrastAdjust: string | null; + msHyphenateLimitChars: string | null; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string | null; + msImeAlign: string | null; + msOverflowStyle: string | null; + msScrollChaining: string | null; + msScrollLimit: string | null; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string | null; + msScrollSnapPointsX: string | null; + msScrollSnapPointsY: string | null; + msScrollSnapType: string | null; + msScrollSnapX: string | null; + msScrollSnapY: string | null; + msScrollTranslation: string | null; + msTextCombineHorizontal: string | null; + msTextSizeAdjust: any; + msTouchAction: string | null; + msTouchSelect: string | null; + msUserSelect: string | null; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + opacity: string | null; + order: string | null; + orphans: string | null; + outline: string | null; + outlineColor: string | null; + outlineStyle: string | null; + outlineWidth: string | null; + overflow: string | null; + overflowX: string | null; + overflowY: string | null; + padding: string | null; + paddingBottom: string | null; + paddingLeft: string | null; + paddingRight: string | null; + paddingTop: string | null; + pageBreakAfter: string | null; + pageBreakBefore: string | null; + pageBreakInside: string | null; + readonly parentRule: CSSRule; + perspective: string | null; + perspectiveOrigin: string | null; + pointerEvents: string | null; + position: string | null; + quotes: string | null; + right: string | null; + rubyAlign: string | null; + rubyOverhang: string | null; + rubyPosition: string | null; + stopColor: string | null; + stopOpacity: string | null; + stroke: string | null; + strokeDasharray: string | null; + strokeDashoffset: string | null; + strokeLinecap: string | null; + strokeLinejoin: string | null; + strokeMiterlimit: string | null; + strokeOpacity: string | null; + strokeWidth: string | null; + tableLayout: string | null; + textAlign: string | null; + textAlignLast: string | null; + textAnchor: string | null; + textDecoration: string | null; + textIndent: string | null; + textJustify: string | null; + textKashida: string | null; + textKashidaSpace: string | null; + textOverflow: string | null; + textShadow: string | null; + textTransform: string | null; + textUnderlinePosition: string | null; + top: string | null; + touchAction: string | null; + transform: string | null; + transformOrigin: string | null; + transformStyle: string | null; + transition: string | null; + transitionDelay: string | null; + transitionDuration: string | null; + transitionProperty: string | null; + transitionTimingFunction: string | null; + unicodeBidi: string | null; + verticalAlign: string | null; + visibility: string | null; + webkitAlignContent: string | null; + webkitAlignItems: string | null; + webkitAlignSelf: string | null; + webkitAnimation: string | null; + webkitAnimationDelay: string | null; + webkitAnimationDirection: string | null; + webkitAnimationDuration: string | null; + webkitAnimationFillMode: string | null; + webkitAnimationIterationCount: string | null; + webkitAnimationName: string | null; + webkitAnimationPlayState: string | null; + webkitAnimationTimingFunction: string | null; + webkitAppearance: string | null; + webkitBackfaceVisibility: string | null; + webkitBackgroundClip: string | null; + webkitBackgroundOrigin: string | null; + webkitBackgroundSize: string | null; + webkitBorderBottomLeftRadius: string | null; + webkitBorderBottomRightRadius: string | null; + webkitBorderImage: string | null; + webkitBorderRadius: string | null; + webkitBorderTopLeftRadius: string | null; + webkitBorderTopRightRadius: string | null; + webkitBoxAlign: string | null; + webkitBoxDirection: string | null; + webkitBoxFlex: string | null; + webkitBoxOrdinalGroup: string | null; + webkitBoxOrient: string | null; + webkitBoxPack: string | null; + webkitBoxSizing: string | null; + webkitColumnBreakAfter: string | null; + webkitColumnBreakBefore: string | null; + webkitColumnBreakInside: string | null; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string | null; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string | null; + webkitColumnRuleWidth: any; + webkitColumnSpan: string | null; + webkitColumnWidth: any; + webkitColumns: string | null; + webkitFilter: string | null; + webkitFlex: string | null; + webkitFlexBasis: string | null; + webkitFlexDirection: string | null; + webkitFlexFlow: string | null; + webkitFlexGrow: string | null; + webkitFlexShrink: string | null; + webkitFlexWrap: string | null; + webkitJustifyContent: string | null; + webkitOrder: string | null; + webkitPerspective: string | null; + webkitPerspectiveOrigin: string | null; + webkitTapHighlightColor: string | null; + webkitTextFillColor: string | null; + webkitTextSizeAdjust: any; + webkitTransform: string | null; + webkitTransformOrigin: string | null; + webkitTransformStyle: string | null; + webkitTransition: string | null; + webkitTransitionDelay: string | null; + webkitTransitionDuration: string | null; + webkitTransitionProperty: string | null; + webkitTransitionTimingFunction: string | null; + webkitUserModify: string | null; + webkitUserSelect: string | null; + webkitWritingMode: string | null; + whiteSpace: string | null; + widows: string | null; + width: string | null; + wordBreak: string | null; + wordSpacing: string | null; + wordWrap: string | null; + writingMode: string | null; + zIndex: string | null; + zoom: string | null; + resize: string | null; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string | null, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface CSSStyleRule extends CSSRule { + readonly readOnly: boolean; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface CSSStyleSheet extends StyleSheet { + readonly cssRules: CSSRuleList; + cssText: string; + readonly href: string; + readonly id: string; + readonly imports: StyleSheetList; + readonly isAlternate: boolean; + readonly isPrefAlternate: boolean; + readonly ownerRule: CSSRule; + readonly owningElement: Element; + readonly pages: StyleSheetPageList; + readonly readOnly: boolean; + readonly rules: CSSRuleList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: string; + msImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + fill(fillRule?: string): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +} + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +} + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface CommandEvent extends Event { + readonly commandName: string; + readonly detail: string | null; +} + +declare var CommandEvent: { + prototype: CommandEvent; + new(type: string, eventInitDict?: CommandEventInit): CommandEvent; +} + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +} + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: string, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string): void; + groupCollapsed(groupTitle?: string): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +} + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +} + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +} + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +} + +interface CustomEvent extends Event { + readonly detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +} + +interface DOMError { + readonly name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; + createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface DOMStringMap { + [name: string]: string; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +} + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +} + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + readonly files: FileList; + readonly items: DataTransferItemList; + readonly types: string[]; + clearData(format?: string): boolean; + getData(format: string): string; + setData(format: string, data: string): boolean; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface DataTransferItem { + readonly kind: string; + readonly type: string; + getAsFile(): File | null; + getAsString(_callback: FunctionStringCallback | null): void; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +} + +interface DataTransferItemList { + readonly length: number; + add(data: File): DataTransferItem | null; + clear(): void; + item(index: number): DataTransferItem; + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +} + +interface DeferredPermissionRequest { + readonly id: number; + readonly type: string; + readonly uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +} + +interface DelayNode extends AudioNode { + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(): DelayNode; +} + +interface DeviceAcceleration { + readonly x: number | null; + readonly y: number | null; + readonly z: number | null; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +} + +interface DeviceLightEvent extends Event { + readonly value: number; +} + +declare var DeviceLightEvent: { + prototype: DeviceLightEvent; + new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; +} + +interface DeviceMotionEvent extends Event { + readonly acceleration: DeviceAcceleration | null; + readonly accelerationIncludingGravity: DeviceAcceleration | null; + readonly interval: number | null; + readonly rotationRate: DeviceRotationRate | null; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(): DeviceMotionEvent; +} + +interface DeviceOrientationEvent extends Event { + readonly absolute: boolean; + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(): DeviceOrientationEvent; +} + +interface DeviceRotationRate { + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +} + +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforedeactivate": UIEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "fullscreenchange": Event; + "fullscreenerror": Event; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "mssitemodejumplistitemremoved": MSSiteModeEvent; + "msthumbnailclick": MSSiteModeEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectionchange": Event; + "selectstart": Event; + "stalled": Event; + "stop": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "volumechange": Event; + "waiting": Event; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; + /** + * Gets the object that has the focus when the parent document has focus. + */ + readonly activeElement: Element; + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollectionOf; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + readonly compatMode: string; + cookie: string; + readonly currentScript: HTMLScriptElement | SVGScriptElement; + /** + * Gets the default character set from the current regional language settings. + */ + readonly defaultCharset: string; + readonly defaultView: Window; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * 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. + */ + readonly doctype: DocumentType; + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollectionOf; + readonly fullscreenElement: Element | null; + readonly fullscreenEnabled: boolean; + readonly head: HTMLHeadElement; + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + readonly inputEncoding: string | null; + /** + * 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. + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollectionOf; + /** + * Contains information about the current URL. + */ + readonly location: Location; + msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (this: Document, ev: FocusEvent) => any; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (this: Document, ev: Event) => any; + oncanplaythrough: (this: Document, ev: Event) => any; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (this: Document, ev: PointerEvent) => any; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (this: Document, 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: (this: Document, 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. + */ + ondragleave: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (this: Document, ev: DragEvent) => any; + ondrop: (this: Document, ev: DragEvent) => any; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (this: Document, ev: Event) => any; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (this: Document, ev: Event) => any; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (this: Document, ev: MediaStreamErrorEvent) => any; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (this: Document, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (this: Document, ev: FocusEvent) => any; + onfullscreenchange: (this: Document, ev: Event) => any; + onfullscreenerror: (this: Document, ev: Event) => any; + oninput: (this: Document, ev: Event) => any; + oninvalid: (this: Document, ev: Event) => any; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (this: Document, ev: Event) => any; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (this: Document, ev: Event) => any; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (this: Document, ev: Event) => any; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (this: Document, ev: WheelEvent) => any; + onmscontentzoom: (this: Document, ev: UIEvent) => any; + onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Document, ev: MSGestureEvent) => any; + onmsgestureend: (this: Document, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Document, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Document, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Document, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Document, ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (this: Document, ev: MSManipulationEvent) => any; + onmspointercancel: (this: Document, ev: MSPointerEvent) => any; + onmspointerdown: (this: Document, ev: MSPointerEvent) => any; + onmspointerenter: (this: Document, ev: MSPointerEvent) => any; + onmspointerleave: (this: Document, ev: MSPointerEvent) => any; + onmspointermove: (this: Document, ev: MSPointerEvent) => any; + onmspointerout: (this: Document, ev: MSPointerEvent) => any; + onmspointerover: (this: Document, ev: MSPointerEvent) => any; + onmspointerup: (this: Document, ev: MSPointerEvent) => any; + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (this: Document, ev: Event) => any; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (this: Document, ev: Event) => any; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (this: Document, ev: Event) => any; + onpointerlockchange: (this: Document, ev: Event) => any; + onpointerlockerror: (this: Document, ev: Event) => any; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (this: Document, ev: ProgressEvent) => any; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (this: Document, ev: Event) => any; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (this: Document, ev: ProgressEvent) => any; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (this: Document, ev: Event) => any; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (this: Document, ev: UIEvent) => any; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (this: Document, ev: Event) => any; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (this: Document, ev: Event) => any; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (this: Document, ev: UIEvent) => any; + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (this: Document, ev: Event) => any; + onselectstart: (this: Document, ev: Event) => any; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (this: Document, ev: Event) => any; + onsubmit: (this: Document, ev: Event) => any; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (this: Document, ev: Event) => any; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (this: Document, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (this: Document, ev: Event) => any; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (this: Document, ev: Event) => any; + onwebkitfullscreenchange: (this: Document, ev: Event) => any; + onwebkitfullscreenerror: (this: Document, ev: Event) => any; + plugins: HTMLCollectionOf; + readonly pointerLockElement: Element; + /** + * Retrieves a value that indicates the current state of the object. + */ + readonly readyState: string; + /** + * Gets the URL of the location that referred the user to the current page. + */ + readonly referrer: string; + /** + * Gets the root svg element in the document hierarchy. + */ + readonly rootElement: SVGSVGElement; + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + readonly styleSheets: StyleSheetList; + /** + * Contains the title of the document. + */ + title: string; + readonly visibilityState: string; + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + readonly webkitCurrentFullScreenElement: Element | null; + readonly webkitFullscreenElement: Element | null; + readonly webkitFullscreenEnabled: boolean; + readonly webkitIsFullScreen: boolean; + readonly xmlEncoding: string | null; + xmlStandalone: boolean; + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string | null; + adoptNode(source: Node): Node; + captureEvents(): void; + caretRangeFromPoint(x: number, y: number): Range; + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: K): HTMLElementTagNameMap[K]; + createElement(tagName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: string | null, qualifiedName: string): Element; + 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. + * @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. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + 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. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker 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. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + exitFullscreen(): void; + exitPointerLock(): void; + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + /** + * 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 | null; + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: Node, deep: boolean): Node; + msElementsFromPoint(x: number, y: number): NodeListOf; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @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. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + 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. + */ + queryCommandText(commandId: string): string; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + releaseEvents(): void; + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + webkitCancelFullScreen(): void; + webkitExitFullscreen(): void; + /** + * 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. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +} + +interface DocumentFragment extends Node, NodeSelector, ParentNode { +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DocumentType extends Node, ChildNode { + readonly entities: NamedNodeMap; + readonly internalSubset: string | null; + readonly name: string; + readonly notations: NamedNodeMap; + readonly publicId: string | null; + readonly systemId: string | null; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface DragEvent extends MouseEvent { + readonly dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DynamicsCompressorNode extends AudioNode { + readonly attack: AudioParam; + readonly knee: AudioParam; + readonly ratio: AudioParam; + readonly reduction: AudioParam; + readonly release: AudioParam; + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(): DynamicsCompressorNode; +} + +interface EXT_frag_depth { +} + +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": AriaRequestEvent; + "command": CommandEvent; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSGotPointerCapture": MSPointerEvent; + "MSInertiaStart": MSGestureEvent; + "MSLostPointerCapture": MSPointerEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { + readonly classList: DOMTokenList; + className: string; + readonly clientHeight: number; + readonly clientLeft: number; + readonly clientTop: number; + readonly clientWidth: number; + id: string; + msContentZoomFactor: number; + readonly msRegionOverflow: string; + onariarequest: (this: Element, ev: AriaRequestEvent) => any; + oncommand: (this: Element, ev: CommandEvent) => any; + ongotpointercapture: (this: Element, ev: PointerEvent) => any; + onlostpointercapture: (this: Element, ev: PointerEvent) => any; + onmsgesturechange: (this: Element, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Element, ev: MSGestureEvent) => any; + onmsgestureend: (this: Element, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Element, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Element, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Element, ev: MSGestureEvent) => any; + onmsgotpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmsinertiastart: (this: Element, ev: MSGestureEvent) => any; + onmslostpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmspointercancel: (this: Element, ev: MSPointerEvent) => any; + onmspointerdown: (this: Element, ev: MSPointerEvent) => any; + onmspointerenter: (this: Element, ev: MSPointerEvent) => any; + onmspointerleave: (this: Element, ev: MSPointerEvent) => any; + onmspointermove: (this: Element, ev: MSPointerEvent) => any; + onmspointerout: (this: Element, ev: MSPointerEvent) => any; + onmspointerover: (this: Element, ev: MSPointerEvent) => any; + onmspointerup: (this: Element, ev: MSPointerEvent) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onwebkitfullscreenchange: (this: Element, ev: Event) => any; + onwebkitfullscreenerror: (this: Element, ev: Event) => any; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly tagName: string; + innerHTML: string; + readonly assignedSlot: HTMLSlotElement | null; + slot: string; + readonly shadowRoot: ShadowRoot | null; + getAttribute(name: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; + msZoomTo(args: MsZoomToOptions): void; + releasePointerCapture(pointerId: number): void; + removeAttribute(name?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + setAttribute(name: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): void; + getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget; + readonly timeStamp: number; + readonly type: string; + readonly scoped: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + deepPath(): EventTarget[]; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +interface EventTarget { + addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +} + +interface External { +} + +declare var External: { + prototype: External; + new(): External; +} + +interface File extends Blob { + readonly lastModifiedDate: any; + readonly name: string; + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +} + +interface FileList { + readonly length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface FileReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +} + +interface FocusEvent extends UIEvent { + readonly relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} + +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface GainNode extends AudioNode { + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(): GainNode; +} + +interface Gamepad { + readonly axes: number[]; + readonly buttons: GamepadButton[]; + readonly connected: boolean; + readonly id: string; + readonly index: number; + readonly mapping: string; + readonly timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +} + +interface GamepadButton { + readonly pressed: boolean; + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +} + +interface GamepadEvent extends Event { + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(): GamepadEvent; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +} + +interface HTMLAnchorElement extends HTMLElement { + Methods: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + readonly mimeType: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + readonly nameProp: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + readonly protocolLong: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: 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; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface HTMLAppletElement extends HTMLElement { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + object: string | null; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + vspace: number; + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + rel: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns a string representation of an object. + */ + toString(): string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Adds an element to the areas, controlRange, or options collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Removes an element from the collection. + */ + remove(index?: number): void; +} + +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface HTMLBodyElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLBodyElement extends HTMLElement { + aLink: any; + background: string; + bgColor: any; + bgProperties: string; + link: any; + noWrap: boolean; + onafterprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; + onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; + onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; + onload: (this: HTMLBodyElement, ev: Event) => any; + onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; + onoffline: (this: HTMLBodyElement, ev: Event) => any; + ononline: (this: HTMLBodyElement, ev: Event) => any; + onorientationchange: (this: HTMLBodyElement, ev: Event) => any; + onpagehide: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; + onresize: (this: HTMLBodyElement, ev: UIEvent) => any; + onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; + onunload: (this: HTMLBodyElement, ev: Event) => any; + text: any; + vLink: any; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + status: any; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * 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; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * 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", 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. + */ + msToBlob(): Blob; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLCollection { + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Retrieves an object from various collections. + */ + item(index: number): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [index: number]: Element; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface HTMLDirectoryElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +} + +interface HTMLElementEventMap extends ElementEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforecopy": ClipboardEvent; + "beforecut": ClipboardEvent; + "beforedeactivate": UIEvent; + "beforepaste": ClipboardEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectstart": Event; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "volumechange": Event; + "waiting": Event; +} + +interface HTMLElement extends Element { + accessKey: string; + readonly children: HTMLCollection; + contentEditable: string; + readonly dataset: DOMStringMap; + dir: string; + draggable: boolean; + hidden: boolean; + hideFocus: boolean; + innerHTML: string; + innerText: string; + readonly isContentEditable: boolean; + lang: string; + readonly offsetHeight: number; + readonly offsetLeft: number; + readonly offsetParent: Element; + readonly offsetTop: number; + readonly offsetWidth: number; + onabort: (this: HTMLElement, ev: UIEvent) => any; + onactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforecopy: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforecut: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforedeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforepaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onblur: (this: HTMLElement, ev: FocusEvent) => any; + oncanplay: (this: HTMLElement, ev: Event) => any; + oncanplaythrough: (this: HTMLElement, ev: Event) => any; + onchange: (this: HTMLElement, ev: Event) => any; + onclick: (this: HTMLElement, ev: MouseEvent) => any; + oncontextmenu: (this: HTMLElement, ev: PointerEvent) => any; + oncopy: (this: HTMLElement, ev: ClipboardEvent) => any; + oncuechange: (this: HTMLElement, ev: Event) => any; + oncut: (this: HTMLElement, ev: ClipboardEvent) => any; + ondblclick: (this: HTMLElement, ev: MouseEvent) => any; + ondeactivate: (this: HTMLElement, ev: UIEvent) => any; + ondrag: (this: HTMLElement, ev: DragEvent) => any; + ondragend: (this: HTMLElement, ev: DragEvent) => any; + ondragenter: (this: HTMLElement, ev: DragEvent) => any; + ondragleave: (this: HTMLElement, ev: DragEvent) => any; + ondragover: (this: HTMLElement, ev: DragEvent) => any; + ondragstart: (this: HTMLElement, ev: DragEvent) => any; + ondrop: (this: HTMLElement, ev: DragEvent) => any; + ondurationchange: (this: HTMLElement, ev: Event) => any; + onemptied: (this: HTMLElement, ev: Event) => any; + onended: (this: HTMLElement, ev: MediaStreamErrorEvent) => any; + onerror: (this: HTMLElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLElement, ev: FocusEvent) => any; + oninput: (this: HTMLElement, ev: Event) => any; + oninvalid: (this: HTMLElement, ev: Event) => any; + onkeydown: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeypress: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeyup: (this: HTMLElement, ev: KeyboardEvent) => any; + onload: (this: HTMLElement, ev: Event) => any; + onloadeddata: (this: HTMLElement, ev: Event) => any; + onloadedmetadata: (this: HTMLElement, ev: Event) => any; + onloadstart: (this: HTMLElement, ev: Event) => any; + onmousedown: (this: HTMLElement, ev: MouseEvent) => any; + onmouseenter: (this: HTMLElement, ev: MouseEvent) => any; + onmouseleave: (this: HTMLElement, ev: MouseEvent) => any; + onmousemove: (this: HTMLElement, ev: MouseEvent) => any; + onmouseout: (this: HTMLElement, ev: MouseEvent) => any; + onmouseover: (this: HTMLElement, ev: MouseEvent) => any; + onmouseup: (this: HTMLElement, ev: MouseEvent) => any; + onmousewheel: (this: HTMLElement, ev: WheelEvent) => any; + onmscontentzoom: (this: HTMLElement, ev: UIEvent) => any; + onmsmanipulationstatechanged: (this: HTMLElement, ev: MSManipulationEvent) => any; + onpaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onpause: (this: HTMLElement, ev: Event) => any; + onplay: (this: HTMLElement, ev: Event) => any; + onplaying: (this: HTMLElement, ev: Event) => any; + onprogress: (this: HTMLElement, ev: ProgressEvent) => any; + onratechange: (this: HTMLElement, ev: Event) => any; + onreset: (this: HTMLElement, ev: Event) => any; + onscroll: (this: HTMLElement, ev: UIEvent) => any; + onseeked: (this: HTMLElement, ev: Event) => any; + onseeking: (this: HTMLElement, ev: Event) => any; + onselect: (this: HTMLElement, ev: UIEvent) => any; + onselectstart: (this: HTMLElement, ev: Event) => any; + onstalled: (this: HTMLElement, ev: Event) => any; + onsubmit: (this: HTMLElement, ev: Event) => any; + onsuspend: (this: HTMLElement, ev: Event) => any; + ontimeupdate: (this: HTMLElement, ev: Event) => any; + onvolumechange: (this: HTMLElement, ev: Event) => any; + onwaiting: (this: HTMLElement, ev: Event) => any; + outerHTML: string; + outerText: string; + spellcheck: boolean; + readonly style: CSSStyleDeclaration; + tabIndex: number; + title: string; + blur(): void; + click(): void; + dragDrop(): boolean; + focus(): void; + msGetInputContext(): MSInputMethodContext; + setActive(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + readonly palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + readonly pluginspage: string; + readonly readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + readonly elements: HTMLCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(name: string): any; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface HTMLFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument { + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string | number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLFrameElement, ev: Event) => any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the width of the object. + */ + width: string | number; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLFrameSetElement extends HTMLElement { + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + name: string; + onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; + /** + * Fires when the object loses the input focus. + */ + onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + */ + onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; + onload: (this: HTMLFrameSetElement, ev: Event) => any; + onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; + onoffline: (this: HTMLFrameSetElement, ev: Event) => any; + ononline: (this: HTMLFrameSetElement, ev: Event) => any; + onorientationchange: (this: HTMLFrameSetElement, ev: Event) => any; + onpagehide: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; + onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; + onunload: (this: HTMLFrameSetElement, ev: Event) => any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface HTMLIFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + allowFullscreen: boolean; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLIFrameElement, ev: Event) => any; + readonly sandbox: DOMSettableTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + crossOrigin: string; + readonly currentSrc: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + lowsrc: string; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * The original height of the image resource before sizing. + */ + readonly naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + readonly naturalWidth: number; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + readonly x: number; + readonly y: number; + msGetAsCastingSource(): any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; + create(): HTMLImageElement; +} + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + readonly files: FileList | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + indeterminate: boolean; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + readonly list: HTMLElement; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + selectionDirection: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + status: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: Date; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + webkitdirectory: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start?: number, end?: number, direction?: string): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface HTMLLabelElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface HTMLLegendElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + import?: Document; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + readonly areas: HTMLAreasCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + +interface HTMLMarqueeElement extends HTMLElement { + behavior: string; + bgColor: any; + direction: string; + height: string; + hspace: number; + loop: number; + onbounce: (this: HTMLMarqueeElement, ev: Event) => any; + onfinish: (this: HTMLMarqueeElement, ev: Event) => any; + onstart: (this: HTMLMarqueeElement, ev: Event) => any; + scrollAmount: number; + scrollDelay: number; + trueSpeed: boolean; + vspace: number; + width: string; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": MSMediaKeyNeededEvent; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + readonly audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + readonly buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + crossOrigin: string; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + readonly currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + readonly duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + readonly ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + readonly error: MediaError; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + readonly mediaKeys: MediaKeys | null; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + readonly msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + readonly msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + readonly networkState: number; + onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; + onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + /** + * Gets a flag that specifies whether playback is paused. + */ + readonly paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + readonly played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + readonly seekable: TimeRanges; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + readonly seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcObject: MediaStream | null; + readonly textTracks: TextTrackList; + readonly videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): string; + /** + * Resets the audio or video object and loads a new media resource. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; +} + +interface HTMLMenuElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface HTMLMeterElement extends HTMLElement { + high: number; + low: number; + max: number; + min: number; + optimum: number; + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMeterElement: { + prototype: HTMLMeterElement; + new(): HTMLMeterElement; +} + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface HTMLOListElement extends HTMLElement { + compact: boolean; + /** + * The starting number. + */ + start: number; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the contained object. + */ + readonly object: any; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface HTMLOptGroupElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + readonly text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; + create(): HTMLOptionElement; +} + +interface HTMLOptionsCollection extends HTMLCollectionOf { + length: number; + selectedIndex: number; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + remove(index: number): void; +} + +declare var HTMLOptionsCollection: { + prototype: HTMLOptionsCollection; + new(): HTMLOptionsCollection; +} + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + +interface HTMLPreElement extends HTMLElement { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + readonly position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * 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; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface HTMLSelectElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly options: HTMLOptionsCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + selectedOptions: HTMLCollectionOf; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * 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. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + msKeySystem: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + disabled: boolean; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + bgColor: any; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + readonly cellIndex: number; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** + * Sets or retrieves the width of the object. + */ + width: any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement { +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + bgColor: any; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollectionOf; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + bgColor: any; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollectionOf; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + readonly rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + readonly sectionRowIndex: number; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface HTMLTemplateElement extends HTMLElement { + readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLTextAreaElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves the type of control. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readonly readyState: number; + src: string; + srclang: string; + readonly track: TextTrack; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; +} + +interface HTMLUListElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + readonly msIsLayoutOptimalForPlayback: boolean; + readonly msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoWidth: number; + readonly webkitDisplayingFullscreen: boolean; + readonly webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullScreen(): void; + webkitEnterFullscreen(): void; + webkitExitFullScreen(): void; + webkitExitFullscreen(): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +} + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +} + +interface IDBCursor { + readonly direction: string; + key: IDBKeyRange | IDBValidKey; + readonly primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: IDBKeyRange | IDBValidKey): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +interface IDBCursorWithValue extends IDBCursor { + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + +interface IDBDatabase extends EventTarget { + readonly name: string; + readonly objectStoreNames: DOMStringList; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; + version: number; + onversionchange: (ev: IDBVersionChangeEvent) => any; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; + addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface IDBIndex { + keyPath: string | string[]; + readonly name: string; + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + multiEntry: boolean; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + get(key: IDBKeyRange | IDBValidKey): IDBRequest; + getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface IDBKeyRange { + readonly lower: any; + readonly lowerOpen: boolean; + readonly upper: any; + readonly upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(lower: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(upper: any, open?: boolean): IDBKeyRange; +} + +interface IDBObjectStore { + readonly indexNames: DOMStringList; + keyPath: string | string[]; + readonly name: string; + readonly transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + clear(): IDBRequest; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + +interface IDBRequest extends EventTarget { + readonly error: DOMError; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; + readonly readyState: string; + readonly result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + readonly transaction: IDBTransaction; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + +interface IDBTransaction extends EventTarget { + readonly db: IDBDatabase; + readonly error: DOMError; + readonly mode: string; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; +} + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface ImageData { + data: Uint8ClampedArray; + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +} + +interface KeyboardEvent extends UIEvent { + readonly altKey: boolean; + readonly char: string | null; + readonly charCode: number; + readonly ctrlKey: boolean; + readonly key: string; + readonly keyCode: number; + readonly locale: string; + readonly location: number; + readonly metaKey: boolean; + readonly repeat: boolean; + readonly shiftKey: boolean; + readonly which: number; + readonly code: string; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +interface ListeningStateChangedEvent extends Event { + readonly label: string; + readonly state: string; +} + +declare var ListeningStateChangedEvent: { + prototype: ListeningStateChangedEvent; + new(): ListeningStateChangedEvent; +} + +interface Location { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + assign(url: string): void; + reload(forcedReload?: boolean): void; + replace(url: string): void; + toString(): string; +} + +declare var Location: { + prototype: Location; + new(): Location; +} + +interface LongRunningScriptDetectedEvent extends Event { + readonly executionTime: number; + stopPageScriptExecution: boolean; +} + +declare var LongRunningScriptDetectedEvent: { + prototype: LongRunningScriptDetectedEvent; + new(): LongRunningScriptDetectedEvent; +} + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + readonly CURRENT: string; + readonly HIGH: string; + readonly IDLE: string; + readonly NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSAppAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; +} + +interface MSAssertion { + readonly id: string; + readonly type: string; +} + +declare var MSAssertion: { + prototype: MSAssertion; + new(): MSAssertion; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +} + +interface MSCredentials { + getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; + makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; +} + +declare var MSCredentials: { + prototype: MSCredentials; + new(): MSCredentials; +} + +interface MSFIDOCredentialAssertion extends MSAssertion { + readonly algorithm: string | Algorithm; + readonly attestation: any; + readonly publicKey: string; + readonly transportHints: string[]; +} + +declare var MSFIDOCredentialAssertion: { + prototype: MSFIDOCredentialAssertion; + new(): MSFIDOCredentialAssertion; +} + +interface MSFIDOSignature { + readonly authnrData: string; + readonly clientData: string; + readonly signature: string; +} + +declare var MSFIDOSignature: { + prototype: MSFIDOSignature; + new(): MSFIDOSignature; +} + +interface MSFIDOSignatureAssertion extends MSAssertion { + readonly signature: MSFIDOSignature; +} + +declare var MSFIDOSignatureAssertion: { + prototype: MSFIDOSignatureAssertion; + new(): MSFIDOSignatureAssertion; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +} + +interface MSGestureEvent extends UIEvent { + readonly clientX: number; + readonly clientY: number; + readonly expansion: number; + readonly gestureObject: any; + readonly hwTimestamp: number; + readonly offsetX: number; + readonly offsetY: number; + readonly rotation: number; + readonly scale: number; + readonly screenX: number; + readonly screenY: number; + readonly translationX: number; + readonly translationY: number; + readonly velocityAngular: number; + readonly velocityExpansion: number; + readonly velocityX: number; + readonly velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +interface MSGraphicsTrust { + readonly constrictionActive: boolean; + readonly status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +} + +interface MSHTMLWebViewElement extends HTMLElement { + readonly canGoBack: boolean; + readonly canGoForward: boolean; + readonly containsFullScreenElement: boolean; + readonly documentTitle: string; + height: number; + readonly settings: MSWebViewSettings; + src: string; + width: number; + addWebAllowedObject(name: string, applicationObject: any): void; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; + getDeferredPermissionRequests(): DeferredPermissionRequest[]; + goBack(): void; + goForward(): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + navigate(uri: string): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + navigateToString(contents: string): void; + navigateWithHttpRequestMessage(requestMessage: any): void; + refresh(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSHTMLWebViewElement: { + prototype: MSHTMLWebViewElement; + new(): MSHTMLWebViewElement; +} + +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowshow: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowupdate: (this: MSInputMethodContext, ev: Event) => any; + readonly target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +} + +interface MSManipulationEvent extends UIEvent { + readonly currentState: number; + readonly inertiaDestinationX: number; + readonly inertiaDestinationY: number; + readonly lastState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +interface MSMediaKeyError { + readonly code: number; + readonly systemCode: number; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +interface MSMediaKeyMessageEvent extends Event { + readonly destinationURL: string | null; + readonly message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +} + +interface MSMediaKeyNeededEvent extends Event { + readonly initData: Uint8Array | null; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +} + +interface MSMediaKeySession extends EventTarget { + readonly error: MSMediaKeyError | null; + readonly keySystem: string; + readonly sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +} + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +} + +interface MSPointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +} + +interface MSRangeCollection { + readonly length: number; + item(index: number): Range; + [index: number]: Range; +} + +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSSiteModeEvent extends Event { + readonly actionURL: string; + readonly buttonID: number; +} + +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MSStreamReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +} + +interface MSWebViewAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSWebViewAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSWebViewAsyncOperation, ev: Event) => any; + onerror: (this: MSWebViewAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + readonly target: MSHTMLWebViewElement; + readonly type: number; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSWebViewAsyncOperation: { + prototype: MSWebViewAsyncOperation; + new(): MSWebViewAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; +} + +interface MSWebViewSettings { + isIndexedDBEnabled: boolean; + isJavaScriptEnabled: boolean; +} + +declare var MSWebViewSettings: { + prototype: MSWebViewSettings; + new(): MSWebViewSettings; +} + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: string; + readonly label: string; +} + +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +} + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): PromiseLike; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +} + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +} + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +} + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: string; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +} + +interface MediaKeySession extends EventTarget { + readonly closed: PromiseLike; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): PromiseLike; + generateRequest(initDataType: string, initData: any): PromiseLike; + load(sessionId: string): PromiseLike; + remove(): PromiseLike; + update(response: any): PromiseLike; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +} + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): string; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +} + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): PromiseLike; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +} + +interface MediaKeys { + createSession(sessionType?: string): MediaKeySession; + setServerCertificate(serverCertificate: any): PromiseLike; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +} + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +} + +interface MediaStreamEventMap { + "active": Event; + "addtrack": TrackEvent; + "inactive": Event; + "removetrack": TrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: TrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: TrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +} + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +} + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +} + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +} + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: string; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): PromiseLike; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +} + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +} + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +} + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +} + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +} + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +} + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +} + +interface MutationEvent extends Event { + readonly attrChange: number; + readonly attrName: string; + readonly newValue: string; + readonly prevValue: string; + readonly relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +interface MutationObserver { + disconnect(): void; + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +} + +interface MutationRecord { + readonly addedNodes: NodeList; + readonly attributeName: string | null; + readonly attributeNamespace: string | null; + readonly nextSibling: Node | null; + readonly oldValue: string | null; + readonly previousSibling: Node | null; + readonly removedNodes: NodeList; + readonly target: Node; + readonly type: string; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +} + +interface NamedNodeMap { + readonly length: number; + getNamedItem(name: string): Attr; + getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + item(index: number): Attr; + removeNamedItem(name: string): Attr; + removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + setNamedItem(arg: Attr): Attr; + setNamedItemNS(arg: Attr): Attr; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface NavigationCompletedEvent extends NavigationEvent { + readonly isSuccess: boolean; + readonly webErrorStatus: number; +} + +declare var NavigationCompletedEvent: { + prototype: NavigationCompletedEvent; + new(): NavigationCompletedEvent; +} + +interface NavigationEvent extends Event { + readonly uri: string; +} + +declare var NavigationEvent: { + prototype: NavigationEvent; + new(): NavigationEvent; +} + +interface NavigationEventWithReferrer extends NavigationEvent { + readonly referer: string; +} + +declare var NavigationEventWithReferrer: { + prototype: NavigationEventWithReferrer; + new(): NavigationEventWithReferrer; +} + +interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { + readonly appCodeName: string; + readonly cookieEnabled: boolean; + readonly language: string; + readonly maxTouchPoints: number; + readonly mimeTypes: MimeTypeArray; + readonly msManipulationViewsEnabled: boolean; + readonly msMaxTouchPoints: number; + readonly msPointerEnabled: boolean; + readonly plugins: PluginArray; + readonly pointerEnabled: boolean; + readonly webdriver: boolean; + readonly hardwareConcurrency: number; + getGamepads(): Gamepad[]; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; + vibrate(pattern: number | number[]): boolean; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface Node extends EventTarget { + readonly attributes: NamedNodeMap; + readonly baseURI: string | null; + readonly childNodes: NodeList; + readonly firstChild: Node | null; + readonly lastChild: Node | null; + readonly localName: string | null; + readonly namespaceURI: string | null; + readonly nextSibling: Node | null; + readonly nodeName: string; + readonly nodeType: number; + nodeValue: string | null; + readonly ownerDocument: Document; + readonly parentElement: HTMLElement | null; + readonly parentNode: Node | null; + readonly previousSibling: Node | null; + textContent: string | null; + appendChild(newChild: Node): Node; + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + contains(child: Node): boolean; + hasAttributes(): boolean; + hasChildNodes(): boolean; + insertBefore(newChild: Node, refChild: Node | null): Node; + isDefaultNamespace(namespaceURI: string | null): boolean; + isEqualNode(arg: Node): boolean; + isSameNode(other: Node): boolean; + lookupNamespaceURI(prefix: string | null): string | null; + lookupPrefix(namespaceURI: string | null): string | null; + normalize(): void; + removeChild(oldChild: Node): Node; + replaceChild(newChild: Node, oldChild: Node): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +interface NodeFilter { + acceptNode(n: Node): number; +} + +declare var NodeFilter: { + readonly FILTER_ACCEPT: number; + readonly FILTER_REJECT: number; + readonly FILTER_SKIP: number; + readonly SHOW_ALL: number; + readonly SHOW_ATTRIBUTE: number; + readonly SHOW_CDATA_SECTION: number; + readonly SHOW_COMMENT: number; + readonly SHOW_DOCUMENT: number; + readonly SHOW_DOCUMENT_FRAGMENT: number; + readonly SHOW_DOCUMENT_TYPE: number; + readonly SHOW_ELEMENT: number; + readonly SHOW_ENTITY: number; + readonly SHOW_ENTITY_REFERENCE: number; + readonly SHOW_NOTATION: number; + readonly SHOW_PROCESSING_INSTRUCTION: number; + readonly SHOW_TEXT: number; +} + +interface NodeIterator { + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + detach(): void; + nextNode(): Node; + previousNode(): Node; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface NodeList { + readonly length: number; + item(index: number): Node; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface OES_element_index_uint { +} + +declare var OES_element_index_uint: { + prototype: OES_element_index_uint; + new(): OES_element_index_uint; +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +declare var OES_standard_derivatives: { + prototype: OES_standard_derivatives; + new(): OES_standard_derivatives; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface OES_texture_float { +} + +declare var OES_texture_float: { + prototype: OES_texture_float; + new(): OES_texture_float; +} + +interface OES_texture_float_linear { +} + +declare var OES_texture_float_linear: { + prototype: OES_texture_float_linear; + new(): OES_texture_float_linear; +} + +interface OfflineAudioCompletionEvent extends Event { + readonly renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(): OfflineAudioCompletionEvent; +} + +interface OfflineAudioContextEventMap { + "complete": Event; +} + +interface OfflineAudioContext extends AudioContext { + oncomplete: (this: OfflineAudioContext, ev: Event) => any; + startRendering(): PromiseLike; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +} + +interface OscillatorNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface OscillatorNode extends AudioNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + type: string; + setPeriodicWave(periodicWave: PeriodicWave): void; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(): OscillatorNode; +} + +interface OverflowEvent extends UIEvent { + readonly horizontalOverflow: boolean; + readonly orient: number; + readonly verticalOverflow: boolean; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +declare var OverflowEvent: { + prototype: OverflowEvent; + new(): OverflowEvent; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +interface PageTransitionEvent extends Event { + readonly persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +} + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: string; + maxDistance: number; + panningModel: string; + refDistance: number; + rolloffFactor: number; + setOrientation(x: number, y: number, z: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(): PannerNode; +} + +interface PerfWidgetExternal { + readonly activeNetworkRequestCount: number; + readonly averageFrameTime: number; + readonly averagePaintTime: number; + readonly extraInformationEnabled: boolean; + readonly independentRenderingEnabled: boolean; + readonly irDisablingContentString: string; + readonly irStatusAvailable: boolean; + readonly maxCpuSpeed: number; + readonly paintRequestsPerSecond: number; + readonly performanceCounter: number; + readonly performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number | null): any; + getRecentFrames(last: number | null): any; + getRecentMemoryUsage(last: number | null): any; + getRecentPaintRequests(last: number | null): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +} + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +} + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +} + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +} + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: string; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +} + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(): PeriodicWave; +} + +interface PermissionRequest extends DeferredPermissionRequest { + readonly state: string; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +} + +interface PermissionRequestedEvent extends Event { + readonly permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +} + +interface Plugin { + readonly description: string; + readonly filename: string; + readonly length: number; + readonly name: string; + readonly version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +} + +interface PluginArray { + readonly length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +} + +interface PointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; +} + +interface PopStateEvent extends Event { + readonly state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +} + +interface PositionError { + readonly code: number; + readonly message: string; + toString(): string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +interface ProcessingInstruction extends CharacterData { + readonly target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +} + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; +} + +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +} + +interface RTCDtlsTransportEventMap { + "dtlsstatechange": RTCDtlsTransportStateChangedEvent; + "error": ErrorEvent; +} + +interface RTCDtlsTransport extends RTCStatsProvider { + ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: ErrorEvent) => any) | null; + readonly state: string; + readonly transport: RTCIceTransport; + getLocalParameters(): RTCDtlsParameters; + getRemoteCertificates(): ArrayBuffer[]; + getRemoteParameters(): RTCDtlsParameters | null; + start(remoteParameters: RTCDtlsParameters): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtlsTransport: { + prototype: RTCDtlsTransport; + new(transport: RTCIceTransport): RTCDtlsTransport; +} + +interface RTCDtlsTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCDtlsTransportStateChangedEvent: { + prototype: RTCDtlsTransportStateChangedEvent; + new(): RTCDtlsTransportStateChangedEvent; +} + +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDtmfSender extends EventTarget { + readonly canInsertDTMF: boolean; + readonly duration: number; + readonly interToneGap: number; + ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + readonly sender: RTCRtpSender; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtmfSender: { + prototype: RTCDtmfSender; + new(sender: RTCRtpSender): RTCDtmfSender; +} + +interface RTCIceCandidatePairChangedEvent extends Event { + readonly pair: RTCIceCandidatePair; +} + +declare var RTCIceCandidatePairChangedEvent: { + prototype: RTCIceCandidatePairChangedEvent; + new(): RTCIceCandidatePairChangedEvent; +} + +interface RTCIceGathererEventMap { + "error": ErrorEvent; + "localcandidate": RTCIceGathererEvent; +} + +interface RTCIceGatherer extends RTCStatsProvider { + readonly component: string; + onerror: ((this: RTCIceGatherer, ev: ErrorEvent) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; + createAssociatedGatherer(): RTCIceGatherer; + getLocalCandidates(): RTCIceCandidate[]; + getLocalParameters(): RTCIceParameters; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceGatherer: { + prototype: RTCIceGatherer; + new(options: RTCIceGatherOptions): RTCIceGatherer; +} + +interface RTCIceGathererEvent extends Event { + readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; +} + +declare var RTCIceGathererEvent: { + prototype: RTCIceGathererEvent; + new(): RTCIceGathererEvent; +} + +interface RTCIceTransportEventMap { + "candidatepairchange": RTCIceCandidatePairChangedEvent; + "icestatechange": RTCIceTransportStateChangedEvent; +} + +interface RTCIceTransport extends RTCStatsProvider { + readonly component: string; + readonly iceGatherer: RTCIceGatherer | null; + oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null; + onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null; + readonly role: string; + readonly state: string; + addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; + createAssociatedTransport(): RTCIceTransport; + getNominatedCandidatePair(): RTCIceCandidatePair | null; + getRemoteCandidates(): RTCIceCandidate[]; + getRemoteParameters(): RTCIceParameters | null; + setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; + start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceTransport: { + prototype: RTCIceTransport; + new(): RTCIceTransport; +} + +interface RTCIceTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCIceTransportStateChangedEvent: { + prototype: RTCIceTransportStateChangedEvent; + new(): RTCIceTransportStateChangedEvent; +} + +interface RTCRtpReceiverEventMap { + "error": ErrorEvent; +} + +interface RTCRtpReceiver extends RTCStatsProvider { + onerror: ((this: RTCRtpReceiver, ev: ErrorEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack | null; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + getContributingSources(): RTCRtpContributingSource[]; + receive(parameters: RTCRtpParameters): void; + requestSendCSRC(csrc: number): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpReceiver: { + prototype: RTCRtpReceiver; + new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCRtpSenderEventMap { + "error": ErrorEvent; + "ssrcconflict": RTCSsrcConflictEvent; +} + +interface RTCRtpSender extends RTCStatsProvider { + onerror: ((this: RTCRtpSender, ev: ErrorEvent) => any) | null; + onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + send(parameters: RTCRtpParameters): void; + setTrack(track: MediaStreamTrack): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpSender: { + prototype: RTCRtpSender; + new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCSrtpSdesTransportEventMap { + "error": ErrorEvent; +} + +interface RTCSrtpSdesTransport extends EventTarget { + onerror: ((this: RTCSrtpSdesTransport, ev: ErrorEvent) => any) | null; + readonly transport: RTCIceTransport; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCSrtpSdesTransport: { + prototype: RTCSrtpSdesTransport; + new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; + getLocalParameters(): RTCSrtpSdesParameters[]; +} + +interface RTCSsrcConflictEvent extends Event { + readonly ssrc: number; +} + +declare var RTCSsrcConflictEvent: { + prototype: RTCSsrcConflictEvent; + new(): RTCSsrcConflictEvent; +} + +interface RTCStatsProvider extends EventTarget { + getStats(): PromiseLike; + msGetStats(): PromiseLike; +} + +declare var RTCStatsProvider: { + prototype: RTCStatsProvider; + new(): RTCStatsProvider; +} + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: string): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface SVGAngle { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +interface SVGAnimatedAngle { + readonly animVal: SVGAngle; + readonly baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGAnimatedBoolean { + readonly animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGAnimatedEnumeration { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGAnimatedInteger { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGAnimatedLength { + readonly animVal: SVGLength; + readonly baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface SVGAnimatedLengthList { + readonly animVal: SVGLengthList; + readonly baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface SVGAnimatedNumber { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface SVGAnimatedNumberList { + readonly animVal: SVGNumberList; + readonly baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGAnimatedPreserveAspectRatio { + readonly animVal: SVGPreserveAspectRatio; + readonly baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface SVGAnimatedRect { + readonly animVal: SVGRect; + readonly baseVal: SVGRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface SVGAnimatedString { + readonly animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGAnimatedTransformList { + readonly animVal: SVGTransformList; + readonly baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + readonly amplitude: SVGAnimatedNumber; + readonly exponent: SVGAnimatedNumber; + readonly intercept: SVGAnimatedNumber; + readonly offset: SVGAnimatedNumber; + readonly slope: SVGAnimatedNumber; + readonly tableValues: SVGAnimatedNumberList; + readonly type: SVGAnimatedEnumeration; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface SVGElementEventMap extends ElementEventMap { + "click": MouseEvent; + "dblclick": MouseEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "load": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; +} + +interface SVGElement extends Element { + onclick: (this: SVGElement, ev: MouseEvent) => any; + ondblclick: (this: SVGElement, ev: MouseEvent) => any; + onfocusin: (this: SVGElement, ev: FocusEvent) => any; + onfocusout: (this: SVGElement, ev: FocusEvent) => any; + onload: (this: SVGElement, ev: Event) => any; + onmousedown: (this: SVGElement, ev: MouseEvent) => any; + onmousemove: (this: SVGElement, ev: MouseEvent) => any; + onmouseout: (this: SVGElement, ev: MouseEvent) => any; + onmouseover: (this: SVGElement, ev: MouseEvent) => any; + onmouseup: (this: SVGElement, ev: MouseEvent) => any; + readonly ownerSVGElement: SVGSVGElement; + readonly viewportElement: SVGElement; + xmlbase: string; + className: any; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface SVGElementInstance extends EventTarget { + readonly childNodes: SVGElementInstanceList; + readonly correspondingElement: SVGElement; + readonly correspondingUseElement: SVGUseElement; + readonly firstChild: SVGElementInstance; + readonly lastChild: SVGElementInstance; + readonly nextSibling: SVGElementInstance; + readonly parentNode: SVGElementInstance; + readonly previousSibling: SVGElementInstance; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface SVGElementInstanceList { + readonly length: number; + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly mode: SVGAnimatedEnumeration; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly type: SVGAnimatedEnumeration; + readonly values: SVGAnimatedNumberList; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly k1: SVGAnimatedNumber; + readonly k2: SVGAnimatedNumber; + readonly k3: SVGAnimatedNumber; + readonly k4: SVGAnimatedNumber; + readonly operator: SVGAnimatedEnumeration; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly bias: SVGAnimatedNumber; + readonly divisor: SVGAnimatedNumber; + readonly edgeMode: SVGAnimatedEnumeration; + readonly in1: SVGAnimatedString; + readonly kernelMatrix: SVGAnimatedNumberList; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly orderX: SVGAnimatedInteger; + readonly orderY: SVGAnimatedInteger; + readonly preserveAlpha: SVGAnimatedBoolean; + readonly targetX: SVGAnimatedInteger; + readonly targetY: SVGAnimatedInteger; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly diffuseConstant: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly scale: SVGAnimatedNumber; + readonly xChannelSelector: SVGAnimatedEnumeration; + readonly yChannelSelector: SVGAnimatedEnumeration; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; +} + +interface SVGFEDistantLightElement extends SVGElement { + readonly azimuth: SVGAnimatedNumber; + readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly stdDeviationX: SVGAnimatedNumber; + readonly stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface SVGFEMergeNodeElement extends SVGElement { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly operator: SVGAnimatedEnumeration; + readonly radiusX: SVGAnimatedNumber; + readonly radiusY: SVGAnimatedNumber; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly dx: SVGAnimatedNumber; + readonly dy: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface SVGFEPointLightElement extends SVGElement { + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly specularConstant: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface SVGFESpotLightElement extends SVGElement { + readonly limitingConeAngle: SVGAnimatedNumber; + readonly pointsAtX: SVGAnimatedNumber; + readonly pointsAtY: SVGAnimatedNumber; + readonly pointsAtZ: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly baseFrequencyX: SVGAnimatedNumber; + readonly baseFrequencyY: SVGAnimatedNumber; + readonly numOctaves: SVGAnimatedInteger; + readonly seed: SVGAnimatedNumber; + readonly stitchTiles: SVGAnimatedEnumeration; + readonly type: SVGAnimatedEnumeration; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly filterResX: SVGAnimatedInteger; + readonly filterResY: SVGAnimatedInteger; + readonly filterUnits: SVGAnimatedEnumeration; + readonly height: SVGAnimatedLength; + readonly primitiveUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { + readonly gradientTransform: SVGAnimatedTransformList; + readonly gradientUnits: SVGAnimatedEnumeration; + readonly spreadMethod: SVGAnimatedEnumeration; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface SVGLength { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +interface SVGLengthList { + readonly numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + readonly markerHeight: SVGAnimatedLength; + readonly markerUnits: SVGAnimatedEnumeration; + readonly markerWidth: SVGAnimatedLength; + readonly orientAngle: SVGAnimatedAngle; + readonly orientType: SVGAnimatedEnumeration; + readonly refX: SVGAnimatedLength; + readonly refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; +} + +interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly maskContentUnits: SVGAnimatedEnumeration; + readonly maskUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +interface SVGMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + flipX(): SVGMatrix; + flipY(): SVGMatrix; + inverse(): SVGMatrix; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + rotate(angle: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + skewX(angle: number): SVGMatrix; + skewY(angle: number): SVGMatrix; + translate(x: number, y: number): SVGMatrix; +} + +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGNumberList { + readonly numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface SVGPathSeg { + readonly pathSegType: number; + readonly pathSegTypeAsLetter: string; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface SVGPathSegList { + readonly numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly patternContentUnits: SVGAnimatedEnumeration; + readonly patternTransform: SVGAnimatedTransformList; + readonly patternUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGPoint { + x: number; + y: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} + +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface SVGPointList { + readonly numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly fx: SVGAnimatedLength; + readonly fy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface SVGRect { + height: number; + width: number; + x: number; + y: number; +} + +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + contentScriptType: string; + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: (this: SVGSVGElement, ev: Event) => any; + onerror: (this: SVGSVGElement, ev: Event) => any; + onresize: (this: SVGSVGElement, ev: UIEvent) => any; + onscroll: (this: SVGSVGElement, ev: UIEvent) => any; + onunload: (this: SVGSVGElement, ev: Event) => any; + onzoom: (this: SVGSVGElement, ev: SVGZoomEvent) => any; + readonly pixelUnitToMillimeterX: number; + readonly pixelUnitToMillimeterY: number; + readonly screenPixelToMillimeterX: number; + readonly screenPixelToMillimeterY: number; + readonly viewport: SVGRect; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + pauseAnimations(): void; + setCurrentTime(seconds: number): void; + suspendRedraw(maxWaitMilliseconds: number): number; + unpauseAnimations(): void; + unsuspendRedraw(suspendHandleID: number): void; + unsuspendRedrawAll(): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly lengthAdjust: SVGAnimatedEnumeration; + readonly textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + readonly method: SVGAnimatedEnumeration; + readonly spacing: SVGAnimatedEnumeration; + readonly startOffset: SVGAnimatedLength; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + readonly dx: SVGAnimatedLengthList; + readonly dy: SVGAnimatedLengthList; + readonly rotate: SVGAnimatedNumberList; + readonly x: SVGAnimatedLengthList; + readonly y: SVGAnimatedLengthList; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface SVGTransform { + readonly angle: number; + readonly matrix: SVGMatrix; + readonly type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +interface SVGTransformList { + readonly numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGUnitTypes { + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: SVGUnitTypes; + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly animatedInstanceRoot: SVGElementInstance; + readonly height: SVGAnimatedLength; + readonly instanceRoot: SVGElementInstance; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface SVGZoomAndPan { + readonly zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +} + +interface SVGZoomEvent extends UIEvent { + readonly newScale: number; + readonly newTranslate: SVGPoint; + readonly previousScale: number; + readonly previousTranslate: SVGPoint; + readonly zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +} + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +} + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: string; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +} + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +} + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface StorageEvent extends Event { + readonly url: string; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface SubtleCrypto { + 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: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +} + +interface Text extends CharacterData { + readonly wholeText: string; + readonly assignedSlot: HTMLSlotElement | null; + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(): Text; +} + +interface TextEvent extends UIEvent { + readonly data: string; + readonly inputMethod: number; + readonly locale: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +interface TextMetrics { + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface TextTrackEventMap { + "cuechange": Event; + "error": ErrorEvent; + "load": Event; +} + +interface TextTrack extends EventTarget { + readonly activeCues: TextTrackCueList; + readonly cues: TextTrackCueList; + readonly inBandMetadataTrackDispatchType: string; + readonly kind: string; + readonly label: string; + readonly language: string; + mode: any; + oncuechange: (this: TextTrack, ev: Event) => any; + onerror: (this: TextTrack, ev: ErrorEvent) => any; + onload: (this: TextTrack, ev: Event) => any; + readonly readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; +} + +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: (this: TextTrackCue, ev: Event) => any; + onexit: (this: TextTrackCue, ev: Event) => any; + pauseOnExit: boolean; + startTime: number; + text: string; + readonly track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +} + +interface TextTrackCueList { + readonly length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + +interface TextTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; + item(index: number): TextTrack; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface TimeRanges { + readonly length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface Touch { + readonly clientX: number; + readonly clientY: number; + readonly identifier: number; + readonly pageX: number; + readonly pageY: number; + readonly screenX: number; + readonly screenY: number; + readonly target: EventTarget; +} + +declare var Touch: { + prototype: Touch; + new(): Touch; +} + +interface TouchEvent extends UIEvent { + readonly altKey: boolean; + readonly changedTouches: TouchList; + readonly ctrlKey: boolean; + readonly metaKey: boolean; + readonly shiftKey: boolean; + readonly targetTouches: TouchList; + readonly touches: TouchList; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(): TouchEvent; +} + +interface TouchList { + readonly length: number; + item(index: number): Touch | null; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +} + +interface TrackEvent extends Event { + readonly track: any; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface TransitionEvent extends Event { + readonly elapsedTime: number; + readonly propertyName: string; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface TreeWalker { + currentNode: Node; + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + firstChild(): Node; + lastChild(): Node; + nextNode(): Node; + nextSibling(): Node; + parentNode(): Node; + previousNode(): Node; + previousSibling(): Node; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface UIEvent extends Event { + readonly detail: number; + readonly view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(type: string, eventInitDict?: UIEventInit): UIEvent; +} + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + username: string; + toString(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string): URL; + createObjectURL(object: any, options?: ObjectURLOptions): string; + revokeObjectURL(url: string): void; +} + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; +} + +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +} + +interface ValidityState { + readonly badInput: boolean; + readonly customError: boolean; + readonly patternMismatch: boolean; + readonly rangeOverflow: boolean; + readonly rangeUnderflow: boolean; + readonly stepMismatch: boolean; + readonly tooLong: boolean; + readonly typeMismatch: boolean; + readonly valid: boolean; + readonly valueMissing: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface VideoPlaybackQuality { + readonly corruptedVideoFrames: number; + readonly creationTime: number; + readonly droppedVideoFrames: number; + readonly totalFrameDelay: number; + readonly totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +} + +interface VideoTrack { + readonly id: string; + kind: string; + readonly label: string; + language: string; + selected: boolean; + readonly sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +} + +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface VideoTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: VideoTrackList, ev: TrackEvent) => any; + onchange: (this: VideoTrackList, ev: Event) => any; + onremovetrack: (this: VideoTrackList, ev: TrackEvent) => any; + readonly selectedIndex: number; + getTrackById(id: string): VideoTrack | null; + item(index: number): VideoTrack; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +interface WaveShaperNode extends AudioNode { + curve: Float32Array | null; + oversample: string; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(): WaveShaperNode; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: number; + readonly type: number; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +} + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +} + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +} + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +} + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +} + +interface WebGLRenderingContext { + readonly canvas: HTMLCanvasElement; + readonly drawingBufferHeight: number; + readonly drawingBufferWidth: number; + activeTexture(texture: number): void; + attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; + bindBuffer(target: number, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: number, texture: WebGLTexture | null): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + blendEquation(mode: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + blendFunc(sfactor: number, dfactor: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; + checkFramebufferStatus(target: number): number; + clear(mask: number): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + clearDepth(depth: number): void; + clearStencil(s: number): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compileShader(shader: WebGLShader | null): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: number): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: number): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: number): void; + depthMask(flag: boolean): void; + depthRange(zNear: number, zFar: number): void; + detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + disable(cap: number): void; + disableVertexAttribArray(index: number): void; + drawArrays(mode: number, first: number, count: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + enable(cap: number): void; + enableVertexAttribArray(index: number): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; + frontFace(mode: number): void; + generateMipmap(target: number): void; + getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram | null, name: string): number; + getBufferParameter(target: number, pname: number): any; + getContextAttributes(): WebGLContextAttributes; + getError(): number; + getExtension(name: string): any; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + getParameter(pname: number): any; + getProgramInfoLog(program: WebGLProgram | null): string | null; + getProgramParameter(program: WebGLProgram | null, pname: number): any; + getRenderbufferParameter(target: number, pname: number): any; + getShaderInfoLog(shader: WebGLShader | null): string | null; + getShaderParameter(shader: WebGLShader | null, pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader | null): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: number, pname: number): any; + getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; + getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: number, pname: number): any; + getVertexAttribOffset(index: number, pname: number): number; + hint(target: number, mode: number): void; + isBuffer(buffer: WebGLBuffer | null): boolean; + isContextLost(): boolean; + isEnabled(cap: number): boolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; + isProgram(program: WebGLProgram | null): boolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; + isShader(shader: WebGLShader | null): boolean; + isTexture(texture: WebGLTexture | null): boolean; + lineWidth(width: number): void; + linkProgram(program: WebGLProgram | null): void; + pixelStorei(pname: number, param: number): void; + polygonOffset(factor: number, units: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + sampleCoverage(value: number, invert: boolean): void; + scissor(x: number, y: number, width: number, height: number): void; + shaderSource(shader: WebGLShader | null, source: string): void; + stencilFunc(func: number, ref: number, mask: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + stencilMask(mask: number): void; + 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, 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, 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; + uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram | null): void; + vertexAttrib1f(indx: number, x: number): void; + vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib2f(indx: number, x: number, y: number): void; + vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + viewport(x: number, y: number, width: number, height: number): void; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +} + +interface WebGLShaderPrecisionFormat { + readonly precision: number; + readonly rangeMax: number; + readonly rangeMin: number; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +} + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +} + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +} + +interface WebKitCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): WebKitCSSMatrix; + multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): WebKitCSSMatrix; + skewY(angle: number): WebKitCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): WebKitCSSMatrix; +} + +declare var WebKitCSSMatrix: { + prototype: WebKitCSSMatrix; + new(text?: string): WebKitCSSMatrix; +} + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +} + +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +} + +interface WheelEvent extends MouseEvent { + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + readonly wheelDelta: number; + readonly wheelDeltaX: number; + readonly wheelDeltaY: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +interface WindowEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "unload": Event; + "volumechange": Event; + "waiting": Event; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { + readonly applicationCache: ApplicationCache; + readonly clientInformation: Navigator; + readonly closed: boolean; + readonly crypto: Crypto; + defaultStatus: string; + readonly devicePixelRatio: number; + readonly doNotTrack: string; + readonly document: Document; + event: Event | undefined; + readonly external: External; + readonly frameElement: Element; + readonly frames: Window; + readonly history: History; + readonly innerHeight: number; + readonly innerWidth: number; + readonly length: number; + readonly location: Location; + readonly locationbar: BarProp; + readonly menubar: BarProp; + readonly msCredentials: MSCredentials; + name: string; + readonly navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (this: Window, ev: UIEvent) => any; + onafterprint: (this: Window, ev: Event) => any; + onbeforeprint: (this: Window, ev: Event) => any; + onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; + onblur: (this: Window, ev: FocusEvent) => any; + oncanplay: (this: Window, ev: Event) => any; + oncanplaythrough: (this: Window, ev: Event) => any; + onchange: (this: Window, ev: Event) => any; + onclick: (this: Window, ev: MouseEvent) => any; + oncompassneedscalibration: (this: Window, ev: Event) => any; + oncontextmenu: (this: Window, ev: PointerEvent) => any; + ondblclick: (this: Window, ev: MouseEvent) => any; + ondevicelight: (this: Window, ev: DeviceLightEvent) => any; + ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; + ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; + ondrag: (this: Window, ev: DragEvent) => any; + ondragend: (this: Window, ev: DragEvent) => any; + ondragenter: (this: Window, ev: DragEvent) => any; + ondragleave: (this: Window, ev: DragEvent) => any; + ondragover: (this: Window, ev: DragEvent) => any; + ondragstart: (this: Window, ev: DragEvent) => any; + ondrop: (this: Window, ev: DragEvent) => any; + ondurationchange: (this: Window, ev: Event) => any; + onemptied: (this: Window, ev: Event) => any; + onended: (this: Window, ev: MediaStreamErrorEvent) => any; + onerror: ErrorEventHandler; + onfocus: (this: Window, ev: FocusEvent) => any; + onhashchange: (this: Window, ev: HashChangeEvent) => any; + oninput: (this: Window, ev: Event) => any; + oninvalid: (this: Window, ev: Event) => any; + onkeydown: (this: Window, ev: KeyboardEvent) => any; + onkeypress: (this: Window, ev: KeyboardEvent) => any; + onkeyup: (this: Window, ev: KeyboardEvent) => any; + onload: (this: Window, ev: Event) => any; + onloadeddata: (this: Window, ev: Event) => any; + onloadedmetadata: (this: Window, ev: Event) => any; + onloadstart: (this: Window, ev: Event) => any; + onmessage: (this: Window, ev: MessageEvent) => any; + onmousedown: (this: Window, ev: MouseEvent) => any; + onmouseenter: (this: Window, ev: MouseEvent) => any; + onmouseleave: (this: Window, ev: MouseEvent) => any; + onmousemove: (this: Window, ev: MouseEvent) => any; + onmouseout: (this: Window, ev: MouseEvent) => any; + onmouseover: (this: Window, ev: MouseEvent) => any; + onmouseup: (this: Window, ev: MouseEvent) => any; + onmousewheel: (this: Window, ev: WheelEvent) => any; + onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; + onmsgestureend: (this: Window, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; + onmspointercancel: (this: Window, ev: MSPointerEvent) => any; + onmspointerdown: (this: Window, ev: MSPointerEvent) => any; + onmspointerenter: (this: Window, ev: MSPointerEvent) => any; + onmspointerleave: (this: Window, ev: MSPointerEvent) => any; + onmspointermove: (this: Window, ev: MSPointerEvent) => any; + onmspointerout: (this: Window, ev: MSPointerEvent) => any; + onmspointerover: (this: Window, ev: MSPointerEvent) => any; + onmspointerup: (this: Window, ev: MSPointerEvent) => any; + onoffline: (this: Window, ev: Event) => any; + ononline: (this: Window, ev: Event) => any; + onorientationchange: (this: Window, ev: Event) => any; + onpagehide: (this: Window, ev: PageTransitionEvent) => any; + onpageshow: (this: Window, ev: PageTransitionEvent) => any; + onpause: (this: Window, ev: Event) => any; + onplay: (this: Window, ev: Event) => any; + onplaying: (this: Window, ev: Event) => any; + onpopstate: (this: Window, ev: PopStateEvent) => any; + onprogress: (this: Window, ev: ProgressEvent) => any; + onratechange: (this: Window, ev: Event) => any; + onreadystatechange: (this: Window, ev: ProgressEvent) => any; + onreset: (this: Window, ev: Event) => any; + onresize: (this: Window, ev: UIEvent) => any; + onscroll: (this: Window, ev: UIEvent) => any; + onseeked: (this: Window, ev: Event) => any; + onseeking: (this: Window, ev: Event) => any; + onselect: (this: Window, ev: UIEvent) => any; + onstalled: (this: Window, ev: Event) => any; + onstorage: (this: Window, ev: StorageEvent) => any; + onsubmit: (this: Window, ev: Event) => any; + onsuspend: (this: Window, ev: Event) => any; + ontimeupdate: (this: Window, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onunload: (this: Window, ev: Event) => any; + onvolumechange: (this: Window, ev: Event) => any; + onwaiting: (this: Window, ev: Event) => any; + opener: any; + orientation: string | number; + readonly outerHeight: number; + readonly outerWidth: number; + readonly pageXOffset: number; + readonly pageYOffset: number; + readonly parent: Window; + readonly performance: Performance; + readonly personalbar: BarProp; + readonly screen: Screen; + readonly screenLeft: number; + readonly screenTop: number; + readonly screenX: number; + readonly screenY: number; + readonly scrollX: number; + readonly scrollY: number; + readonly scrollbars: BarProp; + readonly self: Window; + status: string; + readonly statusbar: BarProp; + readonly styleMedia: StyleMedia; + readonly toolbar: BarProp; + readonly top: Window; + readonly window: Window; + URL: typeof URL; + Blob: typeof Blob; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + matchMedia(mediaQuery: string): MediaQueryList; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: any, targetOrigin: string, transfer?: any[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + webkitCancelAnimationFrame(handle: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Window: { + prototype: Window; + new(): Window; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (this: Worker, ev: MessageEvent) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +} + +interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: string; + readonly responseXML: any; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + msCaching?: string; + readonly responseURL: string; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: Document): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + create(): XMLHttpRequest; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +} + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +} + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +} + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +} + +interface XPathResult { + readonly booleanValue: boolean; + readonly invalidIteratorState: boolean; + readonly numberValue: number; + readonly resultType: number; + readonly singleNodeValue: Node; + readonly snapshotLength: number; + readonly stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +} + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface CanvasPathMethods { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface ChildNode { + remove(): void; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DocumentEvent { + createEvent(eventInterface:"AnimationEvent"): AnimationEvent; + createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; + createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface:"CloseEvent"): CloseEvent; + createEvent(eventInterface:"CommandEvent"): CommandEvent; + createEvent(eventInterface:"CompositionEvent"): CompositionEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; + createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface:"DragEvent"): DragEvent; + createEvent(eventInterface:"ErrorEvent"): ErrorEvent; + createEvent(eventInterface:"Event"): Event; + createEvent(eventInterface:"Events"): Event; + createEvent(eventInterface:"FocusEvent"): FocusEvent; + createEvent(eventInterface:"GamepadEvent"): GamepadEvent; + createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface:"MessageEvent"): MessageEvent; + createEvent(eventInterface:"MouseEvent"): MouseEvent; + createEvent(eventInterface:"MouseEvents"): MouseEvent; + createEvent(eventInterface:"MutationEvent"): MutationEvent; + createEvent(eventInterface:"MutationEvents"): MutationEvent; + createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface:"NavigationEvent"): NavigationEvent; + createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface:"OverflowEvent"): OverflowEvent; + createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface:"PointerEvent"): PointerEvent; + createEvent(eventInterface:"PopStateEvent"): PopStateEvent; + createEvent(eventInterface:"ProgressEvent"): ProgressEvent; + createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface:"StorageEvent"): StorageEvent; + createEvent(eventInterface:"TextEvent"): TextEvent; + createEvent(eventInterface:"TouchEvent"): TouchEvent; + createEvent(eventInterface:"TrackEvent"): TrackEvent; + createEvent(eventInterface:"TransitionEvent"): TransitionEvent; + createEvent(eventInterface:"UIEvent"): UIEvent; + createEvent(eventInterface:"UIEvents"): UIEvent; + createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface:"WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly nextElementSibling: Element; + readonly previousElementSibling: Element; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + onpointercancel: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerdown: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerenter: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerleave: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointermove: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerout: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; +} + +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + +interface LinkStyle { + readonly sheet: StyleSheet; +} + +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSBaseReader { + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; + readonly readyState: number; + readonly result: any; + abort(): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface NavigatorContentUtils { +} + +interface NavigatorGeolocation { + readonly geolocation: Geolocation; +} + +interface NavigatorID { + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + +interface NodeSelector { + querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: string): Element | null; + querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: string): NodeListOf; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface SVGAnimatedPathData { + readonly pathSegList: SVGPathSegList; +} + +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + +interface SVGExternalResourcesRequired { + readonly externalResourcesRequired: SVGAnimatedBoolean; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + readonly height: SVGAnimatedLength; + readonly result: SVGAnimatedString; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly viewBox: SVGAnimatedRect; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface SVGLocatable { + readonly farthestViewportElement: SVGElement; + readonly nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; + getTransformToElement(element: SVGElement): SVGMatrix; +} + +interface SVGStylable { + className: any; + readonly style: CSSStyleDeclaration; +} + +interface SVGTests { + readonly requiredExtensions: SVGStringList; + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface SVGTransformable extends SVGLocatable { + readonly transform: SVGAnimatedTransformList; +} + +interface SVGURIReference { + readonly href: SVGAnimatedString; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +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(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + 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; + [index: number]: TNode; +} + +interface HTMLCollectionOf extends HTMLCollection { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag { + type?: string; + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface MessageEventInit extends EventInit { + data?: any; + origin?: string; + lastEventId?: string; + channel?: string; + source?: any; + ports?: MessagePort[]; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +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 { + namedCurve: 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; +} + +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly stylesheets: StyleSheetList; + getSelection(): Selection | null; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; +} + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + mode: 'open'|'closed'; + delegatesFocus?: boolean; +} + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface ErrorEventHandler { + (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSLaunchUriCallback { + (): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface ForEachCallback { + (keyId: any, status: string): void; +} +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "audio": HTMLAudioElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "del": HTMLModElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "font": HTMLFontElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nextid": HTMLUnknownElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "script": HTMLScriptElement; + "select": HTMLSelectElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "style": HTMLStyleElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "ul": HTMLUListElement; + "video": HTMLVideoElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "circle": SVGCircleElement; + "cite": HTMLElement; + "clippath": SVGClipPathElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "defs": SVGDefsElement; + "del": HTMLModElement; + "desc": SVGDescElement; + "dfn": HTMLElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "ellipse": SVGEllipseElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "feblend": SVGFEBlendElement; + "fecolormatrix": SVGFEColorMatrixElement; + "fecomponenttransfer": SVGFEComponentTransferElement; + "fecomposite": SVGFECompositeElement; + "feconvolvematrix": SVGFEConvolveMatrixElement; + "fediffuselighting": SVGFEDiffuseLightingElement; + "fedisplacementmap": SVGFEDisplacementMapElement; + "fedistantlight": SVGFEDistantLightElement; + "feflood": SVGFEFloodElement; + "fefunca": SVGFEFuncAElement; + "fefuncb": SVGFEFuncBElement; + "fefuncg": SVGFEFuncGElement; + "fefuncr": SVGFEFuncRElement; + "fegaussianblur": SVGFEGaussianBlurElement; + "feimage": SVGFEImageElement; + "femerge": SVGFEMergeElement; + "femergenode": SVGFEMergeNodeElement; + "femorphology": SVGFEMorphologyElement; + "feoffset": SVGFEOffsetElement; + "fepointlight": SVGFEPointLightElement; + "fespecularlighting": SVGFESpecularLightingElement; + "fespotlight": SVGFESpotLightElement; + "fetile": SVGFETileElement; + "feturbulence": SVGFETurbulenceElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "filter": SVGFilterElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "foreignobject": SVGForeignObjectElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "g": SVGGElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "image": SVGImageElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "line": SVGLineElement; + "lineargradient": SVGLinearGradientElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marker": SVGMarkerElement; + "marquee": HTMLMarqueeElement; + "mask": SVGMaskElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "metadata": SVGMetadataElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "picture": HTMLPictureElement; + "plaintext": HTMLElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "radialgradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "stop": SVGStopElement; + "strike": HTMLElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "text": SVGTextElement; + "textpath": SVGTextPathElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "tspan": SVGTSpanElement; + "tt": HTMLElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "use": SVGUseElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "view": SVGViewElement; + "wbr": HTMLElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementListTagNameMap { + "a": NodeListOf; + "abbr": NodeListOf; + "acronym": NodeListOf; + "address": NodeListOf; + "applet": NodeListOf; + "area": NodeListOf; + "article": NodeListOf; + "aside": NodeListOf; + "audio": NodeListOf; + "b": NodeListOf; + "base": NodeListOf; + "basefont": NodeListOf; + "bdo": NodeListOf; + "big": NodeListOf; + "blockquote": NodeListOf; + "body": NodeListOf; + "br": NodeListOf; + "button": NodeListOf; + "canvas": NodeListOf; + "caption": NodeListOf; + "center": NodeListOf; + "circle": NodeListOf; + "cite": NodeListOf; + "clippath": NodeListOf; + "code": NodeListOf; + "col": NodeListOf; + "colgroup": NodeListOf; + "datalist": NodeListOf; + "dd": NodeListOf; + "defs": NodeListOf; + "del": NodeListOf; + "desc": NodeListOf; + "dfn": NodeListOf; + "dir": NodeListOf; + "div": NodeListOf; + "dl": NodeListOf; + "dt": NodeListOf; + "ellipse": NodeListOf; + "em": NodeListOf; + "embed": NodeListOf; + "feblend": NodeListOf; + "fecolormatrix": NodeListOf; + "fecomponenttransfer": NodeListOf; + "fecomposite": NodeListOf; + "feconvolvematrix": NodeListOf; + "fediffuselighting": NodeListOf; + "fedisplacementmap": NodeListOf; + "fedistantlight": NodeListOf; + "feflood": NodeListOf; + "fefunca": NodeListOf; + "fefuncb": NodeListOf; + "fefuncg": NodeListOf; + "fefuncr": NodeListOf; + "fegaussianblur": NodeListOf; + "feimage": NodeListOf; + "femerge": NodeListOf; + "femergenode": NodeListOf; + "femorphology": NodeListOf; + "feoffset": NodeListOf; + "fepointlight": NodeListOf; + "fespecularlighting": NodeListOf; + "fespotlight": NodeListOf; + "fetile": NodeListOf; + "feturbulence": NodeListOf; + "fieldset": NodeListOf; + "figcaption": NodeListOf; + "figure": NodeListOf; + "filter": NodeListOf; + "font": NodeListOf; + "footer": NodeListOf; + "foreignobject": NodeListOf; + "form": NodeListOf; + "frame": NodeListOf; + "frameset": NodeListOf; + "g": NodeListOf; + "h1": NodeListOf; + "h2": NodeListOf; + "h3": NodeListOf; + "h4": NodeListOf; + "h5": NodeListOf; + "h6": NodeListOf; + "head": NodeListOf; + "header": NodeListOf; + "hgroup": NodeListOf; + "hr": NodeListOf; + "html": NodeListOf; + "i": NodeListOf; + "iframe": NodeListOf; + "image": NodeListOf; + "img": NodeListOf; + "input": NodeListOf; + "ins": NodeListOf; + "isindex": NodeListOf; + "kbd": NodeListOf; + "keygen": NodeListOf; + "label": NodeListOf; + "legend": NodeListOf; + "li": NodeListOf; + "line": NodeListOf; + "lineargradient": NodeListOf; + "link": NodeListOf; + "listing": NodeListOf; + "map": NodeListOf; + "mark": NodeListOf; + "marker": NodeListOf; + "marquee": NodeListOf; + "mask": NodeListOf; + "menu": NodeListOf; + "meta": NodeListOf; + "metadata": NodeListOf; + "meter": NodeListOf; + "nav": NodeListOf; + "nextid": NodeListOf; + "nobr": NodeListOf; + "noframes": NodeListOf; + "noscript": NodeListOf; + "object": NodeListOf; + "ol": NodeListOf; + "optgroup": NodeListOf; + "option": NodeListOf; + "p": NodeListOf; + "param": NodeListOf; + "path": NodeListOf; + "pattern": NodeListOf; + "picture": NodeListOf; + "plaintext": NodeListOf; + "polygon": NodeListOf; + "polyline": NodeListOf; + "pre": NodeListOf; + "progress": NodeListOf; + "q": NodeListOf; + "radialgradient": NodeListOf; + "rect": NodeListOf; + "rt": NodeListOf; + "ruby": NodeListOf; + "s": NodeListOf; + "samp": NodeListOf; + "script": NodeListOf; + "section": NodeListOf; + "select": NodeListOf; + "small": NodeListOf; + "source": NodeListOf; + "span": NodeListOf; + "stop": NodeListOf; + "strike": NodeListOf; + "strong": NodeListOf; + "style": NodeListOf; + "sub": NodeListOf; + "sup": NodeListOf; + "svg": NodeListOf; + "switch": NodeListOf; + "symbol": NodeListOf; + "table": NodeListOf; + "tbody": NodeListOf; + "td": NodeListOf; + "template": NodeListOf; + "text": NodeListOf; + "textpath": NodeListOf; + "textarea": NodeListOf; + "tfoot": NodeListOf; + "th": NodeListOf; + "thead": NodeListOf; + "title": NodeListOf; + "tr": NodeListOf; + "track": NodeListOf; + "tspan": NodeListOf; + "tt": NodeListOf; + "u": NodeListOf; + "ul": NodeListOf; + "use": NodeListOf; + "var": NodeListOf; + "video": NodeListOf; + "view": NodeListOf; + "wbr": NodeListOf; + "x-ms-webview": NodeListOf; + "xmp": NodeListOf; +} + +declare var Audio: {new(src?: string): HTMLAudioElement; }; +declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var applicationCache: ApplicationCache; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var doNotTrack: string; +declare var document: Document; +declare var event: Event | undefined; +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msCredentials: MSCredentials; +declare const name: never; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var onabort: (this: Window, ev: UIEvent) => any; +declare var onafterprint: (this: Window, ev: Event) => any; +declare var onbeforeprint: (this: Window, ev: Event) => any; +declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; +declare var onblur: (this: Window, ev: FocusEvent) => any; +declare var oncanplay: (this: Window, ev: Event) => any; +declare var oncanplaythrough: (this: Window, ev: Event) => any; +declare var onchange: (this: Window, ev: Event) => any; +declare var onclick: (this: Window, ev: MouseEvent) => any; +declare var oncompassneedscalibration: (this: Window, ev: Event) => any; +declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; +declare var ondblclick: (this: Window, ev: MouseEvent) => any; +declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; +declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; +declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; +declare var ondrag: (this: Window, ev: DragEvent) => any; +declare var ondragend: (this: Window, ev: DragEvent) => any; +declare var ondragenter: (this: Window, ev: DragEvent) => any; +declare var ondragleave: (this: Window, ev: DragEvent) => any; +declare var ondragover: (this: Window, ev: DragEvent) => any; +declare var ondragstart: (this: Window, ev: DragEvent) => any; +declare var ondrop: (this: Window, ev: DragEvent) => any; +declare var ondurationchange: (this: Window, ev: Event) => any; +declare var onemptied: (this: Window, ev: Event) => any; +declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; +declare var onerror: ErrorEventHandler; +declare var onfocus: (this: Window, ev: FocusEvent) => any; +declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; +declare var oninput: (this: Window, ev: Event) => any; +declare var oninvalid: (this: Window, ev: Event) => any; +declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; +declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; +declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; +declare var onload: (this: Window, ev: Event) => any; +declare var onloadeddata: (this: Window, ev: Event) => any; +declare var onloadedmetadata: (this: Window, ev: Event) => any; +declare var onloadstart: (this: Window, ev: Event) => any; +declare var onmessage: (this: Window, ev: MessageEvent) => any; +declare var onmousedown: (this: Window, ev: MouseEvent) => any; +declare var onmouseenter: (this: Window, ev: MouseEvent) => any; +declare var onmouseleave: (this: Window, ev: MouseEvent) => any; +declare var onmousemove: (this: Window, ev: MouseEvent) => any; +declare var onmouseout: (this: Window, ev: MouseEvent) => any; +declare var onmouseover: (this: Window, ev: MouseEvent) => any; +declare var onmouseup: (this: Window, ev: MouseEvent) => any; +declare var onmousewheel: (this: Window, ev: WheelEvent) => any; +declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; +declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; +declare var onoffline: (this: Window, ev: Event) => any; +declare var ononline: (this: Window, ev: Event) => any; +declare var onorientationchange: (this: Window, ev: Event) => any; +declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; +declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; +declare var onpause: (this: Window, ev: Event) => any; +declare var onplay: (this: Window, ev: Event) => any; +declare var onplaying: (this: Window, ev: Event) => any; +declare var onpopstate: (this: Window, ev: PopStateEvent) => any; +declare var onprogress: (this: Window, ev: ProgressEvent) => any; +declare var onratechange: (this: Window, ev: Event) => any; +declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; +declare var onreset: (this: Window, ev: Event) => any; +declare var onresize: (this: Window, ev: UIEvent) => any; +declare var onscroll: (this: Window, ev: UIEvent) => any; +declare var onseeked: (this: Window, ev: Event) => any; +declare var onseeking: (this: Window, ev: Event) => any; +declare var onselect: (this: Window, ev: UIEvent) => any; +declare var onstalled: (this: Window, ev: Event) => any; +declare var onstorage: (this: Window, ev: StorageEvent) => any; +declare var onsubmit: (this: Window, ev: Event) => any; +declare var onsuspend: (this: Window, ev: Event) => any; +declare var ontimeupdate: (this: Window, ev: Event) => any; +declare var ontouchcancel: (ev: TouchEvent) => any; +declare var ontouchend: (ev: TouchEvent) => any; +declare var ontouchmove: (ev: TouchEvent) => any; +declare var ontouchstart: (ev: TouchEvent) => any; +declare var onunload: (this: Window, ev: Event) => any; +declare var onvolumechange: (this: Window, ev: Event) => any; +declare var onwaiting: (this: Window, ev: Event) => any; +declare var opener: any; +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollX: number; +declare var scrollY: number; +declare var scrollbars: BarProp; +declare var self: Window; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function moveBy(x?: number, y?: number): void; +declare function moveTo(x?: number, y?: number): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string | null; +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x?: number, y?: number): void; +declare function resizeTo(x?: number, y?: number): void; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare function webkitCancelAnimationFrame(handle: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; +declare function toString(): string; +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(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; +declare var onpointercancel: (this: Window, ev: PointerEvent) => any; +declare var onpointerdown: (this: Window, ev: PointerEvent) => any; +declare var onpointerenter: (this: Window, ev: PointerEvent) => any; +declare var onpointerleave: (this: Window, ev: PointerEvent) => any; +declare var onpointermove: (this: Window, ev: PointerEvent) => any; +declare var onpointerout: (this: Window, ev: PointerEvent) => any; +declare var onpointerover: (this: Window, ev: PointerEvent) => any; +declare var onpointerup: (this: Window, ev: PointerEvent) => any; +declare var onwheel: (this: Window, ev: WheelEvent) => any; +declare var indexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +type AAGUID = string; +type AlgorithmIdentifier = string | Algorithm; +type ConstrainBoolean = boolean | ConstrainBooleanParameters; +type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; +type ConstrainDouble = number | ConstrainDoubleRange; +type ConstrainLong = number | ConstrainLongRange; +type CryptoOperationData = ArrayBufferView; +type GLbitfield = number; +type GLboolean = boolean; +type GLbyte = number; +type GLclampf = number; +type GLenum = number; +type GLfloat = number; +type GLint = number; +type GLintptr = number; +type GLshort = number; +type GLsizei = number; +type GLsizeiptr = number; +type GLubyte = number; +type GLuint = number; +type GLushort = number; +type IDBKeyPath = string; +type KeyFormat = string; +type KeyType = string; +type KeyUsage = string; +type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; +type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; +type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; +type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; +type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// These are only available in a Web Worker +declare function importScripts(...urls: string[]): void; + + + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (collection: any): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: any): VBArray; + new (safeArray: any): VBArray; +} + +declare var VBArray: VBArrayConstructor; + +/** + * Automation date (VT_DATE) + */ +interface VarDate { } + +interface DateConstructor { + new (vd: VarDate): Date; +} + +interface Date { + getVarDate: () => VarDate; +} diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 4e45a38c17e..6ee35cd6589 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -1,14641 +1,13738 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// - -///////////////////////////// -/// IE DOM APIs -///////////////////////////// - -interface Algorithm { - name: string; -} - -interface AriaRequestEventInit extends EventInit { - attributeName?: string; - attributeValue?: string; -} - -interface CommandEventInit extends EventInit { - commandName?: string; - detail?: string; -} - -interface CompositionEventInit extends UIEventInit { - data?: string; -} - -interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { - arrayOfDomainStrings?: string[]; -} - -interface ConstrainBooleanParameters { - exact?: boolean; - ideal?: boolean; -} - -interface ConstrainDOMStringParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface ConstrainDoubleRange extends DoubleRange { - exact?: number; - ideal?: number; -} - -interface ConstrainLongRange extends LongRange { - exact?: number; - ideal?: number; -} - -interface ConstrainVideoFacingModeParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface CustomEventInit extends EventInit { - detail?: any; -} - -interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; -} - -interface DeviceLightEventInit extends EventInit { - value?: number; -} - -interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; -} - -interface DoubleRange { - max?: number; - min?: number; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; -} - -interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; - altKey?: boolean; - metaKey?: boolean; - modifierAltGraph?: boolean; - modifierCapsLock?: boolean; - modifierFn?: boolean; - modifierFnLock?: boolean; - modifierHyper?: boolean; - modifierNumLock?: boolean; - modifierOS?: boolean; - modifierScrollLock?: boolean; - modifierSuper?: boolean; - modifierSymbol?: boolean; - modifierSymbolLock?: boolean; -} - -interface ExceptionInformation { - domain?: string; -} - -interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; -} - -interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; -} - -interface IDBIndexParameters { - multiEntry?: boolean; - unique?: boolean; -} - -interface IDBObjectStoreParameters { - autoIncrement?: boolean; - keyPath?: IDBKeyPath; -} - -interface KeyAlgorithm { - name?: string; -} - -interface KeyboardEventInit extends EventModifierInit { - code?: string; - key?: string; - location?: number; - repeat?: boolean; -} - -interface LongRange { - max?: number; - min?: number; -} - -interface MSAccountInfo { - rpDisplayName?: string; - userDisplayName?: string; - accountName?: string; - userId?: string; - accountImageUri?: string; -} - -interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; - cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; - deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; - deviceClippingEventRatio?: number; - deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; - deviceHowlingEventCount?: number; -} - -interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; - burstLossLength1?: number; - burstLossLength2?: number; - burstLossLength3?: number; - burstLossLength4?: number; - burstLossLength5?: number; - burstLossLength6?: number; - burstLossLength7?: number; - burstLossLength8OrHigher?: number; - fecRecvDistance1?: number; - fecRecvDistance2?: number; - fecRecvDistance3?: number; - ratioConcealedSamplesAvg?: number; - ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; -} - -interface MSAudioRecvSignal { - initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; - recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; - renderLoopbackSignalLevel?: number; -} - -interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; - audioFECUsed?: boolean; - sendMutePercent?: number; -} - -interface MSAudioSendSignal { - noiseLevel?: number; - sendSignalLevelCh1?: number; - sendNoiseLevelCh1?: number; -} - -interface MSConnectivity { - iceType?: string; - iceWarningFlags?: MSIceWarningFlags; - relayAddress?: MSRelayAddress; -} - -interface MSCredentialFilter { - accept?: MSCredentialSpec[]; -} - -interface MSCredentialParameters { - type?: string; -} - -interface MSCredentialSpec { - type?: string; - id?: string; -} - -interface MSDelay { - roundTrip?: number; - roundTripMax?: number; -} - -interface MSDescription extends RTCStats { - connectivity?: MSConnectivity; - transport?: string; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; - deviceDevName?: string; - reflexiveLocalIPAddr?: MSIPAddressInfo; -} - -interface MSFIDOCredentialParameters extends MSCredentialParameters { - algorithm?: string | Algorithm; - authenticators?: AAGUID[]; -} - -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - -interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; - turnTcpAllocateFailed?: boolean; - turnTcpSendFailed?: boolean; - udpLocalConnectivityFailed?: boolean; - udpNatConnectivityFailed?: boolean; - udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; - useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; -} - -interface MSJitter { - interArrival?: number; - interArrivalMax?: number; - interArrivalSD?: number; -} - -interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; - networkBandwidthLowEventRatio?: number; -} - -interface MSNetwork extends RTCStats { - jitter?: MSJitter; - delay?: MSDelay; - packetLoss?: MSPacketLoss; - utilization?: MSUtilization; -} - -interface MSNetworkConnectivityInfo { - vpn?: boolean; - linkspeed?: number; - networkConnectionDetails?: string; -} - -interface MSNetworkInterfaceType { - interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; - interfaceTypePPP?: boolean; - interfaceTypeTunnel?: boolean; - interfaceTypeWWAN?: boolean; -} - -interface MSOutboundNetwork extends MSNetwork { - appliedBandwidthLimit?: number; -} - -interface MSPacketLoss { - lossRate?: number; - lossRateMax?: number; -} - -interface MSPayloadBase extends RTCStats { - payloadDescription?: string; -} - -interface MSRelayAddress { - relayAddress?: string; - port?: number; -} - -interface MSSignatureParameters { - userPrompt?: string; -} - -interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: string; - localInterface?: MSNetworkInterfaceType; - localAddrType?: string; - remoteAddrType?: string; - iceRole?: string; - rtpRtcpMux?: boolean; - allocationTimeInMs?: number; - msRtcEngineVersion?: string; -} - -interface MSUtilization { - packets?: number; - bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; - bandwidthEstimationAvg?: number; -} - -interface MSVideoPayload extends MSPayloadBase { - resoluton?: string; - videoBitRateAvg?: number; - videoBitRateMax?: number; - videoFrameRateAvg?: number; - videoPacketLossRate?: number; - durationSeconds?: number; -} - -interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; - recvBitRateAverage?: number; - recvVideoStreamsMax?: number; - recvVideoStreamsMin?: number; - recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; - reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; -} - -interface MSVideoResolutionDistribution { - cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; - h1080Quality?: number; - h1440Quality?: number; - h2160Quality?: number; -} - -interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; - sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; - sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: string; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: string; - persistentState?: string; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; -} - -interface MsZoomToOptions { - contentX?: number; - contentY?: number; - viewportX?: string; - viewportY?: string; - scaleFactor?: number; - animate?: string; -} - -interface MutationObserverInit { - childList?: boolean; - attributes?: boolean; - characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; - characterDataOldValue?: boolean; - attributeFilter?: string[]; -} - -interface ObjectURLOptions { - oneTimeOnly?: boolean; -} - -interface PeriodicWaveConstraints { - disableNormalization?: boolean; -} - -interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; - height?: number; - pressure?: number; - tiltX?: number; - tiltY?: number; - pointerType?: string; - isPrimary?: boolean; -} - -interface PositionOptions { - enableHighAccuracy?: boolean; - timeout?: number; - maximumAge?: number; -} - -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - -interface RTCDtlsFingerprint { - algorithm?: string; - value?: string; -} - -interface RTCDtlsParameters { - role?: string; - fingerprints?: RTCDtlsFingerprint[]; -} - -interface RTCIceCandidate { - foundation?: string; - priority?: number; - ip?: string; - protocol?: string; - port?: number; - type?: string; - tcpType?: string; - relatedAddress?: string; - relatedPort?: number; -} - -interface RTCIceCandidateAttributes extends RTCStats { - ipAddress?: string; - portNumber?: number; - transport?: string; - candidateType?: string; - priority?: number; - addressSourceUrl?: string; -} - -interface RTCIceCandidateComplete { -} - -interface RTCIceCandidatePair { - local?: RTCIceCandidate; - remote?: RTCIceCandidate; -} - -interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: string; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; - availableIncomingBitrate?: number; -} - -interface RTCIceGatherOptions { - gatherPolicy?: string; - iceservers?: RTCIceServer[]; -} - -interface RTCIceParameters { - usernameFragment?: string; - password?: string; -} - -interface RTCIceServer { - urls?: any; - username?: string; - credential?: string; -} - -interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; - bytesReceived?: number; - packetsLost?: number; - jitter?: number; - fractionLost?: number; -} - -interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; - audioLevel?: number; - echoReturnLoss?: number; - echoReturnLossEnhancement?: number; -} - -interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; - bytesSent?: number; - targetBitrate?: number; - roundTripTime?: number; -} - -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - -interface RTCRtcpFeedback { - type?: string; - parameter?: string; -} - -interface RTCRtcpParameters { - ssrc?: number; - cname?: string; - reducedSize?: boolean; - mux?: boolean; -} - -interface RTCRtpCapabilities { - codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; - fecMechanisms?: string[]; -} - -interface RTCRtpCodecCapability { - name?: string; - kind?: string; - clockRate?: number; - preferredPayloadType?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; - maxSpatialLayers?: number; - svcMultiStreamSupport?: boolean; -} - -interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; - clockRate?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; -} - -interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; - audioLevel?: number; -} - -interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - framerateBias?: number; - resolutionScale?: number; - framerateScale?: number; - active?: boolean; - encodingId?: string; - dependencyEncodingIds?: string[]; - ssrcRange?: RTCSsrcRange; -} - -interface RTCRtpFecParameters { - ssrc?: number; - mechanism?: string; -} - -interface RTCRtpHeaderExtension { - kind?: string; - uri?: string; - preferredId?: number; - preferredEncrypt?: boolean; -} - -interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; - encrypt?: boolean; -} - -interface RTCRtpParameters { - muxId?: string; - codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; -} - -interface RTCRtpRtxParameters { - ssrc?: number; -} - -interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; - muxId?: string; -} - -interface RTCSrtpKeyParam { - keyMethod?: string; - keySalt?: string; - lifetime?: string; - mkiValue?: number; - mkiLength?: number; -} - -interface RTCSrtpSdesParameters { - tag?: number; - cryptoSuite?: string; - keyParams?: RTCSrtpKeyParam[]; - sessionParams?: string[]; -} - -interface RTCSsrcRange { - min?: number; - max?: number; -} - -interface RTCStats { - timestamp?: number; - type?: string; - id?: string; - msType?: string; -} - -interface RTCStatsReport { -} - -interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; - activeConnection?: boolean; - selectedCandidatePairId?: string; - localCertificateId?: string; - remoteCertificateId?: string; -} - -interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; - detailURI?: string; -} - -interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { - arrayOfDomainStrings?: string[]; -} - -interface UIEventInit extends EventInit { - view?: Window; - detail?: number; -} - -interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; - alpha?: boolean; - depth?: boolean; - stencil?: boolean; - antialias?: boolean; - premultipliedAlpha?: boolean; - preserveDrawingBuffer?: boolean; -} - -interface WebGLContextEventInit extends EventInit { - statusMessage?: string; -} - -interface WheelEventInit extends MouseEventInit { - deltaX?: number; - deltaY?: number; - deltaZ?: number; - deltaMode?: number; -} - -interface EventListener { - (evt: Event): void; -} - -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -interface AnalyserNode extends AudioNode { - fftSize: number; - readonly frequencyBinCount: number; - maxDecibels: number; - minDecibels: number; - smoothingTimeConstant: number; - getByteFrequencyData(array: Uint8Array): void; - getByteTimeDomainData(array: Uint8Array): void; - getFloatFrequencyData(array: Float32Array): void; - getFloatTimeDomainData(array: Float32Array): void; -} - -declare var AnalyserNode: { - prototype: AnalyserNode; - new(): AnalyserNode; -} - -interface AnimationEvent extends Event { - readonly animationName: string; - readonly elapsedTime: number; - initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; -} - -declare var AnimationEvent: { - prototype: AnimationEvent; - new(): AnimationEvent; -} - -interface ApplicationCache extends EventTarget { - oncached: (this: this, ev: Event) => any; - onchecking: (this: this, ev: Event) => any; - ondownloading: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onnoupdate: (this: this, ev: Event) => any; - onobsolete: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onupdateready: (this: this, ev: Event) => any; - readonly status: number; - abort(): void; - swapCache(): void; - update(): void; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; - addEventListener(type: "cached", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "checking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "downloading", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "noupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "obsolete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "updateready", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ApplicationCache: { - prototype: ApplicationCache; - new(): ApplicationCache; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; -} - -interface AriaRequestEvent extends Event { - readonly attributeName: string; - attributeValue: string | null; -} - -declare var AriaRequestEvent: { - prototype: AriaRequestEvent; - new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; -} - -interface Attr extends Node { - readonly name: string; - readonly ownerElement: Element; - readonly prefix: string | null; - readonly specified: boolean; - value: string; -} - -declare var Attr: { - prototype: Attr; - new(): Attr; -} - -interface AudioBuffer { - readonly duration: number; - readonly length: number; - readonly numberOfChannels: number; - readonly sampleRate: number; - copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; - copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; - getChannelData(channel: number): Float32Array; -} - -declare var AudioBuffer: { - prototype: AudioBuffer; - new(): AudioBuffer; -} - -interface AudioBufferSourceNode extends AudioNode { - buffer: AudioBuffer | null; - readonly detune: AudioParam; - loop: boolean; - loopEnd: number; - loopStart: number; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - readonly playbackRate: AudioParam; - start(when?: number, offset?: number, duration?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var AudioBufferSourceNode: { - prototype: AudioBufferSourceNode; - new(): AudioBufferSourceNode; -} - -interface AudioContext extends EventTarget { - readonly currentTime: number; - readonly destination: AudioDestinationNode; - readonly listener: AudioListener; - readonly sampleRate: number; - state: string; - createAnalyser(): AnalyserNode; - createBiquadFilter(): BiquadFilterNode; - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - createBufferSource(): AudioBufferSourceNode; - createChannelMerger(numberOfInputs?: number): ChannelMergerNode; - createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; - createConvolver(): ConvolverNode; - createDelay(maxDelayTime?: number): DelayNode; - createDynamicsCompressor(): DynamicsCompressorNode; - createGain(): GainNode; - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; - createOscillator(): OscillatorNode; - createPanner(): PannerNode; - createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; - createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; - createStereoPanner(): StereoPannerNode; - createWaveShaper(): WaveShaperNode; - decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; -} - -declare var AudioContext: { - prototype: AudioContext; - new(): AudioContext; -} - -interface AudioDestinationNode extends AudioNode { - readonly maxChannelCount: number; -} - -declare var AudioDestinationNode: { - prototype: AudioDestinationNode; - new(): AudioDestinationNode; -} - -interface AudioListener { - dopplerFactor: number; - speedOfSound: number; - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var AudioListener: { - prototype: AudioListener; - new(): AudioListener; -} - -interface AudioNode extends EventTarget { - channelCount: number; - channelCountMode: string; - channelInterpretation: string; - readonly context: AudioContext; - readonly numberOfInputs: number; - readonly numberOfOutputs: number; - connect(destination: AudioNode, output?: number, input?: number): void; - disconnect(output?: number): void; - disconnect(destination: AudioNode, output?: number, input?: number): void; - disconnect(destination: AudioParam, output?: number): void; -} - -declare var AudioNode: { - prototype: AudioNode; - new(): AudioNode; -} - -interface AudioParam { - readonly defaultValue: number; - value: number; - cancelScheduledValues(startTime: number): void; - exponentialRampToValueAtTime(value: number, endTime: number): void; - linearRampToValueAtTime(value: number, endTime: number): void; - setTargetAtTime(target: number, startTime: number, timeConstant: number): void; - setValueAtTime(value: number, startTime: number): void; - setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; -} - -declare var AudioParam: { - prototype: AudioParam; - new(): AudioParam; -} - -interface AudioProcessingEvent extends Event { - readonly inputBuffer: AudioBuffer; - readonly outputBuffer: AudioBuffer; - readonly playbackTime: number; -} - -declare var AudioProcessingEvent: { - prototype: AudioProcessingEvent; - new(): AudioProcessingEvent; -} - -interface AudioTrack { - enabled: boolean; - readonly id: string; - kind: string; - readonly label: string; - language: string; - readonly sourceBuffer: SourceBuffer; -} - -declare var AudioTrack: { - prototype: AudioTrack; - new(): AudioTrack; -} - -interface AudioTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - getTrackById(id: string): AudioTrack | null; - item(index: number): AudioTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: AudioTrack; -} - -declare var AudioTrackList: { - prototype: AudioTrackList; - new(): AudioTrackList; -} - -interface BarProp { - readonly visible: boolean; -} - -declare var BarProp: { - prototype: BarProp; - new(): BarProp; -} - -interface BeforeUnloadEvent extends Event { - returnValue: any; -} - -declare var BeforeUnloadEvent: { - prototype: BeforeUnloadEvent; - new(): BeforeUnloadEvent; -} - -interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; - readonly detune: AudioParam; - readonly frequency: AudioParam; - readonly gain: AudioParam; - type: string; - getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; -} - -declare var BiquadFilterNode: { - prototype: BiquadFilterNode; - new(): BiquadFilterNode; -} - -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -declare var Blob: { - prototype: Blob; - new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} - -interface CDATASection extends Text { -} - -declare var CDATASection: { - prototype: CDATASection; - new(): CDATASection; -} - -interface CSS { - supports(property: string, value?: string): boolean; -} -declare var CSS: CSS; - -interface CSSConditionRule extends CSSGroupingRule { - conditionText: string; -} - -declare var CSSConditionRule: { - prototype: CSSConditionRule; - new(): CSSConditionRule; -} - -interface CSSFontFaceRule extends CSSRule { - readonly style: CSSStyleDeclaration; -} - -declare var CSSFontFaceRule: { - prototype: CSSFontFaceRule; - new(): CSSFontFaceRule; -} - -interface CSSGroupingRule extends CSSRule { - readonly cssRules: CSSRuleList; - deleteRule(index: number): void; - insertRule(rule: string, index: number): number; -} - -declare var CSSGroupingRule: { - prototype: CSSGroupingRule; - new(): CSSGroupingRule; -} - -interface CSSImportRule extends CSSRule { - readonly href: string; - readonly media: MediaList; - readonly styleSheet: CSSStyleSheet; -} - -declare var CSSImportRule: { - prototype: CSSImportRule; - new(): CSSImportRule; -} - -interface CSSKeyframeRule extends CSSRule { - keyText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSKeyframeRule: { - prototype: CSSKeyframeRule; - new(): CSSKeyframeRule; -} - -interface CSSKeyframesRule extends CSSRule { - readonly cssRules: CSSRuleList; - name: string; - appendRule(rule: string): void; - deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; -} - -declare var CSSKeyframesRule: { - prototype: CSSKeyframesRule; - new(): CSSKeyframesRule; -} - -interface CSSMediaRule extends CSSConditionRule { - readonly media: MediaList; -} - -declare var CSSMediaRule: { - prototype: CSSMediaRule; - new(): CSSMediaRule; -} - -interface CSSNamespaceRule extends CSSRule { - readonly namespaceURI: string; - readonly prefix: string; -} - -declare var CSSNamespaceRule: { - prototype: CSSNamespaceRule; - new(): CSSNamespaceRule; -} - -interface CSSPageRule extends CSSRule { - readonly pseudoClass: string; - readonly selector: string; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSPageRule: { - prototype: CSSPageRule; - new(): CSSPageRule; -} - -interface CSSRule { - cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; - readonly type: number; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -declare var CSSRule: { - prototype: CSSRule; - new(): CSSRule; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -interface CSSRuleList { - readonly length: number; - item(index: number): CSSRule; - [index: number]: CSSRule; -} - -declare var CSSRuleList: { - prototype: CSSRuleList; - new(): CSSRuleList; -} - -interface CSSStyleDeclaration { - alignContent: string | null; - alignItems: string | null; - alignSelf: string | null; - alignmentBaseline: string | null; - animation: string | null; - animationDelay: string | null; - animationDirection: string | null; - animationDuration: string | null; - animationFillMode: string | null; - animationIterationCount: string | null; - animationName: string | null; - animationPlayState: string | null; - animationTimingFunction: string | null; - backfaceVisibility: string | null; - background: string | null; - backgroundAttachment: string | null; - backgroundClip: string | null; - backgroundColor: string | null; - backgroundImage: string | null; - backgroundOrigin: string | null; - backgroundPosition: string | null; - backgroundPositionX: string | null; - backgroundPositionY: string | null; - backgroundRepeat: string | null; - backgroundSize: string | null; - baselineShift: string | null; - border: string | null; - borderBottom: string | null; - borderBottomColor: string | null; - borderBottomLeftRadius: string | null; - borderBottomRightRadius: string | null; - borderBottomStyle: string | null; - borderBottomWidth: string | null; - borderCollapse: string | null; - borderColor: string | null; - borderImage: string | null; - borderImageOutset: string | null; - borderImageRepeat: string | null; - borderImageSlice: string | null; - borderImageSource: string | null; - borderImageWidth: string | null; - borderLeft: string | null; - borderLeftColor: string | null; - borderLeftStyle: string | null; - borderLeftWidth: string | null; - borderRadius: string | null; - borderRight: string | null; - borderRightColor: string | null; - borderRightStyle: string | null; - borderRightWidth: string | null; - borderSpacing: string | null; - borderStyle: string | null; - borderTop: string | null; - borderTopColor: string | null; - borderTopLeftRadius: string | null; - borderTopRightRadius: string | null; - borderTopStyle: string | null; - borderTopWidth: string | null; - borderWidth: string | null; - bottom: string | null; - boxShadow: string | null; - boxSizing: string | null; - breakAfter: string | null; - breakBefore: string | null; - breakInside: string | null; - captionSide: string | null; - clear: string | null; - clip: string | null; - clipPath: string | null; - clipRule: string | null; - color: string | null; - colorInterpolationFilters: string | null; - columnCount: any; - columnFill: string | null; - columnGap: any; - columnRule: string | null; - columnRuleColor: any; - columnRuleStyle: string | null; - columnRuleWidth: any; - columnSpan: string | null; - columnWidth: any; - columns: string | null; - content: string | null; - counterIncrement: string | null; - counterReset: string | null; - cssFloat: string | null; - cssText: string; - cursor: string | null; - direction: string | null; - display: string | null; - dominantBaseline: string | null; - emptyCells: string | null; - enableBackground: string | null; - fill: string | null; - fillOpacity: string | null; - fillRule: string | null; - filter: string | null; - flex: string | null; - flexBasis: string | null; - flexDirection: string | null; - flexFlow: string | null; - flexGrow: string | null; - flexShrink: string | null; - flexWrap: string | null; - floodColor: string | null; - floodOpacity: string | null; - font: string | null; - fontFamily: string | null; - fontFeatureSettings: string | null; - fontSize: string | null; - fontSizeAdjust: string | null; - fontStretch: string | null; - fontStyle: string | null; - fontVariant: string | null; - fontWeight: string | null; - glyphOrientationHorizontal: string | null; - glyphOrientationVertical: string | null; - height: string | null; - imeMode: string | null; - justifyContent: string | null; - kerning: string | null; - left: string | null; - readonly length: number; - letterSpacing: string | null; - lightingColor: string | null; - lineHeight: string | null; - listStyle: string | null; - listStyleImage: string | null; - listStylePosition: string | null; - listStyleType: string | null; - margin: string | null; - marginBottom: string | null; - marginLeft: string | null; - marginRight: string | null; - marginTop: string | null; - marker: string | null; - markerEnd: string | null; - markerMid: string | null; - markerStart: string | null; - mask: string | null; - maxHeight: string | null; - maxWidth: string | null; - minHeight: string | null; - minWidth: string | null; - msContentZoomChaining: string | null; - msContentZoomLimit: string | null; - msContentZoomLimitMax: any; - msContentZoomLimitMin: any; - msContentZoomSnap: string | null; - msContentZoomSnapPoints: string | null; - msContentZoomSnapType: string | null; - msContentZooming: string | null; - msFlowFrom: string | null; - msFlowInto: string | null; - msFontFeatureSettings: string | null; - msGridColumn: any; - msGridColumnAlign: string | null; - msGridColumnSpan: any; - msGridColumns: string | null; - msGridRow: any; - msGridRowAlign: string | null; - msGridRowSpan: any; - msGridRows: string | null; - msHighContrastAdjust: string | null; - msHyphenateLimitChars: string | null; - msHyphenateLimitLines: any; - msHyphenateLimitZone: any; - msHyphens: string | null; - msImeAlign: string | null; - msOverflowStyle: string | null; - msScrollChaining: string | null; - msScrollLimit: string | null; - msScrollLimitXMax: any; - msScrollLimitXMin: any; - msScrollLimitYMax: any; - msScrollLimitYMin: any; - msScrollRails: string | null; - msScrollSnapPointsX: string | null; - msScrollSnapPointsY: string | null; - msScrollSnapType: string | null; - msScrollSnapX: string | null; - msScrollSnapY: string | null; - msScrollTranslation: string | null; - msTextCombineHorizontal: string | null; - msTextSizeAdjust: any; - msTouchAction: string | null; - msTouchSelect: string | null; - msUserSelect: string | null; - msWrapFlow: string; - msWrapMargin: any; - msWrapThrough: string; - opacity: string | null; - order: string | null; - orphans: string | null; - outline: string | null; - outlineColor: string | null; - outlineStyle: string | null; - outlineWidth: string | null; - overflow: string | null; - overflowX: string | null; - overflowY: string | null; - padding: string | null; - paddingBottom: string | null; - paddingLeft: string | null; - paddingRight: string | null; - paddingTop: string | null; - pageBreakAfter: string | null; - pageBreakBefore: string | null; - pageBreakInside: string | null; - readonly parentRule: CSSRule; - perspective: string | null; - perspectiveOrigin: string | null; - pointerEvents: string | null; - position: string | null; - quotes: string | null; - right: string | null; - rubyAlign: string | null; - rubyOverhang: string | null; - rubyPosition: string | null; - stopColor: string | null; - stopOpacity: string | null; - stroke: string | null; - strokeDasharray: string | null; - strokeDashoffset: string | null; - strokeLinecap: string | null; - strokeLinejoin: string | null; - strokeMiterlimit: string | null; - strokeOpacity: string | null; - strokeWidth: string | null; - tableLayout: string | null; - textAlign: string | null; - textAlignLast: string | null; - textAnchor: string | null; - textDecoration: string | null; - textIndent: string | null; - textJustify: string | null; - textKashida: string | null; - textKashidaSpace: string | null; - textOverflow: string | null; - textShadow: string | null; - textTransform: string | null; - textUnderlinePosition: string | null; - top: string | null; - touchAction: string | null; - transform: string | null; - transformOrigin: string | null; - transformStyle: string | null; - transition: string | null; - transitionDelay: string | null; - transitionDuration: string | null; - transitionProperty: string | null; - transitionTimingFunction: string | null; - unicodeBidi: string | null; - verticalAlign: string | null; - visibility: string | null; - webkitAlignContent: string | null; - webkitAlignItems: string | null; - webkitAlignSelf: string | null; - webkitAnimation: string | null; - webkitAnimationDelay: string | null; - webkitAnimationDirection: string | null; - webkitAnimationDuration: string | null; - webkitAnimationFillMode: string | null; - webkitAnimationIterationCount: string | null; - webkitAnimationName: string | null; - webkitAnimationPlayState: string | null; - webkitAnimationTimingFunction: string | null; - webkitAppearance: string | null; - webkitBackfaceVisibility: string | null; - webkitBackgroundClip: string | null; - webkitBackgroundOrigin: string | null; - webkitBackgroundSize: string | null; - webkitBorderBottomLeftRadius: string | null; - webkitBorderBottomRightRadius: string | null; - webkitBorderImage: string | null; - webkitBorderRadius: string | null; - webkitBorderTopLeftRadius: string | null; - webkitBorderTopRightRadius: string | null; - webkitBoxAlign: string | null; - webkitBoxDirection: string | null; - webkitBoxFlex: string | null; - webkitBoxOrdinalGroup: string | null; - webkitBoxOrient: string | null; - webkitBoxPack: string | null; - webkitBoxSizing: string | null; - webkitColumnBreakAfter: string | null; - webkitColumnBreakBefore: string | null; - webkitColumnBreakInside: string | null; - webkitColumnCount: any; - webkitColumnGap: any; - webkitColumnRule: string | null; - webkitColumnRuleColor: any; - webkitColumnRuleStyle: string | null; - webkitColumnRuleWidth: any; - webkitColumnSpan: string | null; - webkitColumnWidth: any; - webkitColumns: string | null; - webkitFilter: string | null; - webkitFlex: string | null; - webkitFlexBasis: string | null; - webkitFlexDirection: string | null; - webkitFlexFlow: string | null; - webkitFlexGrow: string | null; - webkitFlexShrink: string | null; - webkitFlexWrap: string | null; - webkitJustifyContent: string | null; - webkitOrder: string | null; - webkitPerspective: string | null; - webkitPerspectiveOrigin: string | null; - webkitTapHighlightColor: string | null; - webkitTextFillColor: string | null; - webkitTextSizeAdjust: any; - webkitTransform: string | null; - webkitTransformOrigin: string | null; - webkitTransformStyle: string | null; - webkitTransition: string | null; - webkitTransitionDelay: string | null; - webkitTransitionDuration: string | null; - webkitTransitionProperty: string | null; - webkitTransitionTimingFunction: string | null; - webkitUserModify: string | null; - webkitUserSelect: string | null; - webkitWritingMode: string | null; - whiteSpace: string | null; - widows: string | null; - width: string | null; - wordBreak: string | null; - wordSpacing: string | null; - wordWrap: string | null; - writingMode: string | null; - zIndex: string | null; - zoom: string | null; - getPropertyPriority(propertyName: string): string; - getPropertyValue(propertyName: string): string; - item(index: number): string; - removeProperty(propertyName: string): string; - setProperty(propertyName: string, value: string | null, priority?: string): void; - [index: number]: string; -} - -declare var CSSStyleDeclaration: { - prototype: CSSStyleDeclaration; - new(): CSSStyleDeclaration; -} - -interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSStyleRule: { - prototype: CSSStyleRule; - new(): CSSStyleRule; -} - -interface CSSStyleSheet extends StyleSheet { - readonly cssRules: CSSRuleList; - cssText: string; - readonly href: string; - readonly id: string; - readonly imports: StyleSheetList; - readonly isAlternate: boolean; - readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; - readonly owningElement: Element; - readonly pages: StyleSheetPageList; - readonly readOnly: boolean; - readonly rules: CSSRuleList; - addImport(bstrURL: string, lIndex?: number): number; - addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; - addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; - deleteRule(index?: number): void; - insertRule(rule: string, index?: number): number; - removeImport(lIndex: number): void; - removeRule(lIndex: number): void; -} - -declare var CSSStyleSheet: { - prototype: CSSStyleSheet; - new(): CSSStyleSheet; -} - -interface CSSSupportsRule extends CSSConditionRule { -} - -declare var CSSSupportsRule: { - prototype: CSSSupportsRule; - new(): CSSSupportsRule; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: string; - msImageSmoothingEnabled: boolean; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: string): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; - fill(fillRule?: string): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: string): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(): CloseEvent; -} - -interface CommandEvent extends Event { - readonly commandName: string; - readonly detail: string | null; -} - -declare var CommandEvent: { - prototype: CommandEvent; - new(type: string, eventInitDict?: CommandEventInit): CommandEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: string, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} - -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; -} - -declare var CustomEvent: { - prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; - createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} - -interface DataCue extends TextTrackCue { - data: ArrayBuffer; -} - -declare var DataCue: { - prototype: DataCue; - new(): DataCue; -} - -interface DataTransfer { - dropEffect: string; - effectAllowed: string; - readonly files: FileList; - readonly items: DataTransferItemList; - readonly types: DOMStringList; - clearData(format?: string): boolean; - getData(format: string): string; - setData(format: string, data: string): boolean; -} - -declare var DataTransfer: { - prototype: DataTransfer; - new(): DataTransfer; -} - -interface DataTransferItem { - readonly kind: string; - readonly type: string; - getAsFile(): File | null; - getAsString(_callback: FunctionStringCallback | null): void; -} - -declare var DataTransferItem: { - prototype: DataTransferItem; - new(): DataTransferItem; -} - -interface DataTransferItemList { - readonly length: number; - add(data: File): DataTransferItem | null; - clear(): void; - item(index: number): DataTransferItem; - remove(index: number): void; - [index: number]: DataTransferItem; -} - -declare var DataTransferItemList: { - prototype: DataTransferItemList; - new(): DataTransferItemList; -} - -interface DeferredPermissionRequest { - readonly id: number; - readonly type: string; - readonly uri: string; - allow(): void; - deny(): void; -} - -declare var DeferredPermissionRequest: { - prototype: DeferredPermissionRequest; - new(): DeferredPermissionRequest; -} - -interface DelayNode extends AudioNode { - readonly delayTime: AudioParam; -} - -declare var DelayNode: { - prototype: DelayNode; - new(): DelayNode; -} - -interface DeviceAcceleration { - readonly x: number | null; - readonly y: number | null; - readonly z: number | null; -} - -declare var DeviceAcceleration: { - prototype: DeviceAcceleration; - new(): DeviceAcceleration; -} - -interface DeviceLightEvent extends Event { - readonly value: number; -} - -declare var DeviceLightEvent: { - prototype: DeviceLightEvent; - new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} - -interface DeviceMotionEvent extends Event { - readonly acceleration: DeviceAcceleration | null; - readonly accelerationIncludingGravity: DeviceAcceleration | null; - readonly interval: number | null; - readonly rotationRate: DeviceRotationRate | null; - initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; -} - -declare var DeviceMotionEvent: { - prototype: DeviceMotionEvent; - new(): DeviceMotionEvent; -} - -interface DeviceOrientationEvent extends Event { - readonly absolute: boolean; - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; - initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; -} - -declare var DeviceOrientationEvent: { - prototype: DeviceOrientationEvent; - new(): DeviceOrientationEvent; -} - -interface DeviceRotationRate { - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; -} - -declare var DeviceRotationRate: { - prototype: DeviceRotationRate; - new(): DeviceRotationRate; -} - -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { - /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ - readonly activeElement: Element; - /** - * Sets or gets the color of all active links in the document. - */ - alinkColor: string; - /** - * Returns a reference to the collection of elements contained by the object. - */ - readonly all: HTMLAllCollection; - /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ - anchors: HTMLCollectionOf; - /** - * Retrieves a collection of all applet objects in the document. - */ - applets: HTMLCollectionOf; - /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ - bgColor: string; - /** - * Specifies the beginning and end of the document body. - */ - body: HTMLElement; - readonly characterSet: string; - /** - * Gets or sets the character set used to encode the object. - */ - charset: string; - /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ - readonly compatMode: string; - cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; - /** - * Gets the default character set from the current regional language settings. - */ - readonly defaultCharset: string; - readonly defaultView: Window; - /** - * Sets or gets a value that indicates whether the document can be edited. - */ - designMode: string; - /** - * 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. - */ - readonly doctype: DocumentType; - /** - * Gets a reference to the root node of the document. - */ - documentElement: HTMLElement; - /** - * Sets or gets the security domain of the document. - */ - domain: string; - /** - * Retrieves a collection of all embed objects in the document. - */ - embeds: HTMLCollectionOf; - /** - * Sets or gets the foreground (text) color of the document. - */ - fgColor: string; - /** - * Retrieves a collection, in source order, of all form objects in the document. - */ - forms: HTMLCollectionOf; - readonly fullscreenElement: Element | null; - readonly fullscreenEnabled: boolean; - readonly head: HTMLHeadElement; - readonly hidden: boolean; - /** - * Retrieves a collection, in source order, of img objects in the document. - */ - images: HTMLCollectionOf; - /** - * Gets the implementation object of the current document. - */ - readonly implementation: DOMImplementation; - /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ - readonly inputEncoding: string | null; - /** - * 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. - */ - linkColor: string; - /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ - links: HTMLCollectionOf; - /** - * Contains information about the current URL. - */ - readonly location: Location; - msCSSOMElementFloatMetrics: boolean; - msCapsLockWarningOff: boolean; - /** - * Fires when the user aborts the download. - * @param ev The event. - */ - onabort: (this: this, ev: UIEvent) => any; - /** - * Fires when the object is set as the active element. - * @param ev The event. - */ - onactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ - onbeforeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ - onbeforedeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ - onblur: (this: this, ev: FocusEvent) => any; - /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ - onchange: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ - onclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ - oncontextmenu: (this: this, ev: PointerEvent) => any; - /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ - ondblclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ - ondeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ - ondrag: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ - ondragend: (this: this, 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: (this: this, 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. - */ - ondragleave: (this: this, ev: DragEvent) => any; - /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ - ondragover: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ - ondurationchange: (this: this, ev: Event) => any; - /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ - onemptied: (this: this, ev: Event) => any; - /** - * Occurs when the end of playback is reached. - * @param ev The event - */ - onended: (this: this, ev: MediaStreamErrorEvent) => any; - /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - * @param ev The event. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onfullscreenchange: (this: this, ev: Event) => any; - onfullscreenerror: (this: this, ev: Event) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ - onkeydown: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ - onkeypress: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ - onkeyup: (this: this, ev: KeyboardEvent) => any; - /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ - onload: (this: this, ev: Event) => any; - /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ - onloadeddata: (this: this, ev: Event) => any; - /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ - onloadedmetadata: (this: this, ev: Event) => any; - /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ - onloadstart: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ - onmousedown: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ - onmousemove: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ - onmouseout: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ - onmouseover: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ - onmouseup: (this: this, ev: MouseEvent) => any; - /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ - onmssitemodejumplistitemremoved: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ - onmsthumbnailclick: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when playback is paused. - * @param ev The event. - */ - onpause: (this: this, ev: Event) => any; - /** - * Occurs when the play method is requested. - * @param ev The event. - */ - onplay: (this: this, ev: Event) => any; - /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ - onplaying: (this: this, ev: Event) => any; - onpointerlockchange: (this: this, ev: Event) => any; - onpointerlockerror: (this: this, ev: Event) => any; - /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ - onprogress: (this: this, ev: ProgressEvent) => any; - /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ - onratechange: (this: this, ev: Event) => any; - /** - * Fires when the state of the object has changed. - * @param ev The event - */ - onreadystatechange: (this: this, ev: ProgressEvent) => any; - /** - * Fires when the user resets a form. - * @param ev The event. - */ - onreset: (this: this, ev: Event) => any; - /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ - onscroll: (this: this, ev: UIEvent) => any; - /** - * Occurs when the seek operation ends. - * @param ev The event. - */ - onseeked: (this: this, ev: Event) => any; - /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ - onseeking: (this: this, ev: Event) => any; - /** - * Fires when the current selection changes. - * @param ev The event. - */ - onselect: (this: this, ev: UIEvent) => any; - /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ - onselectionchange: (this: this, ev: Event) => any; - onselectstart: (this: this, ev: Event) => any; - /** - * Occurs when the download has stopped. - * @param ev The event. - */ - onstalled: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ - onstop: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ - onsuspend: (this: this, ev: Event) => any; - /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ - onvolumechange: (this: this, ev: Event) => any; - /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ - onwaiting: (this: this, ev: Event) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - plugins: HTMLCollectionOf; - readonly pointerLockElement: Element; - /** - * Retrieves a value that indicates the current state of the object. - */ - readonly readyState: string; - /** - * Gets the URL of the location that referred the user to the current page. - */ - readonly referrer: string; - /** - * Gets the root svg element in the document hierarchy. - */ - readonly rootElement: SVGSVGElement; - /** - * Retrieves a collection of all script objects in the document. - */ - scripts: HTMLCollectionOf; - readonly scrollingElement: Element | null; - /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ - readonly styleSheets: StyleSheetList; - /** - * Contains the title of the document. - */ - title: string; - readonly visibilityState: string; - /** - * Sets or gets the color of the links that the user has visited. - */ - vlinkColor: string; - readonly webkitCurrentFullScreenElement: Element | null; - readonly webkitFullscreenElement: Element | null; - readonly webkitFullscreenEnabled: boolean; - readonly webkitIsFullScreen: boolean; - readonly xmlEncoding: string | null; - xmlStandalone: boolean; - /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ - xmlVersion: string | null; - adoptNode(source: Node): Node; - captureEvents(): void; - caretRangeFromPoint(x: number, y: number): Range; - clear(): void; - /** - * Closes an output stream and forces the sent data to display. - */ - close(): void; - /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ - createAttribute(name: string): Attr; - createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; - createCDATASection(data: string): CDATASection; - /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ - createComment(data: string): Comment; - /** - * Creates a new document. - */ - createDocumentFragment(): DocumentFragment; - /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ - createElement(tagName: "a"): HTMLAnchorElement; - createElement(tagName: "applet"): HTMLAppletElement; - createElement(tagName: "area"): HTMLAreaElement; - createElement(tagName: "audio"): HTMLAudioElement; - createElement(tagName: "base"): HTMLBaseElement; - createElement(tagName: "basefont"): HTMLBaseFontElement; - createElement(tagName: "blockquote"): HTMLQuoteElement; - createElement(tagName: "body"): HTMLBodyElement; - createElement(tagName: "br"): HTMLBRElement; - createElement(tagName: "button"): HTMLButtonElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: "caption"): HTMLTableCaptionElement; - createElement(tagName: "col"): HTMLTableColElement; - createElement(tagName: "colgroup"): HTMLTableColElement; - createElement(tagName: "datalist"): HTMLDataListElement; - createElement(tagName: "del"): HTMLModElement; - createElement(tagName: "dir"): HTMLDirectoryElement; - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "dl"): HTMLDListElement; - createElement(tagName: "embed"): HTMLEmbedElement; - createElement(tagName: "fieldset"): HTMLFieldSetElement; - createElement(tagName: "font"): HTMLFontElement; - createElement(tagName: "form"): HTMLFormElement; - createElement(tagName: "frame"): HTMLFrameElement; - createElement(tagName: "frameset"): HTMLFrameSetElement; - createElement(tagName: "h1"): HTMLHeadingElement; - createElement(tagName: "h2"): HTMLHeadingElement; - createElement(tagName: "h3"): HTMLHeadingElement; - createElement(tagName: "h4"): HTMLHeadingElement; - createElement(tagName: "h5"): HTMLHeadingElement; - createElement(tagName: "h6"): HTMLHeadingElement; - createElement(tagName: "head"): HTMLHeadElement; - createElement(tagName: "hr"): HTMLHRElement; - createElement(tagName: "html"): HTMLHtmlElement; - createElement(tagName: "iframe"): HTMLIFrameElement; - createElement(tagName: "img"): HTMLImageElement; - createElement(tagName: "input"): HTMLInputElement; - createElement(tagName: "ins"): HTMLModElement; - createElement(tagName: "isindex"): HTMLUnknownElement; - createElement(tagName: "label"): HTMLLabelElement; - createElement(tagName: "legend"): HTMLLegendElement; - createElement(tagName: "li"): HTMLLIElement; - createElement(tagName: "link"): HTMLLinkElement; - createElement(tagName: "listing"): HTMLPreElement; - createElement(tagName: "map"): HTMLMapElement; - createElement(tagName: "marquee"): HTMLMarqueeElement; - createElement(tagName: "menu"): HTMLMenuElement; - createElement(tagName: "meta"): HTMLMetaElement; - createElement(tagName: "meter"): HTMLMeterElement; - createElement(tagName: "nextid"): HTMLUnknownElement; - createElement(tagName: "object"): HTMLObjectElement; - createElement(tagName: "ol"): HTMLOListElement; - createElement(tagName: "optgroup"): HTMLOptGroupElement; - createElement(tagName: "option"): HTMLOptionElement; - createElement(tagName: "p"): HTMLParagraphElement; - createElement(tagName: "param"): HTMLParamElement; - createElement(tagName: "picture"): HTMLPictureElement; - createElement(tagName: "pre"): HTMLPreElement; - createElement(tagName: "progress"): HTMLProgressElement; - createElement(tagName: "q"): HTMLQuoteElement; - createElement(tagName: "script"): HTMLScriptElement; - createElement(tagName: "select"): HTMLSelectElement; - createElement(tagName: "source"): HTMLSourceElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "style"): HTMLStyleElement; - createElement(tagName: "table"): HTMLTableElement; - createElement(tagName: "tbody"): HTMLTableSectionElement; - createElement(tagName: "td"): HTMLTableDataCellElement; - createElement(tagName: "template"): HTMLTemplateElement; - createElement(tagName: "textarea"): HTMLTextAreaElement; - createElement(tagName: "tfoot"): HTMLTableSectionElement; - createElement(tagName: "th"): HTMLTableHeaderCellElement; - createElement(tagName: "thead"): HTMLTableSectionElement; - createElement(tagName: "title"): HTMLTitleElement; - createElement(tagName: "tr"): HTMLTableRowElement; - createElement(tagName: "track"): HTMLTrackElement; - createElement(tagName: "ul"): HTMLUListElement; - createElement(tagName: "video"): HTMLVideoElement; - createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; - createElement(tagName: "xmp"): HTMLPreElement; - createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement - createElementNS(namespaceURI: string | null, qualifiedName: string): Element; - 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. - * @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. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - 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. - */ - createRange(): Range; - /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ - createTextNode(data: string): Text; - createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; - createTouchList(...touches: Touch[]): TouchList; - /** - * Creates a TreeWalker 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. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; - /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ - elementFromPoint(x: number, y: number): Element; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; - /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ - execCommand(commandId: string, showUI?: boolean, value?: any): boolean; - /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ - execCommandShowHelp(commandId: string): boolean; - exitFullscreen(): void; - exitPointerLock(): void; - /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ - focus(): void; - /** - * 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 | null; - getElementsByClassName(classNames: string): HTMLCollectionOf; - /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ - getElementsByName(elementName: string): NodeListOf; - /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ - getElementsByTagName(tagname: "a"): NodeListOf; - getElementsByTagName(tagname: "abbr"): NodeListOf; - getElementsByTagName(tagname: "acronym"): NodeListOf; - getElementsByTagName(tagname: "address"): NodeListOf; - getElementsByTagName(tagname: "applet"): NodeListOf; - getElementsByTagName(tagname: "area"): NodeListOf; - getElementsByTagName(tagname: "article"): NodeListOf; - getElementsByTagName(tagname: "aside"): NodeListOf; - getElementsByTagName(tagname: "audio"): NodeListOf; - getElementsByTagName(tagname: "b"): NodeListOf; - getElementsByTagName(tagname: "base"): NodeListOf; - getElementsByTagName(tagname: "basefont"): NodeListOf; - getElementsByTagName(tagname: "bdo"): NodeListOf; - getElementsByTagName(tagname: "big"): NodeListOf; - getElementsByTagName(tagname: "blockquote"): NodeListOf; - getElementsByTagName(tagname: "body"): NodeListOf; - getElementsByTagName(tagname: "br"): NodeListOf; - getElementsByTagName(tagname: "button"): NodeListOf; - getElementsByTagName(tagname: "canvas"): NodeListOf; - getElementsByTagName(tagname: "caption"): NodeListOf; - getElementsByTagName(tagname: "center"): NodeListOf; - getElementsByTagName(tagname: "circle"): NodeListOf; - getElementsByTagName(tagname: "cite"): NodeListOf; - getElementsByTagName(tagname: "clippath"): NodeListOf; - getElementsByTagName(tagname: "code"): NodeListOf; - getElementsByTagName(tagname: "col"): NodeListOf; - getElementsByTagName(tagname: "colgroup"): NodeListOf; - getElementsByTagName(tagname: "datalist"): NodeListOf; - getElementsByTagName(tagname: "dd"): NodeListOf; - getElementsByTagName(tagname: "defs"): NodeListOf; - getElementsByTagName(tagname: "del"): NodeListOf; - getElementsByTagName(tagname: "desc"): NodeListOf; - getElementsByTagName(tagname: "dfn"): NodeListOf; - getElementsByTagName(tagname: "dir"): NodeListOf; - getElementsByTagName(tagname: "div"): NodeListOf; - getElementsByTagName(tagname: "dl"): NodeListOf; - getElementsByTagName(tagname: "dt"): NodeListOf; - getElementsByTagName(tagname: "ellipse"): NodeListOf; - getElementsByTagName(tagname: "em"): NodeListOf; - getElementsByTagName(tagname: "embed"): NodeListOf; - getElementsByTagName(tagname: "feblend"): NodeListOf; - getElementsByTagName(tagname: "fecolormatrix"): NodeListOf; - getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(tagname: "fecomposite"): NodeListOf; - getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf; - getElementsByTagName(tagname: "fediffuselighting"): NodeListOf; - getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf; - getElementsByTagName(tagname: "fedistantlight"): NodeListOf; - getElementsByTagName(tagname: "feflood"): NodeListOf; - getElementsByTagName(tagname: "fefunca"): NodeListOf; - getElementsByTagName(tagname: "fefuncb"): NodeListOf; - getElementsByTagName(tagname: "fefuncg"): NodeListOf; - getElementsByTagName(tagname: "fefuncr"): NodeListOf; - getElementsByTagName(tagname: "fegaussianblur"): NodeListOf; - getElementsByTagName(tagname: "feimage"): NodeListOf; - getElementsByTagName(tagname: "femerge"): NodeListOf; - getElementsByTagName(tagname: "femergenode"): NodeListOf; - getElementsByTagName(tagname: "femorphology"): NodeListOf; - getElementsByTagName(tagname: "feoffset"): NodeListOf; - getElementsByTagName(tagname: "fepointlight"): NodeListOf; - getElementsByTagName(tagname: "fespecularlighting"): NodeListOf; - getElementsByTagName(tagname: "fespotlight"): NodeListOf; - getElementsByTagName(tagname: "fetile"): NodeListOf; - getElementsByTagName(tagname: "feturbulence"): NodeListOf; - getElementsByTagName(tagname: "fieldset"): NodeListOf; - getElementsByTagName(tagname: "figcaption"): NodeListOf; - getElementsByTagName(tagname: "figure"): NodeListOf; - getElementsByTagName(tagname: "filter"): NodeListOf; - getElementsByTagName(tagname: "font"): NodeListOf; - getElementsByTagName(tagname: "footer"): NodeListOf; - getElementsByTagName(tagname: "foreignobject"): NodeListOf; - getElementsByTagName(tagname: "form"): NodeListOf; - getElementsByTagName(tagname: "frame"): NodeListOf; - getElementsByTagName(tagname: "frameset"): NodeListOf; - getElementsByTagName(tagname: "g"): NodeListOf; - getElementsByTagName(tagname: "h1"): NodeListOf; - getElementsByTagName(tagname: "h2"): NodeListOf; - getElementsByTagName(tagname: "h3"): NodeListOf; - getElementsByTagName(tagname: "h4"): NodeListOf; - getElementsByTagName(tagname: "h5"): NodeListOf; - getElementsByTagName(tagname: "h6"): NodeListOf; - getElementsByTagName(tagname: "head"): NodeListOf; - getElementsByTagName(tagname: "header"): NodeListOf; - getElementsByTagName(tagname: "hgroup"): NodeListOf; - getElementsByTagName(tagname: "hr"): NodeListOf; - getElementsByTagName(tagname: "html"): NodeListOf; - getElementsByTagName(tagname: "i"): NodeListOf; - getElementsByTagName(tagname: "iframe"): NodeListOf; - getElementsByTagName(tagname: "image"): NodeListOf; - getElementsByTagName(tagname: "img"): NodeListOf; - getElementsByTagName(tagname: "input"): NodeListOf; - getElementsByTagName(tagname: "ins"): NodeListOf; - getElementsByTagName(tagname: "isindex"): NodeListOf; - getElementsByTagName(tagname: "kbd"): NodeListOf; - getElementsByTagName(tagname: "keygen"): NodeListOf; - getElementsByTagName(tagname: "label"): NodeListOf; - getElementsByTagName(tagname: "legend"): NodeListOf; - getElementsByTagName(tagname: "li"): NodeListOf; - getElementsByTagName(tagname: "line"): NodeListOf; - getElementsByTagName(tagname: "lineargradient"): NodeListOf; - getElementsByTagName(tagname: "link"): NodeListOf; - getElementsByTagName(tagname: "listing"): NodeListOf; - getElementsByTagName(tagname: "map"): NodeListOf; - getElementsByTagName(tagname: "mark"): NodeListOf; - getElementsByTagName(tagname: "marker"): NodeListOf; - getElementsByTagName(tagname: "marquee"): NodeListOf; - getElementsByTagName(tagname: "mask"): NodeListOf; - getElementsByTagName(tagname: "menu"): NodeListOf; - getElementsByTagName(tagname: "meta"): NodeListOf; - getElementsByTagName(tagname: "metadata"): NodeListOf; - getElementsByTagName(tagname: "meter"): NodeListOf; - getElementsByTagName(tagname: "nav"): NodeListOf; - getElementsByTagName(tagname: "nextid"): NodeListOf; - getElementsByTagName(tagname: "nobr"): NodeListOf; - getElementsByTagName(tagname: "noframes"): NodeListOf; - getElementsByTagName(tagname: "noscript"): NodeListOf; - getElementsByTagName(tagname: "object"): NodeListOf; - getElementsByTagName(tagname: "ol"): NodeListOf; - getElementsByTagName(tagname: "optgroup"): NodeListOf; - getElementsByTagName(tagname: "option"): NodeListOf; - getElementsByTagName(tagname: "p"): NodeListOf; - getElementsByTagName(tagname: "param"): NodeListOf; - getElementsByTagName(tagname: "path"): NodeListOf; - getElementsByTagName(tagname: "pattern"): NodeListOf; - getElementsByTagName(tagname: "picture"): NodeListOf; - getElementsByTagName(tagname: "plaintext"): NodeListOf; - getElementsByTagName(tagname: "polygon"): NodeListOf; - getElementsByTagName(tagname: "polyline"): NodeListOf; - getElementsByTagName(tagname: "pre"): NodeListOf; - getElementsByTagName(tagname: "progress"): NodeListOf; - getElementsByTagName(tagname: "q"): NodeListOf; - getElementsByTagName(tagname: "radialgradient"): NodeListOf; - getElementsByTagName(tagname: "rect"): NodeListOf; - getElementsByTagName(tagname: "rt"): NodeListOf; - getElementsByTagName(tagname: "ruby"): NodeListOf; - getElementsByTagName(tagname: "s"): NodeListOf; - getElementsByTagName(tagname: "samp"): NodeListOf; - getElementsByTagName(tagname: "script"): NodeListOf; - getElementsByTagName(tagname: "section"): NodeListOf; - getElementsByTagName(tagname: "select"): NodeListOf; - getElementsByTagName(tagname: "small"): NodeListOf; - getElementsByTagName(tagname: "source"): NodeListOf; - getElementsByTagName(tagname: "span"): NodeListOf; - getElementsByTagName(tagname: "stop"): NodeListOf; - getElementsByTagName(tagname: "strike"): NodeListOf; - getElementsByTagName(tagname: "strong"): NodeListOf; - getElementsByTagName(tagname: "style"): NodeListOf; - getElementsByTagName(tagname: "sub"): NodeListOf; - getElementsByTagName(tagname: "sup"): NodeListOf; - getElementsByTagName(tagname: "svg"): NodeListOf; - getElementsByTagName(tagname: "switch"): NodeListOf; - getElementsByTagName(tagname: "symbol"): NodeListOf; - getElementsByTagName(tagname: "table"): NodeListOf; - getElementsByTagName(tagname: "tbody"): NodeListOf; - getElementsByTagName(tagname: "td"): NodeListOf; - getElementsByTagName(tagname: "template"): NodeListOf; - getElementsByTagName(tagname: "text"): NodeListOf; - getElementsByTagName(tagname: "textpath"): NodeListOf; - getElementsByTagName(tagname: "textarea"): NodeListOf; - getElementsByTagName(tagname: "tfoot"): NodeListOf; - getElementsByTagName(tagname: "th"): NodeListOf; - getElementsByTagName(tagname: "thead"): NodeListOf; - getElementsByTagName(tagname: "title"): NodeListOf; - getElementsByTagName(tagname: "tr"): NodeListOf; - getElementsByTagName(tagname: "track"): NodeListOf; - getElementsByTagName(tagname: "tspan"): NodeListOf; - getElementsByTagName(tagname: "tt"): NodeListOf; - getElementsByTagName(tagname: "u"): NodeListOf; - getElementsByTagName(tagname: "ul"): NodeListOf; - getElementsByTagName(tagname: "use"): NodeListOf; - getElementsByTagName(tagname: "var"): NodeListOf; - getElementsByTagName(tagname: "video"): NodeListOf; - getElementsByTagName(tagname: "view"): NodeListOf; - getElementsByTagName(tagname: "wbr"): NodeListOf; - getElementsByTagName(tagname: "x-ms-webview"): NodeListOf; - getElementsByTagName(tagname: "xmp"): NodeListOf; - getElementsByTagName(tagname: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ - getSelection(): Selection; - /** - * Gets a value indicating whether the object currently has focus. - */ - hasFocus(): boolean; - importNode(importedNode: Node, deep: boolean): Node; - msElementsFromPoint(x: number, y: number): NodeListOf; - msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; - /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @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. - */ - queryCommandEnabled(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ - queryCommandIndeterm(commandId: string): boolean; - /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ - queryCommandState(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ - 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. - */ - queryCommandText(commandId: string): string; - /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ - queryCommandValue(commandId: string): string; - releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; - webkitCancelFullScreen(): void; - webkitExitFullscreen(): void; - /** - * 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. - * @param content The text and HTML tags to write. - */ - writeln(...content: string[]): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mssitemodejumplistitemremoved", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msthumbnailclick", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectionchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stop", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Document: { - prototype: Document; - new(): Document; -} - -interface DocumentFragment extends Node, NodeSelector, ParentNode { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentFragment: { - prototype: DocumentFragment; - new(): DocumentFragment; -} - -interface DocumentType extends Node, ChildNode { - readonly entities: NamedNodeMap; - readonly internalSubset: string | null; - readonly name: string; - readonly notations: NamedNodeMap; - readonly publicId: string | null; - readonly systemId: string | null; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentType: { - prototype: DocumentType; - new(): DocumentType; -} - -interface DragEvent extends MouseEvent { - readonly dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; - msConvertURL(file: File, targetType: string, targetURL?: string): void; -} - -declare var DragEvent: { - prototype: DragEvent; - new(): DragEvent; -} - -interface DynamicsCompressorNode extends AudioNode { - readonly attack: AudioParam; - readonly knee: AudioParam; - readonly ratio: AudioParam; - readonly reduction: AudioParam; - readonly release: AudioParam; - readonly threshold: AudioParam; -} - -declare var DynamicsCompressorNode: { - prototype: DynamicsCompressorNode; - new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { - readonly classList: DOMTokenList; - className: string; - readonly clientHeight: number; - readonly clientLeft: number; - readonly clientTop: number; - readonly clientWidth: number; - id: string; - msContentZoomFactor: number; - readonly msRegionOverflow: string; - onariarequest: (this: this, ev: AriaRequestEvent) => any; - oncommand: (this: this, ev: CommandEvent) => any; - ongotpointercapture: (this: this, ev: PointerEvent) => any; - onlostpointercapture: (this: this, ev: PointerEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsgotpointercapture: (this: this, ev: MSPointerEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmslostpointercapture: (this: this, ev: MSPointerEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - readonly prefix: string | null; - readonly scrollHeight: number; - scrollLeft: number; - scrollTop: number; - readonly scrollWidth: number; - readonly tagName: string; - innerHTML: string; - getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - getElementsByTagName(name: "a"): NodeListOf; - getElementsByTagName(name: "abbr"): NodeListOf; - getElementsByTagName(name: "acronym"): NodeListOf; - getElementsByTagName(name: "address"): NodeListOf; - getElementsByTagName(name: "applet"): NodeListOf; - getElementsByTagName(name: "area"): NodeListOf; - getElementsByTagName(name: "article"): NodeListOf; - getElementsByTagName(name: "aside"): NodeListOf; - getElementsByTagName(name: "audio"): NodeListOf; - getElementsByTagName(name: "b"): NodeListOf; - getElementsByTagName(name: "base"): NodeListOf; - getElementsByTagName(name: "basefont"): NodeListOf; - getElementsByTagName(name: "bdo"): NodeListOf; - getElementsByTagName(name: "big"): NodeListOf; - getElementsByTagName(name: "blockquote"): NodeListOf; - getElementsByTagName(name: "body"): NodeListOf; - getElementsByTagName(name: "br"): NodeListOf; - getElementsByTagName(name: "button"): NodeListOf; - getElementsByTagName(name: "canvas"): NodeListOf; - getElementsByTagName(name: "caption"): NodeListOf; - getElementsByTagName(name: "center"): NodeListOf; - getElementsByTagName(name: "circle"): NodeListOf; - getElementsByTagName(name: "cite"): NodeListOf; - getElementsByTagName(name: "clippath"): NodeListOf; - getElementsByTagName(name: "code"): NodeListOf; - getElementsByTagName(name: "col"): NodeListOf; - getElementsByTagName(name: "colgroup"): NodeListOf; - getElementsByTagName(name: "datalist"): NodeListOf; - getElementsByTagName(name: "dd"): NodeListOf; - getElementsByTagName(name: "defs"): NodeListOf; - getElementsByTagName(name: "del"): NodeListOf; - getElementsByTagName(name: "desc"): NodeListOf; - getElementsByTagName(name: "dfn"): NodeListOf; - getElementsByTagName(name: "dir"): NodeListOf; - getElementsByTagName(name: "div"): NodeListOf; - getElementsByTagName(name: "dl"): NodeListOf; - getElementsByTagName(name: "dt"): NodeListOf; - getElementsByTagName(name: "ellipse"): NodeListOf; - getElementsByTagName(name: "em"): NodeListOf; - getElementsByTagName(name: "embed"): NodeListOf; - getElementsByTagName(name: "feblend"): NodeListOf; - getElementsByTagName(name: "fecolormatrix"): NodeListOf; - getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(name: "fecomposite"): NodeListOf; - getElementsByTagName(name: "feconvolvematrix"): NodeListOf; - getElementsByTagName(name: "fediffuselighting"): NodeListOf; - getElementsByTagName(name: "fedisplacementmap"): NodeListOf; - getElementsByTagName(name: "fedistantlight"): NodeListOf; - getElementsByTagName(name: "feflood"): NodeListOf; - getElementsByTagName(name: "fefunca"): NodeListOf; - getElementsByTagName(name: "fefuncb"): NodeListOf; - getElementsByTagName(name: "fefuncg"): NodeListOf; - getElementsByTagName(name: "fefuncr"): NodeListOf; - getElementsByTagName(name: "fegaussianblur"): NodeListOf; - getElementsByTagName(name: "feimage"): NodeListOf; - getElementsByTagName(name: "femerge"): NodeListOf; - getElementsByTagName(name: "femergenode"): NodeListOf; - getElementsByTagName(name: "femorphology"): NodeListOf; - getElementsByTagName(name: "feoffset"): NodeListOf; - getElementsByTagName(name: "fepointlight"): NodeListOf; - getElementsByTagName(name: "fespecularlighting"): NodeListOf; - getElementsByTagName(name: "fespotlight"): NodeListOf; - getElementsByTagName(name: "fetile"): NodeListOf; - getElementsByTagName(name: "feturbulence"): NodeListOf; - getElementsByTagName(name: "fieldset"): NodeListOf; - getElementsByTagName(name: "figcaption"): NodeListOf; - getElementsByTagName(name: "figure"): NodeListOf; - getElementsByTagName(name: "filter"): NodeListOf; - getElementsByTagName(name: "font"): NodeListOf; - getElementsByTagName(name: "footer"): NodeListOf; - getElementsByTagName(name: "foreignobject"): NodeListOf; - getElementsByTagName(name: "form"): NodeListOf; - getElementsByTagName(name: "frame"): NodeListOf; - getElementsByTagName(name: "frameset"): NodeListOf; - getElementsByTagName(name: "g"): NodeListOf; - getElementsByTagName(name: "h1"): NodeListOf; - getElementsByTagName(name: "h2"): NodeListOf; - getElementsByTagName(name: "h3"): NodeListOf; - getElementsByTagName(name: "h4"): NodeListOf; - getElementsByTagName(name: "h5"): NodeListOf; - getElementsByTagName(name: "h6"): NodeListOf; - getElementsByTagName(name: "head"): NodeListOf; - getElementsByTagName(name: "header"): NodeListOf; - getElementsByTagName(name: "hgroup"): NodeListOf; - getElementsByTagName(name: "hr"): NodeListOf; - getElementsByTagName(name: "html"): NodeListOf; - getElementsByTagName(name: "i"): NodeListOf; - getElementsByTagName(name: "iframe"): NodeListOf; - getElementsByTagName(name: "image"): NodeListOf; - getElementsByTagName(name: "img"): NodeListOf; - getElementsByTagName(name: "input"): NodeListOf; - getElementsByTagName(name: "ins"): NodeListOf; - getElementsByTagName(name: "isindex"): NodeListOf; - getElementsByTagName(name: "kbd"): NodeListOf; - getElementsByTagName(name: "keygen"): NodeListOf; - getElementsByTagName(name: "label"): NodeListOf; - getElementsByTagName(name: "legend"): NodeListOf; - getElementsByTagName(name: "li"): NodeListOf; - getElementsByTagName(name: "line"): NodeListOf; - getElementsByTagName(name: "lineargradient"): NodeListOf; - getElementsByTagName(name: "link"): NodeListOf; - getElementsByTagName(name: "listing"): NodeListOf; - getElementsByTagName(name: "map"): NodeListOf; - getElementsByTagName(name: "mark"): NodeListOf; - getElementsByTagName(name: "marker"): NodeListOf; - getElementsByTagName(name: "marquee"): NodeListOf; - getElementsByTagName(name: "mask"): NodeListOf; - getElementsByTagName(name: "menu"): NodeListOf; - getElementsByTagName(name: "meta"): NodeListOf; - getElementsByTagName(name: "metadata"): NodeListOf; - getElementsByTagName(name: "meter"): NodeListOf; - getElementsByTagName(name: "nav"): NodeListOf; - getElementsByTagName(name: "nextid"): NodeListOf; - getElementsByTagName(name: "nobr"): NodeListOf; - getElementsByTagName(name: "noframes"): NodeListOf; - getElementsByTagName(name: "noscript"): NodeListOf; - getElementsByTagName(name: "object"): NodeListOf; - getElementsByTagName(name: "ol"): NodeListOf; - getElementsByTagName(name: "optgroup"): NodeListOf; - getElementsByTagName(name: "option"): NodeListOf; - getElementsByTagName(name: "p"): NodeListOf; - getElementsByTagName(name: "param"): NodeListOf; - getElementsByTagName(name: "path"): NodeListOf; - getElementsByTagName(name: "pattern"): NodeListOf; - getElementsByTagName(name: "picture"): NodeListOf; - getElementsByTagName(name: "plaintext"): NodeListOf; - getElementsByTagName(name: "polygon"): NodeListOf; - getElementsByTagName(name: "polyline"): NodeListOf; - getElementsByTagName(name: "pre"): NodeListOf; - getElementsByTagName(name: "progress"): NodeListOf; - getElementsByTagName(name: "q"): NodeListOf; - getElementsByTagName(name: "radialgradient"): NodeListOf; - getElementsByTagName(name: "rect"): NodeListOf; - getElementsByTagName(name: "rt"): NodeListOf; - getElementsByTagName(name: "ruby"): NodeListOf; - getElementsByTagName(name: "s"): NodeListOf; - getElementsByTagName(name: "samp"): NodeListOf; - getElementsByTagName(name: "script"): NodeListOf; - getElementsByTagName(name: "section"): NodeListOf; - getElementsByTagName(name: "select"): NodeListOf; - getElementsByTagName(name: "small"): NodeListOf; - getElementsByTagName(name: "source"): NodeListOf; - getElementsByTagName(name: "span"): NodeListOf; - getElementsByTagName(name: "stop"): NodeListOf; - getElementsByTagName(name: "strike"): NodeListOf; - getElementsByTagName(name: "strong"): NodeListOf; - getElementsByTagName(name: "style"): NodeListOf; - getElementsByTagName(name: "sub"): NodeListOf; - getElementsByTagName(name: "sup"): NodeListOf; - getElementsByTagName(name: "svg"): NodeListOf; - getElementsByTagName(name: "switch"): NodeListOf; - getElementsByTagName(name: "symbol"): NodeListOf; - getElementsByTagName(name: "table"): NodeListOf; - getElementsByTagName(name: "tbody"): NodeListOf; - getElementsByTagName(name: "td"): NodeListOf; - getElementsByTagName(name: "template"): NodeListOf; - getElementsByTagName(name: "text"): NodeListOf; - getElementsByTagName(name: "textpath"): NodeListOf; - getElementsByTagName(name: "textarea"): NodeListOf; - getElementsByTagName(name: "tfoot"): NodeListOf; - getElementsByTagName(name: "th"): NodeListOf; - getElementsByTagName(name: "thead"): NodeListOf; - getElementsByTagName(name: "title"): NodeListOf; - getElementsByTagName(name: "tr"): NodeListOf; - getElementsByTagName(name: "track"): NodeListOf; - getElementsByTagName(name: "tspan"): NodeListOf; - getElementsByTagName(name: "tt"): NodeListOf; - getElementsByTagName(name: "u"): NodeListOf; - getElementsByTagName(name: "ul"): NodeListOf; - getElementsByTagName(name: "use"): NodeListOf; - getElementsByTagName(name: "var"): NodeListOf; - getElementsByTagName(name: "video"): NodeListOf; - getElementsByTagName(name: "view"): NodeListOf; - getElementsByTagName(name: "wbr"): NodeListOf; - getElementsByTagName(name: "x-ms-webview"): NodeListOf; - getElementsByTagName(name: "xmp"): NodeListOf; - getElementsByTagName(name: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - hasAttribute(name: string): boolean; - hasAttributeNS(namespaceURI: string, localName: string): boolean; - msGetRegionContent(): MSRangeCollection; - msGetUntransformedBounds(): ClientRect; - msMatchesSelector(selectors: string): boolean; - msReleasePointerCapture(pointerId: number): void; - msSetPointerCapture(pointerId: number): void; - msZoomTo(args: MsZoomToOptions): void; - releasePointerCapture(pointerId: number): void; - removeAttribute(name?: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; - removeAttributeNode(oldAttr: Attr): Attr; - requestFullscreen(): void; - requestPointerLock(): void; - setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; - setAttributeNode(newAttr: Attr): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; - setPointerCapture(pointerId: number): void; - webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; - webkitRequestFullscreen(): void; - getElementsByClassName(classNames: string): NodeListOf; - matches(selector: string): boolean; - closest(selector: string): Element | null; - scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; - scroll(options?: ScrollToOptions): void; - scroll(x: number, y: number): void; - scrollTo(options?: ScrollToOptions): void; - scrollTo(x: number, y: number): void; - scrollBy(options?: ScrollToOptions): void; - scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Element: { - prototype: Element; - new(): Element; -} - -interface ErrorEvent extends Event { - readonly colno: number; - readonly error: any; - readonly filename: string; - readonly lineno: number; - readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; -} - -declare var ErrorEvent: { - prototype: ErrorEvent; - new(): ErrorEvent; -} - -interface Event { - readonly bubbles: boolean; - cancelBubble: boolean; - readonly cancelable: boolean; - readonly currentTarget: EventTarget; - readonly defaultPrevented: boolean; - readonly eventPhase: number; - readonly isTrusted: boolean; - returnValue: boolean; - readonly srcElement: Element | null; - readonly target: EventTarget; - readonly timeStamp: number; - readonly type: string; - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; - preventDefault(): void; - stopImmediatePropagation(): void; - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -declare var Event: { - prototype: Event; - new(type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -interface EventTarget { - addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var EventTarget: { - prototype: EventTarget; - new(): EventTarget; -} - -interface External { -} - -declare var External: { - prototype: External; - new(): External; -} - -interface File extends Blob { - readonly lastModifiedDate: any; - readonly name: string; - readonly webkitRelativePath: string; -} - -declare var File: { - prototype: File; - new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} - -interface FileList { - readonly length: number; - item(index: number): File; - [index: number]: File; -} - -declare var FileList: { - prototype: FileList; - new(): FileList; -} - -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(blob: Blob): void; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var FileReader: { - prototype: FileReader; - new(): FileReader; -} - -interface FocusEvent extends UIEvent { - readonly relatedTarget: EventTarget; - initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; -} - -declare var FocusEvent: { - prototype: FocusEvent; - new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} - -interface FormData { - append(name: any, value: any, blobName?: string): void; -} - -declare var FormData: { - prototype: FormData; - new (form?: HTMLFormElement): FormData; -} - -interface GainNode extends AudioNode { - readonly gain: AudioParam; -} - -declare var GainNode: { - prototype: GainNode; - new(): GainNode; -} - -interface Gamepad { - readonly axes: number[]; - readonly buttons: GamepadButton[]; - readonly connected: boolean; - readonly id: string; - readonly index: number; - readonly mapping: string; - readonly timestamp: number; -} - -declare var Gamepad: { - prototype: Gamepad; - new(): Gamepad; -} - -interface GamepadButton { - readonly pressed: boolean; - readonly value: number; -} - -declare var GamepadButton: { - prototype: GamepadButton; - new(): GamepadButton; -} - -interface GamepadEvent extends Event { - readonly gamepad: Gamepad; -} - -declare var GamepadEvent: { - prototype: GamepadEvent; - new(): GamepadEvent; -} - -interface Geolocation { - clearWatch(watchId: number): void; - getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; - watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; -} - -declare var Geolocation: { - prototype: Geolocation; - new(): Geolocation; -} - -interface HTMLAllCollection extends HTMLCollection { - namedItem(name: string): Element; -} - -declare var HTMLAllCollection: { - prototype: HTMLAllCollection; - new(): HTMLAllCollection; -} - -interface HTMLAnchorElement extends HTMLElement { - Methods: string; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Contains the anchor portion of the URL including the hash sign (#). - */ - hash: string; - /** - * Contains the hostname and port values of the URL. - */ - host: string; - /** - * Contains the hostname of a URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - readonly mimeType: string; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - readonly nameProp: string; - /** - * Contains the pathname of the URL. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Contains the protocol of the URL. - */ - protocol: string; - readonly protocolLong: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: 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; -} - -declare var HTMLAnchorElement: { - prototype: HTMLAnchorElement; - new(): HTMLAnchorElement; -} - -interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ - declare: boolean; - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - object: string | null; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - vspace: number; - width: number; -} - -declare var HTMLAppletElement: { - prototype: HTMLAppletElement; - new(): HTMLAppletElement; -} - -interface HTMLAreaElement extends HTMLElement { - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ - hash: string; - /** - * Sets or retrieves the hostname and port number of the location or URL. - */ - host: string; - /** - * Sets or retrieves the host name part of the location or URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or gets whether clicks in this region cause action. - */ - noHref: boolean; - /** - * Sets or retrieves the file name or path specified by the object. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Sets or retrieves the protocol portion of a URL. - */ - protocol: string; - rel: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns a string representation of an object. - */ - toString(): string; -} - -declare var HTMLAreaElement: { - prototype: HTMLAreaElement; - new(): HTMLAreaElement; -} - -interface HTMLAreasCollection extends HTMLCollection { - /** - * Adds an element to the areas, controlRange, or options collection. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Removes an element from the collection. - */ - remove(index?: number): void; -} - -declare var HTMLAreasCollection: { - prototype: HTMLAreasCollection; - new(): HTMLAreasCollection; -} - -interface HTMLAudioElement extends HTMLMediaElement { -} - -declare var HTMLAudioElement: { - prototype: HTMLAudioElement; - new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} - -interface HTMLBaseElement extends HTMLElement { - /** - * Gets or sets the baseline URL on which relative links are based. - */ - href: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; -} - -declare var HTMLBaseElement: { - prototype: HTMLBaseElement; - new(): HTMLBaseElement; -} - -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - /** - * Sets or retrieves the font size of the object. - */ - size: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -} - -interface HTMLBodyElement extends HTMLElement { - aLink: any; - background: string; - bgColor: any; - bgProperties: string; - link: any; - noWrap: boolean; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - text: any; - vLink: any; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBodyElement: { - prototype: HTMLBodyElement; - new(): HTMLBodyElement; -} - -interface HTMLButtonElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - status: any; - /** - * Gets the classification and default behavior of the button. - */ - type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * 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; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLButtonElement: { - prototype: HTMLButtonElement; - new(): HTMLButtonElement; -} - -interface HTMLCanvasElement extends HTMLElement { - /** - * Gets or sets the height of a canvas element on a document. - */ - height: number; - /** - * Gets or sets the width of a canvas element on a document. - */ - width: number; - /** - * 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", 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. - */ - msToBlob(): Blob; - /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; -} - -declare var HTMLCanvasElement: { - prototype: HTMLCanvasElement; - new(): HTMLCanvasElement; -} - -interface HTMLCollection { - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Retrieves an object from various collections. - */ - item(index: number): Element; - /** - * Retrieves a select object or an object from an options collection. - */ - namedItem(name: string): Element; - [index: number]: Element; -} - -declare var HTMLCollection: { - prototype: HTMLCollection; - new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} - -interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; -} - -declare var HTMLDataListElement: { - prototype: HTMLDataListElement; - new(): HTMLDataListElement; -} - -interface HTMLDirectoryElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDirectoryElement: { - prototype: HTMLDirectoryElement; - new(): HTMLDirectoryElement; -} - -interface HTMLDivElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; -} - -declare var HTMLDivElement: { - prototype: HTMLDivElement; - new(): HTMLDivElement; -} - -interface HTMLDocument extends Document { -} - -declare var HTMLDocument: { - prototype: HTMLDocument; - new(): HTMLDocument; -} - -interface HTMLElement extends Element { - accessKey: string; - readonly children: HTMLCollection; - contentEditable: string; - readonly dataset: DOMStringMap; - dir: string; - draggable: boolean; - hidden: boolean; - hideFocus: boolean; - innerHTML: string; - innerText: string; - readonly isContentEditable: boolean; - lang: string; - readonly offsetHeight: number; - readonly offsetLeft: number; - readonly offsetParent: Element; - readonly offsetTop: number; - readonly offsetWidth: number; - onabort: (this: this, ev: UIEvent) => any; - onactivate: (this: this, ev: UIEvent) => any; - onbeforeactivate: (this: this, ev: UIEvent) => any; - onbeforecopy: (this: this, ev: ClipboardEvent) => any; - onbeforecut: (this: this, ev: ClipboardEvent) => any; - onbeforedeactivate: (this: this, ev: UIEvent) => any; - onbeforepaste: (this: this, ev: ClipboardEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - oncopy: (this: this, ev: ClipboardEvent) => any; - oncuechange: (this: this, ev: Event) => any; - oncut: (this: this, ev: ClipboardEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondeactivate: (this: this, ev: UIEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onpaste: (this: this, ev: ClipboardEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreset: (this: this, ev: Event) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onselectstart: (this: this, ev: Event) => any; - onstalled: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - outerHTML: string; - outerText: string; - spellcheck: boolean; - readonly style: CSSStyleDeclaration; - tabIndex: number; - title: string; - blur(): void; - click(): void; - dragDrop(): boolean; - focus(): void; - msGetInputContext(): MSInputMethodContext; - setActive(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLElement: { - prototype: HTMLElement; - new(): HTMLElement; -} - -interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves the height of the object. - */ - height: string; - hidden: any; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the palette used for the embedded document. - */ - readonly palette: string; - /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ - readonly pluginspage: string; - readonly readyState: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the height and width units of the embed object. - */ - units: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLEmbedElement: { - prototype: HTMLEmbedElement; - new(): HTMLEmbedElement; -} - -interface HTMLFieldSetElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLFieldSetElement: { - prototype: HTMLFieldSetElement; - new(): HTMLFieldSetElement; -} - -interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFontElement: { - prototype: HTMLFontElement; - new(): HTMLFontElement; -} - -interface HTMLFormElement extends HTMLElement { - /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ - acceptCharset: string; - /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ - action: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Retrieves a collection, in source order, of all controls in a given form. - */ - readonly elements: HTMLCollection; - /** - * Sets or retrieves the MIME encoding for the form. - */ - encoding: string; - /** - * Sets or retrieves the encoding type for the form. - */ - enctype: string; - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Sets or retrieves how to send the form data to the server. - */ - method: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Designates a form that is not validated when submitted. - */ - noValidate: boolean; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a form object or an object from an elements collection. - */ - namedItem(name: string): any; - /** - * Fires when the user resets a form. - */ - reset(): void; - /** - * Fires when a FORM is about to be submitted. - */ - submit(): void; - [name: string]: any; -} - -declare var HTMLFormElement: { - prototype: HTMLFormElement; - new(): HTMLFormElement; -} - -interface HTMLFrameElement extends HTMLElement, GetSVGDocument { - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string | number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the width of the object. - */ - width: string | number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameElement: { - prototype: HTMLFrameElement; - new(): HTMLFrameElement; -} - -interface HTMLFrameSetElement extends HTMLElement { - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Sets or retrieves the frame widths of the object. - */ - cols: string; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - name: string; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - /** - * Sets or retrieves the frame heights of the object. - */ - rows: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameSetElement: { - prototype: HTMLFrameSetElement; - new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} - -interface HTMLHeadElement extends HTMLElement { - profile: string; -} - -declare var HTMLHeadElement: { - prototype: HTMLHeadElement; - new(): HTMLHeadElement; -} - -interface HTMLHeadingElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; -} - -declare var HTMLHeadingElement: { - prototype: HTMLHeadingElement; - new(): HTMLHeadingElement; -} - -interface HTMLHtmlElement extends HTMLElement { - /** - * Sets or retrieves the DTD version that governs the current document. - */ - version: string; -} - -declare var HTMLHtmlElement: { - prototype: HTMLHtmlElement; - new(): HTMLHtmlElement; -} - -interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - allowFullscreen: boolean; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the horizontal margin for the object. - */ - hspace: number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - readonly sandbox: DOMSettableTokenList; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLIFrameElement: { - prototype: HTMLIFrameElement; - new(): HTMLIFrameElement; -} - -interface HTMLImageElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - crossOrigin: string; - readonly currentSrc: string; - /** - * Sets or retrieves the height of the object. - */ - height: number; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - /** - * Sets or retrieves whether the image is a server-side image map. - */ - isMap: boolean; - /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ - longDesc: string; - lowsrc: string; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * The original height of the image resource before sizing. - */ - readonly naturalHeight: number; - /** - * The original width of the image resource before sizing. - */ - readonly naturalWidth: number; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: number; - readonly x: number; - readonly y: number; - msGetAsCastingSource(): any; -} - -declare var HTMLImageElement: { - prototype: HTMLImageElement; - new(): HTMLImageElement; - create(): HTMLImageElement; -} - -interface HTMLInputElement extends HTMLElement { - /** - * Sets or retrieves a comma-separated list of content types. - */ - accept: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the state of the check box or radio button. - */ - checked: boolean; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - /** - * Sets or retrieves the state of the check box or radio button. - */ - defaultChecked: boolean; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Returns a FileList object on a file type input object. - */ - readonly files: FileList | null; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - indeterminate: boolean; - /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ - readonly list: HTMLElement; - /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ - max: string; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ - min: string; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ - pattern: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - selectionDirection: string; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - size: number; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - status: boolean; - /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ - step: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns the value of the data at the cursor's current position. - */ - value: string; - valueAsDate: Date; - /** - * Returns the input field value as a number. - */ - valueAsNumber: number; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - webkitdirectory: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Makes the selection equal to the current object. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start?: number, end?: number, direction?: string): void; - /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ - stepDown(n?: number): void; - /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ - stepUp(n?: number): void; -} - -declare var HTMLInputElement: { - prototype: HTMLInputElement; - new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} - -interface HTMLLabelElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the object to which the given label object is assigned. - */ - htmlFor: string; -} - -declare var HTMLLabelElement: { - prototype: HTMLLabelElement; - new(): HTMLLabelElement; -} - -interface HTMLLegendElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - align: string; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; -} - -declare var HTMLLegendElement: { - prototype: HTMLLegendElement; - new(): HTMLLegendElement; -} - -interface HTMLLinkElement extends HTMLElement, LinkStyle { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - disabled: boolean; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - import?: Document; - integrity: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLinkElement: { - prototype: HTMLLinkElement; - new(): HTMLLinkElement; -} - -interface HTMLMapElement extends HTMLElement { - /** - * Retrieves a collection of the area objects defined for the given map object. - */ - readonly areas: HTMLAreasCollection; - /** - * Sets or retrieves the name of the object. - */ - name: string; -} - -declare var HTMLMapElement: { - prototype: HTMLMapElement; - new(): HTMLMapElement; -} - -interface HTMLMarqueeElement extends HTMLElement { - behavior: string; - bgColor: any; - direction: string; - height: string; - hspace: number; - loop: number; - onbounce: (this: this, ev: Event) => any; - onfinish: (this: this, ev: Event) => any; - onstart: (this: this, ev: Event) => any; - scrollAmount: number; - scrollDelay: number; - trueSpeed: boolean; - vspace: number; - width: string; - start(): void; - stop(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "bounce", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "finish", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "start", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMarqueeElement: { - prototype: HTMLMarqueeElement; - new(): HTMLMarqueeElement; -} - -interface HTMLMediaElement extends HTMLElement { - /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ - readonly audioTracks: AudioTrackList; - /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ - autoplay: boolean; - /** - * Gets a collection of buffered time ranges. - */ - readonly buffered: TimeRanges; - /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ - controls: boolean; - crossOrigin: string; - /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ - readonly currentSrc: string; - /** - * Gets or sets the current playback position, in seconds. - */ - currentTime: number; - defaultMuted: boolean; - /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ - defaultPlaybackRate: number; - /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ - readonly duration: number; - /** - * Gets information about whether the playback has ended or not. - */ - readonly ended: boolean; - /** - * Returns an object representing the current error state of the audio or video element. - */ - readonly error: MediaError; - /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ - loop: boolean; - readonly mediaKeys: MediaKeys | null; - /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ - msAudioCategory: string; - /** - * Specifies the output device id that the audio will be sent to. - */ - msAudioDeviceType: string; - readonly msGraphicsTrustStatus: MSGraphicsTrust; - /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ - readonly msKeys: MSMediaKeys; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Specifies whether or not to enable low-latency playback on the media element. - */ - msRealTime: boolean; - /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ - muted: boolean; - /** - * Gets the current network activity for the element. - */ - readonly networkState: number; - onencrypted: (this: this, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: this, ev: MSMediaKeyNeededEvent) => any; - /** - * Gets a flag that specifies whether playback is paused. - */ - readonly paused: boolean; - /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ - playbackRate: number; - /** - * Gets TimeRanges for the current media resource that has been played. - */ - readonly played: TimeRanges; - /** - * Gets or sets the current playback position, in seconds. - */ - preload: string; - readyState: number; - /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ - readonly seekable: TimeRanges; - /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ - readonly seeking: boolean; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcObject: MediaStream | null; - readonly textTracks: TextTrackList; - readonly videoTracks: VideoTrackList; - /** - * Gets or sets the volume level for audio portions of the media element. - */ - volume: number; - addTextTrack(kind: string, label?: string, language?: string): TextTrack; - /** - * Returns a string that specifies whether the client can play a given media resource type. - */ - canPlayType(type: string): string; - /** - * Resets the audio or video object and loads a new media resource. - */ - load(): void; - /** - * Clears all effects from the media pipeline. - */ - msClearEffects(): void; - msGetAsCastingSource(): any; - /** - * Inserts the specified audio effect into media pipeline. - */ - msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetMediaKeys(mediaKeys: MSMediaKeys): void; - /** - * Specifies the media protection manager for a given media pipeline. - */ - msSetMediaProtectionManager(mediaProtectionManager?: any): void; - /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ - pause(): void; - /** - * Loads and starts playback of a media resource. - */ - play(): void; - setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMediaElement: { - prototype: HTMLMediaElement; - new(): HTMLMediaElement; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; -} - -interface HTMLMenuElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLMenuElement: { - prototype: HTMLMenuElement; - new(): HTMLMenuElement; -} - -interface HTMLMetaElement extends HTMLElement { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ - content: string; - /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ - httpEquiv: string; - /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ - name: string; - /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ - scheme: string; - /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ - url: string; -} - -declare var HTMLMetaElement: { - prototype: HTMLMetaElement; - new(): HTMLMetaElement; -} - -interface HTMLMeterElement extends HTMLElement { - high: number; - low: number; - max: number; - min: number; - optimum: number; - value: number; -} - -declare var HTMLMeterElement: { - prototype: HTMLMeterElement; - new(): HTMLMeterElement; -} - -interface HTMLModElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; - /** - * Sets or retrieves the date and time of a modification to the object. - */ - dateTime: string; -} - -declare var HTMLModElement: { - prototype: HTMLModElement; - new(): HTMLModElement; -} - -interface HTMLOListElement extends HTMLElement { - compact: boolean; - /** - * The starting number. - */ - start: number; - type: string; -} - -declare var HTMLOListElement: { - prototype: HTMLOListElement; - new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the contained object. - */ - readonly object: any; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} - -interface HTMLOptGroupElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - readonly text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptGroupElement: { - prototype: HTMLOptGroupElement; - new(): HTMLOptGroupElement; -} - -interface HTMLOptionElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptionElement: { - prototype: HTMLOptionElement; - new(): HTMLOptionElement; - create(): HTMLOptionElement; -} - -interface HTMLOptionsCollection extends HTMLCollectionOf { - length: number; - selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; - remove(index: number): void; -} - -declare var HTMLOptionsCollection: { - prototype: HTMLOptionsCollection; - new(): HTMLOptionsCollection; -} - -interface HTMLParagraphElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - clear: string; -} - -declare var HTMLParagraphElement: { - prototype: HTMLParagraphElement; - new(): HTMLParagraphElement; -} - -interface HTMLParamElement extends HTMLElement { - /** - * Sets or retrieves the name of an input parameter for an element. - */ - name: string; - /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ - type: string; - /** - * Sets or retrieves the value of an input parameter for an element. - */ - value: string; - /** - * Sets or retrieves the data type of the value attribute. - */ - valueType: string; -} - -declare var HTMLParamElement: { - prototype: HTMLParamElement; - new(): HTMLParamElement; -} - -interface HTMLPictureElement extends HTMLElement { -} - -declare var HTMLPictureElement: { - prototype: HTMLPictureElement; - new(): HTMLPictureElement; -} - -interface HTMLPreElement extends HTMLElement { - /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ - width: number; -} - -declare var HTMLPreElement: { - prototype: HTMLPreElement; - new(): HTMLPreElement; -} - -interface HTMLProgressElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Defines the maximum, or "done" value for a progress element. - */ - max: number; - /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ - readonly position: number; - /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ - value: number; -} - -declare var HTMLProgressElement: { - prototype: HTMLProgressElement; - new(): HTMLProgressElement; -} - -interface HTMLQuoteElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; -} - -declare var HTMLQuoteElement: { - prototype: HTMLQuoteElement; - new(): HTMLQuoteElement; -} - -interface HTMLScriptElement extends HTMLElement { - async: boolean; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the status of the script. - */ - defer: boolean; - /** - * 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; - /** - * Retrieves the URL to an external file that contains the source code or data. - */ - src: string; - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; - /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ - type: string; - integrity: string; -} - -declare var HTMLScriptElement: { - prototype: HTMLScriptElement; - new(): HTMLScriptElement; -} - -interface HTMLSelectElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the number of objects in a collection. - */ - length: number; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly options: HTMLOptionsCollection; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the index of the selected option in a select object. - */ - selectedIndex: number; - selectedOptions: HTMLCollectionOf; - /** - * Sets or retrieves the number of rows in the list box. - */ - size: number; - /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * 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. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ - namedItem(name: string): any; - /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ - remove(index?: number): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - [name: string]: any; -} - -declare var HTMLSelectElement: { - prototype: HTMLSelectElement; - new(): HTMLSelectElement; -} - -interface HTMLSourceElement extends HTMLElement { - /** - * Gets or sets the intended media type of the media source. - */ - media: string; - msKeySystem: string; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Gets or sets the MIME type of a media resource. - */ - type: string; -} - -declare var HTMLSourceElement: { - prototype: HTMLSourceElement; - new(): HTMLSourceElement; -} - -interface HTMLSpanElement extends HTMLElement { -} - -declare var HTMLSpanElement: { - prototype: HTMLSpanElement; - new(): HTMLSpanElement; -} - -interface HTMLStyleElement extends HTMLElement, LinkStyle { - disabled: boolean; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Retrieves the CSS language in which the style sheet is written. - */ - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLStyleElement: { - prototype: HTMLStyleElement; - new(): HTMLStyleElement; -} - -interface HTMLTableCaptionElement extends HTMLElement { - /** - * Sets or retrieves the alignment of the caption or legend. - */ - align: string; - /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ - vAlign: string; -} - -declare var HTMLTableCaptionElement: { - prototype: HTMLTableCaptionElement; - new(): HTMLTableCaptionElement; -} - -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves abbreviated text for the object. - */ - abbr: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ - axis: string; - bgColor: any; - /** - * Retrieves the position of the object in the cells collection of a row. - */ - readonly cellIndex: number; - /** - * Sets or retrieves the number columns in the table that the object should span. - */ - colSpan: number; - /** - * Sets or retrieves a list of header cells that provide information for the object. - */ - headers: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; - /** - * Sets or retrieves how many rows in a table the cell should span. - */ - rowSpan: number; - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableCellElement: { - prototype: HTMLTableCellElement; - new(): HTMLTableCellElement; -} - -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ - align: string; - /** - * Sets or retrieves the number of columns in the group. - */ - span: number; - /** - * Sets or retrieves the width of the object. - */ - width: any; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableColElement: { - prototype: HTMLTableColElement; - new(): HTMLTableColElement; -} - -interface HTMLTableDataCellElement extends HTMLTableCellElement { -} - -declare var HTMLTableDataCellElement: { - prototype: HTMLTableDataCellElement; - new(): HTMLTableDataCellElement; -} - -interface HTMLTableElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - bgColor: any; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the caption object of a table. - */ - caption: HTMLTableCaptionElement; - /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ - cellPadding: string; - /** - * Sets or retrieves the amount of space between cells in a table. - */ - cellSpacing: string; - /** - * Sets or retrieves the number of columns in the table. - */ - cols: number; - /** - * Sets or retrieves the way the border frame around the table is displayed. - */ - frame: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ - rules: string; - /** - * Sets or retrieves a description and/or structure of the object. - */ - summary: string; - /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ - tBodies: HTMLCollectionOf; - /** - * Retrieves the tFoot object of the table. - */ - tFoot: HTMLTableSectionElement; - /** - * Retrieves the tHead object of the table. - */ - tHead: HTMLTableSectionElement; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Creates an empty caption element in the table. - */ - createCaption(): HTMLTableCaptionElement; - /** - * Creates an empty tBody element in the table. - */ - createTBody(): HTMLTableSectionElement; - /** - * Creates an empty tFoot element in the table. - */ - createTFoot(): HTMLTableSectionElement; - /** - * Returns the tHead element object if successful, or null otherwise. - */ - createTHead(): HTMLTableSectionElement; - /** - * Deletes the caption element and its contents from the table. - */ - deleteCaption(): void; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Deletes the tFoot element and its contents from the table. - */ - deleteTFoot(): void; - /** - * Deletes the tHead element and its contents from the table. - */ - deleteTHead(): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; -} - -declare var HTMLTableElement: { - prototype: HTMLTableElement; - new(): HTMLTableElement; -} - -interface HTMLTableHeaderCellElement extends HTMLTableCellElement { - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; -} - -declare var HTMLTableHeaderCellElement: { - prototype: HTMLTableHeaderCellElement; - new(): HTMLTableHeaderCellElement; -} - -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - bgColor: any; - /** - * Retrieves a collection of all cells in the table row. - */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Retrieves the position of the object in the rows collection for the table. - */ - readonly rowIndex: number; - /** - * Retrieves the position of the object in the collection. - */ - readonly sectionRowIndex: number; - /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ - deleteCell(index?: number): void; - /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ - insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableRowElement: { - prototype: HTMLTableRowElement; - new(): HTMLTableRowElement; -} - -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableSectionElement: { - prototype: HTMLTableSectionElement; - new(): HTMLTableSectionElement; -} - -interface HTMLTemplateElement extends HTMLElement { - readonly content: DocumentFragment; -} - -declare var HTMLTemplateElement: { - prototype: HTMLTemplateElement; - new(): HTMLTemplateElement; -} - -interface HTMLTextAreaElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the object. - */ - cols: number; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: number; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - /** - * Sets or retrieves the value indicating whether the control is selected. - */ - status: any; - /** - * Retrieves the type of control. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Retrieves or sets the text in the entry field of the textArea element. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Sets or retrieves how to handle wordwrapping in the object. - */ - wrap: string; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Highlights the input area of a form element. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start: number, end: number): void; -} - -declare var HTMLTextAreaElement: { - prototype: HTMLTextAreaElement; - new(): HTMLTextAreaElement; -} - -interface HTMLTitleElement extends HTMLElement { - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; -} - -declare var HTMLTitleElement: { - prototype: HTMLTitleElement; - new(): HTMLTitleElement; -} - -interface HTMLTrackElement extends HTMLElement { - default: boolean; - kind: string; - label: string; - readonly readyState: number; - src: string; - srclang: string; - readonly track: TextTrack; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -declare var HTMLTrackElement: { - prototype: HTMLTrackElement; - new(): HTMLTrackElement; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -interface HTMLUListElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLUListElement: { - prototype: HTMLUListElement; - new(): HTMLUListElement; -} - -interface HTMLUnknownElement extends HTMLElement { -} - -declare var HTMLUnknownElement: { - prototype: HTMLUnknownElement; - new(): HTMLUnknownElement; -} - -interface HTMLVideoElement extends HTMLMediaElement { - /** - * Gets or sets the height of the video element. - */ - height: number; - msHorizontalMirror: boolean; - readonly msIsLayoutOptimalForPlayback: boolean; - readonly msIsStereo3D: boolean; - msStereo3DPackingMode: string; - msStereo3DRenderMode: string; - msZoom: boolean; - onMSVideoFormatChanged: (this: this, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: this, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: this, ev: Event) => any; - /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ - poster: string; - /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoHeight: number; - /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoWidth: number; - readonly webkitDisplayingFullscreen: boolean; - readonly webkitSupportsFullscreen: boolean; - /** - * Gets or sets the width of the video element. - */ - width: number; - getVideoPlaybackQuality(): VideoPlaybackQuality; - msFrameStep(forward: boolean): void; - msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; - webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; - webkitExitFullscreen(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFormatChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFrameStepCompleted", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLVideoElement: { - prototype: HTMLVideoElement; - new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface History { - readonly length: number; - readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; -} - -declare var History: { - prototype: History; - new(): History; -} - -interface IDBCursor { - readonly direction: string; - key: IDBKeyRange | IDBValidKey; - readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; - advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; - delete(): IDBRequest; - update(value: any): IDBRequest; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -declare var IDBCursor: { - prototype: IDBCursor; - new(): IDBCursor; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -interface IDBCursorWithValue extends IDBCursor { - readonly value: any; -} - -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new(): IDBCursorWithValue; -} - -interface IDBDatabase extends EventTarget { - readonly name: string; - readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - version: number; - onversionchange: (ev: IDBVersionChangeEvent) => any; - close(): void; - createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; - deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBDatabase: { - prototype: IDBDatabase; - new(): IDBDatabase; -} - -interface IDBFactory { - cmp(first: any, second: any): number; - deleteDatabase(name: string): IDBOpenDBRequest; - open(name: string, version?: number): IDBOpenDBRequest; -} - -declare var IDBFactory: { - prototype: IDBFactory; - new(): IDBFactory; -} - -interface IDBIndex { - keyPath: string | string[]; - readonly name: string; - readonly objectStore: IDBObjectStore; - readonly unique: boolean; - multiEntry: boolean; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - get(key: IDBKeyRange | IDBValidKey): IDBRequest; - getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; -} - -declare var IDBIndex: { - prototype: IDBIndex; - new(): IDBIndex; -} - -interface IDBKeyRange { - readonly lower: any; - readonly lowerOpen: boolean; - readonly upper: any; - readonly upperOpen: boolean; -} - -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new(): IDBKeyRange; - bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; - lowerBound(lower: any, open?: boolean): IDBKeyRange; - only(value: any): IDBKeyRange; - upperBound(upper: any, open?: boolean): IDBKeyRange; -} - -interface IDBObjectStore { - readonly indexNames: DOMStringList; - keyPath: string | string[]; - readonly name: string; - readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; - clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; - deleteIndex(indexName: string): void; - get(key: any): IDBRequest; - index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; -} - -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new(): IDBObjectStore; -} - -interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new(): IDBOpenDBRequest; -} - -interface IDBRequest extends EventTarget { - readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; - readonly readyState: string; - readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; - readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBRequest: { - prototype: IDBRequest; - new(): IDBRequest; -} - -interface IDBTransaction extends EventTarget { - readonly db: IDBDatabase; - readonly error: DOMError; - readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - abort(): void; - objectStore(name: string): IDBObjectStore; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBTransaction: { - prototype: IDBTransaction; - new(): IDBTransaction; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; -} - -interface IDBVersionChangeEvent extends Event { - readonly newVersion: number | null; - readonly oldVersion: number; -} - -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new(): IDBVersionChangeEvent; -} - -interface ImageData { - data: Uint8ClampedArray; - readonly height: number; - readonly width: number; -} - -declare var ImageData: { - prototype: ImageData; - new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} - -interface KeyboardEvent extends UIEvent { - readonly altKey: boolean; - readonly char: string | null; - readonly charCode: number; - readonly ctrlKey: boolean; - readonly key: string; - readonly keyCode: number; - readonly locale: string; - readonly location: number; - readonly metaKey: boolean; - readonly repeat: boolean; - readonly shiftKey: boolean; - readonly which: number; - readonly code: string; - getModifierState(keyArg: string): boolean; - initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -declare var KeyboardEvent: { - prototype: KeyboardEvent; - new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -interface ListeningStateChangedEvent extends Event { - readonly label: string; - readonly state: string; -} - -declare var ListeningStateChangedEvent: { - prototype: ListeningStateChangedEvent; - new(): ListeningStateChangedEvent; -} - -interface Location { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - pathname: string; - port: string; - protocol: string; - search: string; - assign(url: string): void; - reload(forcedReload?: boolean): void; - replace(url: string): void; - toString(): string; -} - -declare var Location: { - prototype: Location; - new(): Location; -} - -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; -} - -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; -} - -interface MSApp { - clearTemporaryWebDataAsync(): MSAppAsyncOperation; - createBlobFromRandomAccessStream(type: string, seeker: any): Blob; - createDataPackage(object: any): any; - createDataPackageFromSelection(): any; - createFileFromStorageFile(storageFile: any): File; - createStreamFromInputStream(type: string, inputStream: any): MSStream; - execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; - execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; - getCurrentPriority(): string; - getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; - getViewId(view: any): any; - isTaskScheduledAtPriorityOrHigher(priority: string): boolean; - pageHandlesAllApplicationActivations(enabled: boolean): void; - suppressSubdownloadCredentialPrompts(suppress: boolean): void; - terminateApp(exceptionObject: any): void; - readonly CURRENT: string; - readonly HIGH: string; - readonly IDLE: string; - readonly NORMAL: string; -} -declare var MSApp: MSApp; - -interface MSAppAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSAppAsyncOperation: { - prototype: MSAppAsyncOperation; - new(): MSAppAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; -} - -interface MSAssertion { - readonly id: string; - readonly type: string; -} - -declare var MSAssertion: { - prototype: MSAssertion; - new(): MSAssertion; -} - -interface MSBlobBuilder { - append(data: any, endings?: string): void; - getBlob(contentType?: string): Blob; -} - -declare var MSBlobBuilder: { - prototype: MSBlobBuilder; - new(): MSBlobBuilder; -} - -interface MSCredentials { - getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; - makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; -} - -declare var MSCredentials: { - prototype: MSCredentials; - new(): MSCredentials; -} - -interface MSFIDOCredentialAssertion extends MSAssertion { - readonly algorithm: string | Algorithm; - readonly attestation: any; - readonly publicKey: string; - readonly transportHints: string[]; -} - -declare var MSFIDOCredentialAssertion: { - prototype: MSFIDOCredentialAssertion; - new(): MSFIDOCredentialAssertion; -} - -interface MSFIDOSignature { - readonly authnrData: string; - readonly clientData: string; - readonly signature: string; -} - -declare var MSFIDOSignature: { - prototype: MSFIDOSignature; - new(): MSFIDOSignature; -} - -interface MSFIDOSignatureAssertion extends MSAssertion { - readonly signature: MSFIDOSignature; -} - -declare var MSFIDOSignatureAssertion: { - prototype: MSFIDOSignatureAssertion; - new(): MSFIDOSignatureAssertion; -} - -interface MSGesture { - target: Element; - addPointer(pointerId: number): void; - stop(): void; -} - -declare var MSGesture: { - prototype: MSGesture; - new(): MSGesture; -} - -interface MSGestureEvent extends UIEvent { - readonly clientX: number; - readonly clientY: number; - readonly expansion: number; - readonly gestureObject: any; - readonly hwTimestamp: number; - readonly offsetX: number; - readonly offsetY: number; - readonly rotation: number; - readonly scale: number; - readonly screenX: number; - readonly screenY: number; - readonly translationX: number; - readonly translationY: number; - readonly velocityAngular: number; - readonly velocityExpansion: number; - readonly velocityX: number; - readonly velocityY: number; - initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -interface MSGraphicsTrust { - readonly constrictionActive: boolean; - readonly status: string; -} - -declare var MSGraphicsTrust: { - prototype: MSGraphicsTrust; - new(): MSGraphicsTrust; -} - -interface MSHTMLWebViewElement extends HTMLElement { - readonly canGoBack: boolean; - readonly canGoForward: boolean; - readonly containsFullScreenElement: boolean; - readonly documentTitle: string; - height: number; - readonly settings: MSWebViewSettings; - src: string; - width: number; - addWebAllowedObject(name: string, applicationObject: any): void; - buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; - capturePreviewToBlobAsync(): MSWebViewAsyncOperation; - captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; - getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; - getDeferredPermissionRequests(): DeferredPermissionRequest[]; - goBack(): void; - goForward(): void; - invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; - navigate(uri: string): void; - navigateToLocalStreamUri(source: string, streamResolver: any): void; - navigateToString(contents: string): void; - navigateWithHttpRequestMessage(requestMessage: any): void; - refresh(): void; - stop(): void; -} - -declare var MSHTMLWebViewElement: { - prototype: MSHTMLWebViewElement; - new(): MSHTMLWebViewElement; -} - -interface MSInputMethodContext extends EventTarget { - readonly compositionEndOffset: number; - readonly compositionStartOffset: number; - oncandidatewindowhide: (this: this, ev: Event) => any; - oncandidatewindowshow: (this: this, ev: Event) => any; - oncandidatewindowupdate: (this: this, ev: Event) => any; - readonly target: HTMLElement; - getCandidateWindowClientRect(): ClientRect; - getCompositionAlternatives(): string[]; - hasComposition(): boolean; - isCandidateWindowVisible(): boolean; - addEventListener(type: "MSCandidateWindowHide", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowShow", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowUpdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSInputMethodContext: { - prototype: MSInputMethodContext; - new(): MSInputMethodContext; -} - -interface MSManipulationEvent extends UIEvent { - readonly currentState: number; - readonly inertiaDestinationX: number; - readonly inertiaDestinationY: number; - readonly lastState: number; - initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -declare var MSManipulationEvent: { - prototype: MSManipulationEvent; - new(): MSManipulationEvent; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -interface MSMediaKeyError { - readonly code: number; - readonly systemCode: number; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -declare var MSMediaKeyError: { - prototype: MSMediaKeyError; - new(): MSMediaKeyError; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -interface MSMediaKeyMessageEvent extends Event { - readonly destinationURL: string | null; - readonly message: Uint8Array; -} - -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new(): MSMediaKeyMessageEvent; -} - -interface MSMediaKeyNeededEvent extends Event { - readonly initData: Uint8Array | null; -} - -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new(): MSMediaKeyNeededEvent; -} - -interface MSMediaKeySession extends EventTarget { - readonly error: MSMediaKeyError | null; - readonly keySystem: string; - readonly sessionId: string; - close(): void; - update(key: Uint8Array): void; -} - -declare var MSMediaKeySession: { - prototype: MSMediaKeySession; - new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} - -interface MSPointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} - -interface MSRangeCollection { - readonly length: number; - item(index: number): Range; - [index: number]: Range; -} - -declare var MSRangeCollection: { - prototype: MSRangeCollection; - new(): MSRangeCollection; -} - -interface MSSiteModeEvent extends Event { - readonly actionURL: string; - readonly buttonID: number; -} - -declare var MSSiteModeEvent: { - prototype: MSSiteModeEvent; - new(): MSSiteModeEvent; -} - -interface MSStream { - readonly type: string; - msClose(): void; - msDetachStream(): any; -} - -declare var MSStream: { - prototype: MSStream; - new(): MSStream; -} - -interface MSStreamReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(stream: MSStream, size?: number): void; - readAsBinaryString(stream: MSStream, size?: number): void; - readAsBlob(stream: MSStream, size?: number): void; - readAsDataURL(stream: MSStream, size?: number): void; - readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSStreamReader: { - prototype: MSStreamReader; - new(): MSStreamReader; -} - -interface MSWebViewAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - readonly target: MSHTMLWebViewElement; - readonly type: number; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSWebViewAsyncOperation: { - prototype: MSWebViewAsyncOperation; - new(): MSWebViewAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; -} - -interface MSWebViewSettings { - isIndexedDBEnabled: boolean; - isJavaScriptEnabled: boolean; -} - -declare var MSWebViewSettings: { - prototype: MSWebViewSettings; - new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: string; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: this, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): PromiseLike; - addEventListener(type: "devicechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: string; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: PromiseLike; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): PromiseLike; - generateRequest(initDataType: string, initData: any): PromiseLike; - load(sessionId: string): PromiseLike; - remove(): PromiseLike; - update(response: any): PromiseLike; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): string; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): PromiseLike; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: string): MediaKeySession; - setServerCertificate(serverCertificate: any): PromiseLike; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: this, ev: Event) => any; - onaddtrack: (this: this, ev: TrackEvent) => any; - oninactive: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: "active", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "inactive", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onmute: (this: this, ev: Event) => any; - onoverconstrained: (this: this, ev: MediaStreamErrorEvent) => any; - onunmute: (this: this, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: string; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): PromiseLike; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "overconstrained", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unmute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, ports?: any): void; - start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} - -interface MutationEvent extends Event { - readonly attrChange: number; - readonly attrName: string; - readonly newValue: string; - readonly prevValue: string; - readonly relatedNode: Node; - initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -declare var MutationEvent: { - prototype: MutationEvent; - new(): MutationEvent; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -interface MutationObserver { - disconnect(): void; - observe(target: Node, options: MutationObserverInit): void; - takeRecords(): MutationRecord[]; -} - -declare var MutationObserver: { - prototype: MutationObserver; - new(callback: MutationCallback): MutationObserver; -} - -interface MutationRecord { - readonly addedNodes: NodeList; - readonly attributeName: string | null; - readonly attributeNamespace: string | null; - readonly nextSibling: Node | null; - readonly oldValue: string | null; - readonly previousSibling: Node | null; - readonly removedNodes: NodeList; - readonly target: Node; - readonly type: string; -} - -declare var MutationRecord: { - prototype: MutationRecord; - new(): MutationRecord; -} - -interface NamedNodeMap { - readonly length: number; - getNamedItem(name: string): Attr; - getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - item(index: number): Attr; - removeNamedItem(name: string): Attr; - removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - setNamedItem(arg: Attr): Attr; - setNamedItemNS(arg: Attr): Attr; - [index: number]: Attr; -} - -declare var NamedNodeMap: { - prototype: NamedNodeMap; - new(): NamedNodeMap; -} - -interface NavigationCompletedEvent extends NavigationEvent { - readonly isSuccess: boolean; - readonly webErrorStatus: number; -} - -declare var NavigationCompletedEvent: { - prototype: NavigationCompletedEvent; - new(): NavigationCompletedEvent; -} - -interface NavigationEvent extends Event { - readonly uri: string; -} - -declare var NavigationEvent: { - prototype: NavigationEvent; - new(): NavigationEvent; -} - -interface NavigationEventWithReferrer extends NavigationEvent { - readonly referer: string; -} - -declare var NavigationEventWithReferrer: { - prototype: NavigationEventWithReferrer; - new(): NavigationEventWithReferrer; -} - -interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { - readonly appCodeName: string; - readonly cookieEnabled: boolean; - readonly language: string; - readonly maxTouchPoints: number; - readonly mimeTypes: MimeTypeArray; - readonly msManipulationViewsEnabled: boolean; - readonly msMaxTouchPoints: number; - readonly msPointerEnabled: boolean; - readonly plugins: PluginArray; - readonly pointerEnabled: boolean; - readonly webdriver: boolean; - getGamepads(): Gamepad[]; - javaEnabled(): boolean; - msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; - requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; - vibrate(pattern: number | number[]): boolean; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Navigator: { - prototype: Navigator; - new(): Navigator; -} - -interface Node extends EventTarget { - readonly attributes: NamedNodeMap; - readonly baseURI: string | null; - readonly childNodes: NodeList; - readonly firstChild: Node; - readonly lastChild: Node; - readonly localName: string | null; - readonly namespaceURI: string | null; - readonly nextSibling: Node; - readonly nodeName: string; - readonly nodeType: number; - nodeValue: string | null; - readonly ownerDocument: Document; - readonly parentElement: HTMLElement; - readonly parentNode: Node; - readonly previousSibling: Node; - textContent: string | null; - appendChild(newChild: Node): Node; - cloneNode(deep?: boolean): Node; - compareDocumentPosition(other: Node): number; - contains(child: Node): boolean; - hasAttributes(): boolean; - hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node | null): Node; - isDefaultNamespace(namespaceURI: string | null): boolean; - isEqualNode(arg: Node): boolean; - isSameNode(other: Node): boolean; - lookupNamespaceURI(prefix: string | null): string | null; - lookupPrefix(namespaceURI: string | null): string | null; - normalize(): void; - removeChild(oldChild: Node): Node; - replaceChild(newChild: Node, oldChild: Node): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -declare var Node: { - prototype: Node; - new(): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -interface NodeFilter { - acceptNode(n: Node): number; -} - -declare var NodeFilter: { - readonly FILTER_ACCEPT: number; - readonly FILTER_REJECT: number; - readonly FILTER_SKIP: number; - readonly SHOW_ALL: number; - readonly SHOW_ATTRIBUTE: number; - readonly SHOW_CDATA_SECTION: number; - readonly SHOW_COMMENT: number; - readonly SHOW_DOCUMENT: number; - readonly SHOW_DOCUMENT_FRAGMENT: number; - readonly SHOW_DOCUMENT_TYPE: number; - readonly SHOW_ELEMENT: number; - readonly SHOW_ENTITY: number; - readonly SHOW_ENTITY_REFERENCE: number; - readonly SHOW_NOTATION: number; - readonly SHOW_PROCESSING_INSTRUCTION: number; - readonly SHOW_TEXT: number; -} - -interface NodeIterator { - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - detach(): void; - nextNode(): Node; - previousNode(): Node; -} - -declare var NodeIterator: { - prototype: NodeIterator; - new(): NodeIterator; -} - -interface NodeList { - readonly length: number; - item(index: number): Node; - [index: number]: Node; -} - -declare var NodeList: { - prototype: NodeList; - new(): NodeList; -} - -interface OES_element_index_uint { -} - -declare var OES_element_index_uint: { - prototype: OES_element_index_uint; - new(): OES_element_index_uint; -} - -interface OES_standard_derivatives { - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -declare var OES_standard_derivatives: { - prototype: OES_standard_derivatives; - new(): OES_standard_derivatives; - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -interface OES_texture_float { -} - -declare var OES_texture_float: { - prototype: OES_texture_float; - new(): OES_texture_float; -} - -interface OES_texture_float_linear { -} - -declare var OES_texture_float_linear: { - prototype: OES_texture_float_linear; - new(): OES_texture_float_linear; -} - -interface OfflineAudioCompletionEvent extends Event { - readonly renderedBuffer: AudioBuffer; -} - -declare var OfflineAudioCompletionEvent: { - prototype: OfflineAudioCompletionEvent; - new(): OfflineAudioCompletionEvent; -} - -interface OfflineAudioContext extends AudioContext { - oncomplete: (this: this, ev: Event) => any; - startRendering(): PromiseLike; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OfflineAudioContext: { - prototype: OfflineAudioContext; - new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} - -interface OscillatorNode extends AudioNode { - readonly detune: AudioParam; - readonly frequency: AudioParam; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - type: string; - setPeriodicWave(periodicWave: PeriodicWave): void; - start(when?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OscillatorNode: { - prototype: OscillatorNode; - new(): OscillatorNode; -} - -interface OverflowEvent extends UIEvent { - readonly horizontalOverflow: boolean; - readonly orient: number; - readonly verticalOverflow: boolean; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -declare var OverflowEvent: { - prototype: OverflowEvent; - new(): OverflowEvent; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -interface PageTransitionEvent extends Event { - readonly persisted: boolean; -} - -declare var PageTransitionEvent: { - prototype: PageTransitionEvent; - new(): PageTransitionEvent; -} - -interface PannerNode extends AudioNode { - coneInnerAngle: number; - coneOuterAngle: number; - coneOuterGain: number; - distanceModel: string; - maxDistance: number; - panningModel: string; - refDistance: number; - rolloffFactor: number; - setOrientation(x: number, y: number, z: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var PannerNode: { - prototype: PannerNode; - new(): PannerNode; -} - -interface PerfWidgetExternal { - readonly activeNetworkRequestCount: number; - readonly averageFrameTime: number; - readonly averagePaintTime: number; - readonly extraInformationEnabled: boolean; - readonly independentRenderingEnabled: boolean; - readonly irDisablingContentString: string; - readonly irStatusAvailable: boolean; - readonly maxCpuSpeed: number; - readonly paintRequestsPerSecond: number; - readonly performanceCounter: number; - readonly performanceCounterFrequency: number; - addEventListener(eventType: string, callback: Function): void; - getMemoryUsage(): number; - getProcessCpuUsage(): number; - getRecentCpuUsage(last: number | null): any; - getRecentFrames(last: number | null): any; - getRecentMemoryUsage(last: number | null): any; - getRecentPaintRequests(last: number | null): any; - removeEventListener(eventType: string, callback: Function): void; - repositionWindow(x: number, y: number): void; - resizeWindow(width: number, height: number): void; -} - -declare var PerfWidgetExternal: { - prototype: PerfWidgetExternal; - new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: string; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} - -interface PeriodicWave { -} - -declare var PeriodicWave: { - prototype: PeriodicWave; - new(): PeriodicWave; -} - -interface PermissionRequest extends DeferredPermissionRequest { - readonly state: string; - defer(): void; -} - -declare var PermissionRequest: { - prototype: PermissionRequest; - new(): PermissionRequest; -} - -interface PermissionRequestedEvent extends Event { - readonly permissionRequest: PermissionRequest; -} - -declare var PermissionRequestedEvent: { - prototype: PermissionRequestedEvent; - new(): PermissionRequestedEvent; -} - -interface Plugin { - readonly description: string; - readonly filename: string; - readonly length: number; - readonly name: string; - readonly version: string; - item(index: number): MimeType; - namedItem(type: string): MimeType; - [index: number]: MimeType; -} - -declare var Plugin: { - prototype: Plugin; - new(): Plugin; -} - -interface PluginArray { - readonly length: number; - item(index: number): Plugin; - namedItem(name: string): Plugin; - refresh(reload?: boolean): void; - [index: number]: Plugin; -} - -declare var PluginArray: { - prototype: PluginArray; - new(): PluginArray; -} - -interface PointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var PointerEvent: { - prototype: PointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} - -interface PopStateEvent extends Event { - readonly state: any; - initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; -} - -declare var PopStateEvent: { - prototype: PopStateEvent; - new(): PopStateEvent; -} - -interface Position { - readonly coords: Coordinates; - readonly timestamp: number; -} - -declare var Position: { - prototype: Position; - new(): Position; -} - -interface PositionError { - readonly code: number; - readonly message: string; - toString(): string; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -declare var PositionError: { - prototype: PositionError; - new(): PositionError; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -interface ProcessingInstruction extends CharacterData { - readonly target: string; -} - -declare var ProcessingInstruction: { - prototype: ProcessingInstruction; - new(): ProcessingInstruction; -} - -interface ProgressEvent extends Event { - readonly lengthComputable: boolean; - readonly loaded: number; - readonly total: number; - initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; -} - -declare var ProgressEvent: { - prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} - -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; -} - -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; -} - -interface RTCDtlsTransport extends RTCStatsProvider { - ondtlsstatechange: ((this: this, ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly state: string; - readonly transport: RTCIceTransport; - getLocalParameters(): RTCDtlsParameters; - getRemoteCertificates(): ArrayBuffer[]; - getRemoteParameters(): RTCDtlsParameters | null; - start(remoteParameters: RTCDtlsParameters): void; - stop(): void; - addEventListener(type: "dtlsstatechange", listener: (this: this, ev: RTCDtlsTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtlsTransport: { - prototype: RTCDtlsTransport; - new(transport: RTCIceTransport): RTCDtlsTransport; -} - -interface RTCDtlsTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCDtlsTransportStateChangedEvent: { - prototype: RTCDtlsTransportStateChangedEvent; - new(): RTCDtlsTransportStateChangedEvent; -} - -interface RTCDtmfSender extends EventTarget { - readonly canInsertDTMF: boolean; - readonly duration: number; - readonly interToneGap: number; - ontonechange: (this: this, ev: RTCDTMFToneChangeEvent) => any; - readonly sender: RTCRtpSender; - readonly toneBuffer: string; - insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: "tonechange", listener: (this: this, ev: RTCDTMFToneChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtmfSender: { - prototype: RTCDtmfSender; - new(sender: RTCRtpSender): RTCDtmfSender; -} - -interface RTCIceCandidatePairChangedEvent extends Event { - readonly pair: RTCIceCandidatePair; -} - -declare var RTCIceCandidatePairChangedEvent: { - prototype: RTCIceCandidatePairChangedEvent; - new(): RTCIceCandidatePairChangedEvent; -} - -interface RTCIceGatherer extends RTCStatsProvider { - readonly component: string; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onlocalcandidate: ((this: this, ev: RTCIceGathererEvent) => any) | null; - createAssociatedGatherer(): RTCIceGatherer; - getLocalCandidates(): RTCIceCandidate[]; - getLocalParameters(): RTCIceParameters; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "localcandidate", listener: (this: this, ev: RTCIceGathererEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceGatherer: { - prototype: RTCIceGatherer; - new(options: RTCIceGatherOptions): RTCIceGatherer; -} - -interface RTCIceGathererEvent extends Event { - readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; -} - -declare var RTCIceGathererEvent: { - prototype: RTCIceGathererEvent; - new(): RTCIceGathererEvent; -} - -interface RTCIceTransport extends RTCStatsProvider { - readonly component: string; - readonly iceGatherer: RTCIceGatherer | null; - oncandidatepairchange: ((this: this, ev: RTCIceCandidatePairChangedEvent) => any) | null; - onicestatechange: ((this: this, ev: RTCIceTransportStateChangedEvent) => any) | null; - readonly role: string; - readonly state: string; - addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; - createAssociatedTransport(): RTCIceTransport; - getNominatedCandidatePair(): RTCIceCandidatePair | null; - getRemoteCandidates(): RTCIceCandidate[]; - getRemoteParameters(): RTCIceParameters | null; - setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; - start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; - stop(): void; - addEventListener(type: "candidatepairchange", listener: (this: this, ev: RTCIceCandidatePairChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "icestatechange", listener: (this: this, ev: RTCIceTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceTransport: { - prototype: RTCIceTransport; - new(): RTCIceTransport; -} - -interface RTCIceTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCIceTransportStateChangedEvent: { - prototype: RTCIceTransportStateChangedEvent; - new(): RTCIceTransportStateChangedEvent; -} - -interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack | null; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - getContributingSources(): RTCRtpContributingSource[]; - receive(parameters: RTCRtpParameters): void; - requestSendCSRC(csrc: number): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpReceiver: { - prototype: RTCRtpReceiver; - new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCRtpSender extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onssrcconflict: ((this: this, ev: RTCSsrcConflictEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - send(parameters: RTCRtpParameters): void; - setTrack(track: MediaStreamTrack): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ssrcconflict", listener: (this: this, ev: RTCSsrcConflictEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpSender: { - prototype: RTCRtpSender; - new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly transport: RTCIceTransport; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCSrtpSdesTransport: { - prototype: RTCSrtpSdesTransport; - new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; - getLocalParameters(): RTCSrtpSdesParameters[]; -} - -interface RTCSsrcConflictEvent extends Event { - readonly ssrc: number; -} - -declare var RTCSsrcConflictEvent: { - prototype: RTCSsrcConflictEvent; - new(): RTCSsrcConflictEvent; -} - -interface RTCStatsProvider extends EventTarget { - getStats(): PromiseLike; - msGetStats(): PromiseLike; -} - -declare var RTCStatsProvider: { - prototype: RTCStatsProvider; - new(): RTCStatsProvider; -} - -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: string): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; - toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly target: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGAElement: { - prototype: SVGAElement; - new(): SVGAElement; -} - -interface SVGAngle { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -declare var SVGAngle: { - prototype: SVGAngle; - new(): SVGAngle; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -interface SVGAnimatedAngle { - readonly animVal: SVGAngle; - readonly baseVal: SVGAngle; -} - -declare var SVGAnimatedAngle: { - prototype: SVGAnimatedAngle; - new(): SVGAnimatedAngle; -} - -interface SVGAnimatedBoolean { - readonly animVal: boolean; - baseVal: boolean; -} - -declare var SVGAnimatedBoolean: { - prototype: SVGAnimatedBoolean; - new(): SVGAnimatedBoolean; -} - -interface SVGAnimatedEnumeration { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedEnumeration: { - prototype: SVGAnimatedEnumeration; - new(): SVGAnimatedEnumeration; -} - -interface SVGAnimatedInteger { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedInteger: { - prototype: SVGAnimatedInteger; - new(): SVGAnimatedInteger; -} - -interface SVGAnimatedLength { - readonly animVal: SVGLength; - readonly baseVal: SVGLength; -} - -declare var SVGAnimatedLength: { - prototype: SVGAnimatedLength; - new(): SVGAnimatedLength; -} - -interface SVGAnimatedLengthList { - readonly animVal: SVGLengthList; - readonly baseVal: SVGLengthList; -} - -declare var SVGAnimatedLengthList: { - prototype: SVGAnimatedLengthList; - new(): SVGAnimatedLengthList; -} - -interface SVGAnimatedNumber { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedNumber: { - prototype: SVGAnimatedNumber; - new(): SVGAnimatedNumber; -} - -interface SVGAnimatedNumberList { - readonly animVal: SVGNumberList; - readonly baseVal: SVGNumberList; -} - -declare var SVGAnimatedNumberList: { - prototype: SVGAnimatedNumberList; - new(): SVGAnimatedNumberList; -} - -interface SVGAnimatedPreserveAspectRatio { - readonly animVal: SVGPreserveAspectRatio; - readonly baseVal: SVGPreserveAspectRatio; -} - -declare var SVGAnimatedPreserveAspectRatio: { - prototype: SVGAnimatedPreserveAspectRatio; - new(): SVGAnimatedPreserveAspectRatio; -} - -interface SVGAnimatedRect { - readonly animVal: SVGRect; - readonly baseVal: SVGRect; -} - -declare var SVGAnimatedRect: { - prototype: SVGAnimatedRect; - new(): SVGAnimatedRect; -} - -interface SVGAnimatedString { - readonly animVal: string; - baseVal: string; -} - -declare var SVGAnimatedString: { - prototype: SVGAnimatedString; - new(): SVGAnimatedString; -} - -interface SVGAnimatedTransformList { - readonly animVal: SVGTransformList; - readonly baseVal: SVGTransformList; -} - -declare var SVGAnimatedTransformList: { - prototype: SVGAnimatedTransformList; - new(): SVGAnimatedTransformList; -} - -interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGCircleElement: { - prototype: SVGCircleElement; - new(): SVGCircleElement; -} - -interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGClipPathElement: { - prototype: SVGClipPathElement; - new(): SVGClipPathElement; -} - -interface SVGComponentTransferFunctionElement extends SVGElement { - readonly amplitude: SVGAnimatedNumber; - readonly exponent: SVGAnimatedNumber; - readonly intercept: SVGAnimatedNumber; - readonly offset: SVGAnimatedNumber; - readonly slope: SVGAnimatedNumber; - readonly tableValues: SVGAnimatedNumberList; - readonly type: SVGAnimatedEnumeration; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -declare var SVGComponentTransferFunctionElement: { - prototype: SVGComponentTransferFunctionElement; - new(): SVGComponentTransferFunctionElement; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDefsElement: { - prototype: SVGDefsElement; - new(): SVGDefsElement; -} - -interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDescElement: { - prototype: SVGDescElement; - new(): SVGDescElement; -} - -interface SVGElement extends Element { - onclick: (this: this, ev: MouseEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - onfocusin: (this: this, ev: FocusEvent) => any; - onfocusout: (this: this, ev: FocusEvent) => any; - onload: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - readonly ownerSVGElement: SVGSVGElement; - readonly viewportElement: SVGElement; - xmlbase: string; - className: any; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGElement: { - prototype: SVGElement; - new(): SVGElement; -} - -interface SVGElementInstance extends EventTarget { - readonly childNodes: SVGElementInstanceList; - readonly correspondingElement: SVGElement; - readonly correspondingUseElement: SVGUseElement; - readonly firstChild: SVGElementInstance; - readonly lastChild: SVGElementInstance; - readonly nextSibling: SVGElementInstance; - readonly parentNode: SVGElementInstance; - readonly previousSibling: SVGElementInstance; -} - -declare var SVGElementInstance: { - prototype: SVGElementInstance; - new(): SVGElementInstance; -} - -interface SVGElementInstanceList { - readonly length: number; - item(index: number): SVGElementInstance; -} - -declare var SVGElementInstanceList: { - prototype: SVGElementInstanceList; - new(): SVGElementInstanceList; -} - -interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGEllipseElement: { - prototype: SVGEllipseElement; - new(): SVGEllipseElement; -} - -interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly mode: SVGAnimatedEnumeration; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEBlendElement: { - prototype: SVGFEBlendElement; - new(): SVGFEBlendElement; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} - -interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly type: SVGAnimatedEnumeration; - readonly values: SVGAnimatedNumberList; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEColorMatrixElement: { - prototype: SVGFEColorMatrixElement; - new(): SVGFEColorMatrixElement; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} - -interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEComponentTransferElement: { - prototype: SVGFEComponentTransferElement; - new(): SVGFEComponentTransferElement; -} - -interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly k1: SVGAnimatedNumber; - readonly k2: SVGAnimatedNumber; - readonly k3: SVGAnimatedNumber; - readonly k4: SVGAnimatedNumber; - readonly operator: SVGAnimatedEnumeration; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFECompositeElement: { - prototype: SVGFECompositeElement; - new(): SVGFECompositeElement; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} - -interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly bias: SVGAnimatedNumber; - readonly divisor: SVGAnimatedNumber; - readonly edgeMode: SVGAnimatedEnumeration; - readonly in1: SVGAnimatedString; - readonly kernelMatrix: SVGAnimatedNumberList; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly orderX: SVGAnimatedInteger; - readonly orderY: SVGAnimatedInteger; - readonly preserveAlpha: SVGAnimatedBoolean; - readonly targetX: SVGAnimatedInteger; - readonly targetY: SVGAnimatedInteger; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEConvolveMatrixElement: { - prototype: SVGFEConvolveMatrixElement; - new(): SVGFEConvolveMatrixElement; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; -} - -interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly diffuseConstant: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDiffuseLightingElement: { - prototype: SVGFEDiffuseLightingElement; - new(): SVGFEDiffuseLightingElement; -} - -interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly scale: SVGAnimatedNumber; - readonly xChannelSelector: SVGAnimatedEnumeration; - readonly yChannelSelector: SVGAnimatedEnumeration; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDisplacementMapElement: { - prototype: SVGFEDisplacementMapElement; - new(): SVGFEDisplacementMapElement; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; -} - -interface SVGFEDistantLightElement extends SVGElement { - readonly azimuth: SVGAnimatedNumber; - readonly elevation: SVGAnimatedNumber; -} - -declare var SVGFEDistantLightElement: { - prototype: SVGFEDistantLightElement; - new(): SVGFEDistantLightElement; -} - -interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEFloodElement: { - prototype: SVGFEFloodElement; - new(): SVGFEFloodElement; -} - -interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncAElement: { - prototype: SVGFEFuncAElement; - new(): SVGFEFuncAElement; -} - -interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncBElement: { - prototype: SVGFEFuncBElement; - new(): SVGFEFuncBElement; -} - -interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncGElement: { - prototype: SVGFEFuncGElement; - new(): SVGFEFuncGElement; -} - -interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncRElement: { - prototype: SVGFEFuncRElement; - new(): SVGFEFuncRElement; -} - -interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly stdDeviationX: SVGAnimatedNumber; - readonly stdDeviationY: SVGAnimatedNumber; - setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEGaussianBlurElement: { - prototype: SVGFEGaussianBlurElement; - new(): SVGFEGaussianBlurElement; -} - -interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEImageElement: { - prototype: SVGFEImageElement; - new(): SVGFEImageElement; -} - -interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMergeElement: { - prototype: SVGFEMergeElement; - new(): SVGFEMergeElement; -} - -interface SVGFEMergeNodeElement extends SVGElement { - readonly in1: SVGAnimatedString; -} - -declare var SVGFEMergeNodeElement: { - prototype: SVGFEMergeNodeElement; - new(): SVGFEMergeNodeElement; -} - -interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly operator: SVGAnimatedEnumeration; - readonly radiusX: SVGAnimatedNumber; - readonly radiusY: SVGAnimatedNumber; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMorphologyElement: { - prototype: SVGFEMorphologyElement; - new(): SVGFEMorphologyElement; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} - -interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly dx: SVGAnimatedNumber; - readonly dy: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEOffsetElement: { - prototype: SVGFEOffsetElement; - new(): SVGFEOffsetElement; -} - -interface SVGFEPointLightElement extends SVGElement { - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFEPointLightElement: { - prototype: SVGFEPointLightElement; - new(): SVGFEPointLightElement; -} - -interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly specularConstant: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFESpecularLightingElement: { - prototype: SVGFESpecularLightingElement; - new(): SVGFESpecularLightingElement; -} - -interface SVGFESpotLightElement extends SVGElement { - readonly limitingConeAngle: SVGAnimatedNumber; - readonly pointsAtX: SVGAnimatedNumber; - readonly pointsAtY: SVGAnimatedNumber; - readonly pointsAtZ: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFESpotLightElement: { - prototype: SVGFESpotLightElement; - new(): SVGFESpotLightElement; -} - -interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETileElement: { - prototype: SVGFETileElement; - new(): SVGFETileElement; -} - -interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly baseFrequencyX: SVGAnimatedNumber; - readonly baseFrequencyY: SVGAnimatedNumber; - readonly numOctaves: SVGAnimatedInteger; - readonly seed: SVGAnimatedNumber; - readonly stitchTiles: SVGAnimatedEnumeration; - readonly type: SVGAnimatedEnumeration; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETurbulenceElement: { - prototype: SVGFETurbulenceElement; - new(): SVGFETurbulenceElement; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} - -interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly filterResX: SVGAnimatedInteger; - readonly filterResY: SVGAnimatedInteger; - readonly filterUnits: SVGAnimatedEnumeration; - readonly height: SVGAnimatedLength; - readonly primitiveUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFilterElement: { - prototype: SVGFilterElement; - new(): SVGFilterElement; -} - -interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGForeignObjectElement: { - prototype: SVGForeignObjectElement; - new(): SVGForeignObjectElement; -} - -interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGElement: { - prototype: SVGGElement; - new(): SVGGElement; -} - -interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { - readonly gradientTransform: SVGAnimatedTransformList; - readonly gradientUnits: SVGAnimatedEnumeration; - readonly spreadMethod: SVGAnimatedEnumeration; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGradientElement: { - prototype: SVGGradientElement; - new(): SVGGradientElement; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; -} - -interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly height: SVGAnimatedLength; - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGImageElement: { - prototype: SVGImageElement; - new(): SVGImageElement; -} - -interface SVGLength { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -declare var SVGLength: { - prototype: SVGLength; - new(): SVGLength; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -interface SVGLengthList { - readonly numberOfItems: number; - appendItem(newItem: SVGLength): SVGLength; - clear(): void; - getItem(index: number): SVGLength; - initialize(newItem: SVGLength): SVGLength; - insertItemBefore(newItem: SVGLength, index: number): SVGLength; - removeItem(index: number): SVGLength; - replaceItem(newItem: SVGLength, index: number): SVGLength; -} - -declare var SVGLengthList: { - prototype: SVGLengthList; - new(): SVGLengthList; -} - -interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} - -interface SVGLinearGradientElement extends SVGGradientElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; -} - -declare var SVGLinearGradientElement: { - prototype: SVGLinearGradientElement; - new(): SVGLinearGradientElement; -} - -interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - readonly markerHeight: SVGAnimatedLength; - readonly markerUnits: SVGAnimatedEnumeration; - readonly markerWidth: SVGAnimatedLength; - readonly orientAngle: SVGAnimatedAngle; - readonly orientType: SVGAnimatedEnumeration; - readonly refX: SVGAnimatedLength; - readonly refY: SVGAnimatedLength; - setOrientToAngle(angle: SVGAngle): void; - setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMarkerElement: { - prototype: SVGMarkerElement; - new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} - -interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly maskContentUnits: SVGAnimatedEnumeration; - readonly maskUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMaskElement: { - prototype: SVGMaskElement; - new(): SVGMaskElement; -} - -interface SVGMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - flipX(): SVGMatrix; - flipY(): SVGMatrix; - inverse(): SVGMatrix; - multiply(secondMatrix: SVGMatrix): SVGMatrix; - rotate(angle: number): SVGMatrix; - rotateFromVector(x: number, y: number): SVGMatrix; - scale(scaleFactor: number): SVGMatrix; - scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; - skewX(angle: number): SVGMatrix; - skewY(angle: number): SVGMatrix; - translate(x: number, y: number): SVGMatrix; -} - -declare var SVGMatrix: { - prototype: SVGMatrix; - new(): SVGMatrix; -} - -interface SVGMetadataElement extends SVGElement { -} - -declare var SVGMetadataElement: { - prototype: SVGMetadataElement; - new(): SVGMetadataElement; -} - -interface SVGNumber { - value: number; -} - -declare var SVGNumber: { - prototype: SVGNumber; - new(): SVGNumber; -} - -interface SVGNumberList { - readonly numberOfItems: number; - appendItem(newItem: SVGNumber): SVGNumber; - clear(): void; - getItem(index: number): SVGNumber; - initialize(newItem: SVGNumber): SVGNumber; - insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; - removeItem(index: number): SVGNumber; - replaceItem(newItem: SVGNumber, index: number): SVGNumber; -} - -declare var SVGNumberList: { - prototype: SVGNumberList; - new(): SVGNumberList; -} - -interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; - createSVGPathSegClosePath(): SVGPathSegClosePath; - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - getPathSegAtLength(distance: number): number; - getPointAtLength(distance: number): SVGPoint; - getTotalLength(): number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPathElement: { - prototype: SVGPathElement; - new(): SVGPathElement; -} - -interface SVGPathSeg { - readonly pathSegType: number; - readonly pathSegTypeAsLetter: string; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -declare var SVGPathSeg: { - prototype: SVGPathSeg; - new(): SVGPathSeg; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -interface SVGPathSegArcAbs extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcAbs: { - prototype: SVGPathSegArcAbs; - new(): SVGPathSegArcAbs; -} - -interface SVGPathSegArcRel extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcRel: { - prototype: SVGPathSegArcRel; - new(): SVGPathSegArcRel; -} - -interface SVGPathSegClosePath extends SVGPathSeg { -} - -declare var SVGPathSegClosePath: { - prototype: SVGPathSegClosePath; - new(): SVGPathSegClosePath; -} - -interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicAbs: { - prototype: SVGPathSegCurvetoCubicAbs; - new(): SVGPathSegCurvetoCubicAbs; -} - -interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicRel: { - prototype: SVGPathSegCurvetoCubicRel; - new(): SVGPathSegCurvetoCubicRel; -} - -interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothAbs: { - prototype: SVGPathSegCurvetoCubicSmoothAbs; - new(): SVGPathSegCurvetoCubicSmoothAbs; -} - -interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothRel: { - prototype: SVGPathSegCurvetoCubicSmoothRel; - new(): SVGPathSegCurvetoCubicSmoothRel; -} - -interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticAbs: { - prototype: SVGPathSegCurvetoQuadraticAbs; - new(): SVGPathSegCurvetoQuadraticAbs; -} - -interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticRel: { - prototype: SVGPathSegCurvetoQuadraticRel; - new(): SVGPathSegCurvetoQuadraticRel; -} - -interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothAbs: { - prototype: SVGPathSegCurvetoQuadraticSmoothAbs; - new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} - -interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothRel: { - prototype: SVGPathSegCurvetoQuadraticSmoothRel; - new(): SVGPathSegCurvetoQuadraticSmoothRel; -} - -interface SVGPathSegLinetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoAbs: { - prototype: SVGPathSegLinetoAbs; - new(): SVGPathSegLinetoAbs; -} - -interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalAbs: { - prototype: SVGPathSegLinetoHorizontalAbs; - new(): SVGPathSegLinetoHorizontalAbs; -} - -interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalRel: { - prototype: SVGPathSegLinetoHorizontalRel; - new(): SVGPathSegLinetoHorizontalRel; -} - -interface SVGPathSegLinetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoRel: { - prototype: SVGPathSegLinetoRel; - new(): SVGPathSegLinetoRel; -} - -interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalAbs: { - prototype: SVGPathSegLinetoVerticalAbs; - new(): SVGPathSegLinetoVerticalAbs; -} - -interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalRel: { - prototype: SVGPathSegLinetoVerticalRel; - new(): SVGPathSegLinetoVerticalRel; -} - -interface SVGPathSegList { - readonly numberOfItems: number; - appendItem(newItem: SVGPathSeg): SVGPathSeg; - clear(): void; - getItem(index: number): SVGPathSeg; - initialize(newItem: SVGPathSeg): SVGPathSeg; - insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; - removeItem(index: number): SVGPathSeg; - replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; -} - -declare var SVGPathSegList: { - prototype: SVGPathSegList; - new(): SVGPathSegList; -} - -interface SVGPathSegMovetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoAbs: { - prototype: SVGPathSegMovetoAbs; - new(): SVGPathSegMovetoAbs; -} - -interface SVGPathSegMovetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoRel: { - prototype: SVGPathSegMovetoRel; - new(): SVGPathSegMovetoRel; -} - -interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly patternContentUnits: SVGAnimatedEnumeration; - readonly patternTransform: SVGAnimatedTransformList; - readonly patternUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPatternElement: { - prototype: SVGPatternElement; - new(): SVGPatternElement; -} - -interface SVGPoint { - x: number; - y: number; - matrixTransform(matrix: SVGMatrix): SVGPoint; -} - -declare var SVGPoint: { - prototype: SVGPoint; - new(): SVGPoint; -} - -interface SVGPointList { - readonly numberOfItems: number; - appendItem(newItem: SVGPoint): SVGPoint; - clear(): void; - getItem(index: number): SVGPoint; - initialize(newItem: SVGPoint): SVGPoint; - insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; - removeItem(index: number): SVGPoint; - replaceItem(newItem: SVGPoint, index: number): SVGPoint; -} - -declare var SVGPointList: { - prototype: SVGPointList; - new(): SVGPointList; -} - -interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolygonElement: { - prototype: SVGPolygonElement; - new(): SVGPolygonElement; -} - -interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolylineElement: { - prototype: SVGPolylineElement; - new(): SVGPolylineElement; -} - -interface SVGPreserveAspectRatio { - align: number; - meetOrSlice: number; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -declare var SVGPreserveAspectRatio: { - prototype: SVGPreserveAspectRatio; - new(): SVGPreserveAspectRatio; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -interface SVGRadialGradientElement extends SVGGradientElement { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly fx: SVGAnimatedLength; - readonly fy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; -} - -declare var SVGRadialGradientElement: { - prototype: SVGRadialGradientElement; - new(): SVGRadialGradientElement; -} - -interface SVGRect { - height: number; - width: number; - x: number; - y: number; -} - -declare var SVGRect: { - prototype: SVGRect; - new(): SVGRect; -} - -interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGRectElement: { - prototype: SVGRectElement; - new(): SVGRectElement; -} - -interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - contentScriptType: string; - contentStyleType: string; - currentScale: number; - readonly currentTranslate: SVGPoint; - readonly height: SVGAnimatedLength; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onunload: (this: this, ev: Event) => any; - onzoom: (this: this, ev: SVGZoomEvent) => any; - readonly pixelUnitToMillimeterX: number; - readonly pixelUnitToMillimeterY: number; - readonly screenPixelToMillimeterX: number; - readonly screenPixelToMillimeterY: number; - readonly viewport: SVGRect; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - checkEnclosure(element: SVGElement, rect: SVGRect): boolean; - checkIntersection(element: SVGElement, rect: SVGRect): boolean; - createSVGAngle(): SVGAngle; - createSVGLength(): SVGLength; - createSVGMatrix(): SVGMatrix; - createSVGNumber(): SVGNumber; - createSVGPoint(): SVGPoint; - createSVGRect(): SVGRect; - createSVGTransform(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - deselectAll(): void; - forceRedraw(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getCurrentTime(): number; - getElementById(elementId: string): Element; - getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - pauseAnimations(): void; - setCurrentTime(seconds: number): void; - suspendRedraw(maxWaitMilliseconds: number): number; - unpauseAnimations(): void; - unsuspendRedraw(suspendHandleID: number): void; - unsuspendRedrawAll(): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "SVGAbort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGError", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGUnload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGZoom", listener: (this: this, ev: SVGZoomEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSVGElement: { - prototype: SVGSVGElement; - new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement, SVGStylable { - readonly offset: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement, SVGLangSpace { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} - -interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSwitchElement: { - prototype: SVGSwitchElement; - new(): SVGSwitchElement; -} - -interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSymbolElement: { - prototype: SVGSymbolElement; - new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} - -interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly lengthAdjust: SVGAnimatedEnumeration; - readonly textLength: SVGAnimatedLength; - getCharNumAtPosition(point: SVGPoint): number; - getComputedTextLength(): number; - getEndPositionOfChar(charnum: number): SVGPoint; - getExtentOfChar(charnum: number): SVGRect; - getNumberOfChars(): number; - getRotationOfChar(charnum: number): number; - getStartPositionOfChar(charnum: number): SVGPoint; - getSubStringLength(charnum: number, nchars: number): number; - selectSubString(charnum: number, nchars: number): void; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextContentElement: { - prototype: SVGTextContentElement; - new(): SVGTextContentElement; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; -} - -interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextElement: { - prototype: SVGTextElement; - new(): SVGTextElement; -} - -interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { - readonly method: SVGAnimatedEnumeration; - readonly spacing: SVGAnimatedEnumeration; - readonly startOffset: SVGAnimatedLength; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextPathElement: { - prototype: SVGTextPathElement; - new(): SVGTextPathElement; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} - -interface SVGTextPositioningElement extends SVGTextContentElement { - readonly dx: SVGAnimatedLengthList; - readonly dy: SVGAnimatedLengthList; - readonly rotate: SVGAnimatedNumberList; - readonly x: SVGAnimatedLengthList; - readonly y: SVGAnimatedLengthList; -} - -declare var SVGTextPositioningElement: { - prototype: SVGTextPositioningElement; - new(): SVGTextPositioningElement; -} - -interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTitleElement: { - prototype: SVGTitleElement; - new(): SVGTitleElement; -} - -interface SVGTransform { - readonly angle: number; - readonly matrix: SVGMatrix; - readonly type: number; - setMatrix(matrix: SVGMatrix): void; - setRotate(angle: number, cx: number, cy: number): void; - setScale(sx: number, sy: number): void; - setSkewX(angle: number): void; - setSkewY(angle: number): void; - setTranslate(tx: number, ty: number): void; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -declare var SVGTransform: { - prototype: SVGTransform; - new(): SVGTransform; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -interface SVGTransformList { - readonly numberOfItems: number; - appendItem(newItem: SVGTransform): SVGTransform; - clear(): void; - consolidate(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - getItem(index: number): SVGTransform; - initialize(newItem: SVGTransform): SVGTransform; - insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; - removeItem(index: number): SVGTransform; - replaceItem(newItem: SVGTransform, index: number): SVGTransform; -} - -declare var SVGTransformList: { - prototype: SVGTransformList; - new(): SVGTransformList; -} - -interface SVGUnitTypes { - readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; - readonly SVG_UNIT_TYPE_UNKNOWN: number; - readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; -} -declare var SVGUnitTypes: SVGUnitTypes; - -interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; - readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGUseElement: { - prototype: SVGUseElement; - new(): SVGUseElement; -} - -interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - readonly viewTarget: SVGStringList; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGViewElement: { - prototype: SVGViewElement; - new(): SVGViewElement; -} - -interface SVGZoomAndPan { - readonly zoomAndPan: number; -} - -declare var SVGZoomAndPan: { - readonly SVG_ZOOMANDPAN_DISABLE: number; - readonly SVG_ZOOMANDPAN_MAGNIFY: number; - readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} - -interface SVGZoomEvent extends UIEvent { - readonly newScale: number; - readonly newTranslate: SVGPoint; - readonly previousScale: number; - readonly previousTranslate: SVGPoint; - readonly zoomRectScreen: SVGRect; -} - -declare var SVGZoomEvent: { - prototype: SVGZoomEvent; - new(): SVGZoomEvent; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: this, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: "MSOrientationChange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: this, ev: AudioProcessingEvent) => any; - addEventListener(type: "audioprocess", listener: (this: this, ev: AudioProcessingEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: string; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - 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: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} - -interface Text extends CharacterData { - readonly wholeText: string; - splitText(offset: number): Text; -} - -declare var Text: { - prototype: Text; - new(): Text; -} - -interface TextEvent extends UIEvent { - readonly data: string; - readonly inputMethod: number; - readonly locale: string; - initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -declare var TextEvent: { - prototype: TextEvent; - new(): TextEvent; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -interface TextMetrics { - readonly width: number; -} - -declare var TextMetrics: { - prototype: TextMetrics; - new(): TextMetrics; -} - -interface TextTrack extends EventTarget { - readonly activeCues: TextTrackCueList; - readonly cues: TextTrackCueList; - readonly inBandMetadataTrackDispatchType: string; - readonly kind: string; - readonly label: string; - readonly language: string; - mode: any; - oncuechange: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - readonly readyState: number; - addCue(cue: TextTrackCue): void; - removeCue(cue: TextTrackCue): void; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrack: { - prototype: TextTrack; - new(): TextTrack; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; -} - -interface TextTrackCue extends EventTarget { - endTime: number; - id: string; - onenter: (this: this, ev: Event) => any; - onexit: (this: this, ev: Event) => any; - pauseOnExit: boolean; - startTime: number; - text: string; - readonly track: TextTrack; - getCueAsHTML(): DocumentFragment; - addEventListener(type: "enter", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "exit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrackCue: { - prototype: TextTrackCue; - new(startTime: number, endTime: number, text: string): TextTrackCue; -} - -interface TextTrackCueList { - readonly length: number; - getCueById(id: string): TextTrackCue; - item(index: number): TextTrackCue; - [index: number]: TextTrackCue; -} - -declare var TextTrackCueList: { - prototype: TextTrackCueList; - new(): TextTrackCueList; -} - -interface TextTrackList extends EventTarget { - readonly length: number; - onaddtrack: ((this: this, ev: TrackEvent) => any) | null; - item(index: number): TextTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: TextTrack; -} - -declare var TextTrackList: { - prototype: TextTrackList; - new(): TextTrackList; -} - -interface TimeRanges { - readonly length: number; - end(index: number): number; - start(index: number): number; -} - -declare var TimeRanges: { - prototype: TimeRanges; - new(): TimeRanges; -} - -interface Touch { - readonly clientX: number; - readonly clientY: number; - readonly identifier: number; - readonly pageX: number; - readonly pageY: number; - readonly screenX: number; - readonly screenY: number; - readonly target: EventTarget; -} - -declare var Touch: { - prototype: Touch; - new(): Touch; -} - -interface TouchEvent extends UIEvent { - readonly altKey: boolean; - readonly changedTouches: TouchList; - readonly ctrlKey: boolean; - readonly metaKey: boolean; - readonly shiftKey: boolean; - readonly targetTouches: TouchList; - readonly touches: TouchList; -} - -declare var TouchEvent: { - prototype: TouchEvent; - new(): TouchEvent; -} - -interface TouchList { - readonly length: number; - item(index: number): Touch | null; - [index: number]: Touch; -} - -declare var TouchList: { - prototype: TouchList; - new(): TouchList; -} - -interface TrackEvent extends Event { - readonly track: any; -} - -declare var TrackEvent: { - prototype: TrackEvent; - new(): TrackEvent; -} - -interface TransitionEvent extends Event { - readonly elapsedTime: number; - readonly propertyName: string; - initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; -} - -declare var TransitionEvent: { - prototype: TransitionEvent; - new(): TransitionEvent; -} - -interface TreeWalker { - currentNode: Node; - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; -} - -declare var TreeWalker: { - prototype: TreeWalker; - new(): TreeWalker; -} - -interface UIEvent extends Event { - readonly detail: number; - readonly view: Window; - initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; -} - -declare var UIEvent: { - prototype: UIEvent; - new(type: string, eventInitDict?: UIEventInit): UIEvent; -} - -interface URL { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - username: string; - toString(): string; -} - -declare var URL: { - prototype: URL; - new(url: string, base?: string): URL; - createObjectURL(object: any, options?: ObjectURLOptions): string; - revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} - -interface ValidityState { - readonly badInput: boolean; - readonly customError: boolean; - readonly patternMismatch: boolean; - readonly rangeOverflow: boolean; - readonly rangeUnderflow: boolean; - readonly stepMismatch: boolean; - readonly tooLong: boolean; - readonly typeMismatch: boolean; - readonly valid: boolean; - readonly valueMissing: boolean; -} - -declare var ValidityState: { - prototype: ValidityState; - new(): ValidityState; -} - -interface VideoPlaybackQuality { - readonly corruptedVideoFrames: number; - readonly creationTime: number; - readonly droppedVideoFrames: number; - readonly totalFrameDelay: number; - readonly totalVideoFrames: number; -} - -declare var VideoPlaybackQuality: { - prototype: VideoPlaybackQuality; - new(): VideoPlaybackQuality; -} - -interface VideoTrack { - readonly id: string; - kind: string; - readonly label: string; - language: string; - selected: boolean; - readonly sourceBuffer: SourceBuffer; -} - -declare var VideoTrack: { - prototype: VideoTrack; - new(): VideoTrack; -} - -interface VideoTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - readonly selectedIndex: number; - getTrackById(id: string): VideoTrack | null; - item(index: number): VideoTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: VideoTrack; -} - -declare var VideoTrackList: { - prototype: VideoTrackList; - new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -interface WaveShaperNode extends AudioNode { - curve: Float32Array | null; - oversample: string; -} - -declare var WaveShaperNode: { - prototype: WaveShaperNode; - new(): WaveShaperNode; -} - -interface WebGLActiveInfo { - readonly name: string; - readonly size: number; - readonly type: number; -} - -declare var WebGLActiveInfo: { - prototype: WebGLActiveInfo; - new(): WebGLActiveInfo; -} - -interface WebGLBuffer extends WebGLObject { -} - -declare var WebGLBuffer: { - prototype: WebGLBuffer; - new(): WebGLBuffer; -} - -interface WebGLContextEvent extends Event { - readonly statusMessage: string; -} - -declare var WebGLContextEvent: { - prototype: WebGLContextEvent; - new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} - -interface WebGLFramebuffer extends WebGLObject { -} - -declare var WebGLFramebuffer: { - prototype: WebGLFramebuffer; - new(): WebGLFramebuffer; -} - -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -} - -interface WebGLProgram extends WebGLObject { -} - -declare var WebGLProgram: { - prototype: WebGLProgram; - new(): WebGLProgram; -} - -interface WebGLRenderbuffer extends WebGLObject { -} - -declare var WebGLRenderbuffer: { - prototype: WebGLRenderbuffer; - new(): WebGLRenderbuffer; -} - -interface WebGLRenderingContext { - readonly canvas: HTMLCanvasElement; - readonly drawingBufferHeight: number; - readonly drawingBufferWidth: number; - activeTexture(texture: number): void; - attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; - bindBuffer(target: number, buffer: WebGLBuffer | null): void; - bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; - bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; - bindTexture(target: number, texture: WebGLTexture | null): void; - blendColor(red: number, green: number, blue: number, alpha: number): void; - blendEquation(mode: number): void; - blendEquationSeparate(modeRGB: number, modeAlpha: number): void; - blendFunc(sfactor: number, dfactor: number): void; - blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; - bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; - bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; - checkFramebufferStatus(target: number): number; - clear(mask: number): void; - clearColor(red: number, green: number, blue: number, alpha: number): void; - clearDepth(depth: number): void; - clearStencil(s: number): void; - colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; - compileShader(shader: WebGLShader | null): void; - compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; - compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; - copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; - copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; - createBuffer(): WebGLBuffer | null; - createFramebuffer(): WebGLFramebuffer | null; - createProgram(): WebGLProgram | null; - createRenderbuffer(): WebGLRenderbuffer | null; - createShader(type: number): WebGLShader | null; - createTexture(): WebGLTexture | null; - cullFace(mode: number): void; - deleteBuffer(buffer: WebGLBuffer | null): void; - deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; - deleteProgram(program: WebGLProgram | null): void; - deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; - deleteShader(shader: WebGLShader | null): void; - deleteTexture(texture: WebGLTexture | null): void; - depthFunc(func: number): void; - depthMask(flag: boolean): void; - depthRange(zNear: number, zFar: number): void; - detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - disable(cap: number): void; - disableVertexAttribArray(index: number): void; - drawArrays(mode: number, first: number, count: number): void; - drawElements(mode: number, count: number, type: number, offset: number): void; - enable(cap: number): void; - enableVertexAttribArray(index: number): void; - finish(): void; - flush(): void; - framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; - framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; - frontFace(mode: number): void; - generateMipmap(target: number): void; - getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; - getAttribLocation(program: WebGLProgram | null, name: string): number; - getBufferParameter(target: number, pname: number): any; - getContextAttributes(): WebGLContextAttributes; - getError(): number; - getExtension(name: string): any; - getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; - getParameter(pname: number): any; - getProgramInfoLog(program: WebGLProgram | null): string | null; - getProgramParameter(program: WebGLProgram | null, pname: number): any; - getRenderbufferParameter(target: number, pname: number): any; - getShaderInfoLog(shader: WebGLShader | null): string | null; - getShaderParameter(shader: WebGLShader | null, pname: number): any; - getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; - getShaderSource(shader: WebGLShader | null): string | null; - getSupportedExtensions(): string[] | null; - getTexParameter(target: number, pname: number): any; - getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; - getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; - getVertexAttrib(index: number, pname: number): any; - getVertexAttribOffset(index: number, pname: number): number; - hint(target: number, mode: number): void; - isBuffer(buffer: WebGLBuffer | null): boolean; - isContextLost(): boolean; - isEnabled(cap: number): boolean; - isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; - isProgram(program: WebGLProgram | null): boolean; - isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; - isShader(shader: WebGLShader | null): boolean; - isTexture(texture: WebGLTexture | null): boolean; - lineWidth(width: number): void; - linkProgram(program: WebGLProgram | null): void; - pixelStorei(pname: number, param: number): void; - polygonOffset(factor: number, units: number): void; - readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; - renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; - sampleCoverage(value: number, invert: boolean): void; - scissor(x: number, y: number, width: number, height: number): void; - shaderSource(shader: WebGLShader | null, source: string): void; - stencilFunc(func: number, ref: number, mask: number): void; - stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; - stencilMask(mask: number): void; - 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, 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, 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; - uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - useProgram(program: WebGLProgram | null): void; - validateProgram(program: WebGLProgram | null): void; - vertexAttrib1f(indx: number, x: number): void; - vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib2f(indx: number, x: number, y: number): void; - vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib3f(indx: number, x: number, y: number, z: number): void; - vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; - vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; - vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; - viewport(x: number, y: number, width: number, height: number): void; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -declare var WebGLRenderingContext: { - prototype: WebGLRenderingContext; - new(): WebGLRenderingContext; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -interface WebGLShader extends WebGLObject { -} - -declare var WebGLShader: { - prototype: WebGLShader; - new(): WebGLShader; -} - -interface WebGLShaderPrecisionFormat { - readonly precision: number; - readonly rangeMax: number; - readonly rangeMin: number; -} - -declare var WebGLShaderPrecisionFormat: { - prototype: WebGLShaderPrecisionFormat; - new(): WebGLShaderPrecisionFormat; -} - -interface WebGLTexture extends WebGLObject { -} - -declare var WebGLTexture: { - prototype: WebGLTexture; - new(): WebGLTexture; -} - -interface WebGLUniformLocation { -} - -declare var WebGLUniformLocation: { - prototype: WebGLUniformLocation; - new(): WebGLUniformLocation; -} - -interface WebKitCSSMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - m11: number; - m12: number; - m13: number; - m14: number; - m21: number; - m22: number; - m23: number; - m24: number; - m31: number; - m32: number; - m33: number; - m34: number; - m41: number; - m42: number; - m43: number; - m44: number; - inverse(): WebKitCSSMatrix; - multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; - rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; - rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; - scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; - setMatrixValue(value: string): void; - skewX(angle: number): WebKitCSSMatrix; - skewY(angle: number): WebKitCSSMatrix; - toString(): string; - translate(x: number, y: number, z?: number): WebKitCSSMatrix; -} - -declare var WebKitCSSMatrix: { - prototype: WebKitCSSMatrix; - new(text?: string): WebKitCSSMatrix; -} - -interface WebKitPoint { - x: number; - y: number; -} - -declare var WebKitPoint: { - prototype: WebKitPoint; - new(x?: number, y?: number): WebKitPoint; -} - -interface WebSocket extends EventTarget { - binaryType: string; - readonly bufferedAmount: number; - readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; - readonly protocol: string; - readonly readyState: number; - readonly url: string; - close(code?: number, reason?: string): void; - send(data: any): void; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WebSocket: { - prototype: WebSocket; - new(url: string, protocols?: string | string[]): WebSocket; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; -} - -interface WheelEvent extends MouseEvent { - readonly deltaMode: number; - readonly deltaX: number; - readonly deltaY: number; - readonly deltaZ: number; - readonly wheelDelta: number; - readonly wheelDeltaX: number; - readonly wheelDeltaY: number; - getCurrentPoint(element: Element): void; - initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -declare var WheelEvent: { - prototype: WheelEvent; - new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { - readonly applicationCache: ApplicationCache; - readonly clientInformation: Navigator; - readonly closed: boolean; - readonly crypto: Crypto; - defaultStatus: string; - readonly devicePixelRatio: number; - readonly doNotTrack: string; - readonly document: Document; - event: Event; - readonly external: External; - readonly frameElement: Element; - readonly frames: Window; - readonly history: History; - readonly innerHeight: number; - readonly innerWidth: number; - readonly length: number; - readonly location: Location; - readonly locationbar: BarProp; - readonly menubar: BarProp; - readonly msCredentials: MSCredentials; - name: string; - readonly navigator: Navigator; - offscreenBuffering: string | boolean; - onabort: (this: this, ev: UIEvent) => any; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncompassneedscalibration: (this: this, ev: Event) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondevicelight: (this: this, ev: DeviceLightEvent) => any; - ondevicemotion: (this: this, ev: DeviceMotionEvent) => any; - ondeviceorientation: (this: this, ev: DeviceOrientationEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: ErrorEventHandler; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreadystatechange: (this: this, ev: ProgressEvent) => any; - onreset: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onstalled: (this: this, ev: Event) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onunload: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - opener: any; - orientation: string | number; - readonly outerHeight: number; - readonly outerWidth: number; - readonly pageXOffset: number; - readonly pageYOffset: number; - readonly parent: Window; - readonly performance: Performance; - readonly personalbar: BarProp; - readonly screen: Screen; - readonly screenLeft: number; - readonly screenTop: number; - readonly screenX: number; - readonly screenY: number; - readonly scrollX: number; - readonly scrollY: number; - readonly scrollbars: BarProp; - readonly self: Window; - status: string; - readonly statusbar: BarProp; - readonly styleMedia: StyleMedia; - readonly toolbar: BarProp; - readonly top: Window; - readonly window: Window; - URL: typeof URL; - Blob: typeof Blob; - alert(message?: any): void; - blur(): void; - cancelAnimationFrame(handle: number): void; - captureEvents(): void; - close(): void; - confirm(message?: string): boolean; - focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; - getSelection(): Selection; - matchMedia(mediaQuery: string): MediaQueryList; - moveBy(x?: number, y?: number): void; - moveTo(x?: number, y?: number): void; - msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; - postMessage(message: any, targetOrigin: string, transfer?: any[]): void; - print(): void; - prompt(message?: string, _default?: string): string | null; - releaseEvents(): void; - requestAnimationFrame(callback: FrameRequestCallback): number; - resizeBy(x?: number, y?: number): void; - resizeTo(x?: number, y?: number): void; - scroll(x?: number, y?: number): void; - scrollBy(x?: number, y?: number): void; - scrollTo(x?: number, y?: number): void; - webkitCancelAnimationFrame(handle: number): void; - webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; - webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; - webkitRequestAnimationFrame(callback: FrameRequestCallback): number; - scroll(options?: ScrollToOptions): void; - scrollTo(options?: ScrollToOptions): void; - scrollBy(options?: ScrollToOptions): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "compassneedscalibration", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicelight", listener: (this: this, ev: DeviceLightEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicemotion", listener: (this: this, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deviceorientation", listener: (this: this, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; -} - -declare var Window: { - prototype: Window; - new(): Window; -} - -interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; - postMessage(message: any, ports?: any): void; - terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Worker: { - prototype: Worker; - new(stringUrl: string): Worker; -} - -interface XMLDocument extends Document { -} - -declare var XMLDocument: { - prototype: XMLDocument; - new(): XMLDocument; -} - -interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly response: any; - readonly responseText: string; - responseType: string; - readonly responseXML: any; - readonly status: number; - readonly statusText: string; - timeout: number; - readonly upload: XMLHttpRequestUpload; - withCredentials: boolean; - msCaching?: string; - abort(): void; - getAllResponseHeaders(): string; - getResponseHeader(header: string): string | null; - msCachingEnabled(): boolean; - open(method: string, url: string, async?: boolean, user?: string, password?: string): void; - overrideMimeType(mime: string): void; - send(data?: Document): void; - send(data?: string): void; - send(data?: any): void; - setRequestHeader(header: string, value: string): void; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequest: { - prototype: XMLHttpRequest; - new(): XMLHttpRequest; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - create(): XMLHttpRequest; -} - -interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequestUpload: { - prototype: XMLHttpRequestUpload; - new(): XMLHttpRequestUpload; -} - -interface XMLSerializer { - serializeToString(target: Node): string; -} - -declare var XMLSerializer: { - prototype: XMLSerializer; - new(): XMLSerializer; -} - -interface XPathEvaluator { - createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; -} - -declare var XPathEvaluator: { - prototype: XPathEvaluator; - new(): XPathEvaluator; -} - -interface XPathExpression { - evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; -} - -declare var XPathExpression: { - prototype: XPathExpression; - new(): XPathExpression; -} - -interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; -} - -declare var XPathNSResolver: { - prototype: XPathNSResolver; - new(): XPathNSResolver; -} - -interface XPathResult { - readonly booleanValue: boolean; - readonly invalidIteratorState: boolean; - readonly numberValue: number; - readonly resultType: number; - readonly singleNodeValue: Node; - readonly snapshotLength: number; - readonly stringValue: string; - iterateNext(): Node; - snapshotItem(index: number): Node; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -declare var XPathResult: { - prototype: XPathResult; - new(): XPathResult; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -interface XSLTProcessor { - clearParameters(): void; - getParameter(namespaceURI: string, localName: string): any; - importStylesheet(style: Node): void; - removeParameter(namespaceURI: string, localName: string): void; - reset(): void; - setParameter(namespaceURI: string, localName: string, value: any): void; - transformToDocument(source: Node): Document; - transformToFragment(source: Node, document: Document): DocumentFragment; -} - -declare var XSLTProcessor: { - prototype: XSLTProcessor; - new(): XSLTProcessor; -} - -interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface CanvasPathMethods { - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; - bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; - closePath(): void; - ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; - rect(x: number, y: number, w: number, h: number): void; -} - -interface ChildNode { - remove(): void; -} - -interface DOML2DeprecatedColorProperty { - color: string; -} - -interface DOML2DeprecatedSizeProperty { - size: number; -} - -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CommandEvent"): CommandEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - -interface ElementTraversal { - readonly childElementCount: number; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly nextElementSibling: Element; - readonly previousElementSibling: Element; -} - -interface GetSVGDocument { - getSVGDocument(): Document; -} - -interface GlobalEventHandlers { - onpointercancel: (this: this, ev: PointerEvent) => any; - onpointerdown: (this: this, ev: PointerEvent) => any; - onpointerenter: (this: this, ev: PointerEvent) => any; - onpointerleave: (this: this, ev: PointerEvent) => any; - onpointermove: (this: this, ev: PointerEvent) => any; - onpointerout: (this: this, ev: PointerEvent) => any; - onpointerover: (this: this, ev: PointerEvent) => any; - onpointerup: (this: this, ev: PointerEvent) => any; - onwheel: (this: this, ev: WheelEvent) => any; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface HTMLTableAlignment { - /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ - ch: string; - /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ - chOff: string; - /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ - vAlign: string; -} - -interface IDBEnvironment { - readonly indexedDB: IDBFactory; -} - -interface LinkStyle { - readonly sheet: StyleSheet; -} - -interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly result: any; - abort(): void; - readonly DONE: number; - readonly EMPTY: number; - readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface MSFileSaver { - msSaveBlob(blob: any, defaultName?: string): boolean; - msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; -} - -interface MSNavigatorDoNotTrack { - confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; - confirmWebWideTrackingException(args: ExceptionInformation): boolean; - removeSiteSpecificTrackingException(args: ExceptionInformation): void; - removeWebWideTrackingException(args: ExceptionInformation): void; - storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; - storeWebWideTrackingException(args: StoreExceptionsInformation): void; -} - -interface NavigatorContentUtils { -} - -interface NavigatorGeolocation { - readonly geolocation: Geolocation; -} - -interface NavigatorID { - readonly appName: string; - readonly appVersion: string; - readonly platform: string; - readonly product: string; - readonly productSub: string; - readonly userAgent: string; - readonly vendor: string; - readonly vendorSub: string; -} - -interface NavigatorOnLine { - readonly onLine: boolean; -} - -interface NavigatorStorageUtils { -} - -interface NavigatorUserMedia { - readonly mediaDevices: MediaDevices; - getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; -} - -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; -} - -interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; -} - -interface SVGAnimatedPathData { - readonly pathSegList: SVGPathSegList; -} - -interface SVGAnimatedPoints { - readonly animatedPoints: SVGPointList; - readonly points: SVGPointList; -} - -interface SVGExternalResourcesRequired { - readonly externalResourcesRequired: SVGAnimatedBoolean; -} - -interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { - readonly height: SVGAnimatedLength; - readonly result: SVGAnimatedString; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; -} - -interface SVGFitToViewBox { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly viewBox: SVGAnimatedRect; -} - -interface SVGLangSpace { - xmllang: string; - xmlspace: string; -} - -interface SVGLocatable { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; - getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; - getTransformToElement(element: SVGElement): SVGMatrix; -} - -interface SVGStylable { - className: any; - readonly style: CSSStyleDeclaration; -} - -interface SVGTests { - readonly requiredExtensions: SVGStringList; - readonly requiredFeatures: SVGStringList; - readonly systemLanguage: SVGStringList; - hasExtension(extension: string): boolean; -} - -interface SVGTransformable extends SVGLocatable { - readonly transform: SVGAnimatedTransformList; -} - -interface SVGURIReference { - readonly href: SVGAnimatedString; -} - -interface WindowBase64 { - atob(encodedString: string): string; - btoa(rawString: string): string; -} - -interface WindowConsole { - readonly console: Console; -} - -interface WindowLocalStorage { - readonly localStorage: Storage; -} - -interface WindowSessionStorage { - readonly sessionStorage: Storage; -} - -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(handler: (...args: any[]) => void): number; - setImmediate(handler: any, ...args: any[]): number; -} - -interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface StorageEventInit extends EventInit { - key?: string; - oldValue?: string; - newValue?: string; - url: string; - 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; - [index: number]: TNode; -} - -interface HTMLCollectionOf extends HTMLCollection { - item(index: number): T; - namedItem(name: string): T; - [index: number]: T; -} - -interface BlobPropertyBag { - type?: string; - endings?: string; -} - -interface FilePropertyBag { - type?: string; - lastModified?: number; -} - -interface EventListenerObject { - handleEvent(evt: Event): void; -} - -interface MessageEventInit extends EventInit { - data?: any; - origin?: string; - lastEventId?: string; - channel?: string; - source?: any; - ports?: MessagePort[]; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -interface ScrollOptions { - behavior?: ScrollBehavior; -} - -interface ScrollToOptions extends ScrollOptions { - left?: number; - top?: number; -} - -interface ScrollIntoViewOptions extends ScrollOptions { - block?: ScrollLogicalPosition; - inline?: ScrollLogicalPosition; -} - -interface ClipboardEventInit extends EventInit { - data?: string; - dataType?: string; -} - -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 { - namedCurve: 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; -} - -interface ParentNode { - readonly children: HTMLCollection; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly childElementCount: number; -} - -declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; - -interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; -} -interface PositionCallback { - (position: Position): void; -} -interface PositionErrorCallback { - (error: PositionError): void; -} -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: string): void; -} -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; -declare var applicationCache: ApplicationCache; -declare var clientInformation: Navigator; -declare var closed: boolean; -declare var crypto: Crypto; -declare var defaultStatus: string; -declare var devicePixelRatio: number; -declare var doNotTrack: string; -declare var document: Document; -declare var event: Event; -declare var external: External; -declare var frameElement: Element; -declare var frames: Window; -declare var history: History; -declare var innerHeight: number; -declare var innerWidth: number; -declare var length: number; -declare var location: Location; -declare var locationbar: BarProp; -declare var menubar: BarProp; -declare var msCredentials: MSCredentials; -declare const name: never; -declare var navigator: Navigator; -declare var offscreenBuffering: string | boolean; -declare var onabort: (this: Window, ev: UIEvent) => any; -declare var onafterprint: (this: Window, ev: Event) => any; -declare var onbeforeprint: (this: Window, ev: Event) => any; -declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; -declare var onblur: (this: Window, ev: FocusEvent) => any; -declare var oncanplay: (this: Window, ev: Event) => any; -declare var oncanplaythrough: (this: Window, ev: Event) => any; -declare var onchange: (this: Window, ev: Event) => any; -declare var onclick: (this: Window, ev: MouseEvent) => any; -declare var oncompassneedscalibration: (this: Window, ev: Event) => any; -declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; -declare var ondblclick: (this: Window, ev: MouseEvent) => any; -declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; -declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; -declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; -declare var ondrag: (this: Window, ev: DragEvent) => any; -declare var ondragend: (this: Window, ev: DragEvent) => any; -declare var ondragenter: (this: Window, ev: DragEvent) => any; -declare var ondragleave: (this: Window, ev: DragEvent) => any; -declare var ondragover: (this: Window, ev: DragEvent) => any; -declare var ondragstart: (this: Window, ev: DragEvent) => any; -declare var ondrop: (this: Window, ev: DragEvent) => any; -declare var ondurationchange: (this: Window, ev: Event) => any; -declare var onemptied: (this: Window, ev: Event) => any; -declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; -declare var onerror: ErrorEventHandler; -declare var onfocus: (this: Window, ev: FocusEvent) => any; -declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; -declare var oninput: (this: Window, ev: Event) => any; -declare var oninvalid: (this: Window, ev: Event) => any; -declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; -declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; -declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; -declare var onload: (this: Window, ev: Event) => any; -declare var onloadeddata: (this: Window, ev: Event) => any; -declare var onloadedmetadata: (this: Window, ev: Event) => any; -declare var onloadstart: (this: Window, ev: Event) => any; -declare var onmessage: (this: Window, ev: MessageEvent) => any; -declare var onmousedown: (this: Window, ev: MouseEvent) => any; -declare var onmouseenter: (this: Window, ev: MouseEvent) => any; -declare var onmouseleave: (this: Window, ev: MouseEvent) => any; -declare var onmousemove: (this: Window, ev: MouseEvent) => any; -declare var onmouseout: (this: Window, ev: MouseEvent) => any; -declare var onmouseover: (this: Window, ev: MouseEvent) => any; -declare var onmouseup: (this: Window, ev: MouseEvent) => any; -declare var onmousewheel: (this: Window, ev: WheelEvent) => any; -declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; -declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; -declare var onoffline: (this: Window, ev: Event) => any; -declare var ononline: (this: Window, ev: Event) => any; -declare var onorientationchange: (this: Window, ev: Event) => any; -declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; -declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; -declare var onpause: (this: Window, ev: Event) => any; -declare var onplay: (this: Window, ev: Event) => any; -declare var onplaying: (this: Window, ev: Event) => any; -declare var onpopstate: (this: Window, ev: PopStateEvent) => any; -declare var onprogress: (this: Window, ev: ProgressEvent) => any; -declare var onratechange: (this: Window, ev: Event) => any; -declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; -declare var onreset: (this: Window, ev: Event) => any; -declare var onresize: (this: Window, ev: UIEvent) => any; -declare var onscroll: (this: Window, ev: UIEvent) => any; -declare var onseeked: (this: Window, ev: Event) => any; -declare var onseeking: (this: Window, ev: Event) => any; -declare var onselect: (this: Window, ev: UIEvent) => any; -declare var onstalled: (this: Window, ev: Event) => any; -declare var onstorage: (this: Window, ev: StorageEvent) => any; -declare var onsubmit: (this: Window, ev: Event) => any; -declare var onsuspend: (this: Window, ev: Event) => any; -declare var ontimeupdate: (this: Window, ev: Event) => any; -declare var ontouchcancel: (ev: TouchEvent) => any; -declare var ontouchend: (ev: TouchEvent) => any; -declare var ontouchmove: (ev: TouchEvent) => any; -declare var ontouchstart: (ev: TouchEvent) => any; -declare var onunload: (this: Window, ev: Event) => any; -declare var onvolumechange: (this: Window, ev: Event) => any; -declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: any; -declare var orientation: string | number; -declare var outerHeight: number; -declare var outerWidth: number; -declare var pageXOffset: number; -declare var pageYOffset: number; -declare var parent: Window; -declare var performance: Performance; -declare var personalbar: BarProp; -declare var screen: Screen; -declare var screenLeft: number; -declare var screenTop: number; -declare var screenX: number; -declare var screenY: number; -declare var scrollX: number; -declare var scrollY: number; -declare var scrollbars: BarProp; -declare var self: Window; -declare var status: string; -declare var statusbar: BarProp; -declare var styleMedia: StyleMedia; -declare var toolbar: BarProp; -declare var top: Window; -declare var window: Window; -declare function alert(message?: any): void; -declare function blur(): void; -declare function cancelAnimationFrame(handle: number): void; -declare function captureEvents(): void; -declare function close(): void; -declare function confirm(message?: string): boolean; -declare function focus(): void; -declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; -declare function getSelection(): Selection; -declare function matchMedia(mediaQuery: string): MediaQueryList; -declare function moveBy(x?: number, y?: number): void; -declare function moveTo(x?: number, y?: number): void; -declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; -declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; -declare function print(): void; -declare function prompt(message?: string, _default?: string): string | null; -declare function releaseEvents(): void; -declare function requestAnimationFrame(callback: FrameRequestCallback): number; -declare function resizeBy(x?: number, y?: number): void; -declare function resizeTo(x?: number, y?: number): void; -declare function scroll(x?: number, y?: number): void; -declare function scrollBy(x?: number, y?: number): void; -declare function scrollTo(x?: number, y?: number): void; -declare function webkitCancelAnimationFrame(handle: number): void; -declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; -declare function scroll(options?: ScrollToOptions): void; -declare function scrollTo(options?: ScrollToOptions): void; -declare function scrollBy(options?: ScrollToOptions): void; -declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -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(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; -declare var onpointercancel: (this: Window, ev: PointerEvent) => any; -declare var onpointerdown: (this: Window, ev: PointerEvent) => any; -declare var onpointerenter: (this: Window, ev: PointerEvent) => any; -declare var onpointerleave: (this: Window, ev: PointerEvent) => any; -declare var onpointermove: (this: Window, ev: PointerEvent) => any; -declare var onpointerout: (this: Window, ev: PointerEvent) => any; -declare var onpointerover: (this: Window, ev: PointerEvent) => any; -declare var onpointerup: (this: Window, ev: PointerEvent) => any; -declare var onwheel: (this: Window, ev: WheelEvent) => any; -declare var indexedDB: IDBFactory; -declare function atob(encodedString: string): string; -declare function btoa(rawString: string): string; -declare function addEventListener(type: "MSGestureChange", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureDoubleTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureEnd", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureHold", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSInertiaStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerCancel", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerDown", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerEnter", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerLeave", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerMove", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOut", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOver", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerUp", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "abort", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "afterprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeunload", listener: (this: Window, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "blur", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplay", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplaythrough", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "change", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "click", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "compassneedscalibration", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "contextmenu", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dblclick", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicelight", listener: (this: Window, ev: DeviceLightEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicemotion", listener: (this: Window, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "deviceorientation", listener: (this: Window, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drag", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragend", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragenter", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragleave", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragover", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragstart", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drop", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "durationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "emptied", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ended", listener: (this: Window, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "focus", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "hashchange", listener: (this: Window, ev: HashChangeEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "input", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "invalid", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keydown", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keypress", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keyup", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "load", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadeddata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadedmetadata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadstart", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: Window, ev: MessageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousedown", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseenter", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseleave", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseout", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseover", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseup", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousewheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "offline", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "online", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "orientationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pagehide", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pageshow", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pause", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "play", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "playing", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointercancel", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerdown", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerenter", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerleave", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointermove", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerout", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerover", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerup", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "popstate", listener: (this: Window, ev: PopStateEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "progress", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ratechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "readystatechange", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "reset", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "resize", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "scroll", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeked", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeking", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "select", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "stalled", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "storage", listener: (this: Window, ev: StorageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "submit", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "suspend", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "timeupdate", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "unload", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "volumechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "waiting", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "wheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -type AAGUID = string; -type AlgorithmIdentifier = string | Algorithm; -type ConstrainBoolean = boolean | ConstrainBooleanParameters; -type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; -type ConstrainDouble = number | ConstrainDoubleRange; -type ConstrainLong = number | ConstrainLongRange; -type CryptoOperationData = ArrayBufferView; -type GLbitfield = number; -type GLboolean = boolean; -type GLbyte = number; -type GLclampf = number; -type GLenum = number; -type GLfloat = number; -type GLint = number; -type GLintptr = number; -type GLshort = number; -type GLsizei = number; -type GLsizeiptr = number; -type GLubyte = number; -type GLuint = number; -type GLushort = number; -type IDBKeyPath = string; -type KeyFormat = string; -type KeyType = string; -type KeyUsage = string; -type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; -type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; -type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; -type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; -type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; -type payloadtype = number; -type ScrollBehavior = "auto" | "instant" | "smooth"; -type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; -type IDBValidKey = number | string | Date | IDBArrayKey; -type BufferSource = ArrayBuffer | ArrayBufferView; -type MouseWheelEvent = WheelEvent; \ No newline at end of file +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + + +///////////////////////////// +/// IE DOM APIs +///////////////////////////// + +interface Algorithm { + name: string; +} + +interface AriaRequestEventInit extends EventInit { + attributeName?: string; + attributeValue?: string; +} + +interface CommandEventInit extends EventInit { + commandName?: string; + detail?: string; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainLongRange extends LongRange { + exact?: number; + ideal?: number; +} + +interface ConstrainVideoFacingModeParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface CustomEventInit extends EventInit { + detail?: any; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface EventInit { + scoped?: boolean; + bubbles?: boolean; + cancelable?: boolean; +} + +interface EventModifierInit extends UIEventInit { + ctrlKey?: boolean; + shiftKey?: boolean; + altKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierOS?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; +} + +interface ExceptionInformation { + domain?: string; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: IDBKeyPath; +} + +interface KeyAlgorithm { + name?: string; +} + +interface KeyboardEventInit extends EventModifierInit { + code?: string; + key?: string; + location?: number; + repeat?: boolean; +} + +interface LongRange { + max?: number; + min?: number; +} + +interface MSAccountInfo { + rpDisplayName?: string; + userDisplayName?: string; + accountName?: string; + userId?: string; + accountImageUri?: string; +} + +interface MSAudioLocalClientEvent extends MSLocalClientEventBase { + networkSendQualityEventRatio?: number; + networkDelayEventRatio?: number; + cpuInsufficientEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceCaptureNotFunctioningEventRatio?: number; + deviceGlitchesEventRatio?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceClippingEventRatio?: number; + deviceEchoEventRatio?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceHowlingEventCount?: number; +} + +interface MSAudioRecvPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioRecvSignal; + packetReorderRatio?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + burstLossLength1?: number; + burstLossLength2?: number; + burstLossLength3?: number; + burstLossLength4?: number; + burstLossLength5?: number; + burstLossLength6?: number; + burstLossLength7?: number; + burstLossLength8OrHigher?: number; + fecRecvDistance1?: number; + fecRecvDistance2?: number; + fecRecvDistance3?: number; + ratioConcealedSamplesAvg?: number; + ratioStretchedSamplesAvg?: number; + ratioCompressedSamplesAvg?: number; +} + +interface MSAudioRecvSignal { + initialSignalLevelRMS?: number; + recvSignalLevelCh1?: number; + recvNoiseLevelCh1?: number; + renderSignalLevel?: number; + renderNoiseLevel?: number; + renderLoopbackSignalLevel?: number; +} + +interface MSAudioSendPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioSendSignal; + audioFECUsed?: boolean; + sendMutePercent?: number; +} + +interface MSAudioSendSignal { + noiseLevel?: number; + sendSignalLevelCh1?: number; + sendNoiseLevelCh1?: number; +} + +interface MSConnectivity { + iceType?: string; + iceWarningFlags?: MSIceWarningFlags; + relayAddress?: MSRelayAddress; +} + +interface MSCredentialFilter { + accept?: MSCredentialSpec[]; +} + +interface MSCredentialParameters { + type?: string; +} + +interface MSCredentialSpec { + type?: string; + id?: string; +} + +interface MSDelay { + roundTrip?: number; + roundTripMax?: number; +} + +interface MSDescription extends RTCStats { + connectivity?: MSConnectivity; + transport?: string; + networkconnectivity?: MSNetworkConnectivityInfo; + localAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + deviceDevName?: string; + reflexiveLocalIPAddr?: MSIPAddressInfo; +} + +interface MSFIDOCredentialParameters extends MSCredentialParameters { + algorithm?: string | Algorithm; + authenticators?: AAGUID[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + port?: number; + manufacturerMacAddrMask?: string; +} + +interface MSIceWarningFlags { + turnTcpTimedOut?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; + turnTcpAllocateFailed?: boolean; + turnTcpSendFailed?: boolean; + udpLocalConnectivityFailed?: boolean; + udpNatConnectivityFailed?: boolean; + udpRelayConnectivityFailed?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + connCheckMessageIntegrityFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + turnAuthUnknownUsernameError?: boolean; + noRelayServersConfigured?: boolean; + multipleRelayServersAttempted?: boolean; + portRangeExhausted?: boolean; + alternateServerReceived?: boolean; + pseudoTLSFailure?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + useCandidateChecksFailed?: boolean; + fipsAllocationFailure?: boolean; +} + +interface MSJitter { + interArrival?: number; + interArrivalMax?: number; + interArrivalSD?: number; +} + +interface MSLocalClientEventBase extends RTCStats { + networkReceiveQualityEventRatio?: number; + networkBandwidthLowEventRatio?: number; +} + +interface MSNetwork extends RTCStats { + jitter?: MSJitter; + delay?: MSDelay; + packetLoss?: MSPacketLoss; + utilization?: MSUtilization; +} + +interface MSNetworkConnectivityInfo { + vpn?: boolean; + linkspeed?: number; + networkConnectionDetails?: string; +} + +interface MSNetworkInterfaceType { + interfaceTypeEthernet?: boolean; + interfaceTypeWireless?: boolean; + interfaceTypePPP?: boolean; + interfaceTypeTunnel?: boolean; + interfaceTypeWWAN?: boolean; +} + +interface MSOutboundNetwork extends MSNetwork { + appliedBandwidthLimit?: number; +} + +interface MSPacketLoss { + lossRate?: number; + lossRateMax?: number; +} + +interface MSPayloadBase extends RTCStats { + payloadDescription?: string; +} + +interface MSRelayAddress { + relayAddress?: string; + port?: number; +} + +interface MSSignatureParameters { + userPrompt?: string; +} + +interface MSTransportDiagnosticsStats extends RTCStats { + baseAddress?: string; + localAddress?: string; + localSite?: string; + networkName?: string; + remoteAddress?: string; + remoteSite?: string; + localMR?: string; + remoteMR?: string; + iceWarningFlags?: MSIceWarningFlags; + portRangeMin?: number; + portRangeMax?: number; + localMRTCPPort?: number; + remoteMRTCPPort?: number; + stunVer?: number; + numConsentReqSent?: number; + numConsentReqReceived?: number; + numConsentRespSent?: number; + numConsentRespReceived?: number; + interfaces?: MSNetworkInterfaceType; + baseInterface?: MSNetworkInterfaceType; + protocol?: string; + localInterface?: MSNetworkInterfaceType; + localAddrType?: string; + remoteAddrType?: string; + iceRole?: string; + rtpRtcpMux?: boolean; + allocationTimeInMs?: number; + msRtcEngineVersion?: string; +} + +interface MSUtilization { + packets?: number; + bandwidthEstimation?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationStdDev?: number; + bandwidthEstimationAvg?: number; +} + +interface MSVideoPayload extends MSPayloadBase { + resoluton?: string; + videoBitRateAvg?: number; + videoBitRateMax?: number; + videoFrameRateAvg?: number; + videoPacketLossRate?: number; + durationSeconds?: number; +} + +interface MSVideoRecvPayload extends MSVideoPayload { + videoFrameLossRate?: number; + recvCodecType?: string; + recvResolutionWidth?: number; + recvResolutionHeight?: number; + videoResolutions?: MSVideoResolutionDistribution; + recvFrameRateAverage?: number; + recvBitRateMaximum?: number; + recvBitRateAverage?: number; + recvVideoStreamsMax?: number; + recvVideoStreamsMin?: number; + recvVideoStreamsMode?: number; + videoPostFECPLR?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; + reorderBufferTotalPackets?: number; + recvReorderBufferReorderedPackets?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvFpsHarmonicAverage?: number; + recvNumResSwitches?: number; +} + +interface MSVideoResolutionDistribution { + cifQuality?: number; + vgaQuality?: number; + h720Quality?: number; + h1080Quality?: number; + h1440Quality?: number; + h2160Quality?: number; +} + +interface MSVideoSendPayload extends MSVideoPayload { + sendFrameRateAverage?: number; + sendBitRateMaximum?: number; + sendBitRateAverage?: number; + sendVideoStreamsMax?: number; + sendResolutionWidth?: number; + sendResolutionHeight?: number; +} + +interface MediaEncryptedEventInit extends EventInit { + initDataType?: string; + initData?: ArrayBuffer; +} + +interface MediaKeyMessageEventInit extends EventInit { + messageType?: string; + message?: ArrayBuffer; +} + +interface MediaKeySystemConfiguration { + initDataTypes?: string[]; + audioCapabilities?: MediaKeySystemMediaCapability[]; + videoCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: string; + persistentState?: string; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + width?: number | LongRange; + height?: number | LongRange; + aspectRatio?: number | DoubleRange; + frameRate?: number | DoubleRange; + facingMode?: string; + volume?: number | DoubleRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + echoCancellation?: boolean[]; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackConstraintSet { + width?: number | ConstrainLongRange; + height?: number | ConstrainLongRange; + aspectRatio?: number | ConstrainDoubleRange; + frameRate?: number | ConstrainDoubleRange; + facingMode?: string | string[] | ConstrainDOMStringParameters; + volume?: number | ConstrainDoubleRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + echoCancelation?: boolean | ConstrainBooleanParameters; + deviceId?: string | string[] | ConstrainDOMStringParameters; + groupId?: string | string[] | ConstrainDOMStringParameters; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackSettings { + width?: number; + height?: number; + aspectRatio?: number; + frameRate?: number; + facingMode?: string; + volume?: number; + sampleRate?: number; + sampleSize?: number; + echoCancellation?: boolean; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackSupportedConstraints { + width?: boolean; + height?: boolean; + aspectRatio?: boolean; + frameRate?: boolean; + facingMode?: boolean; + volume?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + echoCancellation?: boolean; + deviceId?: boolean; + groupId?: boolean; +} + +interface MouseEventInit extends EventModifierInit { + screenX?: number; + screenY?: number; + clientX?: number; + clientY?: number; + button?: number; + buttons?: number; + relatedTarget?: EventTarget; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: string[]; +} + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + pointerId?: number; + width?: number; + height?: number; + pressure?: number; + tiltX?: number; + tiltY?: number; + pointerType?: string; + isPrimary?: boolean; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCDtlsParameters { + role?: string; + fingerprints?: RTCDtlsFingerprint[]; +} + +interface RTCIceCandidate { + foundation?: string; + priority?: number; + ip?: string; + protocol?: string; + port?: number; + type?: string; + tcpType?: string; + relatedAddress?: string; + relatedPort?: number; +} + +interface RTCIceCandidateAttributes extends RTCStats { + ipAddress?: string; + portNumber?: number; + transport?: string; + candidateType?: string; + priority?: number; + addressSourceUrl?: string; +} + +interface RTCIceCandidateComplete { +} + +interface RTCIceCandidatePair { + local?: RTCIceCandidate; + remote?: RTCIceCandidate; +} + +interface RTCIceCandidatePairStats extends RTCStats { + transportId?: string; + localCandidateId?: string; + remoteCandidateId?: string; + state?: string; + priority?: number; + nominated?: boolean; + writable?: boolean; + readable?: boolean; + bytesSent?: number; + bytesReceived?: number; + roundTripTime?: number; + availableOutgoingBitrate?: number; + availableIncomingBitrate?: number; +} + +interface RTCIceGatherOptions { + gatherPolicy?: string; + iceservers?: RTCIceServer[]; +} + +interface RTCIceParameters { + usernameFragment?: string; + password?: string; +} + +interface RTCIceServer { + urls?: any; + username?: string; + credential?: string; +} + +interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { + packetsReceived?: number; + bytesReceived?: number; + packetsLost?: number; + jitter?: number; + fractionLost?: number; +} + +interface RTCMediaStreamTrackStats extends RTCStats { + trackIdentifier?: string; + remoteSource?: boolean; + ssrcIds?: string[]; + frameWidth?: number; + frameHeight?: number; + framesPerSecond?: number; + framesSent?: number; + framesReceived?: number; + framesDecoded?: number; + framesDropped?: number; + framesCorrupted?: number; + audioLevel?: number; + echoReturnLoss?: number; + echoReturnLossEnhancement?: number; +} + +interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { + packetsSent?: number; + bytesSent?: number; + targetBitrate?: number; + roundTripTime?: number; +} + +interface RTCRTPStreamStats extends RTCStats { + ssrc?: string; + associateStatsId?: string; + isRemote?: boolean; + mediaTrackId?: string; + transportId?: string; + codecId?: string; + firCount?: number; + pliCount?: number; + nackCount?: number; + sliCount?: number; +} + +interface RTCRtcpFeedback { + type?: string; + parameter?: string; +} + +interface RTCRtcpParameters { + ssrc?: number; + cname?: string; + reducedSize?: boolean; + mux?: boolean; +} + +interface RTCRtpCapabilities { + codecs?: RTCRtpCodecCapability[]; + headerExtensions?: RTCRtpHeaderExtension[]; + fecMechanisms?: string[]; +} + +interface RTCRtpCodecCapability { + name?: string; + kind?: string; + clockRate?: number; + preferredPayloadType?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; + options?: any; + maxTemporalLayers?: number; + maxSpatialLayers?: number; + svcMultiStreamSupport?: boolean; +} + +interface RTCRtpCodecParameters { + name?: string; + payloadType?: any; + clockRate?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; +} + +interface RTCRtpContributingSource { + timestamp?: number; + csrc?: number; + audioLevel?: number; +} + +interface RTCRtpEncodingParameters { + ssrc?: number; + codecPayloadType?: number; + fec?: RTCRtpFecParameters; + rtx?: RTCRtpRtxParameters; + priority?: number; + maxBitrate?: number; + minQuality?: number; + framerateBias?: number; + resolutionScale?: number; + framerateScale?: number; + active?: boolean; + encodingId?: string; + dependencyEncodingIds?: string[]; + ssrcRange?: RTCSsrcRange; +} + +interface RTCRtpFecParameters { + ssrc?: number; + mechanism?: string; +} + +interface RTCRtpHeaderExtension { + kind?: string; + uri?: string; + preferredId?: number; + preferredEncrypt?: boolean; +} + +interface RTCRtpHeaderExtensionParameters { + uri?: string; + id?: number; + encrypt?: boolean; +} + +interface RTCRtpParameters { + muxId?: string; + codecs?: RTCRtpCodecParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + encodings?: RTCRtpEncodingParameters[]; + rtcp?: RTCRtcpParameters; +} + +interface RTCRtpRtxParameters { + ssrc?: number; +} + +interface RTCRtpUnhandled { + ssrc?: number; + payloadType?: number; + muxId?: string; +} + +interface RTCSrtpKeyParam { + keyMethod?: string; + keySalt?: string; + lifetime?: string; + mkiValue?: number; + mkiLength?: number; +} + +interface RTCSrtpSdesParameters { + tag?: number; + cryptoSuite?: string; + keyParams?: RTCSrtpKeyParam[]; + sessionParams?: string[]; +} + +interface RTCSsrcRange { + min?: number; + max?: number; +} + +interface RTCStats { + timestamp?: number; + type?: string; + id?: string; + msType?: string; +} + +interface RTCStatsReport { +} + +interface RTCTransportStats extends RTCStats { + bytesSent?: number; + bytesReceived?: number; + rtcpTransportStatsId?: string; + activeConnection?: boolean; + selectedCandidatePairId?: string; + localCertificateId?: string; + remoteCertificateId?: string; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface UIEventInit extends EventInit { + view?: Window; + detail?: number; +} + +interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; + alpha?: boolean; + depth?: boolean; + stencil?: boolean; + antialias?: boolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaX?: number; + deltaY?: number; + deltaZ?: number; + deltaMode?: number; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + readonly frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(): AnalyserNode; +} + +interface AnimationEvent extends Event { + readonly animationName: string; + readonly elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": ErrorEvent; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + +interface ApplicationCache extends EventTarget { + oncached: (this: ApplicationCache, ev: Event) => any; + onchecking: (this: ApplicationCache, ev: Event) => any; + ondownloading: (this: ApplicationCache, ev: Event) => any; + onerror: (this: ApplicationCache, ev: ErrorEvent) => any; + onnoupdate: (this: ApplicationCache, ev: Event) => any; + onobsolete: (this: ApplicationCache, ev: Event) => any; + onprogress: (this: ApplicationCache, ev: ProgressEvent) => any; + onupdateready: (this: ApplicationCache, ev: Event) => any; + readonly status: number; + abort(): void; + swapCache(): void; + update(): void; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; +} + +interface AriaRequestEvent extends Event { + readonly attributeName: string; + attributeValue: string | null; +} + +declare var AriaRequestEvent: { + prototype: AriaRequestEvent; + new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; +} + +interface Attr extends Node { + readonly name: string; + readonly ownerElement: Element; + readonly prefix: string | null; + readonly specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +} + +interface AudioBufferSourceNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface AudioBufferSourceNode extends AudioNode { + buffer: AudioBuffer | null; + readonly detune: AudioParam; + loop: boolean; + loopEnd: number; + loopStart: number; + onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + readonly playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(): AudioBufferSourceNode; +} + +interface AudioContext extends EventTarget { + readonly currentTime: number; + readonly destination: AudioDestinationNode; + readonly listener: AudioListener; + readonly sampleRate: number; + state: string; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; +} + +declare var AudioContext: { + prototype: AudioContext; + new(): AudioContext; +} + +interface AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +} + +interface AudioListener { + dopplerFactor: number; + speedOfSound: number; + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +} + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: string; + channelInterpretation: string; + readonly context: AudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + connect(destination: AudioNode, output?: number, input?: number): void; + disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +} + +interface AudioParam { + readonly defaultValue: number; + value: number; + cancelScheduledValues(startTime: number): void; + exponentialRampToValueAtTime(value: number, endTime: number): void; + linearRampToValueAtTime(value: number, endTime: number): void; + setTargetAtTime(target: number, startTime: number, timeConstant: number): void; + setValueAtTime(value: number, startTime: number): void; + setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +} + +interface AudioProcessingEvent extends Event { + readonly inputBuffer: AudioBuffer; + readonly outputBuffer: AudioBuffer; + readonly playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(): AudioProcessingEvent; +} + +interface AudioTrack { + enabled: boolean; + readonly id: string; + kind: string; + readonly label: string; + language: string; + readonly sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface AudioTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: AudioTrackList, ev: TrackEvent) => any; + onchange: (this: AudioTrackList, ev: Event) => any; + onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack | null; + item(index: number): AudioTrack; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface BarProp { + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +} + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; + readonly detune: AudioParam; + readonly frequency: AudioParam; + readonly gain: AudioParam; + type: string; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(): BiquadFilterNode; +} + +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface CSS { + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +} + +interface CSSFontFaceRule extends CSSRule { + readonly style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface CSSGroupingRule extends CSSRule { + readonly cssRules: CSSRuleList; + deleteRule(index: number): void; + insertRule(rule: string, index: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +} + +interface CSSImportRule extends CSSRule { + readonly href: string; + readonly media: MediaList; + readonly styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSKeyframesRule extends CSSRule { + readonly cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(rule: string): void; + findRule(rule: string): CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface CSSMediaRule extends CSSConditionRule { + readonly media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface CSSNamespaceRule extends CSSRule { + readonly namespaceURI: string; + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface CSSPageRule extends CSSRule { + readonly pseudoClass: string; + readonly selector: string; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface CSSRule { + cssText: string; + readonly parentRule: CSSRule; + readonly parentStyleSheet: CSSStyleSheet; + readonly type: number; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +interface CSSRuleList { + readonly length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface CSSStyleDeclaration { + alignContent: string | null; + alignItems: string | null; + alignSelf: string | null; + alignmentBaseline: string | null; + animation: string | null; + animationDelay: string | null; + animationDirection: string | null; + animationDuration: string | null; + animationFillMode: string | null; + animationIterationCount: string | null; + animationName: string | null; + animationPlayState: string | null; + animationTimingFunction: string | null; + backfaceVisibility: string | null; + background: string | null; + backgroundAttachment: string | null; + backgroundClip: string | null; + backgroundColor: string | null; + backgroundImage: string | null; + backgroundOrigin: string | null; + backgroundPosition: string | null; + backgroundPositionX: string | null; + backgroundPositionY: string | null; + backgroundRepeat: string | null; + backgroundSize: string | null; + baselineShift: string | null; + border: string | null; + borderBottom: string | null; + borderBottomColor: string | null; + borderBottomLeftRadius: string | null; + borderBottomRightRadius: string | null; + borderBottomStyle: string | null; + borderBottomWidth: string | null; + borderCollapse: string | null; + borderColor: string | null; + borderImage: string | null; + borderImageOutset: string | null; + borderImageRepeat: string | null; + borderImageSlice: string | null; + borderImageSource: string | null; + borderImageWidth: string | null; + borderLeft: string | null; + borderLeftColor: string | null; + borderLeftStyle: string | null; + borderLeftWidth: string | null; + borderRadius: string | null; + borderRight: string | null; + borderRightColor: string | null; + borderRightStyle: string | null; + borderRightWidth: string | null; + borderSpacing: string | null; + borderStyle: string | null; + borderTop: string | null; + borderTopColor: string | null; + borderTopLeftRadius: string | null; + borderTopRightRadius: string | null; + borderTopStyle: string | null; + borderTopWidth: string | null; + borderWidth: string | null; + bottom: string | null; + boxShadow: string | null; + boxSizing: string | null; + breakAfter: string | null; + breakBefore: string | null; + breakInside: string | null; + captionSide: string | null; + clear: string | null; + clip: string | null; + clipPath: string | null; + clipRule: string | null; + color: string | null; + colorInterpolationFilters: string | null; + columnCount: any; + columnFill: string | null; + columnGap: any; + columnRule: string | null; + columnRuleColor: any; + columnRuleStyle: string | null; + columnRuleWidth: any; + columnSpan: string | null; + columnWidth: any; + columns: string | null; + content: string | null; + counterIncrement: string | null; + counterReset: string | null; + cssFloat: string | null; + cssText: string; + cursor: string | null; + direction: string | null; + display: string | null; + dominantBaseline: string | null; + emptyCells: string | null; + enableBackground: string | null; + fill: string | null; + fillOpacity: string | null; + fillRule: string | null; + filter: string | null; + flex: string | null; + flexBasis: string | null; + flexDirection: string | null; + flexFlow: string | null; + flexGrow: string | null; + flexShrink: string | null; + flexWrap: string | null; + floodColor: string | null; + floodOpacity: string | null; + font: string | null; + fontFamily: string | null; + fontFeatureSettings: string | null; + fontSize: string | null; + fontSizeAdjust: string | null; + fontStretch: string | null; + fontStyle: string | null; + fontVariant: string | null; + fontWeight: string | null; + glyphOrientationHorizontal: string | null; + glyphOrientationVertical: string | null; + height: string | null; + imeMode: string | null; + justifyContent: string | null; + kerning: string | null; + left: string | null; + readonly length: number; + letterSpacing: string | null; + lightingColor: string | null; + lineHeight: string | null; + listStyle: string | null; + listStyleImage: string | null; + listStylePosition: string | null; + listStyleType: string | null; + margin: string | null; + marginBottom: string | null; + marginLeft: string | null; + marginRight: string | null; + marginTop: string | null; + marker: string | null; + markerEnd: string | null; + markerMid: string | null; + markerStart: string | null; + mask: string | null; + maxHeight: string | null; + maxWidth: string | null; + minHeight: string | null; + minWidth: string | null; + msContentZoomChaining: string | null; + msContentZoomLimit: string | null; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string | null; + msContentZoomSnapPoints: string | null; + msContentZoomSnapType: string | null; + msContentZooming: string | null; + msFlowFrom: string | null; + msFlowInto: string | null; + msFontFeatureSettings: string | null; + msGridColumn: any; + msGridColumnAlign: string | null; + msGridColumnSpan: any; + msGridColumns: string | null; + msGridRow: any; + msGridRowAlign: string | null; + msGridRowSpan: any; + msGridRows: string | null; + msHighContrastAdjust: string | null; + msHyphenateLimitChars: string | null; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string | null; + msImeAlign: string | null; + msOverflowStyle: string | null; + msScrollChaining: string | null; + msScrollLimit: string | null; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string | null; + msScrollSnapPointsX: string | null; + msScrollSnapPointsY: string | null; + msScrollSnapType: string | null; + msScrollSnapX: string | null; + msScrollSnapY: string | null; + msScrollTranslation: string | null; + msTextCombineHorizontal: string | null; + msTextSizeAdjust: any; + msTouchAction: string | null; + msTouchSelect: string | null; + msUserSelect: string | null; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + opacity: string | null; + order: string | null; + orphans: string | null; + outline: string | null; + outlineColor: string | null; + outlineStyle: string | null; + outlineWidth: string | null; + overflow: string | null; + overflowX: string | null; + overflowY: string | null; + padding: string | null; + paddingBottom: string | null; + paddingLeft: string | null; + paddingRight: string | null; + paddingTop: string | null; + pageBreakAfter: string | null; + pageBreakBefore: string | null; + pageBreakInside: string | null; + readonly parentRule: CSSRule; + perspective: string | null; + perspectiveOrigin: string | null; + pointerEvents: string | null; + position: string | null; + quotes: string | null; + right: string | null; + rubyAlign: string | null; + rubyOverhang: string | null; + rubyPosition: string | null; + stopColor: string | null; + stopOpacity: string | null; + stroke: string | null; + strokeDasharray: string | null; + strokeDashoffset: string | null; + strokeLinecap: string | null; + strokeLinejoin: string | null; + strokeMiterlimit: string | null; + strokeOpacity: string | null; + strokeWidth: string | null; + tableLayout: string | null; + textAlign: string | null; + textAlignLast: string | null; + textAnchor: string | null; + textDecoration: string | null; + textIndent: string | null; + textJustify: string | null; + textKashida: string | null; + textKashidaSpace: string | null; + textOverflow: string | null; + textShadow: string | null; + textTransform: string | null; + textUnderlinePosition: string | null; + top: string | null; + touchAction: string | null; + transform: string | null; + transformOrigin: string | null; + transformStyle: string | null; + transition: string | null; + transitionDelay: string | null; + transitionDuration: string | null; + transitionProperty: string | null; + transitionTimingFunction: string | null; + unicodeBidi: string | null; + verticalAlign: string | null; + visibility: string | null; + webkitAlignContent: string | null; + webkitAlignItems: string | null; + webkitAlignSelf: string | null; + webkitAnimation: string | null; + webkitAnimationDelay: string | null; + webkitAnimationDirection: string | null; + webkitAnimationDuration: string | null; + webkitAnimationFillMode: string | null; + webkitAnimationIterationCount: string | null; + webkitAnimationName: string | null; + webkitAnimationPlayState: string | null; + webkitAnimationTimingFunction: string | null; + webkitAppearance: string | null; + webkitBackfaceVisibility: string | null; + webkitBackgroundClip: string | null; + webkitBackgroundOrigin: string | null; + webkitBackgroundSize: string | null; + webkitBorderBottomLeftRadius: string | null; + webkitBorderBottomRightRadius: string | null; + webkitBorderImage: string | null; + webkitBorderRadius: string | null; + webkitBorderTopLeftRadius: string | null; + webkitBorderTopRightRadius: string | null; + webkitBoxAlign: string | null; + webkitBoxDirection: string | null; + webkitBoxFlex: string | null; + webkitBoxOrdinalGroup: string | null; + webkitBoxOrient: string | null; + webkitBoxPack: string | null; + webkitBoxSizing: string | null; + webkitColumnBreakAfter: string | null; + webkitColumnBreakBefore: string | null; + webkitColumnBreakInside: string | null; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string | null; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string | null; + webkitColumnRuleWidth: any; + webkitColumnSpan: string | null; + webkitColumnWidth: any; + webkitColumns: string | null; + webkitFilter: string | null; + webkitFlex: string | null; + webkitFlexBasis: string | null; + webkitFlexDirection: string | null; + webkitFlexFlow: string | null; + webkitFlexGrow: string | null; + webkitFlexShrink: string | null; + webkitFlexWrap: string | null; + webkitJustifyContent: string | null; + webkitOrder: string | null; + webkitPerspective: string | null; + webkitPerspectiveOrigin: string | null; + webkitTapHighlightColor: string | null; + webkitTextFillColor: string | null; + webkitTextSizeAdjust: any; + webkitTransform: string | null; + webkitTransformOrigin: string | null; + webkitTransformStyle: string | null; + webkitTransition: string | null; + webkitTransitionDelay: string | null; + webkitTransitionDuration: string | null; + webkitTransitionProperty: string | null; + webkitTransitionTimingFunction: string | null; + webkitUserModify: string | null; + webkitUserSelect: string | null; + webkitWritingMode: string | null; + whiteSpace: string | null; + widows: string | null; + width: string | null; + wordBreak: string | null; + wordSpacing: string | null; + wordWrap: string | null; + writingMode: string | null; + zIndex: string | null; + zoom: string | null; + resize: string | null; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string | null, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface CSSStyleRule extends CSSRule { + readonly readOnly: boolean; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface CSSStyleSheet extends StyleSheet { + readonly cssRules: CSSRuleList; + cssText: string; + readonly href: string; + readonly id: string; + readonly imports: StyleSheetList; + readonly isAlternate: boolean; + readonly isPrefAlternate: boolean; + readonly ownerRule: CSSRule; + readonly owningElement: Element; + readonly pages: StyleSheetPageList; + readonly readOnly: boolean; + readonly rules: CSSRuleList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: string; + msImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + fill(fillRule?: string): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +} + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +} + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface CommandEvent extends Event { + readonly commandName: string; + readonly detail: string | null; +} + +declare var CommandEvent: { + prototype: CommandEvent; + new(type: string, eventInitDict?: CommandEventInit): CommandEvent; +} + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +} + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: string, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string): void; + groupCollapsed(groupTitle?: string): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +} + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +} + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +} + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +} + +interface CustomEvent extends Event { + readonly detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +} + +interface DOMError { + readonly name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; + createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface DOMStringMap { + [name: string]: string; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +} + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +} + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + readonly files: FileList; + readonly items: DataTransferItemList; + readonly types: string[]; + clearData(format?: string): boolean; + getData(format: string): string; + setData(format: string, data: string): boolean; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface DataTransferItem { + readonly kind: string; + readonly type: string; + getAsFile(): File | null; + getAsString(_callback: FunctionStringCallback | null): void; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +} + +interface DataTransferItemList { + readonly length: number; + add(data: File): DataTransferItem | null; + clear(): void; + item(index: number): DataTransferItem; + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +} + +interface DeferredPermissionRequest { + readonly id: number; + readonly type: string; + readonly uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +} + +interface DelayNode extends AudioNode { + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(): DelayNode; +} + +interface DeviceAcceleration { + readonly x: number | null; + readonly y: number | null; + readonly z: number | null; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +} + +interface DeviceLightEvent extends Event { + readonly value: number; +} + +declare var DeviceLightEvent: { + prototype: DeviceLightEvent; + new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; +} + +interface DeviceMotionEvent extends Event { + readonly acceleration: DeviceAcceleration | null; + readonly accelerationIncludingGravity: DeviceAcceleration | null; + readonly interval: number | null; + readonly rotationRate: DeviceRotationRate | null; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(): DeviceMotionEvent; +} + +interface DeviceOrientationEvent extends Event { + readonly absolute: boolean; + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(): DeviceOrientationEvent; +} + +interface DeviceRotationRate { + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +} + +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforedeactivate": UIEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "fullscreenchange": Event; + "fullscreenerror": Event; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "mssitemodejumplistitemremoved": MSSiteModeEvent; + "msthumbnailclick": MSSiteModeEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectionchange": Event; + "selectstart": Event; + "stalled": Event; + "stop": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "volumechange": Event; + "waiting": Event; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; + /** + * Gets the object that has the focus when the parent document has focus. + */ + readonly activeElement: Element; + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollectionOf; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + readonly compatMode: string; + cookie: string; + readonly currentScript: HTMLScriptElement | SVGScriptElement; + /** + * Gets the default character set from the current regional language settings. + */ + readonly defaultCharset: string; + readonly defaultView: Window; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * 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. + */ + readonly doctype: DocumentType; + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollectionOf; + readonly fullscreenElement: Element | null; + readonly fullscreenEnabled: boolean; + readonly head: HTMLHeadElement; + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + readonly inputEncoding: string | null; + /** + * 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. + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollectionOf; + /** + * Contains information about the current URL. + */ + readonly location: Location; + msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (this: Document, ev: FocusEvent) => any; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (this: Document, ev: Event) => any; + oncanplaythrough: (this: Document, ev: Event) => any; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (this: Document, ev: PointerEvent) => any; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (this: Document, 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: (this: Document, 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. + */ + ondragleave: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (this: Document, ev: DragEvent) => any; + ondrop: (this: Document, ev: DragEvent) => any; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (this: Document, ev: Event) => any; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (this: Document, ev: Event) => any; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (this: Document, ev: MediaStreamErrorEvent) => any; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (this: Document, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (this: Document, ev: FocusEvent) => any; + onfullscreenchange: (this: Document, ev: Event) => any; + onfullscreenerror: (this: Document, ev: Event) => any; + oninput: (this: Document, ev: Event) => any; + oninvalid: (this: Document, ev: Event) => any; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (this: Document, ev: Event) => any; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (this: Document, ev: Event) => any; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (this: Document, ev: Event) => any; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (this: Document, ev: WheelEvent) => any; + onmscontentzoom: (this: Document, ev: UIEvent) => any; + onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Document, ev: MSGestureEvent) => any; + onmsgestureend: (this: Document, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Document, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Document, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Document, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Document, ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (this: Document, ev: MSManipulationEvent) => any; + onmspointercancel: (this: Document, ev: MSPointerEvent) => any; + onmspointerdown: (this: Document, ev: MSPointerEvent) => any; + onmspointerenter: (this: Document, ev: MSPointerEvent) => any; + onmspointerleave: (this: Document, ev: MSPointerEvent) => any; + onmspointermove: (this: Document, ev: MSPointerEvent) => any; + onmspointerout: (this: Document, ev: MSPointerEvent) => any; + onmspointerover: (this: Document, ev: MSPointerEvent) => any; + onmspointerup: (this: Document, ev: MSPointerEvent) => any; + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (this: Document, ev: Event) => any; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (this: Document, ev: Event) => any; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (this: Document, ev: Event) => any; + onpointerlockchange: (this: Document, ev: Event) => any; + onpointerlockerror: (this: Document, ev: Event) => any; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (this: Document, ev: ProgressEvent) => any; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (this: Document, ev: Event) => any; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (this: Document, ev: ProgressEvent) => any; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (this: Document, ev: Event) => any; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (this: Document, ev: UIEvent) => any; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (this: Document, ev: Event) => any; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (this: Document, ev: Event) => any; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (this: Document, ev: UIEvent) => any; + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (this: Document, ev: Event) => any; + onselectstart: (this: Document, ev: Event) => any; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (this: Document, ev: Event) => any; + onsubmit: (this: Document, ev: Event) => any; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (this: Document, ev: Event) => any; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (this: Document, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (this: Document, ev: Event) => any; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (this: Document, ev: Event) => any; + onwebkitfullscreenchange: (this: Document, ev: Event) => any; + onwebkitfullscreenerror: (this: Document, ev: Event) => any; + plugins: HTMLCollectionOf; + readonly pointerLockElement: Element; + /** + * Retrieves a value that indicates the current state of the object. + */ + readonly readyState: string; + /** + * Gets the URL of the location that referred the user to the current page. + */ + readonly referrer: string; + /** + * Gets the root svg element in the document hierarchy. + */ + readonly rootElement: SVGSVGElement; + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + readonly styleSheets: StyleSheetList; + /** + * Contains the title of the document. + */ + title: string; + readonly visibilityState: string; + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + readonly webkitCurrentFullScreenElement: Element | null; + readonly webkitFullscreenElement: Element | null; + readonly webkitFullscreenEnabled: boolean; + readonly webkitIsFullScreen: boolean; + readonly xmlEncoding: string | null; + xmlStandalone: boolean; + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string | null; + adoptNode(source: Node): Node; + captureEvents(): void; + caretRangeFromPoint(x: number, y: number): Range; + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: K): HTMLElementTagNameMap[K]; + createElement(tagName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: string | null, qualifiedName: string): Element; + 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. + * @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. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + 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. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker 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. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + exitFullscreen(): void; + exitPointerLock(): void; + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + /** + * 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 | null; + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: Node, deep: boolean): Node; + msElementsFromPoint(x: number, y: number): NodeListOf; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @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. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + 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. + */ + queryCommandText(commandId: string): string; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + releaseEvents(): void; + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + webkitCancelFullScreen(): void; + webkitExitFullscreen(): void; + /** + * 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. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +} + +interface DocumentFragment extends Node, NodeSelector, ParentNode { +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DocumentType extends Node, ChildNode { + readonly entities: NamedNodeMap; + readonly internalSubset: string | null; + readonly name: string; + readonly notations: NamedNodeMap; + readonly publicId: string | null; + readonly systemId: string | null; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface DragEvent extends MouseEvent { + readonly dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DynamicsCompressorNode extends AudioNode { + readonly attack: AudioParam; + readonly knee: AudioParam; + readonly ratio: AudioParam; + readonly reduction: AudioParam; + readonly release: AudioParam; + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(): DynamicsCompressorNode; +} + +interface EXT_frag_depth { +} + +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": AriaRequestEvent; + "command": CommandEvent; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSGotPointerCapture": MSPointerEvent; + "MSInertiaStart": MSGestureEvent; + "MSLostPointerCapture": MSPointerEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { + readonly classList: DOMTokenList; + className: string; + readonly clientHeight: number; + readonly clientLeft: number; + readonly clientTop: number; + readonly clientWidth: number; + id: string; + msContentZoomFactor: number; + readonly msRegionOverflow: string; + onariarequest: (this: Element, ev: AriaRequestEvent) => any; + oncommand: (this: Element, ev: CommandEvent) => any; + ongotpointercapture: (this: Element, ev: PointerEvent) => any; + onlostpointercapture: (this: Element, ev: PointerEvent) => any; + onmsgesturechange: (this: Element, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Element, ev: MSGestureEvent) => any; + onmsgestureend: (this: Element, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Element, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Element, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Element, ev: MSGestureEvent) => any; + onmsgotpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmsinertiastart: (this: Element, ev: MSGestureEvent) => any; + onmslostpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmspointercancel: (this: Element, ev: MSPointerEvent) => any; + onmspointerdown: (this: Element, ev: MSPointerEvent) => any; + onmspointerenter: (this: Element, ev: MSPointerEvent) => any; + onmspointerleave: (this: Element, ev: MSPointerEvent) => any; + onmspointermove: (this: Element, ev: MSPointerEvent) => any; + onmspointerout: (this: Element, ev: MSPointerEvent) => any; + onmspointerover: (this: Element, ev: MSPointerEvent) => any; + onmspointerup: (this: Element, ev: MSPointerEvent) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onwebkitfullscreenchange: (this: Element, ev: Event) => any; + onwebkitfullscreenerror: (this: Element, ev: Event) => any; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly tagName: string; + innerHTML: string; + readonly assignedSlot: HTMLSlotElement | null; + slot: string; + readonly shadowRoot: ShadowRoot | null; + getAttribute(name: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; + msZoomTo(args: MsZoomToOptions): void; + releasePointerCapture(pointerId: number): void; + removeAttribute(name?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + setAttribute(name: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): void; + getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget; + readonly timeStamp: number; + readonly type: string; + readonly scoped: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + deepPath(): EventTarget[]; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +interface EventTarget { + addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +} + +interface External { +} + +declare var External: { + prototype: External; + new(): External; +} + +interface File extends Blob { + readonly lastModifiedDate: any; + readonly name: string; + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +} + +interface FileList { + readonly length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface FileReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +} + +interface FocusEvent extends UIEvent { + readonly relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} + +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface GainNode extends AudioNode { + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(): GainNode; +} + +interface Gamepad { + readonly axes: number[]; + readonly buttons: GamepadButton[]; + readonly connected: boolean; + readonly id: string; + readonly index: number; + readonly mapping: string; + readonly timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +} + +interface GamepadButton { + readonly pressed: boolean; + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +} + +interface GamepadEvent extends Event { + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(): GamepadEvent; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +} + +interface HTMLAnchorElement extends HTMLElement { + Methods: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + readonly mimeType: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + readonly nameProp: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + readonly protocolLong: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: 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; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface HTMLAppletElement extends HTMLElement { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + object: string | null; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + vspace: number; + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + rel: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns a string representation of an object. + */ + toString(): string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Adds an element to the areas, controlRange, or options collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Removes an element from the collection. + */ + remove(index?: number): void; +} + +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface HTMLBodyElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLBodyElement extends HTMLElement { + aLink: any; + background: string; + bgColor: any; + bgProperties: string; + link: any; + noWrap: boolean; + onafterprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; + onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; + onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; + onload: (this: HTMLBodyElement, ev: Event) => any; + onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; + onoffline: (this: HTMLBodyElement, ev: Event) => any; + ononline: (this: HTMLBodyElement, ev: Event) => any; + onorientationchange: (this: HTMLBodyElement, ev: Event) => any; + onpagehide: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; + onresize: (this: HTMLBodyElement, ev: UIEvent) => any; + onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; + onunload: (this: HTMLBodyElement, ev: Event) => any; + text: any; + vLink: any; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + status: any; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * 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; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * 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", 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. + */ + msToBlob(): Blob; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLCollection { + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Retrieves an object from various collections. + */ + item(index: number): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [index: number]: Element; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface HTMLDirectoryElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +} + +interface HTMLElementEventMap extends ElementEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforecopy": ClipboardEvent; + "beforecut": ClipboardEvent; + "beforedeactivate": UIEvent; + "beforepaste": ClipboardEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectstart": Event; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "volumechange": Event; + "waiting": Event; +} + +interface HTMLElement extends Element { + accessKey: string; + readonly children: HTMLCollection; + contentEditable: string; + readonly dataset: DOMStringMap; + dir: string; + draggable: boolean; + hidden: boolean; + hideFocus: boolean; + innerHTML: string; + innerText: string; + readonly isContentEditable: boolean; + lang: string; + readonly offsetHeight: number; + readonly offsetLeft: number; + readonly offsetParent: Element; + readonly offsetTop: number; + readonly offsetWidth: number; + onabort: (this: HTMLElement, ev: UIEvent) => any; + onactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforecopy: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforecut: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforedeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforepaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onblur: (this: HTMLElement, ev: FocusEvent) => any; + oncanplay: (this: HTMLElement, ev: Event) => any; + oncanplaythrough: (this: HTMLElement, ev: Event) => any; + onchange: (this: HTMLElement, ev: Event) => any; + onclick: (this: HTMLElement, ev: MouseEvent) => any; + oncontextmenu: (this: HTMLElement, ev: PointerEvent) => any; + oncopy: (this: HTMLElement, ev: ClipboardEvent) => any; + oncuechange: (this: HTMLElement, ev: Event) => any; + oncut: (this: HTMLElement, ev: ClipboardEvent) => any; + ondblclick: (this: HTMLElement, ev: MouseEvent) => any; + ondeactivate: (this: HTMLElement, ev: UIEvent) => any; + ondrag: (this: HTMLElement, ev: DragEvent) => any; + ondragend: (this: HTMLElement, ev: DragEvent) => any; + ondragenter: (this: HTMLElement, ev: DragEvent) => any; + ondragleave: (this: HTMLElement, ev: DragEvent) => any; + ondragover: (this: HTMLElement, ev: DragEvent) => any; + ondragstart: (this: HTMLElement, ev: DragEvent) => any; + ondrop: (this: HTMLElement, ev: DragEvent) => any; + ondurationchange: (this: HTMLElement, ev: Event) => any; + onemptied: (this: HTMLElement, ev: Event) => any; + onended: (this: HTMLElement, ev: MediaStreamErrorEvent) => any; + onerror: (this: HTMLElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLElement, ev: FocusEvent) => any; + oninput: (this: HTMLElement, ev: Event) => any; + oninvalid: (this: HTMLElement, ev: Event) => any; + onkeydown: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeypress: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeyup: (this: HTMLElement, ev: KeyboardEvent) => any; + onload: (this: HTMLElement, ev: Event) => any; + onloadeddata: (this: HTMLElement, ev: Event) => any; + onloadedmetadata: (this: HTMLElement, ev: Event) => any; + onloadstart: (this: HTMLElement, ev: Event) => any; + onmousedown: (this: HTMLElement, ev: MouseEvent) => any; + onmouseenter: (this: HTMLElement, ev: MouseEvent) => any; + onmouseleave: (this: HTMLElement, ev: MouseEvent) => any; + onmousemove: (this: HTMLElement, ev: MouseEvent) => any; + onmouseout: (this: HTMLElement, ev: MouseEvent) => any; + onmouseover: (this: HTMLElement, ev: MouseEvent) => any; + onmouseup: (this: HTMLElement, ev: MouseEvent) => any; + onmousewheel: (this: HTMLElement, ev: WheelEvent) => any; + onmscontentzoom: (this: HTMLElement, ev: UIEvent) => any; + onmsmanipulationstatechanged: (this: HTMLElement, ev: MSManipulationEvent) => any; + onpaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onpause: (this: HTMLElement, ev: Event) => any; + onplay: (this: HTMLElement, ev: Event) => any; + onplaying: (this: HTMLElement, ev: Event) => any; + onprogress: (this: HTMLElement, ev: ProgressEvent) => any; + onratechange: (this: HTMLElement, ev: Event) => any; + onreset: (this: HTMLElement, ev: Event) => any; + onscroll: (this: HTMLElement, ev: UIEvent) => any; + onseeked: (this: HTMLElement, ev: Event) => any; + onseeking: (this: HTMLElement, ev: Event) => any; + onselect: (this: HTMLElement, ev: UIEvent) => any; + onselectstart: (this: HTMLElement, ev: Event) => any; + onstalled: (this: HTMLElement, ev: Event) => any; + onsubmit: (this: HTMLElement, ev: Event) => any; + onsuspend: (this: HTMLElement, ev: Event) => any; + ontimeupdate: (this: HTMLElement, ev: Event) => any; + onvolumechange: (this: HTMLElement, ev: Event) => any; + onwaiting: (this: HTMLElement, ev: Event) => any; + outerHTML: string; + outerText: string; + spellcheck: boolean; + readonly style: CSSStyleDeclaration; + tabIndex: number; + title: string; + blur(): void; + click(): void; + dragDrop(): boolean; + focus(): void; + msGetInputContext(): MSInputMethodContext; + setActive(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + readonly palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + readonly pluginspage: string; + readonly readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + readonly elements: HTMLCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(name: string): any; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface HTMLFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument { + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string | number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLFrameElement, ev: Event) => any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the width of the object. + */ + width: string | number; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLFrameSetElement extends HTMLElement { + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + name: string; + onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; + /** + * Fires when the object loses the input focus. + */ + onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + */ + onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; + onload: (this: HTMLFrameSetElement, ev: Event) => any; + onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; + onoffline: (this: HTMLFrameSetElement, ev: Event) => any; + ononline: (this: HTMLFrameSetElement, ev: Event) => any; + onorientationchange: (this: HTMLFrameSetElement, ev: Event) => any; + onpagehide: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; + onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; + onunload: (this: HTMLFrameSetElement, ev: Event) => any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface HTMLIFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + allowFullscreen: boolean; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLIFrameElement, ev: Event) => any; + readonly sandbox: DOMSettableTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + crossOrigin: string; + readonly currentSrc: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + lowsrc: string; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * The original height of the image resource before sizing. + */ + readonly naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + readonly naturalWidth: number; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + readonly x: number; + readonly y: number; + msGetAsCastingSource(): any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; + create(): HTMLImageElement; +} + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + readonly files: FileList | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + indeterminate: boolean; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + readonly list: HTMLElement; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + selectionDirection: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + status: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: Date; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + webkitdirectory: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start?: number, end?: number, direction?: string): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface HTMLLabelElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface HTMLLegendElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + import?: Document; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + readonly areas: HTMLAreasCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + +interface HTMLMarqueeElement extends HTMLElement { + behavior: string; + bgColor: any; + direction: string; + height: string; + hspace: number; + loop: number; + onbounce: (this: HTMLMarqueeElement, ev: Event) => any; + onfinish: (this: HTMLMarqueeElement, ev: Event) => any; + onstart: (this: HTMLMarqueeElement, ev: Event) => any; + scrollAmount: number; + scrollDelay: number; + trueSpeed: boolean; + vspace: number; + width: string; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": MSMediaKeyNeededEvent; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + readonly audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + readonly buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + crossOrigin: string; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + readonly currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + readonly duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + readonly ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + readonly error: MediaError; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + readonly mediaKeys: MediaKeys | null; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + readonly msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + readonly msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + readonly networkState: number; + onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; + onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + /** + * Gets a flag that specifies whether playback is paused. + */ + readonly paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + readonly played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + readonly seekable: TimeRanges; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + readonly seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcObject: MediaStream | null; + readonly textTracks: TextTrackList; + readonly videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): string; + /** + * Resets the audio or video object and loads a new media resource. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; +} + +interface HTMLMenuElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface HTMLMeterElement extends HTMLElement { + high: number; + low: number; + max: number; + min: number; + optimum: number; + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMeterElement: { + prototype: HTMLMeterElement; + new(): HTMLMeterElement; +} + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface HTMLOListElement extends HTMLElement { + compact: boolean; + /** + * The starting number. + */ + start: number; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the contained object. + */ + readonly object: any; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface HTMLOptGroupElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + readonly text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; + create(): HTMLOptionElement; +} + +interface HTMLOptionsCollection extends HTMLCollectionOf { + length: number; + selectedIndex: number; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + remove(index: number): void; +} + +declare var HTMLOptionsCollection: { + prototype: HTMLOptionsCollection; + new(): HTMLOptionsCollection; +} + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + +interface HTMLPreElement extends HTMLElement { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + readonly position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * 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; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface HTMLSelectElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly options: HTMLOptionsCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + selectedOptions: HTMLCollectionOf; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * 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. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + msKeySystem: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + disabled: boolean; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + bgColor: any; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + readonly cellIndex: number; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** + * Sets or retrieves the width of the object. + */ + width: any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement { +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + bgColor: any; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollectionOf; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + bgColor: any; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollectionOf; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + readonly rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + readonly sectionRowIndex: number; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface HTMLTemplateElement extends HTMLElement { + readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLTextAreaElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves the type of control. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readonly readyState: number; + src: string; + srclang: string; + readonly track: TextTrack; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; +} + +interface HTMLUListElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + readonly msIsLayoutOptimalForPlayback: boolean; + readonly msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoWidth: number; + readonly webkitDisplayingFullscreen: boolean; + readonly webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullScreen(): void; + webkitEnterFullscreen(): void; + webkitExitFullScreen(): void; + webkitExitFullscreen(): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +} + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +} + +interface IDBCursor { + readonly direction: string; + key: IDBKeyRange | IDBValidKey; + readonly primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: IDBKeyRange | IDBValidKey): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +interface IDBCursorWithValue extends IDBCursor { + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + +interface IDBDatabase extends EventTarget { + readonly name: string; + readonly objectStoreNames: DOMStringList; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; + version: number; + onversionchange: (ev: IDBVersionChangeEvent) => any; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; + addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface IDBIndex { + keyPath: string | string[]; + readonly name: string; + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + multiEntry: boolean; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + get(key: IDBKeyRange | IDBValidKey): IDBRequest; + getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface IDBKeyRange { + readonly lower: any; + readonly lowerOpen: boolean; + readonly upper: any; + readonly upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(lower: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(upper: any, open?: boolean): IDBKeyRange; +} + +interface IDBObjectStore { + readonly indexNames: DOMStringList; + keyPath: string | string[]; + readonly name: string; + readonly transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + clear(): IDBRequest; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + +interface IDBRequest extends EventTarget { + readonly error: DOMError; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; + readonly readyState: string; + readonly result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + readonly transaction: IDBTransaction; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + +interface IDBTransaction extends EventTarget { + readonly db: IDBDatabase; + readonly error: DOMError; + readonly mode: string; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; +} + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface ImageData { + data: Uint8ClampedArray; + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +} + +interface KeyboardEvent extends UIEvent { + readonly altKey: boolean; + readonly char: string | null; + readonly charCode: number; + readonly ctrlKey: boolean; + readonly key: string; + readonly keyCode: number; + readonly locale: string; + readonly location: number; + readonly metaKey: boolean; + readonly repeat: boolean; + readonly shiftKey: boolean; + readonly which: number; + readonly code: string; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +interface ListeningStateChangedEvent extends Event { + readonly label: string; + readonly state: string; +} + +declare var ListeningStateChangedEvent: { + prototype: ListeningStateChangedEvent; + new(): ListeningStateChangedEvent; +} + +interface Location { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + assign(url: string): void; + reload(forcedReload?: boolean): void; + replace(url: string): void; + toString(): string; +} + +declare var Location: { + prototype: Location; + new(): Location; +} + +interface LongRunningScriptDetectedEvent extends Event { + readonly executionTime: number; + stopPageScriptExecution: boolean; +} + +declare var LongRunningScriptDetectedEvent: { + prototype: LongRunningScriptDetectedEvent; + new(): LongRunningScriptDetectedEvent; +} + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + readonly CURRENT: string; + readonly HIGH: string; + readonly IDLE: string; + readonly NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSAppAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; +} + +interface MSAssertion { + readonly id: string; + readonly type: string; +} + +declare var MSAssertion: { + prototype: MSAssertion; + new(): MSAssertion; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +} + +interface MSCredentials { + getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; + makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; +} + +declare var MSCredentials: { + prototype: MSCredentials; + new(): MSCredentials; +} + +interface MSFIDOCredentialAssertion extends MSAssertion { + readonly algorithm: string | Algorithm; + readonly attestation: any; + readonly publicKey: string; + readonly transportHints: string[]; +} + +declare var MSFIDOCredentialAssertion: { + prototype: MSFIDOCredentialAssertion; + new(): MSFIDOCredentialAssertion; +} + +interface MSFIDOSignature { + readonly authnrData: string; + readonly clientData: string; + readonly signature: string; +} + +declare var MSFIDOSignature: { + prototype: MSFIDOSignature; + new(): MSFIDOSignature; +} + +interface MSFIDOSignatureAssertion extends MSAssertion { + readonly signature: MSFIDOSignature; +} + +declare var MSFIDOSignatureAssertion: { + prototype: MSFIDOSignatureAssertion; + new(): MSFIDOSignatureAssertion; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +} + +interface MSGestureEvent extends UIEvent { + readonly clientX: number; + readonly clientY: number; + readonly expansion: number; + readonly gestureObject: any; + readonly hwTimestamp: number; + readonly offsetX: number; + readonly offsetY: number; + readonly rotation: number; + readonly scale: number; + readonly screenX: number; + readonly screenY: number; + readonly translationX: number; + readonly translationY: number; + readonly velocityAngular: number; + readonly velocityExpansion: number; + readonly velocityX: number; + readonly velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +interface MSGraphicsTrust { + readonly constrictionActive: boolean; + readonly status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +} + +interface MSHTMLWebViewElement extends HTMLElement { + readonly canGoBack: boolean; + readonly canGoForward: boolean; + readonly containsFullScreenElement: boolean; + readonly documentTitle: string; + height: number; + readonly settings: MSWebViewSettings; + src: string; + width: number; + addWebAllowedObject(name: string, applicationObject: any): void; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; + getDeferredPermissionRequests(): DeferredPermissionRequest[]; + goBack(): void; + goForward(): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + navigate(uri: string): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + navigateToString(contents: string): void; + navigateWithHttpRequestMessage(requestMessage: any): void; + refresh(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSHTMLWebViewElement: { + prototype: MSHTMLWebViewElement; + new(): MSHTMLWebViewElement; +} + +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowshow: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowupdate: (this: MSInputMethodContext, ev: Event) => any; + readonly target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +} + +interface MSManipulationEvent extends UIEvent { + readonly currentState: number; + readonly inertiaDestinationX: number; + readonly inertiaDestinationY: number; + readonly lastState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +interface MSMediaKeyError { + readonly code: number; + readonly systemCode: number; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +interface MSMediaKeyMessageEvent extends Event { + readonly destinationURL: string | null; + readonly message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +} + +interface MSMediaKeyNeededEvent extends Event { + readonly initData: Uint8Array | null; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +} + +interface MSMediaKeySession extends EventTarget { + readonly error: MSMediaKeyError | null; + readonly keySystem: string; + readonly sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +} + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +} + +interface MSPointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +} + +interface MSRangeCollection { + readonly length: number; + item(index: number): Range; + [index: number]: Range; +} + +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSSiteModeEvent extends Event { + readonly actionURL: string; + readonly buttonID: number; +} + +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MSStreamReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +} + +interface MSWebViewAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSWebViewAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSWebViewAsyncOperation, ev: Event) => any; + onerror: (this: MSWebViewAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + readonly target: MSHTMLWebViewElement; + readonly type: number; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSWebViewAsyncOperation: { + prototype: MSWebViewAsyncOperation; + new(): MSWebViewAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; +} + +interface MSWebViewSettings { + isIndexedDBEnabled: boolean; + isJavaScriptEnabled: boolean; +} + +declare var MSWebViewSettings: { + prototype: MSWebViewSettings; + new(): MSWebViewSettings; +} + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: string; + readonly label: string; +} + +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +} + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): PromiseLike; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +} + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +} + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +} + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: string; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +} + +interface MediaKeySession extends EventTarget { + readonly closed: PromiseLike; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): PromiseLike; + generateRequest(initDataType: string, initData: any): PromiseLike; + load(sessionId: string): PromiseLike; + remove(): PromiseLike; + update(response: any): PromiseLike; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +} + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): string; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +} + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): PromiseLike; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +} + +interface MediaKeys { + createSession(sessionType?: string): MediaKeySession; + setServerCertificate(serverCertificate: any): PromiseLike; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +} + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +} + +interface MediaStreamEventMap { + "active": Event; + "addtrack": TrackEvent; + "inactive": Event; + "removetrack": TrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: TrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: TrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +} + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +} + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +} + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +} + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: string; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): PromiseLike; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +} + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +} + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +} + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +} + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +} + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +} + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +} + +interface MutationEvent extends Event { + readonly attrChange: number; + readonly attrName: string; + readonly newValue: string; + readonly prevValue: string; + readonly relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +interface MutationObserver { + disconnect(): void; + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +} + +interface MutationRecord { + readonly addedNodes: NodeList; + readonly attributeName: string | null; + readonly attributeNamespace: string | null; + readonly nextSibling: Node | null; + readonly oldValue: string | null; + readonly previousSibling: Node | null; + readonly removedNodes: NodeList; + readonly target: Node; + readonly type: string; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +} + +interface NamedNodeMap { + readonly length: number; + getNamedItem(name: string): Attr; + getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + item(index: number): Attr; + removeNamedItem(name: string): Attr; + removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + setNamedItem(arg: Attr): Attr; + setNamedItemNS(arg: Attr): Attr; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface NavigationCompletedEvent extends NavigationEvent { + readonly isSuccess: boolean; + readonly webErrorStatus: number; +} + +declare var NavigationCompletedEvent: { + prototype: NavigationCompletedEvent; + new(): NavigationCompletedEvent; +} + +interface NavigationEvent extends Event { + readonly uri: string; +} + +declare var NavigationEvent: { + prototype: NavigationEvent; + new(): NavigationEvent; +} + +interface NavigationEventWithReferrer extends NavigationEvent { + readonly referer: string; +} + +declare var NavigationEventWithReferrer: { + prototype: NavigationEventWithReferrer; + new(): NavigationEventWithReferrer; +} + +interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { + readonly appCodeName: string; + readonly cookieEnabled: boolean; + readonly language: string; + readonly maxTouchPoints: number; + readonly mimeTypes: MimeTypeArray; + readonly msManipulationViewsEnabled: boolean; + readonly msMaxTouchPoints: number; + readonly msPointerEnabled: boolean; + readonly plugins: PluginArray; + readonly pointerEnabled: boolean; + readonly webdriver: boolean; + readonly hardwareConcurrency: number; + getGamepads(): Gamepad[]; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; + vibrate(pattern: number | number[]): boolean; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface Node extends EventTarget { + readonly attributes: NamedNodeMap; + readonly baseURI: string | null; + readonly childNodes: NodeList; + readonly firstChild: Node | null; + readonly lastChild: Node | null; + readonly localName: string | null; + readonly namespaceURI: string | null; + readonly nextSibling: Node | null; + readonly nodeName: string; + readonly nodeType: number; + nodeValue: string | null; + readonly ownerDocument: Document; + readonly parentElement: HTMLElement | null; + readonly parentNode: Node | null; + readonly previousSibling: Node | null; + textContent: string | null; + appendChild(newChild: Node): Node; + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + contains(child: Node): boolean; + hasAttributes(): boolean; + hasChildNodes(): boolean; + insertBefore(newChild: Node, refChild: Node | null): Node; + isDefaultNamespace(namespaceURI: string | null): boolean; + isEqualNode(arg: Node): boolean; + isSameNode(other: Node): boolean; + lookupNamespaceURI(prefix: string | null): string | null; + lookupPrefix(namespaceURI: string | null): string | null; + normalize(): void; + removeChild(oldChild: Node): Node; + replaceChild(newChild: Node, oldChild: Node): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +interface NodeFilter { + acceptNode(n: Node): number; +} + +declare var NodeFilter: { + readonly FILTER_ACCEPT: number; + readonly FILTER_REJECT: number; + readonly FILTER_SKIP: number; + readonly SHOW_ALL: number; + readonly SHOW_ATTRIBUTE: number; + readonly SHOW_CDATA_SECTION: number; + readonly SHOW_COMMENT: number; + readonly SHOW_DOCUMENT: number; + readonly SHOW_DOCUMENT_FRAGMENT: number; + readonly SHOW_DOCUMENT_TYPE: number; + readonly SHOW_ELEMENT: number; + readonly SHOW_ENTITY: number; + readonly SHOW_ENTITY_REFERENCE: number; + readonly SHOW_NOTATION: number; + readonly SHOW_PROCESSING_INSTRUCTION: number; + readonly SHOW_TEXT: number; +} + +interface NodeIterator { + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + detach(): void; + nextNode(): Node; + previousNode(): Node; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface NodeList { + readonly length: number; + item(index: number): Node; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface OES_element_index_uint { +} + +declare var OES_element_index_uint: { + prototype: OES_element_index_uint; + new(): OES_element_index_uint; +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +declare var OES_standard_derivatives: { + prototype: OES_standard_derivatives; + new(): OES_standard_derivatives; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface OES_texture_float { +} + +declare var OES_texture_float: { + prototype: OES_texture_float; + new(): OES_texture_float; +} + +interface OES_texture_float_linear { +} + +declare var OES_texture_float_linear: { + prototype: OES_texture_float_linear; + new(): OES_texture_float_linear; +} + +interface OfflineAudioCompletionEvent extends Event { + readonly renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(): OfflineAudioCompletionEvent; +} + +interface OfflineAudioContextEventMap { + "complete": Event; +} + +interface OfflineAudioContext extends AudioContext { + oncomplete: (this: OfflineAudioContext, ev: Event) => any; + startRendering(): PromiseLike; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +} + +interface OscillatorNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface OscillatorNode extends AudioNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + type: string; + setPeriodicWave(periodicWave: PeriodicWave): void; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(): OscillatorNode; +} + +interface OverflowEvent extends UIEvent { + readonly horizontalOverflow: boolean; + readonly orient: number; + readonly verticalOverflow: boolean; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +declare var OverflowEvent: { + prototype: OverflowEvent; + new(): OverflowEvent; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +interface PageTransitionEvent extends Event { + readonly persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +} + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: string; + maxDistance: number; + panningModel: string; + refDistance: number; + rolloffFactor: number; + setOrientation(x: number, y: number, z: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(): PannerNode; +} + +interface PerfWidgetExternal { + readonly activeNetworkRequestCount: number; + readonly averageFrameTime: number; + readonly averagePaintTime: number; + readonly extraInformationEnabled: boolean; + readonly independentRenderingEnabled: boolean; + readonly irDisablingContentString: string; + readonly irStatusAvailable: boolean; + readonly maxCpuSpeed: number; + readonly paintRequestsPerSecond: number; + readonly performanceCounter: number; + readonly performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number | null): any; + getRecentFrames(last: number | null): any; + getRecentMemoryUsage(last: number | null): any; + getRecentPaintRequests(last: number | null): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +} + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +} + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +} + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +} + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: string; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +} + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(): PeriodicWave; +} + +interface PermissionRequest extends DeferredPermissionRequest { + readonly state: string; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +} + +interface PermissionRequestedEvent extends Event { + readonly permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +} + +interface Plugin { + readonly description: string; + readonly filename: string; + readonly length: number; + readonly name: string; + readonly version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +} + +interface PluginArray { + readonly length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +} + +interface PointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; +} + +interface PopStateEvent extends Event { + readonly state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +} + +interface PositionError { + readonly code: number; + readonly message: string; + toString(): string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +interface ProcessingInstruction extends CharacterData { + readonly target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +} + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; +} + +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +} + +interface RTCDtlsTransportEventMap { + "dtlsstatechange": RTCDtlsTransportStateChangedEvent; + "error": ErrorEvent; +} + +interface RTCDtlsTransport extends RTCStatsProvider { + ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: ErrorEvent) => any) | null; + readonly state: string; + readonly transport: RTCIceTransport; + getLocalParameters(): RTCDtlsParameters; + getRemoteCertificates(): ArrayBuffer[]; + getRemoteParameters(): RTCDtlsParameters | null; + start(remoteParameters: RTCDtlsParameters): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtlsTransport: { + prototype: RTCDtlsTransport; + new(transport: RTCIceTransport): RTCDtlsTransport; +} + +interface RTCDtlsTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCDtlsTransportStateChangedEvent: { + prototype: RTCDtlsTransportStateChangedEvent; + new(): RTCDtlsTransportStateChangedEvent; +} + +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDtmfSender extends EventTarget { + readonly canInsertDTMF: boolean; + readonly duration: number; + readonly interToneGap: number; + ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + readonly sender: RTCRtpSender; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtmfSender: { + prototype: RTCDtmfSender; + new(sender: RTCRtpSender): RTCDtmfSender; +} + +interface RTCIceCandidatePairChangedEvent extends Event { + readonly pair: RTCIceCandidatePair; +} + +declare var RTCIceCandidatePairChangedEvent: { + prototype: RTCIceCandidatePairChangedEvent; + new(): RTCIceCandidatePairChangedEvent; +} + +interface RTCIceGathererEventMap { + "error": ErrorEvent; + "localcandidate": RTCIceGathererEvent; +} + +interface RTCIceGatherer extends RTCStatsProvider { + readonly component: string; + onerror: ((this: RTCIceGatherer, ev: ErrorEvent) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; + createAssociatedGatherer(): RTCIceGatherer; + getLocalCandidates(): RTCIceCandidate[]; + getLocalParameters(): RTCIceParameters; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceGatherer: { + prototype: RTCIceGatherer; + new(options: RTCIceGatherOptions): RTCIceGatherer; +} + +interface RTCIceGathererEvent extends Event { + readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; +} + +declare var RTCIceGathererEvent: { + prototype: RTCIceGathererEvent; + new(): RTCIceGathererEvent; +} + +interface RTCIceTransportEventMap { + "candidatepairchange": RTCIceCandidatePairChangedEvent; + "icestatechange": RTCIceTransportStateChangedEvent; +} + +interface RTCIceTransport extends RTCStatsProvider { + readonly component: string; + readonly iceGatherer: RTCIceGatherer | null; + oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null; + onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null; + readonly role: string; + readonly state: string; + addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; + createAssociatedTransport(): RTCIceTransport; + getNominatedCandidatePair(): RTCIceCandidatePair | null; + getRemoteCandidates(): RTCIceCandidate[]; + getRemoteParameters(): RTCIceParameters | null; + setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; + start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceTransport: { + prototype: RTCIceTransport; + new(): RTCIceTransport; +} + +interface RTCIceTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCIceTransportStateChangedEvent: { + prototype: RTCIceTransportStateChangedEvent; + new(): RTCIceTransportStateChangedEvent; +} + +interface RTCRtpReceiverEventMap { + "error": ErrorEvent; +} + +interface RTCRtpReceiver extends RTCStatsProvider { + onerror: ((this: RTCRtpReceiver, ev: ErrorEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack | null; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + getContributingSources(): RTCRtpContributingSource[]; + receive(parameters: RTCRtpParameters): void; + requestSendCSRC(csrc: number): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpReceiver: { + prototype: RTCRtpReceiver; + new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCRtpSenderEventMap { + "error": ErrorEvent; + "ssrcconflict": RTCSsrcConflictEvent; +} + +interface RTCRtpSender extends RTCStatsProvider { + onerror: ((this: RTCRtpSender, ev: ErrorEvent) => any) | null; + onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + send(parameters: RTCRtpParameters): void; + setTrack(track: MediaStreamTrack): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpSender: { + prototype: RTCRtpSender; + new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCSrtpSdesTransportEventMap { + "error": ErrorEvent; +} + +interface RTCSrtpSdesTransport extends EventTarget { + onerror: ((this: RTCSrtpSdesTransport, ev: ErrorEvent) => any) | null; + readonly transport: RTCIceTransport; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCSrtpSdesTransport: { + prototype: RTCSrtpSdesTransport; + new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; + getLocalParameters(): RTCSrtpSdesParameters[]; +} + +interface RTCSsrcConflictEvent extends Event { + readonly ssrc: number; +} + +declare var RTCSsrcConflictEvent: { + prototype: RTCSsrcConflictEvent; + new(): RTCSsrcConflictEvent; +} + +interface RTCStatsProvider extends EventTarget { + getStats(): PromiseLike; + msGetStats(): PromiseLike; +} + +declare var RTCStatsProvider: { + prototype: RTCStatsProvider; + new(): RTCStatsProvider; +} + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: string): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface SVGAngle { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +interface SVGAnimatedAngle { + readonly animVal: SVGAngle; + readonly baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGAnimatedBoolean { + readonly animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGAnimatedEnumeration { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGAnimatedInteger { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGAnimatedLength { + readonly animVal: SVGLength; + readonly baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface SVGAnimatedLengthList { + readonly animVal: SVGLengthList; + readonly baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface SVGAnimatedNumber { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface SVGAnimatedNumberList { + readonly animVal: SVGNumberList; + readonly baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGAnimatedPreserveAspectRatio { + readonly animVal: SVGPreserveAspectRatio; + readonly baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface SVGAnimatedRect { + readonly animVal: SVGRect; + readonly baseVal: SVGRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface SVGAnimatedString { + readonly animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGAnimatedTransformList { + readonly animVal: SVGTransformList; + readonly baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + readonly amplitude: SVGAnimatedNumber; + readonly exponent: SVGAnimatedNumber; + readonly intercept: SVGAnimatedNumber; + readonly offset: SVGAnimatedNumber; + readonly slope: SVGAnimatedNumber; + readonly tableValues: SVGAnimatedNumberList; + readonly type: SVGAnimatedEnumeration; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface SVGElementEventMap extends ElementEventMap { + "click": MouseEvent; + "dblclick": MouseEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "load": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; +} + +interface SVGElement extends Element { + onclick: (this: SVGElement, ev: MouseEvent) => any; + ondblclick: (this: SVGElement, ev: MouseEvent) => any; + onfocusin: (this: SVGElement, ev: FocusEvent) => any; + onfocusout: (this: SVGElement, ev: FocusEvent) => any; + onload: (this: SVGElement, ev: Event) => any; + onmousedown: (this: SVGElement, ev: MouseEvent) => any; + onmousemove: (this: SVGElement, ev: MouseEvent) => any; + onmouseout: (this: SVGElement, ev: MouseEvent) => any; + onmouseover: (this: SVGElement, ev: MouseEvent) => any; + onmouseup: (this: SVGElement, ev: MouseEvent) => any; + readonly ownerSVGElement: SVGSVGElement; + readonly viewportElement: SVGElement; + xmlbase: string; + className: any; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface SVGElementInstance extends EventTarget { + readonly childNodes: SVGElementInstanceList; + readonly correspondingElement: SVGElement; + readonly correspondingUseElement: SVGUseElement; + readonly firstChild: SVGElementInstance; + readonly lastChild: SVGElementInstance; + readonly nextSibling: SVGElementInstance; + readonly parentNode: SVGElementInstance; + readonly previousSibling: SVGElementInstance; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface SVGElementInstanceList { + readonly length: number; + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly mode: SVGAnimatedEnumeration; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly type: SVGAnimatedEnumeration; + readonly values: SVGAnimatedNumberList; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly k1: SVGAnimatedNumber; + readonly k2: SVGAnimatedNumber; + readonly k3: SVGAnimatedNumber; + readonly k4: SVGAnimatedNumber; + readonly operator: SVGAnimatedEnumeration; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly bias: SVGAnimatedNumber; + readonly divisor: SVGAnimatedNumber; + readonly edgeMode: SVGAnimatedEnumeration; + readonly in1: SVGAnimatedString; + readonly kernelMatrix: SVGAnimatedNumberList; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly orderX: SVGAnimatedInteger; + readonly orderY: SVGAnimatedInteger; + readonly preserveAlpha: SVGAnimatedBoolean; + readonly targetX: SVGAnimatedInteger; + readonly targetY: SVGAnimatedInteger; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly diffuseConstant: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly scale: SVGAnimatedNumber; + readonly xChannelSelector: SVGAnimatedEnumeration; + readonly yChannelSelector: SVGAnimatedEnumeration; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; +} + +interface SVGFEDistantLightElement extends SVGElement { + readonly azimuth: SVGAnimatedNumber; + readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly stdDeviationX: SVGAnimatedNumber; + readonly stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface SVGFEMergeNodeElement extends SVGElement { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly operator: SVGAnimatedEnumeration; + readonly radiusX: SVGAnimatedNumber; + readonly radiusY: SVGAnimatedNumber; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly dx: SVGAnimatedNumber; + readonly dy: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface SVGFEPointLightElement extends SVGElement { + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly specularConstant: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface SVGFESpotLightElement extends SVGElement { + readonly limitingConeAngle: SVGAnimatedNumber; + readonly pointsAtX: SVGAnimatedNumber; + readonly pointsAtY: SVGAnimatedNumber; + readonly pointsAtZ: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly baseFrequencyX: SVGAnimatedNumber; + readonly baseFrequencyY: SVGAnimatedNumber; + readonly numOctaves: SVGAnimatedInteger; + readonly seed: SVGAnimatedNumber; + readonly stitchTiles: SVGAnimatedEnumeration; + readonly type: SVGAnimatedEnumeration; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly filterResX: SVGAnimatedInteger; + readonly filterResY: SVGAnimatedInteger; + readonly filterUnits: SVGAnimatedEnumeration; + readonly height: SVGAnimatedLength; + readonly primitiveUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { + readonly gradientTransform: SVGAnimatedTransformList; + readonly gradientUnits: SVGAnimatedEnumeration; + readonly spreadMethod: SVGAnimatedEnumeration; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface SVGLength { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +interface SVGLengthList { + readonly numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + readonly markerHeight: SVGAnimatedLength; + readonly markerUnits: SVGAnimatedEnumeration; + readonly markerWidth: SVGAnimatedLength; + readonly orientAngle: SVGAnimatedAngle; + readonly orientType: SVGAnimatedEnumeration; + readonly refX: SVGAnimatedLength; + readonly refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; +} + +interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly maskContentUnits: SVGAnimatedEnumeration; + readonly maskUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +interface SVGMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + flipX(): SVGMatrix; + flipY(): SVGMatrix; + inverse(): SVGMatrix; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + rotate(angle: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + skewX(angle: number): SVGMatrix; + skewY(angle: number): SVGMatrix; + translate(x: number, y: number): SVGMatrix; +} + +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGNumberList { + readonly numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface SVGPathSeg { + readonly pathSegType: number; + readonly pathSegTypeAsLetter: string; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface SVGPathSegList { + readonly numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly patternContentUnits: SVGAnimatedEnumeration; + readonly patternTransform: SVGAnimatedTransformList; + readonly patternUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGPoint { + x: number; + y: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} + +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface SVGPointList { + readonly numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly fx: SVGAnimatedLength; + readonly fy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface SVGRect { + height: number; + width: number; + x: number; + y: number; +} + +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + contentScriptType: string; + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: (this: SVGSVGElement, ev: Event) => any; + onerror: (this: SVGSVGElement, ev: Event) => any; + onresize: (this: SVGSVGElement, ev: UIEvent) => any; + onscroll: (this: SVGSVGElement, ev: UIEvent) => any; + onunload: (this: SVGSVGElement, ev: Event) => any; + onzoom: (this: SVGSVGElement, ev: SVGZoomEvent) => any; + readonly pixelUnitToMillimeterX: number; + readonly pixelUnitToMillimeterY: number; + readonly screenPixelToMillimeterX: number; + readonly screenPixelToMillimeterY: number; + readonly viewport: SVGRect; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + pauseAnimations(): void; + setCurrentTime(seconds: number): void; + suspendRedraw(maxWaitMilliseconds: number): number; + unpauseAnimations(): void; + unsuspendRedraw(suspendHandleID: number): void; + unsuspendRedrawAll(): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly lengthAdjust: SVGAnimatedEnumeration; + readonly textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + readonly method: SVGAnimatedEnumeration; + readonly spacing: SVGAnimatedEnumeration; + readonly startOffset: SVGAnimatedLength; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + readonly dx: SVGAnimatedLengthList; + readonly dy: SVGAnimatedLengthList; + readonly rotate: SVGAnimatedNumberList; + readonly x: SVGAnimatedLengthList; + readonly y: SVGAnimatedLengthList; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface SVGTransform { + readonly angle: number; + readonly matrix: SVGMatrix; + readonly type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +interface SVGTransformList { + readonly numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGUnitTypes { + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: SVGUnitTypes; + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly animatedInstanceRoot: SVGElementInstance; + readonly height: SVGAnimatedLength; + readonly instanceRoot: SVGElementInstance; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface SVGZoomAndPan { + readonly zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +} + +interface SVGZoomEvent extends UIEvent { + readonly newScale: number; + readonly newTranslate: SVGPoint; + readonly previousScale: number; + readonly previousTranslate: SVGPoint; + readonly zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +} + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +} + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: string; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +} + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +} + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface StorageEvent extends Event { + readonly url: string; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface SubtleCrypto { + 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: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +} + +interface Text extends CharacterData { + readonly wholeText: string; + readonly assignedSlot: HTMLSlotElement | null; + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(): Text; +} + +interface TextEvent extends UIEvent { + readonly data: string; + readonly inputMethod: number; + readonly locale: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +interface TextMetrics { + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface TextTrackEventMap { + "cuechange": Event; + "error": ErrorEvent; + "load": Event; +} + +interface TextTrack extends EventTarget { + readonly activeCues: TextTrackCueList; + readonly cues: TextTrackCueList; + readonly inBandMetadataTrackDispatchType: string; + readonly kind: string; + readonly label: string; + readonly language: string; + mode: any; + oncuechange: (this: TextTrack, ev: Event) => any; + onerror: (this: TextTrack, ev: ErrorEvent) => any; + onload: (this: TextTrack, ev: Event) => any; + readonly readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; +} + +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: (this: TextTrackCue, ev: Event) => any; + onexit: (this: TextTrackCue, ev: Event) => any; + pauseOnExit: boolean; + startTime: number; + text: string; + readonly track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +} + +interface TextTrackCueList { + readonly length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + +interface TextTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; + item(index: number): TextTrack; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface TimeRanges { + readonly length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface Touch { + readonly clientX: number; + readonly clientY: number; + readonly identifier: number; + readonly pageX: number; + readonly pageY: number; + readonly screenX: number; + readonly screenY: number; + readonly target: EventTarget; +} + +declare var Touch: { + prototype: Touch; + new(): Touch; +} + +interface TouchEvent extends UIEvent { + readonly altKey: boolean; + readonly changedTouches: TouchList; + readonly ctrlKey: boolean; + readonly metaKey: boolean; + readonly shiftKey: boolean; + readonly targetTouches: TouchList; + readonly touches: TouchList; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(): TouchEvent; +} + +interface TouchList { + readonly length: number; + item(index: number): Touch | null; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +} + +interface TrackEvent extends Event { + readonly track: any; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface TransitionEvent extends Event { + readonly elapsedTime: number; + readonly propertyName: string; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface TreeWalker { + currentNode: Node; + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + firstChild(): Node; + lastChild(): Node; + nextNode(): Node; + nextSibling(): Node; + parentNode(): Node; + previousNode(): Node; + previousSibling(): Node; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface UIEvent extends Event { + readonly detail: number; + readonly view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(type: string, eventInitDict?: UIEventInit): UIEvent; +} + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + username: string; + toString(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string): URL; + createObjectURL(object: any, options?: ObjectURLOptions): string; + revokeObjectURL(url: string): void; +} + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; +} + +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +} + +interface ValidityState { + readonly badInput: boolean; + readonly customError: boolean; + readonly patternMismatch: boolean; + readonly rangeOverflow: boolean; + readonly rangeUnderflow: boolean; + readonly stepMismatch: boolean; + readonly tooLong: boolean; + readonly typeMismatch: boolean; + readonly valid: boolean; + readonly valueMissing: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface VideoPlaybackQuality { + readonly corruptedVideoFrames: number; + readonly creationTime: number; + readonly droppedVideoFrames: number; + readonly totalFrameDelay: number; + readonly totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +} + +interface VideoTrack { + readonly id: string; + kind: string; + readonly label: string; + language: string; + selected: boolean; + readonly sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +} + +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface VideoTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: VideoTrackList, ev: TrackEvent) => any; + onchange: (this: VideoTrackList, ev: Event) => any; + onremovetrack: (this: VideoTrackList, ev: TrackEvent) => any; + readonly selectedIndex: number; + getTrackById(id: string): VideoTrack | null; + item(index: number): VideoTrack; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +interface WaveShaperNode extends AudioNode { + curve: Float32Array | null; + oversample: string; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(): WaveShaperNode; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: number; + readonly type: number; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +} + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +} + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +} + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +} + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +} + +interface WebGLRenderingContext { + readonly canvas: HTMLCanvasElement; + readonly drawingBufferHeight: number; + readonly drawingBufferWidth: number; + activeTexture(texture: number): void; + attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; + bindBuffer(target: number, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: number, texture: WebGLTexture | null): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + blendEquation(mode: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + blendFunc(sfactor: number, dfactor: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; + checkFramebufferStatus(target: number): number; + clear(mask: number): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + clearDepth(depth: number): void; + clearStencil(s: number): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compileShader(shader: WebGLShader | null): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: number): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: number): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: number): void; + depthMask(flag: boolean): void; + depthRange(zNear: number, zFar: number): void; + detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + disable(cap: number): void; + disableVertexAttribArray(index: number): void; + drawArrays(mode: number, first: number, count: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + enable(cap: number): void; + enableVertexAttribArray(index: number): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; + frontFace(mode: number): void; + generateMipmap(target: number): void; + getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram | null, name: string): number; + getBufferParameter(target: number, pname: number): any; + getContextAttributes(): WebGLContextAttributes; + getError(): number; + getExtension(name: string): any; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + getParameter(pname: number): any; + getProgramInfoLog(program: WebGLProgram | null): string | null; + getProgramParameter(program: WebGLProgram | null, pname: number): any; + getRenderbufferParameter(target: number, pname: number): any; + getShaderInfoLog(shader: WebGLShader | null): string | null; + getShaderParameter(shader: WebGLShader | null, pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader | null): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: number, pname: number): any; + getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; + getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: number, pname: number): any; + getVertexAttribOffset(index: number, pname: number): number; + hint(target: number, mode: number): void; + isBuffer(buffer: WebGLBuffer | null): boolean; + isContextLost(): boolean; + isEnabled(cap: number): boolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; + isProgram(program: WebGLProgram | null): boolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; + isShader(shader: WebGLShader | null): boolean; + isTexture(texture: WebGLTexture | null): boolean; + lineWidth(width: number): void; + linkProgram(program: WebGLProgram | null): void; + pixelStorei(pname: number, param: number): void; + polygonOffset(factor: number, units: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + sampleCoverage(value: number, invert: boolean): void; + scissor(x: number, y: number, width: number, height: number): void; + shaderSource(shader: WebGLShader | null, source: string): void; + stencilFunc(func: number, ref: number, mask: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + stencilMask(mask: number): void; + 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, 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, 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; + uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram | null): void; + vertexAttrib1f(indx: number, x: number): void; + vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib2f(indx: number, x: number, y: number): void; + vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + viewport(x: number, y: number, width: number, height: number): void; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +} + +interface WebGLShaderPrecisionFormat { + readonly precision: number; + readonly rangeMax: number; + readonly rangeMin: number; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +} + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +} + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +} + +interface WebKitCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): WebKitCSSMatrix; + multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): WebKitCSSMatrix; + skewY(angle: number): WebKitCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): WebKitCSSMatrix; +} + +declare var WebKitCSSMatrix: { + prototype: WebKitCSSMatrix; + new(text?: string): WebKitCSSMatrix; +} + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +} + +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +} + +interface WheelEvent extends MouseEvent { + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + readonly wheelDelta: number; + readonly wheelDeltaX: number; + readonly wheelDeltaY: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +interface WindowEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "unload": Event; + "volumechange": Event; + "waiting": Event; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { + readonly applicationCache: ApplicationCache; + readonly clientInformation: Navigator; + readonly closed: boolean; + readonly crypto: Crypto; + defaultStatus: string; + readonly devicePixelRatio: number; + readonly doNotTrack: string; + readonly document: Document; + event: Event | undefined; + readonly external: External; + readonly frameElement: Element; + readonly frames: Window; + readonly history: History; + readonly innerHeight: number; + readonly innerWidth: number; + readonly length: number; + readonly location: Location; + readonly locationbar: BarProp; + readonly menubar: BarProp; + readonly msCredentials: MSCredentials; + name: string; + readonly navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (this: Window, ev: UIEvent) => any; + onafterprint: (this: Window, ev: Event) => any; + onbeforeprint: (this: Window, ev: Event) => any; + onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; + onblur: (this: Window, ev: FocusEvent) => any; + oncanplay: (this: Window, ev: Event) => any; + oncanplaythrough: (this: Window, ev: Event) => any; + onchange: (this: Window, ev: Event) => any; + onclick: (this: Window, ev: MouseEvent) => any; + oncompassneedscalibration: (this: Window, ev: Event) => any; + oncontextmenu: (this: Window, ev: PointerEvent) => any; + ondblclick: (this: Window, ev: MouseEvent) => any; + ondevicelight: (this: Window, ev: DeviceLightEvent) => any; + ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; + ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; + ondrag: (this: Window, ev: DragEvent) => any; + ondragend: (this: Window, ev: DragEvent) => any; + ondragenter: (this: Window, ev: DragEvent) => any; + ondragleave: (this: Window, ev: DragEvent) => any; + ondragover: (this: Window, ev: DragEvent) => any; + ondragstart: (this: Window, ev: DragEvent) => any; + ondrop: (this: Window, ev: DragEvent) => any; + ondurationchange: (this: Window, ev: Event) => any; + onemptied: (this: Window, ev: Event) => any; + onended: (this: Window, ev: MediaStreamErrorEvent) => any; + onerror: ErrorEventHandler; + onfocus: (this: Window, ev: FocusEvent) => any; + onhashchange: (this: Window, ev: HashChangeEvent) => any; + oninput: (this: Window, ev: Event) => any; + oninvalid: (this: Window, ev: Event) => any; + onkeydown: (this: Window, ev: KeyboardEvent) => any; + onkeypress: (this: Window, ev: KeyboardEvent) => any; + onkeyup: (this: Window, ev: KeyboardEvent) => any; + onload: (this: Window, ev: Event) => any; + onloadeddata: (this: Window, ev: Event) => any; + onloadedmetadata: (this: Window, ev: Event) => any; + onloadstart: (this: Window, ev: Event) => any; + onmessage: (this: Window, ev: MessageEvent) => any; + onmousedown: (this: Window, ev: MouseEvent) => any; + onmouseenter: (this: Window, ev: MouseEvent) => any; + onmouseleave: (this: Window, ev: MouseEvent) => any; + onmousemove: (this: Window, ev: MouseEvent) => any; + onmouseout: (this: Window, ev: MouseEvent) => any; + onmouseover: (this: Window, ev: MouseEvent) => any; + onmouseup: (this: Window, ev: MouseEvent) => any; + onmousewheel: (this: Window, ev: WheelEvent) => any; + onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; + onmsgestureend: (this: Window, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; + onmspointercancel: (this: Window, ev: MSPointerEvent) => any; + onmspointerdown: (this: Window, ev: MSPointerEvent) => any; + onmspointerenter: (this: Window, ev: MSPointerEvent) => any; + onmspointerleave: (this: Window, ev: MSPointerEvent) => any; + onmspointermove: (this: Window, ev: MSPointerEvent) => any; + onmspointerout: (this: Window, ev: MSPointerEvent) => any; + onmspointerover: (this: Window, ev: MSPointerEvent) => any; + onmspointerup: (this: Window, ev: MSPointerEvent) => any; + onoffline: (this: Window, ev: Event) => any; + ononline: (this: Window, ev: Event) => any; + onorientationchange: (this: Window, ev: Event) => any; + onpagehide: (this: Window, ev: PageTransitionEvent) => any; + onpageshow: (this: Window, ev: PageTransitionEvent) => any; + onpause: (this: Window, ev: Event) => any; + onplay: (this: Window, ev: Event) => any; + onplaying: (this: Window, ev: Event) => any; + onpopstate: (this: Window, ev: PopStateEvent) => any; + onprogress: (this: Window, ev: ProgressEvent) => any; + onratechange: (this: Window, ev: Event) => any; + onreadystatechange: (this: Window, ev: ProgressEvent) => any; + onreset: (this: Window, ev: Event) => any; + onresize: (this: Window, ev: UIEvent) => any; + onscroll: (this: Window, ev: UIEvent) => any; + onseeked: (this: Window, ev: Event) => any; + onseeking: (this: Window, ev: Event) => any; + onselect: (this: Window, ev: UIEvent) => any; + onstalled: (this: Window, ev: Event) => any; + onstorage: (this: Window, ev: StorageEvent) => any; + onsubmit: (this: Window, ev: Event) => any; + onsuspend: (this: Window, ev: Event) => any; + ontimeupdate: (this: Window, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onunload: (this: Window, ev: Event) => any; + onvolumechange: (this: Window, ev: Event) => any; + onwaiting: (this: Window, ev: Event) => any; + opener: any; + orientation: string | number; + readonly outerHeight: number; + readonly outerWidth: number; + readonly pageXOffset: number; + readonly pageYOffset: number; + readonly parent: Window; + readonly performance: Performance; + readonly personalbar: BarProp; + readonly screen: Screen; + readonly screenLeft: number; + readonly screenTop: number; + readonly screenX: number; + readonly screenY: number; + readonly scrollX: number; + readonly scrollY: number; + readonly scrollbars: BarProp; + readonly self: Window; + status: string; + readonly statusbar: BarProp; + readonly styleMedia: StyleMedia; + readonly toolbar: BarProp; + readonly top: Window; + readonly window: Window; + URL: typeof URL; + Blob: typeof Blob; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + matchMedia(mediaQuery: string): MediaQueryList; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: any, targetOrigin: string, transfer?: any[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + webkitCancelAnimationFrame(handle: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Window: { + prototype: Window; + new(): Window; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (this: Worker, ev: MessageEvent) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +} + +interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: string; + readonly responseXML: any; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + msCaching?: string; + readonly responseURL: string; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: Document): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + create(): XMLHttpRequest; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +} + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +} + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +} + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +} + +interface XPathResult { + readonly booleanValue: boolean; + readonly invalidIteratorState: boolean; + readonly numberValue: number; + readonly resultType: number; + readonly singleNodeValue: Node; + readonly snapshotLength: number; + readonly stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +} + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface CanvasPathMethods { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface ChildNode { + remove(): void; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DocumentEvent { + createEvent(eventInterface:"AnimationEvent"): AnimationEvent; + createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; + createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface:"CloseEvent"): CloseEvent; + createEvent(eventInterface:"CommandEvent"): CommandEvent; + createEvent(eventInterface:"CompositionEvent"): CompositionEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; + createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface:"DragEvent"): DragEvent; + createEvent(eventInterface:"ErrorEvent"): ErrorEvent; + createEvent(eventInterface:"Event"): Event; + createEvent(eventInterface:"Events"): Event; + createEvent(eventInterface:"FocusEvent"): FocusEvent; + createEvent(eventInterface:"GamepadEvent"): GamepadEvent; + createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface:"MessageEvent"): MessageEvent; + createEvent(eventInterface:"MouseEvent"): MouseEvent; + createEvent(eventInterface:"MouseEvents"): MouseEvent; + createEvent(eventInterface:"MutationEvent"): MutationEvent; + createEvent(eventInterface:"MutationEvents"): MutationEvent; + createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface:"NavigationEvent"): NavigationEvent; + createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface:"OverflowEvent"): OverflowEvent; + createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface:"PointerEvent"): PointerEvent; + createEvent(eventInterface:"PopStateEvent"): PopStateEvent; + createEvent(eventInterface:"ProgressEvent"): ProgressEvent; + createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface:"StorageEvent"): StorageEvent; + createEvent(eventInterface:"TextEvent"): TextEvent; + createEvent(eventInterface:"TouchEvent"): TouchEvent; + createEvent(eventInterface:"TrackEvent"): TrackEvent; + createEvent(eventInterface:"TransitionEvent"): TransitionEvent; + createEvent(eventInterface:"UIEvent"): UIEvent; + createEvent(eventInterface:"UIEvents"): UIEvent; + createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface:"WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly nextElementSibling: Element; + readonly previousElementSibling: Element; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + onpointercancel: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerdown: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerenter: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerleave: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointermove: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerout: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; +} + +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + +interface LinkStyle { + readonly sheet: StyleSheet; +} + +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSBaseReader { + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; + readonly readyState: number; + readonly result: any; + abort(): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface NavigatorContentUtils { +} + +interface NavigatorGeolocation { + readonly geolocation: Geolocation; +} + +interface NavigatorID { + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + +interface NodeSelector { + querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: string): Element | null; + querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: string): NodeListOf; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface SVGAnimatedPathData { + readonly pathSegList: SVGPathSegList; +} + +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + +interface SVGExternalResourcesRequired { + readonly externalResourcesRequired: SVGAnimatedBoolean; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + readonly height: SVGAnimatedLength; + readonly result: SVGAnimatedString; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly viewBox: SVGAnimatedRect; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface SVGLocatable { + readonly farthestViewportElement: SVGElement; + readonly nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; + getTransformToElement(element: SVGElement): SVGMatrix; +} + +interface SVGStylable { + className: any; + readonly style: CSSStyleDeclaration; +} + +interface SVGTests { + readonly requiredExtensions: SVGStringList; + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface SVGTransformable extends SVGLocatable { + readonly transform: SVGAnimatedTransformList; +} + +interface SVGURIReference { + readonly href: SVGAnimatedString; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +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(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + 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; + [index: number]: TNode; +} + +interface HTMLCollectionOf extends HTMLCollection { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag { + type?: string; + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface MessageEventInit extends EventInit { + data?: any; + origin?: string; + lastEventId?: string; + channel?: string; + source?: any; + ports?: MessagePort[]; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +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 { + namedCurve: 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; +} + +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly stylesheets: StyleSheetList; + getSelection(): Selection | null; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; +} + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + mode: 'open'|'closed'; + delegatesFocus?: boolean; +} + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface ErrorEventHandler { + (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSLaunchUriCallback { + (): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface ForEachCallback { + (keyId: any, status: string): void; +} +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "audio": HTMLAudioElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "del": HTMLModElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "font": HTMLFontElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nextid": HTMLUnknownElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "script": HTMLScriptElement; + "select": HTMLSelectElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "style": HTMLStyleElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "ul": HTMLUListElement; + "video": HTMLVideoElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "circle": SVGCircleElement; + "cite": HTMLElement; + "clippath": SVGClipPathElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "defs": SVGDefsElement; + "del": HTMLModElement; + "desc": SVGDescElement; + "dfn": HTMLElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "ellipse": SVGEllipseElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "feblend": SVGFEBlendElement; + "fecolormatrix": SVGFEColorMatrixElement; + "fecomponenttransfer": SVGFEComponentTransferElement; + "fecomposite": SVGFECompositeElement; + "feconvolvematrix": SVGFEConvolveMatrixElement; + "fediffuselighting": SVGFEDiffuseLightingElement; + "fedisplacementmap": SVGFEDisplacementMapElement; + "fedistantlight": SVGFEDistantLightElement; + "feflood": SVGFEFloodElement; + "fefunca": SVGFEFuncAElement; + "fefuncb": SVGFEFuncBElement; + "fefuncg": SVGFEFuncGElement; + "fefuncr": SVGFEFuncRElement; + "fegaussianblur": SVGFEGaussianBlurElement; + "feimage": SVGFEImageElement; + "femerge": SVGFEMergeElement; + "femergenode": SVGFEMergeNodeElement; + "femorphology": SVGFEMorphologyElement; + "feoffset": SVGFEOffsetElement; + "fepointlight": SVGFEPointLightElement; + "fespecularlighting": SVGFESpecularLightingElement; + "fespotlight": SVGFESpotLightElement; + "fetile": SVGFETileElement; + "feturbulence": SVGFETurbulenceElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "filter": SVGFilterElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "foreignobject": SVGForeignObjectElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "g": SVGGElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "image": SVGImageElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "line": SVGLineElement; + "lineargradient": SVGLinearGradientElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marker": SVGMarkerElement; + "marquee": HTMLMarqueeElement; + "mask": SVGMaskElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "metadata": SVGMetadataElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "picture": HTMLPictureElement; + "plaintext": HTMLElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "radialgradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "stop": SVGStopElement; + "strike": HTMLElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "text": SVGTextElement; + "textpath": SVGTextPathElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "tspan": SVGTSpanElement; + "tt": HTMLElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "use": SVGUseElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "view": SVGViewElement; + "wbr": HTMLElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementListTagNameMap { + "a": NodeListOf; + "abbr": NodeListOf; + "acronym": NodeListOf; + "address": NodeListOf; + "applet": NodeListOf; + "area": NodeListOf; + "article": NodeListOf; + "aside": NodeListOf; + "audio": NodeListOf; + "b": NodeListOf; + "base": NodeListOf; + "basefont": NodeListOf; + "bdo": NodeListOf; + "big": NodeListOf; + "blockquote": NodeListOf; + "body": NodeListOf; + "br": NodeListOf; + "button": NodeListOf; + "canvas": NodeListOf; + "caption": NodeListOf; + "center": NodeListOf; + "circle": NodeListOf; + "cite": NodeListOf; + "clippath": NodeListOf; + "code": NodeListOf; + "col": NodeListOf; + "colgroup": NodeListOf; + "datalist": NodeListOf; + "dd": NodeListOf; + "defs": NodeListOf; + "del": NodeListOf; + "desc": NodeListOf; + "dfn": NodeListOf; + "dir": NodeListOf; + "div": NodeListOf; + "dl": NodeListOf; + "dt": NodeListOf; + "ellipse": NodeListOf; + "em": NodeListOf; + "embed": NodeListOf; + "feblend": NodeListOf; + "fecolormatrix": NodeListOf; + "fecomponenttransfer": NodeListOf; + "fecomposite": NodeListOf; + "feconvolvematrix": NodeListOf; + "fediffuselighting": NodeListOf; + "fedisplacementmap": NodeListOf; + "fedistantlight": NodeListOf; + "feflood": NodeListOf; + "fefunca": NodeListOf; + "fefuncb": NodeListOf; + "fefuncg": NodeListOf; + "fefuncr": NodeListOf; + "fegaussianblur": NodeListOf; + "feimage": NodeListOf; + "femerge": NodeListOf; + "femergenode": NodeListOf; + "femorphology": NodeListOf; + "feoffset": NodeListOf; + "fepointlight": NodeListOf; + "fespecularlighting": NodeListOf; + "fespotlight": NodeListOf; + "fetile": NodeListOf; + "feturbulence": NodeListOf; + "fieldset": NodeListOf; + "figcaption": NodeListOf; + "figure": NodeListOf; + "filter": NodeListOf; + "font": NodeListOf; + "footer": NodeListOf; + "foreignobject": NodeListOf; + "form": NodeListOf; + "frame": NodeListOf; + "frameset": NodeListOf; + "g": NodeListOf; + "h1": NodeListOf; + "h2": NodeListOf; + "h3": NodeListOf; + "h4": NodeListOf; + "h5": NodeListOf; + "h6": NodeListOf; + "head": NodeListOf; + "header": NodeListOf; + "hgroup": NodeListOf; + "hr": NodeListOf; + "html": NodeListOf; + "i": NodeListOf; + "iframe": NodeListOf; + "image": NodeListOf; + "img": NodeListOf; + "input": NodeListOf; + "ins": NodeListOf; + "isindex": NodeListOf; + "kbd": NodeListOf; + "keygen": NodeListOf; + "label": NodeListOf; + "legend": NodeListOf; + "li": NodeListOf; + "line": NodeListOf; + "lineargradient": NodeListOf; + "link": NodeListOf; + "listing": NodeListOf; + "map": NodeListOf; + "mark": NodeListOf; + "marker": NodeListOf; + "marquee": NodeListOf; + "mask": NodeListOf; + "menu": NodeListOf; + "meta": NodeListOf; + "metadata": NodeListOf; + "meter": NodeListOf; + "nav": NodeListOf; + "nextid": NodeListOf; + "nobr": NodeListOf; + "noframes": NodeListOf; + "noscript": NodeListOf; + "object": NodeListOf; + "ol": NodeListOf; + "optgroup": NodeListOf; + "option": NodeListOf; + "p": NodeListOf; + "param": NodeListOf; + "path": NodeListOf; + "pattern": NodeListOf; + "picture": NodeListOf; + "plaintext": NodeListOf; + "polygon": NodeListOf; + "polyline": NodeListOf; + "pre": NodeListOf; + "progress": NodeListOf; + "q": NodeListOf; + "radialgradient": NodeListOf; + "rect": NodeListOf; + "rt": NodeListOf; + "ruby": NodeListOf; + "s": NodeListOf; + "samp": NodeListOf; + "script": NodeListOf; + "section": NodeListOf; + "select": NodeListOf; + "small": NodeListOf; + "source": NodeListOf; + "span": NodeListOf; + "stop": NodeListOf; + "strike": NodeListOf; + "strong": NodeListOf; + "style": NodeListOf; + "sub": NodeListOf; + "sup": NodeListOf; + "svg": NodeListOf; + "switch": NodeListOf; + "symbol": NodeListOf; + "table": NodeListOf; + "tbody": NodeListOf; + "td": NodeListOf; + "template": NodeListOf; + "text": NodeListOf; + "textpath": NodeListOf; + "textarea": NodeListOf; + "tfoot": NodeListOf; + "th": NodeListOf; + "thead": NodeListOf; + "title": NodeListOf; + "tr": NodeListOf; + "track": NodeListOf; + "tspan": NodeListOf; + "tt": NodeListOf; + "u": NodeListOf; + "ul": NodeListOf; + "use": NodeListOf; + "var": NodeListOf; + "video": NodeListOf; + "view": NodeListOf; + "wbr": NodeListOf; + "x-ms-webview": NodeListOf; + "xmp": NodeListOf; +} + +declare var Audio: {new(src?: string): HTMLAudioElement; }; +declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var applicationCache: ApplicationCache; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var doNotTrack: string; +declare var document: Document; +declare var event: Event | undefined; +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msCredentials: MSCredentials; +declare const name: never; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var onabort: (this: Window, ev: UIEvent) => any; +declare var onafterprint: (this: Window, ev: Event) => any; +declare var onbeforeprint: (this: Window, ev: Event) => any; +declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; +declare var onblur: (this: Window, ev: FocusEvent) => any; +declare var oncanplay: (this: Window, ev: Event) => any; +declare var oncanplaythrough: (this: Window, ev: Event) => any; +declare var onchange: (this: Window, ev: Event) => any; +declare var onclick: (this: Window, ev: MouseEvent) => any; +declare var oncompassneedscalibration: (this: Window, ev: Event) => any; +declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; +declare var ondblclick: (this: Window, ev: MouseEvent) => any; +declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; +declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; +declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; +declare var ondrag: (this: Window, ev: DragEvent) => any; +declare var ondragend: (this: Window, ev: DragEvent) => any; +declare var ondragenter: (this: Window, ev: DragEvent) => any; +declare var ondragleave: (this: Window, ev: DragEvent) => any; +declare var ondragover: (this: Window, ev: DragEvent) => any; +declare var ondragstart: (this: Window, ev: DragEvent) => any; +declare var ondrop: (this: Window, ev: DragEvent) => any; +declare var ondurationchange: (this: Window, ev: Event) => any; +declare var onemptied: (this: Window, ev: Event) => any; +declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; +declare var onerror: ErrorEventHandler; +declare var onfocus: (this: Window, ev: FocusEvent) => any; +declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; +declare var oninput: (this: Window, ev: Event) => any; +declare var oninvalid: (this: Window, ev: Event) => any; +declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; +declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; +declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; +declare var onload: (this: Window, ev: Event) => any; +declare var onloadeddata: (this: Window, ev: Event) => any; +declare var onloadedmetadata: (this: Window, ev: Event) => any; +declare var onloadstart: (this: Window, ev: Event) => any; +declare var onmessage: (this: Window, ev: MessageEvent) => any; +declare var onmousedown: (this: Window, ev: MouseEvent) => any; +declare var onmouseenter: (this: Window, ev: MouseEvent) => any; +declare var onmouseleave: (this: Window, ev: MouseEvent) => any; +declare var onmousemove: (this: Window, ev: MouseEvent) => any; +declare var onmouseout: (this: Window, ev: MouseEvent) => any; +declare var onmouseover: (this: Window, ev: MouseEvent) => any; +declare var onmouseup: (this: Window, ev: MouseEvent) => any; +declare var onmousewheel: (this: Window, ev: WheelEvent) => any; +declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; +declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; +declare var onoffline: (this: Window, ev: Event) => any; +declare var ononline: (this: Window, ev: Event) => any; +declare var onorientationchange: (this: Window, ev: Event) => any; +declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; +declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; +declare var onpause: (this: Window, ev: Event) => any; +declare var onplay: (this: Window, ev: Event) => any; +declare var onplaying: (this: Window, ev: Event) => any; +declare var onpopstate: (this: Window, ev: PopStateEvent) => any; +declare var onprogress: (this: Window, ev: ProgressEvent) => any; +declare var onratechange: (this: Window, ev: Event) => any; +declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; +declare var onreset: (this: Window, ev: Event) => any; +declare var onresize: (this: Window, ev: UIEvent) => any; +declare var onscroll: (this: Window, ev: UIEvent) => any; +declare var onseeked: (this: Window, ev: Event) => any; +declare var onseeking: (this: Window, ev: Event) => any; +declare var onselect: (this: Window, ev: UIEvent) => any; +declare var onstalled: (this: Window, ev: Event) => any; +declare var onstorage: (this: Window, ev: StorageEvent) => any; +declare var onsubmit: (this: Window, ev: Event) => any; +declare var onsuspend: (this: Window, ev: Event) => any; +declare var ontimeupdate: (this: Window, ev: Event) => any; +declare var ontouchcancel: (ev: TouchEvent) => any; +declare var ontouchend: (ev: TouchEvent) => any; +declare var ontouchmove: (ev: TouchEvent) => any; +declare var ontouchstart: (ev: TouchEvent) => any; +declare var onunload: (this: Window, ev: Event) => any; +declare var onvolumechange: (this: Window, ev: Event) => any; +declare var onwaiting: (this: Window, ev: Event) => any; +declare var opener: any; +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollX: number; +declare var scrollY: number; +declare var scrollbars: BarProp; +declare var self: Window; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function moveBy(x?: number, y?: number): void; +declare function moveTo(x?: number, y?: number): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string | null; +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x?: number, y?: number): void; +declare function resizeTo(x?: number, y?: number): void; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare function webkitCancelAnimationFrame(handle: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; +declare function toString(): string; +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(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; +declare var onpointercancel: (this: Window, ev: PointerEvent) => any; +declare var onpointerdown: (this: Window, ev: PointerEvent) => any; +declare var onpointerenter: (this: Window, ev: PointerEvent) => any; +declare var onpointerleave: (this: Window, ev: PointerEvent) => any; +declare var onpointermove: (this: Window, ev: PointerEvent) => any; +declare var onpointerout: (this: Window, ev: PointerEvent) => any; +declare var onpointerover: (this: Window, ev: PointerEvent) => any; +declare var onpointerup: (this: Window, ev: PointerEvent) => any; +declare var onwheel: (this: Window, ev: WheelEvent) => any; +declare var indexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +type AAGUID = string; +type AlgorithmIdentifier = string | Algorithm; +type ConstrainBoolean = boolean | ConstrainBooleanParameters; +type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; +type ConstrainDouble = number | ConstrainDoubleRange; +type ConstrainLong = number | ConstrainLongRange; +type CryptoOperationData = ArrayBufferView; +type GLbitfield = number; +type GLboolean = boolean; +type GLbyte = number; +type GLclampf = number; +type GLenum = number; +type GLfloat = number; +type GLint = number; +type GLintptr = number; +type GLshort = number; +type GLsizei = number; +type GLsizeiptr = number; +type GLubyte = number; +type GLuint = number; +type GLushort = number; +type IDBKeyPath = string; +type KeyFormat = string; +type KeyType = string; +type KeyUsage = string; +type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; +type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; +type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; +type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; +type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; \ No newline at end of file diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index 397e0ab111e..7557e4d06e3 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -1,29 +1,33 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// - -interface DOMTokenList { - [Symbol.iterator](): IterableIterator; -} - -interface NodeList { - [Symbol.iterator](): IterableIterator -} - -interface NodeListOf { - [Symbol.iterator](): IterableIterator -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator +} diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 24c737df74b..9f4a23f3254 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -1,88 +1,92 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value?: V): this; - readonly size: number; -} - -interface MapConstructor { - new (): Map; - new (entries?: [K, V][]): Map; - readonly prototype: Map; -} -declare var Map: MapConstructor; - -interface ReadonlyMap { - forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; - get(key: K): V|undefined; - has(key: K): boolean; - readonly size: number; -} - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value?: V): this; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (entries?: [K, V][]): WeakMap; - readonly prototype: WeakMap; -} -declare var WeakMap: WeakMapConstructor; - -interface Set { - add(value: T): this; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface SetConstructor { - new (): Set; - new (values?: T[]): Set; - readonly prototype: Set; -} -declare var Set: SetConstructor; - -interface ReadonlySet { - forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface WeakSet { - add(value: T): this; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (values?: T[]): WeakSet; - readonly prototype: WeakSet; -} -declare var WeakSet: WeakSetConstructor; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value?: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V|undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value?: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 49a81a220ce..7f03aaec04d 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -1,540 +1,544 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -declare type PropertyKey = string | number | symbol; - -interface Array { - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): this; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): Array; -} - -interface DateConstructor { - new (value: Date): Date; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - readonly name: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[] ): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - readonly EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - readonly MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - readonly MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: any, ...sources: any[]): any; - - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - */ - setPrototypeOf(o: any, proto: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface ReadonlyArray { - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - readonly flags: string; - - /** - * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular - * expression. Default is false. Read-only. - */ - readonly sticky: boolean; - - /** - * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular - * expression. Default is false. Read-only. - */ - readonly unicode: boolean; -} - -interface RegExpConstructor { - new (pattern: RegExp, flags?: string): RegExp; - (pattern: RegExp, flags?: string): RegExp; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number | undefined; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form?: string): string; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} diff --git a/lib/lib.es2015.d.ts b/lib/lib.es2015.d.ts index 973d5180989..a536e9c8922 100644 --- a/lib/lib.es2015.d.ts +++ b/lib/lib.es2015.d.ts @@ -1,26 +1,30 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// +/// +/// +/// +/// /// \ No newline at end of file diff --git a/lib/lib.es2015.generator.d.ts b/lib/lib.es2015.generator.d.ts index 003f325e4e0..3166063a42e 100644 --- a/lib/lib.es2015.generator.d.ts +++ b/lib/lib.es2015.generator.d.ts @@ -1,28 +1,32 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface GeneratorFunction extends Function { } - -interface GeneratorFunctionConstructor { - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): GeneratorFunction; - (...args: string[]): GeneratorFunction; - readonly prototype: GeneratorFunction; -} -declare var GeneratorFunction: GeneratorFunctionConstructor; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface GeneratorFunction extends Function { } + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + (...args: string[]): GeneratorFunction; + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 1c27525d432..02c72a5ee36 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -1,461 +1,465 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// - -interface SymbolConstructor { - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - readonly iterator: symbol; -} - -interface IteratorResult { - done: boolean; - value: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface ArrayConstructor { - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; -} - -interface ReadonlyArray { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface IArguments { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Map { - [Symbol.iterator](): IterableIterator<[K,V]>; - entries(): IterableIterator<[K, V]>; - keys(): IterableIterator; - values(): IterableIterator; -} - -interface MapConstructor { - new (iterable: Iterable<[K, V]>): Map; -} - -interface WeakMap { } - -interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; -} - -interface Set { - [Symbol.iterator](): IterableIterator; - entries(): IterableIterator<[T, T]>; - keys(): IterableIterator; - values(): IterableIterator; -} - -interface SetConstructor { - new (iterable: Iterable): Set; -} - -interface WeakSet { } - -interface WeakSetConstructor { - new (iterable: Iterable): WeakSet; -} - -interface Promise { } - -interface PromiseConstructor { - /** - * 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: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; -} - -declare namespace Reflect { - function enumerate(target: any): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; -} - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; -} - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; - - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; -} - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; -} - -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; -} - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + [Symbol.iterator](): IterableIterator<[K,V]>; + entries(): IterableIterator<[K, V]>; + keys(): IterableIterator; + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + [Symbol.iterator](): IterableIterator; + entries(): IterableIterator<[T, T]>; + keys(): IterableIterator; + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * 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: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: any): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } \ No newline at end of file diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 36fe9e7777f..99df9263ea1 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -1,270 +1,274 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/** - * Represents the completion of an asynchronous operation - */ -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) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, 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. - * @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) | undefined | null): 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 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) | undefined | null): 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) => TResult | PromiseLike): Promise; -} - -interface PromiseConstructor { - /** - * 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, - * 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 - * 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 Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(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; - - /** - * 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; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/** + * Represents the completion of an asynchronous operation + */ +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) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, 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. + * @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) | undefined | null): 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 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) | undefined | null): 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) => TResult | PromiseLike): Promise; +} + +interface PromiseConstructor { + /** + * 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, + * 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 + * 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 Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(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; + + /** + * 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; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + declare var Promise: PromiseConstructor; \ No newline at end of file diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index 3908e97c17c..d935cdf9781 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -1,38 +1,42 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface ProxyHandler { - getPrototypeOf? (target: T): any; - setPrototypeOf? (target: T, v: any): boolean; - isExtensible? (target: T): boolean; - preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; - has? (target: T, p: PropertyKey): boolean; - get? (target: T, p: PropertyKey, receiver: any): any; - set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; - deleteProperty? (target: T, p: PropertyKey): boolean; - defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; - enumerate? (target: T): PropertyKey[]; - ownKeys? (target: T): PropertyKey[]; - apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, thisArg: any, argArray?: any): any; -} - -interface ProxyConstructor { - revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; - new (target: T, handler: ProxyHandler): T -} -declare var Proxy: ProxyConstructor; \ No newline at end of file +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ProxyHandler { + getPrototypeOf? (target: T): {} | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): {}; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T +} +declare var Proxy: ProxyConstructor; diff --git a/lib/lib.es2015.reflect.d.ts b/lib/lib.es2015.reflect.d.ts index 0f1a491ebcf..53a087143c9 100644 --- a/lib/lib.es2015.reflect.d.ts +++ b/lib/lib.es2015.reflect.d.ts @@ -1,31 +1,35 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; - function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; - function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; - function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: any, proto: any): boolean; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; } \ No newline at end of file diff --git a/lib/lib.es2015.symbol.d.ts b/lib/lib.es2015.symbol.d.ts index 4ab7b4374f1..3776a44670d 100644 --- a/lib/lib.es2015.symbol.d.ts +++ b/lib/lib.es2015.symbol.d.ts @@ -1,52 +1,56 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; -} - -interface SymbolConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string|number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string | undefined; -} - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + declare var Symbol: SymbolConstructor; \ No newline at end of file diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 2d122d1284e..e95f324131a 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -1,343 +1,347 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// - -interface SymbolConstructor { - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - readonly hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - readonly isConcatSpreadable: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - readonly match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - readonly replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - readonly search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - readonly species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - readonly split: symbol; - - /** - * A method that converts an object to a corresponding primitive value. - * Called by the ToPrimitive abstract operation. - */ - readonly toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the 'with' - * environment bindings of the associated objects. - */ - readonly unscopables: symbol; -} - -interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; -} - -interface Array { - /** - * Returns an object whose properties have the value 'true' - * when they will be absent when used in a 'with' statement. - */ - [Symbol.unscopables](): { - copyWithin: boolean; - entries: boolean; - fill: boolean; - find: boolean; - findIndex: boolean; - keys: boolean; - values: boolean; - }; -} - -interface Date { - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "default"): string; - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "string"): string; - /** - * Converts a Date object to a number. - */ - [Symbol.toPrimitive](hint: "number"): number; - /** - * Converts a Date object to a string or number. - * - * @param hint The strings "number", "string", or "default" to specify what primitive to return. - * - * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". - * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". - */ - [Symbol.toPrimitive](hint: string): string | number; -} - -interface Map { - readonly [Symbol.toStringTag]: "Map"; -} - -interface WeakMap{ - readonly [Symbol.toStringTag]: "WeakMap"; -} - -interface Set { - readonly [Symbol.toStringTag]: "Set"; -} - -interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; -} - -interface JSON { - readonly [Symbol.toStringTag]: "JSON"; -} - -interface Function { - /** - * Determines whether the given value inherits from this function if this function was used - * as a constructor function. - * - * A constructor function can control which objects are recognized as its instances by - * 'instanceof' by overriding this method. - */ - [Symbol.hasInstance](value: any): boolean; -} - -interface GeneratorFunction extends Function { - readonly [Symbol.toStringTag]: "GeneratorFunction"; -} - -interface Math { - readonly [Symbol.toStringTag]: "Math"; -} - -interface Promise { - readonly [Symbol.toStringTag]: "Promise"; -} - -interface PromiseConstructor { - readonly [Symbol.species]: Function; -} - -interface RegExp { - /** - * Matches a string with this regular expression, and returns an array containing the results of - * that search. - * @param string A string to search within. - */ - [Symbol.match](string: string): RegExpMatchArray | null; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replaceValue A String object or string literal containing the text to replace for every - * successful match of this regular expression. - */ - [Symbol.replace](string: string, replaceValue: string): string; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replacer A function that returns the replacement text. - */ - [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the position beginning first substring match in a regular expression search - * using this regular expression. - * - * @param string The string to search within. - */ - [Symbol.search](string: string): number; - - /** - * Returns an array of substrings that were delimited by strings in the original input that - * match against this regular expression. - * - * If the regular expression contains capturing parentheses, then each time this - * regular expression matches, the results (including any undefined results) of the - * capturing parentheses are spliced. - * - * @param string string value to split - * @param limit if not undefined, the output array is truncated so that it contains no more - * than 'limit' elements. - */ - [Symbol.split](string: string, limit?: number): string[]; -} - -interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; -} - -interface String { - /** - * Matches a string an object that supports being matched against, and returns an array containing the results of that search. - * @param matcher An object that supports being matched against. - */ - match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param searcher An object which supports searching within a string. - */ - search(searcher: { [Symbol.search](string: string): number; }): number; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param splitter An object that can split a string. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; -} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; -} - -interface DataView { - readonly [Symbol.toStringTag]: "DataView"; -} - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - readonly [Symbol.toStringTag]: "Int8Array"; -} - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; -} - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - readonly [Symbol.toStringTag]: "Uint8ClampedArray"; -} - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - readonly [Symbol.toStringTag]: "Int16Array"; -} - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - readonly [Symbol.toStringTag]: "Uint16Array"; -} - -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - readonly [Symbol.toStringTag]: "Int32Array"; -} - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - readonly [Symbol.toStringTag]: "Uint32Array"; -} - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - readonly [Symbol.toStringTag]: "Float32Array"; -} - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - readonly [Symbol.toStringTag]: "Float64Array"; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction extends Function { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; } \ No newline at end of file diff --git a/lib/lib.es2016.array.include.d.ts b/lib/lib.es2016.array.include.d.ts index a4677e7cf1e..f2e80297db0 100644 --- a/lib/lib.es2016.array.include.d.ts +++ b/lib/lib.es2016.array.include.d.ts @@ -1,105 +1,118 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: T, fromIndex?: number): boolean; -} - -interface Int8Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Uint8Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Uint8ClampedArray { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Int16Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Uint16Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Int32Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Uint32Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Float32Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -interface Float64Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface ReadonlyArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface Int8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8ClampedArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float64Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; } \ No newline at end of file diff --git a/lib/lib.es2016.d.ts b/lib/lib.es2016.d.ts index 04a23379676..50fdffa8592 100644 --- a/lib/lib.es2016.d.ts +++ b/lib/lib.es2016.d.ts @@ -1,18 +1,22 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// /// \ No newline at end of file diff --git a/lib/lib.es2017.d.ts b/lib/lib.es2017.d.ts index 24d23994d96..91d11bcf301 100644 --- a/lib/lib.es2017.d.ts +++ b/lib/lib.es2017.d.ts @@ -1,19 +1,24 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// -/// -/// \ No newline at end of file +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index ac3a16ab370..2e4e673d060 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -1,30 +1,45 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -interface ObjectConstructor { - /** - * Returns an array of values of the enumerable properties of an object - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - values(o: { [s: string]: T }): T[]; - values(o: any): any[]; - /** - * Returns an array of key/values of the enumerable properties of an object - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - entries(o: { [s: string]: T }): [string, T][]; - entries(o: any): [string, any][]; -} \ No newline at end of file +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ObjectConstructor { + /** + * Returns an array of values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: { [s: string]: T }): T[]; + + /** + * Returns an array of values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: any): any[]; + + /** + * Returns an array of key/values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: { [s: string]: T }): [string, T][]; + + /** + * Returns an array of key/values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: any): [string, any][]; +} diff --git a/lib/lib.es2017.sharedmemory.d.ts b/lib/lib.es2017.sharedmemory.d.ts index 639ca7530e4..656caaefee7 100644 --- a/lib/lib.es2017.sharedmemory.d.ts +++ b/lib/lib.es2017.sharedmemory.d.ts @@ -1,43 +1,47 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -/// -/// - -interface SharedArrayBuffer { - /** - * Read-only. The length of the ArrayBuffer (in bytes). - */ - readonly byteLength: number; - - /* - * The SharedArrayBuffer constructor's length property whose value is 1. - */ - length: number; - /** - * Returns a section of an SharedArrayBuffer. - */ - slice(begin:number, end?:number): SharedArrayBuffer; - readonly [Symbol.species]: SharedArrayBuffer; - readonly [Symbol.toStringTag]: "SharedArrayBuffer"; -} - -interface SharedArrayBufferConstructor { - readonly prototype: SharedArrayBuffer; - new (byteLength: number): SharedArrayBuffer; -} - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// + +interface SharedArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /* + * The SharedArrayBuffer constructor's length property whose value is 1. + */ + length: number; + /** + * Returns a section of an SharedArrayBuffer. + */ + slice(begin:number, end?:number): SharedArrayBuffer; + readonly [Symbol.species]: SharedArrayBuffer; + readonly [Symbol.toStringTag]: "SharedArrayBuffer"; +} + +interface SharedArrayBufferConstructor { + readonly prototype: SharedArrayBuffer; + new (byteLength: number): SharedArrayBuffer; +} + declare var SharedArrayBuffer: SharedArrayBufferConstructor; \ No newline at end of file diff --git a/lib/lib.es2017.string.d.ts b/lib/lib.es2017.string.d.ts new file mode 100644 index 00000000000..303c4644b96 --- /dev/null +++ b/lib/lib.es2017.string.d.ts @@ -0,0 +1,47 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface String { + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the start (left) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padStart(maxLength: number, fillString?: string): string; + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the end (right) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padEnd(maxLength: number, fillString?: string): string; +} diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 5df0d7d4068..4d48fed85ed 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1,4124 +1,4195 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -///////////////////////////// -/// ECMAScript APIs -///////////////////////////// - -declare const NaN: number; -declare const Infinity: number; - -/** - * Evaluates JavaScript code and executes it. - * @param x A String value that contains valid JavaScript code. - */ -declare function eval(x: string): any; - -/** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ -declare function parseInt(s: string, radix?: number): number; - -/** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ -declare function parseFloat(string: string): number; - -/** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). - * @param number A numeric value. - */ -declare function isNaN(number: number): boolean; - -/** - * Determines whether a supplied number is finite. - * @param number Any numeric value. - */ -declare function isFinite(number: number): boolean; - -/** - * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). - * @param encodedURI A value representing an encoded URI. - */ -declare function decodeURI(encodedURI: string): string; - -/** - * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). - * @param encodedURIComponent A value representing an encoded URI component. - */ -declare function decodeURIComponent(encodedURIComponent: string): string; - -/** - * Encodes a text string as a valid Uniform Resource Identifier (URI) - * @param uri A value representing an encoded URI. - */ -declare function encodeURI(uri: string): string; - -/** - * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). - * @param uriComponent A value representing an encoded URI component. - */ -declare function encodeURIComponent(uriComponent: string): string; - -interface PropertyDescriptor { - configurable?: boolean; - enumerable?: boolean; - value?: any; - writable?: boolean; - get? (): any; - set? (v: any): void; -} - -interface PropertyDescriptorMap { - [s: string]: PropertyDescriptor; -} - -interface Object { - /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ - constructor: Function; - - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns a date converted to a string using the current locale. */ - toLocaleString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; - - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: string): boolean; - - /** - * Determines whether an object exists in another object's prototype chain. - * @param v Another object whose prototype chain is to be checked. - */ - isPrototypeOf(v: Object): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: string): boolean; -} - -interface ObjectConstructor { - new (value?: any): Object; - (): any; - (value: any): any; - - /** A reference to the prototype for a class of objects. */ - readonly prototype: Object; - - /** - * Returns the prototype of an object. - * @param o The object that references the prototype. - */ - getPrototypeOf(o: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; - - /** - * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly - * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. - * @param o Object that contains the own properties. - */ - getOwnPropertyNames(o: any): string[]; - - /** - * Creates an object that has null prototype. - * @param o Object to use as a prototype. May be null - */ - create(o: null): any; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - */ - create(o: T): T; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - * @param properties JavaScript object that contains one or more property descriptors. - */ - create(o: any, properties: PropertyDescriptorMap): any; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor property. - */ - defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; - - /** - * Adds one or more properties to an object, and/or modifies attributes of existing properties. - * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. - * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. - */ - defineProperties(o: any, properties: PropertyDescriptorMap): any; - - /** - * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - seal(o: T): T; - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(o: T): T; - - /** - * Prevents the addition of new properties to an object. - * @param o Object to make non-extensible. - */ - preventExtensions(o: T): T; - - /** - * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. - * @param o Object to test. - */ - isSealed(o: any): boolean; - - /** - * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. - * @param o Object to test. - */ - isFrozen(o: any): boolean; - - /** - * Returns a value that indicates whether new properties can be added to an object. - * @param o Object to test. - */ - isExtensible(o: any): boolean; - - /** - * Returns the names of the enumerable properties and methods of an object. - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - keys(o: any): string[]; -} - -/** - * Provides functionality common to all JavaScript objects. - */ -declare const Object: ObjectConstructor; - -/** - * Creates a new function. - */ -interface Function { - /** - * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. - * @param thisArg The object to be used as the this object. - * @param argArray A set of arguments to be passed to the function. - */ - apply(this: Function, thisArg: any, argArray?: any): any; - - /** - * Calls a method of an object, substituting another object for the current object. - * @param thisArg The object to be used as the current object. - * @param argArray A list of arguments to be passed to the method. - */ - call(this: Function, thisArg: any, ...argArray: any[]): any; - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg An object to which the this keyword can refer inside the new function. - * @param argArray A list of arguments to be passed to the new function. - */ - bind(this: Function, thisArg: any, ...argArray: any[]): any; - - prototype: any; - readonly length: number; - - // Non-standard extensions - arguments: any; - caller: Function; -} - -interface FunctionConstructor { - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - readonly prototype: Function; -} - -declare const Function: FunctionConstructor; - -interface IArguments { - [index: number]: any; - length: number; - callee: Function; -} - -interface String { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): RegExpMatchArray | null; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): RegExpMatchArray | null; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Removes the leading and trailing white space and line terminator characters from a string. */ - trim(): string; - - /** Returns the length of a String object. */ - readonly length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): string; - - readonly [index: number]: string; -} - -interface StringConstructor { - new (value?: any): String; - (value?: any): string; - readonly prototype: String; - fromCharCode(...codes: number[]): string; -} - -/** - * Allows manipulation and formatting of text strings and determination and location of substrings within strings. - */ -declare const String: StringConstructor; - -interface Boolean { - /** Returns the primitive value of the specified object. */ - valueOf(): boolean; -} - -interface BooleanConstructor { - new (value?: any): Boolean; - (value?: any): boolean; - readonly prototype: Boolean; -} - -declare const Boolean: BooleanConstructor; - -interface Number { - /** - * Returns a string representation of an object. - * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. - */ - toString(radix?: number): string; - - /** - * Returns a string representing a number in fixed-point notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toFixed(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented in exponential notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toExponential(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. - * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. - */ - toPrecision(precision?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): number; -} - -interface NumberConstructor { - new (value?: any): Number; - (value?: any): number; - readonly prototype: Number; - - /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - readonly MAX_VALUE: number; - - /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - readonly MIN_VALUE: number; - - /** - * A value that is not a number. - * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. - */ - readonly NaN: number; - - /** - * A value that is less than the largest negative number that can be represented in JavaScript. - * JavaScript displays NEGATIVE_INFINITY values as -infinity. - */ - readonly NEGATIVE_INFINITY: number; - - /** - * A value greater than the largest number that can be represented in JavaScript. - * JavaScript displays POSITIVE_INFINITY values as infinity. - */ - readonly POSITIVE_INFINITY: number; -} - -/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare const Number: NumberConstructor; - -interface TemplateStringsArray extends ReadonlyArray { - readonly raw: ReadonlyArray -} - -interface Math { - /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - readonly E: number; - /** The natural logarithm of 10. */ - readonly LN10: number; - /** The natural logarithm of 2. */ - readonly LN2: number; - /** The base-2 logarithm of e. */ - readonly LOG2E: number; - /** The base-10 logarithm of e. */ - readonly LOG10E: number; - /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - readonly PI: number; - /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - readonly SQRT1_2: number; - /** The square root of 2. */ - readonly SQRT2: number; - /** - * Returns the absolute value of a number (the value without regard to whether it is positive or negative). - * For example, the absolute value of -5 is the same as the absolute value of 5. - * @param x A numeric expression for which the absolute value is needed. - */ - abs(x: number): number; - /** - * Returns the arc cosine (or inverse cosine) of a number. - * @param x A numeric expression. - */ - acos(x: number): number; - /** - * Returns the arcsine of a number. - * @param x A numeric expression. - */ - asin(x: number): number; - /** - * Returns the arctangent of a number. - * @param x A numeric expression for which the arctangent is needed. - */ - atan(x: number): number; - /** - * Returns the angle (in radians) from the X axis to a point. - * @param y A numeric expression representing the cartesian y-coordinate. - * @param x A numeric expression representing the cartesian x-coordinate. - */ - atan2(y: number, x: number): number; - /** - * Returns the smallest number greater than or equal to its numeric argument. - * @param x A numeric expression. - */ - ceil(x: number): number; - /** - * Returns the cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cos(x: number): number; - /** - * Returns e (the base of natural logarithms) raised to a power. - * @param x A numeric expression representing the power of e. - */ - exp(x: number): number; - /** - * Returns the greatest number less than or equal to its numeric argument. - * @param x A numeric expression. - */ - floor(x: number): number; - /** - * Returns the natural logarithm (base e) of a number. - * @param x A numeric expression. - */ - log(x: number): number; - /** - * Returns the larger of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - max(...values: number[]): number; - /** - * Returns the smaller of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - min(...values: number[]): number; - /** - * Returns the value of a base expression taken to a specified power. - * @param x The base value of the expression. - * @param y The exponent value of the expression. - */ - pow(x: number, y: number): number; - /** Returns a pseudorandom number between 0 and 1. */ - random(): number; - /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. - */ - round(x: number): number; - /** - * Returns the sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sin(x: number): number; - /** - * Returns the square root of a number. - * @param x A numeric expression. - */ - sqrt(x: number): number; - /** - * Returns the tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tan(x: number): number; -} -/** An intrinsic object that provides basic mathematics functionality and constants. */ -declare const Math: Math; - -/** Enables basic storage and retrieval of dates and times. */ -interface Date { - /** Returns a string representation of a date. The format of the string depends on the locale. */ - toString(): string; - /** Returns a date as a string value. */ - toDateString(): string; - /** Returns a time as a string value. */ - toTimeString(): string; - /** Returns a value as a string value appropriate to the host environment's current locale. */ - toLocaleString(): string; - /** Returns a date as a string value appropriate to the host environment's current locale. */ - toLocaleDateString(): string; - /** Returns a time as a string value appropriate to the host environment's current locale. */ - toLocaleTimeString(): string; - /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ - valueOf(): number; - /** Gets the time value in milliseconds. */ - getTime(): number; - /** Gets the year, using local time. */ - getFullYear(): number; - /** Gets the year using Universal Coordinated Time (UTC). */ - getUTCFullYear(): number; - /** Gets the month, using local time. */ - getMonth(): number; - /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ - getUTCMonth(): number; - /** Gets the day-of-the-month, using local time. */ - getDate(): number; - /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ - getUTCDate(): number; - /** Gets the day of the week, using local time. */ - getDay(): number; - /** Gets the day of the week using Universal Coordinated Time (UTC). */ - getUTCDay(): number; - /** Gets the hours in a date, using local time. */ - getHours(): number; - /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ - getUTCHours(): number; - /** Gets the minutes of a Date object, using local time. */ - getMinutes(): number; - /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ - getUTCMinutes(): number; - /** Gets the seconds of a Date object, using local time. */ - getSeconds(): number; - /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCSeconds(): number; - /** Gets the milliseconds of a Date, using local time. */ - getMilliseconds(): number; - /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCMilliseconds(): number; - /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ - getTimezoneOffset(): number; - /** - * Sets the date and time value in the Date object. - * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. - */ - setTime(time: number): number; - /** - * Sets the milliseconds value in the Date object using local time. - * @param ms A numeric value equal to the millisecond value. - */ - setMilliseconds(ms: number): number; - /** - * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). - * @param ms A numeric value equal to the millisecond value. - */ - setUTCMilliseconds(ms: number): number; - - /** - * Sets the seconds value in the Date object using local time. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setSeconds(sec: number, ms?: number): number; - /** - * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCSeconds(sec: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using local time. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the hour value in the Date object using local time. - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the hours value in the Date object using Universal Coordinated Time (UTC). - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the numeric day-of-the-month value of the Date object using local time. - * @param date A numeric value equal to the day of the month. - */ - setDate(date: number): number; - /** - * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). - * @param date A numeric value equal to the day of the month. - */ - setUTCDate(date: number): number; - /** - * Sets the month value in the Date object using local time. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. - */ - setMonth(month: number, date?: number): number; - /** - * Sets the month value in the Date object using Universal Coordinated Time (UTC). - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. - */ - setUTCMonth(month: number, date?: number): number; - /** - * Sets the year of the Date object using local time. - * @param year A numeric value for the year. - * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. - * @param date A numeric value equal for the day of the month. - */ - setFullYear(year: number, month?: number, date?: number): number; - /** - * Sets the year value in the Date object using Universal Coordinated Time (UTC). - * @param year A numeric value equal to the year. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. - * @param date A numeric value equal to the day of the month. - */ - setUTCFullYear(year: number, month?: number, date?: number): number; - /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ - toUTCString(): string; - /** Returns a date as a string value in ISO format. */ - toISOString(): string; - /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ - toJSON(key?: any): string; -} - -interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; - (): string; - readonly prototype: Date; - /** - * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. - * @param s A date string - */ - parse(s: string): number; - /** - * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. - * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. - */ - UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; - now(): number; -} - -declare const Date: DateConstructor; - -interface RegExpMatchArray extends Array { - index?: number; - input?: string; -} - -interface RegExpExecArray extends Array { - index: number; - input: string; -} - -interface RegExp { - /** - * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. - * @param string The String object or string literal on which to perform the search. - */ - exec(string: string): RegExpExecArray | null; - - /** - * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. - * @param string String on which to perform the search. - */ - test(string: string): boolean; - - /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - readonly source: string; - - /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - readonly global: boolean; - - /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - readonly ignoreCase: boolean; - - /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - readonly multiline: boolean; - - lastIndex: number; - - // Non-standard extensions - compile(): this; -} - -interface RegExpConstructor { - new (pattern: RegExp): RegExp; - new (pattern: string, flags?: string): RegExp; - (pattern: RegExp): RegExp; - (pattern: string, flags?: string): RegExp; - readonly prototype: RegExp; - - // Non-standard extensions - $1: string; - $2: string; - $3: string; - $4: string; - $5: string; - $6: string; - $7: string; - $8: string; - $9: string; - lastMatch: string; -} - -declare const RegExp: RegExpConstructor; - -interface Error { - name: string; - message: string; - stack?: string; -} - -interface ErrorConstructor { - new (message?: string): Error; - (message?: string): Error; - readonly prototype: Error; -} - -declare const Error: ErrorConstructor; - -interface EvalError extends Error { -} - -interface EvalErrorConstructor { - new (message?: string): EvalError; - (message?: string): EvalError; - readonly prototype: EvalError; -} - -declare const EvalError: EvalErrorConstructor; - -interface RangeError extends Error { -} - -interface RangeErrorConstructor { - new (message?: string): RangeError; - (message?: string): RangeError; - readonly prototype: RangeError; -} - -declare const RangeError: RangeErrorConstructor; - -interface ReferenceError extends Error { -} - -interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; - (message?: string): ReferenceError; - readonly prototype: ReferenceError; -} - -declare const ReferenceError: ReferenceErrorConstructor; - -interface SyntaxError extends Error { -} - -interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; - (message?: string): SyntaxError; - readonly prototype: SyntaxError; -} - -declare const SyntaxError: SyntaxErrorConstructor; - -interface TypeError extends Error { -} - -interface TypeErrorConstructor { - new (message?: string): TypeError; - (message?: string): TypeError; - readonly prototype: TypeError; -} - -declare const TypeError: TypeErrorConstructor; - -interface URIError extends Error { -} - -interface URIErrorConstructor { - new (message?: string): URIError; - (message?: string): URIError; - readonly prototype: URIError; -} - -declare const URIError: URIErrorConstructor; - -interface JSON { - /** - * Converts a JavaScript Object Notation (JSON) string into an object. - * @param text A valid JSON string. - * @param reviver A function that transforms the results. This function is called for each member of the object. - * If a member contains nested objects, the nested objects are transformed before the parent object is. - */ - parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; -} - -/** - * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. - */ -declare const JSON: JSON; - - -///////////////////////////// -/// ECMAScript Array API (specially handled by compiler) -///////////////////////////// - -interface ReadonlyArray { - /** - * Gets the length of the array. This is a number one higher than the highest element defined in an array. - */ - readonly length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat>(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - - readonly [n: number]: T; -} - -interface Array { - /** - * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - */ - length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Appends new elements to an array, and returns the new length of the array. - * @param items New elements of the Array. - */ - push(...items: T[]): number; - /** - * Removes the last element from an array and returns it. - */ - pop(): T | undefined; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Reverses the elements in an Array. - */ - reverse(): T[]; - /** - * Removes the first element from an array and returns it. - */ - shift(): T | undefined; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: T, b: T) => number): this; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - */ - splice(start: number): T[]; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** - * Inserts new elements at the start of an array. - * @param items Elements to insert at the start of the Array. - */ - unshift(...items: T[]): number; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - [n: number]: T; -} - -interface ArrayConstructor { - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): arg is Array; - readonly prototype: Array; -} - -declare const Array: ArrayConstructor; - -interface TypedPropertyDescriptor { - enumerable?: boolean; - configurable?: boolean; - writable?: boolean; - value?: T; - get?: () => T; - set?: (value: T) => void; -} - -declare type ClassDecorator = (target: TFunction) => TFunction | void; -declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; -declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; -declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; - -declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; - -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) => T | PromiseLike) | undefined | null, - onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, - 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. - * @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) | undefined | null): 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; -} - -interface ArrayLike { - readonly length: number; - readonly [n: number]: T; -} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - /** - * Read-only. The length of the ArrayBuffer (in bytes). - */ - readonly byteLength: number; - - /** - * Returns a section of an ArrayBuffer. - */ - slice(begin:number, end?:number): ArrayBuffer; -} - -interface ArrayBufferConstructor { - readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; - isView(arg: any): arg is ArrayBufferView; -} -declare const ArrayBuffer: ArrayBufferConstructor; - -interface ArrayBufferView { - /** - * The ArrayBuffer instance referenced by the array. - */ - buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - byteLength: number; - - /** - * The offset in bytes of the array. - */ - byteOffset: number; -} - -interface DataView { - readonly buffer: ArrayBuffer; - readonly byteLength: number; - readonly byteOffset: number; - /** - * Gets the Float32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Float64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat64(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Int8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt8(byteOffset: number): number; - - /** - * Gets the Int16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt16(byteOffset: number, littleEndian?: boolean): number; - /** - * Gets the Int32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint8(byteOffset: number): number; - - /** - * Gets the Uint16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint16(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Stores an Float32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Float64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setInt8(byteOffset: number, value: number): void; - - /** - * Stores an Int16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setUint8(byteOffset: number, value: number): void; - - /** - * Stores an Uint16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; -} - -interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; -} -declare const DataView: DataViewConstructor; - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} -interface Int8ArrayConstructor { - readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - -} -declare const Int8Array: Int8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ArrayConstructor { - readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; - -} -declare const Uint8Array: Uint8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8ClampedArray; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: Uint8ClampedArray, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8ClampedArray; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8ClampedArray; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ClampedArrayConstructor { - readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8ClampedArray; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} -declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int16ArrayConstructor { - readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - -} -declare const Int16Array: Int16ArrayConstructor; - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint16ArrayConstructor { - readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - -} -declare const Uint16Array: Uint16ArrayConstructor; -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int32ArrayConstructor { - readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} -declare const Int32Array: Int32ArrayConstructor; - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint32ArrayConstructor { - readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} -declare const Uint32Array: Uint32ArrayConstructor; - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float32ArrayConstructor { - readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - -} -declare const Float32Array: Float32ArrayConstructor; - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float64Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float64Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float64Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float64ArrayConstructor { - readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} -declare const Float64Array: Float64ArrayConstructor; - -///////////////////////////// -/// ECMAScript Internationalization API -///////////////////////////// - -declare module Intl { - interface CollatorOptions { - usage?: string; - localeMatcher?: string; - numeric?: boolean; - caseFirst?: string; - sensitivity?: string; - ignorePunctuation?: boolean; - } - - interface ResolvedCollatorOptions { - locale: string; - usage: string; - sensitivity: string; - ignorePunctuation: boolean; - collation: string; - caseFirst: string; - numeric: boolean; - } - - interface Collator { - compare(x: string, y: string): number; - resolvedOptions(): ResolvedCollatorOptions; - } - var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; - (locales?: string | string[], options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; - } - - interface NumberFormatOptions { - localeMatcher?: string; - style?: string; - currency?: string; - currencyDisplay?: string; - useGrouping?: boolean; - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - } - - interface ResolvedNumberFormatOptions { - locale: string; - numberingSystem: string; - style: string; - currency?: string; - currencyDisplay?: string; - minimumIntegerDigits: number; - minimumFractionDigits: number; - maximumFractionDigits: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - useGrouping: boolean; - } - - interface NumberFormat { - format(value: number): string; - resolvedOptions(): ResolvedNumberFormatOptions; - } - var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; - } - - interface DateTimeFormatOptions { - localeMatcher?: string; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - formatMatcher?: string; - hour12?: boolean; - timeZone?: string; - } - - interface ResolvedDateTimeFormatOptions { - locale: string; - calendar: string; - numberingSystem: string; - timeZone: string; - hour12?: boolean; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - } - - interface DateTimeFormat { - format(date?: Date | number): string; - resolvedOptions(): ResolvedDateTimeFormatOptions; - } - var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; - } -} - -interface String { - /** - * Determines whether two strings are equivalent in the current or specified locale. - * @param that String to compare to target string - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; -} - -interface Number { - /** - * Converts a number to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; -} - -interface Date { - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - /** - * Converts a date to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has null prototype. + * @param o Object to use as a prototype. May be null + */ + create(o: null): any; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + */ + create(o: T): T; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(a: T[]): ReadonlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(this: Function, thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(this: Function, thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(this: Function, thisArg: any, ...argArray: any[]): any; + + /** Returns a string representation of a function. */ + toString(): string; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): RegExpMatchArray | null; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): RegExpMatchArray | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new (value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new (value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new (value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest number greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest number less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray | null; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): this; +} + +interface RegExpConstructor { + new (pattern: RegExp): RegExp; + new (pattern: string, flags?: string): RegExp; + (pattern: RegExp): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; + stack?: string; +} + +interface ErrorConstructor { + new (message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new (message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new (message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new (message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new (message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T | undefined; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): this; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +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) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, + 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. + * @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) | undefined | null): 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; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T pick a set of properties K + */ +type Pick = { + [P in K]: T[P]; +} + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8ClampedArray, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} +declare const Float64Array: Float64ArrayConstructor; + +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare module Intl { + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12?: boolean; + timeZone?: string; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; + } +} + +interface String { + /** + * Determines whether two strings are equivalent in the current or specified locale. + * @param that String to compare to target string + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; +} + +interface Number { + /** + * Converts a number to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; +} + +interface Date { + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + /** + * Converts a date to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; +} diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index f6c7766ea9f..9530bf7bfbc 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1,20759 +1,19950 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// -///////////////////////////// -/// ECMAScript APIs -///////////////////////////// - -declare const NaN: number; -declare const Infinity: number; - -/** - * Evaluates JavaScript code and executes it. - * @param x A String value that contains valid JavaScript code. - */ -declare function eval(x: string): any; - -/** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ -declare function parseInt(s: string, radix?: number): number; - -/** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ -declare function parseFloat(string: string): number; - -/** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). - * @param number A numeric value. - */ -declare function isNaN(number: number): boolean; - -/** - * Determines whether a supplied number is finite. - * @param number Any numeric value. - */ -declare function isFinite(number: number): boolean; - -/** - * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). - * @param encodedURI A value representing an encoded URI. - */ -declare function decodeURI(encodedURI: string): string; - -/** - * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). - * @param encodedURIComponent A value representing an encoded URI component. - */ -declare function decodeURIComponent(encodedURIComponent: string): string; - -/** - * Encodes a text string as a valid Uniform Resource Identifier (URI) - * @param uri A value representing an encoded URI. - */ -declare function encodeURI(uri: string): string; - -/** - * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). - * @param uriComponent A value representing an encoded URI component. - */ -declare function encodeURIComponent(uriComponent: string): string; - -interface PropertyDescriptor { - configurable?: boolean; - enumerable?: boolean; - value?: any; - writable?: boolean; - get? (): any; - set? (v: any): void; -} - -interface PropertyDescriptorMap { - [s: string]: PropertyDescriptor; -} - -interface Object { - /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ - constructor: Function; - - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns a date converted to a string using the current locale. */ - toLocaleString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; - - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: string): boolean; - - /** - * Determines whether an object exists in another object's prototype chain. - * @param v Another object whose prototype chain is to be checked. - */ - isPrototypeOf(v: Object): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: string): boolean; -} - -interface ObjectConstructor { - new (value?: any): Object; - (): any; - (value: any): any; - - /** A reference to the prototype for a class of objects. */ - readonly prototype: Object; - - /** - * Returns the prototype of an object. - * @param o The object that references the prototype. - */ - getPrototypeOf(o: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; - - /** - * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly - * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. - * @param o Object that contains the own properties. - */ - getOwnPropertyNames(o: any): string[]; - - /** - * Creates an object that has null prototype. - * @param o Object to use as a prototype. May be null - */ - create(o: null): any; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - */ - create(o: T): T; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - * @param properties JavaScript object that contains one or more property descriptors. - */ - create(o: any, properties: PropertyDescriptorMap): any; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor property. - */ - defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; - - /** - * Adds one or more properties to an object, and/or modifies attributes of existing properties. - * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. - * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. - */ - defineProperties(o: any, properties: PropertyDescriptorMap): any; - - /** - * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - seal(o: T): T; - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(o: T): T; - - /** - * Prevents the addition of new properties to an object. - * @param o Object to make non-extensible. - */ - preventExtensions(o: T): T; - - /** - * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. - * @param o Object to test. - */ - isSealed(o: any): boolean; - - /** - * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. - * @param o Object to test. - */ - isFrozen(o: any): boolean; - - /** - * Returns a value that indicates whether new properties can be added to an object. - * @param o Object to test. - */ - isExtensible(o: any): boolean; - - /** - * Returns the names of the enumerable properties and methods of an object. - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - keys(o: any): string[]; -} - -/** - * Provides functionality common to all JavaScript objects. - */ -declare const Object: ObjectConstructor; - -/** - * Creates a new function. - */ -interface Function { - /** - * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. - * @param thisArg The object to be used as the this object. - * @param argArray A set of arguments to be passed to the function. - */ - apply(this: Function, thisArg: any, argArray?: any): any; - - /** - * Calls a method of an object, substituting another object for the current object. - * @param thisArg The object to be used as the current object. - * @param argArray A list of arguments to be passed to the method. - */ - call(this: Function, thisArg: any, ...argArray: any[]): any; - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg An object to which the this keyword can refer inside the new function. - * @param argArray A list of arguments to be passed to the new function. - */ - bind(this: Function, thisArg: any, ...argArray: any[]): any; - - prototype: any; - readonly length: number; - - // Non-standard extensions - arguments: any; - caller: Function; -} - -interface FunctionConstructor { - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - readonly prototype: Function; -} - -declare const Function: FunctionConstructor; - -interface IArguments { - [index: number]: any; - length: number; - callee: Function; -} - -interface String { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): RegExpMatchArray | null; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): RegExpMatchArray | null; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string that represents the regular expression. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Removes the leading and trailing white space and line terminator characters from a string. */ - trim(): string; - - /** Returns the length of a String object. */ - readonly length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): string; - - readonly [index: number]: string; -} - -interface StringConstructor { - new (value?: any): String; - (value?: any): string; - readonly prototype: String; - fromCharCode(...codes: number[]): string; -} - -/** - * Allows manipulation and formatting of text strings and determination and location of substrings within strings. - */ -declare const String: StringConstructor; - -interface Boolean { - /** Returns the primitive value of the specified object. */ - valueOf(): boolean; -} - -interface BooleanConstructor { - new (value?: any): Boolean; - (value?: any): boolean; - readonly prototype: Boolean; -} - -declare const Boolean: BooleanConstructor; - -interface Number { - /** - * Returns a string representation of an object. - * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. - */ - toString(radix?: number): string; - - /** - * Returns a string representing a number in fixed-point notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toFixed(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented in exponential notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toExponential(fractionDigits?: number): string; - - /** - * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. - * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. - */ - toPrecision(precision?: number): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): number; -} - -interface NumberConstructor { - new (value?: any): Number; - (value?: any): number; - readonly prototype: Number; - - /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - readonly MAX_VALUE: number; - - /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - readonly MIN_VALUE: number; - - /** - * A value that is not a number. - * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. - */ - readonly NaN: number; - - /** - * A value that is less than the largest negative number that can be represented in JavaScript. - * JavaScript displays NEGATIVE_INFINITY values as -infinity. - */ - readonly NEGATIVE_INFINITY: number; - - /** - * A value greater than the largest number that can be represented in JavaScript. - * JavaScript displays POSITIVE_INFINITY values as infinity. - */ - readonly POSITIVE_INFINITY: number; -} - -/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare const Number: NumberConstructor; - -interface TemplateStringsArray extends ReadonlyArray { - readonly raw: ReadonlyArray -} - -interface Math { - /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - readonly E: number; - /** The natural logarithm of 10. */ - readonly LN10: number; - /** The natural logarithm of 2. */ - readonly LN2: number; - /** The base-2 logarithm of e. */ - readonly LOG2E: number; - /** The base-10 logarithm of e. */ - readonly LOG10E: number; - /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - readonly PI: number; - /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - readonly SQRT1_2: number; - /** The square root of 2. */ - readonly SQRT2: number; - /** - * Returns the absolute value of a number (the value without regard to whether it is positive or negative). - * For example, the absolute value of -5 is the same as the absolute value of 5. - * @param x A numeric expression for which the absolute value is needed. - */ - abs(x: number): number; - /** - * Returns the arc cosine (or inverse cosine) of a number. - * @param x A numeric expression. - */ - acos(x: number): number; - /** - * Returns the arcsine of a number. - * @param x A numeric expression. - */ - asin(x: number): number; - /** - * Returns the arctangent of a number. - * @param x A numeric expression for which the arctangent is needed. - */ - atan(x: number): number; - /** - * Returns the angle (in radians) from the X axis to a point. - * @param y A numeric expression representing the cartesian y-coordinate. - * @param x A numeric expression representing the cartesian x-coordinate. - */ - atan2(y: number, x: number): number; - /** - * Returns the smallest number greater than or equal to its numeric argument. - * @param x A numeric expression. - */ - ceil(x: number): number; - /** - * Returns the cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cos(x: number): number; - /** - * Returns e (the base of natural logarithms) raised to a power. - * @param x A numeric expression representing the power of e. - */ - exp(x: number): number; - /** - * Returns the greatest number less than or equal to its numeric argument. - * @param x A numeric expression. - */ - floor(x: number): number; - /** - * Returns the natural logarithm (base e) of a number. - * @param x A numeric expression. - */ - log(x: number): number; - /** - * Returns the larger of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - max(...values: number[]): number; - /** - * Returns the smaller of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - min(...values: number[]): number; - /** - * Returns the value of a base expression taken to a specified power. - * @param x The base value of the expression. - * @param y The exponent value of the expression. - */ - pow(x: number, y: number): number; - /** Returns a pseudorandom number between 0 and 1. */ - random(): number; - /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. - */ - round(x: number): number; - /** - * Returns the sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sin(x: number): number; - /** - * Returns the square root of a number. - * @param x A numeric expression. - */ - sqrt(x: number): number; - /** - * Returns the tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tan(x: number): number; -} -/** An intrinsic object that provides basic mathematics functionality and constants. */ -declare const Math: Math; - -/** Enables basic storage and retrieval of dates and times. */ -interface Date { - /** Returns a string representation of a date. The format of the string depends on the locale. */ - toString(): string; - /** Returns a date as a string value. */ - toDateString(): string; - /** Returns a time as a string value. */ - toTimeString(): string; - /** Returns a value as a string value appropriate to the host environment's current locale. */ - toLocaleString(): string; - /** Returns a date as a string value appropriate to the host environment's current locale. */ - toLocaleDateString(): string; - /** Returns a time as a string value appropriate to the host environment's current locale. */ - toLocaleTimeString(): string; - /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ - valueOf(): number; - /** Gets the time value in milliseconds. */ - getTime(): number; - /** Gets the year, using local time. */ - getFullYear(): number; - /** Gets the year using Universal Coordinated Time (UTC). */ - getUTCFullYear(): number; - /** Gets the month, using local time. */ - getMonth(): number; - /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ - getUTCMonth(): number; - /** Gets the day-of-the-month, using local time. */ - getDate(): number; - /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ - getUTCDate(): number; - /** Gets the day of the week, using local time. */ - getDay(): number; - /** Gets the day of the week using Universal Coordinated Time (UTC). */ - getUTCDay(): number; - /** Gets the hours in a date, using local time. */ - getHours(): number; - /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ - getUTCHours(): number; - /** Gets the minutes of a Date object, using local time. */ - getMinutes(): number; - /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ - getUTCMinutes(): number; - /** Gets the seconds of a Date object, using local time. */ - getSeconds(): number; - /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCSeconds(): number; - /** Gets the milliseconds of a Date, using local time. */ - getMilliseconds(): number; - /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCMilliseconds(): number; - /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ - getTimezoneOffset(): number; - /** - * Sets the date and time value in the Date object. - * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. - */ - setTime(time: number): number; - /** - * Sets the milliseconds value in the Date object using local time. - * @param ms A numeric value equal to the millisecond value. - */ - setMilliseconds(ms: number): number; - /** - * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). - * @param ms A numeric value equal to the millisecond value. - */ - setUTCMilliseconds(ms: number): number; - - /** - * Sets the seconds value in the Date object using local time. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setSeconds(sec: number, ms?: number): number; - /** - * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCSeconds(sec: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using local time. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCMinutes(min: number, sec?: number, ms?: number): number; - /** - * Sets the hour value in the Date object using local time. - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the hours value in the Date object using Universal Coordinated Time (UTC). - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; - /** - * Sets the numeric day-of-the-month value of the Date object using local time. - * @param date A numeric value equal to the day of the month. - */ - setDate(date: number): number; - /** - * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). - * @param date A numeric value equal to the day of the month. - */ - setUTCDate(date: number): number; - /** - * Sets the month value in the Date object using local time. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. - */ - setMonth(month: number, date?: number): number; - /** - * Sets the month value in the Date object using Universal Coordinated Time (UTC). - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. - */ - setUTCMonth(month: number, date?: number): number; - /** - * Sets the year of the Date object using local time. - * @param year A numeric value for the year. - * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. - * @param date A numeric value equal for the day of the month. - */ - setFullYear(year: number, month?: number, date?: number): number; - /** - * Sets the year value in the Date object using Universal Coordinated Time (UTC). - * @param year A numeric value equal to the year. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. - * @param date A numeric value equal to the day of the month. - */ - setUTCFullYear(year: number, month?: number, date?: number): number; - /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ - toUTCString(): string; - /** Returns a date as a string value in ISO format. */ - toISOString(): string; - /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ - toJSON(key?: any): string; -} - -interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; - (): string; - readonly prototype: Date; - /** - * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. - * @param s A date string - */ - parse(s: string): number; - /** - * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. - * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. - */ - UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; - now(): number; -} - -declare const Date: DateConstructor; - -interface RegExpMatchArray extends Array { - index?: number; - input?: string; -} - -interface RegExpExecArray extends Array { - index: number; - input: string; -} - -interface RegExp { - /** - * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. - * @param string The String object or string literal on which to perform the search. - */ - exec(string: string): RegExpExecArray | null; - - /** - * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. - * @param string String on which to perform the search. - */ - test(string: string): boolean; - - /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - readonly source: string; - - /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - readonly global: boolean; - - /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - readonly ignoreCase: boolean; - - /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - readonly multiline: boolean; - - lastIndex: number; - - // Non-standard extensions - compile(): this; -} - -interface RegExpConstructor { - new (pattern: RegExp): RegExp; - new (pattern: string, flags?: string): RegExp; - (pattern: RegExp): RegExp; - (pattern: string, flags?: string): RegExp; - readonly prototype: RegExp; - - // Non-standard extensions - $1: string; - $2: string; - $3: string; - $4: string; - $5: string; - $6: string; - $7: string; - $8: string; - $9: string; - lastMatch: string; -} - -declare const RegExp: RegExpConstructor; - -interface Error { - name: string; - message: string; - stack?: string; -} - -interface ErrorConstructor { - new (message?: string): Error; - (message?: string): Error; - readonly prototype: Error; -} - -declare const Error: ErrorConstructor; - -interface EvalError extends Error { -} - -interface EvalErrorConstructor { - new (message?: string): EvalError; - (message?: string): EvalError; - readonly prototype: EvalError; -} - -declare const EvalError: EvalErrorConstructor; - -interface RangeError extends Error { -} - -interface RangeErrorConstructor { - new (message?: string): RangeError; - (message?: string): RangeError; - readonly prototype: RangeError; -} - -declare const RangeError: RangeErrorConstructor; - -interface ReferenceError extends Error { -} - -interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; - (message?: string): ReferenceError; - readonly prototype: ReferenceError; -} - -declare const ReferenceError: ReferenceErrorConstructor; - -interface SyntaxError extends Error { -} - -interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; - (message?: string): SyntaxError; - readonly prototype: SyntaxError; -} - -declare const SyntaxError: SyntaxErrorConstructor; - -interface TypeError extends Error { -} - -interface TypeErrorConstructor { - new (message?: string): TypeError; - (message?: string): TypeError; - readonly prototype: TypeError; -} - -declare const TypeError: TypeErrorConstructor; - -interface URIError extends Error { -} - -interface URIErrorConstructor { - new (message?: string): URIError; - (message?: string): URIError; - readonly prototype: URIError; -} - -declare const URIError: URIErrorConstructor; - -interface JSON { - /** - * Converts a JavaScript Object Notation (JSON) string into an object. - * @param text A valid JSON string. - * @param reviver A function that transforms the results. This function is called for each member of the object. - * If a member contains nested objects, the nested objects are transformed before the parent object is. - */ - parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; -} - -/** - * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. - */ -declare const JSON: JSON; - - -///////////////////////////// -/// ECMAScript Array API (specially handled by compiler) -///////////////////////////// - -interface ReadonlyArray { - /** - * Gets the length of the array. This is a number one higher than the highest element defined in an array. - */ - readonly length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat>(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; - - readonly [n: number]: T; -} - -interface Array { - /** - * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - */ - length: number; - /** - * Returns a string representation of an array. - */ - toString(): string; - toLocaleString(): string; - /** - * Appends new elements to an array, and returns the new length of the array. - * @param items New elements of the Array. - */ - push(...items: T[]): number; - /** - * Removes the last element from an array and returns it. - */ - pop(): T | undefined; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[][]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | T[])[]): T[]; - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - /** - * Reverses the elements in an Array. - */ - reverse(): T[]; - /** - * Removes the first element from an array and returns it. - */ - shift(): T | undefined; - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): T[]; - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: T, b: T) => number): this; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - */ - splice(start: number): T[]; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** - * Inserts new elements at the start of an array. - * @param items Elements to insert at the start of the Array. - */ - unshift(...items: T[]): number; - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number; - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number; - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - [n: number]: T; -} - -interface ArrayConstructor { - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): arg is Array; - readonly prototype: Array; -} - -declare const Array: ArrayConstructor; - -interface TypedPropertyDescriptor { - enumerable?: boolean; - configurable?: boolean; - writable?: boolean; - value?: T; - get?: () => T; - set?: (value: T) => void; -} - -declare type ClassDecorator = (target: TFunction) => TFunction | void; -declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; -declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; -declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; - -declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; - -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) => T | PromiseLike) | undefined | null, - onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, - 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. - * @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) | undefined | null): 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; -} - -interface ArrayLike { - readonly length: number; - readonly [n: number]: T; -} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - /** - * Read-only. The length of the ArrayBuffer (in bytes). - */ - readonly byteLength: number; - - /** - * Returns a section of an ArrayBuffer. - */ - slice(begin:number, end?:number): ArrayBuffer; -} - -interface ArrayBufferConstructor { - readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; - isView(arg: any): arg is ArrayBufferView; -} -declare const ArrayBuffer: ArrayBufferConstructor; - -interface ArrayBufferView { - /** - * The ArrayBuffer instance referenced by the array. - */ - buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - byteLength: number; - - /** - * The offset in bytes of the array. - */ - byteOffset: number; -} - -interface DataView { - readonly buffer: ArrayBuffer; - readonly byteLength: number; - readonly byteOffset: number; - /** - * Gets the Float32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Float64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat64(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Int8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt8(byteOffset: number): number; - - /** - * Gets the Int16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt16(byteOffset: number, littleEndian?: boolean): number; - /** - * Gets the Int32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint8(byteOffset: number): number; - - /** - * Gets the Uint16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint16(byteOffset: number, littleEndian?: boolean): number; - - /** - * Gets the Uint32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint32(byteOffset: number, littleEndian?: boolean): number; - - /** - * Stores an Float32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Float64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setInt8(byteOffset: number, value: number): void; - - /** - * Stores an Int16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Int32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setUint8(byteOffset: number, value: number): void; - - /** - * Stores an Uint16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * Stores an Uint32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; -} - -interface DataViewConstructor { - new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; -} -declare const DataView: DataViewConstructor; - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} -interface Int8ArrayConstructor { - readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - -} -declare const Int8Array: Int8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ArrayConstructor { - readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; - -} -declare const Uint8Array: Uint8ArrayConstructor; - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8ClampedArray; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: Uint8ClampedArray, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint8ClampedArray; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint8ClampedArray; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint8ClampedArrayConstructor { - readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8ClampedArray; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} -declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int16ArrayConstructor { - readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - -} -declare const Int16Array: Int16ArrayConstructor; - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint16Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint16Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint16Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint16ArrayConstructor { - readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - -} -declare const Uint16Array: Uint16ArrayConstructor; -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Int32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Int32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Int32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Int32ArrayConstructor { - readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} -declare const Int32Array: Int32ArrayConstructor; - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Uint32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Uint32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Uint32ArrayConstructor { - readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} -declare const Uint32Array: Uint32ArrayConstructor; - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float32Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float32Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float32Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float32ArrayConstructor { - readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - -} -declare const Float32Array: Float32ArrayConstructor; - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBuffer; - - /** - * The length in bytes of the array. - */ - readonly byteLength: number; - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in array1 until the callbackfn returns false, - * or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this; - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls - * the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; - - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number; - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string; - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number; - - /** - * The length of the array. - */ - readonly length: number; - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; - - /** - * Reverses the elements in an Array. - */ - reverse(): Float64Array; - - /** - * Sets a value or an array of values. - * @param index The index of the location to set. - * @param value The value to set. - */ - set(index: number, value: number): void; - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void; - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ - slice(start?: number, end?: number): Float64Array; - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in array1 until the callbackfn returns true, or until - * the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; - - /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If - * omitted, the elements are sorted in ascending, ASCII character order. - */ - sort(compareFn?: (a: number, b: number) => number): this; - - /** - * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin: number, end?: number): Float64Array; - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string; - - /** - * Returns a string representation of an array. - */ - toString(): string; - - [index: number]: number; -} - -interface Float64ArrayConstructor { - readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} -declare const Float64Array: Float64ArrayConstructor; - -///////////////////////////// -/// ECMAScript Internationalization API -///////////////////////////// - -declare module Intl { - interface CollatorOptions { - usage?: string; - localeMatcher?: string; - numeric?: boolean; - caseFirst?: string; - sensitivity?: string; - ignorePunctuation?: boolean; - } - - interface ResolvedCollatorOptions { - locale: string; - usage: string; - sensitivity: string; - ignorePunctuation: boolean; - collation: string; - caseFirst: string; - numeric: boolean; - } - - interface Collator { - compare(x: string, y: string): number; - resolvedOptions(): ResolvedCollatorOptions; - } - var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; - (locales?: string | string[], options?: CollatorOptions): Collator; - supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; - } - - interface NumberFormatOptions { - localeMatcher?: string; - style?: string; - currency?: string; - currencyDisplay?: string; - useGrouping?: boolean; - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - } - - interface ResolvedNumberFormatOptions { - locale: string; - numberingSystem: string; - style: string; - currency?: string; - currencyDisplay?: string; - minimumIntegerDigits: number; - minimumFractionDigits: number; - maximumFractionDigits: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - useGrouping: boolean; - } - - interface NumberFormat { - format(value: number): string; - resolvedOptions(): ResolvedNumberFormatOptions; - } - var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; - supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; - } - - interface DateTimeFormatOptions { - localeMatcher?: string; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - formatMatcher?: string; - hour12?: boolean; - timeZone?: string; - } - - interface ResolvedDateTimeFormatOptions { - locale: string; - calendar: string; - numberingSystem: string; - timeZone: string; - hour12?: boolean; - weekday?: string; - era?: string; - year?: string; - month?: string; - day?: string; - hour?: string; - minute?: string; - second?: string; - timeZoneName?: string; - } - - interface DateTimeFormat { - format(date?: Date | number): string; - resolvedOptions(): ResolvedDateTimeFormatOptions; - } - var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; - supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; - } -} - -interface String { - /** - * Determines whether two strings are equivalent in the current or specified locale. - * @param that String to compare to target string - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; -} - -interface Number { - /** - * Converts a number to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; -} - -interface Date { - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - /** - * Converts a date to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; - - /** - * Converts a time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; -} -declare type PropertyKey = string | number | symbol; - -interface Array { - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): this; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): Array; -} - -interface DateConstructor { - new (value: Date): Date; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - readonly name: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[] ): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - readonly EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - readonly MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - readonly MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: any, ...sources: any[]): any; - - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - */ - setPrototypeOf(o: any, proto: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface ReadonlyArray { - /** - * Returns the value 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, find - * immediately returns that element value. Otherwise, find returns undefined. - * @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. - */ - find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * 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. - */ - findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - readonly flags: string; - - /** - * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular - * expression. Default is false. Read-only. - */ - readonly sticky: boolean; - - /** - * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular - * expression. Default is false. Read-only. - */ - readonly unicode: boolean; -} - -interface RegExpConstructor { - new (pattern: RegExp, flags?: string): RegExp; - (pattern: RegExp, flags?: string): RegExp; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number | undefined; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form?: string): string; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value?: V): this; - readonly size: number; -} - -interface MapConstructor { - new (): Map; - new (entries?: [K, V][]): Map; - readonly prototype: Map; -} -declare var Map: MapConstructor; - -interface ReadonlyMap { - forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; - get(key: K): V|undefined; - has(key: K): boolean; - readonly size: number; -} - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value?: V): this; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (entries?: [K, V][]): WeakMap; - readonly prototype: WeakMap; -} -declare var WeakMap: WeakMapConstructor; - -interface Set { - add(value: T): this; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface SetConstructor { - new (): Set; - new (values?: T[]): Set; - readonly prototype: Set; -} -declare var Set: SetConstructor; - -interface ReadonlySet { - forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface WeakSet { - add(value: T): this; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (values?: T[]): WeakSet; - readonly prototype: WeakSet; -} -declare var WeakSet: WeakSetConstructor; -interface GeneratorFunction extends Function { } - -interface GeneratorFunctionConstructor { - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): GeneratorFunction; - (...args: string[]): GeneratorFunction; - readonly prototype: GeneratorFunction; -} -declare var GeneratorFunction: GeneratorFunctionConstructor; -/// - -interface SymbolConstructor { - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - readonly iterator: symbol; -} - -interface IteratorResult { - done: boolean; - value: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface ArrayConstructor { - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; -} - -interface ReadonlyArray { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface IArguments { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Map { - [Symbol.iterator](): IterableIterator<[K,V]>; - entries(): IterableIterator<[K, V]>; - keys(): IterableIterator; - values(): IterableIterator; -} - -interface MapConstructor { - new (iterable: Iterable<[K, V]>): Map; -} - -interface WeakMap { } - -interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; -} - -interface Set { - [Symbol.iterator](): IterableIterator; - entries(): IterableIterator<[T, T]>; - keys(): IterableIterator; - values(): IterableIterator; -} - -interface SetConstructor { - new (iterable: Iterable): Set; -} - -interface WeakSet { } - -interface WeakSetConstructor { - new (iterable: Iterable): WeakSet; -} - -interface Promise { } - -interface PromiseConstructor { - /** - * 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: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; -} - -declare namespace Reflect { - function enumerate(target: any): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; -} - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; -} - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; - - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; -} - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; -} - -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; -} - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -}/** - * Represents the completion of an asynchronous operation - */ -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) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, 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. - * @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) | undefined | null): 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 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) | undefined | null): 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) => TResult | PromiseLike): Promise; -} - -interface PromiseConstructor { - /** - * 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, - * 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 - * 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 Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(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; - - /** - * 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; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor;interface ProxyHandler { - getPrototypeOf? (target: T): any; - setPrototypeOf? (target: T, v: any): boolean; - isExtensible? (target: T): boolean; - preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; - has? (target: T, p: PropertyKey): boolean; - get? (target: T, p: PropertyKey, receiver: any): any; - set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; - deleteProperty? (target: T, p: PropertyKey): boolean; - defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; - enumerate? (target: T): PropertyKey[]; - ownKeys? (target: T): PropertyKey[]; - apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, thisArg: any, argArray?: any): any; -} - -interface ProxyConstructor { - revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; - new (target: T, handler: ProxyHandler): T -} -declare var Proxy: ProxyConstructor;declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; - function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; - function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; - function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: any, proto: any): boolean; -}interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; -} - -interface SymbolConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string|number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string | undefined; -} - -declare var Symbol: SymbolConstructor;/// - -interface SymbolConstructor { - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - readonly hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - readonly isConcatSpreadable: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - readonly match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - readonly replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - readonly search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - readonly species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - readonly split: symbol; - - /** - * A method that converts an object to a corresponding primitive value. - * Called by the ToPrimitive abstract operation. - */ - readonly toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the 'with' - * environment bindings of the associated objects. - */ - readonly unscopables: symbol; -} - -interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; -} - -interface Array { - /** - * Returns an object whose properties have the value 'true' - * when they will be absent when used in a 'with' statement. - */ - [Symbol.unscopables](): { - copyWithin: boolean; - entries: boolean; - fill: boolean; - find: boolean; - findIndex: boolean; - keys: boolean; - values: boolean; - }; -} - -interface Date { - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "default"): string; - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "string"): string; - /** - * Converts a Date object to a number. - */ - [Symbol.toPrimitive](hint: "number"): number; - /** - * Converts a Date object to a string or number. - * - * @param hint The strings "number", "string", or "default" to specify what primitive to return. - * - * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". - * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". - */ - [Symbol.toPrimitive](hint: string): string | number; -} - -interface Map { - readonly [Symbol.toStringTag]: "Map"; -} - -interface WeakMap{ - readonly [Symbol.toStringTag]: "WeakMap"; -} - -interface Set { - readonly [Symbol.toStringTag]: "Set"; -} - -interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; -} - -interface JSON { - readonly [Symbol.toStringTag]: "JSON"; -} - -interface Function { - /** - * Determines whether the given value inherits from this function if this function was used - * as a constructor function. - * - * A constructor function can control which objects are recognized as its instances by - * 'instanceof' by overriding this method. - */ - [Symbol.hasInstance](value: any): boolean; -} - -interface GeneratorFunction extends Function { - readonly [Symbol.toStringTag]: "GeneratorFunction"; -} - -interface Math { - readonly [Symbol.toStringTag]: "Math"; -} - -interface Promise { - readonly [Symbol.toStringTag]: "Promise"; -} - -interface PromiseConstructor { - readonly [Symbol.species]: Function; -} - -interface RegExp { - /** - * Matches a string with this regular expression, and returns an array containing the results of - * that search. - * @param string A string to search within. - */ - [Symbol.match](string: string): RegExpMatchArray | null; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replaceValue A String object or string literal containing the text to replace for every - * successful match of this regular expression. - */ - [Symbol.replace](string: string, replaceValue: string): string; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replacer A function that returns the replacement text. - */ - [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the position beginning first substring match in a regular expression search - * using this regular expression. - * - * @param string The string to search within. - */ - [Symbol.search](string: string): number; - - /** - * Returns an array of substrings that were delimited by strings in the original input that - * match against this regular expression. - * - * If the regular expression contains capturing parentheses, then each time this - * regular expression matches, the results (including any undefined results) of the - * capturing parentheses are spliced. - * - * @param string string value to split - * @param limit if not undefined, the output array is truncated so that it contains no more - * than 'limit' elements. - */ - [Symbol.split](string: string, limit?: number): string[]; -} - -interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; -} - -interface String { - /** - * Matches a string an object that supports being matched against, and returns an array containing the results of that search. - * @param matcher An object that supports being matched against. - */ - match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param searcher An object which supports searching within a string. - */ - search(searcher: { [Symbol.search](string: string): number; }): number; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param splitter An object that can split a string. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; -} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; -} - -interface DataView { - readonly [Symbol.toStringTag]: "DataView"; -} - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - readonly [Symbol.toStringTag]: "Int8Array"; -} - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; -} - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - readonly [Symbol.toStringTag]: "Uint8ClampedArray"; -} - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - readonly [Symbol.toStringTag]: "Int16Array"; -} - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - readonly [Symbol.toStringTag]: "Uint16Array"; -} - -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - readonly [Symbol.toStringTag]: "Int32Array"; -} - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - readonly [Symbol.toStringTag]: "Uint32Array"; -} - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - readonly [Symbol.toStringTag]: "Float32Array"; -} - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - readonly [Symbol.toStringTag]: "Float64Array"; -} -///////////////////////////// -/// IE DOM APIs -///////////////////////////// - -interface Algorithm { - name: string; -} - -interface AriaRequestEventInit extends EventInit { - attributeName?: string; - attributeValue?: string; -} - -interface CommandEventInit extends EventInit { - commandName?: string; - detail?: string; -} - -interface CompositionEventInit extends UIEventInit { - data?: string; -} - -interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { - arrayOfDomainStrings?: string[]; -} - -interface ConstrainBooleanParameters { - exact?: boolean; - ideal?: boolean; -} - -interface ConstrainDOMStringParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface ConstrainDoubleRange extends DoubleRange { - exact?: number; - ideal?: number; -} - -interface ConstrainLongRange extends LongRange { - exact?: number; - ideal?: number; -} - -interface ConstrainVideoFacingModeParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface CustomEventInit extends EventInit { - detail?: any; -} - -interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; -} - -interface DeviceLightEventInit extends EventInit { - value?: number; -} - -interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; -} - -interface DoubleRange { - max?: number; - min?: number; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; -} - -interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; - altKey?: boolean; - metaKey?: boolean; - modifierAltGraph?: boolean; - modifierCapsLock?: boolean; - modifierFn?: boolean; - modifierFnLock?: boolean; - modifierHyper?: boolean; - modifierNumLock?: boolean; - modifierOS?: boolean; - modifierScrollLock?: boolean; - modifierSuper?: boolean; - modifierSymbol?: boolean; - modifierSymbolLock?: boolean; -} - -interface ExceptionInformation { - domain?: string; -} - -interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; -} - -interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; -} - -interface IDBIndexParameters { - multiEntry?: boolean; - unique?: boolean; -} - -interface IDBObjectStoreParameters { - autoIncrement?: boolean; - keyPath?: IDBKeyPath; -} - -interface KeyAlgorithm { - name?: string; -} - -interface KeyboardEventInit extends EventModifierInit { - code?: string; - key?: string; - location?: number; - repeat?: boolean; -} - -interface LongRange { - max?: number; - min?: number; -} - -interface MSAccountInfo { - rpDisplayName?: string; - userDisplayName?: string; - accountName?: string; - userId?: string; - accountImageUri?: string; -} - -interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - networkSendQualityEventRatio?: number; - networkDelayEventRatio?: number; - cpuInsufficientEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; - deviceCaptureNotFunctioningEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; - deviceClippingEventRatio?: number; - deviceEchoEventRatio?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; - deviceHowlingEventCount?: number; -} - -interface MSAudioRecvPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioRecvSignal; - packetReorderRatio?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; - burstLossLength1?: number; - burstLossLength2?: number; - burstLossLength3?: number; - burstLossLength4?: number; - burstLossLength5?: number; - burstLossLength6?: number; - burstLossLength7?: number; - burstLossLength8OrHigher?: number; - fecRecvDistance1?: number; - fecRecvDistance2?: number; - fecRecvDistance3?: number; - ratioConcealedSamplesAvg?: number; - ratioStretchedSamplesAvg?: number; - ratioCompressedSamplesAvg?: number; -} - -interface MSAudioRecvSignal { - initialSignalLevelRMS?: number; - recvSignalLevelCh1?: number; - recvNoiseLevelCh1?: number; - renderSignalLevel?: number; - renderNoiseLevel?: number; - renderLoopbackSignalLevel?: number; -} - -interface MSAudioSendPayload extends MSPayloadBase { - samplingRate?: number; - signal?: MSAudioSendSignal; - audioFECUsed?: boolean; - sendMutePercent?: number; -} - -interface MSAudioSendSignal { - noiseLevel?: number; - sendSignalLevelCh1?: number; - sendNoiseLevelCh1?: number; -} - -interface MSConnectivity { - iceType?: string; - iceWarningFlags?: MSIceWarningFlags; - relayAddress?: MSRelayAddress; -} - -interface MSCredentialFilter { - accept?: MSCredentialSpec[]; -} - -interface MSCredentialParameters { - type?: string; -} - -interface MSCredentialSpec { - type?: string; - id?: string; -} - -interface MSDelay { - roundTrip?: number; - roundTripMax?: number; -} - -interface MSDescription extends RTCStats { - connectivity?: MSConnectivity; - transport?: string; - networkconnectivity?: MSNetworkConnectivityInfo; - localAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; - deviceDevName?: string; - reflexiveLocalIPAddr?: MSIPAddressInfo; -} - -interface MSFIDOCredentialParameters extends MSCredentialParameters { - algorithm?: string | Algorithm; - authenticators?: AAGUID[]; -} - -interface MSIPAddressInfo { - ipAddr?: string; - port?: number; - manufacturerMacAddrMask?: string; -} - -interface MSIceWarningFlags { - turnTcpTimedOut?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; - turnTcpAllocateFailed?: boolean; - turnTcpSendFailed?: boolean; - udpLocalConnectivityFailed?: boolean; - udpNatConnectivityFailed?: boolean; - udpRelayConnectivityFailed?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - connCheckMessageIntegrityFailed?: boolean; - allocationMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - turnAuthUnknownUsernameError?: boolean; - noRelayServersConfigured?: boolean; - multipleRelayServersAttempted?: boolean; - portRangeExhausted?: boolean; - alternateServerReceived?: boolean; - pseudoTLSFailure?: boolean; - turnTurnTcpConnectivityFailed?: boolean; - useCandidateChecksFailed?: boolean; - fipsAllocationFailure?: boolean; -} - -interface MSJitter { - interArrival?: number; - interArrivalMax?: number; - interArrivalSD?: number; -} - -interface MSLocalClientEventBase extends RTCStats { - networkReceiveQualityEventRatio?: number; - networkBandwidthLowEventRatio?: number; -} - -interface MSNetwork extends RTCStats { - jitter?: MSJitter; - delay?: MSDelay; - packetLoss?: MSPacketLoss; - utilization?: MSUtilization; -} - -interface MSNetworkConnectivityInfo { - vpn?: boolean; - linkspeed?: number; - networkConnectionDetails?: string; -} - -interface MSNetworkInterfaceType { - interfaceTypeEthernet?: boolean; - interfaceTypeWireless?: boolean; - interfaceTypePPP?: boolean; - interfaceTypeTunnel?: boolean; - interfaceTypeWWAN?: boolean; -} - -interface MSOutboundNetwork extends MSNetwork { - appliedBandwidthLimit?: number; -} - -interface MSPacketLoss { - lossRate?: number; - lossRateMax?: number; -} - -interface MSPayloadBase extends RTCStats { - payloadDescription?: string; -} - -interface MSRelayAddress { - relayAddress?: string; - port?: number; -} - -interface MSSignatureParameters { - userPrompt?: string; -} - -interface MSTransportDiagnosticsStats extends RTCStats { - baseAddress?: string; - localAddress?: string; - localSite?: string; - networkName?: string; - remoteAddress?: string; - remoteSite?: string; - localMR?: string; - remoteMR?: string; - iceWarningFlags?: MSIceWarningFlags; - portRangeMin?: number; - portRangeMax?: number; - localMRTCPPort?: number; - remoteMRTCPPort?: number; - stunVer?: number; - numConsentReqSent?: number; - numConsentReqReceived?: number; - numConsentRespSent?: number; - numConsentRespReceived?: number; - interfaces?: MSNetworkInterfaceType; - baseInterface?: MSNetworkInterfaceType; - protocol?: string; - localInterface?: MSNetworkInterfaceType; - localAddrType?: string; - remoteAddrType?: string; - iceRole?: string; - rtpRtcpMux?: boolean; - allocationTimeInMs?: number; - msRtcEngineVersion?: string; -} - -interface MSUtilization { - packets?: number; - bandwidthEstimation?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationStdDev?: number; - bandwidthEstimationAvg?: number; -} - -interface MSVideoPayload extends MSPayloadBase { - resoluton?: string; - videoBitRateAvg?: number; - videoBitRateMax?: number; - videoFrameRateAvg?: number; - videoPacketLossRate?: number; - durationSeconds?: number; -} - -interface MSVideoRecvPayload extends MSVideoPayload { - videoFrameLossRate?: number; - recvCodecType?: string; - recvResolutionWidth?: number; - recvResolutionHeight?: number; - videoResolutions?: MSVideoResolutionDistribution; - recvFrameRateAverage?: number; - recvBitRateMaximum?: number; - recvBitRateAverage?: number; - recvVideoStreamsMax?: number; - recvVideoStreamsMin?: number; - recvVideoStreamsMode?: number; - videoPostFECPLR?: number; - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; - reorderBufferTotalPackets?: number; - recvReorderBufferReorderedPackets?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvFpsHarmonicAverage?: number; - recvNumResSwitches?: number; -} - -interface MSVideoResolutionDistribution { - cifQuality?: number; - vgaQuality?: number; - h720Quality?: number; - h1080Quality?: number; - h1440Quality?: number; - h2160Quality?: number; -} - -interface MSVideoSendPayload extends MSVideoPayload { - sendFrameRateAverage?: number; - sendBitRateMaximum?: number; - sendBitRateAverage?: number; - sendVideoStreamsMax?: number; - sendResolutionWidth?: number; - sendResolutionHeight?: number; -} - -interface MediaEncryptedEventInit extends EventInit { - initDataType?: string; - initData?: ArrayBuffer; -} - -interface MediaKeyMessageEventInit extends EventInit { - messageType?: string; - message?: ArrayBuffer; -} - -interface MediaKeySystemConfiguration { - initDataTypes?: string[]; - audioCapabilities?: MediaKeySystemMediaCapability[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: string; - persistentState?: string; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - robustness?: string; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; -} - -interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - width?: number | LongRange; - height?: number | LongRange; - aspectRatio?: number | DoubleRange; - frameRate?: number | DoubleRange; - facingMode?: string; - volume?: number | DoubleRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - echoCancellation?: boolean[]; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackConstraintSet { - width?: number | ConstrainLongRange; - height?: number | ConstrainLongRange; - aspectRatio?: number | ConstrainDoubleRange; - frameRate?: number | ConstrainDoubleRange; - facingMode?: string | string[] | ConstrainDOMStringParameters; - volume?: number | ConstrainDoubleRange; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - echoCancelation?: boolean | ConstrainBooleanParameters; - deviceId?: string | string[] | ConstrainDOMStringParameters; - groupId?: string | string[] | ConstrainDOMStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - width?: number; - height?: number; - aspectRatio?: number; - frameRate?: number; - facingMode?: string; - volume?: number; - sampleRate?: number; - sampleSize?: number; - echoCancellation?: boolean; - deviceId?: string; - groupId?: string; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MouseEventInit extends EventModifierInit { - screenX?: number; - screenY?: number; - clientX?: number; - clientY?: number; - button?: number; - buttons?: number; - relatedTarget?: EventTarget; -} - -interface MsZoomToOptions { - contentX?: number; - contentY?: number; - viewportX?: string; - viewportY?: string; - scaleFactor?: number; - animate?: string; -} - -interface MutationObserverInit { - childList?: boolean; - attributes?: boolean; - characterData?: boolean; - subtree?: boolean; - attributeOldValue?: boolean; - characterDataOldValue?: boolean; - attributeFilter?: string[]; -} - -interface ObjectURLOptions { - oneTimeOnly?: boolean; -} - -interface PeriodicWaveConstraints { - disableNormalization?: boolean; -} - -interface PointerEventInit extends MouseEventInit { - pointerId?: number; - width?: number; - height?: number; - pressure?: number; - tiltX?: number; - tiltY?: number; - pointerType?: string; - isPrimary?: boolean; -} - -interface PositionOptions { - enableHighAccuracy?: boolean; - timeout?: number; - maximumAge?: number; -} - -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - -interface RTCDtlsFingerprint { - algorithm?: string; - value?: string; -} - -interface RTCDtlsParameters { - role?: string; - fingerprints?: RTCDtlsFingerprint[]; -} - -interface RTCIceCandidate { - foundation?: string; - priority?: number; - ip?: string; - protocol?: string; - port?: number; - type?: string; - tcpType?: string; - relatedAddress?: string; - relatedPort?: number; -} - -interface RTCIceCandidateAttributes extends RTCStats { - ipAddress?: string; - portNumber?: number; - transport?: string; - candidateType?: string; - priority?: number; - addressSourceUrl?: string; -} - -interface RTCIceCandidateComplete { -} - -interface RTCIceCandidatePair { - local?: RTCIceCandidate; - remote?: RTCIceCandidate; -} - -interface RTCIceCandidatePairStats extends RTCStats { - transportId?: string; - localCandidateId?: string; - remoteCandidateId?: string; - state?: string; - priority?: number; - nominated?: boolean; - writable?: boolean; - readable?: boolean; - bytesSent?: number; - bytesReceived?: number; - roundTripTime?: number; - availableOutgoingBitrate?: number; - availableIncomingBitrate?: number; -} - -interface RTCIceGatherOptions { - gatherPolicy?: string; - iceservers?: RTCIceServer[]; -} - -interface RTCIceParameters { - usernameFragment?: string; - password?: string; -} - -interface RTCIceServer { - urls?: any; - username?: string; - credential?: string; -} - -interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { - packetsReceived?: number; - bytesReceived?: number; - packetsLost?: number; - jitter?: number; - fractionLost?: number; -} - -interface RTCMediaStreamTrackStats extends RTCStats { - trackIdentifier?: string; - remoteSource?: boolean; - ssrcIds?: string[]; - frameWidth?: number; - frameHeight?: number; - framesPerSecond?: number; - framesSent?: number; - framesReceived?: number; - framesDecoded?: number; - framesDropped?: number; - framesCorrupted?: number; - audioLevel?: number; - echoReturnLoss?: number; - echoReturnLossEnhancement?: number; -} - -interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { - packetsSent?: number; - bytesSent?: number; - targetBitrate?: number; - roundTripTime?: number; -} - -interface RTCRTPStreamStats extends RTCStats { - ssrc?: string; - associateStatsId?: string; - isRemote?: boolean; - mediaTrackId?: string; - transportId?: string; - codecId?: string; - firCount?: number; - pliCount?: number; - nackCount?: number; - sliCount?: number; -} - -interface RTCRtcpFeedback { - type?: string; - parameter?: string; -} - -interface RTCRtcpParameters { - ssrc?: number; - cname?: string; - reducedSize?: boolean; - mux?: boolean; -} - -interface RTCRtpCapabilities { - codecs?: RTCRtpCodecCapability[]; - headerExtensions?: RTCRtpHeaderExtension[]; - fecMechanisms?: string[]; -} - -interface RTCRtpCodecCapability { - name?: string; - kind?: string; - clockRate?: number; - preferredPayloadType?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; - options?: any; - maxTemporalLayers?: number; - maxSpatialLayers?: number; - svcMultiStreamSupport?: boolean; -} - -interface RTCRtpCodecParameters { - name?: string; - payloadType?: any; - clockRate?: number; - maxptime?: number; - numChannels?: number; - rtcpFeedback?: RTCRtcpFeedback[]; - parameters?: any; -} - -interface RTCRtpContributingSource { - timestamp?: number; - csrc?: number; - audioLevel?: number; -} - -interface RTCRtpEncodingParameters { - ssrc?: number; - codecPayloadType?: number; - fec?: RTCRtpFecParameters; - rtx?: RTCRtpRtxParameters; - priority?: number; - maxBitrate?: number; - minQuality?: number; - framerateBias?: number; - resolutionScale?: number; - framerateScale?: number; - active?: boolean; - encodingId?: string; - dependencyEncodingIds?: string[]; - ssrcRange?: RTCSsrcRange; -} - -interface RTCRtpFecParameters { - ssrc?: number; - mechanism?: string; -} - -interface RTCRtpHeaderExtension { - kind?: string; - uri?: string; - preferredId?: number; - preferredEncrypt?: boolean; -} - -interface RTCRtpHeaderExtensionParameters { - uri?: string; - id?: number; - encrypt?: boolean; -} - -interface RTCRtpParameters { - muxId?: string; - codecs?: RTCRtpCodecParameters[]; - headerExtensions?: RTCRtpHeaderExtensionParameters[]; - encodings?: RTCRtpEncodingParameters[]; - rtcp?: RTCRtcpParameters; -} - -interface RTCRtpRtxParameters { - ssrc?: number; -} - -interface RTCRtpUnhandled { - ssrc?: number; - payloadType?: number; - muxId?: string; -} - -interface RTCSrtpKeyParam { - keyMethod?: string; - keySalt?: string; - lifetime?: string; - mkiValue?: number; - mkiLength?: number; -} - -interface RTCSrtpSdesParameters { - tag?: number; - cryptoSuite?: string; - keyParams?: RTCSrtpKeyParam[]; - sessionParams?: string[]; -} - -interface RTCSsrcRange { - min?: number; - max?: number; -} - -interface RTCStats { - timestamp?: number; - type?: string; - id?: string; - msType?: string; -} - -interface RTCStatsReport { -} - -interface RTCTransportStats extends RTCStats { - bytesSent?: number; - bytesReceived?: number; - rtcpTransportStatsId?: string; - activeConnection?: boolean; - selectedCandidatePairId?: string; - localCertificateId?: string; - remoteCertificateId?: string; -} - -interface StoreExceptionsInformation extends ExceptionInformation { - siteName?: string; - explanationString?: string; - detailURI?: string; -} - -interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { - arrayOfDomainStrings?: string[]; -} - -interface UIEventInit extends EventInit { - view?: Window; - detail?: number; -} - -interface WebGLContextAttributes { - failIfMajorPerformanceCaveat?: boolean; - alpha?: boolean; - depth?: boolean; - stencil?: boolean; - antialias?: boolean; - premultipliedAlpha?: boolean; - preserveDrawingBuffer?: boolean; -} - -interface WebGLContextEventInit extends EventInit { - statusMessage?: string; -} - -interface WheelEventInit extends MouseEventInit { - deltaX?: number; - deltaY?: number; - deltaZ?: number; - deltaMode?: number; -} - -interface EventListener { - (evt: Event): void; -} - -interface ANGLE_instanced_arrays { - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -declare var ANGLE_instanced_arrays: { - prototype: ANGLE_instanced_arrays; - new(): ANGLE_instanced_arrays; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; -} - -interface AnalyserNode extends AudioNode { - fftSize: number; - readonly frequencyBinCount: number; - maxDecibels: number; - minDecibels: number; - smoothingTimeConstant: number; - getByteFrequencyData(array: Uint8Array): void; - getByteTimeDomainData(array: Uint8Array): void; - getFloatFrequencyData(array: Float32Array): void; - getFloatTimeDomainData(array: Float32Array): void; -} - -declare var AnalyserNode: { - prototype: AnalyserNode; - new(): AnalyserNode; -} - -interface AnimationEvent extends Event { - readonly animationName: string; - readonly elapsedTime: number; - initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; -} - -declare var AnimationEvent: { - prototype: AnimationEvent; - new(): AnimationEvent; -} - -interface ApplicationCache extends EventTarget { - oncached: (this: this, ev: Event) => any; - onchecking: (this: this, ev: Event) => any; - ondownloading: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onnoupdate: (this: this, ev: Event) => any; - onobsolete: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onupdateready: (this: this, ev: Event) => any; - readonly status: number; - abort(): void; - swapCache(): void; - update(): void; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; - addEventListener(type: "cached", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "checking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "downloading", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "noupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "obsolete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "updateready", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ApplicationCache: { - prototype: ApplicationCache; - new(): ApplicationCache; - readonly CHECKING: number; - readonly DOWNLOADING: number; - readonly IDLE: number; - readonly OBSOLETE: number; - readonly UNCACHED: number; - readonly UPDATEREADY: number; -} - -interface AriaRequestEvent extends Event { - readonly attributeName: string; - attributeValue: string | null; -} - -declare var AriaRequestEvent: { - prototype: AriaRequestEvent; - new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; -} - -interface Attr extends Node { - readonly name: string; - readonly ownerElement: Element; - readonly prefix: string | null; - readonly specified: boolean; - value: string; -} - -declare var Attr: { - prototype: Attr; - new(): Attr; -} - -interface AudioBuffer { - readonly duration: number; - readonly length: number; - readonly numberOfChannels: number; - readonly sampleRate: number; - copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; - copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; - getChannelData(channel: number): Float32Array; -} - -declare var AudioBuffer: { - prototype: AudioBuffer; - new(): AudioBuffer; -} - -interface AudioBufferSourceNode extends AudioNode { - buffer: AudioBuffer | null; - readonly detune: AudioParam; - loop: boolean; - loopEnd: number; - loopStart: number; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - readonly playbackRate: AudioParam; - start(when?: number, offset?: number, duration?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var AudioBufferSourceNode: { - prototype: AudioBufferSourceNode; - new(): AudioBufferSourceNode; -} - -interface AudioContext extends EventTarget { - readonly currentTime: number; - readonly destination: AudioDestinationNode; - readonly listener: AudioListener; - readonly sampleRate: number; - state: string; - createAnalyser(): AnalyserNode; - createBiquadFilter(): BiquadFilterNode; - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - createBufferSource(): AudioBufferSourceNode; - createChannelMerger(numberOfInputs?: number): ChannelMergerNode; - createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; - createConvolver(): ConvolverNode; - createDelay(maxDelayTime?: number): DelayNode; - createDynamicsCompressor(): DynamicsCompressorNode; - createGain(): GainNode; - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; - createOscillator(): OscillatorNode; - createPanner(): PannerNode; - createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; - createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; - createStereoPanner(): StereoPannerNode; - createWaveShaper(): WaveShaperNode; - decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; -} - -declare var AudioContext: { - prototype: AudioContext; - new(): AudioContext; -} - -interface AudioDestinationNode extends AudioNode { - readonly maxChannelCount: number; -} - -declare var AudioDestinationNode: { - prototype: AudioDestinationNode; - new(): AudioDestinationNode; -} - -interface AudioListener { - dopplerFactor: number; - speedOfSound: number; - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var AudioListener: { - prototype: AudioListener; - new(): AudioListener; -} - -interface AudioNode extends EventTarget { - channelCount: number; - channelCountMode: string; - channelInterpretation: string; - readonly context: AudioContext; - readonly numberOfInputs: number; - readonly numberOfOutputs: number; - connect(destination: AudioNode, output?: number, input?: number): void; - disconnect(output?: number): void; - disconnect(destination: AudioNode, output?: number, input?: number): void; - disconnect(destination: AudioParam, output?: number): void; -} - -declare var AudioNode: { - prototype: AudioNode; - new(): AudioNode; -} - -interface AudioParam { - readonly defaultValue: number; - value: number; - cancelScheduledValues(startTime: number): void; - exponentialRampToValueAtTime(value: number, endTime: number): void; - linearRampToValueAtTime(value: number, endTime: number): void; - setTargetAtTime(target: number, startTime: number, timeConstant: number): void; - setValueAtTime(value: number, startTime: number): void; - setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; -} - -declare var AudioParam: { - prototype: AudioParam; - new(): AudioParam; -} - -interface AudioProcessingEvent extends Event { - readonly inputBuffer: AudioBuffer; - readonly outputBuffer: AudioBuffer; - readonly playbackTime: number; -} - -declare var AudioProcessingEvent: { - prototype: AudioProcessingEvent; - new(): AudioProcessingEvent; -} - -interface AudioTrack { - enabled: boolean; - readonly id: string; - kind: string; - readonly label: string; - language: string; - readonly sourceBuffer: SourceBuffer; -} - -declare var AudioTrack: { - prototype: AudioTrack; - new(): AudioTrack; -} - -interface AudioTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - getTrackById(id: string): AudioTrack | null; - item(index: number): AudioTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: AudioTrack; -} - -declare var AudioTrackList: { - prototype: AudioTrackList; - new(): AudioTrackList; -} - -interface BarProp { - readonly visible: boolean; -} - -declare var BarProp: { - prototype: BarProp; - new(): BarProp; -} - -interface BeforeUnloadEvent extends Event { - returnValue: any; -} - -declare var BeforeUnloadEvent: { - prototype: BeforeUnloadEvent; - new(): BeforeUnloadEvent; -} - -interface BiquadFilterNode extends AudioNode { - readonly Q: AudioParam; - readonly detune: AudioParam; - readonly frequency: AudioParam; - readonly gain: AudioParam; - type: string; - getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; -} - -declare var BiquadFilterNode: { - prototype: BiquadFilterNode; - new(): BiquadFilterNode; -} - -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -declare var Blob: { - prototype: Blob; - new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} - -interface CDATASection extends Text { -} - -declare var CDATASection: { - prototype: CDATASection; - new(): CDATASection; -} - -interface CSS { - supports(property: string, value?: string): boolean; -} -declare var CSS: CSS; - -interface CSSConditionRule extends CSSGroupingRule { - conditionText: string; -} - -declare var CSSConditionRule: { - prototype: CSSConditionRule; - new(): CSSConditionRule; -} - -interface CSSFontFaceRule extends CSSRule { - readonly style: CSSStyleDeclaration; -} - -declare var CSSFontFaceRule: { - prototype: CSSFontFaceRule; - new(): CSSFontFaceRule; -} - -interface CSSGroupingRule extends CSSRule { - readonly cssRules: CSSRuleList; - deleteRule(index: number): void; - insertRule(rule: string, index: number): number; -} - -declare var CSSGroupingRule: { - prototype: CSSGroupingRule; - new(): CSSGroupingRule; -} - -interface CSSImportRule extends CSSRule { - readonly href: string; - readonly media: MediaList; - readonly styleSheet: CSSStyleSheet; -} - -declare var CSSImportRule: { - prototype: CSSImportRule; - new(): CSSImportRule; -} - -interface CSSKeyframeRule extends CSSRule { - keyText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSKeyframeRule: { - prototype: CSSKeyframeRule; - new(): CSSKeyframeRule; -} - -interface CSSKeyframesRule extends CSSRule { - readonly cssRules: CSSRuleList; - name: string; - appendRule(rule: string): void; - deleteRule(rule: string): void; - findRule(rule: string): CSSKeyframeRule; -} - -declare var CSSKeyframesRule: { - prototype: CSSKeyframesRule; - new(): CSSKeyframesRule; -} - -interface CSSMediaRule extends CSSConditionRule { - readonly media: MediaList; -} - -declare var CSSMediaRule: { - prototype: CSSMediaRule; - new(): CSSMediaRule; -} - -interface CSSNamespaceRule extends CSSRule { - readonly namespaceURI: string; - readonly prefix: string; -} - -declare var CSSNamespaceRule: { - prototype: CSSNamespaceRule; - new(): CSSNamespaceRule; -} - -interface CSSPageRule extends CSSRule { - readonly pseudoClass: string; - readonly selector: string; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSPageRule: { - prototype: CSSPageRule; - new(): CSSPageRule; -} - -interface CSSRule { - cssText: string; - readonly parentRule: CSSRule; - readonly parentStyleSheet: CSSStyleSheet; - readonly type: number; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -declare var CSSRule: { - prototype: CSSRule; - new(): CSSRule; - readonly CHARSET_RULE: number; - readonly FONT_FACE_RULE: number; - readonly IMPORT_RULE: number; - readonly KEYFRAMES_RULE: number; - readonly KEYFRAME_RULE: number; - readonly MEDIA_RULE: number; - readonly NAMESPACE_RULE: number; - readonly PAGE_RULE: number; - readonly STYLE_RULE: number; - readonly SUPPORTS_RULE: number; - readonly UNKNOWN_RULE: number; - readonly VIEWPORT_RULE: number; -} - -interface CSSRuleList { - readonly length: number; - item(index: number): CSSRule; - [index: number]: CSSRule; -} - -declare var CSSRuleList: { - prototype: CSSRuleList; - new(): CSSRuleList; -} - -interface CSSStyleDeclaration { - alignContent: string | null; - alignItems: string | null; - alignSelf: string | null; - alignmentBaseline: string | null; - animation: string | null; - animationDelay: string | null; - animationDirection: string | null; - animationDuration: string | null; - animationFillMode: string | null; - animationIterationCount: string | null; - animationName: string | null; - animationPlayState: string | null; - animationTimingFunction: string | null; - backfaceVisibility: string | null; - background: string | null; - backgroundAttachment: string | null; - backgroundClip: string | null; - backgroundColor: string | null; - backgroundImage: string | null; - backgroundOrigin: string | null; - backgroundPosition: string | null; - backgroundPositionX: string | null; - backgroundPositionY: string | null; - backgroundRepeat: string | null; - backgroundSize: string | null; - baselineShift: string | null; - border: string | null; - borderBottom: string | null; - borderBottomColor: string | null; - borderBottomLeftRadius: string | null; - borderBottomRightRadius: string | null; - borderBottomStyle: string | null; - borderBottomWidth: string | null; - borderCollapse: string | null; - borderColor: string | null; - borderImage: string | null; - borderImageOutset: string | null; - borderImageRepeat: string | null; - borderImageSlice: string | null; - borderImageSource: string | null; - borderImageWidth: string | null; - borderLeft: string | null; - borderLeftColor: string | null; - borderLeftStyle: string | null; - borderLeftWidth: string | null; - borderRadius: string | null; - borderRight: string | null; - borderRightColor: string | null; - borderRightStyle: string | null; - borderRightWidth: string | null; - borderSpacing: string | null; - borderStyle: string | null; - borderTop: string | null; - borderTopColor: string | null; - borderTopLeftRadius: string | null; - borderTopRightRadius: string | null; - borderTopStyle: string | null; - borderTopWidth: string | null; - borderWidth: string | null; - bottom: string | null; - boxShadow: string | null; - boxSizing: string | null; - breakAfter: string | null; - breakBefore: string | null; - breakInside: string | null; - captionSide: string | null; - clear: string | null; - clip: string | null; - clipPath: string | null; - clipRule: string | null; - color: string | null; - colorInterpolationFilters: string | null; - columnCount: any; - columnFill: string | null; - columnGap: any; - columnRule: string | null; - columnRuleColor: any; - columnRuleStyle: string | null; - columnRuleWidth: any; - columnSpan: string | null; - columnWidth: any; - columns: string | null; - content: string | null; - counterIncrement: string | null; - counterReset: string | null; - cssFloat: string | null; - cssText: string; - cursor: string | null; - direction: string | null; - display: string | null; - dominantBaseline: string | null; - emptyCells: string | null; - enableBackground: string | null; - fill: string | null; - fillOpacity: string | null; - fillRule: string | null; - filter: string | null; - flex: string | null; - flexBasis: string | null; - flexDirection: string | null; - flexFlow: string | null; - flexGrow: string | null; - flexShrink: string | null; - flexWrap: string | null; - floodColor: string | null; - floodOpacity: string | null; - font: string | null; - fontFamily: string | null; - fontFeatureSettings: string | null; - fontSize: string | null; - fontSizeAdjust: string | null; - fontStretch: string | null; - fontStyle: string | null; - fontVariant: string | null; - fontWeight: string | null; - glyphOrientationHorizontal: string | null; - glyphOrientationVertical: string | null; - height: string | null; - imeMode: string | null; - justifyContent: string | null; - kerning: string | null; - left: string | null; - readonly length: number; - letterSpacing: string | null; - lightingColor: string | null; - lineHeight: string | null; - listStyle: string | null; - listStyleImage: string | null; - listStylePosition: string | null; - listStyleType: string | null; - margin: string | null; - marginBottom: string | null; - marginLeft: string | null; - marginRight: string | null; - marginTop: string | null; - marker: string | null; - markerEnd: string | null; - markerMid: string | null; - markerStart: string | null; - mask: string | null; - maxHeight: string | null; - maxWidth: string | null; - minHeight: string | null; - minWidth: string | null; - msContentZoomChaining: string | null; - msContentZoomLimit: string | null; - msContentZoomLimitMax: any; - msContentZoomLimitMin: any; - msContentZoomSnap: string | null; - msContentZoomSnapPoints: string | null; - msContentZoomSnapType: string | null; - msContentZooming: string | null; - msFlowFrom: string | null; - msFlowInto: string | null; - msFontFeatureSettings: string | null; - msGridColumn: any; - msGridColumnAlign: string | null; - msGridColumnSpan: any; - msGridColumns: string | null; - msGridRow: any; - msGridRowAlign: string | null; - msGridRowSpan: any; - msGridRows: string | null; - msHighContrastAdjust: string | null; - msHyphenateLimitChars: string | null; - msHyphenateLimitLines: any; - msHyphenateLimitZone: any; - msHyphens: string | null; - msImeAlign: string | null; - msOverflowStyle: string | null; - msScrollChaining: string | null; - msScrollLimit: string | null; - msScrollLimitXMax: any; - msScrollLimitXMin: any; - msScrollLimitYMax: any; - msScrollLimitYMin: any; - msScrollRails: string | null; - msScrollSnapPointsX: string | null; - msScrollSnapPointsY: string | null; - msScrollSnapType: string | null; - msScrollSnapX: string | null; - msScrollSnapY: string | null; - msScrollTranslation: string | null; - msTextCombineHorizontal: string | null; - msTextSizeAdjust: any; - msTouchAction: string | null; - msTouchSelect: string | null; - msUserSelect: string | null; - msWrapFlow: string; - msWrapMargin: any; - msWrapThrough: string; - opacity: string | null; - order: string | null; - orphans: string | null; - outline: string | null; - outlineColor: string | null; - outlineStyle: string | null; - outlineWidth: string | null; - overflow: string | null; - overflowX: string | null; - overflowY: string | null; - padding: string | null; - paddingBottom: string | null; - paddingLeft: string | null; - paddingRight: string | null; - paddingTop: string | null; - pageBreakAfter: string | null; - pageBreakBefore: string | null; - pageBreakInside: string | null; - readonly parentRule: CSSRule; - perspective: string | null; - perspectiveOrigin: string | null; - pointerEvents: string | null; - position: string | null; - quotes: string | null; - right: string | null; - rubyAlign: string | null; - rubyOverhang: string | null; - rubyPosition: string | null; - stopColor: string | null; - stopOpacity: string | null; - stroke: string | null; - strokeDasharray: string | null; - strokeDashoffset: string | null; - strokeLinecap: string | null; - strokeLinejoin: string | null; - strokeMiterlimit: string | null; - strokeOpacity: string | null; - strokeWidth: string | null; - tableLayout: string | null; - textAlign: string | null; - textAlignLast: string | null; - textAnchor: string | null; - textDecoration: string | null; - textIndent: string | null; - textJustify: string | null; - textKashida: string | null; - textKashidaSpace: string | null; - textOverflow: string | null; - textShadow: string | null; - textTransform: string | null; - textUnderlinePosition: string | null; - top: string | null; - touchAction: string | null; - transform: string | null; - transformOrigin: string | null; - transformStyle: string | null; - transition: string | null; - transitionDelay: string | null; - transitionDuration: string | null; - transitionProperty: string | null; - transitionTimingFunction: string | null; - unicodeBidi: string | null; - verticalAlign: string | null; - visibility: string | null; - webkitAlignContent: string | null; - webkitAlignItems: string | null; - webkitAlignSelf: string | null; - webkitAnimation: string | null; - webkitAnimationDelay: string | null; - webkitAnimationDirection: string | null; - webkitAnimationDuration: string | null; - webkitAnimationFillMode: string | null; - webkitAnimationIterationCount: string | null; - webkitAnimationName: string | null; - webkitAnimationPlayState: string | null; - webkitAnimationTimingFunction: string | null; - webkitAppearance: string | null; - webkitBackfaceVisibility: string | null; - webkitBackgroundClip: string | null; - webkitBackgroundOrigin: string | null; - webkitBackgroundSize: string | null; - webkitBorderBottomLeftRadius: string | null; - webkitBorderBottomRightRadius: string | null; - webkitBorderImage: string | null; - webkitBorderRadius: string | null; - webkitBorderTopLeftRadius: string | null; - webkitBorderTopRightRadius: string | null; - webkitBoxAlign: string | null; - webkitBoxDirection: string | null; - webkitBoxFlex: string | null; - webkitBoxOrdinalGroup: string | null; - webkitBoxOrient: string | null; - webkitBoxPack: string | null; - webkitBoxSizing: string | null; - webkitColumnBreakAfter: string | null; - webkitColumnBreakBefore: string | null; - webkitColumnBreakInside: string | null; - webkitColumnCount: any; - webkitColumnGap: any; - webkitColumnRule: string | null; - webkitColumnRuleColor: any; - webkitColumnRuleStyle: string | null; - webkitColumnRuleWidth: any; - webkitColumnSpan: string | null; - webkitColumnWidth: any; - webkitColumns: string | null; - webkitFilter: string | null; - webkitFlex: string | null; - webkitFlexBasis: string | null; - webkitFlexDirection: string | null; - webkitFlexFlow: string | null; - webkitFlexGrow: string | null; - webkitFlexShrink: string | null; - webkitFlexWrap: string | null; - webkitJustifyContent: string | null; - webkitOrder: string | null; - webkitPerspective: string | null; - webkitPerspectiveOrigin: string | null; - webkitTapHighlightColor: string | null; - webkitTextFillColor: string | null; - webkitTextSizeAdjust: any; - webkitTransform: string | null; - webkitTransformOrigin: string | null; - webkitTransformStyle: string | null; - webkitTransition: string | null; - webkitTransitionDelay: string | null; - webkitTransitionDuration: string | null; - webkitTransitionProperty: string | null; - webkitTransitionTimingFunction: string | null; - webkitUserModify: string | null; - webkitUserSelect: string | null; - webkitWritingMode: string | null; - whiteSpace: string | null; - widows: string | null; - width: string | null; - wordBreak: string | null; - wordSpacing: string | null; - wordWrap: string | null; - writingMode: string | null; - zIndex: string | null; - zoom: string | null; - getPropertyPriority(propertyName: string): string; - getPropertyValue(propertyName: string): string; - item(index: number): string; - removeProperty(propertyName: string): string; - setProperty(propertyName: string, value: string | null, priority?: string): void; - [index: number]: string; -} - -declare var CSSStyleDeclaration: { - prototype: CSSStyleDeclaration; - new(): CSSStyleDeclaration; -} - -interface CSSStyleRule extends CSSRule { - readonly readOnly: boolean; - selectorText: string; - readonly style: CSSStyleDeclaration; -} - -declare var CSSStyleRule: { - prototype: CSSStyleRule; - new(): CSSStyleRule; -} - -interface CSSStyleSheet extends StyleSheet { - readonly cssRules: CSSRuleList; - cssText: string; - readonly href: string; - readonly id: string; - readonly imports: StyleSheetList; - readonly isAlternate: boolean; - readonly isPrefAlternate: boolean; - readonly ownerRule: CSSRule; - readonly owningElement: Element; - readonly pages: StyleSheetPageList; - readonly readOnly: boolean; - readonly rules: CSSRuleList; - addImport(bstrURL: string, lIndex?: number): number; - addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; - addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; - deleteRule(index?: number): void; - insertRule(rule: string, index?: number): number; - removeImport(lIndex: number): void; - removeRule(lIndex: number): void; -} - -declare var CSSStyleSheet: { - prototype: CSSStyleSheet; - new(): CSSStyleSheet; -} - -interface CSSSupportsRule extends CSSConditionRule { -} - -declare var CSSSupportsRule: { - prototype: CSSSupportsRule; - new(): CSSSupportsRule; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} - -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface CanvasPattern { -} - -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface CanvasRenderingContext2D extends Object, CanvasPathMethods { - readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - msFillRule: string; - msImageSmoothingEnabled: boolean; - shadowBlur: number; - shadowColor: string; - shadowOffsetX: number; - shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - mozImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: string): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; - fill(fillRule?: string): void; - fillRect(x: number, y: number, w: number, h: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: string): boolean; - measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; - rotate(angle: number): void; - save(): void; - scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - translate(x: number, y: number): void; -} - -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface ChannelMergerNode extends AudioNode { -} - -declare var ChannelMergerNode: { - prototype: ChannelMergerNode; - new(): ChannelMergerNode; -} - -interface ChannelSplitterNode extends AudioNode { -} - -declare var ChannelSplitterNode: { - prototype: ChannelSplitterNode; - new(): ChannelSplitterNode; -} - -interface CharacterData extends Node, ChildNode { - data: string; - readonly length: number; - appendData(arg: string): void; - deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; - substringData(offset: number, count: number): string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface ClientRect { - bottom: number; - readonly height: number; - left: number; - right: number; - top: number; - readonly width: number; -} - -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface ClientRectList { - readonly length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} - -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface ClipboardEvent extends Event { - readonly clipboardData: DataTransfer; -} - -declare var ClipboardEvent: { - prototype: ClipboardEvent; - new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(): CloseEvent; -} - -interface CommandEvent extends Event { - readonly commandName: string; - readonly detail: string | null; -} - -declare var CommandEvent: { - prototype: CommandEvent; - new(type: string, eventInitDict?: CommandEventInit): CommandEvent; -} - -interface Comment extends CharacterData { - text: string; -} - -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CompositionEvent extends UIEvent { - readonly data: string; - readonly locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; -} - -declare var CompositionEvent: { - prototype: CompositionEvent; - new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: string, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface ConvolverNode extends AudioNode { - buffer: AudioBuffer | null; - normalize: boolean; -} - -declare var ConvolverNode: { - prototype: ConvolverNode; - new(): ConvolverNode; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface Crypto extends Object, RandomSource { - readonly subtle: SubtleCrypto; -} - -declare var Crypto: { - prototype: Crypto; - new(): Crypto; -} - -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; -} - -declare var CryptoKey: { - prototype: CryptoKey; - new(): CryptoKey; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -declare var CryptoKeyPair: { - prototype: CryptoKeyPair; - new(): CryptoKeyPair; -} - -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; -} - -declare var CustomEvent: { - prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; -} - -interface DOMError { - readonly name: string; - toString(): string; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMImplementation { - createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; - createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; - createHTMLDocument(title: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; -} - -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} - -declare var DOMParser: { - prototype: DOMParser; - new(): DOMParser; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} - -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface DOMStringMap { - [name: string]: string; -} - -declare var DOMStringMap: { - prototype: DOMStringMap; - new(): DOMStringMap; -} - -interface DOMTokenList { - readonly length: number; - add(...token: string[]): void; - contains(token: string): boolean; - item(index: number): string; - remove(...token: string[]): void; - toString(): string; - toggle(token: string, force?: boolean): boolean; - [index: number]: string; -} - -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} - -interface DataCue extends TextTrackCue { - data: ArrayBuffer; -} - -declare var DataCue: { - prototype: DataCue; - new(): DataCue; -} - -interface DataTransfer { - dropEffect: string; - effectAllowed: string; - readonly files: FileList; - readonly items: DataTransferItemList; - readonly types: DOMStringList; - clearData(format?: string): boolean; - getData(format: string): string; - setData(format: string, data: string): boolean; -} - -declare var DataTransfer: { - prototype: DataTransfer; - new(): DataTransfer; -} - -interface DataTransferItem { - readonly kind: string; - readonly type: string; - getAsFile(): File | null; - getAsString(_callback: FunctionStringCallback | null): void; -} - -declare var DataTransferItem: { - prototype: DataTransferItem; - new(): DataTransferItem; -} - -interface DataTransferItemList { - readonly length: number; - add(data: File): DataTransferItem | null; - clear(): void; - item(index: number): DataTransferItem; - remove(index: number): void; - [index: number]: DataTransferItem; -} - -declare var DataTransferItemList: { - prototype: DataTransferItemList; - new(): DataTransferItemList; -} - -interface DeferredPermissionRequest { - readonly id: number; - readonly type: string; - readonly uri: string; - allow(): void; - deny(): void; -} - -declare var DeferredPermissionRequest: { - prototype: DeferredPermissionRequest; - new(): DeferredPermissionRequest; -} - -interface DelayNode extends AudioNode { - readonly delayTime: AudioParam; -} - -declare var DelayNode: { - prototype: DelayNode; - new(): DelayNode; -} - -interface DeviceAcceleration { - readonly x: number | null; - readonly y: number | null; - readonly z: number | null; -} - -declare var DeviceAcceleration: { - prototype: DeviceAcceleration; - new(): DeviceAcceleration; -} - -interface DeviceLightEvent extends Event { - readonly value: number; -} - -declare var DeviceLightEvent: { - prototype: DeviceLightEvent; - new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} - -interface DeviceMotionEvent extends Event { - readonly acceleration: DeviceAcceleration | null; - readonly accelerationIncludingGravity: DeviceAcceleration | null; - readonly interval: number | null; - readonly rotationRate: DeviceRotationRate | null; - initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; -} - -declare var DeviceMotionEvent: { - prototype: DeviceMotionEvent; - new(): DeviceMotionEvent; -} - -interface DeviceOrientationEvent extends Event { - readonly absolute: boolean; - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; - initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; -} - -declare var DeviceOrientationEvent: { - prototype: DeviceOrientationEvent; - new(): DeviceOrientationEvent; -} - -interface DeviceRotationRate { - readonly alpha: number | null; - readonly beta: number | null; - readonly gamma: number | null; -} - -declare var DeviceRotationRate: { - prototype: DeviceRotationRate; - new(): DeviceRotationRate; -} - -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { - /** - * Sets or gets the URL for the current document. - */ - readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; - /** - * Gets the object that has the focus when the parent document has focus. - */ - readonly activeElement: Element; - /** - * Sets or gets the color of all active links in the document. - */ - alinkColor: string; - /** - * Returns a reference to the collection of elements contained by the object. - */ - readonly all: HTMLAllCollection; - /** - * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. - */ - anchors: HTMLCollectionOf; - /** - * Retrieves a collection of all applet objects in the document. - */ - applets: HTMLCollectionOf; - /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. - */ - bgColor: string; - /** - * Specifies the beginning and end of the document body. - */ - body: HTMLElement; - readonly characterSet: string; - /** - * Gets or sets the character set used to encode the object. - */ - charset: string; - /** - * Gets a value that indicates whether standards-compliant mode is switched on for the object. - */ - readonly compatMode: string; - cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; - /** - * Gets the default character set from the current regional language settings. - */ - readonly defaultCharset: string; - readonly defaultView: Window; - /** - * Sets or gets a value that indicates whether the document can be edited. - */ - designMode: string; - /** - * 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. - */ - readonly doctype: DocumentType; - /** - * Gets a reference to the root node of the document. - */ - documentElement: HTMLElement; - /** - * Sets or gets the security domain of the document. - */ - domain: string; - /** - * Retrieves a collection of all embed objects in the document. - */ - embeds: HTMLCollectionOf; - /** - * Sets or gets the foreground (text) color of the document. - */ - fgColor: string; - /** - * Retrieves a collection, in source order, of all form objects in the document. - */ - forms: HTMLCollectionOf; - readonly fullscreenElement: Element | null; - readonly fullscreenEnabled: boolean; - readonly head: HTMLHeadElement; - readonly hidden: boolean; - /** - * Retrieves a collection, in source order, of img objects in the document. - */ - images: HTMLCollectionOf; - /** - * Gets the implementation object of the current document. - */ - readonly implementation: DOMImplementation; - /** - * Returns the character encoding used to create the webpage that is loaded into the document object. - */ - readonly inputEncoding: string | null; - /** - * 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. - */ - linkColor: string; - /** - * Retrieves a collection of all a objects that specify the href property and all area objects in the document. - */ - links: HTMLCollectionOf; - /** - * Contains information about the current URL. - */ - readonly location: Location; - msCSSOMElementFloatMetrics: boolean; - msCapsLockWarningOff: boolean; - /** - * Fires when the user aborts the download. - * @param ev The event. - */ - onabort: (this: this, ev: UIEvent) => any; - /** - * Fires when the object is set as the active element. - * @param ev The event. - */ - onactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ - onbeforeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ - onbeforedeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ - onblur: (this: this, ev: FocusEvent) => any; - /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ - onchange: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ - onclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ - oncontextmenu: (this: this, ev: PointerEvent) => any; - /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ - ondblclick: (this: this, ev: MouseEvent) => any; - /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event - */ - ondeactivate: (this: this, ev: UIEvent) => any; - /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. - */ - ondrag: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. - */ - ondragend: (this: this, 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: (this: this, 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. - */ - ondragleave: (this: this, ev: DragEvent) => any; - /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. - */ - ondragover: (this: this, ev: DragEvent) => any; - /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. - */ - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - /** - * Occurs when the duration attribute is updated. - * @param ev The event. - */ - ondurationchange: (this: this, ev: Event) => any; - /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. - */ - onemptied: (this: this, ev: Event) => any; - /** - * Occurs when the end of playback is reached. - * @param ev The event - */ - onended: (this: this, ev: MediaStreamErrorEvent) => any; - /** - * Fires when an error occurs during object loading. - * @param ev The event. - */ - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - * @param ev The event. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onfullscreenchange: (this: this, ev: Event) => any; - onfullscreenerror: (this: this, ev: Event) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - /** - * Fires when the user presses a key. - * @param ev The keyboard event - */ - onkeydown: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. - */ - onkeypress: (this: this, ev: KeyboardEvent) => any; - /** - * Fires when the user releases a key. - * @param ev The keyboard event - */ - onkeyup: (this: this, ev: KeyboardEvent) => any; - /** - * Fires immediately after the browser loads the object. - * @param ev The event. - */ - onload: (this: this, ev: Event) => any; - /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ - onloadeddata: (this: this, ev: Event) => any; - /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ - onloadedmetadata: (this: this, ev: Event) => any; - /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ - onloadstart: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ - onmousedown: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ - onmousemove: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ - onmouseout: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ - onmouseover: (this: this, ev: MouseEvent) => any; - /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ - onmouseup: (this: this, ev: MouseEvent) => any; - /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ - onmssitemodejumplistitemremoved: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ - onmsthumbnailclick: (this: this, ev: MSSiteModeEvent) => any; - /** - * Occurs when playback is paused. - * @param ev The event. - */ - onpause: (this: this, ev: Event) => any; - /** - * Occurs when the play method is requested. - * @param ev The event. - */ - onplay: (this: this, ev: Event) => any; - /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ - onplaying: (this: this, ev: Event) => any; - onpointerlockchange: (this: this, ev: Event) => any; - onpointerlockerror: (this: this, ev: Event) => any; - /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ - onprogress: (this: this, ev: ProgressEvent) => any; - /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ - onratechange: (this: this, ev: Event) => any; - /** - * Fires when the state of the object has changed. - * @param ev The event - */ - onreadystatechange: (this: this, ev: ProgressEvent) => any; - /** - * Fires when the user resets a form. - * @param ev The event. - */ - onreset: (this: this, ev: Event) => any; - /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ - onscroll: (this: this, ev: UIEvent) => any; - /** - * Occurs when the seek operation ends. - * @param ev The event. - */ - onseeked: (this: this, ev: Event) => any; - /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ - onseeking: (this: this, ev: Event) => any; - /** - * Fires when the current selection changes. - * @param ev The event. - */ - onselect: (this: this, ev: UIEvent) => any; - /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ - onselectionchange: (this: this, ev: Event) => any; - onselectstart: (this: this, ev: Event) => any; - /** - * Occurs when the download has stopped. - * @param ev The event. - */ - onstalled: (this: this, ev: Event) => any; - /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ - onstop: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ - onsuspend: (this: this, ev: Event) => any; - /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ - onvolumechange: (this: this, ev: Event) => any; - /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ - onwaiting: (this: this, ev: Event) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - plugins: HTMLCollectionOf; - readonly pointerLockElement: Element; - /** - * Retrieves a value that indicates the current state of the object. - */ - readonly readyState: string; - /** - * Gets the URL of the location that referred the user to the current page. - */ - readonly referrer: string; - /** - * Gets the root svg element in the document hierarchy. - */ - readonly rootElement: SVGSVGElement; - /** - * Retrieves a collection of all script objects in the document. - */ - scripts: HTMLCollectionOf; - readonly scrollingElement: Element | null; - /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ - readonly styleSheets: StyleSheetList; - /** - * Contains the title of the document. - */ - title: string; - readonly visibilityState: string; - /** - * Sets or gets the color of the links that the user has visited. - */ - vlinkColor: string; - readonly webkitCurrentFullScreenElement: Element | null; - readonly webkitFullscreenElement: Element | null; - readonly webkitFullscreenEnabled: boolean; - readonly webkitIsFullScreen: boolean; - readonly xmlEncoding: string | null; - xmlStandalone: boolean; - /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ - xmlVersion: string | null; - adoptNode(source: Node): Node; - captureEvents(): void; - caretRangeFromPoint(x: number, y: number): Range; - clear(): void; - /** - * Closes an output stream and forces the sent data to display. - */ - close(): void; - /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ - createAttribute(name: string): Attr; - createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; - createCDATASection(data: string): CDATASection; - /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ - createComment(data: string): Comment; - /** - * Creates a new document. - */ - createDocumentFragment(): DocumentFragment; - /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ - createElement(tagName: "a"): HTMLAnchorElement; - createElement(tagName: "applet"): HTMLAppletElement; - createElement(tagName: "area"): HTMLAreaElement; - createElement(tagName: "audio"): HTMLAudioElement; - createElement(tagName: "base"): HTMLBaseElement; - createElement(tagName: "basefont"): HTMLBaseFontElement; - createElement(tagName: "blockquote"): HTMLQuoteElement; - createElement(tagName: "body"): HTMLBodyElement; - createElement(tagName: "br"): HTMLBRElement; - createElement(tagName: "button"): HTMLButtonElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: "caption"): HTMLTableCaptionElement; - createElement(tagName: "col"): HTMLTableColElement; - createElement(tagName: "colgroup"): HTMLTableColElement; - createElement(tagName: "datalist"): HTMLDataListElement; - createElement(tagName: "del"): HTMLModElement; - createElement(tagName: "dir"): HTMLDirectoryElement; - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "dl"): HTMLDListElement; - createElement(tagName: "embed"): HTMLEmbedElement; - createElement(tagName: "fieldset"): HTMLFieldSetElement; - createElement(tagName: "font"): HTMLFontElement; - createElement(tagName: "form"): HTMLFormElement; - createElement(tagName: "frame"): HTMLFrameElement; - createElement(tagName: "frameset"): HTMLFrameSetElement; - createElement(tagName: "h1"): HTMLHeadingElement; - createElement(tagName: "h2"): HTMLHeadingElement; - createElement(tagName: "h3"): HTMLHeadingElement; - createElement(tagName: "h4"): HTMLHeadingElement; - createElement(tagName: "h5"): HTMLHeadingElement; - createElement(tagName: "h6"): HTMLHeadingElement; - createElement(tagName: "head"): HTMLHeadElement; - createElement(tagName: "hr"): HTMLHRElement; - createElement(tagName: "html"): HTMLHtmlElement; - createElement(tagName: "iframe"): HTMLIFrameElement; - createElement(tagName: "img"): HTMLImageElement; - createElement(tagName: "input"): HTMLInputElement; - createElement(tagName: "ins"): HTMLModElement; - createElement(tagName: "isindex"): HTMLUnknownElement; - createElement(tagName: "label"): HTMLLabelElement; - createElement(tagName: "legend"): HTMLLegendElement; - createElement(tagName: "li"): HTMLLIElement; - createElement(tagName: "link"): HTMLLinkElement; - createElement(tagName: "listing"): HTMLPreElement; - createElement(tagName: "map"): HTMLMapElement; - createElement(tagName: "marquee"): HTMLMarqueeElement; - createElement(tagName: "menu"): HTMLMenuElement; - createElement(tagName: "meta"): HTMLMetaElement; - createElement(tagName: "meter"): HTMLMeterElement; - createElement(tagName: "nextid"): HTMLUnknownElement; - createElement(tagName: "object"): HTMLObjectElement; - createElement(tagName: "ol"): HTMLOListElement; - createElement(tagName: "optgroup"): HTMLOptGroupElement; - createElement(tagName: "option"): HTMLOptionElement; - createElement(tagName: "p"): HTMLParagraphElement; - createElement(tagName: "param"): HTMLParamElement; - createElement(tagName: "picture"): HTMLPictureElement; - createElement(tagName: "pre"): HTMLPreElement; - createElement(tagName: "progress"): HTMLProgressElement; - createElement(tagName: "q"): HTMLQuoteElement; - createElement(tagName: "script"): HTMLScriptElement; - createElement(tagName: "select"): HTMLSelectElement; - createElement(tagName: "source"): HTMLSourceElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "style"): HTMLStyleElement; - createElement(tagName: "table"): HTMLTableElement; - createElement(tagName: "tbody"): HTMLTableSectionElement; - createElement(tagName: "td"): HTMLTableDataCellElement; - createElement(tagName: "template"): HTMLTemplateElement; - createElement(tagName: "textarea"): HTMLTextAreaElement; - createElement(tagName: "tfoot"): HTMLTableSectionElement; - createElement(tagName: "th"): HTMLTableHeaderCellElement; - createElement(tagName: "thead"): HTMLTableSectionElement; - createElement(tagName: "title"): HTMLTitleElement; - createElement(tagName: "tr"): HTMLTableRowElement; - createElement(tagName: "track"): HTMLTrackElement; - createElement(tagName: "ul"): HTMLUListElement; - createElement(tagName: "video"): HTMLVideoElement; - createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; - createElement(tagName: "xmp"): HTMLPreElement; - createElement(tagName: string): HTMLElement; - createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement - createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement - createElementNS(namespaceURI: string | null, qualifiedName: string): Element; - 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. - * @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. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - 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. - */ - createRange(): Range; - /** - * Creates a text string from the specified value. - * @param data String that specifies the nodeValue property of the text node. - */ - createTextNode(data: string): Text; - createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; - createTouchList(...touches: Touch[]): TouchList; - /** - * Creates a TreeWalker 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. For more information, see whatToShow. - * @param filter A custom NodeFilter function to use. - * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. - */ - createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; - /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ - elementFromPoint(x: number, y: number): Element; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; - /** - * Executes a command on the current document, current selection, or the given range. - * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. - * @param showUI Display the user interface, defaults to false. - * @param value Value to assign. - */ - execCommand(commandId: string, showUI?: boolean, value?: any): boolean; - /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ - execCommandShowHelp(commandId: string): boolean; - exitFullscreen(): void; - exitPointerLock(): void; - /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. - */ - focus(): void; - /** - * 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 | null; - getElementsByClassName(classNames: string): HTMLCollectionOf; - /** - * Gets a collection of objects based on the value of the NAME or ID attribute. - * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. - */ - getElementsByName(elementName: string): NodeListOf; - /** - * Retrieves a collection of objects based on the specified element name. - * @param name Specifies the name of an element. - */ - getElementsByTagName(tagname: "a"): NodeListOf; - getElementsByTagName(tagname: "abbr"): NodeListOf; - getElementsByTagName(tagname: "acronym"): NodeListOf; - getElementsByTagName(tagname: "address"): NodeListOf; - getElementsByTagName(tagname: "applet"): NodeListOf; - getElementsByTagName(tagname: "area"): NodeListOf; - getElementsByTagName(tagname: "article"): NodeListOf; - getElementsByTagName(tagname: "aside"): NodeListOf; - getElementsByTagName(tagname: "audio"): NodeListOf; - getElementsByTagName(tagname: "b"): NodeListOf; - getElementsByTagName(tagname: "base"): NodeListOf; - getElementsByTagName(tagname: "basefont"): NodeListOf; - getElementsByTagName(tagname: "bdo"): NodeListOf; - getElementsByTagName(tagname: "big"): NodeListOf; - getElementsByTagName(tagname: "blockquote"): NodeListOf; - getElementsByTagName(tagname: "body"): NodeListOf; - getElementsByTagName(tagname: "br"): NodeListOf; - getElementsByTagName(tagname: "button"): NodeListOf; - getElementsByTagName(tagname: "canvas"): NodeListOf; - getElementsByTagName(tagname: "caption"): NodeListOf; - getElementsByTagName(tagname: "center"): NodeListOf; - getElementsByTagName(tagname: "circle"): NodeListOf; - getElementsByTagName(tagname: "cite"): NodeListOf; - getElementsByTagName(tagname: "clippath"): NodeListOf; - getElementsByTagName(tagname: "code"): NodeListOf; - getElementsByTagName(tagname: "col"): NodeListOf; - getElementsByTagName(tagname: "colgroup"): NodeListOf; - getElementsByTagName(tagname: "datalist"): NodeListOf; - getElementsByTagName(tagname: "dd"): NodeListOf; - getElementsByTagName(tagname: "defs"): NodeListOf; - getElementsByTagName(tagname: "del"): NodeListOf; - getElementsByTagName(tagname: "desc"): NodeListOf; - getElementsByTagName(tagname: "dfn"): NodeListOf; - getElementsByTagName(tagname: "dir"): NodeListOf; - getElementsByTagName(tagname: "div"): NodeListOf; - getElementsByTagName(tagname: "dl"): NodeListOf; - getElementsByTagName(tagname: "dt"): NodeListOf; - getElementsByTagName(tagname: "ellipse"): NodeListOf; - getElementsByTagName(tagname: "em"): NodeListOf; - getElementsByTagName(tagname: "embed"): NodeListOf; - getElementsByTagName(tagname: "feblend"): NodeListOf; - getElementsByTagName(tagname: "fecolormatrix"): NodeListOf; - getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(tagname: "fecomposite"): NodeListOf; - getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf; - getElementsByTagName(tagname: "fediffuselighting"): NodeListOf; - getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf; - getElementsByTagName(tagname: "fedistantlight"): NodeListOf; - getElementsByTagName(tagname: "feflood"): NodeListOf; - getElementsByTagName(tagname: "fefunca"): NodeListOf; - getElementsByTagName(tagname: "fefuncb"): NodeListOf; - getElementsByTagName(tagname: "fefuncg"): NodeListOf; - getElementsByTagName(tagname: "fefuncr"): NodeListOf; - getElementsByTagName(tagname: "fegaussianblur"): NodeListOf; - getElementsByTagName(tagname: "feimage"): NodeListOf; - getElementsByTagName(tagname: "femerge"): NodeListOf; - getElementsByTagName(tagname: "femergenode"): NodeListOf; - getElementsByTagName(tagname: "femorphology"): NodeListOf; - getElementsByTagName(tagname: "feoffset"): NodeListOf; - getElementsByTagName(tagname: "fepointlight"): NodeListOf; - getElementsByTagName(tagname: "fespecularlighting"): NodeListOf; - getElementsByTagName(tagname: "fespotlight"): NodeListOf; - getElementsByTagName(tagname: "fetile"): NodeListOf; - getElementsByTagName(tagname: "feturbulence"): NodeListOf; - getElementsByTagName(tagname: "fieldset"): NodeListOf; - getElementsByTagName(tagname: "figcaption"): NodeListOf; - getElementsByTagName(tagname: "figure"): NodeListOf; - getElementsByTagName(tagname: "filter"): NodeListOf; - getElementsByTagName(tagname: "font"): NodeListOf; - getElementsByTagName(tagname: "footer"): NodeListOf; - getElementsByTagName(tagname: "foreignobject"): NodeListOf; - getElementsByTagName(tagname: "form"): NodeListOf; - getElementsByTagName(tagname: "frame"): NodeListOf; - getElementsByTagName(tagname: "frameset"): NodeListOf; - getElementsByTagName(tagname: "g"): NodeListOf; - getElementsByTagName(tagname: "h1"): NodeListOf; - getElementsByTagName(tagname: "h2"): NodeListOf; - getElementsByTagName(tagname: "h3"): NodeListOf; - getElementsByTagName(tagname: "h4"): NodeListOf; - getElementsByTagName(tagname: "h5"): NodeListOf; - getElementsByTagName(tagname: "h6"): NodeListOf; - getElementsByTagName(tagname: "head"): NodeListOf; - getElementsByTagName(tagname: "header"): NodeListOf; - getElementsByTagName(tagname: "hgroup"): NodeListOf; - getElementsByTagName(tagname: "hr"): NodeListOf; - getElementsByTagName(tagname: "html"): NodeListOf; - getElementsByTagName(tagname: "i"): NodeListOf; - getElementsByTagName(tagname: "iframe"): NodeListOf; - getElementsByTagName(tagname: "image"): NodeListOf; - getElementsByTagName(tagname: "img"): NodeListOf; - getElementsByTagName(tagname: "input"): NodeListOf; - getElementsByTagName(tagname: "ins"): NodeListOf; - getElementsByTagName(tagname: "isindex"): NodeListOf; - getElementsByTagName(tagname: "kbd"): NodeListOf; - getElementsByTagName(tagname: "keygen"): NodeListOf; - getElementsByTagName(tagname: "label"): NodeListOf; - getElementsByTagName(tagname: "legend"): NodeListOf; - getElementsByTagName(tagname: "li"): NodeListOf; - getElementsByTagName(tagname: "line"): NodeListOf; - getElementsByTagName(tagname: "lineargradient"): NodeListOf; - getElementsByTagName(tagname: "link"): NodeListOf; - getElementsByTagName(tagname: "listing"): NodeListOf; - getElementsByTagName(tagname: "map"): NodeListOf; - getElementsByTagName(tagname: "mark"): NodeListOf; - getElementsByTagName(tagname: "marker"): NodeListOf; - getElementsByTagName(tagname: "marquee"): NodeListOf; - getElementsByTagName(tagname: "mask"): NodeListOf; - getElementsByTagName(tagname: "menu"): NodeListOf; - getElementsByTagName(tagname: "meta"): NodeListOf; - getElementsByTagName(tagname: "metadata"): NodeListOf; - getElementsByTagName(tagname: "meter"): NodeListOf; - getElementsByTagName(tagname: "nav"): NodeListOf; - getElementsByTagName(tagname: "nextid"): NodeListOf; - getElementsByTagName(tagname: "nobr"): NodeListOf; - getElementsByTagName(tagname: "noframes"): NodeListOf; - getElementsByTagName(tagname: "noscript"): NodeListOf; - getElementsByTagName(tagname: "object"): NodeListOf; - getElementsByTagName(tagname: "ol"): NodeListOf; - getElementsByTagName(tagname: "optgroup"): NodeListOf; - getElementsByTagName(tagname: "option"): NodeListOf; - getElementsByTagName(tagname: "p"): NodeListOf; - getElementsByTagName(tagname: "param"): NodeListOf; - getElementsByTagName(tagname: "path"): NodeListOf; - getElementsByTagName(tagname: "pattern"): NodeListOf; - getElementsByTagName(tagname: "picture"): NodeListOf; - getElementsByTagName(tagname: "plaintext"): NodeListOf; - getElementsByTagName(tagname: "polygon"): NodeListOf; - getElementsByTagName(tagname: "polyline"): NodeListOf; - getElementsByTagName(tagname: "pre"): NodeListOf; - getElementsByTagName(tagname: "progress"): NodeListOf; - getElementsByTagName(tagname: "q"): NodeListOf; - getElementsByTagName(tagname: "radialgradient"): NodeListOf; - getElementsByTagName(tagname: "rect"): NodeListOf; - getElementsByTagName(tagname: "rt"): NodeListOf; - getElementsByTagName(tagname: "ruby"): NodeListOf; - getElementsByTagName(tagname: "s"): NodeListOf; - getElementsByTagName(tagname: "samp"): NodeListOf; - getElementsByTagName(tagname: "script"): NodeListOf; - getElementsByTagName(tagname: "section"): NodeListOf; - getElementsByTagName(tagname: "select"): NodeListOf; - getElementsByTagName(tagname: "small"): NodeListOf; - getElementsByTagName(tagname: "source"): NodeListOf; - getElementsByTagName(tagname: "span"): NodeListOf; - getElementsByTagName(tagname: "stop"): NodeListOf; - getElementsByTagName(tagname: "strike"): NodeListOf; - getElementsByTagName(tagname: "strong"): NodeListOf; - getElementsByTagName(tagname: "style"): NodeListOf; - getElementsByTagName(tagname: "sub"): NodeListOf; - getElementsByTagName(tagname: "sup"): NodeListOf; - getElementsByTagName(tagname: "svg"): NodeListOf; - getElementsByTagName(tagname: "switch"): NodeListOf; - getElementsByTagName(tagname: "symbol"): NodeListOf; - getElementsByTagName(tagname: "table"): NodeListOf; - getElementsByTagName(tagname: "tbody"): NodeListOf; - getElementsByTagName(tagname: "td"): NodeListOf; - getElementsByTagName(tagname: "template"): NodeListOf; - getElementsByTagName(tagname: "text"): NodeListOf; - getElementsByTagName(tagname: "textpath"): NodeListOf; - getElementsByTagName(tagname: "textarea"): NodeListOf; - getElementsByTagName(tagname: "tfoot"): NodeListOf; - getElementsByTagName(tagname: "th"): NodeListOf; - getElementsByTagName(tagname: "thead"): NodeListOf; - getElementsByTagName(tagname: "title"): NodeListOf; - getElementsByTagName(tagname: "tr"): NodeListOf; - getElementsByTagName(tagname: "track"): NodeListOf; - getElementsByTagName(tagname: "tspan"): NodeListOf; - getElementsByTagName(tagname: "tt"): NodeListOf; - getElementsByTagName(tagname: "u"): NodeListOf; - getElementsByTagName(tagname: "ul"): NodeListOf; - getElementsByTagName(tagname: "use"): NodeListOf; - getElementsByTagName(tagname: "var"): NodeListOf; - getElementsByTagName(tagname: "video"): NodeListOf; - getElementsByTagName(tagname: "view"): NodeListOf; - getElementsByTagName(tagname: "wbr"): NodeListOf; - getElementsByTagName(tagname: "x-ms-webview"): NodeListOf; - getElementsByTagName(tagname: "xmp"): NodeListOf; - getElementsByTagName(tagname: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ - getSelection(): Selection; - /** - * Gets a value indicating whether the object currently has focus. - */ - hasFocus(): boolean; - importNode(importedNode: Node, deep: boolean): Node; - msElementsFromPoint(x: number, y: number): NodeListOf; - msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; - /** - * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. - * @param url Specifies a MIME type for the document. - * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. - * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. - * @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. - */ - queryCommandEnabled(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. - * @param commandId String that specifies a command identifier. - */ - queryCommandIndeterm(commandId: string): boolean; - /** - * Returns a Boolean value that indicates the current state of the command. - * @param commandId String that specifies a command identifier. - */ - queryCommandState(commandId: string): boolean; - /** - * Returns a Boolean value that indicates whether the current command is supported on the current range. - * @param commandId Specifies a command identifier. - */ - 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. - */ - queryCommandText(commandId: string): string; - /** - * Returns the current value of the document, range, or current selection for the given command. - * @param commandId String that specifies a command identifier. - */ - queryCommandValue(commandId: string): string; - releaseEvents(): void; - /** - * Allows updating the print settings for the page. - */ - updateSettings(): void; - webkitCancelFullScreen(): void; - webkitExitFullscreen(): void; - /** - * 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. - * @param content The text and HTML tags to write. - */ - writeln(...content: string[]): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mssitemodejumplistitemremoved", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msthumbnailclick", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectionchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stop", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Document: { - prototype: Document; - new(): Document; -} - -interface DocumentFragment extends Node, NodeSelector, ParentNode { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentFragment: { - prototype: DocumentFragment; - new(): DocumentFragment; -} - -interface DocumentType extends Node, ChildNode { - readonly entities: NamedNodeMap; - readonly internalSubset: string | null; - readonly name: string; - readonly notations: NamedNodeMap; - readonly publicId: string | null; - readonly systemId: string | null; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var DocumentType: { - prototype: DocumentType; - new(): DocumentType; -} - -interface DragEvent extends MouseEvent { - readonly dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; - msConvertURL(file: File, targetType: string, targetURL?: string): void; -} - -declare var DragEvent: { - prototype: DragEvent; - new(): DragEvent; -} - -interface DynamicsCompressorNode extends AudioNode { - readonly attack: AudioParam; - readonly knee: AudioParam; - readonly ratio: AudioParam; - readonly reduction: AudioParam; - readonly release: AudioParam; - readonly threshold: AudioParam; -} - -declare var DynamicsCompressorNode: { - prototype: DynamicsCompressorNode; - new(): DynamicsCompressorNode; -} - -interface EXT_frag_depth { -} - -declare var EXT_frag_depth: { - prototype: EXT_frag_depth; - new(): EXT_frag_depth; -} - -interface EXT_texture_filter_anisotropic { - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { - readonly classList: DOMTokenList; - className: string; - readonly clientHeight: number; - readonly clientLeft: number; - readonly clientTop: number; - readonly clientWidth: number; - id: string; - msContentZoomFactor: number; - readonly msRegionOverflow: string; - onariarequest: (this: this, ev: AriaRequestEvent) => any; - oncommand: (this: this, ev: CommandEvent) => any; - ongotpointercapture: (this: this, ev: PointerEvent) => any; - onlostpointercapture: (this: this, ev: PointerEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsgotpointercapture: (this: this, ev: MSPointerEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmslostpointercapture: (this: this, ev: MSPointerEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; - readonly prefix: string | null; - readonly scrollHeight: number; - scrollLeft: number; - scrollTop: number; - readonly scrollWidth: number; - readonly tagName: string; - innerHTML: string; - getAttribute(name: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - getElementsByTagName(name: "a"): NodeListOf; - getElementsByTagName(name: "abbr"): NodeListOf; - getElementsByTagName(name: "acronym"): NodeListOf; - getElementsByTagName(name: "address"): NodeListOf; - getElementsByTagName(name: "applet"): NodeListOf; - getElementsByTagName(name: "area"): NodeListOf; - getElementsByTagName(name: "article"): NodeListOf; - getElementsByTagName(name: "aside"): NodeListOf; - getElementsByTagName(name: "audio"): NodeListOf; - getElementsByTagName(name: "b"): NodeListOf; - getElementsByTagName(name: "base"): NodeListOf; - getElementsByTagName(name: "basefont"): NodeListOf; - getElementsByTagName(name: "bdo"): NodeListOf; - getElementsByTagName(name: "big"): NodeListOf; - getElementsByTagName(name: "blockquote"): NodeListOf; - getElementsByTagName(name: "body"): NodeListOf; - getElementsByTagName(name: "br"): NodeListOf; - getElementsByTagName(name: "button"): NodeListOf; - getElementsByTagName(name: "canvas"): NodeListOf; - getElementsByTagName(name: "caption"): NodeListOf; - getElementsByTagName(name: "center"): NodeListOf; - getElementsByTagName(name: "circle"): NodeListOf; - getElementsByTagName(name: "cite"): NodeListOf; - getElementsByTagName(name: "clippath"): NodeListOf; - getElementsByTagName(name: "code"): NodeListOf; - getElementsByTagName(name: "col"): NodeListOf; - getElementsByTagName(name: "colgroup"): NodeListOf; - getElementsByTagName(name: "datalist"): NodeListOf; - getElementsByTagName(name: "dd"): NodeListOf; - getElementsByTagName(name: "defs"): NodeListOf; - getElementsByTagName(name: "del"): NodeListOf; - getElementsByTagName(name: "desc"): NodeListOf; - getElementsByTagName(name: "dfn"): NodeListOf; - getElementsByTagName(name: "dir"): NodeListOf; - getElementsByTagName(name: "div"): NodeListOf; - getElementsByTagName(name: "dl"): NodeListOf; - getElementsByTagName(name: "dt"): NodeListOf; - getElementsByTagName(name: "ellipse"): NodeListOf; - getElementsByTagName(name: "em"): NodeListOf; - getElementsByTagName(name: "embed"): NodeListOf; - getElementsByTagName(name: "feblend"): NodeListOf; - getElementsByTagName(name: "fecolormatrix"): NodeListOf; - getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(name: "fecomposite"): NodeListOf; - getElementsByTagName(name: "feconvolvematrix"): NodeListOf; - getElementsByTagName(name: "fediffuselighting"): NodeListOf; - getElementsByTagName(name: "fedisplacementmap"): NodeListOf; - getElementsByTagName(name: "fedistantlight"): NodeListOf; - getElementsByTagName(name: "feflood"): NodeListOf; - getElementsByTagName(name: "fefunca"): NodeListOf; - getElementsByTagName(name: "fefuncb"): NodeListOf; - getElementsByTagName(name: "fefuncg"): NodeListOf; - getElementsByTagName(name: "fefuncr"): NodeListOf; - getElementsByTagName(name: "fegaussianblur"): NodeListOf; - getElementsByTagName(name: "feimage"): NodeListOf; - getElementsByTagName(name: "femerge"): NodeListOf; - getElementsByTagName(name: "femergenode"): NodeListOf; - getElementsByTagName(name: "femorphology"): NodeListOf; - getElementsByTagName(name: "feoffset"): NodeListOf; - getElementsByTagName(name: "fepointlight"): NodeListOf; - getElementsByTagName(name: "fespecularlighting"): NodeListOf; - getElementsByTagName(name: "fespotlight"): NodeListOf; - getElementsByTagName(name: "fetile"): NodeListOf; - getElementsByTagName(name: "feturbulence"): NodeListOf; - getElementsByTagName(name: "fieldset"): NodeListOf; - getElementsByTagName(name: "figcaption"): NodeListOf; - getElementsByTagName(name: "figure"): NodeListOf; - getElementsByTagName(name: "filter"): NodeListOf; - getElementsByTagName(name: "font"): NodeListOf; - getElementsByTagName(name: "footer"): NodeListOf; - getElementsByTagName(name: "foreignobject"): NodeListOf; - getElementsByTagName(name: "form"): NodeListOf; - getElementsByTagName(name: "frame"): NodeListOf; - getElementsByTagName(name: "frameset"): NodeListOf; - getElementsByTagName(name: "g"): NodeListOf; - getElementsByTagName(name: "h1"): NodeListOf; - getElementsByTagName(name: "h2"): NodeListOf; - getElementsByTagName(name: "h3"): NodeListOf; - getElementsByTagName(name: "h4"): NodeListOf; - getElementsByTagName(name: "h5"): NodeListOf; - getElementsByTagName(name: "h6"): NodeListOf; - getElementsByTagName(name: "head"): NodeListOf; - getElementsByTagName(name: "header"): NodeListOf; - getElementsByTagName(name: "hgroup"): NodeListOf; - getElementsByTagName(name: "hr"): NodeListOf; - getElementsByTagName(name: "html"): NodeListOf; - getElementsByTagName(name: "i"): NodeListOf; - getElementsByTagName(name: "iframe"): NodeListOf; - getElementsByTagName(name: "image"): NodeListOf; - getElementsByTagName(name: "img"): NodeListOf; - getElementsByTagName(name: "input"): NodeListOf; - getElementsByTagName(name: "ins"): NodeListOf; - getElementsByTagName(name: "isindex"): NodeListOf; - getElementsByTagName(name: "kbd"): NodeListOf; - getElementsByTagName(name: "keygen"): NodeListOf; - getElementsByTagName(name: "label"): NodeListOf; - getElementsByTagName(name: "legend"): NodeListOf; - getElementsByTagName(name: "li"): NodeListOf; - getElementsByTagName(name: "line"): NodeListOf; - getElementsByTagName(name: "lineargradient"): NodeListOf; - getElementsByTagName(name: "link"): NodeListOf; - getElementsByTagName(name: "listing"): NodeListOf; - getElementsByTagName(name: "map"): NodeListOf; - getElementsByTagName(name: "mark"): NodeListOf; - getElementsByTagName(name: "marker"): NodeListOf; - getElementsByTagName(name: "marquee"): NodeListOf; - getElementsByTagName(name: "mask"): NodeListOf; - getElementsByTagName(name: "menu"): NodeListOf; - getElementsByTagName(name: "meta"): NodeListOf; - getElementsByTagName(name: "metadata"): NodeListOf; - getElementsByTagName(name: "meter"): NodeListOf; - getElementsByTagName(name: "nav"): NodeListOf; - getElementsByTagName(name: "nextid"): NodeListOf; - getElementsByTagName(name: "nobr"): NodeListOf; - getElementsByTagName(name: "noframes"): NodeListOf; - getElementsByTagName(name: "noscript"): NodeListOf; - getElementsByTagName(name: "object"): NodeListOf; - getElementsByTagName(name: "ol"): NodeListOf; - getElementsByTagName(name: "optgroup"): NodeListOf; - getElementsByTagName(name: "option"): NodeListOf; - getElementsByTagName(name: "p"): NodeListOf; - getElementsByTagName(name: "param"): NodeListOf; - getElementsByTagName(name: "path"): NodeListOf; - getElementsByTagName(name: "pattern"): NodeListOf; - getElementsByTagName(name: "picture"): NodeListOf; - getElementsByTagName(name: "plaintext"): NodeListOf; - getElementsByTagName(name: "polygon"): NodeListOf; - getElementsByTagName(name: "polyline"): NodeListOf; - getElementsByTagName(name: "pre"): NodeListOf; - getElementsByTagName(name: "progress"): NodeListOf; - getElementsByTagName(name: "q"): NodeListOf; - getElementsByTagName(name: "radialgradient"): NodeListOf; - getElementsByTagName(name: "rect"): NodeListOf; - getElementsByTagName(name: "rt"): NodeListOf; - getElementsByTagName(name: "ruby"): NodeListOf; - getElementsByTagName(name: "s"): NodeListOf; - getElementsByTagName(name: "samp"): NodeListOf; - getElementsByTagName(name: "script"): NodeListOf; - getElementsByTagName(name: "section"): NodeListOf; - getElementsByTagName(name: "select"): NodeListOf; - getElementsByTagName(name: "small"): NodeListOf; - getElementsByTagName(name: "source"): NodeListOf; - getElementsByTagName(name: "span"): NodeListOf; - getElementsByTagName(name: "stop"): NodeListOf; - getElementsByTagName(name: "strike"): NodeListOf; - getElementsByTagName(name: "strong"): NodeListOf; - getElementsByTagName(name: "style"): NodeListOf; - getElementsByTagName(name: "sub"): NodeListOf; - getElementsByTagName(name: "sup"): NodeListOf; - getElementsByTagName(name: "svg"): NodeListOf; - getElementsByTagName(name: "switch"): NodeListOf; - getElementsByTagName(name: "symbol"): NodeListOf; - getElementsByTagName(name: "table"): NodeListOf; - getElementsByTagName(name: "tbody"): NodeListOf; - getElementsByTagName(name: "td"): NodeListOf; - getElementsByTagName(name: "template"): NodeListOf; - getElementsByTagName(name: "text"): NodeListOf; - getElementsByTagName(name: "textpath"): NodeListOf; - getElementsByTagName(name: "textarea"): NodeListOf; - getElementsByTagName(name: "tfoot"): NodeListOf; - getElementsByTagName(name: "th"): NodeListOf; - getElementsByTagName(name: "thead"): NodeListOf; - getElementsByTagName(name: "title"): NodeListOf; - getElementsByTagName(name: "tr"): NodeListOf; - getElementsByTagName(name: "track"): NodeListOf; - getElementsByTagName(name: "tspan"): NodeListOf; - getElementsByTagName(name: "tt"): NodeListOf; - getElementsByTagName(name: "u"): NodeListOf; - getElementsByTagName(name: "ul"): NodeListOf; - getElementsByTagName(name: "use"): NodeListOf; - getElementsByTagName(name: "var"): NodeListOf; - getElementsByTagName(name: "video"): NodeListOf; - getElementsByTagName(name: "view"): NodeListOf; - getElementsByTagName(name: "wbr"): NodeListOf; - getElementsByTagName(name: "x-ms-webview"): NodeListOf; - getElementsByTagName(name: "xmp"): NodeListOf; - getElementsByTagName(name: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - hasAttribute(name: string): boolean; - hasAttributeNS(namespaceURI: string, localName: string): boolean; - msGetRegionContent(): MSRangeCollection; - msGetUntransformedBounds(): ClientRect; - msMatchesSelector(selectors: string): boolean; - msReleasePointerCapture(pointerId: number): void; - msSetPointerCapture(pointerId: number): void; - msZoomTo(args: MsZoomToOptions): void; - releasePointerCapture(pointerId: number): void; - removeAttribute(name?: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; - removeAttributeNode(oldAttr: Attr): Attr; - requestFullscreen(): void; - requestPointerLock(): void; - setAttribute(name: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; - setAttributeNode(newAttr: Attr): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; - setPointerCapture(pointerId: number): void; - webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; - webkitRequestFullscreen(): void; - getElementsByClassName(classNames: string): NodeListOf; - matches(selector: string): boolean; - closest(selector: string): Element | null; - scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; - scroll(options?: ScrollToOptions): void; - scroll(x: number, y: number): void; - scrollTo(options?: ScrollToOptions): void; - scrollTo(x: number, y: number): void; - scrollBy(options?: ScrollToOptions): void; - scrollBy(x: number, y: number): void; - insertAdjacentElement(position: string, insertedElement: Element): Element | null; - insertAdjacentHTML(where: string, html: string): void; - insertAdjacentText(where: string, text: string): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Element: { - prototype: Element; - new(): Element; -} - -interface ErrorEvent extends Event { - readonly colno: number; - readonly error: any; - readonly filename: string; - readonly lineno: number; - readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; -} - -declare var ErrorEvent: { - prototype: ErrorEvent; - new(): ErrorEvent; -} - -interface Event { - readonly bubbles: boolean; - cancelBubble: boolean; - readonly cancelable: boolean; - readonly currentTarget: EventTarget; - readonly defaultPrevented: boolean; - readonly eventPhase: number; - readonly isTrusted: boolean; - returnValue: boolean; - readonly srcElement: Element | null; - readonly target: EventTarget; - readonly timeStamp: number; - readonly type: string; - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; - preventDefault(): void; - stopImmediatePropagation(): void; - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -declare var Event: { - prototype: Event; - new(type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -interface EventTarget { - addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var EventTarget: { - prototype: EventTarget; - new(): EventTarget; -} - -interface External { -} - -declare var External: { - prototype: External; - new(): External; -} - -interface File extends Blob { - readonly lastModifiedDate: any; - readonly name: string; - readonly webkitRelativePath: string; -} - -declare var File: { - prototype: File; - new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} - -interface FileList { - readonly length: number; - item(index: number): File; - [index: number]: File; -} - -declare var FileList: { - prototype: FileList; - new(): FileList; -} - -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(blob: Blob): void; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var FileReader: { - prototype: FileReader; - new(): FileReader; -} - -interface FocusEvent extends UIEvent { - readonly relatedTarget: EventTarget; - initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; -} - -declare var FocusEvent: { - prototype: FocusEvent; - new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} - -interface FormData { - append(name: any, value: any, blobName?: string): void; -} - -declare var FormData: { - prototype: FormData; - new (form?: HTMLFormElement): FormData; -} - -interface GainNode extends AudioNode { - readonly gain: AudioParam; -} - -declare var GainNode: { - prototype: GainNode; - new(): GainNode; -} - -interface Gamepad { - readonly axes: number[]; - readonly buttons: GamepadButton[]; - readonly connected: boolean; - readonly id: string; - readonly index: number; - readonly mapping: string; - readonly timestamp: number; -} - -declare var Gamepad: { - prototype: Gamepad; - new(): Gamepad; -} - -interface GamepadButton { - readonly pressed: boolean; - readonly value: number; -} - -declare var GamepadButton: { - prototype: GamepadButton; - new(): GamepadButton; -} - -interface GamepadEvent extends Event { - readonly gamepad: Gamepad; -} - -declare var GamepadEvent: { - prototype: GamepadEvent; - new(): GamepadEvent; -} - -interface Geolocation { - clearWatch(watchId: number): void; - getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; - watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; -} - -declare var Geolocation: { - prototype: Geolocation; - new(): Geolocation; -} - -interface HTMLAllCollection extends HTMLCollection { - namedItem(name: string): Element; -} - -declare var HTMLAllCollection: { - prototype: HTMLAllCollection; - new(): HTMLAllCollection; -} - -interface HTMLAnchorElement extends HTMLElement { - Methods: string; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Contains the anchor portion of the URL including the hash sign (#). - */ - hash: string; - /** - * Contains the hostname and port values of the URL. - */ - host: string; - /** - * Contains the hostname of a URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - readonly mimeType: string; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - readonly nameProp: string; - /** - * Contains the pathname of the URL. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Contains the protocol of the URL. - */ - protocol: string; - readonly protocolLong: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: 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; -} - -declare var HTMLAnchorElement: { - prototype: HTMLAnchorElement; - new(): HTMLAnchorElement; -} - -interface HTMLAppletElement extends HTMLElement { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - /** - * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. - */ - declare: boolean; - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Sets or retrieves the shape of the object. - */ - name: string; - object: string | null; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - vspace: number; - width: number; -} - -declare var HTMLAppletElement: { - prototype: HTMLAppletElement; - new(): HTMLAppletElement; -} - -interface HTMLAreaElement extends HTMLElement { - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Sets or retrieves the coordinates of the object. - */ - coords: string; - download: string; - /** - * Sets or retrieves the subsection of the href property that follows the number sign (#). - */ - hash: string; - /** - * Sets or retrieves the hostname and port number of the location or URL. - */ - host: string; - /** - * Sets or retrieves the host name part of the location or URL. - */ - hostname: string; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or gets whether clicks in this region cause action. - */ - noHref: boolean; - /** - * Sets or retrieves the file name or path specified by the object. - */ - pathname: string; - /** - * Sets or retrieves the port number associated with a URL. - */ - port: string; - /** - * Sets or retrieves the protocol portion of a URL. - */ - protocol: string; - rel: string; - /** - * Sets or retrieves the substring of the href property that follows the question mark. - */ - search: string; - /** - * Sets or retrieves the shape of the object. - */ - shape: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns a string representation of an object. - */ - toString(): string; -} - -declare var HTMLAreaElement: { - prototype: HTMLAreaElement; - new(): HTMLAreaElement; -} - -interface HTMLAreasCollection extends HTMLCollection { - /** - * Adds an element to the areas, controlRange, or options collection. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Removes an element from the collection. - */ - remove(index?: number): void; -} - -declare var HTMLAreasCollection: { - prototype: HTMLAreasCollection; - new(): HTMLAreasCollection; -} - -interface HTMLAudioElement extends HTMLMediaElement { -} - -declare var HTMLAudioElement: { - prototype: HTMLAudioElement; - new(): HTMLAudioElement; -} - -interface HTMLBRElement extends HTMLElement { - /** - * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. - */ - clear: string; -} - -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} - -interface HTMLBaseElement extends HTMLElement { - /** - * Gets or sets the baseline URL on which relative links are based. - */ - href: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; -} - -declare var HTMLBaseElement: { - prototype: HTMLBaseElement; - new(): HTMLBaseElement; -} - -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - /** - * Sets or retrieves the font size of the object. - */ - size: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -} - -interface HTMLBodyElement extends HTMLElement { - aLink: any; - background: string; - bgColor: any; - bgProperties: string; - link: any; - noWrap: boolean; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - text: any; - vLink: any; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLBodyElement: { - prototype: HTMLBodyElement; - new(): HTMLBodyElement; -} - -interface HTMLButtonElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - status: any; - /** - * Gets the classification and default behavior of the button. - */ - type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * 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; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLButtonElement: { - prototype: HTMLButtonElement; - new(): HTMLButtonElement; -} - -interface HTMLCanvasElement extends HTMLElement { - /** - * Gets or sets the height of a canvas element on a document. - */ - height: number; - /** - * Gets or sets the width of a canvas element on a document. - */ - width: number; - /** - * 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", 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. - */ - msToBlob(): Blob; - /** - * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. - * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; -} - -declare var HTMLCanvasElement: { - prototype: HTMLCanvasElement; - new(): HTMLCanvasElement; -} - -interface HTMLCollection { - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Retrieves an object from various collections. - */ - item(index: number): Element; - /** - * Retrieves a select object or an object from an options collection. - */ - namedItem(name: string): Element; - [index: number]: Element; -} - -declare var HTMLCollection: { - prototype: HTMLCollection; - new(): HTMLCollection; -} - -interface HTMLDListElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} - -interface HTMLDataListElement extends HTMLElement { - options: HTMLCollectionOf; -} - -declare var HTMLDataListElement: { - prototype: HTMLDataListElement; - new(): HTMLDataListElement; -} - -interface HTMLDirectoryElement extends HTMLElement { - compact: boolean; -} - -declare var HTMLDirectoryElement: { - prototype: HTMLDirectoryElement; - new(): HTMLDirectoryElement; -} - -interface HTMLDivElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; -} - -declare var HTMLDivElement: { - prototype: HTMLDivElement; - new(): HTMLDivElement; -} - -interface HTMLDocument extends Document { -} - -declare var HTMLDocument: { - prototype: HTMLDocument; - new(): HTMLDocument; -} - -interface HTMLElement extends Element { - accessKey: string; - readonly children: HTMLCollection; - contentEditable: string; - readonly dataset: DOMStringMap; - dir: string; - draggable: boolean; - hidden: boolean; - hideFocus: boolean; - innerHTML: string; - innerText: string; - readonly isContentEditable: boolean; - lang: string; - readonly offsetHeight: number; - readonly offsetLeft: number; - readonly offsetParent: Element; - readonly offsetTop: number; - readonly offsetWidth: number; - onabort: (this: this, ev: UIEvent) => any; - onactivate: (this: this, ev: UIEvent) => any; - onbeforeactivate: (this: this, ev: UIEvent) => any; - onbeforecopy: (this: this, ev: ClipboardEvent) => any; - onbeforecut: (this: this, ev: ClipboardEvent) => any; - onbeforedeactivate: (this: this, ev: UIEvent) => any; - onbeforepaste: (this: this, ev: ClipboardEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - oncopy: (this: this, ev: ClipboardEvent) => any; - oncuechange: (this: this, ev: Event) => any; - oncut: (this: this, ev: ClipboardEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondeactivate: (this: this, ev: UIEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onpaste: (this: this, ev: ClipboardEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreset: (this: this, ev: Event) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onselectstart: (this: this, ev: Event) => any; - onstalled: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - outerHTML: string; - outerText: string; - spellcheck: boolean; - readonly style: CSSStyleDeclaration; - tabIndex: number; - title: string; - blur(): void; - click(): void; - dragDrop(): boolean; - focus(): void; - msGetInputContext(): MSInputMethodContext; - setActive(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLElement: { - prototype: HTMLElement; - new(): HTMLElement; -} - -interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves the height of the object. - */ - height: string; - hidden: any; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the palette used for the embedded document. - */ - readonly palette: string; - /** - * Retrieves the URL of the plug-in used to view an embedded document. - */ - readonly pluginspage: string; - readonly readyState: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the height and width units of the embed object. - */ - units: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLEmbedElement: { - prototype: HTMLEmbedElement; - new(): HTMLEmbedElement; -} - -interface HTMLFieldSetElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; -} - -declare var HTMLFieldSetElement: { - prototype: HTMLFieldSetElement; - new(): HTMLFieldSetElement; -} - -interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves the current typeface family. - */ - face: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFontElement: { - prototype: HTMLFontElement; - new(): HTMLFontElement; -} - -interface HTMLFormElement extends HTMLElement { - /** - * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. - */ - acceptCharset: string; - /** - * Sets or retrieves the URL to which the form content is sent for processing. - */ - action: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Retrieves a collection, in source order, of all controls in a given form. - */ - readonly elements: HTMLCollection; - /** - * Sets or retrieves the MIME encoding for the form. - */ - encoding: string; - /** - * Sets or retrieves the encoding type for the form. - */ - enctype: string; - /** - * Sets or retrieves the number of objects in a collection. - */ - readonly length: number; - /** - * Sets or retrieves how to send the form data to the server. - */ - method: string; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Designates a form that is not validated when submitted. - */ - noValidate: boolean; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a form object or an object from an elements collection. - */ - namedItem(name: string): any; - /** - * Fires when the user resets a form. - */ - reset(): void; - /** - * Fires when a FORM is about to be submitted. - */ - submit(): void; - [name: string]: any; -} - -declare var HTMLFormElement: { - prototype: HTMLFormElement; - new(): HTMLFormElement; -} - -interface HTMLFrameElement extends HTMLElement, GetSVGDocument { - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string | number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the width of the object. - */ - width: string | number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameElement: { - prototype: HTMLFrameElement; - new(): HTMLFrameElement; -} - -interface HTMLFrameSetElement extends HTMLElement { - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Sets or retrieves the frame widths of the object. - */ - cols: string; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - name: string; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; - /** - * Sets or retrieves the frame heights of the object. - */ - rows: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLFrameSetElement: { - prototype: HTMLFrameSetElement; - new(): HTMLFrameSetElement; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. - */ - noShade: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} - -interface HTMLHeadElement extends HTMLElement { - profile: string; -} - -declare var HTMLHeadElement: { - prototype: HTMLHeadElement; - new(): HTMLHeadElement; -} - -interface HTMLHeadingElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; -} - -declare var HTMLHeadingElement: { - prototype: HTMLHeadingElement; - new(): HTMLHeadingElement; -} - -interface HTMLHtmlElement extends HTMLElement { - /** - * Sets or retrieves the DTD version that governs the current document. - */ - version: string; -} - -declare var HTMLHtmlElement: { - prototype: HTMLHtmlElement; - new(): HTMLHtmlElement; -} - -interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - allowFullscreen: boolean; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Retrieves the object of the specified. - */ - readonly contentWindow: Window; - /** - * Sets or retrieves whether to display a border for the frame. - */ - frameBorder: string; - /** - * Sets or retrieves the amount of additional space between the frames. - */ - frameSpacing: any; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the horizontal margin for the object. - */ - hspace: number; - /** - * Sets or retrieves a URI to a long description of the object. - */ - longDesc: string; - /** - * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. - */ - marginHeight: string; - /** - * Sets or retrieves the left and right margin widths before displaying the text in a frame. - */ - marginWidth: string; - /** - * Sets or retrieves the frame name. - */ - name: string; - /** - * Sets or retrieves whether the user can resize the frame. - */ - noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: this, ev: Event) => any; - readonly sandbox: DOMSettableTokenList; - /** - * Sets or retrieves whether the frame can be scrolled. - */ - scrolling: string; - /** - * Sets or retrieves a URL to be loaded by the object. - */ - src: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLIFrameElement: { - prototype: HTMLIFrameElement; - new(): HTMLIFrameElement; -} - -interface HTMLImageElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies the properties of a border drawn around an object. - */ - border: string; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - crossOrigin: string; - readonly currentSrc: string; - /** - * Sets or retrieves the height of the object. - */ - height: number; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - /** - * Sets or retrieves whether the image is a server-side image map. - */ - isMap: boolean; - /** - * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. - */ - longDesc: string; - lowsrc: string; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * The original height of the image resource before sizing. - */ - readonly naturalHeight: number; - /** - * The original width of the image resource before sizing. - */ - readonly naturalWidth: number; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: number; - readonly x: number; - readonly y: number; - msGetAsCastingSource(): any; -} - -declare var HTMLImageElement: { - prototype: HTMLImageElement; - new(): HTMLImageElement; - create(): HTMLImageElement; -} - -interface HTMLInputElement extends HTMLElement { - /** - * Sets or retrieves a comma-separated list of content types. - */ - accept: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Specifies whether autocomplete is applied to an editable text field. - */ - autocomplete: string; - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the state of the check box or radio button. - */ - checked: boolean; - /** - * Retrieves whether the object is fully loaded. - */ - readonly complete: boolean; - /** - * Sets or retrieves the state of the check box or radio button. - */ - defaultChecked: boolean; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Returns a FileList object on a file type input object. - */ - readonly files: FileList | null; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Overrides the action attribute (where the data on a form is sent) on the parent form element. - */ - formAction: string; - /** - * Used to override the encoding (formEnctype attribute) specified on the form element. - */ - formEnctype: string; - /** - * Overrides the submit method attribute previously specified on a form element. - */ - formMethod: string; - /** - * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. - */ - formNoValidate: string; - /** - * Overrides the target attribute on a form element. - */ - formTarget: string; - /** - * Sets or retrieves the height of the object. - */ - height: string; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - hspace: number; - indeterminate: boolean; - /** - * Specifies the ID of a pre-defined datalist of options for an input element. - */ - readonly list: HTMLElement; - /** - * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. - */ - max: string; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. - */ - min: string; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a string containing a regular expression that the user's input must match. - */ - pattern: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - selectionDirection: string; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - size: number; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - status: boolean; - /** - * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. - */ - step: string; - /** - * Returns the content type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Returns the value of the data at the cursor's current position. - */ - value: string; - valueAsDate: Date; - /** - * Returns the input field value as a number. - */ - valueAsNumber: number; - /** - * Sets or retrieves the vertical margin for the object. - */ - vspace: number; - webkitdirectory: boolean; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Makes the selection equal to the current object. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start?: number, end?: number, direction?: string): void; - /** - * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. - * @param n Value to decrement the value by. - */ - stepDown(n?: number): void; - /** - * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. - * @param n Value to increment the value by. - */ - stepUp(n?: number): void; -} - -declare var HTMLInputElement: { - prototype: HTMLInputElement; - new(): HTMLInputElement; -} - -interface HTMLLIElement extends HTMLElement { - type: string; - /** - * Sets or retrieves the value of a list item. - */ - value: number; -} - -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} - -interface HTMLLabelElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the object to which the given label object is assigned. - */ - htmlFor: string; -} - -declare var HTMLLabelElement: { - prototype: HTMLLabelElement; - new(): HTMLLabelElement; -} - -interface HTMLLegendElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - align: string; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; -} - -declare var HTMLLegendElement: { - prototype: HTMLLegendElement; - new(): HTMLLegendElement; -} - -interface HTMLLinkElement extends HTMLElement, LinkStyle { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - disabled: boolean; - /** - * Sets or retrieves a destination URL or an anchor point. - */ - href: string; - /** - * Sets or retrieves the language code of the object. - */ - hreflang: string; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rel: string; - /** - * Sets or retrieves the relationship between the object and the destination of the link. - */ - rev: string; - /** - * Sets or retrieves the window or frame at which to target content. - */ - target: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - import?: Document; - integrity: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLLinkElement: { - prototype: HTMLLinkElement; - new(): HTMLLinkElement; -} - -interface HTMLMapElement extends HTMLElement { - /** - * Retrieves a collection of the area objects defined for the given map object. - */ - readonly areas: HTMLAreasCollection; - /** - * Sets or retrieves the name of the object. - */ - name: string; -} - -declare var HTMLMapElement: { - prototype: HTMLMapElement; - new(): HTMLMapElement; -} - -interface HTMLMarqueeElement extends HTMLElement { - behavior: string; - bgColor: any; - direction: string; - height: string; - hspace: number; - loop: number; - onbounce: (this: this, ev: Event) => any; - onfinish: (this: this, ev: Event) => any; - onstart: (this: this, ev: Event) => any; - scrollAmount: number; - scrollDelay: number; - trueSpeed: boolean; - vspace: number; - width: string; - start(): void; - stop(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "bounce", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "finish", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "start", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMarqueeElement: { - prototype: HTMLMarqueeElement; - new(): HTMLMarqueeElement; -} - -interface HTMLMediaElement extends HTMLElement { - /** - * Returns an AudioTrackList object with the audio tracks for a given video element. - */ - readonly audioTracks: AudioTrackList; - /** - * Gets or sets a value that indicates whether to start playing the media automatically. - */ - autoplay: boolean; - /** - * Gets a collection of buffered time ranges. - */ - readonly buffered: TimeRanges; - /** - * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). - */ - controls: boolean; - crossOrigin: string; - /** - * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. - */ - readonly currentSrc: string; - /** - * Gets or sets the current playback position, in seconds. - */ - currentTime: number; - defaultMuted: boolean; - /** - * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. - */ - defaultPlaybackRate: number; - /** - * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. - */ - readonly duration: number; - /** - * Gets information about whether the playback has ended or not. - */ - readonly ended: boolean; - /** - * Returns an object representing the current error state of the audio or video element. - */ - readonly error: MediaError; - /** - * Gets or sets a flag to specify whether playback should restart after it completes. - */ - loop: boolean; - readonly mediaKeys: MediaKeys | null; - /** - * Specifies the purpose of the audio or video media, such as background audio or alerts. - */ - msAudioCategory: string; - /** - * Specifies the output device id that the audio will be sent to. - */ - msAudioDeviceType: string; - readonly msGraphicsTrustStatus: MSGraphicsTrust; - /** - * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. - */ - readonly msKeys: MSMediaKeys; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Specifies whether or not to enable low-latency playback on the media element. - */ - msRealTime: boolean; - /** - * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. - */ - muted: boolean; - /** - * Gets the current network activity for the element. - */ - readonly networkState: number; - onencrypted: (this: this, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: this, ev: MSMediaKeyNeededEvent) => any; - /** - * Gets a flag that specifies whether playback is paused. - */ - readonly paused: boolean; - /** - * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. - */ - playbackRate: number; - /** - * Gets TimeRanges for the current media resource that has been played. - */ - readonly played: TimeRanges; - /** - * Gets or sets the current playback position, in seconds. - */ - preload: string; - readyState: number; - /** - * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. - */ - readonly seekable: TimeRanges; - /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. - */ - readonly seeking: boolean; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcObject: MediaStream | null; - readonly textTracks: TextTrackList; - readonly videoTracks: VideoTrackList; - /** - * Gets or sets the volume level for audio portions of the media element. - */ - volume: number; - addTextTrack(kind: string, label?: string, language?: string): TextTrack; - /** - * Returns a string that specifies whether the client can play a given media resource type. - */ - canPlayType(type: string): string; - /** - * Resets the audio or video object and loads a new media resource. - */ - load(): void; - /** - * Clears all effects from the media pipeline. - */ - msClearEffects(): void; - msGetAsCastingSource(): any; - /** - * Inserts the specified audio effect into media pipeline. - */ - msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetMediaKeys(mediaKeys: MSMediaKeys): void; - /** - * Specifies the media protection manager for a given media pipeline. - */ - msSetMediaProtectionManager(mediaProtectionManager?: any): void; - /** - * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. - */ - pause(): void; - /** - * Loads and starts playback of a media resource. - */ - play(): void; - setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLMediaElement: { - prototype: HTMLMediaElement; - new(): HTMLMediaElement; - readonly HAVE_CURRENT_DATA: number; - readonly HAVE_ENOUGH_DATA: number; - readonly HAVE_FUTURE_DATA: number; - readonly HAVE_METADATA: number; - readonly HAVE_NOTHING: number; - readonly NETWORK_EMPTY: number; - readonly NETWORK_IDLE: number; - readonly NETWORK_LOADING: number; - readonly NETWORK_NO_SOURCE: number; -} - -interface HTMLMenuElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLMenuElement: { - prototype: HTMLMenuElement; - new(): HTMLMenuElement; -} - -interface HTMLMetaElement extends HTMLElement { - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Gets or sets meta-information to associate with httpEquiv or name. - */ - content: string; - /** - * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. - */ - httpEquiv: string; - /** - * Sets or retrieves the value specified in the content attribute of the meta object. - */ - name: string; - /** - * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. - */ - scheme: string; - /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ - url: string; -} - -declare var HTMLMetaElement: { - prototype: HTMLMetaElement; - new(): HTMLMetaElement; -} - -interface HTMLMeterElement extends HTMLElement { - high: number; - low: number; - max: number; - min: number; - optimum: number; - value: number; -} - -declare var HTMLMeterElement: { - prototype: HTMLMeterElement; - new(): HTMLMeterElement; -} - -interface HTMLModElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; - /** - * Sets or retrieves the date and time of a modification to the object. - */ - dateTime: string; -} - -declare var HTMLModElement: { - prototype: HTMLModElement; - new(): HTMLModElement; -} - -interface HTMLOListElement extends HTMLElement { - compact: boolean; - /** - * The starting number. - */ - start: number; - type: string; -} - -declare var HTMLOListElement: { - prototype: HTMLOListElement; - new(): HTMLOListElement; -} - -interface HTMLObjectElement extends HTMLElement, GetSVGDocument { - /** - * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. - */ - readonly BaseHref: string; - align: string; - /** - * Sets or retrieves a text alternative to the graphic. - */ - alt: string; - /** - * Gets or sets the optional alternative HTML script to execute if the object fails to load. - */ - altHtml: string; - /** - * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. - */ - archive: string; - border: string; - /** - * Sets or retrieves the URL of the file containing the compiled Java class. - */ - code: string; - /** - * Sets or retrieves the URL of the component. - */ - codeBase: string; - /** - * Sets or retrieves the Internet media type for the code associated with the object. - */ - codeType: string; - /** - * Retrieves the document object of the page or frame. - */ - readonly contentDocument: Document; - /** - * Sets or retrieves the URL that references the data of the object. - */ - data: string; - declare: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the height of the object. - */ - height: string; - hspace: number; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - /** - * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. - */ - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Retrieves the contained object. - */ - readonly object: any; - readonly readyState: number; - /** - * Sets or retrieves a message to be displayed while an object is loading. - */ - standby: string; - /** - * Sets or retrieves the MIME type of the object. - */ - type: string; - /** - * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. - */ - useMap: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - vspace: number; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} - -interface HTMLOptGroupElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - readonly text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptGroupElement: { - prototype: HTMLOptGroupElement; - new(): HTMLOptGroupElement; -} - -interface HTMLOptionElement extends HTMLElement { - /** - * Sets or retrieves the status of an option. - */ - defaultSelected: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the ordinal position of an option in a list box. - */ - readonly index: number; - /** - * Sets or retrieves a value that you can use to implement your own label functionality for the object. - */ - label: string; - /** - * Sets or retrieves whether the option in the list box is the default item. - */ - selected: boolean; - /** - * Sets or retrieves the text string specified by the option tag. - */ - text: string; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; -} - -declare var HTMLOptionElement: { - prototype: HTMLOptionElement; - new(): HTMLOptionElement; - create(): HTMLOptionElement; -} - -interface HTMLOptionsCollection extends HTMLCollectionOf { - length: number; - selectedIndex: number; - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; - remove(index: number): void; -} - -declare var HTMLOptionsCollection: { - prototype: HTMLOptionsCollection; - new(): HTMLOptionsCollection; -} - -interface HTMLParagraphElement extends HTMLElement { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - clear: string; -} - -declare var HTMLParagraphElement: { - prototype: HTMLParagraphElement; - new(): HTMLParagraphElement; -} - -interface HTMLParamElement extends HTMLElement { - /** - * Sets or retrieves the name of an input parameter for an element. - */ - name: string; - /** - * Sets or retrieves the content type of the resource designated by the value attribute. - */ - type: string; - /** - * Sets or retrieves the value of an input parameter for an element. - */ - value: string; - /** - * Sets or retrieves the data type of the value attribute. - */ - valueType: string; -} - -declare var HTMLParamElement: { - prototype: HTMLParamElement; - new(): HTMLParamElement; -} - -interface HTMLPictureElement extends HTMLElement { -} - -declare var HTMLPictureElement: { - prototype: HTMLPictureElement; - new(): HTMLPictureElement; -} - -interface HTMLPreElement extends HTMLElement { - /** - * Sets or gets a value that you can use to implement your own width functionality for the object. - */ - width: number; -} - -declare var HTMLPreElement: { - prototype: HTMLPreElement; - new(): HTMLPreElement; -} - -interface HTMLProgressElement extends HTMLElement { - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Defines the maximum, or "done" value for a progress element. - */ - max: number; - /** - * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). - */ - readonly position: number; - /** - * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. - */ - value: number; -} - -declare var HTMLProgressElement: { - prototype: HTMLProgressElement; - new(): HTMLProgressElement; -} - -interface HTMLQuoteElement extends HTMLElement { - /** - * Sets or retrieves reference information about the object. - */ - cite: string; -} - -declare var HTMLQuoteElement: { - prototype: HTMLQuoteElement; - new(): HTMLQuoteElement; -} - -interface HTMLScriptElement extends HTMLElement { - async: boolean; - /** - * Sets or retrieves the character set used to encode the object. - */ - charset: string; - /** - * Sets or retrieves the status of the script. - */ - defer: boolean; - /** - * 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; - /** - * Retrieves the URL to an external file that contains the source code or data. - */ - src: string; - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; - /** - * Sets or retrieves the MIME type for the associated scripting engine. - */ - type: string; - integrity: string; -} - -declare var HTMLScriptElement: { - prototype: HTMLScriptElement; - new(): HTMLScriptElement; -} - -interface HTMLSelectElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the number of objects in a collection. - */ - length: number; - /** - * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. - */ - multiple: boolean; - /** - * Sets or retrieves the name of the object. - */ - name: string; - readonly options: HTMLOptionsCollection; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the index of the selected option in a select object. - */ - selectedIndex: number; - selectedOptions: HTMLCollectionOf; - /** - * Sets or retrieves the number of rows in the list box. - */ - size: number; - /** - * Retrieves the type of select control based on the value of the MULTIPLE attribute. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Sets or retrieves the value which is returned to the server when the form control is submitted. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * 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. - */ - add(element: HTMLElement, before?: HTMLElement | number): void; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Retrieves a select object or an object from an options collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a select object or an object from an options collection. - * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. - */ - namedItem(name: string): any; - /** - * Removes an element from the collection. - * @param index Number that specifies the zero-based index of the element to remove from the collection. - */ - remove(index?: number): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - [name: string]: any; -} - -declare var HTMLSelectElement: { - prototype: HTMLSelectElement; - new(): HTMLSelectElement; -} - -interface HTMLSourceElement extends HTMLElement { - /** - * Gets or sets the intended media type of the media source. - */ - media: string; - msKeySystem: string; - sizes: string; - /** - * The address or URL of the a media resource that is to be considered. - */ - src: string; - srcset: string; - /** - * Gets or sets the MIME type of a media resource. - */ - type: string; -} - -declare var HTMLSourceElement: { - prototype: HTMLSourceElement; - new(): HTMLSourceElement; -} - -interface HTMLSpanElement extends HTMLElement { -} - -declare var HTMLSpanElement: { - prototype: HTMLSpanElement; - new(): HTMLSpanElement; -} - -interface HTMLStyleElement extends HTMLElement, LinkStyle { - disabled: boolean; - /** - * Sets or retrieves the media type. - */ - media: string; - /** - * Retrieves the CSS language in which the style sheet is written. - */ - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLStyleElement: { - prototype: HTMLStyleElement; - new(): HTMLStyleElement; -} - -interface HTMLTableCaptionElement extends HTMLElement { - /** - * Sets or retrieves the alignment of the caption or legend. - */ - align: string; - /** - * Sets or retrieves whether the caption appears at the top or bottom of the table. - */ - vAlign: string; -} - -declare var HTMLTableCaptionElement: { - prototype: HTMLTableCaptionElement; - new(): HTMLTableCaptionElement; -} - -interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves abbreviated text for the object. - */ - abbr: string; - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - /** - * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. - */ - axis: string; - bgColor: any; - /** - * Retrieves the position of the object in the cells collection of a row. - */ - readonly cellIndex: number; - /** - * Sets or retrieves the number columns in the table that the object should span. - */ - colSpan: number; - /** - * Sets or retrieves a list of header cells that provide information for the object. - */ - headers: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; - /** - * Sets or retrieves how many rows in a table the cell should span. - */ - rowSpan: number; - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; - /** - * Sets or retrieves the width of the object. - */ - width: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableCellElement: { - prototype: HTMLTableCellElement; - new(): HTMLTableCellElement; -} - -interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves the alignment of the object relative to the display or table. - */ - align: string; - /** - * Sets or retrieves the number of columns in the group. - */ - span: number; - /** - * Sets or retrieves the width of the object. - */ - width: any; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableColElement: { - prototype: HTMLTableColElement; - new(): HTMLTableColElement; -} - -interface HTMLTableDataCellElement extends HTMLTableCellElement { -} - -declare var HTMLTableDataCellElement: { - prototype: HTMLTableDataCellElement; - new(): HTMLTableDataCellElement; -} - -interface HTMLTableElement extends HTMLElement { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - bgColor: any; - /** - * Sets or retrieves the width of the border to draw around the object. - */ - border: string; - /** - * Sets or retrieves the border color of the object. - */ - borderColor: any; - /** - * Retrieves the caption object of a table. - */ - caption: HTMLTableCaptionElement; - /** - * Sets or retrieves the amount of space between the border of the cell and the content of the cell. - */ - cellPadding: string; - /** - * Sets or retrieves the amount of space between cells in a table. - */ - cellSpacing: string; - /** - * Sets or retrieves the number of columns in the table. - */ - cols: number; - /** - * Sets or retrieves the way the border frame around the table is displayed. - */ - frame: string; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Sets or retrieves which dividing lines (inner borders) are displayed. - */ - rules: string; - /** - * Sets or retrieves a description and/or structure of the object. - */ - summary: string; - /** - * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. - */ - tBodies: HTMLCollectionOf; - /** - * Retrieves the tFoot object of the table. - */ - tFoot: HTMLTableSectionElement; - /** - * Retrieves the tHead object of the table. - */ - tHead: HTMLTableSectionElement; - /** - * Sets or retrieves the width of the object. - */ - width: string; - /** - * Creates an empty caption element in the table. - */ - createCaption(): HTMLTableCaptionElement; - /** - * Creates an empty tBody element in the table. - */ - createTBody(): HTMLTableSectionElement; - /** - * Creates an empty tFoot element in the table. - */ - createTFoot(): HTMLTableSectionElement; - /** - * Returns the tHead element object if successful, or null otherwise. - */ - createTHead(): HTMLTableSectionElement; - /** - * Deletes the caption element and its contents from the table. - */ - deleteCaption(): void; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Deletes the tFoot element and its contents from the table. - */ - deleteTFoot(): void; - /** - * Deletes the tHead element and its contents from the table. - */ - deleteTHead(): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; -} - -declare var HTMLTableElement: { - prototype: HTMLTableElement; - new(): HTMLTableElement; -} - -interface HTMLTableHeaderCellElement extends HTMLTableCellElement { - /** - * Sets or retrieves the group of cells in a table to which the object's information applies. - */ - scope: string; -} - -declare var HTMLTableHeaderCellElement: { - prototype: HTMLTableHeaderCellElement; - new(): HTMLTableHeaderCellElement; -} - -interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves how the object is aligned with adjacent text. - */ - align: string; - bgColor: any; - /** - * Retrieves a collection of all cells in the table row. - */ - cells: HTMLCollectionOf; - /** - * Sets or retrieves the height of the object. - */ - height: any; - /** - * Retrieves the position of the object in the rows collection for the table. - */ - readonly rowIndex: number; - /** - * Retrieves the position of the object in the collection. - */ - readonly sectionRowIndex: number; - /** - * Removes the specified cell from the table row, as well as from the cells collection. - * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. - */ - deleteCell(index?: number): void; - /** - * Creates a new cell in the table row, and adds the cell to the cells collection. - * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. - */ - insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableRowElement: { - prototype: HTMLTableRowElement; - new(): HTMLTableRowElement; -} - -interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { - /** - * Sets or retrieves a value that indicates the table alignment. - */ - align: string; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: HTMLCollectionOf; - /** - * Removes the specified row (tr) from the element and from the rows collection. - * @param index Number that specifies the zero-based position in the rows collection of the row to remove. - */ - deleteRow(index?: number): void; - /** - * Creates a new row (tr) in the table, and adds the row to the rows collection. - * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. - */ - insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLTableSectionElement: { - prototype: HTMLTableSectionElement; - new(): HTMLTableSectionElement; -} - -interface HTMLTemplateElement extends HTMLElement { - readonly content: DocumentFragment; -} - -declare var HTMLTemplateElement: { - prototype: HTMLTemplateElement; - new(): HTMLTemplateElement; -} - -interface HTMLTextAreaElement extends HTMLElement { - /** - * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. - */ - autofocus: boolean; - /** - * Sets or retrieves the width of the object. - */ - cols: number; - /** - * Sets or retrieves the initial contents of the object. - */ - defaultValue: string; - disabled: boolean; - /** - * Retrieves a reference to the form that the object is embedded in. - */ - readonly form: HTMLFormElement; - /** - * Sets or retrieves the maximum number of characters that the user can enter in a text control. - */ - maxLength: number; - /** - * Sets or retrieves the name of the object. - */ - name: string; - /** - * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. - */ - placeholder: string; - /** - * Sets or retrieves the value indicated whether the content of the object is read-only. - */ - readOnly: boolean; - /** - * When present, marks an element that can't be submitted without a value. - */ - required: boolean; - /** - * Sets or retrieves the number of horizontal rows contained in the object. - */ - rows: number; - /** - * Gets or sets the end position or offset of a text selection. - */ - selectionEnd: number; - /** - * Gets or sets the starting position or offset of a text selection. - */ - selectionStart: number; - /** - * Sets or retrieves the value indicating whether the control is selected. - */ - status: any; - /** - * Retrieves the type of control. - */ - readonly type: string; - /** - * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. - */ - readonly validationMessage: string; - /** - * Returns a ValidityState object that represents the validity states of an element. - */ - readonly validity: ValidityState; - /** - * Retrieves or sets the text in the entry field of the textArea element. - */ - value: string; - /** - * Returns whether an element will successfully validate based on forms validation rules and constraints. - */ - readonly willValidate: boolean; - /** - * Sets or retrieves how to handle wordwrapping in the object. - */ - wrap: string; - minLength: number; - /** - * Returns whether a form will validate when it is submitted, without having to submit it. - */ - checkValidity(): boolean; - /** - * Highlights the input area of a form element. - */ - select(): void; - /** - * Sets a custom error message that is displayed when a form is submitted. - * @param error Sets a custom error message that is displayed when a form is submitted. - */ - setCustomValidity(error: string): void; - /** - * Sets the start and end positions of a selection in a text field. - * @param start The offset into the text field for the start of the selection. - * @param end The offset into the text field for the end of the selection. - */ - setSelectionRange(start: number, end: number): void; -} - -declare var HTMLTextAreaElement: { - prototype: HTMLTextAreaElement; - new(): HTMLTextAreaElement; -} - -interface HTMLTitleElement extends HTMLElement { - /** - * Retrieves or sets the text of the object as a string. - */ - text: string; -} - -declare var HTMLTitleElement: { - prototype: HTMLTitleElement; - new(): HTMLTitleElement; -} - -interface HTMLTrackElement extends HTMLElement { - default: boolean; - kind: string; - label: string; - readonly readyState: number; - src: string; - srclang: string; - readonly track: TextTrack; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -declare var HTMLTrackElement: { - prototype: HTMLTrackElement; - new(): HTMLTrackElement; - readonly ERROR: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; -} - -interface HTMLUListElement extends HTMLElement { - compact: boolean; - type: string; -} - -declare var HTMLUListElement: { - prototype: HTMLUListElement; - new(): HTMLUListElement; -} - -interface HTMLUnknownElement extends HTMLElement { -} - -declare var HTMLUnknownElement: { - prototype: HTMLUnknownElement; - new(): HTMLUnknownElement; -} - -interface HTMLVideoElement extends HTMLMediaElement { - /** - * Gets or sets the height of the video element. - */ - height: number; - msHorizontalMirror: boolean; - readonly msIsLayoutOptimalForPlayback: boolean; - readonly msIsStereo3D: boolean; - msStereo3DPackingMode: string; - msStereo3DRenderMode: string; - msZoom: boolean; - onMSVideoFormatChanged: (this: this, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: this, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: this, ev: Event) => any; - /** - * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. - */ - poster: string; - /** - * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoHeight: number; - /** - * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. - */ - readonly videoWidth: number; - readonly webkitDisplayingFullscreen: boolean; - readonly webkitSupportsFullscreen: boolean; - /** - * Gets or sets the width of the video element. - */ - width: number; - getVideoPlaybackQuality(): VideoPlaybackQuality; - msFrameStep(forward: boolean): void; - msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; - msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - webkitEnterFullScreen(): void; - webkitEnterFullscreen(): void; - webkitExitFullScreen(): void; - webkitExitFullscreen(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFormatChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFrameStepCompleted", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var HTMLVideoElement: { - prototype: HTMLVideoElement; - new(): HTMLVideoElement; -} - -interface HashChangeEvent extends Event { - readonly newURL: string | null; - readonly oldURL: string | null; -} - -declare var HashChangeEvent: { - prototype: HashChangeEvent; - new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; -} - -interface History { - readonly length: number; - readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; -} - -declare var History: { - prototype: History; - new(): History; -} - -interface IDBCursor { - readonly direction: string; - key: IDBKeyRange | IDBValidKey; - readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; - advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; - delete(): IDBRequest; - update(value: any): IDBRequest; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -declare var IDBCursor: { - prototype: IDBCursor; - new(): IDBCursor; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -interface IDBCursorWithValue extends IDBCursor { - readonly value: any; -} - -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new(): IDBCursorWithValue; -} - -interface IDBDatabase extends EventTarget { - readonly name: string; - readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - version: number; - onversionchange: (ev: IDBVersionChangeEvent) => any; - close(): void; - createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; - deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBDatabase: { - prototype: IDBDatabase; - new(): IDBDatabase; -} - -interface IDBFactory { - cmp(first: any, second: any): number; - deleteDatabase(name: string): IDBOpenDBRequest; - open(name: string, version?: number): IDBOpenDBRequest; -} - -declare var IDBFactory: { - prototype: IDBFactory; - new(): IDBFactory; -} - -interface IDBIndex { - keyPath: string | string[]; - readonly name: string; - readonly objectStore: IDBObjectStore; - readonly unique: boolean; - multiEntry: boolean; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - get(key: IDBKeyRange | IDBValidKey): IDBRequest; - getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; -} - -declare var IDBIndex: { - prototype: IDBIndex; - new(): IDBIndex; -} - -interface IDBKeyRange { - readonly lower: any; - readonly lowerOpen: boolean; - readonly upper: any; - readonly upperOpen: boolean; -} - -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new(): IDBKeyRange; - bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; - lowerBound(lower: any, open?: boolean): IDBKeyRange; - only(value: any): IDBKeyRange; - upperBound(upper: any, open?: boolean): IDBKeyRange; -} - -interface IDBObjectStore { - readonly indexNames: DOMStringList; - keyPath: string | string[]; - readonly name: string; - readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; - clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; - deleteIndex(indexName: string): void; - get(key: any): IDBRequest; - index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; -} - -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new(): IDBObjectStore; -} - -interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new(): IDBOpenDBRequest; -} - -interface IDBRequest extends EventTarget { - readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; - readonly readyState: string; - readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; - readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBRequest: { - prototype: IDBRequest; - new(): IDBRequest; -} - -interface IDBTransaction extends EventTarget { - readonly db: IDBDatabase; - readonly error: DOMError; - readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - abort(): void; - objectStore(name: string): IDBObjectStore; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBTransaction: { - prototype: IDBTransaction; - new(): IDBTransaction; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; -} - -interface IDBVersionChangeEvent extends Event { - readonly newVersion: number | null; - readonly oldVersion: number; -} - -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new(): IDBVersionChangeEvent; -} - -interface ImageData { - data: Uint8ClampedArray; - readonly height: number; - readonly width: number; -} - -declare var ImageData: { - prototype: ImageData; - new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} - -interface KeyboardEvent extends UIEvent { - readonly altKey: boolean; - readonly char: string | null; - readonly charCode: number; - readonly ctrlKey: boolean; - readonly key: string; - readonly keyCode: number; - readonly locale: string; - readonly location: number; - readonly metaKey: boolean; - readonly repeat: boolean; - readonly shiftKey: boolean; - readonly which: number; - readonly code: string; - getModifierState(keyArg: string): boolean; - initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -declare var KeyboardEvent: { - prototype: KeyboardEvent; - new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; - readonly DOM_KEY_LOCATION_JOYSTICK: number; - readonly DOM_KEY_LOCATION_LEFT: number; - readonly DOM_KEY_LOCATION_MOBILE: number; - readonly DOM_KEY_LOCATION_NUMPAD: number; - readonly DOM_KEY_LOCATION_RIGHT: number; - readonly DOM_KEY_LOCATION_STANDARD: number; -} - -interface ListeningStateChangedEvent extends Event { - readonly label: string; - readonly state: string; -} - -declare var ListeningStateChangedEvent: { - prototype: ListeningStateChangedEvent; - new(): ListeningStateChangedEvent; -} - -interface Location { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - pathname: string; - port: string; - protocol: string; - search: string; - assign(url: string): void; - reload(forcedReload?: boolean): void; - replace(url: string): void; - toString(): string; -} - -declare var Location: { - prototype: Location; - new(): Location; -} - -interface LongRunningScriptDetectedEvent extends Event { - readonly executionTime: number; - stopPageScriptExecution: boolean; -} - -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new(): LongRunningScriptDetectedEvent; -} - -interface MSApp { - clearTemporaryWebDataAsync(): MSAppAsyncOperation; - createBlobFromRandomAccessStream(type: string, seeker: any): Blob; - createDataPackage(object: any): any; - createDataPackageFromSelection(): any; - createFileFromStorageFile(storageFile: any): File; - createStreamFromInputStream(type: string, inputStream: any): MSStream; - execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; - execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; - getCurrentPriority(): string; - getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; - getViewId(view: any): any; - isTaskScheduledAtPriorityOrHigher(priority: string): boolean; - pageHandlesAllApplicationActivations(enabled: boolean): void; - suppressSubdownloadCredentialPrompts(suppress: boolean): void; - terminateApp(exceptionObject: any): void; - readonly CURRENT: string; - readonly HIGH: string; - readonly IDLE: string; - readonly NORMAL: string; -} -declare var MSApp: MSApp; - -interface MSAppAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSAppAsyncOperation: { - prototype: MSAppAsyncOperation; - new(): MSAppAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; -} - -interface MSAssertion { - readonly id: string; - readonly type: string; -} - -declare var MSAssertion: { - prototype: MSAssertion; - new(): MSAssertion; -} - -interface MSBlobBuilder { - append(data: any, endings?: string): void; - getBlob(contentType?: string): Blob; -} - -declare var MSBlobBuilder: { - prototype: MSBlobBuilder; - new(): MSBlobBuilder; -} - -interface MSCredentials { - getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; - makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; -} - -declare var MSCredentials: { - prototype: MSCredentials; - new(): MSCredentials; -} - -interface MSFIDOCredentialAssertion extends MSAssertion { - readonly algorithm: string | Algorithm; - readonly attestation: any; - readonly publicKey: string; - readonly transportHints: string[]; -} - -declare var MSFIDOCredentialAssertion: { - prototype: MSFIDOCredentialAssertion; - new(): MSFIDOCredentialAssertion; -} - -interface MSFIDOSignature { - readonly authnrData: string; - readonly clientData: string; - readonly signature: string; -} - -declare var MSFIDOSignature: { - prototype: MSFIDOSignature; - new(): MSFIDOSignature; -} - -interface MSFIDOSignatureAssertion extends MSAssertion { - readonly signature: MSFIDOSignature; -} - -declare var MSFIDOSignatureAssertion: { - prototype: MSFIDOSignatureAssertion; - new(): MSFIDOSignatureAssertion; -} - -interface MSGesture { - target: Element; - addPointer(pointerId: number): void; - stop(): void; -} - -declare var MSGesture: { - prototype: MSGesture; - new(): MSGesture; -} - -interface MSGestureEvent extends UIEvent { - readonly clientX: number; - readonly clientY: number; - readonly expansion: number; - readonly gestureObject: any; - readonly hwTimestamp: number; - readonly offsetX: number; - readonly offsetY: number; - readonly rotation: number; - readonly scale: number; - readonly screenX: number; - readonly screenY: number; - readonly translationX: number; - readonly translationY: number; - readonly velocityAngular: number; - readonly velocityExpansion: number; - readonly velocityX: number; - readonly velocityY: number; - initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -interface MSGraphicsTrust { - readonly constrictionActive: boolean; - readonly status: string; -} - -declare var MSGraphicsTrust: { - prototype: MSGraphicsTrust; - new(): MSGraphicsTrust; -} - -interface MSHTMLWebViewElement extends HTMLElement { - readonly canGoBack: boolean; - readonly canGoForward: boolean; - readonly containsFullScreenElement: boolean; - readonly documentTitle: string; - height: number; - readonly settings: MSWebViewSettings; - src: string; - width: number; - addWebAllowedObject(name: string, applicationObject: any): void; - buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; - capturePreviewToBlobAsync(): MSWebViewAsyncOperation; - captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; - getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; - getDeferredPermissionRequests(): DeferredPermissionRequest[]; - goBack(): void; - goForward(): void; - invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; - navigate(uri: string): void; - navigateToLocalStreamUri(source: string, streamResolver: any): void; - navigateToString(contents: string): void; - navigateWithHttpRequestMessage(requestMessage: any): void; - refresh(): void; - stop(): void; -} - -declare var MSHTMLWebViewElement: { - prototype: MSHTMLWebViewElement; - new(): MSHTMLWebViewElement; -} - -interface MSInputMethodContext extends EventTarget { - readonly compositionEndOffset: number; - readonly compositionStartOffset: number; - oncandidatewindowhide: (this: this, ev: Event) => any; - oncandidatewindowshow: (this: this, ev: Event) => any; - oncandidatewindowupdate: (this: this, ev: Event) => any; - readonly target: HTMLElement; - getCandidateWindowClientRect(): ClientRect; - getCompositionAlternatives(): string[]; - hasComposition(): boolean; - isCandidateWindowVisible(): boolean; - addEventListener(type: "MSCandidateWindowHide", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowShow", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowUpdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSInputMethodContext: { - prototype: MSInputMethodContext; - new(): MSInputMethodContext; -} - -interface MSManipulationEvent extends UIEvent { - readonly currentState: number; - readonly inertiaDestinationX: number; - readonly inertiaDestinationY: number; - readonly lastState: number; - initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -declare var MSManipulationEvent: { - prototype: MSManipulationEvent; - new(): MSManipulationEvent; - readonly MS_MANIPULATION_STATE_ACTIVE: number; - readonly MS_MANIPULATION_STATE_CANCELLED: number; - readonly MS_MANIPULATION_STATE_COMMITTED: number; - readonly MS_MANIPULATION_STATE_DRAGGING: number; - readonly MS_MANIPULATION_STATE_INERTIA: number; - readonly MS_MANIPULATION_STATE_PRESELECT: number; - readonly MS_MANIPULATION_STATE_SELECTING: number; - readonly MS_MANIPULATION_STATE_STOPPED: number; -} - -interface MSMediaKeyError { - readonly code: number; - readonly systemCode: number; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -declare var MSMediaKeyError: { - prototype: MSMediaKeyError; - new(): MSMediaKeyError; - readonly MS_MEDIA_KEYERR_CLIENT: number; - readonly MS_MEDIA_KEYERR_DOMAIN: number; - readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; - readonly MS_MEDIA_KEYERR_OUTPUT: number; - readonly MS_MEDIA_KEYERR_SERVICE: number; - readonly MS_MEDIA_KEYERR_UNKNOWN: number; -} - -interface MSMediaKeyMessageEvent extends Event { - readonly destinationURL: string | null; - readonly message: Uint8Array; -} - -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new(): MSMediaKeyMessageEvent; -} - -interface MSMediaKeyNeededEvent extends Event { - readonly initData: Uint8Array | null; -} - -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new(): MSMediaKeyNeededEvent; -} - -interface MSMediaKeySession extends EventTarget { - readonly error: MSMediaKeyError | null; - readonly keySystem: string; - readonly sessionId: string; - close(): void; - update(key: Uint8Array): void; -} - -declare var MSMediaKeySession: { - prototype: MSMediaKeySession; - new(): MSMediaKeySession; -} - -interface MSMediaKeys { - readonly keySystem: string; - createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; -} - -declare var MSMediaKeys: { - prototype: MSMediaKeys; - new(keySystem: string): MSMediaKeys; - isTypeSupported(keySystem: string, type?: string): boolean; - isTypeSupportedWithFeatures(keySystem: string, type?: string): string; -} - -interface MSPointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} - -interface MSRangeCollection { - readonly length: number; - item(index: number): Range; - [index: number]: Range; -} - -declare var MSRangeCollection: { - prototype: MSRangeCollection; - new(): MSRangeCollection; -} - -interface MSSiteModeEvent extends Event { - readonly actionURL: string; - readonly buttonID: number; -} - -declare var MSSiteModeEvent: { - prototype: MSSiteModeEvent; - new(): MSSiteModeEvent; -} - -interface MSStream { - readonly type: string; - msClose(): void; - msDetachStream(): any; -} - -declare var MSStream: { - prototype: MSStream; - new(): MSStream; -} - -interface MSStreamReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(stream: MSStream, size?: number): void; - readAsBinaryString(stream: MSStream, size?: number): void; - readAsBlob(stream: MSStream, size?: number): void; - readAsDataURL(stream: MSStream, size?: number): void; - readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSStreamReader: { - prototype: MSStreamReader; - new(): MSStreamReader; -} - -interface MSWebViewAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - readonly target: MSHTMLWebViewElement; - readonly type: number; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSWebViewAsyncOperation: { - prototype: MSWebViewAsyncOperation; - new(): MSWebViewAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; - readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; - readonly TYPE_INVOKE_SCRIPT: number; -} - -interface MSWebViewSettings { - isIndexedDBEnabled: boolean; - isJavaScriptEnabled: boolean; -} - -declare var MSWebViewSettings: { - prototype: MSWebViewSettings; - new(): MSWebViewSettings; -} - -interface MediaDeviceInfo { - readonly deviceId: string; - readonly groupId: string; - readonly kind: string; - readonly label: string; -} - -declare var MediaDeviceInfo: { - prototype: MediaDeviceInfo; - new(): MediaDeviceInfo; -} - -interface MediaDevices extends EventTarget { - ondevicechange: (this: this, ev: Event) => any; - enumerateDevices(): any; - getSupportedConstraints(): MediaTrackSupportedConstraints; - getUserMedia(constraints: MediaStreamConstraints): PromiseLike; - addEventListener(type: "devicechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaDevices: { - prototype: MediaDevices; - new(): MediaDevices; -} - -interface MediaElementAudioSourceNode extends AudioNode { -} - -declare var MediaElementAudioSourceNode: { - prototype: MediaElementAudioSourceNode; - new(): MediaElementAudioSourceNode; -} - -interface MediaEncryptedEvent extends Event { - readonly initData: ArrayBuffer | null; - readonly initDataType: string; -} - -declare var MediaEncryptedEvent: { - prototype: MediaEncryptedEvent; - new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; -} - -interface MediaError { - readonly code: number; - readonly msExtendedCode: number; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - readonly MEDIA_ERR_ABORTED: number; - readonly MEDIA_ERR_DECODE: number; - readonly MEDIA_ERR_NETWORK: number; - readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; - readonly MS_MEDIA_ERR_ENCRYPTED: number; -} - -interface MediaKeyMessageEvent extends Event { - readonly message: ArrayBuffer; - readonly messageType: string; -} - -declare var MediaKeyMessageEvent: { - prototype: MediaKeyMessageEvent; - new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; -} - -interface MediaKeySession extends EventTarget { - readonly closed: PromiseLike; - readonly expiration: number; - readonly keyStatuses: MediaKeyStatusMap; - readonly sessionId: string; - close(): PromiseLike; - generateRequest(initDataType: string, initData: any): PromiseLike; - load(sessionId: string): PromiseLike; - remove(): PromiseLike; - update(response: any): PromiseLike; -} - -declare var MediaKeySession: { - prototype: MediaKeySession; - new(): MediaKeySession; -} - -interface MediaKeyStatusMap { - readonly size: number; - forEach(callback: ForEachCallback): void; - get(keyId: any): string; - has(keyId: any): boolean; -} - -declare var MediaKeyStatusMap: { - prototype: MediaKeyStatusMap; - new(): MediaKeyStatusMap; -} - -interface MediaKeySystemAccess { - readonly keySystem: string; - createMediaKeys(): PromiseLike; - getConfiguration(): MediaKeySystemConfiguration; -} - -declare var MediaKeySystemAccess: { - prototype: MediaKeySystemAccess; - new(): MediaKeySystemAccess; -} - -interface MediaKeys { - createSession(sessionType?: string): MediaKeySession; - setServerCertificate(serverCertificate: any): PromiseLike; -} - -declare var MediaKeys: { - prototype: MediaKeys; - new(): MediaKeys; -} - -interface MediaList { - readonly length: number; - mediaText: string; - appendMedium(newMedium: string): void; - deleteMedium(oldMedium: string): void; - item(index: number): string; - toString(): string; - [index: number]: string; -} - -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MediaSource extends EventTarget { - readonly activeSourceBuffers: SourceBufferList; - duration: number; - readonly readyState: string; - readonly sourceBuffers: SourceBufferList; - addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: number): void; - removeSourceBuffer(sourceBuffer: SourceBuffer): void; -} - -declare var MediaSource: { - prototype: MediaSource; - new(): MediaSource; - isTypeSupported(type: string): boolean; -} - -interface MediaStream extends EventTarget { - readonly active: boolean; - readonly id: string; - onactive: (this: this, ev: Event) => any; - onaddtrack: (this: this, ev: TrackEvent) => any; - oninactive: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - addTrack(track: MediaStreamTrack): void; - clone(): MediaStream; - getAudioTracks(): MediaStreamTrack[]; - getTrackById(trackId: string): MediaStreamTrack | null; - getTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - removeTrack(track: MediaStreamTrack): void; - stop(): void; - addEventListener(type: "active", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "inactive", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStream: { - prototype: MediaStream; - new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; -} - -interface MediaStreamAudioSourceNode extends AudioNode { -} - -declare var MediaStreamAudioSourceNode: { - prototype: MediaStreamAudioSourceNode; - new(): MediaStreamAudioSourceNode; -} - -interface MediaStreamError { - readonly constraintName: string | null; - readonly message: string | null; - readonly name: string; -} - -declare var MediaStreamError: { - prototype: MediaStreamError; - new(): MediaStreamError; -} - -interface MediaStreamErrorEvent extends Event { - readonly error: MediaStreamError | null; -} - -declare var MediaStreamErrorEvent: { - prototype: MediaStreamErrorEvent; - new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; -} - -interface MediaStreamTrack extends EventTarget { - enabled: boolean; - readonly id: string; - readonly kind: string; - readonly label: string; - readonly muted: boolean; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onmute: (this: this, ev: Event) => any; - onoverconstrained: (this: this, ev: MediaStreamErrorEvent) => any; - onunmute: (this: this, ev: Event) => any; - readonly readonly: boolean; - readonly readyState: string; - readonly remote: boolean; - applyConstraints(constraints: MediaTrackConstraints): PromiseLike; - clone(): MediaStreamTrack; - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - stop(): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "overconstrained", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unmute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new(): MediaStreamTrack; -} - -interface MediaStreamTrackEvent extends Event { - readonly track: MediaStreamTrack; -} - -declare var MediaStreamTrackEvent: { - prototype: MediaStreamTrackEvent; - new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: Window; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, ports?: any): void; - start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface MimeType { - readonly description: string; - readonly enabledPlugin: Plugin; - readonly suffixes: string; - readonly type: string; -} - -declare var MimeType: { - prototype: MimeType; - new(): MimeType; -} - -interface MimeTypeArray { - readonly length: number; - item(index: number): Plugin; - namedItem(type: string): Plugin; - [index: number]: Plugin; -} - -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new(): MimeTypeArray; -} - -interface MouseEvent extends UIEvent { - readonly altKey: boolean; - readonly button: number; - readonly buttons: number; - readonly clientX: number; - readonly clientY: number; - readonly ctrlKey: boolean; - readonly fromElement: Element; - readonly layerX: number; - readonly layerY: number; - readonly metaKey: boolean; - readonly movementX: number; - readonly movementY: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pageX: number; - readonly pageY: number; - readonly relatedTarget: EventTarget; - readonly screenX: number; - readonly screenY: number; - readonly shiftKey: boolean; - readonly toElement: Element; - readonly which: number; - readonly x: number; - readonly y: number; - getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; -} - -declare var MouseEvent: { - prototype: MouseEvent; - new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; -} - -interface MutationEvent extends Event { - readonly attrChange: number; - readonly attrName: string; - readonly newValue: string; - readonly prevValue: string; - readonly relatedNode: Node; - initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -declare var MutationEvent: { - prototype: MutationEvent; - new(): MutationEvent; - readonly ADDITION: number; - readonly MODIFICATION: number; - readonly REMOVAL: number; -} - -interface MutationObserver { - disconnect(): void; - observe(target: Node, options: MutationObserverInit): void; - takeRecords(): MutationRecord[]; -} - -declare var MutationObserver: { - prototype: MutationObserver; - new(callback: MutationCallback): MutationObserver; -} - -interface MutationRecord { - readonly addedNodes: NodeList; - readonly attributeName: string | null; - readonly attributeNamespace: string | null; - readonly nextSibling: Node | null; - readonly oldValue: string | null; - readonly previousSibling: Node | null; - readonly removedNodes: NodeList; - readonly target: Node; - readonly type: string; -} - -declare var MutationRecord: { - prototype: MutationRecord; - new(): MutationRecord; -} - -interface NamedNodeMap { - readonly length: number; - getNamedItem(name: string): Attr; - getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - item(index: number): Attr; - removeNamedItem(name: string): Attr; - removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; - setNamedItem(arg: Attr): Attr; - setNamedItemNS(arg: Attr): Attr; - [index: number]: Attr; -} - -declare var NamedNodeMap: { - prototype: NamedNodeMap; - new(): NamedNodeMap; -} - -interface NavigationCompletedEvent extends NavigationEvent { - readonly isSuccess: boolean; - readonly webErrorStatus: number; -} - -declare var NavigationCompletedEvent: { - prototype: NavigationCompletedEvent; - new(): NavigationCompletedEvent; -} - -interface NavigationEvent extends Event { - readonly uri: string; -} - -declare var NavigationEvent: { - prototype: NavigationEvent; - new(): NavigationEvent; -} - -interface NavigationEventWithReferrer extends NavigationEvent { - readonly referer: string; -} - -declare var NavigationEventWithReferrer: { - prototype: NavigationEventWithReferrer; - new(): NavigationEventWithReferrer; -} - -interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { - readonly appCodeName: string; - readonly cookieEnabled: boolean; - readonly language: string; - readonly maxTouchPoints: number; - readonly mimeTypes: MimeTypeArray; - readonly msManipulationViewsEnabled: boolean; - readonly msMaxTouchPoints: number; - readonly msPointerEnabled: boolean; - readonly plugins: PluginArray; - readonly pointerEnabled: boolean; - readonly webdriver: boolean; - getGamepads(): Gamepad[]; - javaEnabled(): boolean; - msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; - requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; - vibrate(pattern: number | number[]): boolean; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Navigator: { - prototype: Navigator; - new(): Navigator; -} - -interface Node extends EventTarget { - readonly attributes: NamedNodeMap; - readonly baseURI: string | null; - readonly childNodes: NodeList; - readonly firstChild: Node; - readonly lastChild: Node; - readonly localName: string | null; - readonly namespaceURI: string | null; - readonly nextSibling: Node; - readonly nodeName: string; - readonly nodeType: number; - nodeValue: string | null; - readonly ownerDocument: Document; - readonly parentElement: HTMLElement; - readonly parentNode: Node; - readonly previousSibling: Node; - textContent: string | null; - appendChild(newChild: Node): Node; - cloneNode(deep?: boolean): Node; - compareDocumentPosition(other: Node): number; - contains(child: Node): boolean; - hasAttributes(): boolean; - hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node | null): Node; - isDefaultNamespace(namespaceURI: string | null): boolean; - isEqualNode(arg: Node): boolean; - isSameNode(other: Node): boolean; - lookupNamespaceURI(prefix: string | null): string | null; - lookupPrefix(namespaceURI: string | null): string | null; - normalize(): void; - removeChild(oldChild: Node): Node; - replaceChild(newChild: Node, oldChild: Node): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -declare var Node: { - prototype: Node; - new(): Node; - readonly ATTRIBUTE_NODE: number; - readonly CDATA_SECTION_NODE: number; - readonly COMMENT_NODE: number; - readonly DOCUMENT_FRAGMENT_NODE: number; - readonly DOCUMENT_NODE: number; - readonly DOCUMENT_POSITION_CONTAINED_BY: number; - readonly DOCUMENT_POSITION_CONTAINS: number; - readonly DOCUMENT_POSITION_DISCONNECTED: number; - readonly DOCUMENT_POSITION_FOLLOWING: number; - readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - readonly DOCUMENT_POSITION_PRECEDING: number; - readonly DOCUMENT_TYPE_NODE: number; - readonly ELEMENT_NODE: number; - readonly ENTITY_NODE: number; - readonly ENTITY_REFERENCE_NODE: number; - readonly NOTATION_NODE: number; - readonly PROCESSING_INSTRUCTION_NODE: number; - readonly TEXT_NODE: number; -} - -interface NodeFilter { - acceptNode(n: Node): number; -} - -declare var NodeFilter: { - readonly FILTER_ACCEPT: number; - readonly FILTER_REJECT: number; - readonly FILTER_SKIP: number; - readonly SHOW_ALL: number; - readonly SHOW_ATTRIBUTE: number; - readonly SHOW_CDATA_SECTION: number; - readonly SHOW_COMMENT: number; - readonly SHOW_DOCUMENT: number; - readonly SHOW_DOCUMENT_FRAGMENT: number; - readonly SHOW_DOCUMENT_TYPE: number; - readonly SHOW_ELEMENT: number; - readonly SHOW_ENTITY: number; - readonly SHOW_ENTITY_REFERENCE: number; - readonly SHOW_NOTATION: number; - readonly SHOW_PROCESSING_INSTRUCTION: number; - readonly SHOW_TEXT: number; -} - -interface NodeIterator { - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - detach(): void; - nextNode(): Node; - previousNode(): Node; -} - -declare var NodeIterator: { - prototype: NodeIterator; - new(): NodeIterator; -} - -interface NodeList { - readonly length: number; - item(index: number): Node; - [index: number]: Node; -} - -declare var NodeList: { - prototype: NodeList; - new(): NodeList; -} - -interface OES_element_index_uint { -} - -declare var OES_element_index_uint: { - prototype: OES_element_index_uint; - new(): OES_element_index_uint; -} - -interface OES_standard_derivatives { - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -declare var OES_standard_derivatives: { - prototype: OES_standard_derivatives; - new(): OES_standard_derivatives; - readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -interface OES_texture_float { -} - -declare var OES_texture_float: { - prototype: OES_texture_float; - new(): OES_texture_float; -} - -interface OES_texture_float_linear { -} - -declare var OES_texture_float_linear: { - prototype: OES_texture_float_linear; - new(): OES_texture_float_linear; -} - -interface OfflineAudioCompletionEvent extends Event { - readonly renderedBuffer: AudioBuffer; -} - -declare var OfflineAudioCompletionEvent: { - prototype: OfflineAudioCompletionEvent; - new(): OfflineAudioCompletionEvent; -} - -interface OfflineAudioContext extends AudioContext { - oncomplete: (this: this, ev: Event) => any; - startRendering(): PromiseLike; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OfflineAudioContext: { - prototype: OfflineAudioContext; - new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} - -interface OscillatorNode extends AudioNode { - readonly detune: AudioParam; - readonly frequency: AudioParam; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - type: string; - setPeriodicWave(periodicWave: PeriodicWave): void; - start(when?: number): void; - stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var OscillatorNode: { - prototype: OscillatorNode; - new(): OscillatorNode; -} - -interface OverflowEvent extends UIEvent { - readonly horizontalOverflow: boolean; - readonly orient: number; - readonly verticalOverflow: boolean; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -declare var OverflowEvent: { - prototype: OverflowEvent; - new(): OverflowEvent; - readonly BOTH: number; - readonly HORIZONTAL: number; - readonly VERTICAL: number; -} - -interface PageTransitionEvent extends Event { - readonly persisted: boolean; -} - -declare var PageTransitionEvent: { - prototype: PageTransitionEvent; - new(): PageTransitionEvent; -} - -interface PannerNode extends AudioNode { - coneInnerAngle: number; - coneOuterAngle: number; - coneOuterGain: number; - distanceModel: string; - maxDistance: number; - panningModel: string; - refDistance: number; - rolloffFactor: number; - setOrientation(x: number, y: number, z: number): void; - setPosition(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; -} - -declare var PannerNode: { - prototype: PannerNode; - new(): PannerNode; -} - -interface PerfWidgetExternal { - readonly activeNetworkRequestCount: number; - readonly averageFrameTime: number; - readonly averagePaintTime: number; - readonly extraInformationEnabled: boolean; - readonly independentRenderingEnabled: boolean; - readonly irDisablingContentString: string; - readonly irStatusAvailable: boolean; - readonly maxCpuSpeed: number; - readonly paintRequestsPerSecond: number; - readonly performanceCounter: number; - readonly performanceCounterFrequency: number; - addEventListener(eventType: string, callback: Function): void; - getMemoryUsage(): number; - getProcessCpuUsage(): number; - getRecentCpuUsage(last: number | null): any; - getRecentFrames(last: number | null): any; - getRecentMemoryUsage(last: number | null): any; - getRecentPaintRequests(last: number | null): any; - removeEventListener(eventType: string, callback: Function): void; - repositionWindow(x: number, y: number): void; - resizeWindow(width: number, height: number): void; -} - -declare var PerfWidgetExternal: { - prototype: PerfWidgetExternal; - new(): PerfWidgetExternal; -} - -interface Performance { - readonly navigation: PerformanceNavigation; - readonly timing: PerformanceTiming; - clearMarks(markName?: string): void; - clearMeasures(measureName?: string): void; - clearResourceTimings(): void; - getEntries(): any; - getEntriesByName(name: string, entryType?: string): any; - getEntriesByType(entryType: string): any; - getMarks(markName?: string): any; - getMeasures(measureName?: string): any; - mark(markName: string): void; - measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - now(): number; - setResourceTimingBufferSize(maxSize: number): void; - toJSON(): any; -} - -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface PerformanceEntry { - readonly duration: number; - readonly entryType: string; - readonly name: string; - readonly startTime: number; -} - -declare var PerformanceEntry: { - prototype: PerformanceEntry; - new(): PerformanceEntry; -} - -interface PerformanceMark extends PerformanceEntry { -} - -declare var PerformanceMark: { - prototype: PerformanceMark; - new(): PerformanceMark; -} - -interface PerformanceMeasure extends PerformanceEntry { -} - -declare var PerformanceMeasure: { - prototype: PerformanceMeasure; - new(): PerformanceMeasure; -} - -interface PerformanceNavigation { - readonly redirectCount: number; - readonly type: number; - toJSON(): any; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - readonly TYPE_BACK_FORWARD: number; - readonly TYPE_NAVIGATE: number; - readonly TYPE_RELOAD: number; - readonly TYPE_RESERVED: number; -} - -interface PerformanceNavigationTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly navigationStart: number; - readonly redirectCount: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly type: string; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; -} - -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new(): PerformanceNavigationTiming; -} - -interface PerformanceResourceTiming extends PerformanceEntry { - readonly connectEnd: number; - readonly connectStart: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly initiatorType: string; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; -} - -declare var PerformanceResourceTiming: { - prototype: PerformanceResourceTiming; - new(): PerformanceResourceTiming; -} - -interface PerformanceTiming { - readonly connectEnd: number; - readonly connectStart: number; - readonly domComplete: number; - readonly domContentLoadedEventEnd: number; - readonly domContentLoadedEventStart: number; - readonly domInteractive: number; - readonly domLoading: number; - readonly domainLookupEnd: number; - readonly domainLookupStart: number; - readonly fetchStart: number; - readonly loadEventEnd: number; - readonly loadEventStart: number; - readonly msFirstPaint: number; - readonly navigationStart: number; - readonly redirectEnd: number; - readonly redirectStart: number; - readonly requestStart: number; - readonly responseEnd: number; - readonly responseStart: number; - readonly unloadEventEnd: number; - readonly unloadEventStart: number; - readonly secureConnectionStart: number; - toJSON(): any; -} - -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} - -interface PeriodicWave { -} - -declare var PeriodicWave: { - prototype: PeriodicWave; - new(): PeriodicWave; -} - -interface PermissionRequest extends DeferredPermissionRequest { - readonly state: string; - defer(): void; -} - -declare var PermissionRequest: { - prototype: PermissionRequest; - new(): PermissionRequest; -} - -interface PermissionRequestedEvent extends Event { - readonly permissionRequest: PermissionRequest; -} - -declare var PermissionRequestedEvent: { - prototype: PermissionRequestedEvent; - new(): PermissionRequestedEvent; -} - -interface Plugin { - readonly description: string; - readonly filename: string; - readonly length: number; - readonly name: string; - readonly version: string; - item(index: number): MimeType; - namedItem(type: string): MimeType; - [index: number]: MimeType; -} - -declare var Plugin: { - prototype: Plugin; - new(): Plugin; -} - -interface PluginArray { - readonly length: number; - item(index: number): Plugin; - namedItem(name: string): Plugin; - refresh(reload?: boolean): void; - [index: number]: Plugin; -} - -declare var PluginArray: { - prototype: PluginArray; - new(): PluginArray; -} - -interface PointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var PointerEvent: { - prototype: PointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} - -interface PopStateEvent extends Event { - readonly state: any; - initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; -} - -declare var PopStateEvent: { - prototype: PopStateEvent; - new(): PopStateEvent; -} - -interface Position { - readonly coords: Coordinates; - readonly timestamp: number; -} - -declare var Position: { - prototype: Position; - new(): Position; -} - -interface PositionError { - readonly code: number; - readonly message: string; - toString(): string; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -declare var PositionError: { - prototype: PositionError; - new(): PositionError; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -interface ProcessingInstruction extends CharacterData { - readonly target: string; -} - -declare var ProcessingInstruction: { - prototype: ProcessingInstruction; - new(): ProcessingInstruction; -} - -interface ProgressEvent extends Event { - readonly lengthComputable: boolean; - readonly loaded: number; - readonly total: number; - initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; -} - -declare var ProgressEvent: { - prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} - -interface RTCDTMFToneChangeEvent extends Event { - readonly tone: string; -} - -declare var RTCDTMFToneChangeEvent: { - prototype: RTCDTMFToneChangeEvent; - new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; -} - -interface RTCDtlsTransport extends RTCStatsProvider { - ondtlsstatechange: ((this: this, ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly state: string; - readonly transport: RTCIceTransport; - getLocalParameters(): RTCDtlsParameters; - getRemoteCertificates(): ArrayBuffer[]; - getRemoteParameters(): RTCDtlsParameters | null; - start(remoteParameters: RTCDtlsParameters): void; - stop(): void; - addEventListener(type: "dtlsstatechange", listener: (this: this, ev: RTCDtlsTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtlsTransport: { - prototype: RTCDtlsTransport; - new(transport: RTCIceTransport): RTCDtlsTransport; -} - -interface RTCDtlsTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCDtlsTransportStateChangedEvent: { - prototype: RTCDtlsTransportStateChangedEvent; - new(): RTCDtlsTransportStateChangedEvent; -} - -interface RTCDtmfSender extends EventTarget { - readonly canInsertDTMF: boolean; - readonly duration: number; - readonly interToneGap: number; - ontonechange: (this: this, ev: RTCDTMFToneChangeEvent) => any; - readonly sender: RTCRtpSender; - readonly toneBuffer: string; - insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: "tonechange", listener: (this: this, ev: RTCDTMFToneChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCDtmfSender: { - prototype: RTCDtmfSender; - new(sender: RTCRtpSender): RTCDtmfSender; -} - -interface RTCIceCandidatePairChangedEvent extends Event { - readonly pair: RTCIceCandidatePair; -} - -declare var RTCIceCandidatePairChangedEvent: { - prototype: RTCIceCandidatePairChangedEvent; - new(): RTCIceCandidatePairChangedEvent; -} - -interface RTCIceGatherer extends RTCStatsProvider { - readonly component: string; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onlocalcandidate: ((this: this, ev: RTCIceGathererEvent) => any) | null; - createAssociatedGatherer(): RTCIceGatherer; - getLocalCandidates(): RTCIceCandidate[]; - getLocalParameters(): RTCIceParameters; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "localcandidate", listener: (this: this, ev: RTCIceGathererEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceGatherer: { - prototype: RTCIceGatherer; - new(options: RTCIceGatherOptions): RTCIceGatherer; -} - -interface RTCIceGathererEvent extends Event { - readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; -} - -declare var RTCIceGathererEvent: { - prototype: RTCIceGathererEvent; - new(): RTCIceGathererEvent; -} - -interface RTCIceTransport extends RTCStatsProvider { - readonly component: string; - readonly iceGatherer: RTCIceGatherer | null; - oncandidatepairchange: ((this: this, ev: RTCIceCandidatePairChangedEvent) => any) | null; - onicestatechange: ((this: this, ev: RTCIceTransportStateChangedEvent) => any) | null; - readonly role: string; - readonly state: string; - addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; - createAssociatedTransport(): RTCIceTransport; - getNominatedCandidatePair(): RTCIceCandidatePair | null; - getRemoteCandidates(): RTCIceCandidate[]; - getRemoteParameters(): RTCIceParameters | null; - setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; - start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; - stop(): void; - addEventListener(type: "candidatepairchange", listener: (this: this, ev: RTCIceCandidatePairChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "icestatechange", listener: (this: this, ev: RTCIceTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCIceTransport: { - prototype: RTCIceTransport; - new(): RTCIceTransport; -} - -interface RTCIceTransportStateChangedEvent extends Event { - readonly state: string; -} - -declare var RTCIceTransportStateChangedEvent: { - prototype: RTCIceTransportStateChangedEvent; - new(): RTCIceTransportStateChangedEvent; -} - -interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack | null; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - getContributingSources(): RTCRtpContributingSource[]; - receive(parameters: RTCRtpParameters): void; - requestSendCSRC(csrc: number): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpReceiver: { - prototype: RTCRtpReceiver; - new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCRtpSender extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onssrcconflict: ((this: this, ev: RTCSsrcConflictEvent) => any) | null; - readonly rtcpTransport: RTCDtlsTransport; - readonly track: MediaStreamTrack; - readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; - send(parameters: RTCRtpParameters): void; - setTrack(track: MediaStreamTrack): void; - setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; - stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ssrcconflict", listener: (this: this, ev: RTCSsrcConflictEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCRtpSender: { - prototype: RTCRtpSender; - new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; - getCapabilities(kind?: string): RTCRtpCapabilities; -} - -interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - readonly transport: RTCIceTransport; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var RTCSrtpSdesTransport: { - prototype: RTCSrtpSdesTransport; - new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; - getLocalParameters(): RTCSrtpSdesParameters[]; -} - -interface RTCSsrcConflictEvent extends Event { - readonly ssrc: number; -} - -declare var RTCSsrcConflictEvent: { - prototype: RTCSsrcConflictEvent; - new(): RTCSsrcConflictEvent; -} - -interface RTCStatsProvider extends EventTarget { - getStats(): PromiseLike; - msGetStats(): PromiseLike; -} - -declare var RTCStatsProvider: { - prototype: RTCStatsProvider; - new(): RTCStatsProvider; -} - -interface Range { - readonly collapsed: boolean; - readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; - cloneContents(): DocumentFragment; - cloneRange(): Range; - collapse(toStart: boolean): void; - compareBoundaryPoints(how: number, sourceRange: Range): number; - createContextualFragment(fragment: string): DocumentFragment; - deleteContents(): void; - detach(): void; - expand(Unit: string): boolean; - extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - insertNode(newNode: Node): void; - selectNode(refNode: Node): void; - selectNodeContents(refNode: Node): void; - setEnd(refNode: Node, offset: number): void; - setEndAfter(refNode: Node): void; - setEndBefore(refNode: Node): void; - setStart(refNode: Node, offset: number): void; - setStartAfter(refNode: Node): void; - setStartBefore(refNode: Node): void; - surroundContents(newParent: Node): void; - toString(): string; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -declare var Range: { - prototype: Range; - new(): Range; - readonly END_TO_END: number; - readonly END_TO_START: number; - readonly START_TO_END: number; - readonly START_TO_START: number; -} - -interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly target: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGAElement: { - prototype: SVGAElement; - new(): SVGAElement; -} - -interface SVGAngle { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -declare var SVGAngle: { - prototype: SVGAngle; - new(): SVGAngle; - readonly SVG_ANGLETYPE_DEG: number; - readonly SVG_ANGLETYPE_GRAD: number; - readonly SVG_ANGLETYPE_RAD: number; - readonly SVG_ANGLETYPE_UNKNOWN: number; - readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} - -interface SVGAnimatedAngle { - readonly animVal: SVGAngle; - readonly baseVal: SVGAngle; -} - -declare var SVGAnimatedAngle: { - prototype: SVGAnimatedAngle; - new(): SVGAnimatedAngle; -} - -interface SVGAnimatedBoolean { - readonly animVal: boolean; - baseVal: boolean; -} - -declare var SVGAnimatedBoolean: { - prototype: SVGAnimatedBoolean; - new(): SVGAnimatedBoolean; -} - -interface SVGAnimatedEnumeration { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedEnumeration: { - prototype: SVGAnimatedEnumeration; - new(): SVGAnimatedEnumeration; -} - -interface SVGAnimatedInteger { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedInteger: { - prototype: SVGAnimatedInteger; - new(): SVGAnimatedInteger; -} - -interface SVGAnimatedLength { - readonly animVal: SVGLength; - readonly baseVal: SVGLength; -} - -declare var SVGAnimatedLength: { - prototype: SVGAnimatedLength; - new(): SVGAnimatedLength; -} - -interface SVGAnimatedLengthList { - readonly animVal: SVGLengthList; - readonly baseVal: SVGLengthList; -} - -declare var SVGAnimatedLengthList: { - prototype: SVGAnimatedLengthList; - new(): SVGAnimatedLengthList; -} - -interface SVGAnimatedNumber { - readonly animVal: number; - baseVal: number; -} - -declare var SVGAnimatedNumber: { - prototype: SVGAnimatedNumber; - new(): SVGAnimatedNumber; -} - -interface SVGAnimatedNumberList { - readonly animVal: SVGNumberList; - readonly baseVal: SVGNumberList; -} - -declare var SVGAnimatedNumberList: { - prototype: SVGAnimatedNumberList; - new(): SVGAnimatedNumberList; -} - -interface SVGAnimatedPreserveAspectRatio { - readonly animVal: SVGPreserveAspectRatio; - readonly baseVal: SVGPreserveAspectRatio; -} - -declare var SVGAnimatedPreserveAspectRatio: { - prototype: SVGAnimatedPreserveAspectRatio; - new(): SVGAnimatedPreserveAspectRatio; -} - -interface SVGAnimatedRect { - readonly animVal: SVGRect; - readonly baseVal: SVGRect; -} - -declare var SVGAnimatedRect: { - prototype: SVGAnimatedRect; - new(): SVGAnimatedRect; -} - -interface SVGAnimatedString { - readonly animVal: string; - baseVal: string; -} - -declare var SVGAnimatedString: { - prototype: SVGAnimatedString; - new(): SVGAnimatedString; -} - -interface SVGAnimatedTransformList { - readonly animVal: SVGTransformList; - readonly baseVal: SVGTransformList; -} - -declare var SVGAnimatedTransformList: { - prototype: SVGAnimatedTransformList; - new(): SVGAnimatedTransformList; -} - -interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGCircleElement: { - prototype: SVGCircleElement; - new(): SVGCircleElement; -} - -interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGClipPathElement: { - prototype: SVGClipPathElement; - new(): SVGClipPathElement; -} - -interface SVGComponentTransferFunctionElement extends SVGElement { - readonly amplitude: SVGAnimatedNumber; - readonly exponent: SVGAnimatedNumber; - readonly intercept: SVGAnimatedNumber; - readonly offset: SVGAnimatedNumber; - readonly slope: SVGAnimatedNumber; - readonly tableValues: SVGAnimatedNumberList; - readonly type: SVGAnimatedEnumeration; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -declare var SVGComponentTransferFunctionElement: { - prototype: SVGComponentTransferFunctionElement; - new(): SVGComponentTransferFunctionElement; - readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; -} - -interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDefsElement: { - prototype: SVGDefsElement; - new(): SVGDefsElement; -} - -interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGDescElement: { - prototype: SVGDescElement; - new(): SVGDescElement; -} - -interface SVGElement extends Element { - onclick: (this: this, ev: MouseEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - onfocusin: (this: this, ev: FocusEvent) => any; - onfocusout: (this: this, ev: FocusEvent) => any; - onload: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - readonly ownerSVGElement: SVGSVGElement; - readonly viewportElement: SVGElement; - xmlbase: string; - className: any; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGElement: { - prototype: SVGElement; - new(): SVGElement; -} - -interface SVGElementInstance extends EventTarget { - readonly childNodes: SVGElementInstanceList; - readonly correspondingElement: SVGElement; - readonly correspondingUseElement: SVGUseElement; - readonly firstChild: SVGElementInstance; - readonly lastChild: SVGElementInstance; - readonly nextSibling: SVGElementInstance; - readonly parentNode: SVGElementInstance; - readonly previousSibling: SVGElementInstance; -} - -declare var SVGElementInstance: { - prototype: SVGElementInstance; - new(): SVGElementInstance; -} - -interface SVGElementInstanceList { - readonly length: number; - item(index: number): SVGElementInstance; -} - -declare var SVGElementInstanceList: { - prototype: SVGElementInstanceList; - new(): SVGElementInstanceList; -} - -interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGEllipseElement: { - prototype: SVGEllipseElement; - new(): SVGEllipseElement; -} - -interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly mode: SVGAnimatedEnumeration; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEBlendElement: { - prototype: SVGFEBlendElement; - new(): SVGFEBlendElement; - readonly SVG_FEBLEND_MODE_COLOR: number; - readonly SVG_FEBLEND_MODE_COLOR_BURN: number; - readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; - readonly SVG_FEBLEND_MODE_DARKEN: number; - readonly SVG_FEBLEND_MODE_DIFFERENCE: number; - readonly SVG_FEBLEND_MODE_EXCLUSION: number; - readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; - readonly SVG_FEBLEND_MODE_HUE: number; - readonly SVG_FEBLEND_MODE_LIGHTEN: number; - readonly SVG_FEBLEND_MODE_LUMINOSITY: number; - readonly SVG_FEBLEND_MODE_MULTIPLY: number; - readonly SVG_FEBLEND_MODE_NORMAL: number; - readonly SVG_FEBLEND_MODE_OVERLAY: number; - readonly SVG_FEBLEND_MODE_SATURATION: number; - readonly SVG_FEBLEND_MODE_SCREEN: number; - readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; - readonly SVG_FEBLEND_MODE_UNKNOWN: number; -} - -interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly type: SVGAnimatedEnumeration; - readonly values: SVGAnimatedNumberList; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEColorMatrixElement: { - prototype: SVGFEColorMatrixElement; - new(): SVGFEColorMatrixElement; - readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; - readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; - readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; - readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; -} - -interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEComponentTransferElement: { - prototype: SVGFEComponentTransferElement; - new(): SVGFEComponentTransferElement; -} - -interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly k1: SVGAnimatedNumber; - readonly k2: SVGAnimatedNumber; - readonly k3: SVGAnimatedNumber; - readonly k4: SVGAnimatedNumber; - readonly operator: SVGAnimatedEnumeration; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFECompositeElement: { - prototype: SVGFECompositeElement; - new(): SVGFECompositeElement; - readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; - readonly SVG_FECOMPOSITE_OPERATOR_IN: number; - readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; - readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; - readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; -} - -interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly bias: SVGAnimatedNumber; - readonly divisor: SVGAnimatedNumber; - readonly edgeMode: SVGAnimatedEnumeration; - readonly in1: SVGAnimatedString; - readonly kernelMatrix: SVGAnimatedNumberList; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly orderX: SVGAnimatedInteger; - readonly orderY: SVGAnimatedInteger; - readonly preserveAlpha: SVGAnimatedBoolean; - readonly targetX: SVGAnimatedInteger; - readonly targetY: SVGAnimatedInteger; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEConvolveMatrixElement: { - prototype: SVGFEConvolveMatrixElement; - new(): SVGFEConvolveMatrixElement; - readonly SVG_EDGEMODE_DUPLICATE: number; - readonly SVG_EDGEMODE_NONE: number; - readonly SVG_EDGEMODE_UNKNOWN: number; - readonly SVG_EDGEMODE_WRAP: number; -} - -interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly diffuseConstant: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDiffuseLightingElement: { - prototype: SVGFEDiffuseLightingElement; - new(): SVGFEDiffuseLightingElement; -} - -interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly in2: SVGAnimatedString; - readonly scale: SVGAnimatedNumber; - readonly xChannelSelector: SVGAnimatedEnumeration; - readonly yChannelSelector: SVGAnimatedEnumeration; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEDisplacementMapElement: { - prototype: SVGFEDisplacementMapElement; - new(): SVGFEDisplacementMapElement; - readonly SVG_CHANNEL_A: number; - readonly SVG_CHANNEL_B: number; - readonly SVG_CHANNEL_G: number; - readonly SVG_CHANNEL_R: number; - readonly SVG_CHANNEL_UNKNOWN: number; -} - -interface SVGFEDistantLightElement extends SVGElement { - readonly azimuth: SVGAnimatedNumber; - readonly elevation: SVGAnimatedNumber; -} - -declare var SVGFEDistantLightElement: { - prototype: SVGFEDistantLightElement; - new(): SVGFEDistantLightElement; -} - -interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEFloodElement: { - prototype: SVGFEFloodElement; - new(): SVGFEFloodElement; -} - -interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncAElement: { - prototype: SVGFEFuncAElement; - new(): SVGFEFuncAElement; -} - -interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncBElement: { - prototype: SVGFEFuncBElement; - new(): SVGFEFuncBElement; -} - -interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncGElement: { - prototype: SVGFEFuncGElement; - new(): SVGFEFuncGElement; -} - -interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { -} - -declare var SVGFEFuncRElement: { - prototype: SVGFEFuncRElement; - new(): SVGFEFuncRElement; -} - -interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly stdDeviationX: SVGAnimatedNumber; - readonly stdDeviationY: SVGAnimatedNumber; - setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEGaussianBlurElement: { - prototype: SVGFEGaussianBlurElement; - new(): SVGFEGaussianBlurElement; -} - -interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEImageElement: { - prototype: SVGFEImageElement; - new(): SVGFEImageElement; -} - -interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMergeElement: { - prototype: SVGFEMergeElement; - new(): SVGFEMergeElement; -} - -interface SVGFEMergeNodeElement extends SVGElement { - readonly in1: SVGAnimatedString; -} - -declare var SVGFEMergeNodeElement: { - prototype: SVGFEMergeNodeElement; - new(): SVGFEMergeNodeElement; -} - -interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly operator: SVGAnimatedEnumeration; - readonly radiusX: SVGAnimatedNumber; - readonly radiusY: SVGAnimatedNumber; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEMorphologyElement: { - prototype: SVGFEMorphologyElement; - new(): SVGFEMorphologyElement; - readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; - readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; - readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; -} - -interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly dx: SVGAnimatedNumber; - readonly dy: SVGAnimatedNumber; - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFEOffsetElement: { - prototype: SVGFEOffsetElement; - new(): SVGFEOffsetElement; -} - -interface SVGFEPointLightElement extends SVGElement { - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFEPointLightElement: { - prototype: SVGFEPointLightElement; - new(): SVGFEPointLightElement; -} - -interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - readonly kernelUnitLengthX: SVGAnimatedNumber; - readonly kernelUnitLengthY: SVGAnimatedNumber; - readonly specularConstant: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFESpecularLightingElement: { - prototype: SVGFESpecularLightingElement; - new(): SVGFESpecularLightingElement; -} - -interface SVGFESpotLightElement extends SVGElement { - readonly limitingConeAngle: SVGAnimatedNumber; - readonly pointsAtX: SVGAnimatedNumber; - readonly pointsAtY: SVGAnimatedNumber; - readonly pointsAtZ: SVGAnimatedNumber; - readonly specularExponent: SVGAnimatedNumber; - readonly x: SVGAnimatedNumber; - readonly y: SVGAnimatedNumber; - readonly z: SVGAnimatedNumber; -} - -declare var SVGFESpotLightElement: { - prototype: SVGFESpotLightElement; - new(): SVGFESpotLightElement; -} - -interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly in1: SVGAnimatedString; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETileElement: { - prototype: SVGFETileElement; - new(): SVGFETileElement; -} - -interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - readonly baseFrequencyX: SVGAnimatedNumber; - readonly baseFrequencyY: SVGAnimatedNumber; - readonly numOctaves: SVGAnimatedInteger; - readonly seed: SVGAnimatedNumber; - readonly stitchTiles: SVGAnimatedEnumeration; - readonly type: SVGAnimatedEnumeration; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFETurbulenceElement: { - prototype: SVGFETurbulenceElement; - new(): SVGFETurbulenceElement; - readonly SVG_STITCHTYPE_NOSTITCH: number; - readonly SVG_STITCHTYPE_STITCH: number; - readonly SVG_STITCHTYPE_UNKNOWN: number; - readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; - readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; -} - -interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { - readonly filterResX: SVGAnimatedInteger; - readonly filterResY: SVGAnimatedInteger; - readonly filterUnits: SVGAnimatedEnumeration; - readonly height: SVGAnimatedLength; - readonly primitiveUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGFilterElement: { - prototype: SVGFilterElement; - new(): SVGFilterElement; -} - -interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGForeignObjectElement: { - prototype: SVGForeignObjectElement; - new(): SVGForeignObjectElement; -} - -interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGElement: { - prototype: SVGGElement; - new(): SVGGElement; -} - -interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { - readonly gradientTransform: SVGAnimatedTransformList; - readonly gradientUnits: SVGAnimatedEnumeration; - readonly spreadMethod: SVGAnimatedEnumeration; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGGradientElement: { - prototype: SVGGradientElement; - new(): SVGGradientElement; - readonly SVG_SPREADMETHOD_PAD: number; - readonly SVG_SPREADMETHOD_REFLECT: number; - readonly SVG_SPREADMETHOD_REPEAT: number; - readonly SVG_SPREADMETHOD_UNKNOWN: number; -} - -interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly height: SVGAnimatedLength; - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGImageElement: { - prototype: SVGImageElement; - new(): SVGImageElement; -} - -interface SVGLength { - readonly unitType: number; - value: number; - valueAsString: string; - valueInSpecifiedUnits: number; - convertToSpecifiedUnits(unitType: number): void; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -declare var SVGLength: { - prototype: SVGLength; - new(): SVGLength; - readonly SVG_LENGTHTYPE_CM: number; - readonly SVG_LENGTHTYPE_EMS: number; - readonly SVG_LENGTHTYPE_EXS: number; - readonly SVG_LENGTHTYPE_IN: number; - readonly SVG_LENGTHTYPE_MM: number; - readonly SVG_LENGTHTYPE_NUMBER: number; - readonly SVG_LENGTHTYPE_PC: number; - readonly SVG_LENGTHTYPE_PERCENTAGE: number; - readonly SVG_LENGTHTYPE_PT: number; - readonly SVG_LENGTHTYPE_PX: number; - readonly SVG_LENGTHTYPE_UNKNOWN: number; -} - -interface SVGLengthList { - readonly numberOfItems: number; - appendItem(newItem: SVGLength): SVGLength; - clear(): void; - getItem(index: number): SVGLength; - initialize(newItem: SVGLength): SVGLength; - insertItemBefore(newItem: SVGLength, index: number): SVGLength; - removeItem(index: number): SVGLength; - replaceItem(newItem: SVGLength, index: number): SVGLength; -} - -declare var SVGLengthList: { - prototype: SVGLengthList; - new(): SVGLengthList; -} - -interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} - -interface SVGLinearGradientElement extends SVGGradientElement { - readonly x1: SVGAnimatedLength; - readonly x2: SVGAnimatedLength; - readonly y1: SVGAnimatedLength; - readonly y2: SVGAnimatedLength; -} - -declare var SVGLinearGradientElement: { - prototype: SVGLinearGradientElement; - new(): SVGLinearGradientElement; -} - -interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - readonly markerHeight: SVGAnimatedLength; - readonly markerUnits: SVGAnimatedEnumeration; - readonly markerWidth: SVGAnimatedLength; - readonly orientAngle: SVGAnimatedAngle; - readonly orientType: SVGAnimatedEnumeration; - readonly refX: SVGAnimatedLength; - readonly refY: SVGAnimatedLength; - setOrientToAngle(angle: SVGAngle): void; - setOrientToAuto(): void; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMarkerElement: { - prototype: SVGMarkerElement; - new(): SVGMarkerElement; - readonly SVG_MARKERUNITS_STROKEWIDTH: number; - readonly SVG_MARKERUNITS_UNKNOWN: number; - readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - readonly SVG_MARKER_ORIENT_ANGLE: number; - readonly SVG_MARKER_ORIENT_AUTO: number; - readonly SVG_MARKER_ORIENT_UNKNOWN: number; -} - -interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly maskContentUnits: SVGAnimatedEnumeration; - readonly maskUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGMaskElement: { - prototype: SVGMaskElement; - new(): SVGMaskElement; -} - -interface SVGMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - flipX(): SVGMatrix; - flipY(): SVGMatrix; - inverse(): SVGMatrix; - multiply(secondMatrix: SVGMatrix): SVGMatrix; - rotate(angle: number): SVGMatrix; - rotateFromVector(x: number, y: number): SVGMatrix; - scale(scaleFactor: number): SVGMatrix; - scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; - skewX(angle: number): SVGMatrix; - skewY(angle: number): SVGMatrix; - translate(x: number, y: number): SVGMatrix; -} - -declare var SVGMatrix: { - prototype: SVGMatrix; - new(): SVGMatrix; -} - -interface SVGMetadataElement extends SVGElement { -} - -declare var SVGMetadataElement: { - prototype: SVGMetadataElement; - new(): SVGMetadataElement; -} - -interface SVGNumber { - value: number; -} - -declare var SVGNumber: { - prototype: SVGNumber; - new(): SVGNumber; -} - -interface SVGNumberList { - readonly numberOfItems: number; - appendItem(newItem: SVGNumber): SVGNumber; - clear(): void; - getItem(index: number): SVGNumber; - initialize(newItem: SVGNumber): SVGNumber; - insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; - removeItem(index: number): SVGNumber; - replaceItem(newItem: SVGNumber, index: number): SVGNumber; -} - -declare var SVGNumberList: { - prototype: SVGNumberList; - new(): SVGNumberList; -} - -interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; - createSVGPathSegClosePath(): SVGPathSegClosePath; - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - getPathSegAtLength(distance: number): number; - getPointAtLength(distance: number): SVGPoint; - getTotalLength(): number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPathElement: { - prototype: SVGPathElement; - new(): SVGPathElement; -} - -interface SVGPathSeg { - readonly pathSegType: number; - readonly pathSegTypeAsLetter: string; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -declare var SVGPathSeg: { - prototype: SVGPathSeg; - new(): SVGPathSeg; - readonly PATHSEG_ARC_ABS: number; - readonly PATHSEG_ARC_REL: number; - readonly PATHSEG_CLOSEPATH: number; - readonly PATHSEG_CURVETO_CUBIC_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_REL: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_REL: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; - readonly PATHSEG_LINETO_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; - readonly PATHSEG_LINETO_HORIZONTAL_REL: number; - readonly PATHSEG_LINETO_REL: number; - readonly PATHSEG_LINETO_VERTICAL_ABS: number; - readonly PATHSEG_LINETO_VERTICAL_REL: number; - readonly PATHSEG_MOVETO_ABS: number; - readonly PATHSEG_MOVETO_REL: number; - readonly PATHSEG_UNKNOWN: number; -} - -interface SVGPathSegArcAbs extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcAbs: { - prototype: SVGPathSegArcAbs; - new(): SVGPathSegArcAbs; -} - -interface SVGPathSegArcRel extends SVGPathSeg { - angle: number; - largeArcFlag: boolean; - r1: number; - r2: number; - sweepFlag: boolean; - x: number; - y: number; -} - -declare var SVGPathSegArcRel: { - prototype: SVGPathSegArcRel; - new(): SVGPathSegArcRel; -} - -interface SVGPathSegClosePath extends SVGPathSeg { -} - -declare var SVGPathSegClosePath: { - prototype: SVGPathSegClosePath; - new(): SVGPathSegClosePath; -} - -interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicAbs: { - prototype: SVGPathSegCurvetoCubicAbs; - new(): SVGPathSegCurvetoCubicAbs; -} - -interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { - x: number; - x1: number; - x2: number; - y: number; - y1: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicRel: { - prototype: SVGPathSegCurvetoCubicRel; - new(): SVGPathSegCurvetoCubicRel; -} - -interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothAbs: { - prototype: SVGPathSegCurvetoCubicSmoothAbs; - new(): SVGPathSegCurvetoCubicSmoothAbs; -} - -interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { - x: number; - x2: number; - y: number; - y2: number; -} - -declare var SVGPathSegCurvetoCubicSmoothRel: { - prototype: SVGPathSegCurvetoCubicSmoothRel; - new(): SVGPathSegCurvetoCubicSmoothRel; -} - -interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticAbs: { - prototype: SVGPathSegCurvetoQuadraticAbs; - new(): SVGPathSegCurvetoQuadraticAbs; -} - -interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { - x: number; - x1: number; - y: number; - y1: number; -} - -declare var SVGPathSegCurvetoQuadraticRel: { - prototype: SVGPathSegCurvetoQuadraticRel; - new(): SVGPathSegCurvetoQuadraticRel; -} - -interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothAbs: { - prototype: SVGPathSegCurvetoQuadraticSmoothAbs; - new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} - -interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegCurvetoQuadraticSmoothRel: { - prototype: SVGPathSegCurvetoQuadraticSmoothRel; - new(): SVGPathSegCurvetoQuadraticSmoothRel; -} - -interface SVGPathSegLinetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoAbs: { - prototype: SVGPathSegLinetoAbs; - new(): SVGPathSegLinetoAbs; -} - -interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalAbs: { - prototype: SVGPathSegLinetoHorizontalAbs; - new(): SVGPathSegLinetoHorizontalAbs; -} - -interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { - x: number; -} - -declare var SVGPathSegLinetoHorizontalRel: { - prototype: SVGPathSegLinetoHorizontalRel; - new(): SVGPathSegLinetoHorizontalRel; -} - -interface SVGPathSegLinetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegLinetoRel: { - prototype: SVGPathSegLinetoRel; - new(): SVGPathSegLinetoRel; -} - -interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalAbs: { - prototype: SVGPathSegLinetoVerticalAbs; - new(): SVGPathSegLinetoVerticalAbs; -} - -interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { - y: number; -} - -declare var SVGPathSegLinetoVerticalRel: { - prototype: SVGPathSegLinetoVerticalRel; - new(): SVGPathSegLinetoVerticalRel; -} - -interface SVGPathSegList { - readonly numberOfItems: number; - appendItem(newItem: SVGPathSeg): SVGPathSeg; - clear(): void; - getItem(index: number): SVGPathSeg; - initialize(newItem: SVGPathSeg): SVGPathSeg; - insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; - removeItem(index: number): SVGPathSeg; - replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; -} - -declare var SVGPathSegList: { - prototype: SVGPathSegList; - new(): SVGPathSegList; -} - -interface SVGPathSegMovetoAbs extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoAbs: { - prototype: SVGPathSegMovetoAbs; - new(): SVGPathSegMovetoAbs; -} - -interface SVGPathSegMovetoRel extends SVGPathSeg { - x: number; - y: number; -} - -declare var SVGPathSegMovetoRel: { - prototype: SVGPathSegMovetoRel; - new(): SVGPathSegMovetoRel; -} - -interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { - readonly height: SVGAnimatedLength; - readonly patternContentUnits: SVGAnimatedEnumeration; - readonly patternTransform: SVGAnimatedTransformList; - readonly patternUnits: SVGAnimatedEnumeration; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPatternElement: { - prototype: SVGPatternElement; - new(): SVGPatternElement; -} - -interface SVGPoint { - x: number; - y: number; - matrixTransform(matrix: SVGMatrix): SVGPoint; -} - -declare var SVGPoint: { - prototype: SVGPoint; - new(): SVGPoint; -} - -interface SVGPointList { - readonly numberOfItems: number; - appendItem(newItem: SVGPoint): SVGPoint; - clear(): void; - getItem(index: number): SVGPoint; - initialize(newItem: SVGPoint): SVGPoint; - insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; - removeItem(index: number): SVGPoint; - replaceItem(newItem: SVGPoint, index: number): SVGPoint; -} - -declare var SVGPointList: { - prototype: SVGPointList; - new(): SVGPointList; -} - -interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolygonElement: { - prototype: SVGPolygonElement; - new(): SVGPolygonElement; -} - -interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGPolylineElement: { - prototype: SVGPolylineElement; - new(): SVGPolylineElement; -} - -interface SVGPreserveAspectRatio { - align: number; - meetOrSlice: number; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -declare var SVGPreserveAspectRatio: { - prototype: SVGPreserveAspectRatio; - new(): SVGPreserveAspectRatio; - readonly SVG_MEETORSLICE_MEET: number; - readonly SVG_MEETORSLICE_SLICE: number; - readonly SVG_MEETORSLICE_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_NONE: number; - readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; - readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; -} - -interface SVGRadialGradientElement extends SVGGradientElement { - readonly cx: SVGAnimatedLength; - readonly cy: SVGAnimatedLength; - readonly fx: SVGAnimatedLength; - readonly fy: SVGAnimatedLength; - readonly r: SVGAnimatedLength; -} - -declare var SVGRadialGradientElement: { - prototype: SVGRadialGradientElement; - new(): SVGRadialGradientElement; -} - -interface SVGRect { - height: number; - width: number; - x: number; - y: number; -} - -declare var SVGRect: { - prototype: SVGRect; - new(): SVGRect; -} - -interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly height: SVGAnimatedLength; - readonly rx: SVGAnimatedLength; - readonly ry: SVGAnimatedLength; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGRectElement: { - prototype: SVGRectElement; - new(): SVGRectElement; -} - -interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - contentScriptType: string; - contentStyleType: string; - currentScale: number; - readonly currentTranslate: SVGPoint; - readonly height: SVGAnimatedLength; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onunload: (this: this, ev: Event) => any; - onzoom: (this: this, ev: SVGZoomEvent) => any; - readonly pixelUnitToMillimeterX: number; - readonly pixelUnitToMillimeterY: number; - readonly screenPixelToMillimeterX: number; - readonly screenPixelToMillimeterY: number; - readonly viewport: SVGRect; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - checkEnclosure(element: SVGElement, rect: SVGRect): boolean; - checkIntersection(element: SVGElement, rect: SVGRect): boolean; - createSVGAngle(): SVGAngle; - createSVGLength(): SVGLength; - createSVGMatrix(): SVGMatrix; - createSVGNumber(): SVGNumber; - createSVGPoint(): SVGPoint; - createSVGRect(): SVGRect; - createSVGTransform(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - deselectAll(): void; - forceRedraw(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getCurrentTime(): number; - getElementById(elementId: string): Element; - getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; - pauseAnimations(): void; - setCurrentTime(seconds: number): void; - suspendRedraw(maxWaitMilliseconds: number): number; - unpauseAnimations(): void; - unsuspendRedraw(suspendHandleID: number): void; - unsuspendRedrawAll(): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "SVGAbort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGError", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGUnload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGZoom", listener: (this: this, ev: SVGZoomEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSVGElement: { - prototype: SVGSVGElement; - new(): SVGSVGElement; -} - -interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface SVGStopElement extends SVGElement, SVGStylable { - readonly offset: SVGAnimatedNumber; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface SVGStringList { - readonly numberOfItems: number; - appendItem(newItem: string): string; - clear(): void; - getItem(index: number): string; - initialize(newItem: string): string; - insertItemBefore(newItem: string, index: number): string; - removeItem(index: number): string; - replaceItem(newItem: string, index: number): string; -} - -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface SVGStyleElement extends SVGElement, SVGLangSpace { - disabled: boolean; - media: string; - title: string; - type: string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} - -interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSwitchElement: { - prototype: SVGSwitchElement; - new(): SVGSwitchElement; -} - -interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGSymbolElement: { - prototype: SVGSymbolElement; - new(): SVGSymbolElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { -} - -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} - -interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { - readonly lengthAdjust: SVGAnimatedEnumeration; - readonly textLength: SVGAnimatedLength; - getCharNumAtPosition(point: SVGPoint): number; - getComputedTextLength(): number; - getEndPositionOfChar(charnum: number): SVGPoint; - getExtentOfChar(charnum: number): SVGRect; - getNumberOfChars(): number; - getRotationOfChar(charnum: number): number; - getStartPositionOfChar(charnum: number): SVGPoint; - getSubStringLength(charnum: number, nchars: number): number; - selectSubString(charnum: number, nchars: number): void; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextContentElement: { - prototype: SVGTextContentElement; - new(): SVGTextContentElement; - readonly LENGTHADJUST_SPACING: number; - readonly LENGTHADJUST_SPACINGANDGLYPHS: number; - readonly LENGTHADJUST_UNKNOWN: number; -} - -interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextElement: { - prototype: SVGTextElement; - new(): SVGTextElement; -} - -interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { - readonly method: SVGAnimatedEnumeration; - readonly spacing: SVGAnimatedEnumeration; - readonly startOffset: SVGAnimatedLength; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTextPathElement: { - prototype: SVGTextPathElement; - new(): SVGTextPathElement; - readonly TEXTPATH_METHODTYPE_ALIGN: number; - readonly TEXTPATH_METHODTYPE_STRETCH: number; - readonly TEXTPATH_METHODTYPE_UNKNOWN: number; - readonly TEXTPATH_SPACINGTYPE_AUTO: number; - readonly TEXTPATH_SPACINGTYPE_EXACT: number; - readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; -} - -interface SVGTextPositioningElement extends SVGTextContentElement { - readonly dx: SVGAnimatedLengthList; - readonly dy: SVGAnimatedLengthList; - readonly rotate: SVGAnimatedNumberList; - readonly x: SVGAnimatedLengthList; - readonly y: SVGAnimatedLengthList; -} - -declare var SVGTextPositioningElement: { - prototype: SVGTextPositioningElement; - new(): SVGTextPositioningElement; -} - -interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGTitleElement: { - prototype: SVGTitleElement; - new(): SVGTitleElement; -} - -interface SVGTransform { - readonly angle: number; - readonly matrix: SVGMatrix; - readonly type: number; - setMatrix(matrix: SVGMatrix): void; - setRotate(angle: number, cx: number, cy: number): void; - setScale(sx: number, sy: number): void; - setSkewX(angle: number): void; - setSkewY(angle: number): void; - setTranslate(tx: number, ty: number): void; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -declare var SVGTransform: { - prototype: SVGTransform; - new(): SVGTransform; - readonly SVG_TRANSFORM_MATRIX: number; - readonly SVG_TRANSFORM_ROTATE: number; - readonly SVG_TRANSFORM_SCALE: number; - readonly SVG_TRANSFORM_SKEWX: number; - readonly SVG_TRANSFORM_SKEWY: number; - readonly SVG_TRANSFORM_TRANSLATE: number; - readonly SVG_TRANSFORM_UNKNOWN: number; -} - -interface SVGTransformList { - readonly numberOfItems: number; - appendItem(newItem: SVGTransform): SVGTransform; - clear(): void; - consolidate(): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - getItem(index: number): SVGTransform; - initialize(newItem: SVGTransform): SVGTransform; - insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; - removeItem(index: number): SVGTransform; - replaceItem(newItem: SVGTransform, index: number): SVGTransform; -} - -declare var SVGTransformList: { - prototype: SVGTransformList; - new(): SVGTransformList; -} - -interface SVGUnitTypes { - readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; - readonly SVG_UNIT_TYPE_UNKNOWN: number; - readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; -} -declare var SVGUnitTypes: SVGUnitTypes; - -interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance; - readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGUseElement: { - prototype: SVGUseElement; - new(): SVGUseElement; -} - -interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { - readonly viewTarget: SVGStringList; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var SVGViewElement: { - prototype: SVGViewElement; - new(): SVGViewElement; -} - -interface SVGZoomAndPan { - readonly zoomAndPan: number; -} - -declare var SVGZoomAndPan: { - readonly SVG_ZOOMANDPAN_DISABLE: number; - readonly SVG_ZOOMANDPAN_MAGNIFY: number; - readonly SVG_ZOOMANDPAN_UNKNOWN: number; -} - -interface SVGZoomEvent extends UIEvent { - readonly newScale: number; - readonly newTranslate: SVGPoint; - readonly previousScale: number; - readonly previousTranslate: SVGPoint; - readonly zoomRectScreen: SVGRect; -} - -declare var SVGZoomEvent: { - prototype: SVGZoomEvent; - new(): SVGZoomEvent; -} - -interface Screen extends EventTarget { - readonly availHeight: number; - readonly availWidth: number; - bufferDepth: number; - readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; - readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: (this: this, ev: Event) => any; - readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; - readonly width: number; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - addEventListener(type: "MSOrientationChange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface ScriptNotifyEvent extends Event { - readonly callingUri: string; - readonly value: string; -} - -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new(): ScriptNotifyEvent; -} - -interface ScriptProcessorNode extends AudioNode { - readonly bufferSize: number; - onaudioprocess: (this: this, ev: AudioProcessingEvent) => any; - addEventListener(type: "audioprocess", listener: (this: this, ev: AudioProcessingEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var ScriptProcessorNode: { - prototype: ScriptProcessorNode; - new(): ScriptProcessorNode; -} - -interface Selection { - readonly anchorNode: Node; - readonly anchorOffset: number; - readonly focusNode: Node; - readonly focusOffset: number; - readonly isCollapsed: boolean; - readonly rangeCount: number; - readonly type: string; - addRange(range: Range): void; - collapse(parentNode: Node, offset: number): void; - collapseToEnd(): void; - collapseToStart(): void; - containsNode(node: Node, partlyContained: boolean): boolean; - deleteFromDocument(): void; - empty(): void; - extend(newNode: Node, offset: number): void; - getRangeAt(index: number): Range; - removeAllRanges(): void; - removeRange(range: Range): void; - selectAllChildren(parentNode: Node): void; - setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; - toString(): string; -} - -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface SourceBuffer extends EventTarget { - appendWindowEnd: number; - appendWindowStart: number; - readonly audioTracks: AudioTrackList; - readonly buffered: TimeRanges; - mode: string; - timestampOffset: number; - readonly updating: boolean; - readonly videoTracks: VideoTrackList; - abort(): void; - appendBuffer(data: ArrayBuffer | ArrayBufferView): void; - appendStream(stream: MSStream, maxSize?: number): void; - remove(start: number, end: number): void; -} - -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - -interface SourceBufferList extends EventTarget { - readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; -} - -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; -} - -interface StereoPannerNode extends AudioNode { - readonly pan: AudioParam; -} - -declare var StereoPannerNode: { - prototype: StereoPannerNode; - new(): StereoPannerNode; -} - -interface Storage { - readonly length: number; - clear(): void; - getItem(key: string): string | null; - key(index: number): string | null; - removeItem(key: string): void; - setItem(key: string, data: string): void; - [key: string]: any; - [index: number]: string; -} - -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface StorageEvent extends Event { - readonly url: string; - key?: string; - oldValue?: string; - newValue?: string; - storageArea?: Storage; -} - -declare var StorageEvent: { - prototype: StorageEvent; - new (type: string, eventInitDict?: StorageEventInit): StorageEvent; -} - -interface StyleMedia { - readonly type: string; - matchMedium(mediaquery: string): boolean; -} - -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface StyleSheet { - disabled: boolean; - readonly href: string; - readonly media: MediaList; - readonly ownerNode: Node; - readonly parentStyleSheet: StyleSheet; - readonly title: string; - readonly type: string; -} - -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface StyleSheetList { - readonly length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} - -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface StyleSheetPageList { - readonly length: number; - item(index: number): CSSPageRule; - [index: number]: CSSPageRule; -} - -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface SubtleCrypto { - 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: { - prototype: SubtleCrypto; - new(): SubtleCrypto; -} - -interface Text extends CharacterData { - readonly wholeText: string; - splitText(offset: number): Text; -} - -declare var Text: { - prototype: Text; - new(): Text; -} - -interface TextEvent extends UIEvent { - readonly data: string; - readonly inputMethod: number; - readonly locale: string; - initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -declare var TextEvent: { - prototype: TextEvent; - new(): TextEvent; - readonly DOM_INPUT_METHOD_DROP: number; - readonly DOM_INPUT_METHOD_HANDWRITING: number; - readonly DOM_INPUT_METHOD_IME: number; - readonly DOM_INPUT_METHOD_KEYBOARD: number; - readonly DOM_INPUT_METHOD_MULTIMODAL: number; - readonly DOM_INPUT_METHOD_OPTION: number; - readonly DOM_INPUT_METHOD_PASTE: number; - readonly DOM_INPUT_METHOD_SCRIPT: number; - readonly DOM_INPUT_METHOD_UNKNOWN: number; - readonly DOM_INPUT_METHOD_VOICE: number; -} - -interface TextMetrics { - readonly width: number; -} - -declare var TextMetrics: { - prototype: TextMetrics; - new(): TextMetrics; -} - -interface TextTrack extends EventTarget { - readonly activeCues: TextTrackCueList; - readonly cues: TextTrackCueList; - readonly inBandMetadataTrackDispatchType: string; - readonly kind: string; - readonly label: string; - readonly language: string; - mode: any; - oncuechange: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - readonly readyState: number; - addCue(cue: TextTrackCue): void; - removeCue(cue: TextTrackCue): void; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrack: { - prototype: TextTrack; - new(): TextTrack; - readonly DISABLED: number; - readonly ERROR: number; - readonly HIDDEN: number; - readonly LOADED: number; - readonly LOADING: number; - readonly NONE: number; - readonly SHOWING: number; -} - -interface TextTrackCue extends EventTarget { - endTime: number; - id: string; - onenter: (this: this, ev: Event) => any; - onexit: (this: this, ev: Event) => any; - pauseOnExit: boolean; - startTime: number; - text: string; - readonly track: TextTrack; - getCueAsHTML(): DocumentFragment; - addEventListener(type: "enter", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "exit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var TextTrackCue: { - prototype: TextTrackCue; - new(startTime: number, endTime: number, text: string): TextTrackCue; -} - -interface TextTrackCueList { - readonly length: number; - getCueById(id: string): TextTrackCue; - item(index: number): TextTrackCue; - [index: number]: TextTrackCue; -} - -declare var TextTrackCueList: { - prototype: TextTrackCueList; - new(): TextTrackCueList; -} - -interface TextTrackList extends EventTarget { - readonly length: number; - onaddtrack: ((this: this, ev: TrackEvent) => any) | null; - item(index: number): TextTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: TextTrack; -} - -declare var TextTrackList: { - prototype: TextTrackList; - new(): TextTrackList; -} - -interface TimeRanges { - readonly length: number; - end(index: number): number; - start(index: number): number; -} - -declare var TimeRanges: { - prototype: TimeRanges; - new(): TimeRanges; -} - -interface Touch { - readonly clientX: number; - readonly clientY: number; - readonly identifier: number; - readonly pageX: number; - readonly pageY: number; - readonly screenX: number; - readonly screenY: number; - readonly target: EventTarget; -} - -declare var Touch: { - prototype: Touch; - new(): Touch; -} - -interface TouchEvent extends UIEvent { - readonly altKey: boolean; - readonly changedTouches: TouchList; - readonly ctrlKey: boolean; - readonly metaKey: boolean; - readonly shiftKey: boolean; - readonly targetTouches: TouchList; - readonly touches: TouchList; -} - -declare var TouchEvent: { - prototype: TouchEvent; - new(): TouchEvent; -} - -interface TouchList { - readonly length: number; - item(index: number): Touch | null; - [index: number]: Touch; -} - -declare var TouchList: { - prototype: TouchList; - new(): TouchList; -} - -interface TrackEvent extends Event { - readonly track: any; -} - -declare var TrackEvent: { - prototype: TrackEvent; - new(): TrackEvent; -} - -interface TransitionEvent extends Event { - readonly elapsedTime: number; - readonly propertyName: string; - initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; -} - -declare var TransitionEvent: { - prototype: TransitionEvent; - new(): TransitionEvent; -} - -interface TreeWalker { - currentNode: Node; - readonly expandEntityReferences: boolean; - readonly filter: NodeFilter; - readonly root: Node; - readonly whatToShow: number; - firstChild(): Node; - lastChild(): Node; - nextNode(): Node; - nextSibling(): Node; - parentNode(): Node; - previousNode(): Node; - previousSibling(): Node; -} - -declare var TreeWalker: { - prototype: TreeWalker; - new(): TreeWalker; -} - -interface UIEvent extends Event { - readonly detail: number; - readonly view: Window; - initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; -} - -declare var UIEvent: { - prototype: UIEvent; - new(type: string, eventInitDict?: UIEventInit): UIEvent; -} - -interface URL { - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - username: string; - toString(): string; -} - -declare var URL: { - prototype: URL; - new(url: string, base?: string): URL; - createObjectURL(object: any, options?: ObjectURLOptions): string; - revokeObjectURL(url: string): void; -} - -interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { - readonly mediaType: string; -} - -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new(): UnviewableContentIdentifiedEvent; -} - -interface ValidityState { - readonly badInput: boolean; - readonly customError: boolean; - readonly patternMismatch: boolean; - readonly rangeOverflow: boolean; - readonly rangeUnderflow: boolean; - readonly stepMismatch: boolean; - readonly tooLong: boolean; - readonly typeMismatch: boolean; - readonly valid: boolean; - readonly valueMissing: boolean; -} - -declare var ValidityState: { - prototype: ValidityState; - new(): ValidityState; -} - -interface VideoPlaybackQuality { - readonly corruptedVideoFrames: number; - readonly creationTime: number; - readonly droppedVideoFrames: number; - readonly totalFrameDelay: number; - readonly totalVideoFrames: number; -} - -declare var VideoPlaybackQuality: { - prototype: VideoPlaybackQuality; - new(): VideoPlaybackQuality; -} - -interface VideoTrack { - readonly id: string; - kind: string; - readonly label: string; - language: string; - selected: boolean; - readonly sourceBuffer: SourceBuffer; -} - -declare var VideoTrack: { - prototype: VideoTrack; - new(): VideoTrack; -} - -interface VideoTrackList extends EventTarget { - readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; - readonly selectedIndex: number; - getTrackById(id: string): VideoTrack | null; - item(index: number): VideoTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: VideoTrack; -} - -declare var VideoTrackList: { - prototype: VideoTrackList; - new(): VideoTrackList; -} - -interface WEBGL_compressed_texture_s3tc { - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -declare var WEBGL_compressed_texture_s3tc: { - prototype: WEBGL_compressed_texture_s3tc; - new(): WEBGL_compressed_texture_s3tc; - readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; - readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; -} - -interface WEBGL_debug_renderer_info { - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -declare var WEBGL_debug_renderer_info: { - prototype: WEBGL_debug_renderer_info; - new(): WEBGL_debug_renderer_info; - readonly UNMASKED_RENDERER_WEBGL: number; - readonly UNMASKED_VENDOR_WEBGL: number; -} - -interface WEBGL_depth_texture { - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -declare var WEBGL_depth_texture: { - prototype: WEBGL_depth_texture; - new(): WEBGL_depth_texture; - readonly UNSIGNED_INT_24_8_WEBGL: number; -} - -interface WaveShaperNode extends AudioNode { - curve: Float32Array | null; - oversample: string; -} - -declare var WaveShaperNode: { - prototype: WaveShaperNode; - new(): WaveShaperNode; -} - -interface WebGLActiveInfo { - readonly name: string; - readonly size: number; - readonly type: number; -} - -declare var WebGLActiveInfo: { - prototype: WebGLActiveInfo; - new(): WebGLActiveInfo; -} - -interface WebGLBuffer extends WebGLObject { -} - -declare var WebGLBuffer: { - prototype: WebGLBuffer; - new(): WebGLBuffer; -} - -interface WebGLContextEvent extends Event { - readonly statusMessage: string; -} - -declare var WebGLContextEvent: { - prototype: WebGLContextEvent; - new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} - -interface WebGLFramebuffer extends WebGLObject { -} - -declare var WebGLFramebuffer: { - prototype: WebGLFramebuffer; - new(): WebGLFramebuffer; -} - -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -} - -interface WebGLProgram extends WebGLObject { -} - -declare var WebGLProgram: { - prototype: WebGLProgram; - new(): WebGLProgram; -} - -interface WebGLRenderbuffer extends WebGLObject { -} - -declare var WebGLRenderbuffer: { - prototype: WebGLRenderbuffer; - new(): WebGLRenderbuffer; -} - -interface WebGLRenderingContext { - readonly canvas: HTMLCanvasElement; - readonly drawingBufferHeight: number; - readonly drawingBufferWidth: number; - activeTexture(texture: number): void; - attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; - bindBuffer(target: number, buffer: WebGLBuffer | null): void; - bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; - bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; - bindTexture(target: number, texture: WebGLTexture | null): void; - blendColor(red: number, green: number, blue: number, alpha: number): void; - blendEquation(mode: number): void; - blendEquationSeparate(modeRGB: number, modeAlpha: number): void; - blendFunc(sfactor: number, dfactor: number): void; - blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; - bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; - bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; - checkFramebufferStatus(target: number): number; - clear(mask: number): void; - clearColor(red: number, green: number, blue: number, alpha: number): void; - clearDepth(depth: number): void; - clearStencil(s: number): void; - colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; - compileShader(shader: WebGLShader | null): void; - compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; - compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; - copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; - copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; - createBuffer(): WebGLBuffer | null; - createFramebuffer(): WebGLFramebuffer | null; - createProgram(): WebGLProgram | null; - createRenderbuffer(): WebGLRenderbuffer | null; - createShader(type: number): WebGLShader | null; - createTexture(): WebGLTexture | null; - cullFace(mode: number): void; - deleteBuffer(buffer: WebGLBuffer | null): void; - deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; - deleteProgram(program: WebGLProgram | null): void; - deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; - deleteShader(shader: WebGLShader | null): void; - deleteTexture(texture: WebGLTexture | null): void; - depthFunc(func: number): void; - depthMask(flag: boolean): void; - depthRange(zNear: number, zFar: number): void; - detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - disable(cap: number): void; - disableVertexAttribArray(index: number): void; - drawArrays(mode: number, first: number, count: number): void; - drawElements(mode: number, count: number, type: number, offset: number): void; - enable(cap: number): void; - enableVertexAttribArray(index: number): void; - finish(): void; - flush(): void; - framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; - framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; - frontFace(mode: number): void; - generateMipmap(target: number): void; - getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; - getAttribLocation(program: WebGLProgram | null, name: string): number; - getBufferParameter(target: number, pname: number): any; - getContextAttributes(): WebGLContextAttributes; - getError(): number; - getExtension(name: string): any; - getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; - getParameter(pname: number): any; - getProgramInfoLog(program: WebGLProgram | null): string | null; - getProgramParameter(program: WebGLProgram | null, pname: number): any; - getRenderbufferParameter(target: number, pname: number): any; - getShaderInfoLog(shader: WebGLShader | null): string | null; - getShaderParameter(shader: WebGLShader | null, pname: number): any; - getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; - getShaderSource(shader: WebGLShader | null): string | null; - getSupportedExtensions(): string[] | null; - getTexParameter(target: number, pname: number): any; - getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; - getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; - getVertexAttrib(index: number, pname: number): any; - getVertexAttribOffset(index: number, pname: number): number; - hint(target: number, mode: number): void; - isBuffer(buffer: WebGLBuffer | null): boolean; - isContextLost(): boolean; - isEnabled(cap: number): boolean; - isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; - isProgram(program: WebGLProgram | null): boolean; - isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; - isShader(shader: WebGLShader | null): boolean; - isTexture(texture: WebGLTexture | null): boolean; - lineWidth(width: number): void; - linkProgram(program: WebGLProgram | null): void; - pixelStorei(pname: number, param: number): void; - polygonOffset(factor: number, units: number): void; - readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; - renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; - sampleCoverage(value: number, invert: boolean): void; - scissor(x: number, y: number, width: number, height: number): void; - shaderSource(shader: WebGLShader | null, source: string): void; - stencilFunc(func: number, ref: number, mask: number): void; - stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; - stencilMask(mask: number): void; - 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, 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, 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; - uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; - uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; - uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; - useProgram(program: WebGLProgram | null): void; - validateProgram(program: WebGLProgram | null): void; - vertexAttrib1f(indx: number, x: number): void; - vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib2f(indx: number, x: number, y: number): void; - vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib3f(indx: number, x: number, y: number, z: number): void; - vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; - vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; - vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; - viewport(x: number, y: number, width: number, height: number): void; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -declare var WebGLRenderingContext: { - prototype: WebGLRenderingContext; - new(): WebGLRenderingContext; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -} - -interface WebGLShader extends WebGLObject { -} - -declare var WebGLShader: { - prototype: WebGLShader; - new(): WebGLShader; -} - -interface WebGLShaderPrecisionFormat { - readonly precision: number; - readonly rangeMax: number; - readonly rangeMin: number; -} - -declare var WebGLShaderPrecisionFormat: { - prototype: WebGLShaderPrecisionFormat; - new(): WebGLShaderPrecisionFormat; -} - -interface WebGLTexture extends WebGLObject { -} - -declare var WebGLTexture: { - prototype: WebGLTexture; - new(): WebGLTexture; -} - -interface WebGLUniformLocation { -} - -declare var WebGLUniformLocation: { - prototype: WebGLUniformLocation; - new(): WebGLUniformLocation; -} - -interface WebKitCSSMatrix { - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - m11: number; - m12: number; - m13: number; - m14: number; - m21: number; - m22: number; - m23: number; - m24: number; - m31: number; - m32: number; - m33: number; - m34: number; - m41: number; - m42: number; - m43: number; - m44: number; - inverse(): WebKitCSSMatrix; - multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; - rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; - rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; - scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; - setMatrixValue(value: string): void; - skewX(angle: number): WebKitCSSMatrix; - skewY(angle: number): WebKitCSSMatrix; - toString(): string; - translate(x: number, y: number, z?: number): WebKitCSSMatrix; -} - -declare var WebKitCSSMatrix: { - prototype: WebKitCSSMatrix; - new(text?: string): WebKitCSSMatrix; -} - -interface WebKitPoint { - x: number; - y: number; -} - -declare var WebKitPoint: { - prototype: WebKitPoint; - new(x?: number, y?: number): WebKitPoint; -} - -interface WebSocket extends EventTarget { - binaryType: string; - readonly bufferedAmount: number; - readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; - readonly protocol: string; - readonly readyState: number; - readonly url: string; - close(code?: number, reason?: string): void; - send(data: any): void; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WebSocket: { - prototype: WebSocket; - new(url: string, protocols?: string | string[]): WebSocket; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; -} - -interface WheelEvent extends MouseEvent { - readonly deltaMode: number; - readonly deltaX: number; - readonly deltaY: number; - readonly deltaZ: number; - readonly wheelDelta: number; - readonly wheelDeltaX: number; - readonly wheelDeltaY: number; - getCurrentPoint(element: Element): void; - initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -declare var WheelEvent: { - prototype: WheelEvent; - new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; - readonly DOM_DELTA_LINE: number; - readonly DOM_DELTA_PAGE: number; - readonly DOM_DELTA_PIXEL: number; -} - -interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { - readonly applicationCache: ApplicationCache; - readonly clientInformation: Navigator; - readonly closed: boolean; - readonly crypto: Crypto; - defaultStatus: string; - readonly devicePixelRatio: number; - readonly doNotTrack: string; - readonly document: Document; - event: Event; - readonly external: External; - readonly frameElement: Element; - readonly frames: Window; - readonly history: History; - readonly innerHeight: number; - readonly innerWidth: number; - readonly length: number; - readonly location: Location; - readonly locationbar: BarProp; - readonly menubar: BarProp; - readonly msCredentials: MSCredentials; - name: string; - readonly navigator: Navigator; - offscreenBuffering: string | boolean; - onabort: (this: this, ev: UIEvent) => any; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncompassneedscalibration: (this: this, ev: Event) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondevicelight: (this: this, ev: DeviceLightEvent) => any; - ondevicemotion: (this: this, ev: DeviceMotionEvent) => any; - ondeviceorientation: (this: this, ev: DeviceOrientationEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: ErrorEventHandler; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreadystatechange: (this: this, ev: ProgressEvent) => any; - onreset: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onstalled: (this: this, ev: Event) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - ontouchcancel: (ev: TouchEvent) => any; - ontouchend: (ev: TouchEvent) => any; - ontouchmove: (ev: TouchEvent) => any; - ontouchstart: (ev: TouchEvent) => any; - onunload: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; - opener: any; - orientation: string | number; - readonly outerHeight: number; - readonly outerWidth: number; - readonly pageXOffset: number; - readonly pageYOffset: number; - readonly parent: Window; - readonly performance: Performance; - readonly personalbar: BarProp; - readonly screen: Screen; - readonly screenLeft: number; - readonly screenTop: number; - readonly screenX: number; - readonly screenY: number; - readonly scrollX: number; - readonly scrollY: number; - readonly scrollbars: BarProp; - readonly self: Window; - status: string; - readonly statusbar: BarProp; - readonly styleMedia: StyleMedia; - readonly toolbar: BarProp; - readonly top: Window; - readonly window: Window; - URL: typeof URL; - Blob: typeof Blob; - alert(message?: any): void; - blur(): void; - cancelAnimationFrame(handle: number): void; - captureEvents(): void; - close(): void; - confirm(message?: string): boolean; - focus(): void; - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; - getSelection(): Selection; - matchMedia(mediaQuery: string): MediaQueryList; - moveBy(x?: number, y?: number): void; - moveTo(x?: number, y?: number): void; - msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; - postMessage(message: any, targetOrigin: string, transfer?: any[]): void; - print(): void; - prompt(message?: string, _default?: string): string | null; - releaseEvents(): void; - requestAnimationFrame(callback: FrameRequestCallback): number; - resizeBy(x?: number, y?: number): void; - resizeTo(x?: number, y?: number): void; - scroll(x?: number, y?: number): void; - scrollBy(x?: number, y?: number): void; - scrollTo(x?: number, y?: number): void; - webkitCancelAnimationFrame(handle: number): void; - webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; - webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; - webkitRequestAnimationFrame(callback: FrameRequestCallback): number; - scroll(options?: ScrollToOptions): void; - scrollTo(options?: ScrollToOptions): void; - scrollBy(options?: ScrollToOptions): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "compassneedscalibration", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicelight", listener: (this: this, ev: DeviceLightEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicemotion", listener: (this: this, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deviceorientation", listener: (this: this, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; -} - -declare var Window: { - prototype: Window; - new(): Window; -} - -interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; - postMessage(message: any, ports?: any): void; - terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Worker: { - prototype: Worker; - new(stringUrl: string): Worker; -} - -interface XMLDocument extends Document { -} - -declare var XMLDocument: { - prototype: XMLDocument; - new(): XMLDocument; -} - -interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly response: any; - readonly responseText: string; - responseType: string; - readonly responseXML: any; - readonly status: number; - readonly statusText: string; - timeout: number; - readonly upload: XMLHttpRequestUpload; - withCredentials: boolean; - msCaching?: string; - abort(): void; - getAllResponseHeaders(): string; - getResponseHeader(header: string): string | null; - msCachingEnabled(): boolean; - open(method: string, url: string, async?: boolean, user?: string, password?: string): void; - overrideMimeType(mime: string): void; - send(data?: Document): void; - send(data?: string): void; - send(data?: any): void; - setRequestHeader(header: string, value: string): void; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequest: { - prototype: XMLHttpRequest; - new(): XMLHttpRequest; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - create(): XMLHttpRequest; -} - -interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequestUpload: { - prototype: XMLHttpRequestUpload; - new(): XMLHttpRequestUpload; -} - -interface XMLSerializer { - serializeToString(target: Node): string; -} - -declare var XMLSerializer: { - prototype: XMLSerializer; - new(): XMLSerializer; -} - -interface XPathEvaluator { - createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; -} - -declare var XPathEvaluator: { - prototype: XPathEvaluator; - new(): XPathEvaluator; -} - -interface XPathExpression { - evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; -} - -declare var XPathExpression: { - prototype: XPathExpression; - new(): XPathExpression; -} - -interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; -} - -declare var XPathNSResolver: { - prototype: XPathNSResolver; - new(): XPathNSResolver; -} - -interface XPathResult { - readonly booleanValue: boolean; - readonly invalidIteratorState: boolean; - readonly numberValue: number; - readonly resultType: number; - readonly singleNodeValue: Node; - readonly snapshotLength: number; - readonly stringValue: string; - iterateNext(): Node; - snapshotItem(index: number): Node; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -declare var XPathResult: { - prototype: XPathResult; - new(): XPathResult; - readonly ANY_TYPE: number; - readonly ANY_UNORDERED_NODE_TYPE: number; - readonly BOOLEAN_TYPE: number; - readonly FIRST_ORDERED_NODE_TYPE: number; - readonly NUMBER_TYPE: number; - readonly ORDERED_NODE_ITERATOR_TYPE: number; - readonly ORDERED_NODE_SNAPSHOT_TYPE: number; - readonly STRING_TYPE: number; - readonly UNORDERED_NODE_ITERATOR_TYPE: number; - readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} - -interface XSLTProcessor { - clearParameters(): void; - getParameter(namespaceURI: string, localName: string): any; - importStylesheet(style: Node): void; - removeParameter(namespaceURI: string, localName: string): void; - reset(): void; - setParameter(namespaceURI: string, localName: string, value: any): void; - transformToDocument(source: Node): Document; - transformToFragment(source: Node, document: Document): DocumentFragment; -} - -declare var XSLTProcessor: { - prototype: XSLTProcessor; - new(): XSLTProcessor; -} - -interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface CanvasPathMethods { - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; - bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; - closePath(): void; - ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; - rect(x: number, y: number, w: number, h: number): void; -} - -interface ChildNode { - remove(): void; -} - -interface DOML2DeprecatedColorProperty { - color: string; -} - -interface DOML2DeprecatedSizeProperty { - size: number; -} - -interface DocumentEvent { - createEvent(eventInterface:"AnimationEvent"): AnimationEvent; - createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; - createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; - createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; - createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; - createEvent(eventInterface:"CloseEvent"): CloseEvent; - createEvent(eventInterface:"CommandEvent"): CommandEvent; - createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface:"CustomEvent"): CustomEvent; - createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; - createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; - createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; - createEvent(eventInterface:"DragEvent"): DragEvent; - createEvent(eventInterface:"ErrorEvent"): ErrorEvent; - createEvent(eventInterface:"Event"): Event; - createEvent(eventInterface:"Events"): Event; - createEvent(eventInterface:"FocusEvent"): FocusEvent; - createEvent(eventInterface:"GamepadEvent"): GamepadEvent; - createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; - createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; - createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; - createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; - createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; - createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; - createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; - createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; - createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; - createEvent(eventInterface:"MessageEvent"): MessageEvent; - createEvent(eventInterface:"MouseEvent"): MouseEvent; - createEvent(eventInterface:"MouseEvents"): MouseEvent; - createEvent(eventInterface:"MutationEvent"): MutationEvent; - createEvent(eventInterface:"MutationEvents"): MutationEvent; - createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; - createEvent(eventInterface:"NavigationEvent"): NavigationEvent; - createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; - createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; - createEvent(eventInterface:"OverflowEvent"): OverflowEvent; - createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; - createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; - createEvent(eventInterface:"PointerEvent"): PointerEvent; - createEvent(eventInterface:"PopStateEvent"): PopStateEvent; - createEvent(eventInterface:"ProgressEvent"): ProgressEvent; - createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; - createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; - createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; - createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; - createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; - createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; - createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; - createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; - createEvent(eventInterface:"StorageEvent"): StorageEvent; - createEvent(eventInterface:"TextEvent"): TextEvent; - createEvent(eventInterface:"TouchEvent"): TouchEvent; - createEvent(eventInterface:"TrackEvent"): TrackEvent; - createEvent(eventInterface:"TransitionEvent"): TransitionEvent; - createEvent(eventInterface:"UIEvent"): UIEvent; - createEvent(eventInterface:"UIEvents"): UIEvent; - createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; - createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; - createEvent(eventInterface:"WheelEvent"): WheelEvent; - createEvent(eventInterface: string): Event; -} - -interface ElementTraversal { - readonly childElementCount: number; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly nextElementSibling: Element; - readonly previousElementSibling: Element; -} - -interface GetSVGDocument { - getSVGDocument(): Document; -} - -interface GlobalEventHandlers { - onpointercancel: (this: this, ev: PointerEvent) => any; - onpointerdown: (this: this, ev: PointerEvent) => any; - onpointerenter: (this: this, ev: PointerEvent) => any; - onpointerleave: (this: this, ev: PointerEvent) => any; - onpointermove: (this: this, ev: PointerEvent) => any; - onpointerout: (this: this, ev: PointerEvent) => any; - onpointerover: (this: this, ev: PointerEvent) => any; - onpointerup: (this: this, ev: PointerEvent) => any; - onwheel: (this: this, ev: WheelEvent) => any; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface HTMLTableAlignment { - /** - * Sets or retrieves a value that you can use to implement your own ch functionality for the object. - */ - ch: string; - /** - * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. - */ - chOff: string; - /** - * Sets or retrieves how text and other content are vertically aligned within the object that contains them. - */ - vAlign: string; -} - -interface IDBEnvironment { - readonly indexedDB: IDBFactory; -} - -interface LinkStyle { - readonly sheet: StyleSheet; -} - -interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly result: any; - abort(): void; - readonly DONE: number; - readonly EMPTY: number; - readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface MSFileSaver { - msSaveBlob(blob: any, defaultName?: string): boolean; - msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; -} - -interface MSNavigatorDoNotTrack { - confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; - confirmWebWideTrackingException(args: ExceptionInformation): boolean; - removeSiteSpecificTrackingException(args: ExceptionInformation): void; - removeWebWideTrackingException(args: ExceptionInformation): void; - storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; - storeWebWideTrackingException(args: StoreExceptionsInformation): void; -} - -interface NavigatorContentUtils { -} - -interface NavigatorGeolocation { - readonly geolocation: Geolocation; -} - -interface NavigatorID { - readonly appName: string; - readonly appVersion: string; - readonly platform: string; - readonly product: string; - readonly productSub: string; - readonly userAgent: string; - readonly vendor: string; - readonly vendorSub: string; -} - -interface NavigatorOnLine { - readonly onLine: boolean; -} - -interface NavigatorStorageUtils { -} - -interface NavigatorUserMedia { - readonly mediaDevices: MediaDevices; - getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; -} - -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; -} - -interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; -} - -interface SVGAnimatedPathData { - readonly pathSegList: SVGPathSegList; -} - -interface SVGAnimatedPoints { - readonly animatedPoints: SVGPointList; - readonly points: SVGPointList; -} - -interface SVGExternalResourcesRequired { - readonly externalResourcesRequired: SVGAnimatedBoolean; -} - -interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { - readonly height: SVGAnimatedLength; - readonly result: SVGAnimatedString; - readonly width: SVGAnimatedLength; - readonly x: SVGAnimatedLength; - readonly y: SVGAnimatedLength; -} - -interface SVGFitToViewBox { - readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - readonly viewBox: SVGAnimatedRect; -} - -interface SVGLangSpace { - xmllang: string; - xmlspace: string; -} - -interface SVGLocatable { - readonly farthestViewportElement: SVGElement; - readonly nearestViewportElement: SVGElement; - getBBox(): SVGRect; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; - getTransformToElement(element: SVGElement): SVGMatrix; -} - -interface SVGStylable { - className: any; - readonly style: CSSStyleDeclaration; -} - -interface SVGTests { - readonly requiredExtensions: SVGStringList; - readonly requiredFeatures: SVGStringList; - readonly systemLanguage: SVGStringList; - hasExtension(extension: string): boolean; -} - -interface SVGTransformable extends SVGLocatable { - readonly transform: SVGAnimatedTransformList; -} - -interface SVGURIReference { - readonly href: SVGAnimatedString; -} - -interface WindowBase64 { - atob(encodedString: string): string; - btoa(rawString: string): string; -} - -interface WindowConsole { - readonly console: Console; -} - -interface WindowLocalStorage { - readonly localStorage: Storage; -} - -interface WindowSessionStorage { - readonly sessionStorage: Storage; -} - -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(handler: (...args: any[]) => void): number; - setImmediate(handler: any, ...args: any[]): number; -} - -interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface StorageEventInit extends EventInit { - key?: string; - oldValue?: string; - newValue?: string; - url: string; - 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; - [index: number]: TNode; -} - -interface HTMLCollectionOf extends HTMLCollection { - item(index: number): T; - namedItem(name: string): T; - [index: number]: T; -} - -interface BlobPropertyBag { - type?: string; - endings?: string; -} - -interface FilePropertyBag { - type?: string; - lastModified?: number; -} - -interface EventListenerObject { - handleEvent(evt: Event): void; -} - -interface MessageEventInit extends EventInit { - data?: any; - origin?: string; - lastEventId?: string; - channel?: string; - source?: any; - ports?: MessagePort[]; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -interface ScrollOptions { - behavior?: ScrollBehavior; -} - -interface ScrollToOptions extends ScrollOptions { - left?: number; - top?: number; -} - -interface ScrollIntoViewOptions extends ScrollOptions { - block?: ScrollLogicalPosition; - inline?: ScrollLogicalPosition; -} - -interface ClipboardEventInit extends EventInit { - data?: string; - dataType?: string; -} - -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 { - namedCurve: 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; -} - -interface ParentNode { - readonly children: HTMLCollection; - readonly firstElementChild: Element; - readonly lastElementChild: Element; - readonly childElementCount: number; -} - -declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; - -interface ErrorEventHandler { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; -} -interface PositionCallback { - (position: Position): void; -} -interface PositionErrorCallback { - (error: PositionError): void; -} -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface FrameRequestCallback { - (time: number): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface MutationCallback { - (mutations: MutationRecord[], observer: MutationObserver): void; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -interface NavigatorUserMediaSuccessCallback { - (stream: MediaStream): void; -} -interface NavigatorUserMediaErrorCallback { - (error: MediaStreamError): void; -} -interface ForEachCallback { - (keyId: any, status: string): void; -} -declare var Audio: {new(src?: string): HTMLAudioElement; }; -declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; -declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; -declare var applicationCache: ApplicationCache; -declare var clientInformation: Navigator; -declare var closed: boolean; -declare var crypto: Crypto; -declare var defaultStatus: string; -declare var devicePixelRatio: number; -declare var doNotTrack: string; -declare var document: Document; -declare var event: Event; -declare var external: External; -declare var frameElement: Element; -declare var frames: Window; -declare var history: History; -declare var innerHeight: number; -declare var innerWidth: number; -declare var length: number; -declare var location: Location; -declare var locationbar: BarProp; -declare var menubar: BarProp; -declare var msCredentials: MSCredentials; -declare const name: never; -declare var navigator: Navigator; -declare var offscreenBuffering: string | boolean; -declare var onabort: (this: Window, ev: UIEvent) => any; -declare var onafterprint: (this: Window, ev: Event) => any; -declare var onbeforeprint: (this: Window, ev: Event) => any; -declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; -declare var onblur: (this: Window, ev: FocusEvent) => any; -declare var oncanplay: (this: Window, ev: Event) => any; -declare var oncanplaythrough: (this: Window, ev: Event) => any; -declare var onchange: (this: Window, ev: Event) => any; -declare var onclick: (this: Window, ev: MouseEvent) => any; -declare var oncompassneedscalibration: (this: Window, ev: Event) => any; -declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; -declare var ondblclick: (this: Window, ev: MouseEvent) => any; -declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; -declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; -declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; -declare var ondrag: (this: Window, ev: DragEvent) => any; -declare var ondragend: (this: Window, ev: DragEvent) => any; -declare var ondragenter: (this: Window, ev: DragEvent) => any; -declare var ondragleave: (this: Window, ev: DragEvent) => any; -declare var ondragover: (this: Window, ev: DragEvent) => any; -declare var ondragstart: (this: Window, ev: DragEvent) => any; -declare var ondrop: (this: Window, ev: DragEvent) => any; -declare var ondurationchange: (this: Window, ev: Event) => any; -declare var onemptied: (this: Window, ev: Event) => any; -declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; -declare var onerror: ErrorEventHandler; -declare var onfocus: (this: Window, ev: FocusEvent) => any; -declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; -declare var oninput: (this: Window, ev: Event) => any; -declare var oninvalid: (this: Window, ev: Event) => any; -declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; -declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; -declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; -declare var onload: (this: Window, ev: Event) => any; -declare var onloadeddata: (this: Window, ev: Event) => any; -declare var onloadedmetadata: (this: Window, ev: Event) => any; -declare var onloadstart: (this: Window, ev: Event) => any; -declare var onmessage: (this: Window, ev: MessageEvent) => any; -declare var onmousedown: (this: Window, ev: MouseEvent) => any; -declare var onmouseenter: (this: Window, ev: MouseEvent) => any; -declare var onmouseleave: (this: Window, ev: MouseEvent) => any; -declare var onmousemove: (this: Window, ev: MouseEvent) => any; -declare var onmouseout: (this: Window, ev: MouseEvent) => any; -declare var onmouseover: (this: Window, ev: MouseEvent) => any; -declare var onmouseup: (this: Window, ev: MouseEvent) => any; -declare var onmousewheel: (this: Window, ev: WheelEvent) => any; -declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; -declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; -declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; -declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; -declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; -declare var onoffline: (this: Window, ev: Event) => any; -declare var ononline: (this: Window, ev: Event) => any; -declare var onorientationchange: (this: Window, ev: Event) => any; -declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; -declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; -declare var onpause: (this: Window, ev: Event) => any; -declare var onplay: (this: Window, ev: Event) => any; -declare var onplaying: (this: Window, ev: Event) => any; -declare var onpopstate: (this: Window, ev: PopStateEvent) => any; -declare var onprogress: (this: Window, ev: ProgressEvent) => any; -declare var onratechange: (this: Window, ev: Event) => any; -declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; -declare var onreset: (this: Window, ev: Event) => any; -declare var onresize: (this: Window, ev: UIEvent) => any; -declare var onscroll: (this: Window, ev: UIEvent) => any; -declare var onseeked: (this: Window, ev: Event) => any; -declare var onseeking: (this: Window, ev: Event) => any; -declare var onselect: (this: Window, ev: UIEvent) => any; -declare var onstalled: (this: Window, ev: Event) => any; -declare var onstorage: (this: Window, ev: StorageEvent) => any; -declare var onsubmit: (this: Window, ev: Event) => any; -declare var onsuspend: (this: Window, ev: Event) => any; -declare var ontimeupdate: (this: Window, ev: Event) => any; -declare var ontouchcancel: (ev: TouchEvent) => any; -declare var ontouchend: (ev: TouchEvent) => any; -declare var ontouchmove: (ev: TouchEvent) => any; -declare var ontouchstart: (ev: TouchEvent) => any; -declare var onunload: (this: Window, ev: Event) => any; -declare var onvolumechange: (this: Window, ev: Event) => any; -declare var onwaiting: (this: Window, ev: Event) => any; -declare var opener: any; -declare var orientation: string | number; -declare var outerHeight: number; -declare var outerWidth: number; -declare var pageXOffset: number; -declare var pageYOffset: number; -declare var parent: Window; -declare var performance: Performance; -declare var personalbar: BarProp; -declare var screen: Screen; -declare var screenLeft: number; -declare var screenTop: number; -declare var screenX: number; -declare var screenY: number; -declare var scrollX: number; -declare var scrollY: number; -declare var scrollbars: BarProp; -declare var self: Window; -declare var status: string; -declare var statusbar: BarProp; -declare var styleMedia: StyleMedia; -declare var toolbar: BarProp; -declare var top: Window; -declare var window: Window; -declare function alert(message?: any): void; -declare function blur(): void; -declare function cancelAnimationFrame(handle: number): void; -declare function captureEvents(): void; -declare function close(): void; -declare function confirm(message?: string): boolean; -declare function focus(): void; -declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; -declare function getSelection(): Selection; -declare function matchMedia(mediaQuery: string): MediaQueryList; -declare function moveBy(x?: number, y?: number): void; -declare function moveTo(x?: number, y?: number): void; -declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; -declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; -declare function print(): void; -declare function prompt(message?: string, _default?: string): string | null; -declare function releaseEvents(): void; -declare function requestAnimationFrame(callback: FrameRequestCallback): number; -declare function resizeBy(x?: number, y?: number): void; -declare function resizeTo(x?: number, y?: number): void; -declare function scroll(x?: number, y?: number): void; -declare function scrollBy(x?: number, y?: number): void; -declare function scrollTo(x?: number, y?: number): void; -declare function webkitCancelAnimationFrame(handle: number): void; -declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; -declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; -declare function scroll(options?: ScrollToOptions): void; -declare function scrollTo(options?: ScrollToOptions): void; -declare function scrollBy(options?: ScrollToOptions): void; -declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -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(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; -declare var onpointercancel: (this: Window, ev: PointerEvent) => any; -declare var onpointerdown: (this: Window, ev: PointerEvent) => any; -declare var onpointerenter: (this: Window, ev: PointerEvent) => any; -declare var onpointerleave: (this: Window, ev: PointerEvent) => any; -declare var onpointermove: (this: Window, ev: PointerEvent) => any; -declare var onpointerout: (this: Window, ev: PointerEvent) => any; -declare var onpointerover: (this: Window, ev: PointerEvent) => any; -declare var onpointerup: (this: Window, ev: PointerEvent) => any; -declare var onwheel: (this: Window, ev: WheelEvent) => any; -declare var indexedDB: IDBFactory; -declare function atob(encodedString: string): string; -declare function btoa(rawString: string): string; -declare function addEventListener(type: "MSGestureChange", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureDoubleTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureEnd", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureHold", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSInertiaStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerCancel", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerDown", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerEnter", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerLeave", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerMove", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOut", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOver", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerUp", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "abort", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "afterprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeunload", listener: (this: Window, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "blur", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplay", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplaythrough", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "change", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "click", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "compassneedscalibration", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "contextmenu", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dblclick", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicelight", listener: (this: Window, ev: DeviceLightEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicemotion", listener: (this: Window, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "deviceorientation", listener: (this: Window, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drag", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragend", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragenter", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragleave", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragover", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragstart", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drop", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "durationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "emptied", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ended", listener: (this: Window, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "focus", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "hashchange", listener: (this: Window, ev: HashChangeEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "input", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "invalid", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keydown", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keypress", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keyup", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "load", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadeddata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadedmetadata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadstart", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: Window, ev: MessageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousedown", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseenter", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseleave", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseout", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseover", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseup", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousewheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "offline", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "online", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "orientationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pagehide", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pageshow", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pause", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "play", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "playing", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointercancel", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerdown", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerenter", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerleave", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointermove", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerout", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerover", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerup", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "popstate", listener: (this: Window, ev: PopStateEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "progress", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ratechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "readystatechange", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "reset", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "resize", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "scroll", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeked", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeking", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "select", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "stalled", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "storage", listener: (this: Window, ev: StorageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "submit", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "suspend", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "timeupdate", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "unload", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "volumechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "waiting", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "wheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -type AAGUID = string; -type AlgorithmIdentifier = string | Algorithm; -type ConstrainBoolean = boolean | ConstrainBooleanParameters; -type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; -type ConstrainDouble = number | ConstrainDoubleRange; -type ConstrainLong = number | ConstrainLongRange; -type CryptoOperationData = ArrayBufferView; -type GLbitfield = number; -type GLboolean = boolean; -type GLbyte = number; -type GLclampf = number; -type GLenum = number; -type GLfloat = number; -type GLint = number; -type GLintptr = number; -type GLshort = number; -type GLsizei = number; -type GLsizeiptr = number; -type GLubyte = number; -type GLuint = number; -type GLushort = number; -type IDBKeyPath = string; -type KeyFormat = string; -type KeyType = string; -type KeyUsage = string; -type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; -type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; -type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; -type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; -type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; -type payloadtype = number; -type ScrollBehavior = "auto" | "instant" | "smooth"; -type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; -type IDBValidKey = number | string | Date | IDBArrayKey; -type BufferSource = ArrayBuffer | ArrayBufferView; -type MouseWheelEvent = WheelEvent; -///////////////////////////// -/// WorkerGlobalScope APIs -///////////////////////////// -// These are only available in a Web Worker -declare function importScripts(...urls: string[]): void; - - -///////////////////////////// -/// Windows Script Host APIS -///////////////////////////// - - -interface ActiveXObject { - new (s: string): any; -} -declare var ActiveXObject: ActiveXObject; - -interface ITextWriter { - Write(s: string): void; - WriteLine(s: string): void; - Close(): void; -} - -interface TextStreamBase { - /** - * The column number of the current character position in an input stream. - */ - Column: number; - - /** - * The current line number in an input stream. - */ - Line: number; - - /** - * Closes a text stream. - * It is not necessary to close standard streams; they close automatically when the process ends. If - * you close a standard stream, be aware that any other pointers to that standard stream become invalid. - */ - Close(): void; -} - -interface TextStreamWriter extends TextStreamBase { - /** - * Sends a string to an output stream. - */ - Write(s: string): void; - - /** - * Sends a specified number of blank lines (newline characters) to an output stream. - */ - WriteBlankLines(intLines: number): void; - - /** - * Sends a string followed by a newline character to an output stream. - */ - WriteLine(s: string): void; -} - -interface TextStreamReader extends TextStreamBase { - /** - * Returns a specified number of characters from an input stream, starting at the current pointer position. - * Does not return until the ENTER key is pressed. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - Read(characters: number): string; - - /** - * Returns all characters from an input stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadAll(): string; - - /** - * Returns an entire line from an input stream. - * Although this method extracts the newline character, it does not add it to the returned string. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadLine(): string; - - /** - * Skips a specified number of characters when reading from an input text stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) - */ - Skip(characters: number): void; - - /** - * Skips the next line when reading from an input text stream. - * Can only be used on a stream in reading mode, not writing or appending mode. - */ - SkipLine(): void; - - /** - * Indicates whether the stream pointer position is at the end of a line. - */ - AtEndOfLine: boolean; - - /** - * Indicates whether the stream pointer position is at the end of a stream. - */ - AtEndOfStream: boolean; -} - -declare var WScript: { - /** - * Outputs text to either a message box (under WScript.exe) or the command console window followed by - * a newline (under CScript.exe). - */ - Echo(s: any): void; - - /** - * Exposes the write-only error output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdErr: TextStreamWriter; - - /** - * Exposes the write-only output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdOut: TextStreamWriter; - Arguments: { length: number; Item(n: number): string; }; - - /** - * The full path of the currently running script. - */ - ScriptFullName: string; - - /** - * Forces the script to stop immediately, with an optional exit code. - */ - Quit(exitCode?: number): number; - - /** - * The Windows Script Host build version number. - */ - BuildVersion: number; - - /** - * Fully qualified path of the host executable. - */ - FullName: string; - - /** - * Gets/sets the script mode - interactive(true) or batch(false). - */ - Interactive: boolean; - - /** - * The name of the host executable (WScript.exe or CScript.exe). - */ - Name: string; - - /** - * Path of the directory containing the host executable. - */ - Path: string; - - /** - * The filename of the currently running script. - */ - ScriptName: string; - - /** - * Exposes the read-only input stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdIn: TextStreamReader; - - /** - * Windows Script Host version - */ - Version: string; - - /** - * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. - */ - ConnectObject(objEventSource: any, strPrefix: string): void; - - /** - * Creates a COM object. - * @param strProgiID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - CreateObject(strProgID: string, strPrefix?: string): any; - - /** - * Disconnects a COM object from its event sources. - */ - DisconnectObject(obj: any): void; - - /** - * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. - * @param strPathname Fully qualified path to the file containing the object persisted to disk. - * For objects in memory, pass a zero-length string. - * @param strProgID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; - - /** - * Suspends script execution for a specified length of time, then continues execution. - * @param intTime Interval (in milliseconds) to suspend script execution. - */ - Sleep(intTime: number): void; -}; - -/** - * Allows enumerating over a COM collection, which may not have indexed item access. - */ -interface Enumerator { - /** - * Returns true if the current item is the last one in the collection, or the collection is empty, - * or the current item is undefined. - */ - atEnd(): boolean; - - /** - * Returns the current item in the collection - */ - item(): T; - - /** - * Resets the current item in the collection to the first item. If there are no items in the collection, - * the current item is set to undefined. - */ - moveFirst(): void; - - /** - * Moves the current item to the next item in the collection. If the enumerator is at the end of - * the collection or the collection is empty, the current item is set to undefined. - */ - moveNext(): void; -} - -interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; -} - -declare var Enumerator: EnumeratorConstructor; - -/** - * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. - */ -interface VBArray { - /** - * Returns the number of dimensions (1-based). - */ - dimensions(): number; - - /** - * Takes an index for each dimension in the array, and returns the item at the corresponding location. - */ - getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; - - /** - * Returns the smallest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - lbound(dimension?: number): number; - - /** - * Returns the largest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - ubound(dimension?: number): number; - - /** - * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, - * each successive dimension is appended to the end of the array. - * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] - */ - toArray(): T[]; -} - -interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; -} - -declare var VBArray: VBArrayConstructor; - -/** - * Automation date (VT_DATE) - */ -interface VarDate { } - -interface DateConstructor { - new (vd: VarDate): Date; -} - -interface Date { - getVarDate: () => VarDate; -} -/// - -interface DOMTokenList { - [Symbol.iterator](): IterableIterator; -} - -interface NodeList { - [Symbol.iterator](): IterableIterator -} - -interface NodeListOf { - [Symbol.iterator](): IterableIterator -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has null prototype. + * @param o Object to use as a prototype. May be null + */ + create(o: null): any; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + */ + create(o: T): T; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(a: T[]): ReadonlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(this: Function, thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(this: Function, thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(this: Function, thisArg: any, ...argArray: any[]): any; + + /** Returns a string representation of a function. */ + toString(): string; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): RegExpMatchArray | null; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): RegExpMatchArray | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new (value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new (value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new (value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends ReadonlyArray { + readonly raw: ReadonlyArray +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest number greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest number less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray | null; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): this; +} + +interface RegExpConstructor { + new (pattern: RegExp): RegExp; + new (pattern: string, flags?: string): RegExp; + (pattern: RegExp): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; + stack?: string; +} + +interface ErrorConstructor { + new (message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new (message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new (message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new (message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new (message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(): T | undefined; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[][]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T | undefined; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): this; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +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) => T | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, + 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. + * @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) | undefined | null): 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; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T pick a set of properties K + */ +type Pick = { + [P in K]: T[P]; +} + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8ClampedArray, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): this; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} +declare const Float64Array: Float64ArrayConstructor; + +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare module Intl { + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string | string[], options?: CollatorOptions): Collator; + (locales?: string | string[], options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12?: boolean; + timeZone?: string; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; + } +} + +interface String { + /** + * Determines whether two strings are equivalent in the current or specified locale. + * @param that String to compare to target string + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; +} + +interface Number { + /** + * Converts a number to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; +} + +interface Date { + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + /** + * Converts a date to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; +} + + +declare type PropertyKey = string | number | symbol; + +interface Array { + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): this; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface DateConstructor { + new (value: Date): Date; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface ReadonlyArray { + /** + * Returns the value 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, find + * immediately returns that element value. Otherwise, find returns undefined. + * @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. + */ + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * 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. + */ + findIndex(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): number; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + new (pattern: RegExp, flags?: string): RegExp; + (pattern: RegExp, flags?: string): RegExp; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number | undefined; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value?: V): this; + readonly size: number; +} + +interface MapConstructor { + new (): Map; + new (entries?: [K, V][]): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface ReadonlyMap { + forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; + get(key: K): V|undefined; + has(key: K): boolean; + readonly size: number; +} + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value?: V): this; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (entries?: [K, V][]): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): this; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface SetConstructor { + new (): Set; + new (values?: T[]): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface ReadonlySet { + forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + has(value: T): boolean; + readonly size: number; +} + +interface WeakSet { + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (values?: T[]): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + + +interface GeneratorFunction extends Function { } + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + (...args: string[]): GeneratorFunction; + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + + +/// + +interface SymbolConstructor { + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; +} + +interface IteratorResult { + done: boolean; + value: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; +} + +interface ReadonlyArray { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Map { + [Symbol.iterator](): IterableIterator<[K,V]>; + entries(): IterableIterator<[K, V]>; + keys(): IterableIterator; + values(): IterableIterator; +} + +interface MapConstructor { + new (iterable: Iterable<[K, V]>): Map; +} + +interface WeakMap { } + +interface WeakMapConstructor { + new (iterable: Iterable<[K, V]>): WeakMap; +} + +interface Set { + [Symbol.iterator](): IterableIterator; + entries(): IterableIterator<[T, T]>; + keys(): IterableIterator; + values(): IterableIterator; +} + +interface SetConstructor { + new (iterable: Iterable): Set; +} + +interface WeakSet { } + +interface WeakSetConstructor { + new (iterable: Iterable): WeakSet; +} + +interface Promise { } + +interface PromiseConstructor { + /** + * 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: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; +} + +declare namespace Reflect { + function enumerate(target: any): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + [Symbol.iterator](): IterableIterator; + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} + +/** + * Represents the completion of an asynchronous operation + */ +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) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): 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) => T | PromiseLike) | undefined | null, 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. + * @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) | undefined | null): 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 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) | undefined | null): 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) => TResult | PromiseLike): Promise; +} + +interface PromiseConstructor { + /** + * 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, + * 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 + * 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 Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(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; + + /** + * 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; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface ProxyHandler { + getPrototypeOf? (target: T): {} | null; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): {}; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T +} +declare var Proxy: ProxyConstructor; + + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string | undefined; +} + +declare var Symbol: SymbolConstructor; + +/// + +interface SymbolConstructor { + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} + +interface Symbol { + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface Array { + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface Map { + readonly [Symbol.toStringTag]: "Map"; +} + +interface WeakMap{ + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface Set { + readonly [Symbol.toStringTag]: "Set"; +} + +interface WeakSet { + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +interface Function { + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface GeneratorFunction extends Function { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface Math { + readonly [Symbol.toStringTag]: "Math"; +} + +interface Promise { + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + readonly [Symbol.species]: Function; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray | null; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface String { + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + readonly [Symbol.toStringTag]: "Int8Array"; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + readonly [Symbol.toStringTag]: "Int16Array"; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + readonly [Symbol.toStringTag]: "Int32Array"; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + readonly [Symbol.toStringTag]: "Float32Array"; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + readonly [Symbol.toStringTag]: "Float64Array"; +} + + +///////////////////////////// +/// IE DOM APIs +///////////////////////////// + +interface Algorithm { + name: string; +} + +interface AriaRequestEventInit extends EventInit { + attributeName?: string; + attributeValue?: string; +} + +interface CommandEventInit extends EventInit { + commandName?: string; + detail?: string; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainLongRange extends LongRange { + exact?: number; + ideal?: number; +} + +interface ConstrainVideoFacingModeParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface CustomEventInit extends EventInit { + detail?: any; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface EventInit { + scoped?: boolean; + bubbles?: boolean; + cancelable?: boolean; +} + +interface EventModifierInit extends UIEventInit { + ctrlKey?: boolean; + shiftKey?: boolean; + altKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierOS?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; +} + +interface ExceptionInformation { + domain?: string; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: IDBKeyPath; +} + +interface KeyAlgorithm { + name?: string; +} + +interface KeyboardEventInit extends EventModifierInit { + code?: string; + key?: string; + location?: number; + repeat?: boolean; +} + +interface LongRange { + max?: number; + min?: number; +} + +interface MSAccountInfo { + rpDisplayName?: string; + userDisplayName?: string; + accountName?: string; + userId?: string; + accountImageUri?: string; +} + +interface MSAudioLocalClientEvent extends MSLocalClientEventBase { + networkSendQualityEventRatio?: number; + networkDelayEventRatio?: number; + cpuInsufficientEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceCaptureNotFunctioningEventRatio?: number; + deviceGlitchesEventRatio?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceClippingEventRatio?: number; + deviceEchoEventRatio?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceHowlingEventCount?: number; +} + +interface MSAudioRecvPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioRecvSignal; + packetReorderRatio?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + burstLossLength1?: number; + burstLossLength2?: number; + burstLossLength3?: number; + burstLossLength4?: number; + burstLossLength5?: number; + burstLossLength6?: number; + burstLossLength7?: number; + burstLossLength8OrHigher?: number; + fecRecvDistance1?: number; + fecRecvDistance2?: number; + fecRecvDistance3?: number; + ratioConcealedSamplesAvg?: number; + ratioStretchedSamplesAvg?: number; + ratioCompressedSamplesAvg?: number; +} + +interface MSAudioRecvSignal { + initialSignalLevelRMS?: number; + recvSignalLevelCh1?: number; + recvNoiseLevelCh1?: number; + renderSignalLevel?: number; + renderNoiseLevel?: number; + renderLoopbackSignalLevel?: number; +} + +interface MSAudioSendPayload extends MSPayloadBase { + samplingRate?: number; + signal?: MSAudioSendSignal; + audioFECUsed?: boolean; + sendMutePercent?: number; +} + +interface MSAudioSendSignal { + noiseLevel?: number; + sendSignalLevelCh1?: number; + sendNoiseLevelCh1?: number; +} + +interface MSConnectivity { + iceType?: string; + iceWarningFlags?: MSIceWarningFlags; + relayAddress?: MSRelayAddress; +} + +interface MSCredentialFilter { + accept?: MSCredentialSpec[]; +} + +interface MSCredentialParameters { + type?: string; +} + +interface MSCredentialSpec { + type?: string; + id?: string; +} + +interface MSDelay { + roundTrip?: number; + roundTripMax?: number; +} + +interface MSDescription extends RTCStats { + connectivity?: MSConnectivity; + transport?: string; + networkconnectivity?: MSNetworkConnectivityInfo; + localAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + deviceDevName?: string; + reflexiveLocalIPAddr?: MSIPAddressInfo; +} + +interface MSFIDOCredentialParameters extends MSCredentialParameters { + algorithm?: string | Algorithm; + authenticators?: AAGUID[]; +} + +interface MSIPAddressInfo { + ipAddr?: string; + port?: number; + manufacturerMacAddrMask?: string; +} + +interface MSIceWarningFlags { + turnTcpTimedOut?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; + turnTcpAllocateFailed?: boolean; + turnTcpSendFailed?: boolean; + udpLocalConnectivityFailed?: boolean; + udpNatConnectivityFailed?: boolean; + udpRelayConnectivityFailed?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + connCheckMessageIntegrityFailed?: boolean; + allocationMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + turnAuthUnknownUsernameError?: boolean; + noRelayServersConfigured?: boolean; + multipleRelayServersAttempted?: boolean; + portRangeExhausted?: boolean; + alternateServerReceived?: boolean; + pseudoTLSFailure?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + useCandidateChecksFailed?: boolean; + fipsAllocationFailure?: boolean; +} + +interface MSJitter { + interArrival?: number; + interArrivalMax?: number; + interArrivalSD?: number; +} + +interface MSLocalClientEventBase extends RTCStats { + networkReceiveQualityEventRatio?: number; + networkBandwidthLowEventRatio?: number; +} + +interface MSNetwork extends RTCStats { + jitter?: MSJitter; + delay?: MSDelay; + packetLoss?: MSPacketLoss; + utilization?: MSUtilization; +} + +interface MSNetworkConnectivityInfo { + vpn?: boolean; + linkspeed?: number; + networkConnectionDetails?: string; +} + +interface MSNetworkInterfaceType { + interfaceTypeEthernet?: boolean; + interfaceTypeWireless?: boolean; + interfaceTypePPP?: boolean; + interfaceTypeTunnel?: boolean; + interfaceTypeWWAN?: boolean; +} + +interface MSOutboundNetwork extends MSNetwork { + appliedBandwidthLimit?: number; +} + +interface MSPacketLoss { + lossRate?: number; + lossRateMax?: number; +} + +interface MSPayloadBase extends RTCStats { + payloadDescription?: string; +} + +interface MSRelayAddress { + relayAddress?: string; + port?: number; +} + +interface MSSignatureParameters { + userPrompt?: string; +} + +interface MSTransportDiagnosticsStats extends RTCStats { + baseAddress?: string; + localAddress?: string; + localSite?: string; + networkName?: string; + remoteAddress?: string; + remoteSite?: string; + localMR?: string; + remoteMR?: string; + iceWarningFlags?: MSIceWarningFlags; + portRangeMin?: number; + portRangeMax?: number; + localMRTCPPort?: number; + remoteMRTCPPort?: number; + stunVer?: number; + numConsentReqSent?: number; + numConsentReqReceived?: number; + numConsentRespSent?: number; + numConsentRespReceived?: number; + interfaces?: MSNetworkInterfaceType; + baseInterface?: MSNetworkInterfaceType; + protocol?: string; + localInterface?: MSNetworkInterfaceType; + localAddrType?: string; + remoteAddrType?: string; + iceRole?: string; + rtpRtcpMux?: boolean; + allocationTimeInMs?: number; + msRtcEngineVersion?: string; +} + +interface MSUtilization { + packets?: number; + bandwidthEstimation?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationStdDev?: number; + bandwidthEstimationAvg?: number; +} + +interface MSVideoPayload extends MSPayloadBase { + resoluton?: string; + videoBitRateAvg?: number; + videoBitRateMax?: number; + videoFrameRateAvg?: number; + videoPacketLossRate?: number; + durationSeconds?: number; +} + +interface MSVideoRecvPayload extends MSVideoPayload { + videoFrameLossRate?: number; + recvCodecType?: string; + recvResolutionWidth?: number; + recvResolutionHeight?: number; + videoResolutions?: MSVideoResolutionDistribution; + recvFrameRateAverage?: number; + recvBitRateMaximum?: number; + recvBitRateAverage?: number; + recvVideoStreamsMax?: number; + recvVideoStreamsMin?: number; + recvVideoStreamsMode?: number; + videoPostFECPLR?: number; + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; + reorderBufferTotalPackets?: number; + recvReorderBufferReorderedPackets?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvFpsHarmonicAverage?: number; + recvNumResSwitches?: number; +} + +interface MSVideoResolutionDistribution { + cifQuality?: number; + vgaQuality?: number; + h720Quality?: number; + h1080Quality?: number; + h1440Quality?: number; + h2160Quality?: number; +} + +interface MSVideoSendPayload extends MSVideoPayload { + sendFrameRateAverage?: number; + sendBitRateMaximum?: number; + sendBitRateAverage?: number; + sendVideoStreamsMax?: number; + sendResolutionWidth?: number; + sendResolutionHeight?: number; +} + +interface MediaEncryptedEventInit extends EventInit { + initDataType?: string; + initData?: ArrayBuffer; +} + +interface MediaKeyMessageEventInit extends EventInit { + messageType?: string; + message?: ArrayBuffer; +} + +interface MediaKeySystemConfiguration { + initDataTypes?: string[]; + audioCapabilities?: MediaKeySystemMediaCapability[]; + videoCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: string; + persistentState?: string; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + width?: number | LongRange; + height?: number | LongRange; + aspectRatio?: number | DoubleRange; + frameRate?: number | DoubleRange; + facingMode?: string; + volume?: number | DoubleRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + echoCancellation?: boolean[]; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackConstraintSet { + width?: number | ConstrainLongRange; + height?: number | ConstrainLongRange; + aspectRatio?: number | ConstrainDoubleRange; + frameRate?: number | ConstrainDoubleRange; + facingMode?: string | string[] | ConstrainDOMStringParameters; + volume?: number | ConstrainDoubleRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + echoCancelation?: boolean | ConstrainBooleanParameters; + deviceId?: string | string[] | ConstrainDOMStringParameters; + groupId?: string | string[] | ConstrainDOMStringParameters; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackSettings { + width?: number; + height?: number; + aspectRatio?: number; + frameRate?: number; + facingMode?: string; + volume?: number; + sampleRate?: number; + sampleSize?: number; + echoCancellation?: boolean; + deviceId?: string; + groupId?: string; +} + +interface MediaTrackSupportedConstraints { + width?: boolean; + height?: boolean; + aspectRatio?: boolean; + frameRate?: boolean; + facingMode?: boolean; + volume?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + echoCancellation?: boolean; + deviceId?: boolean; + groupId?: boolean; +} + +interface MouseEventInit extends EventModifierInit { + screenX?: number; + screenY?: number; + clientX?: number; + clientY?: number; + button?: number; + buttons?: number; + relatedTarget?: EventTarget; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: string[]; +} + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + pointerId?: number; + width?: number; + height?: number; + pressure?: number; + tiltX?: number; + tiltY?: number; + pointerType?: string; + isPrimary?: boolean; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCDtlsParameters { + role?: string; + fingerprints?: RTCDtlsFingerprint[]; +} + +interface RTCIceCandidate { + foundation?: string; + priority?: number; + ip?: string; + protocol?: string; + port?: number; + type?: string; + tcpType?: string; + relatedAddress?: string; + relatedPort?: number; +} + +interface RTCIceCandidateAttributes extends RTCStats { + ipAddress?: string; + portNumber?: number; + transport?: string; + candidateType?: string; + priority?: number; + addressSourceUrl?: string; +} + +interface RTCIceCandidateComplete { +} + +interface RTCIceCandidatePair { + local?: RTCIceCandidate; + remote?: RTCIceCandidate; +} + +interface RTCIceCandidatePairStats extends RTCStats { + transportId?: string; + localCandidateId?: string; + remoteCandidateId?: string; + state?: string; + priority?: number; + nominated?: boolean; + writable?: boolean; + readable?: boolean; + bytesSent?: number; + bytesReceived?: number; + roundTripTime?: number; + availableOutgoingBitrate?: number; + availableIncomingBitrate?: number; +} + +interface RTCIceGatherOptions { + gatherPolicy?: string; + iceservers?: RTCIceServer[]; +} + +interface RTCIceParameters { + usernameFragment?: string; + password?: string; +} + +interface RTCIceServer { + urls?: any; + username?: string; + credential?: string; +} + +interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { + packetsReceived?: number; + bytesReceived?: number; + packetsLost?: number; + jitter?: number; + fractionLost?: number; +} + +interface RTCMediaStreamTrackStats extends RTCStats { + trackIdentifier?: string; + remoteSource?: boolean; + ssrcIds?: string[]; + frameWidth?: number; + frameHeight?: number; + framesPerSecond?: number; + framesSent?: number; + framesReceived?: number; + framesDecoded?: number; + framesDropped?: number; + framesCorrupted?: number; + audioLevel?: number; + echoReturnLoss?: number; + echoReturnLossEnhancement?: number; +} + +interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { + packetsSent?: number; + bytesSent?: number; + targetBitrate?: number; + roundTripTime?: number; +} + +interface RTCRTPStreamStats extends RTCStats { + ssrc?: string; + associateStatsId?: string; + isRemote?: boolean; + mediaTrackId?: string; + transportId?: string; + codecId?: string; + firCount?: number; + pliCount?: number; + nackCount?: number; + sliCount?: number; +} + +interface RTCRtcpFeedback { + type?: string; + parameter?: string; +} + +interface RTCRtcpParameters { + ssrc?: number; + cname?: string; + reducedSize?: boolean; + mux?: boolean; +} + +interface RTCRtpCapabilities { + codecs?: RTCRtpCodecCapability[]; + headerExtensions?: RTCRtpHeaderExtension[]; + fecMechanisms?: string[]; +} + +interface RTCRtpCodecCapability { + name?: string; + kind?: string; + clockRate?: number; + preferredPayloadType?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; + options?: any; + maxTemporalLayers?: number; + maxSpatialLayers?: number; + svcMultiStreamSupport?: boolean; +} + +interface RTCRtpCodecParameters { + name?: string; + payloadType?: any; + clockRate?: number; + maxptime?: number; + numChannels?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + parameters?: any; +} + +interface RTCRtpContributingSource { + timestamp?: number; + csrc?: number; + audioLevel?: number; +} + +interface RTCRtpEncodingParameters { + ssrc?: number; + codecPayloadType?: number; + fec?: RTCRtpFecParameters; + rtx?: RTCRtpRtxParameters; + priority?: number; + maxBitrate?: number; + minQuality?: number; + framerateBias?: number; + resolutionScale?: number; + framerateScale?: number; + active?: boolean; + encodingId?: string; + dependencyEncodingIds?: string[]; + ssrcRange?: RTCSsrcRange; +} + +interface RTCRtpFecParameters { + ssrc?: number; + mechanism?: string; +} + +interface RTCRtpHeaderExtension { + kind?: string; + uri?: string; + preferredId?: number; + preferredEncrypt?: boolean; +} + +interface RTCRtpHeaderExtensionParameters { + uri?: string; + id?: number; + encrypt?: boolean; +} + +interface RTCRtpParameters { + muxId?: string; + codecs?: RTCRtpCodecParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + encodings?: RTCRtpEncodingParameters[]; + rtcp?: RTCRtcpParameters; +} + +interface RTCRtpRtxParameters { + ssrc?: number; +} + +interface RTCRtpUnhandled { + ssrc?: number; + payloadType?: number; + muxId?: string; +} + +interface RTCSrtpKeyParam { + keyMethod?: string; + keySalt?: string; + lifetime?: string; + mkiValue?: number; + mkiLength?: number; +} + +interface RTCSrtpSdesParameters { + tag?: number; + cryptoSuite?: string; + keyParams?: RTCSrtpKeyParam[]; + sessionParams?: string[]; +} + +interface RTCSsrcRange { + min?: number; + max?: number; +} + +interface RTCStats { + timestamp?: number; + type?: string; + id?: string; + msType?: string; +} + +interface RTCStatsReport { +} + +interface RTCTransportStats extends RTCStats { + bytesSent?: number; + bytesReceived?: number; + rtcpTransportStatsId?: string; + activeConnection?: boolean; + selectedCandidatePairId?: string; + localCertificateId?: string; + remoteCertificateId?: string; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface UIEventInit extends EventInit { + view?: Window; + detail?: number; +} + +interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; + alpha?: boolean; + depth?: boolean; + stencil?: boolean; + antialias?: boolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaX?: number; + deltaY?: number; + deltaZ?: number; + deltaMode?: number; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + readonly frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(): AnalyserNode; +} + +interface AnimationEvent extends Event { + readonly animationName: string; + readonly elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": ErrorEvent; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + +interface ApplicationCache extends EventTarget { + oncached: (this: ApplicationCache, ev: Event) => any; + onchecking: (this: ApplicationCache, ev: Event) => any; + ondownloading: (this: ApplicationCache, ev: Event) => any; + onerror: (this: ApplicationCache, ev: ErrorEvent) => any; + onnoupdate: (this: ApplicationCache, ev: Event) => any; + onobsolete: (this: ApplicationCache, ev: Event) => any; + onprogress: (this: ApplicationCache, ev: ProgressEvent) => any; + onupdateready: (this: ApplicationCache, ev: Event) => any; + readonly status: number; + abort(): void; + swapCache(): void; + update(): void; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; +} + +interface AriaRequestEvent extends Event { + readonly attributeName: string; + attributeValue: string | null; +} + +declare var AriaRequestEvent: { + prototype: AriaRequestEvent; + new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; +} + +interface Attr extends Node { + readonly name: string; + readonly ownerElement: Element; + readonly prefix: string | null; + readonly specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +} + +interface AudioBufferSourceNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface AudioBufferSourceNode extends AudioNode { + buffer: AudioBuffer | null; + readonly detune: AudioParam; + loop: boolean; + loopEnd: number; + loopStart: number; + onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + readonly playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(): AudioBufferSourceNode; +} + +interface AudioContext extends EventTarget { + readonly currentTime: number; + readonly destination: AudioDestinationNode; + readonly listener: AudioListener; + readonly sampleRate: number; + state: string; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): PromiseLike; +} + +declare var AudioContext: { + prototype: AudioContext; + new(): AudioContext; +} + +interface AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +} + +interface AudioListener { + dopplerFactor: number; + speedOfSound: number; + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +} + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: string; + channelInterpretation: string; + readonly context: AudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + connect(destination: AudioNode, output?: number, input?: number): void; + disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +} + +interface AudioParam { + readonly defaultValue: number; + value: number; + cancelScheduledValues(startTime: number): void; + exponentialRampToValueAtTime(value: number, endTime: number): void; + linearRampToValueAtTime(value: number, endTime: number): void; + setTargetAtTime(target: number, startTime: number, timeConstant: number): void; + setValueAtTime(value: number, startTime: number): void; + setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +} + +interface AudioProcessingEvent extends Event { + readonly inputBuffer: AudioBuffer; + readonly outputBuffer: AudioBuffer; + readonly playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(): AudioProcessingEvent; +} + +interface AudioTrack { + enabled: boolean; + readonly id: string; + kind: string; + readonly label: string; + language: string; + readonly sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface AudioTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: AudioTrackList, ev: TrackEvent) => any; + onchange: (this: AudioTrackList, ev: Event) => any; + onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack | null; + item(index: number): AudioTrack; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface BarProp { + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +} + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface BiquadFilterNode extends AudioNode { + readonly Q: AudioParam; + readonly detune: AudioParam; + readonly frequency: AudioParam; + readonly gain: AudioParam; + type: string; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(): BiquadFilterNode; +} + +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface CSS { + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +} + +interface CSSFontFaceRule extends CSSRule { + readonly style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface CSSGroupingRule extends CSSRule { + readonly cssRules: CSSRuleList; + deleteRule(index: number): void; + insertRule(rule: string, index: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +} + +interface CSSImportRule extends CSSRule { + readonly href: string; + readonly media: MediaList; + readonly styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSKeyframesRule extends CSSRule { + readonly cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(rule: string): void; + findRule(rule: string): CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface CSSMediaRule extends CSSConditionRule { + readonly media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface CSSNamespaceRule extends CSSRule { + readonly namespaceURI: string; + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface CSSPageRule extends CSSRule { + readonly pseudoClass: string; + readonly selector: string; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface CSSRule { + cssText: string; + readonly parentRule: CSSRule; + readonly parentStyleSheet: CSSStyleSheet; + readonly type: number; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly KEYFRAME_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +interface CSSRuleList { + readonly length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface CSSStyleDeclaration { + alignContent: string | null; + alignItems: string | null; + alignSelf: string | null; + alignmentBaseline: string | null; + animation: string | null; + animationDelay: string | null; + animationDirection: string | null; + animationDuration: string | null; + animationFillMode: string | null; + animationIterationCount: string | null; + animationName: string | null; + animationPlayState: string | null; + animationTimingFunction: string | null; + backfaceVisibility: string | null; + background: string | null; + backgroundAttachment: string | null; + backgroundClip: string | null; + backgroundColor: string | null; + backgroundImage: string | null; + backgroundOrigin: string | null; + backgroundPosition: string | null; + backgroundPositionX: string | null; + backgroundPositionY: string | null; + backgroundRepeat: string | null; + backgroundSize: string | null; + baselineShift: string | null; + border: string | null; + borderBottom: string | null; + borderBottomColor: string | null; + borderBottomLeftRadius: string | null; + borderBottomRightRadius: string | null; + borderBottomStyle: string | null; + borderBottomWidth: string | null; + borderCollapse: string | null; + borderColor: string | null; + borderImage: string | null; + borderImageOutset: string | null; + borderImageRepeat: string | null; + borderImageSlice: string | null; + borderImageSource: string | null; + borderImageWidth: string | null; + borderLeft: string | null; + borderLeftColor: string | null; + borderLeftStyle: string | null; + borderLeftWidth: string | null; + borderRadius: string | null; + borderRight: string | null; + borderRightColor: string | null; + borderRightStyle: string | null; + borderRightWidth: string | null; + borderSpacing: string | null; + borderStyle: string | null; + borderTop: string | null; + borderTopColor: string | null; + borderTopLeftRadius: string | null; + borderTopRightRadius: string | null; + borderTopStyle: string | null; + borderTopWidth: string | null; + borderWidth: string | null; + bottom: string | null; + boxShadow: string | null; + boxSizing: string | null; + breakAfter: string | null; + breakBefore: string | null; + breakInside: string | null; + captionSide: string | null; + clear: string | null; + clip: string | null; + clipPath: string | null; + clipRule: string | null; + color: string | null; + colorInterpolationFilters: string | null; + columnCount: any; + columnFill: string | null; + columnGap: any; + columnRule: string | null; + columnRuleColor: any; + columnRuleStyle: string | null; + columnRuleWidth: any; + columnSpan: string | null; + columnWidth: any; + columns: string | null; + content: string | null; + counterIncrement: string | null; + counterReset: string | null; + cssFloat: string | null; + cssText: string; + cursor: string | null; + direction: string | null; + display: string | null; + dominantBaseline: string | null; + emptyCells: string | null; + enableBackground: string | null; + fill: string | null; + fillOpacity: string | null; + fillRule: string | null; + filter: string | null; + flex: string | null; + flexBasis: string | null; + flexDirection: string | null; + flexFlow: string | null; + flexGrow: string | null; + flexShrink: string | null; + flexWrap: string | null; + floodColor: string | null; + floodOpacity: string | null; + font: string | null; + fontFamily: string | null; + fontFeatureSettings: string | null; + fontSize: string | null; + fontSizeAdjust: string | null; + fontStretch: string | null; + fontStyle: string | null; + fontVariant: string | null; + fontWeight: string | null; + glyphOrientationHorizontal: string | null; + glyphOrientationVertical: string | null; + height: string | null; + imeMode: string | null; + justifyContent: string | null; + kerning: string | null; + left: string | null; + readonly length: number; + letterSpacing: string | null; + lightingColor: string | null; + lineHeight: string | null; + listStyle: string | null; + listStyleImage: string | null; + listStylePosition: string | null; + listStyleType: string | null; + margin: string | null; + marginBottom: string | null; + marginLeft: string | null; + marginRight: string | null; + marginTop: string | null; + marker: string | null; + markerEnd: string | null; + markerMid: string | null; + markerStart: string | null; + mask: string | null; + maxHeight: string | null; + maxWidth: string | null; + minHeight: string | null; + minWidth: string | null; + msContentZoomChaining: string | null; + msContentZoomLimit: string | null; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string | null; + msContentZoomSnapPoints: string | null; + msContentZoomSnapType: string | null; + msContentZooming: string | null; + msFlowFrom: string | null; + msFlowInto: string | null; + msFontFeatureSettings: string | null; + msGridColumn: any; + msGridColumnAlign: string | null; + msGridColumnSpan: any; + msGridColumns: string | null; + msGridRow: any; + msGridRowAlign: string | null; + msGridRowSpan: any; + msGridRows: string | null; + msHighContrastAdjust: string | null; + msHyphenateLimitChars: string | null; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string | null; + msImeAlign: string | null; + msOverflowStyle: string | null; + msScrollChaining: string | null; + msScrollLimit: string | null; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string | null; + msScrollSnapPointsX: string | null; + msScrollSnapPointsY: string | null; + msScrollSnapType: string | null; + msScrollSnapX: string | null; + msScrollSnapY: string | null; + msScrollTranslation: string | null; + msTextCombineHorizontal: string | null; + msTextSizeAdjust: any; + msTouchAction: string | null; + msTouchSelect: string | null; + msUserSelect: string | null; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + opacity: string | null; + order: string | null; + orphans: string | null; + outline: string | null; + outlineColor: string | null; + outlineStyle: string | null; + outlineWidth: string | null; + overflow: string | null; + overflowX: string | null; + overflowY: string | null; + padding: string | null; + paddingBottom: string | null; + paddingLeft: string | null; + paddingRight: string | null; + paddingTop: string | null; + pageBreakAfter: string | null; + pageBreakBefore: string | null; + pageBreakInside: string | null; + readonly parentRule: CSSRule; + perspective: string | null; + perspectiveOrigin: string | null; + pointerEvents: string | null; + position: string | null; + quotes: string | null; + right: string | null; + rubyAlign: string | null; + rubyOverhang: string | null; + rubyPosition: string | null; + stopColor: string | null; + stopOpacity: string | null; + stroke: string | null; + strokeDasharray: string | null; + strokeDashoffset: string | null; + strokeLinecap: string | null; + strokeLinejoin: string | null; + strokeMiterlimit: string | null; + strokeOpacity: string | null; + strokeWidth: string | null; + tableLayout: string | null; + textAlign: string | null; + textAlignLast: string | null; + textAnchor: string | null; + textDecoration: string | null; + textIndent: string | null; + textJustify: string | null; + textKashida: string | null; + textKashidaSpace: string | null; + textOverflow: string | null; + textShadow: string | null; + textTransform: string | null; + textUnderlinePosition: string | null; + top: string | null; + touchAction: string | null; + transform: string | null; + transformOrigin: string | null; + transformStyle: string | null; + transition: string | null; + transitionDelay: string | null; + transitionDuration: string | null; + transitionProperty: string | null; + transitionTimingFunction: string | null; + unicodeBidi: string | null; + verticalAlign: string | null; + visibility: string | null; + webkitAlignContent: string | null; + webkitAlignItems: string | null; + webkitAlignSelf: string | null; + webkitAnimation: string | null; + webkitAnimationDelay: string | null; + webkitAnimationDirection: string | null; + webkitAnimationDuration: string | null; + webkitAnimationFillMode: string | null; + webkitAnimationIterationCount: string | null; + webkitAnimationName: string | null; + webkitAnimationPlayState: string | null; + webkitAnimationTimingFunction: string | null; + webkitAppearance: string | null; + webkitBackfaceVisibility: string | null; + webkitBackgroundClip: string | null; + webkitBackgroundOrigin: string | null; + webkitBackgroundSize: string | null; + webkitBorderBottomLeftRadius: string | null; + webkitBorderBottomRightRadius: string | null; + webkitBorderImage: string | null; + webkitBorderRadius: string | null; + webkitBorderTopLeftRadius: string | null; + webkitBorderTopRightRadius: string | null; + webkitBoxAlign: string | null; + webkitBoxDirection: string | null; + webkitBoxFlex: string | null; + webkitBoxOrdinalGroup: string | null; + webkitBoxOrient: string | null; + webkitBoxPack: string | null; + webkitBoxSizing: string | null; + webkitColumnBreakAfter: string | null; + webkitColumnBreakBefore: string | null; + webkitColumnBreakInside: string | null; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string | null; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string | null; + webkitColumnRuleWidth: any; + webkitColumnSpan: string | null; + webkitColumnWidth: any; + webkitColumns: string | null; + webkitFilter: string | null; + webkitFlex: string | null; + webkitFlexBasis: string | null; + webkitFlexDirection: string | null; + webkitFlexFlow: string | null; + webkitFlexGrow: string | null; + webkitFlexShrink: string | null; + webkitFlexWrap: string | null; + webkitJustifyContent: string | null; + webkitOrder: string | null; + webkitPerspective: string | null; + webkitPerspectiveOrigin: string | null; + webkitTapHighlightColor: string | null; + webkitTextFillColor: string | null; + webkitTextSizeAdjust: any; + webkitTransform: string | null; + webkitTransformOrigin: string | null; + webkitTransformStyle: string | null; + webkitTransition: string | null; + webkitTransitionDelay: string | null; + webkitTransitionDuration: string | null; + webkitTransitionProperty: string | null; + webkitTransitionTimingFunction: string | null; + webkitUserModify: string | null; + webkitUserSelect: string | null; + webkitWritingMode: string | null; + whiteSpace: string | null; + widows: string | null; + width: string | null; + wordBreak: string | null; + wordSpacing: string | null; + wordWrap: string | null; + writingMode: string | null; + zIndex: string | null; + zoom: string | null; + resize: string | null; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string | null, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface CSSStyleRule extends CSSRule { + readonly readOnly: boolean; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface CSSStyleSheet extends StyleSheet { + readonly cssRules: CSSRuleList; + cssText: string; + readonly href: string; + readonly id: string; + readonly imports: StyleSheetList; + readonly isAlternate: boolean; + readonly isPrefAlternate: boolean; + readonly ownerRule: CSSRule; + readonly owningElement: Element; + readonly pages: StyleSheetPageList; + readonly readOnly: boolean; + readonly rules: CSSRuleList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: string; + msImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + fill(fillRule?: string): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +} + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +} + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface CommandEvent extends Event { + readonly commandName: string; + readonly detail: string | null; +} + +declare var CommandEvent: { + prototype: CommandEvent; + new(type: string, eventInitDict?: CommandEventInit): CommandEvent; +} + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +} + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: string, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string): void; + groupCollapsed(groupTitle?: string): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +} + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +} + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +} + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +} + +interface CustomEvent extends Event { + readonly detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +} + +interface DOMError { + readonly name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType): Document; + createDocumentType(qualifiedName: string, publicId: string | null, systemId: string | null): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface DOMStringMap { + [name: string]: string; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +} + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +} + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + readonly files: FileList; + readonly items: DataTransferItemList; + readonly types: string[]; + clearData(format?: string): boolean; + getData(format: string): string; + setData(format: string, data: string): boolean; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface DataTransferItem { + readonly kind: string; + readonly type: string; + getAsFile(): File | null; + getAsString(_callback: FunctionStringCallback | null): void; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +} + +interface DataTransferItemList { + readonly length: number; + add(data: File): DataTransferItem | null; + clear(): void; + item(index: number): DataTransferItem; + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +} + +interface DeferredPermissionRequest { + readonly id: number; + readonly type: string; + readonly uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +} + +interface DelayNode extends AudioNode { + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(): DelayNode; +} + +interface DeviceAcceleration { + readonly x: number | null; + readonly y: number | null; + readonly z: number | null; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +} + +interface DeviceLightEvent extends Event { + readonly value: number; +} + +declare var DeviceLightEvent: { + prototype: DeviceLightEvent; + new(type: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; +} + +interface DeviceMotionEvent extends Event { + readonly acceleration: DeviceAcceleration | null; + readonly accelerationIncludingGravity: DeviceAcceleration | null; + readonly interval: number | null; + readonly rotationRate: DeviceRotationRate | null; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(): DeviceMotionEvent; +} + +interface DeviceOrientationEvent extends Event { + readonly absolute: boolean; + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(): DeviceOrientationEvent; +} + +interface DeviceRotationRate { + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +} + +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforedeactivate": UIEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "fullscreenchange": Event; + "fullscreenerror": Event; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "mssitemodejumplistitemremoved": MSSiteModeEvent; + "msthumbnailclick": MSSiteModeEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectionchange": Event; + "selectstart": Event; + "stalled": Event; + "stop": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "volumechange": Event; + "waiting": Event; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; + /** + * Gets the object that has the focus when the parent document has focus. + */ + readonly activeElement: Element; + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollectionOf; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + readonly compatMode: string; + cookie: string; + readonly currentScript: HTMLScriptElement | SVGScriptElement; + /** + * Gets the default character set from the current regional language settings. + */ + readonly defaultCharset: string; + readonly defaultView: Window; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * 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. + */ + readonly doctype: DocumentType; + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollectionOf; + readonly fullscreenElement: Element | null; + readonly fullscreenEnabled: boolean; + readonly head: HTMLHeadElement; + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + readonly inputEncoding: string | null; + /** + * 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. + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollectionOf; + /** + * Contains information about the current URL. + */ + readonly location: Location; + msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (this: Document, ev: FocusEvent) => any; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (this: Document, ev: Event) => any; + oncanplaythrough: (this: Document, ev: Event) => any; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (this: Document, ev: PointerEvent) => any; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (this: Document, 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: (this: Document, 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. + */ + ondragleave: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (this: Document, ev: DragEvent) => any; + ondrop: (this: Document, ev: DragEvent) => any; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (this: Document, ev: Event) => any; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (this: Document, ev: Event) => any; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (this: Document, ev: MediaStreamErrorEvent) => any; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (this: Document, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (this: Document, ev: FocusEvent) => any; + onfullscreenchange: (this: Document, ev: Event) => any; + onfullscreenerror: (this: Document, ev: Event) => any; + oninput: (this: Document, ev: Event) => any; + oninvalid: (this: Document, ev: Event) => any; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (this: Document, ev: Event) => any; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (this: Document, ev: Event) => any; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (this: Document, ev: Event) => any; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (this: Document, ev: WheelEvent) => any; + onmscontentzoom: (this: Document, ev: UIEvent) => any; + onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Document, ev: MSGestureEvent) => any; + onmsgestureend: (this: Document, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Document, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Document, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Document, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Document, ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (this: Document, ev: MSManipulationEvent) => any; + onmspointercancel: (this: Document, ev: MSPointerEvent) => any; + onmspointerdown: (this: Document, ev: MSPointerEvent) => any; + onmspointerenter: (this: Document, ev: MSPointerEvent) => any; + onmspointerleave: (this: Document, ev: MSPointerEvent) => any; + onmspointermove: (this: Document, ev: MSPointerEvent) => any; + onmspointerout: (this: Document, ev: MSPointerEvent) => any; + onmspointerover: (this: Document, ev: MSPointerEvent) => any; + onmspointerup: (this: Document, ev: MSPointerEvent) => any; + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (this: Document, ev: Event) => any; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (this: Document, ev: Event) => any; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (this: Document, ev: Event) => any; + onpointerlockchange: (this: Document, ev: Event) => any; + onpointerlockerror: (this: Document, ev: Event) => any; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (this: Document, ev: ProgressEvent) => any; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (this: Document, ev: Event) => any; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (this: Document, ev: ProgressEvent) => any; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (this: Document, ev: Event) => any; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (this: Document, ev: UIEvent) => any; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (this: Document, ev: Event) => any; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (this: Document, ev: Event) => any; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (this: Document, ev: UIEvent) => any; + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (this: Document, ev: Event) => any; + onselectstart: (this: Document, ev: Event) => any; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (this: Document, ev: Event) => any; + onsubmit: (this: Document, ev: Event) => any; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (this: Document, ev: Event) => any; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (this: Document, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (this: Document, ev: Event) => any; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (this: Document, ev: Event) => any; + onwebkitfullscreenchange: (this: Document, ev: Event) => any; + onwebkitfullscreenerror: (this: Document, ev: Event) => any; + plugins: HTMLCollectionOf; + readonly pointerLockElement: Element; + /** + * Retrieves a value that indicates the current state of the object. + */ + readonly readyState: string; + /** + * Gets the URL of the location that referred the user to the current page. + */ + readonly referrer: string; + /** + * Gets the root svg element in the document hierarchy. + */ + readonly rootElement: SVGSVGElement; + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + readonly styleSheets: StyleSheetList; + /** + * Contains the title of the document. + */ + title: string; + readonly visibilityState: string; + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + readonly webkitCurrentFullScreenElement: Element | null; + readonly webkitFullscreenElement: Element | null; + readonly webkitFullscreenEnabled: boolean; + readonly webkitIsFullScreen: boolean; + readonly xmlEncoding: string | null; + xmlStandalone: boolean; + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string | null; + adoptNode(source: Node): Node; + captureEvents(): void; + caretRangeFromPoint(x: number, y: number): Range; + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: K): HTMLElementTagNameMap[K]; + createElement(tagName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: string | null, qualifiedName: string): Element; + 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. + * @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. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + 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. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker 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. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + exitFullscreen(): void; + exitPointerLock(): void; + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + /** + * 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 | null; + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: Node, deep: boolean): Node; + msElementsFromPoint(x: number, y: number): NodeListOf; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @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. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + 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. + */ + queryCommandText(commandId: string): string; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + releaseEvents(): void; + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + webkitCancelFullScreen(): void; + webkitExitFullscreen(): void; + /** + * 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. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +} + +interface DocumentFragment extends Node, NodeSelector, ParentNode { +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DocumentType extends Node, ChildNode { + readonly entities: NamedNodeMap; + readonly internalSubset: string | null; + readonly name: string; + readonly notations: NamedNodeMap; + readonly publicId: string | null; + readonly systemId: string | null; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface DragEvent extends MouseEvent { + readonly dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DynamicsCompressorNode extends AudioNode { + readonly attack: AudioParam; + readonly knee: AudioParam; + readonly ratio: AudioParam; + readonly reduction: AudioParam; + readonly release: AudioParam; + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(): DynamicsCompressorNode; +} + +interface EXT_frag_depth { +} + +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +} + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": AriaRequestEvent; + "command": CommandEvent; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSGotPointerCapture": MSPointerEvent; + "MSInertiaStart": MSGestureEvent; + "MSLostPointerCapture": MSPointerEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { + readonly classList: DOMTokenList; + className: string; + readonly clientHeight: number; + readonly clientLeft: number; + readonly clientTop: number; + readonly clientWidth: number; + id: string; + msContentZoomFactor: number; + readonly msRegionOverflow: string; + onariarequest: (this: Element, ev: AriaRequestEvent) => any; + oncommand: (this: Element, ev: CommandEvent) => any; + ongotpointercapture: (this: Element, ev: PointerEvent) => any; + onlostpointercapture: (this: Element, ev: PointerEvent) => any; + onmsgesturechange: (this: Element, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Element, ev: MSGestureEvent) => any; + onmsgestureend: (this: Element, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Element, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Element, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Element, ev: MSGestureEvent) => any; + onmsgotpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmsinertiastart: (this: Element, ev: MSGestureEvent) => any; + onmslostpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmspointercancel: (this: Element, ev: MSPointerEvent) => any; + onmspointerdown: (this: Element, ev: MSPointerEvent) => any; + onmspointerenter: (this: Element, ev: MSPointerEvent) => any; + onmspointerleave: (this: Element, ev: MSPointerEvent) => any; + onmspointermove: (this: Element, ev: MSPointerEvent) => any; + onmspointerout: (this: Element, ev: MSPointerEvent) => any; + onmspointerover: (this: Element, ev: MSPointerEvent) => any; + onmspointerup: (this: Element, ev: MSPointerEvent) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onwebkitfullscreenchange: (this: Element, ev: Event) => any; + onwebkitfullscreenerror: (this: Element, ev: Event) => any; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly tagName: string; + innerHTML: string; + readonly assignedSlot: HTMLSlotElement | null; + slot: string; + readonly shadowRoot: ShadowRoot | null; + getAttribute(name: string): string | null; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; + msZoomTo(args: MsZoomToOptions): void; + releasePointerCapture(pointerId: number): void; + removeAttribute(name?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + setAttribute(name: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): void; + getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: string, insertedElement: Element): Element | null; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget; + readonly timeStamp: number; + readonly type: string; + readonly scoped: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + deepPath(): EventTarget[]; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +interface EventTarget { + addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +} + +interface External { +} + +declare var External: { + prototype: External; + new(): External; +} + +interface File extends Blob { + readonly lastModifiedDate: any; + readonly name: string; + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +} + +interface FileList { + readonly length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface FileReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +} + +interface FocusEvent extends UIEvent { + readonly relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} + +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface GainNode extends AudioNode { + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(): GainNode; +} + +interface Gamepad { + readonly axes: number[]; + readonly buttons: GamepadButton[]; + readonly connected: boolean; + readonly id: string; + readonly index: number; + readonly mapping: string; + readonly timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +} + +interface GamepadButton { + readonly pressed: boolean; + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +} + +interface GamepadEvent extends Event { + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(): GamepadEvent; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +} + +interface HTMLAnchorElement extends HTMLElement { + Methods: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + readonly mimeType: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + readonly nameProp: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + readonly protocolLong: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: 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; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface HTMLAppletElement extends HTMLElement { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + object: string | null; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + vspace: number; + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + rel: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns a string representation of an object. + */ + toString(): string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Adds an element to the areas, controlRange, or options collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Removes an element from the collection. + */ + remove(index?: number): void; +} + +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface HTMLBodyElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLBodyElement extends HTMLElement { + aLink: any; + background: string; + bgColor: any; + bgProperties: string; + link: any; + noWrap: boolean; + onafterprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; + onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; + onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; + onload: (this: HTMLBodyElement, ev: Event) => any; + onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; + onoffline: (this: HTMLBodyElement, ev: Event) => any; + ononline: (this: HTMLBodyElement, ev: Event) => any; + onorientationchange: (this: HTMLBodyElement, ev: Event) => any; + onpagehide: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; + onresize: (this: HTMLBodyElement, ev: UIEvent) => any; + onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; + onunload: (this: HTMLBodyElement, ev: Event) => any; + text: any; + vLink: any; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + status: any; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * 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; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * 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", 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. + */ + msToBlob(): Blob; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @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(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLCollection { + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Retrieves an object from various collections. + */ + item(index: number): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [index: number]: Element; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface HTMLDirectoryElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +} + +interface HTMLElementEventMap extends ElementEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforecopy": ClipboardEvent; + "beforecut": ClipboardEvent; + "beforedeactivate": UIEvent; + "beforepaste": ClipboardEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectstart": Event; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "volumechange": Event; + "waiting": Event; +} + +interface HTMLElement extends Element { + accessKey: string; + readonly children: HTMLCollection; + contentEditable: string; + readonly dataset: DOMStringMap; + dir: string; + draggable: boolean; + hidden: boolean; + hideFocus: boolean; + innerHTML: string; + innerText: string; + readonly isContentEditable: boolean; + lang: string; + readonly offsetHeight: number; + readonly offsetLeft: number; + readonly offsetParent: Element; + readonly offsetTop: number; + readonly offsetWidth: number; + onabort: (this: HTMLElement, ev: UIEvent) => any; + onactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforecopy: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforecut: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforedeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforepaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onblur: (this: HTMLElement, ev: FocusEvent) => any; + oncanplay: (this: HTMLElement, ev: Event) => any; + oncanplaythrough: (this: HTMLElement, ev: Event) => any; + onchange: (this: HTMLElement, ev: Event) => any; + onclick: (this: HTMLElement, ev: MouseEvent) => any; + oncontextmenu: (this: HTMLElement, ev: PointerEvent) => any; + oncopy: (this: HTMLElement, ev: ClipboardEvent) => any; + oncuechange: (this: HTMLElement, ev: Event) => any; + oncut: (this: HTMLElement, ev: ClipboardEvent) => any; + ondblclick: (this: HTMLElement, ev: MouseEvent) => any; + ondeactivate: (this: HTMLElement, ev: UIEvent) => any; + ondrag: (this: HTMLElement, ev: DragEvent) => any; + ondragend: (this: HTMLElement, ev: DragEvent) => any; + ondragenter: (this: HTMLElement, ev: DragEvent) => any; + ondragleave: (this: HTMLElement, ev: DragEvent) => any; + ondragover: (this: HTMLElement, ev: DragEvent) => any; + ondragstart: (this: HTMLElement, ev: DragEvent) => any; + ondrop: (this: HTMLElement, ev: DragEvent) => any; + ondurationchange: (this: HTMLElement, ev: Event) => any; + onemptied: (this: HTMLElement, ev: Event) => any; + onended: (this: HTMLElement, ev: MediaStreamErrorEvent) => any; + onerror: (this: HTMLElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLElement, ev: FocusEvent) => any; + oninput: (this: HTMLElement, ev: Event) => any; + oninvalid: (this: HTMLElement, ev: Event) => any; + onkeydown: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeypress: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeyup: (this: HTMLElement, ev: KeyboardEvent) => any; + onload: (this: HTMLElement, ev: Event) => any; + onloadeddata: (this: HTMLElement, ev: Event) => any; + onloadedmetadata: (this: HTMLElement, ev: Event) => any; + onloadstart: (this: HTMLElement, ev: Event) => any; + onmousedown: (this: HTMLElement, ev: MouseEvent) => any; + onmouseenter: (this: HTMLElement, ev: MouseEvent) => any; + onmouseleave: (this: HTMLElement, ev: MouseEvent) => any; + onmousemove: (this: HTMLElement, ev: MouseEvent) => any; + onmouseout: (this: HTMLElement, ev: MouseEvent) => any; + onmouseover: (this: HTMLElement, ev: MouseEvent) => any; + onmouseup: (this: HTMLElement, ev: MouseEvent) => any; + onmousewheel: (this: HTMLElement, ev: WheelEvent) => any; + onmscontentzoom: (this: HTMLElement, ev: UIEvent) => any; + onmsmanipulationstatechanged: (this: HTMLElement, ev: MSManipulationEvent) => any; + onpaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onpause: (this: HTMLElement, ev: Event) => any; + onplay: (this: HTMLElement, ev: Event) => any; + onplaying: (this: HTMLElement, ev: Event) => any; + onprogress: (this: HTMLElement, ev: ProgressEvent) => any; + onratechange: (this: HTMLElement, ev: Event) => any; + onreset: (this: HTMLElement, ev: Event) => any; + onscroll: (this: HTMLElement, ev: UIEvent) => any; + onseeked: (this: HTMLElement, ev: Event) => any; + onseeking: (this: HTMLElement, ev: Event) => any; + onselect: (this: HTMLElement, ev: UIEvent) => any; + onselectstart: (this: HTMLElement, ev: Event) => any; + onstalled: (this: HTMLElement, ev: Event) => any; + onsubmit: (this: HTMLElement, ev: Event) => any; + onsuspend: (this: HTMLElement, ev: Event) => any; + ontimeupdate: (this: HTMLElement, ev: Event) => any; + onvolumechange: (this: HTMLElement, ev: Event) => any; + onwaiting: (this: HTMLElement, ev: Event) => any; + outerHTML: string; + outerText: string; + spellcheck: boolean; + readonly style: CSSStyleDeclaration; + tabIndex: number; + title: string; + blur(): void; + click(): void; + dragDrop(): boolean; + focus(): void; + msGetInputContext(): MSInputMethodContext; + setActive(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + readonly palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + readonly pluginspage: string; + readonly readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + readonly elements: HTMLCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(name: string): any; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface HTMLFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument { + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string | number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLFrameElement, ev: Event) => any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the width of the object. + */ + width: string | number; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLFrameSetElement extends HTMLElement { + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + name: string; + onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; + /** + * Fires when the object loses the input focus. + */ + onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + */ + onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; + onload: (this: HTMLFrameSetElement, ev: Event) => any; + onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; + onoffline: (this: HTMLFrameSetElement, ev: Event) => any; + ononline: (this: HTMLFrameSetElement, ev: Event) => any; + onorientationchange: (this: HTMLFrameSetElement, ev: Event) => any; + onpagehide: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; + onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; + onunload: (this: HTMLFrameSetElement, ev: Event) => any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface HTMLIFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + allowFullscreen: boolean; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (this: HTMLIFrameElement, ev: Event) => any; + readonly sandbox: DOMSettableTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + crossOrigin: string; + readonly currentSrc: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + lowsrc: string; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * The original height of the image resource before sizing. + */ + readonly naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + readonly naturalWidth: number; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + readonly x: number; + readonly y: number; + msGetAsCastingSource(): any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; + create(): HTMLImageElement; +} + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + readonly files: FileList | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + indeterminate: boolean; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + readonly list: HTMLElement; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + selectionDirection: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + status: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: Date; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + webkitdirectory: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start?: number, end?: number, direction?: string): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface HTMLLabelElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface HTMLLegendElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + import?: Document; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + readonly areas: HTMLAreasCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + +interface HTMLMarqueeElement extends HTMLElement { + behavior: string; + bgColor: any; + direction: string; + height: string; + hspace: number; + loop: number; + onbounce: (this: HTMLMarqueeElement, ev: Event) => any; + onfinish: (this: HTMLMarqueeElement, ev: Event) => any; + onstart: (this: HTMLMarqueeElement, ev: Event) => any; + scrollAmount: number; + scrollDelay: number; + trueSpeed: boolean; + vspace: number; + width: string; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": MSMediaKeyNeededEvent; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + readonly audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + readonly buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + crossOrigin: string; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + readonly currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + readonly duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + readonly ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + readonly error: MediaError; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + readonly mediaKeys: MediaKeys | null; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + readonly msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + readonly msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + readonly networkState: number; + onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; + onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + /** + * Gets a flag that specifies whether playback is paused. + */ + readonly paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + readonly played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + readonly seekable: TimeRanges; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + readonly seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcObject: MediaStream | null; + readonly textTracks: TextTrackList; + readonly videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): string; + /** + * Resets the audio or video object and loads a new media resource. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + setMediaKeys(mediaKeys: MediaKeys | null): PromiseLike; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; +} + +interface HTMLMenuElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface HTMLMeterElement extends HTMLElement { + high: number; + low: number; + max: number; + min: number; + optimum: number; + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMeterElement: { + prototype: HTMLMeterElement; + new(): HTMLMeterElement; +} + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface HTMLOListElement extends HTMLElement { + compact: boolean; + /** + * The starting number. + */ + start: number; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the contained object. + */ + readonly object: any; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface HTMLOptGroupElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + readonly text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; + create(): HTMLOptionElement; +} + +interface HTMLOptionsCollection extends HTMLCollectionOf { + length: number; + selectedIndex: number; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + remove(index: number): void; +} + +declare var HTMLOptionsCollection: { + prototype: HTMLOptionsCollection; + new(): HTMLOptionsCollection; +} + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + +interface HTMLPreElement extends HTMLElement { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + readonly position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * 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; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface HTMLSelectElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly options: HTMLOptionsCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + selectedOptions: HTMLCollectionOf; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * 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. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [name: string]: any; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + msKeySystem: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + disabled: boolean; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + bgColor: any; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + readonly cellIndex: number; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** + * Sets or retrieves the width of the object. + */ + width: any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement { +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + bgColor: any; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollectionOf; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + bgColor: any; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollectionOf; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + readonly rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + readonly sectionRowIndex: number; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface HTMLTemplateElement extends HTMLElement { + readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLTextAreaElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves the type of control. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readonly readyState: number; + src: string; + srclang: string; + readonly track: TextTrack; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; +} + +interface HTMLUListElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + readonly msIsLayoutOptimalForPlayback: boolean; + readonly msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoWidth: number; + readonly webkitDisplayingFullscreen: boolean; + readonly webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullScreen(): void; + webkitEnterFullscreen(): void; + webkitExitFullScreen(): void; + webkitExitFullscreen(): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +} + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +} + +interface IDBCursor { + readonly direction: string; + key: IDBKeyRange | IDBValidKey; + readonly primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: IDBKeyRange | IDBValidKey): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +interface IDBCursorWithValue extends IDBCursor { + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + +interface IDBDatabase extends EventTarget { + readonly name: string; + readonly objectStoreNames: DOMStringList; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; + version: number; + onversionchange: (ev: IDBVersionChangeEvent) => any; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; + addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface IDBIndex { + keyPath: string | string[]; + readonly name: string; + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + multiEntry: boolean; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + get(key: IDBKeyRange | IDBValidKey): IDBRequest; + getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface IDBKeyRange { + readonly lower: any; + readonly lowerOpen: boolean; + readonly upper: any; + readonly upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(lower: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(upper: any, open?: boolean): IDBKeyRange; +} + +interface IDBObjectStore { + readonly indexNames: DOMStringList; + keyPath: string | string[]; + readonly name: string; + readonly transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + clear(): IDBRequest; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + +interface IDBRequest extends EventTarget { + readonly error: DOMError; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; + readonly readyState: string; + readonly result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + readonly transaction: IDBTransaction; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + +interface IDBTransaction extends EventTarget { + readonly db: IDBDatabase; + readonly error: DOMError; + readonly mode: string; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; +} + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface ImageData { + data: Uint8ClampedArray; + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +} + +interface KeyboardEvent extends UIEvent { + readonly altKey: boolean; + readonly char: string | null; + readonly charCode: number; + readonly ctrlKey: boolean; + readonly key: string; + readonly keyCode: number; + readonly locale: string; + readonly location: number; + readonly metaKey: boolean; + readonly repeat: boolean; + readonly shiftKey: boolean; + readonly which: number; + readonly code: string; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +interface ListeningStateChangedEvent extends Event { + readonly label: string; + readonly state: string; +} + +declare var ListeningStateChangedEvent: { + prototype: ListeningStateChangedEvent; + new(): ListeningStateChangedEvent; +} + +interface Location { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + assign(url: string): void; + reload(forcedReload?: boolean): void; + replace(url: string): void; + toString(): string; +} + +declare var Location: { + prototype: Location; + new(): Location; +} + +interface LongRunningScriptDetectedEvent extends Event { + readonly executionTime: number; + stopPageScriptExecution: boolean; +} + +declare var LongRunningScriptDetectedEvent: { + prototype: LongRunningScriptDetectedEvent; + new(): LongRunningScriptDetectedEvent; +} + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + readonly CURRENT: string; + readonly HIGH: string; + readonly IDLE: string; + readonly NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSAppAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; +} + +interface MSAssertion { + readonly id: string; + readonly type: string; +} + +declare var MSAssertion: { + prototype: MSAssertion; + new(): MSAssertion; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +} + +interface MSCredentials { + getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): PromiseLike; + makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): PromiseLike; +} + +declare var MSCredentials: { + prototype: MSCredentials; + new(): MSCredentials; +} + +interface MSFIDOCredentialAssertion extends MSAssertion { + readonly algorithm: string | Algorithm; + readonly attestation: any; + readonly publicKey: string; + readonly transportHints: string[]; +} + +declare var MSFIDOCredentialAssertion: { + prototype: MSFIDOCredentialAssertion; + new(): MSFIDOCredentialAssertion; +} + +interface MSFIDOSignature { + readonly authnrData: string; + readonly clientData: string; + readonly signature: string; +} + +declare var MSFIDOSignature: { + prototype: MSFIDOSignature; + new(): MSFIDOSignature; +} + +interface MSFIDOSignatureAssertion extends MSAssertion { + readonly signature: MSFIDOSignature; +} + +declare var MSFIDOSignatureAssertion: { + prototype: MSFIDOSignatureAssertion; + new(): MSFIDOSignatureAssertion; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +} + +interface MSGestureEvent extends UIEvent { + readonly clientX: number; + readonly clientY: number; + readonly expansion: number; + readonly gestureObject: any; + readonly hwTimestamp: number; + readonly offsetX: number; + readonly offsetY: number; + readonly rotation: number; + readonly scale: number; + readonly screenX: number; + readonly screenY: number; + readonly translationX: number; + readonly translationY: number; + readonly velocityAngular: number; + readonly velocityExpansion: number; + readonly velocityX: number; + readonly velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +interface MSGraphicsTrust { + readonly constrictionActive: boolean; + readonly status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +} + +interface MSHTMLWebViewElement extends HTMLElement { + readonly canGoBack: boolean; + readonly canGoForward: boolean; + readonly containsFullScreenElement: boolean; + readonly documentTitle: string; + height: number; + readonly settings: MSWebViewSettings; + src: string; + width: number; + addWebAllowedObject(name: string, applicationObject: any): void; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; + getDeferredPermissionRequests(): DeferredPermissionRequest[]; + goBack(): void; + goForward(): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + navigate(uri: string): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + navigateToString(contents: string): void; + navigateWithHttpRequestMessage(requestMessage: any): void; + refresh(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSHTMLWebViewElement: { + prototype: MSHTMLWebViewElement; + new(): MSHTMLWebViewElement; +} + +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowshow: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowupdate: (this: MSInputMethodContext, ev: Event) => any; + readonly target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +} + +interface MSManipulationEvent extends UIEvent { + readonly currentState: number; + readonly inertiaDestinationX: number; + readonly inertiaDestinationY: number; + readonly lastState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +interface MSMediaKeyError { + readonly code: number; + readonly systemCode: number; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +interface MSMediaKeyMessageEvent extends Event { + readonly destinationURL: string | null; + readonly message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +} + +interface MSMediaKeyNeededEvent extends Event { + readonly initData: Uint8Array | null; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +} + +interface MSMediaKeySession extends EventTarget { + readonly error: MSMediaKeyError | null; + readonly keySystem: string; + readonly sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +} + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +} + +interface MSPointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +} + +interface MSRangeCollection { + readonly length: number; + item(index: number): Range; + [index: number]: Range; +} + +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSSiteModeEvent extends Event { + readonly actionURL: string; + readonly buttonID: number; +} + +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MSStreamReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +} + +interface MSWebViewAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSWebViewAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSWebViewAsyncOperation, ev: Event) => any; + onerror: (this: MSWebViewAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + readonly target: MSHTMLWebViewElement; + readonly type: number; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSWebViewAsyncOperation: { + prototype: MSWebViewAsyncOperation; + new(): MSWebViewAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; +} + +interface MSWebViewSettings { + isIndexedDBEnabled: boolean; + isJavaScriptEnabled: boolean; +} + +declare var MSWebViewSettings: { + prototype: MSWebViewSettings; + new(): MSWebViewSettings; +} + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: string; + readonly label: string; +} + +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +} + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): any; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): PromiseLike; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +} + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +} + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +} + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: string; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +} + +interface MediaKeySession extends EventTarget { + readonly closed: PromiseLike; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): PromiseLike; + generateRequest(initDataType: string, initData: any): PromiseLike; + load(sessionId: string): PromiseLike; + remove(): PromiseLike; + update(response: any): PromiseLike; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +} + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): string; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +} + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): PromiseLike; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +} + +interface MediaKeys { + createSession(sessionType?: string): MediaKeySession; + setServerCertificate(serverCertificate: any): PromiseLike; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +} + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +} + +interface MediaStreamEventMap { + "active": Event; + "addtrack": TrackEvent; + "inactive": Event; + "removetrack": TrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: TrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: TrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +} + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +} + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +} + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +} + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: string; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): PromiseLike; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +} + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(type: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +} + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +} + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +} + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +} + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +} + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +} + +interface MutationEvent extends Event { + readonly attrChange: number; + readonly attrName: string; + readonly newValue: string; + readonly prevValue: string; + readonly relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +interface MutationObserver { + disconnect(): void; + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +} + +interface MutationRecord { + readonly addedNodes: NodeList; + readonly attributeName: string | null; + readonly attributeNamespace: string | null; + readonly nextSibling: Node | null; + readonly oldValue: string | null; + readonly previousSibling: Node | null; + readonly removedNodes: NodeList; + readonly target: Node; + readonly type: string; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +} + +interface NamedNodeMap { + readonly length: number; + getNamedItem(name: string): Attr; + getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + item(index: number): Attr; + removeNamedItem(name: string): Attr; + removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + setNamedItem(arg: Attr): Attr; + setNamedItemNS(arg: Attr): Attr; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface NavigationCompletedEvent extends NavigationEvent { + readonly isSuccess: boolean; + readonly webErrorStatus: number; +} + +declare var NavigationCompletedEvent: { + prototype: NavigationCompletedEvent; + new(): NavigationCompletedEvent; +} + +interface NavigationEvent extends Event { + readonly uri: string; +} + +declare var NavigationEvent: { + prototype: NavigationEvent; + new(): NavigationEvent; +} + +interface NavigationEventWithReferrer extends NavigationEvent { + readonly referer: string; +} + +declare var NavigationEventWithReferrer: { + prototype: NavigationEventWithReferrer; + new(): NavigationEventWithReferrer; +} + +interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorUserMedia { + readonly appCodeName: string; + readonly cookieEnabled: boolean; + readonly language: string; + readonly maxTouchPoints: number; + readonly mimeTypes: MimeTypeArray; + readonly msManipulationViewsEnabled: boolean; + readonly msMaxTouchPoints: number; + readonly msPointerEnabled: boolean; + readonly plugins: PluginArray; + readonly pointerEnabled: boolean; + readonly webdriver: boolean; + readonly hardwareConcurrency: number; + getGamepads(): Gamepad[]; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; + vibrate(pattern: number | number[]): boolean; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface Node extends EventTarget { + readonly attributes: NamedNodeMap; + readonly baseURI: string | null; + readonly childNodes: NodeList; + readonly firstChild: Node | null; + readonly lastChild: Node | null; + readonly localName: string | null; + readonly namespaceURI: string | null; + readonly nextSibling: Node | null; + readonly nodeName: string; + readonly nodeType: number; + nodeValue: string | null; + readonly ownerDocument: Document; + readonly parentElement: HTMLElement | null; + readonly parentNode: Node | null; + readonly previousSibling: Node | null; + textContent: string | null; + appendChild(newChild: Node): Node; + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + contains(child: Node): boolean; + hasAttributes(): boolean; + hasChildNodes(): boolean; + insertBefore(newChild: Node, refChild: Node | null): Node; + isDefaultNamespace(namespaceURI: string | null): boolean; + isEqualNode(arg: Node): boolean; + isSameNode(other: Node): boolean; + lookupNamespaceURI(prefix: string | null): string | null; + lookupPrefix(namespaceURI: string | null): string | null; + normalize(): void; + removeChild(oldChild: Node): Node; + replaceChild(newChild: Node, oldChild: Node): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +interface NodeFilter { + acceptNode(n: Node): number; +} + +declare var NodeFilter: { + readonly FILTER_ACCEPT: number; + readonly FILTER_REJECT: number; + readonly FILTER_SKIP: number; + readonly SHOW_ALL: number; + readonly SHOW_ATTRIBUTE: number; + readonly SHOW_CDATA_SECTION: number; + readonly SHOW_COMMENT: number; + readonly SHOW_DOCUMENT: number; + readonly SHOW_DOCUMENT_FRAGMENT: number; + readonly SHOW_DOCUMENT_TYPE: number; + readonly SHOW_ELEMENT: number; + readonly SHOW_ENTITY: number; + readonly SHOW_ENTITY_REFERENCE: number; + readonly SHOW_NOTATION: number; + readonly SHOW_PROCESSING_INSTRUCTION: number; + readonly SHOW_TEXT: number; +} + +interface NodeIterator { + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + detach(): void; + nextNode(): Node; + previousNode(): Node; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface NodeList { + readonly length: number; + item(index: number): Node; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface OES_element_index_uint { +} + +declare var OES_element_index_uint: { + prototype: OES_element_index_uint; + new(): OES_element_index_uint; +} + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +declare var OES_standard_derivatives: { + prototype: OES_standard_derivatives; + new(): OES_standard_derivatives; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface OES_texture_float { +} + +declare var OES_texture_float: { + prototype: OES_texture_float; + new(): OES_texture_float; +} + +interface OES_texture_float_linear { +} + +declare var OES_texture_float_linear: { + prototype: OES_texture_float_linear; + new(): OES_texture_float_linear; +} + +interface OfflineAudioCompletionEvent extends Event { + readonly renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(): OfflineAudioCompletionEvent; +} + +interface OfflineAudioContextEventMap { + "complete": Event; +} + +interface OfflineAudioContext extends AudioContext { + oncomplete: (this: OfflineAudioContext, ev: Event) => any; + startRendering(): PromiseLike; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +} + +interface OscillatorNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface OscillatorNode extends AudioNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + type: string; + setPeriodicWave(periodicWave: PeriodicWave): void; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(): OscillatorNode; +} + +interface OverflowEvent extends UIEvent { + readonly horizontalOverflow: boolean; + readonly orient: number; + readonly verticalOverflow: boolean; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +declare var OverflowEvent: { + prototype: OverflowEvent; + new(): OverflowEvent; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +interface PageTransitionEvent extends Event { + readonly persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +} + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: string; + maxDistance: number; + panningModel: string; + refDistance: number; + rolloffFactor: number; + setOrientation(x: number, y: number, z: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(): PannerNode; +} + +interface PerfWidgetExternal { + readonly activeNetworkRequestCount: number; + readonly averageFrameTime: number; + readonly averagePaintTime: number; + readonly extraInformationEnabled: boolean; + readonly independentRenderingEnabled: boolean; + readonly irDisablingContentString: string; + readonly irStatusAvailable: boolean; + readonly maxCpuSpeed: number; + readonly paintRequestsPerSecond: number; + readonly performanceCounter: number; + readonly performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number | null): any; + getRecentFrames(last: number | null): any; + getRecentMemoryUsage(last: number | null): any; + getRecentPaintRequests(last: number | null): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +} + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +} + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +} + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +} + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: string; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +} + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(): PeriodicWave; +} + +interface PermissionRequest extends DeferredPermissionRequest { + readonly state: string; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +} + +interface PermissionRequestedEvent extends Event { + readonly permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +} + +interface Plugin { + readonly description: string; + readonly filename: string; + readonly length: number; + readonly name: string; + readonly version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +} + +interface PluginArray { + readonly length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +} + +interface PointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; +} + +interface PopStateEvent extends Event { + readonly state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +} + +interface PositionError { + readonly code: number; + readonly message: string; + toString(): string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +interface ProcessingInstruction extends CharacterData { + readonly target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +} + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; +} + +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +} + +interface RTCDtlsTransportEventMap { + "dtlsstatechange": RTCDtlsTransportStateChangedEvent; + "error": ErrorEvent; +} + +interface RTCDtlsTransport extends RTCStatsProvider { + ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: ErrorEvent) => any) | null; + readonly state: string; + readonly transport: RTCIceTransport; + getLocalParameters(): RTCDtlsParameters; + getRemoteCertificates(): ArrayBuffer[]; + getRemoteParameters(): RTCDtlsParameters | null; + start(remoteParameters: RTCDtlsParameters): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtlsTransport: { + prototype: RTCDtlsTransport; + new(transport: RTCIceTransport): RTCDtlsTransport; +} + +interface RTCDtlsTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCDtlsTransportStateChangedEvent: { + prototype: RTCDtlsTransportStateChangedEvent; + new(): RTCDtlsTransportStateChangedEvent; +} + +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDtmfSender extends EventTarget { + readonly canInsertDTMF: boolean; + readonly duration: number; + readonly interToneGap: number; + ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + readonly sender: RTCRtpSender; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCDtmfSender: { + prototype: RTCDtmfSender; + new(sender: RTCRtpSender): RTCDtmfSender; +} + +interface RTCIceCandidatePairChangedEvent extends Event { + readonly pair: RTCIceCandidatePair; +} + +declare var RTCIceCandidatePairChangedEvent: { + prototype: RTCIceCandidatePairChangedEvent; + new(): RTCIceCandidatePairChangedEvent; +} + +interface RTCIceGathererEventMap { + "error": ErrorEvent; + "localcandidate": RTCIceGathererEvent; +} + +interface RTCIceGatherer extends RTCStatsProvider { + readonly component: string; + onerror: ((this: RTCIceGatherer, ev: ErrorEvent) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; + createAssociatedGatherer(): RTCIceGatherer; + getLocalCandidates(): RTCIceCandidate[]; + getLocalParameters(): RTCIceParameters; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceGatherer: { + prototype: RTCIceGatherer; + new(options: RTCIceGatherOptions): RTCIceGatherer; +} + +interface RTCIceGathererEvent extends Event { + readonly candidate: RTCIceCandidate | RTCIceCandidateComplete; +} + +declare var RTCIceGathererEvent: { + prototype: RTCIceGathererEvent; + new(): RTCIceGathererEvent; +} + +interface RTCIceTransportEventMap { + "candidatepairchange": RTCIceCandidatePairChangedEvent; + "icestatechange": RTCIceTransportStateChangedEvent; +} + +interface RTCIceTransport extends RTCStatsProvider { + readonly component: string; + readonly iceGatherer: RTCIceGatherer | null; + oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null; + onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null; + readonly role: string; + readonly state: string; + addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; + createAssociatedTransport(): RTCIceTransport; + getNominatedCandidatePair(): RTCIceCandidatePair | null; + getRemoteCandidates(): RTCIceCandidate[]; + getRemoteParameters(): RTCIceParameters | null; + setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; + start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCIceTransport: { + prototype: RTCIceTransport; + new(): RTCIceTransport; +} + +interface RTCIceTransportStateChangedEvent extends Event { + readonly state: string; +} + +declare var RTCIceTransportStateChangedEvent: { + prototype: RTCIceTransportStateChangedEvent; + new(): RTCIceTransportStateChangedEvent; +} + +interface RTCRtpReceiverEventMap { + "error": ErrorEvent; +} + +interface RTCRtpReceiver extends RTCStatsProvider { + onerror: ((this: RTCRtpReceiver, ev: ErrorEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack | null; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + getContributingSources(): RTCRtpContributingSource[]; + receive(parameters: RTCRtpParameters): void; + requestSendCSRC(csrc: number): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpReceiver: { + prototype: RTCRtpReceiver; + new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCRtpSenderEventMap { + "error": ErrorEvent; + "ssrcconflict": RTCSsrcConflictEvent; +} + +interface RTCRtpSender extends RTCStatsProvider { + onerror: ((this: RTCRtpSender, ev: ErrorEvent) => any) | null; + onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + send(parameters: RTCRtpParameters): void; + setTrack(track: MediaStreamTrack): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCRtpSender: { + prototype: RTCRtpSender; + new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; + getCapabilities(kind?: string): RTCRtpCapabilities; +} + +interface RTCSrtpSdesTransportEventMap { + "error": ErrorEvent; +} + +interface RTCSrtpSdesTransport extends EventTarget { + onerror: ((this: RTCSrtpSdesTransport, ev: ErrorEvent) => any) | null; + readonly transport: RTCIceTransport; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var RTCSrtpSdesTransport: { + prototype: RTCSrtpSdesTransport; + new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; + getLocalParameters(): RTCSrtpSdesParameters[]; +} + +interface RTCSsrcConflictEvent extends Event { + readonly ssrc: number; +} + +declare var RTCSsrcConflictEvent: { + prototype: RTCSsrcConflictEvent; + new(): RTCSsrcConflictEvent; +} + +interface RTCStatsProvider extends EventTarget { + getStats(): PromiseLike; + msGetStats(): PromiseLike; +} + +declare var RTCStatsProvider: { + prototype: RTCStatsProvider; + new(): RTCStatsProvider; +} + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: string): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface SVGAngle { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +interface SVGAnimatedAngle { + readonly animVal: SVGAngle; + readonly baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGAnimatedBoolean { + readonly animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGAnimatedEnumeration { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGAnimatedInteger { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGAnimatedLength { + readonly animVal: SVGLength; + readonly baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface SVGAnimatedLengthList { + readonly animVal: SVGLengthList; + readonly baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface SVGAnimatedNumber { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface SVGAnimatedNumberList { + readonly animVal: SVGNumberList; + readonly baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGAnimatedPreserveAspectRatio { + readonly animVal: SVGPreserveAspectRatio; + readonly baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface SVGAnimatedRect { + readonly animVal: SVGRect; + readonly baseVal: SVGRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface SVGAnimatedString { + readonly animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGAnimatedTransformList { + readonly animVal: SVGTransformList; + readonly baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + readonly amplitude: SVGAnimatedNumber; + readonly exponent: SVGAnimatedNumber; + readonly intercept: SVGAnimatedNumber; + readonly offset: SVGAnimatedNumber; + readonly slope: SVGAnimatedNumber; + readonly tableValues: SVGAnimatedNumberList; + readonly type: SVGAnimatedEnumeration; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface SVGElementEventMap extends ElementEventMap { + "click": MouseEvent; + "dblclick": MouseEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "load": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; +} + +interface SVGElement extends Element { + onclick: (this: SVGElement, ev: MouseEvent) => any; + ondblclick: (this: SVGElement, ev: MouseEvent) => any; + onfocusin: (this: SVGElement, ev: FocusEvent) => any; + onfocusout: (this: SVGElement, ev: FocusEvent) => any; + onload: (this: SVGElement, ev: Event) => any; + onmousedown: (this: SVGElement, ev: MouseEvent) => any; + onmousemove: (this: SVGElement, ev: MouseEvent) => any; + onmouseout: (this: SVGElement, ev: MouseEvent) => any; + onmouseover: (this: SVGElement, ev: MouseEvent) => any; + onmouseup: (this: SVGElement, ev: MouseEvent) => any; + readonly ownerSVGElement: SVGSVGElement; + readonly viewportElement: SVGElement; + xmlbase: string; + className: any; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface SVGElementInstance extends EventTarget { + readonly childNodes: SVGElementInstanceList; + readonly correspondingElement: SVGElement; + readonly correspondingUseElement: SVGUseElement; + readonly firstChild: SVGElementInstance; + readonly lastChild: SVGElementInstance; + readonly nextSibling: SVGElementInstance; + readonly parentNode: SVGElementInstance; + readonly previousSibling: SVGElementInstance; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface SVGElementInstanceList { + readonly length: number; + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly mode: SVGAnimatedEnumeration; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly type: SVGAnimatedEnumeration; + readonly values: SVGAnimatedNumberList; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly k1: SVGAnimatedNumber; + readonly k2: SVGAnimatedNumber; + readonly k3: SVGAnimatedNumber; + readonly k4: SVGAnimatedNumber; + readonly operator: SVGAnimatedEnumeration; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly bias: SVGAnimatedNumber; + readonly divisor: SVGAnimatedNumber; + readonly edgeMode: SVGAnimatedEnumeration; + readonly in1: SVGAnimatedString; + readonly kernelMatrix: SVGAnimatedNumberList; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly orderX: SVGAnimatedInteger; + readonly orderY: SVGAnimatedInteger; + readonly preserveAlpha: SVGAnimatedBoolean; + readonly targetX: SVGAnimatedInteger; + readonly targetY: SVGAnimatedInteger; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly diffuseConstant: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly scale: SVGAnimatedNumber; + readonly xChannelSelector: SVGAnimatedEnumeration; + readonly yChannelSelector: SVGAnimatedEnumeration; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; +} + +interface SVGFEDistantLightElement extends SVGElement { + readonly azimuth: SVGAnimatedNumber; + readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly stdDeviationX: SVGAnimatedNumber; + readonly stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface SVGFEMergeNodeElement extends SVGElement { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly operator: SVGAnimatedEnumeration; + readonly radiusX: SVGAnimatedNumber; + readonly radiusY: SVGAnimatedNumber; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly dx: SVGAnimatedNumber; + readonly dy: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface SVGFEPointLightElement extends SVGElement { + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly specularConstant: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface SVGFESpotLightElement extends SVGElement { + readonly limitingConeAngle: SVGAnimatedNumber; + readonly pointsAtX: SVGAnimatedNumber; + readonly pointsAtY: SVGAnimatedNumber; + readonly pointsAtZ: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly baseFrequencyX: SVGAnimatedNumber; + readonly baseFrequencyY: SVGAnimatedNumber; + readonly numOctaves: SVGAnimatedInteger; + readonly seed: SVGAnimatedNumber; + readonly stitchTiles: SVGAnimatedEnumeration; + readonly type: SVGAnimatedEnumeration; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + readonly filterResX: SVGAnimatedInteger; + readonly filterResY: SVGAnimatedInteger; + readonly filterUnits: SVGAnimatedEnumeration; + readonly height: SVGAnimatedLength; + readonly primitiveUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { + readonly gradientTransform: SVGAnimatedTransformList; + readonly gradientUnits: SVGAnimatedEnumeration; + readonly spreadMethod: SVGAnimatedEnumeration; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface SVGLength { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +interface SVGLengthList { + readonly numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + readonly markerHeight: SVGAnimatedLength; + readonly markerUnits: SVGAnimatedEnumeration; + readonly markerWidth: SVGAnimatedLength; + readonly orientAngle: SVGAnimatedAngle; + readonly orientType: SVGAnimatedEnumeration; + readonly refX: SVGAnimatedLength; + readonly refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; +} + +interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly maskContentUnits: SVGAnimatedEnumeration; + readonly maskUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +interface SVGMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + flipX(): SVGMatrix; + flipY(): SVGMatrix; + inverse(): SVGMatrix; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + rotate(angle: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + skewX(angle: number): SVGMatrix; + skewY(angle: number): SVGMatrix; + translate(x: number, y: number): SVGMatrix; +} + +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGNumberList { + readonly numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface SVGPathSeg { + readonly pathSegType: number; + readonly pathSegTypeAsLetter: string; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface SVGPathSegList { + readonly numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly patternContentUnits: SVGAnimatedEnumeration; + readonly patternTransform: SVGAnimatedTransformList; + readonly patternUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGPoint { + x: number; + y: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} + +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface SVGPointList { + readonly numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly fx: SVGAnimatedLength; + readonly fy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface SVGRect { + height: number; + width: number; + x: number; + y: number; +} + +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly height: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + contentScriptType: string; + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: (this: SVGSVGElement, ev: Event) => any; + onerror: (this: SVGSVGElement, ev: Event) => any; + onresize: (this: SVGSVGElement, ev: UIEvent) => any; + onscroll: (this: SVGSVGElement, ev: UIEvent) => any; + onunload: (this: SVGSVGElement, ev: Event) => any; + onzoom: (this: SVGSVGElement, ev: SVGZoomEvent) => any; + readonly pixelUnitToMillimeterX: number; + readonly pixelUnitToMillimeterY: number; + readonly screenPixelToMillimeterX: number; + readonly screenPixelToMillimeterY: number; + readonly viewport: SVGRect; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + pauseAnimations(): void; + setCurrentTime(seconds: number): void; + suspendRedraw(maxWaitMilliseconds: number): number; + unpauseAnimations(): void; + unsuspendRedraw(suspendHandleID: number): void; + unsuspendRedrawAll(): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + readonly lengthAdjust: SVGAnimatedEnumeration; + readonly textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + readonly method: SVGAnimatedEnumeration; + readonly spacing: SVGAnimatedEnumeration; + readonly startOffset: SVGAnimatedLength; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + readonly dx: SVGAnimatedLengthList; + readonly dy: SVGAnimatedLengthList; + readonly rotate: SVGAnimatedNumberList; + readonly x: SVGAnimatedLengthList; + readonly y: SVGAnimatedLengthList; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface SVGTransform { + readonly angle: number; + readonly matrix: SVGMatrix; + readonly type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +interface SVGTransformList { + readonly numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGUnitTypes { + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: SVGUnitTypes; + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + readonly animatedInstanceRoot: SVGElementInstance; + readonly height: SVGAnimatedLength; + readonly instanceRoot: SVGElementInstance; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface SVGZoomAndPan { + readonly zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +} + +interface SVGZoomEvent extends UIEvent { + readonly newScale: number; + readonly newTranslate: SVGPoint; + readonly previousScale: number; + readonly previousTranslate: SVGPoint; + readonly zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +} + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +} + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: string; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +} + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +} + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface StorageEvent extends Event { + readonly url: string; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +} + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface SubtleCrypto { + 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: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +} + +interface Text extends CharacterData { + readonly wholeText: string; + readonly assignedSlot: HTMLSlotElement | null; + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(): Text; +} + +interface TextEvent extends UIEvent { + readonly data: string; + readonly inputMethod: number; + readonly locale: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +interface TextMetrics { + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface TextTrackEventMap { + "cuechange": Event; + "error": ErrorEvent; + "load": Event; +} + +interface TextTrack extends EventTarget { + readonly activeCues: TextTrackCueList; + readonly cues: TextTrackCueList; + readonly inBandMetadataTrackDispatchType: string; + readonly kind: string; + readonly label: string; + readonly language: string; + mode: any; + oncuechange: (this: TextTrack, ev: Event) => any; + onerror: (this: TextTrack, ev: ErrorEvent) => any; + onload: (this: TextTrack, ev: Event) => any; + readonly readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; +} + +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: (this: TextTrackCue, ev: Event) => any; + onexit: (this: TextTrackCue, ev: Event) => any; + pauseOnExit: boolean; + startTime: number; + text: string; + readonly track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +} + +interface TextTrackCueList { + readonly length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + +interface TextTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; + item(index: number): TextTrack; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface TimeRanges { + readonly length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface Touch { + readonly clientX: number; + readonly clientY: number; + readonly identifier: number; + readonly pageX: number; + readonly pageY: number; + readonly screenX: number; + readonly screenY: number; + readonly target: EventTarget; +} + +declare var Touch: { + prototype: Touch; + new(): Touch; +} + +interface TouchEvent extends UIEvent { + readonly altKey: boolean; + readonly changedTouches: TouchList; + readonly ctrlKey: boolean; + readonly metaKey: boolean; + readonly shiftKey: boolean; + readonly targetTouches: TouchList; + readonly touches: TouchList; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(): TouchEvent; +} + +interface TouchList { + readonly length: number; + item(index: number): Touch | null; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +} + +interface TrackEvent extends Event { + readonly track: any; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface TransitionEvent extends Event { + readonly elapsedTime: number; + readonly propertyName: string; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface TreeWalker { + currentNode: Node; + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + firstChild(): Node; + lastChild(): Node; + nextNode(): Node; + nextSibling(): Node; + parentNode(): Node; + previousNode(): Node; + previousSibling(): Node; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface UIEvent extends Event { + readonly detail: number; + readonly view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(type: string, eventInitDict?: UIEventInit): UIEvent; +} + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + username: string; + toString(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string): URL; + createObjectURL(object: any, options?: ObjectURLOptions): string; + revokeObjectURL(url: string): void; +} + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; +} + +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +} + +interface ValidityState { + readonly badInput: boolean; + readonly customError: boolean; + readonly patternMismatch: boolean; + readonly rangeOverflow: boolean; + readonly rangeUnderflow: boolean; + readonly stepMismatch: boolean; + readonly tooLong: boolean; + readonly typeMismatch: boolean; + readonly valid: boolean; + readonly valueMissing: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface VideoPlaybackQuality { + readonly corruptedVideoFrames: number; + readonly creationTime: number; + readonly droppedVideoFrames: number; + readonly totalFrameDelay: number; + readonly totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +} + +interface VideoTrack { + readonly id: string; + kind: string; + readonly label: string; + language: string; + selected: boolean; + readonly sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +} + +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface VideoTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: VideoTrackList, ev: TrackEvent) => any; + onchange: (this: VideoTrackList, ev: Event) => any; + onremovetrack: (this: VideoTrackList, ev: TrackEvent) => any; + readonly selectedIndex: number; + getTrackById(id: string): VideoTrack | null; + item(index: number): VideoTrack; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +} + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +interface WaveShaperNode extends AudioNode { + curve: Float32Array | null; + oversample: string; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(): WaveShaperNode; +} + +interface WebGLActiveInfo { + readonly name: string; + readonly size: number; + readonly type: number; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +} + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +} + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(type: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +} + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +} + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +} + +interface WebGLRenderingContext { + readonly canvas: HTMLCanvasElement; + readonly drawingBufferHeight: number; + readonly drawingBufferWidth: number; + activeTexture(texture: number): void; + attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; + bindBuffer(target: number, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: number, texture: WebGLTexture | null): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + blendEquation(mode: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + blendFunc(sfactor: number, dfactor: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; + checkFramebufferStatus(target: number): number; + clear(mask: number): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + clearDepth(depth: number): void; + clearStencil(s: number): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compileShader(shader: WebGLShader | null): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: number): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: number): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: number): void; + depthMask(flag: boolean): void; + depthRange(zNear: number, zFar: number): void; + detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + disable(cap: number): void; + disableVertexAttribArray(index: number): void; + drawArrays(mode: number, first: number, count: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + enable(cap: number): void; + enableVertexAttribArray(index: number): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; + frontFace(mode: number): void; + generateMipmap(target: number): void; + getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram | null, name: string): number; + getBufferParameter(target: number, pname: number): any; + getContextAttributes(): WebGLContextAttributes; + getError(): number; + getExtension(name: string): any; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + getParameter(pname: number): any; + getProgramInfoLog(program: WebGLProgram | null): string | null; + getProgramParameter(program: WebGLProgram | null, pname: number): any; + getRenderbufferParameter(target: number, pname: number): any; + getShaderInfoLog(shader: WebGLShader | null): string | null; + getShaderParameter(shader: WebGLShader | null, pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader | null): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: number, pname: number): any; + getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; + getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: number, pname: number): any; + getVertexAttribOffset(index: number, pname: number): number; + hint(target: number, mode: number): void; + isBuffer(buffer: WebGLBuffer | null): boolean; + isContextLost(): boolean; + isEnabled(cap: number): boolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; + isProgram(program: WebGLProgram | null): boolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; + isShader(shader: WebGLShader | null): boolean; + isTexture(texture: WebGLTexture | null): boolean; + lineWidth(width: number): void; + linkProgram(program: WebGLProgram | null): void; + pixelStorei(pname: number, param: number): void; + polygonOffset(factor: number, units: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + sampleCoverage(value: number, invert: boolean): void; + scissor(x: number, y: number, width: number, height: number): void; + shaderSource(shader: WebGLShader | null, source: string): void; + stencilFunc(func: number, ref: number, mask: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + stencilMask(mask: number): void; + 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, 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, 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; + uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram | null): void; + vertexAttrib1f(indx: number, x: number): void; + vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib2f(indx: number, x: number, y: number): void; + vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + viewport(x: number, y: number, width: number, height: number): void; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly NO_ERROR: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB565: number; + readonly RGB5_A1: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TRIANGLES: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +} + +interface WebGLShaderPrecisionFormat { + readonly precision: number; + readonly rangeMax: number; + readonly rangeMin: number; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +} + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +} + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +} + +interface WebKitCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): WebKitCSSMatrix; + multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): WebKitCSSMatrix; + skewY(angle: number): WebKitCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): WebKitCSSMatrix; +} + +declare var WebKitCSSMatrix: { + prototype: WebKitCSSMatrix; + new(text?: string): WebKitCSSMatrix; +} + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +} + +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +} + +interface WheelEvent extends MouseEvent { + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + readonly wheelDelta: number; + readonly wheelDeltaX: number; + readonly wheelDeltaY: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +interface WindowEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "unload": Event; + "volumechange": Event; + "waiting": Event; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { + readonly applicationCache: ApplicationCache; + readonly clientInformation: Navigator; + readonly closed: boolean; + readonly crypto: Crypto; + defaultStatus: string; + readonly devicePixelRatio: number; + readonly doNotTrack: string; + readonly document: Document; + event: Event | undefined; + readonly external: External; + readonly frameElement: Element; + readonly frames: Window; + readonly history: History; + readonly innerHeight: number; + readonly innerWidth: number; + readonly length: number; + readonly location: Location; + readonly locationbar: BarProp; + readonly menubar: BarProp; + readonly msCredentials: MSCredentials; + name: string; + readonly navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (this: Window, ev: UIEvent) => any; + onafterprint: (this: Window, ev: Event) => any; + onbeforeprint: (this: Window, ev: Event) => any; + onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; + onblur: (this: Window, ev: FocusEvent) => any; + oncanplay: (this: Window, ev: Event) => any; + oncanplaythrough: (this: Window, ev: Event) => any; + onchange: (this: Window, ev: Event) => any; + onclick: (this: Window, ev: MouseEvent) => any; + oncompassneedscalibration: (this: Window, ev: Event) => any; + oncontextmenu: (this: Window, ev: PointerEvent) => any; + ondblclick: (this: Window, ev: MouseEvent) => any; + ondevicelight: (this: Window, ev: DeviceLightEvent) => any; + ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; + ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; + ondrag: (this: Window, ev: DragEvent) => any; + ondragend: (this: Window, ev: DragEvent) => any; + ondragenter: (this: Window, ev: DragEvent) => any; + ondragleave: (this: Window, ev: DragEvent) => any; + ondragover: (this: Window, ev: DragEvent) => any; + ondragstart: (this: Window, ev: DragEvent) => any; + ondrop: (this: Window, ev: DragEvent) => any; + ondurationchange: (this: Window, ev: Event) => any; + onemptied: (this: Window, ev: Event) => any; + onended: (this: Window, ev: MediaStreamErrorEvent) => any; + onerror: ErrorEventHandler; + onfocus: (this: Window, ev: FocusEvent) => any; + onhashchange: (this: Window, ev: HashChangeEvent) => any; + oninput: (this: Window, ev: Event) => any; + oninvalid: (this: Window, ev: Event) => any; + onkeydown: (this: Window, ev: KeyboardEvent) => any; + onkeypress: (this: Window, ev: KeyboardEvent) => any; + onkeyup: (this: Window, ev: KeyboardEvent) => any; + onload: (this: Window, ev: Event) => any; + onloadeddata: (this: Window, ev: Event) => any; + onloadedmetadata: (this: Window, ev: Event) => any; + onloadstart: (this: Window, ev: Event) => any; + onmessage: (this: Window, ev: MessageEvent) => any; + onmousedown: (this: Window, ev: MouseEvent) => any; + onmouseenter: (this: Window, ev: MouseEvent) => any; + onmouseleave: (this: Window, ev: MouseEvent) => any; + onmousemove: (this: Window, ev: MouseEvent) => any; + onmouseout: (this: Window, ev: MouseEvent) => any; + onmouseover: (this: Window, ev: MouseEvent) => any; + onmouseup: (this: Window, ev: MouseEvent) => any; + onmousewheel: (this: Window, ev: WheelEvent) => any; + onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; + onmsgestureend: (this: Window, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; + onmspointercancel: (this: Window, ev: MSPointerEvent) => any; + onmspointerdown: (this: Window, ev: MSPointerEvent) => any; + onmspointerenter: (this: Window, ev: MSPointerEvent) => any; + onmspointerleave: (this: Window, ev: MSPointerEvent) => any; + onmspointermove: (this: Window, ev: MSPointerEvent) => any; + onmspointerout: (this: Window, ev: MSPointerEvent) => any; + onmspointerover: (this: Window, ev: MSPointerEvent) => any; + onmspointerup: (this: Window, ev: MSPointerEvent) => any; + onoffline: (this: Window, ev: Event) => any; + ononline: (this: Window, ev: Event) => any; + onorientationchange: (this: Window, ev: Event) => any; + onpagehide: (this: Window, ev: PageTransitionEvent) => any; + onpageshow: (this: Window, ev: PageTransitionEvent) => any; + onpause: (this: Window, ev: Event) => any; + onplay: (this: Window, ev: Event) => any; + onplaying: (this: Window, ev: Event) => any; + onpopstate: (this: Window, ev: PopStateEvent) => any; + onprogress: (this: Window, ev: ProgressEvent) => any; + onratechange: (this: Window, ev: Event) => any; + onreadystatechange: (this: Window, ev: ProgressEvent) => any; + onreset: (this: Window, ev: Event) => any; + onresize: (this: Window, ev: UIEvent) => any; + onscroll: (this: Window, ev: UIEvent) => any; + onseeked: (this: Window, ev: Event) => any; + onseeking: (this: Window, ev: Event) => any; + onselect: (this: Window, ev: UIEvent) => any; + onstalled: (this: Window, ev: Event) => any; + onstorage: (this: Window, ev: StorageEvent) => any; + onsubmit: (this: Window, ev: Event) => any; + onsuspend: (this: Window, ev: Event) => any; + ontimeupdate: (this: Window, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onunload: (this: Window, ev: Event) => any; + onvolumechange: (this: Window, ev: Event) => any; + onwaiting: (this: Window, ev: Event) => any; + opener: any; + orientation: string | number; + readonly outerHeight: number; + readonly outerWidth: number; + readonly pageXOffset: number; + readonly pageYOffset: number; + readonly parent: Window; + readonly performance: Performance; + readonly personalbar: BarProp; + readonly screen: Screen; + readonly screenLeft: number; + readonly screenTop: number; + readonly screenX: number; + readonly screenY: number; + readonly scrollX: number; + readonly scrollY: number; + readonly scrollbars: BarProp; + readonly self: Window; + status: string; + readonly statusbar: BarProp; + readonly styleMedia: StyleMedia; + readonly toolbar: BarProp; + readonly top: Window; + readonly window: Window; + URL: typeof URL; + Blob: typeof Blob; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + matchMedia(mediaQuery: string): MediaQueryList; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: any, targetOrigin: string, transfer?: any[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + webkitCancelAnimationFrame(handle: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Window: { + prototype: Window; + new(): Window; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (this: Worker, ev: MessageEvent) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +} + +interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: string; + readonly responseXML: any; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + msCaching?: string; + readonly responseURL: string; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: Document): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + create(): XMLHttpRequest; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +} + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +} + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +} + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +} + +interface XPathResult { + readonly booleanValue: boolean; + readonly invalidIteratorState: boolean; + readonly numberValue: number; + readonly resultType: number; + readonly singleNodeValue: Node; + readonly snapshotLength: number; + readonly stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +} + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface CanvasPathMethods { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface ChildNode { + remove(): void; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DocumentEvent { + createEvent(eventInterface:"AnimationEvent"): AnimationEvent; + createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; + createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface:"CloseEvent"): CloseEvent; + createEvent(eventInterface:"CommandEvent"): CommandEvent; + createEvent(eventInterface:"CompositionEvent"): CompositionEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; + createEvent(eventInterface:"DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface:"DragEvent"): DragEvent; + createEvent(eventInterface:"ErrorEvent"): ErrorEvent; + createEvent(eventInterface:"Event"): Event; + createEvent(eventInterface:"Events"): Event; + createEvent(eventInterface:"FocusEvent"): FocusEvent; + createEvent(eventInterface:"GamepadEvent"): GamepadEvent; + createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface:"ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface:"MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface:"MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface:"MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface:"MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface:"MessageEvent"): MessageEvent; + createEvent(eventInterface:"MouseEvent"): MouseEvent; + createEvent(eventInterface:"MouseEvents"): MouseEvent; + createEvent(eventInterface:"MutationEvent"): MutationEvent; + createEvent(eventInterface:"MutationEvents"): MutationEvent; + createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface:"NavigationEvent"): NavigationEvent; + createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface:"OverflowEvent"): OverflowEvent; + createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface:"PointerEvent"): PointerEvent; + createEvent(eventInterface:"PopStateEvent"): PopStateEvent; + createEvent(eventInterface:"ProgressEvent"): ProgressEvent; + createEvent(eventInterface:"RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface:"RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface:"RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface:"RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface:"RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface:"RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface:"StorageEvent"): StorageEvent; + createEvent(eventInterface:"TextEvent"): TextEvent; + createEvent(eventInterface:"TouchEvent"): TouchEvent; + createEvent(eventInterface:"TrackEvent"): TrackEvent; + createEvent(eventInterface:"TransitionEvent"): TransitionEvent; + createEvent(eventInterface:"UIEvent"): UIEvent; + createEvent(eventInterface:"UIEvents"): UIEvent; + createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface:"WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly nextElementSibling: Element; + readonly previousElementSibling: Element; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + onpointercancel: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerdown: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerenter: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerleave: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointermove: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerout: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; +} + +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + +interface LinkStyle { + readonly sheet: StyleSheet; +} + +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSBaseReader { + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; + readonly readyState: number; + readonly result: any; + abort(): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface NavigatorContentUtils { +} + +interface NavigatorGeolocation { + readonly geolocation: Geolocation; +} + +interface NavigatorID { + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + +interface NodeSelector { + querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: string): Element | null; + querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: string): NodeListOf; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface SVGAnimatedPathData { + readonly pathSegList: SVGPathSegList; +} + +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + +interface SVGExternalResourcesRequired { + readonly externalResourcesRequired: SVGAnimatedBoolean; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + readonly height: SVGAnimatedLength; + readonly result: SVGAnimatedString; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly viewBox: SVGAnimatedRect; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface SVGLocatable { + readonly farthestViewportElement: SVGElement; + readonly nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; + getTransformToElement(element: SVGElement): SVGMatrix; +} + +interface SVGStylable { + className: any; + readonly style: CSSStyleDeclaration; +} + +interface SVGTests { + readonly requiredExtensions: SVGStringList; + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface SVGTransformable extends SVGLocatable { + readonly transform: SVGAnimatedTransformList; +} + +interface SVGURIReference { + readonly href: SVGAnimatedString; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +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(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + 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; + [index: number]: TNode; +} + +interface HTMLCollectionOf extends HTMLCollection { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag { + type?: string; + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface MessageEventInit extends EventInit { + data?: any; + origin?: string; + lastEventId?: string; + channel?: string; + source?: any; + ports?: MessagePort[]; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +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 { + namedCurve: 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; +} + +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element; + readonly lastElementChild: Element; + readonly childElementCount: number; +} + +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly stylesheets: StyleSheetList; + getSelection(): Selection | null; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; +} + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + mode: 'open'|'closed'; + delegatesFocus?: boolean; +} + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface ErrorEventHandler { + (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSLaunchUriCallback { + (): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface ForEachCallback { + (keyId: any, status: string): void; +} +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "audio": HTMLAudioElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "del": HTMLModElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "font": HTMLFontElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nextid": HTMLUnknownElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "script": HTMLScriptElement; + "select": HTMLSelectElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "style": HTMLStyleElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "ul": HTMLUListElement; + "video": HTMLVideoElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "circle": SVGCircleElement; + "cite": HTMLElement; + "clippath": SVGClipPathElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "defs": SVGDefsElement; + "del": HTMLModElement; + "desc": SVGDescElement; + "dfn": HTMLElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "ellipse": SVGEllipseElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "feblend": SVGFEBlendElement; + "fecolormatrix": SVGFEColorMatrixElement; + "fecomponenttransfer": SVGFEComponentTransferElement; + "fecomposite": SVGFECompositeElement; + "feconvolvematrix": SVGFEConvolveMatrixElement; + "fediffuselighting": SVGFEDiffuseLightingElement; + "fedisplacementmap": SVGFEDisplacementMapElement; + "fedistantlight": SVGFEDistantLightElement; + "feflood": SVGFEFloodElement; + "fefunca": SVGFEFuncAElement; + "fefuncb": SVGFEFuncBElement; + "fefuncg": SVGFEFuncGElement; + "fefuncr": SVGFEFuncRElement; + "fegaussianblur": SVGFEGaussianBlurElement; + "feimage": SVGFEImageElement; + "femerge": SVGFEMergeElement; + "femergenode": SVGFEMergeNodeElement; + "femorphology": SVGFEMorphologyElement; + "feoffset": SVGFEOffsetElement; + "fepointlight": SVGFEPointLightElement; + "fespecularlighting": SVGFESpecularLightingElement; + "fespotlight": SVGFESpotLightElement; + "fetile": SVGFETileElement; + "feturbulence": SVGFETurbulenceElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "filter": SVGFilterElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "foreignobject": SVGForeignObjectElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "g": SVGGElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "image": SVGImageElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "line": SVGLineElement; + "lineargradient": SVGLinearGradientElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marker": SVGMarkerElement; + "marquee": HTMLMarqueeElement; + "mask": SVGMaskElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "metadata": SVGMetadataElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "picture": HTMLPictureElement; + "plaintext": HTMLElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "radialgradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "stop": SVGStopElement; + "strike": HTMLElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "text": SVGTextElement; + "textpath": SVGTextPathElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "tspan": SVGTSpanElement; + "tt": HTMLElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "use": SVGUseElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "view": SVGViewElement; + "wbr": HTMLElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementListTagNameMap { + "a": NodeListOf; + "abbr": NodeListOf; + "acronym": NodeListOf; + "address": NodeListOf; + "applet": NodeListOf; + "area": NodeListOf; + "article": NodeListOf; + "aside": NodeListOf; + "audio": NodeListOf; + "b": NodeListOf; + "base": NodeListOf; + "basefont": NodeListOf; + "bdo": NodeListOf; + "big": NodeListOf; + "blockquote": NodeListOf; + "body": NodeListOf; + "br": NodeListOf; + "button": NodeListOf; + "canvas": NodeListOf; + "caption": NodeListOf; + "center": NodeListOf; + "circle": NodeListOf; + "cite": NodeListOf; + "clippath": NodeListOf; + "code": NodeListOf; + "col": NodeListOf; + "colgroup": NodeListOf; + "datalist": NodeListOf; + "dd": NodeListOf; + "defs": NodeListOf; + "del": NodeListOf; + "desc": NodeListOf; + "dfn": NodeListOf; + "dir": NodeListOf; + "div": NodeListOf; + "dl": NodeListOf; + "dt": NodeListOf; + "ellipse": NodeListOf; + "em": NodeListOf; + "embed": NodeListOf; + "feblend": NodeListOf; + "fecolormatrix": NodeListOf; + "fecomponenttransfer": NodeListOf; + "fecomposite": NodeListOf; + "feconvolvematrix": NodeListOf; + "fediffuselighting": NodeListOf; + "fedisplacementmap": NodeListOf; + "fedistantlight": NodeListOf; + "feflood": NodeListOf; + "fefunca": NodeListOf; + "fefuncb": NodeListOf; + "fefuncg": NodeListOf; + "fefuncr": NodeListOf; + "fegaussianblur": NodeListOf; + "feimage": NodeListOf; + "femerge": NodeListOf; + "femergenode": NodeListOf; + "femorphology": NodeListOf; + "feoffset": NodeListOf; + "fepointlight": NodeListOf; + "fespecularlighting": NodeListOf; + "fespotlight": NodeListOf; + "fetile": NodeListOf; + "feturbulence": NodeListOf; + "fieldset": NodeListOf; + "figcaption": NodeListOf; + "figure": NodeListOf; + "filter": NodeListOf; + "font": NodeListOf; + "footer": NodeListOf; + "foreignobject": NodeListOf; + "form": NodeListOf; + "frame": NodeListOf; + "frameset": NodeListOf; + "g": NodeListOf; + "h1": NodeListOf; + "h2": NodeListOf; + "h3": NodeListOf; + "h4": NodeListOf; + "h5": NodeListOf; + "h6": NodeListOf; + "head": NodeListOf; + "header": NodeListOf; + "hgroup": NodeListOf; + "hr": NodeListOf; + "html": NodeListOf; + "i": NodeListOf; + "iframe": NodeListOf; + "image": NodeListOf; + "img": NodeListOf; + "input": NodeListOf; + "ins": NodeListOf; + "isindex": NodeListOf; + "kbd": NodeListOf; + "keygen": NodeListOf; + "label": NodeListOf; + "legend": NodeListOf; + "li": NodeListOf; + "line": NodeListOf; + "lineargradient": NodeListOf; + "link": NodeListOf; + "listing": NodeListOf; + "map": NodeListOf; + "mark": NodeListOf; + "marker": NodeListOf; + "marquee": NodeListOf; + "mask": NodeListOf; + "menu": NodeListOf; + "meta": NodeListOf; + "metadata": NodeListOf; + "meter": NodeListOf; + "nav": NodeListOf; + "nextid": NodeListOf; + "nobr": NodeListOf; + "noframes": NodeListOf; + "noscript": NodeListOf; + "object": NodeListOf; + "ol": NodeListOf; + "optgroup": NodeListOf; + "option": NodeListOf; + "p": NodeListOf; + "param": NodeListOf; + "path": NodeListOf; + "pattern": NodeListOf; + "picture": NodeListOf; + "plaintext": NodeListOf; + "polygon": NodeListOf; + "polyline": NodeListOf; + "pre": NodeListOf; + "progress": NodeListOf; + "q": NodeListOf; + "radialgradient": NodeListOf; + "rect": NodeListOf; + "rt": NodeListOf; + "ruby": NodeListOf; + "s": NodeListOf; + "samp": NodeListOf; + "script": NodeListOf; + "section": NodeListOf; + "select": NodeListOf; + "small": NodeListOf; + "source": NodeListOf; + "span": NodeListOf; + "stop": NodeListOf; + "strike": NodeListOf; + "strong": NodeListOf; + "style": NodeListOf; + "sub": NodeListOf; + "sup": NodeListOf; + "svg": NodeListOf; + "switch": NodeListOf; + "symbol": NodeListOf; + "table": NodeListOf; + "tbody": NodeListOf; + "td": NodeListOf; + "template": NodeListOf; + "text": NodeListOf; + "textpath": NodeListOf; + "textarea": NodeListOf; + "tfoot": NodeListOf; + "th": NodeListOf; + "thead": NodeListOf; + "title": NodeListOf; + "tr": NodeListOf; + "track": NodeListOf; + "tspan": NodeListOf; + "tt": NodeListOf; + "u": NodeListOf; + "ul": NodeListOf; + "use": NodeListOf; + "var": NodeListOf; + "video": NodeListOf; + "view": NodeListOf; + "wbr": NodeListOf; + "x-ms-webview": NodeListOf; + "xmp": NodeListOf; +} + +declare var Audio: {new(src?: string): HTMLAudioElement; }; +declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var applicationCache: ApplicationCache; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var doNotTrack: string; +declare var document: Document; +declare var event: Event | undefined; +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msCredentials: MSCredentials; +declare const name: never; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var onabort: (this: Window, ev: UIEvent) => any; +declare var onafterprint: (this: Window, ev: Event) => any; +declare var onbeforeprint: (this: Window, ev: Event) => any; +declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; +declare var onblur: (this: Window, ev: FocusEvent) => any; +declare var oncanplay: (this: Window, ev: Event) => any; +declare var oncanplaythrough: (this: Window, ev: Event) => any; +declare var onchange: (this: Window, ev: Event) => any; +declare var onclick: (this: Window, ev: MouseEvent) => any; +declare var oncompassneedscalibration: (this: Window, ev: Event) => any; +declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; +declare var ondblclick: (this: Window, ev: MouseEvent) => any; +declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; +declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; +declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; +declare var ondrag: (this: Window, ev: DragEvent) => any; +declare var ondragend: (this: Window, ev: DragEvent) => any; +declare var ondragenter: (this: Window, ev: DragEvent) => any; +declare var ondragleave: (this: Window, ev: DragEvent) => any; +declare var ondragover: (this: Window, ev: DragEvent) => any; +declare var ondragstart: (this: Window, ev: DragEvent) => any; +declare var ondrop: (this: Window, ev: DragEvent) => any; +declare var ondurationchange: (this: Window, ev: Event) => any; +declare var onemptied: (this: Window, ev: Event) => any; +declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; +declare var onerror: ErrorEventHandler; +declare var onfocus: (this: Window, ev: FocusEvent) => any; +declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; +declare var oninput: (this: Window, ev: Event) => any; +declare var oninvalid: (this: Window, ev: Event) => any; +declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; +declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; +declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; +declare var onload: (this: Window, ev: Event) => any; +declare var onloadeddata: (this: Window, ev: Event) => any; +declare var onloadedmetadata: (this: Window, ev: Event) => any; +declare var onloadstart: (this: Window, ev: Event) => any; +declare var onmessage: (this: Window, ev: MessageEvent) => any; +declare var onmousedown: (this: Window, ev: MouseEvent) => any; +declare var onmouseenter: (this: Window, ev: MouseEvent) => any; +declare var onmouseleave: (this: Window, ev: MouseEvent) => any; +declare var onmousemove: (this: Window, ev: MouseEvent) => any; +declare var onmouseout: (this: Window, ev: MouseEvent) => any; +declare var onmouseover: (this: Window, ev: MouseEvent) => any; +declare var onmouseup: (this: Window, ev: MouseEvent) => any; +declare var onmousewheel: (this: Window, ev: WheelEvent) => any; +declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; +declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; +declare var onoffline: (this: Window, ev: Event) => any; +declare var ononline: (this: Window, ev: Event) => any; +declare var onorientationchange: (this: Window, ev: Event) => any; +declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; +declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; +declare var onpause: (this: Window, ev: Event) => any; +declare var onplay: (this: Window, ev: Event) => any; +declare var onplaying: (this: Window, ev: Event) => any; +declare var onpopstate: (this: Window, ev: PopStateEvent) => any; +declare var onprogress: (this: Window, ev: ProgressEvent) => any; +declare var onratechange: (this: Window, ev: Event) => any; +declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; +declare var onreset: (this: Window, ev: Event) => any; +declare var onresize: (this: Window, ev: UIEvent) => any; +declare var onscroll: (this: Window, ev: UIEvent) => any; +declare var onseeked: (this: Window, ev: Event) => any; +declare var onseeking: (this: Window, ev: Event) => any; +declare var onselect: (this: Window, ev: UIEvent) => any; +declare var onstalled: (this: Window, ev: Event) => any; +declare var onstorage: (this: Window, ev: StorageEvent) => any; +declare var onsubmit: (this: Window, ev: Event) => any; +declare var onsuspend: (this: Window, ev: Event) => any; +declare var ontimeupdate: (this: Window, ev: Event) => any; +declare var ontouchcancel: (ev: TouchEvent) => any; +declare var ontouchend: (ev: TouchEvent) => any; +declare var ontouchmove: (ev: TouchEvent) => any; +declare var ontouchstart: (ev: TouchEvent) => any; +declare var onunload: (this: Window, ev: Event) => any; +declare var onvolumechange: (this: Window, ev: Event) => any; +declare var onwaiting: (this: Window, ev: Event) => any; +declare var opener: any; +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollX: number; +declare var scrollY: number; +declare var scrollbars: BarProp; +declare var self: Window; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function moveBy(x?: number, y?: number): void; +declare function moveTo(x?: number, y?: number): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string | null; +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x?: number, y?: number): void; +declare function resizeTo(x?: number, y?: number): void; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare function webkitCancelAnimationFrame(handle: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; +declare function toString(): string; +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(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; +declare var onpointercancel: (this: Window, ev: PointerEvent) => any; +declare var onpointerdown: (this: Window, ev: PointerEvent) => any; +declare var onpointerenter: (this: Window, ev: PointerEvent) => any; +declare var onpointerleave: (this: Window, ev: PointerEvent) => any; +declare var onpointermove: (this: Window, ev: PointerEvent) => any; +declare var onpointerout: (this: Window, ev: PointerEvent) => any; +declare var onpointerover: (this: Window, ev: PointerEvent) => any; +declare var onpointerup: (this: Window, ev: PointerEvent) => any; +declare var onwheel: (this: Window, ev: WheelEvent) => any; +declare var indexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +type AAGUID = string; +type AlgorithmIdentifier = string | Algorithm; +type ConstrainBoolean = boolean | ConstrainBooleanParameters; +type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; +type ConstrainDouble = number | ConstrainDoubleRange; +type ConstrainLong = number | ConstrainLongRange; +type CryptoOperationData = ArrayBufferView; +type GLbitfield = number; +type GLboolean = boolean; +type GLbyte = number; +type GLclampf = number; +type GLenum = number; +type GLfloat = number; +type GLint = number; +type GLintptr = number; +type GLshort = number; +type GLsizei = number; +type GLsizeiptr = number; +type GLubyte = number; +type GLuint = number; +type GLushort = number; +type IDBKeyPath = string; +type KeyFormat = string; +type KeyType = string; +type KeyUsage = string; +type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; +type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; +type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; +type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; +type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// These are only available in a Web Worker +declare function importScripts(...urls: string[]): void; + + + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (collection: any): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: any): VBArray; + new (safeArray: any): VBArray; +} + +declare var VBArray: VBArrayConstructor; + +/** + * Automation date (VT_DATE) + */ +interface VarDate { } + +interface DateConstructor { + new (vd: VarDate): Date; +} + +interface Date { + getVarDate: () => VarDate; +} + + +/// + +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator +} diff --git a/lib/lib.scripthost.d.ts b/lib/lib.scripthost.d.ts index b4e52a342f1..2be78dec994 100644 --- a/lib/lib.scripthost.d.ts +++ b/lib/lib.scripthost.d.ts @@ -1,307 +1,311 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// - - -///////////////////////////// -/// Windows Script Host APIS -///////////////////////////// - - -interface ActiveXObject { - new (s: string): any; -} -declare var ActiveXObject: ActiveXObject; - -interface ITextWriter { - Write(s: string): void; - WriteLine(s: string): void; - Close(): void; -} - -interface TextStreamBase { - /** - * The column number of the current character position in an input stream. - */ - Column: number; - - /** - * The current line number in an input stream. - */ - Line: number; - - /** - * Closes a text stream. - * It is not necessary to close standard streams; they close automatically when the process ends. If - * you close a standard stream, be aware that any other pointers to that standard stream become invalid. - */ - Close(): void; -} - -interface TextStreamWriter extends TextStreamBase { - /** - * Sends a string to an output stream. - */ - Write(s: string): void; - - /** - * Sends a specified number of blank lines (newline characters) to an output stream. - */ - WriteBlankLines(intLines: number): void; - - /** - * Sends a string followed by a newline character to an output stream. - */ - WriteLine(s: string): void; -} - -interface TextStreamReader extends TextStreamBase { - /** - * Returns a specified number of characters from an input stream, starting at the current pointer position. - * Does not return until the ENTER key is pressed. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - Read(characters: number): string; - - /** - * Returns all characters from an input stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadAll(): string; - - /** - * Returns an entire line from an input stream. - * Although this method extracts the newline character, it does not add it to the returned string. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - */ - ReadLine(): string; - - /** - * Skips a specified number of characters when reading from an input text stream. - * Can only be used on a stream in reading mode; causes an error in writing or appending mode. - * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) - */ - Skip(characters: number): void; - - /** - * Skips the next line when reading from an input text stream. - * Can only be used on a stream in reading mode, not writing or appending mode. - */ - SkipLine(): void; - - /** - * Indicates whether the stream pointer position is at the end of a line. - */ - AtEndOfLine: boolean; - - /** - * Indicates whether the stream pointer position is at the end of a stream. - */ - AtEndOfStream: boolean; -} - -declare var WScript: { - /** - * Outputs text to either a message box (under WScript.exe) or the command console window followed by - * a newline (under CScript.exe). - */ - Echo(s: any): void; - - /** - * Exposes the write-only error output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdErr: TextStreamWriter; - - /** - * Exposes the write-only output stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdOut: TextStreamWriter; - Arguments: { length: number; Item(n: number): string; }; - - /** - * The full path of the currently running script. - */ - ScriptFullName: string; - - /** - * Forces the script to stop immediately, with an optional exit code. - */ - Quit(exitCode?: number): number; - - /** - * The Windows Script Host build version number. - */ - BuildVersion: number; - - /** - * Fully qualified path of the host executable. - */ - FullName: string; - - /** - * Gets/sets the script mode - interactive(true) or batch(false). - */ - Interactive: boolean; - - /** - * The name of the host executable (WScript.exe or CScript.exe). - */ - Name: string; - - /** - * Path of the directory containing the host executable. - */ - Path: string; - - /** - * The filename of the currently running script. - */ - ScriptName: string; - - /** - * Exposes the read-only input stream for the current script. - * Can be accessed only while using CScript.exe. - */ - StdIn: TextStreamReader; - - /** - * Windows Script Host version - */ - Version: string; - - /** - * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. - */ - ConnectObject(objEventSource: any, strPrefix: string): void; - - /** - * Creates a COM object. - * @param strProgiID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - CreateObject(strProgID: string, strPrefix?: string): any; - - /** - * Disconnects a COM object from its event sources. - */ - DisconnectObject(obj: any): void; - - /** - * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. - * @param strPathname Fully qualified path to the file containing the object persisted to disk. - * For objects in memory, pass a zero-length string. - * @param strProgID - * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. - */ - GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; - - /** - * Suspends script execution for a specified length of time, then continues execution. - * @param intTime Interval (in milliseconds) to suspend script execution. - */ - Sleep(intTime: number): void; -}; - -/** - * Allows enumerating over a COM collection, which may not have indexed item access. - */ -interface Enumerator { - /** - * Returns true if the current item is the last one in the collection, or the collection is empty, - * or the current item is undefined. - */ - atEnd(): boolean; - - /** - * Returns the current item in the collection - */ - item(): T; - - /** - * Resets the current item in the collection to the first item. If there are no items in the collection, - * the current item is set to undefined. - */ - moveFirst(): void; - - /** - * Moves the current item to the next item in the collection. If the enumerator is at the end of - * the collection or the collection is empty, the current item is set to undefined. - */ - moveNext(): void; -} - -interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; -} - -declare var Enumerator: EnumeratorConstructor; - -/** - * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. - */ -interface VBArray { - /** - * Returns the number of dimensions (1-based). - */ - dimensions(): number; - - /** - * Takes an index for each dimension in the array, and returns the item at the corresponding location. - */ - getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; - - /** - * Returns the smallest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - lbound(dimension?: number): number; - - /** - * Returns the largest available index for a given dimension. - * @param dimension 1-based dimension (defaults to 1) - */ - ubound(dimension?: number): number; - - /** - * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, - * each successive dimension is appended to the end of the array. - * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] - */ - toArray(): T[]; -} - -interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; -} - -declare var VBArray: VBArrayConstructor; - -/** - * Automation date (VT_DATE) - */ -interface VarDate { } - -interface DateConstructor { - new (vd: VarDate): Date; -} - -interface Date { - getVarDate: () => VarDate; -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (collection: any): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: any): VBArray; + new (safeArray: any): VBArray; +} + +declare var VBArray: VBArrayConstructor; + +/** + * Automation date (VT_DATE) + */ +interface VarDate { } + +interface DateConstructor { + new (vd: VarDate): Date; +} + +interface Date { + getVarDate: () => VarDate; +} diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 5b35d820dfe..4ee2566928d 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -1,1220 +1,1274 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// - -///////////////////////////// -/// IE Worker APIs -///////////////////////////// - -interface Algorithm { - name: string; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; -} - -interface IDBIndexParameters { - multiEntry?: boolean; - unique?: boolean; -} - -interface IDBObjectStoreParameters { - autoIncrement?: boolean; - keyPath?: IDBKeyPath; -} - -interface KeyAlgorithm { - name?: string; -} - -interface EventListener { - (evt: Event): void; -} - -interface AudioBuffer { - readonly duration: number; - readonly length: number; - readonly numberOfChannels: number; - readonly sampleRate: number; - copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; - copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; - getChannelData(channel: number): Float32Array; -} - -declare var AudioBuffer: { - prototype: AudioBuffer; - new(): AudioBuffer; -} - -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -declare var Blob: { - prototype: Blob; - new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} - -interface CloseEvent extends Event { - readonly code: number; - readonly reason: string; - readonly wasClean: boolean; - initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; -} - -declare var CloseEvent: { - prototype: CloseEvent; - new(): CloseEvent; -} - -interface Console { - assert(test?: boolean, message?: string, ...optionalParams: any[]): void; - clear(): void; - count(countTitle?: string): void; - debug(message?: string, ...optionalParams: any[]): void; - dir(value?: any, ...optionalParams: any[]): void; - dirxml(value: any): void; - error(message?: any, ...optionalParams: any[]): void; - exception(message?: string, ...optionalParams: any[]): void; - group(groupTitle?: string): void; - groupCollapsed(groupTitle?: string): void; - groupEnd(): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: any): boolean; - profile(reportName?: string): void; - profileEnd(): void; - select(element: any): void; - table(...data: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; -} - -declare var Console: { - prototype: Console; - new(): Console; -} - -interface Coordinates { - readonly accuracy: number; - readonly altitude: number | null; - readonly altitudeAccuracy: number | null; - readonly heading: number | null; - readonly latitude: number; - readonly longitude: number; - readonly speed: number | null; -} - -declare var Coordinates: { - prototype: 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; -} - -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface DOMException { - readonly code: number; - readonly message: string; - readonly name: string; - toString(): string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly PARSE_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SERIALIZE_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; -} - -interface DOMStringList { - readonly length: number; - contains(str: string): boolean; - item(index: number): string | null; - [index: number]: string; -} - -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface ErrorEvent extends Event { - readonly colno: number; - readonly error: any; - readonly filename: string; - readonly lineno: number; - readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; -} - -declare var ErrorEvent: { - prototype: ErrorEvent; - new(): ErrorEvent; -} - -interface Event { - readonly bubbles: boolean; - cancelBubble: boolean; - readonly cancelable: boolean; - readonly currentTarget: EventTarget; - readonly defaultPrevented: boolean; - readonly eventPhase: number; - readonly isTrusted: boolean; - returnValue: boolean; - readonly srcElement: any; - readonly target: EventTarget; - readonly timeStamp: number; - readonly type: string; - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; - preventDefault(): void; - stopImmediatePropagation(): void; - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -declare var Event: { - prototype: Event; - new(type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; -} - -interface EventTarget { - addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var EventTarget: { - prototype: EventTarget; - new(): EventTarget; -} - -interface File extends Blob { - readonly lastModifiedDate: any; - readonly name: string; - readonly webkitRelativePath: string; -} - -declare var File: { - prototype: File; - new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; -} - -interface FileList { - readonly length: number; - item(index: number): File; - [index: number]: File; -} - -declare var FileList: { - prototype: FileList; - new(): FileList; -} - -interface FileReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(blob: Blob): void; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var FileReader: { - prototype: FileReader; - new(): FileReader; -} - -interface IDBCursor { - readonly direction: string; - key: IDBKeyRange | IDBValidKey; - readonly primaryKey: any; - source: IDBObjectStore | IDBIndex; - advance(count: number): void; - continue(key?: IDBKeyRange | IDBValidKey): void; - delete(): IDBRequest; - update(value: any): IDBRequest; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -declare var IDBCursor: { - prototype: IDBCursor; - new(): IDBCursor; - readonly NEXT: string; - readonly NEXT_NO_DUPLICATE: string; - readonly PREV: string; - readonly PREV_NO_DUPLICATE: string; -} - -interface IDBCursorWithValue extends IDBCursor { - readonly value: any; -} - -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new(): IDBCursorWithValue; -} - -interface IDBDatabase extends EventTarget { - readonly name: string; - readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - version: number; - onversionchange: (ev: IDBVersionChangeEvent) => any; - close(): void; - createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; - deleteObjectStore(name: string): void; - transaction(storeNames: string | string[], mode?: string): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBDatabase: { - prototype: IDBDatabase; - new(): IDBDatabase; -} - -interface IDBFactory { - cmp(first: any, second: any): number; - deleteDatabase(name: string): IDBOpenDBRequest; - open(name: string, version?: number): IDBOpenDBRequest; -} - -declare var IDBFactory: { - prototype: IDBFactory; - new(): IDBFactory; -} - -interface IDBIndex { - keyPath: string | string[]; - readonly name: string; - readonly objectStore: IDBObjectStore; - readonly unique: boolean; - multiEntry: boolean; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - get(key: IDBKeyRange | IDBValidKey): IDBRequest; - getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; -} - -declare var IDBIndex: { - prototype: IDBIndex; - new(): IDBIndex; -} - -interface IDBKeyRange { - readonly lower: any; - readonly lowerOpen: boolean; - readonly upper: any; - readonly upperOpen: boolean; -} - -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new(): IDBKeyRange; - bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; - lowerBound(lower: any, open?: boolean): IDBKeyRange; - only(value: any): IDBKeyRange; - upperBound(upper: any, open?: boolean): IDBKeyRange; -} - -interface IDBObjectStore { - readonly indexNames: DOMStringList; - keyPath: string | string[]; - readonly name: string; - readonly transaction: IDBTransaction; - autoIncrement: boolean; - add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; - clear(): IDBRequest; - count(key?: IDBKeyRange | IDBValidKey): IDBRequest; - createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; - delete(key: IDBKeyRange | IDBValidKey): IDBRequest; - deleteIndex(indexName: string): void; - get(key: any): IDBRequest; - index(name: string): IDBIndex; - openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; - put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; -} - -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new(): IDBObjectStore; -} - -interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new(): IDBOpenDBRequest; -} - -interface IDBRequest extends EventTarget { - readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; - readonly readyState: string; - readonly result: any; - source: IDBObjectStore | IDBIndex | IDBCursor; - readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBRequest: { - prototype: IDBRequest; - new(): IDBRequest; -} - -interface IDBTransaction extends EventTarget { - readonly db: IDBDatabase; - readonly error: DOMError; - readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - abort(): void; - objectStore(name: string): IDBObjectStore; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var IDBTransaction: { - prototype: IDBTransaction; - new(): IDBTransaction; - readonly READ_ONLY: string; - readonly READ_WRITE: string; - readonly VERSION_CHANGE: string; -} - -interface IDBVersionChangeEvent extends Event { - readonly newVersion: number | null; - readonly oldVersion: number; -} - -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new(): IDBVersionChangeEvent; -} - -interface ImageData { - data: Uint8ClampedArray; - readonly height: number; - readonly width: number; -} - -declare var ImageData: { - prototype: ImageData; - new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; -} - -interface MSApp { - clearTemporaryWebDataAsync(): MSAppAsyncOperation; - createBlobFromRandomAccessStream(type: string, seeker: any): Blob; - createDataPackage(object: any): any; - createDataPackageFromSelection(): any; - createFileFromStorageFile(storageFile: any): File; - createStreamFromInputStream(type: string, inputStream: any): MSStream; - execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; - execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; - getCurrentPriority(): string; - getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; - getViewId(view: any): any; - isTaskScheduledAtPriorityOrHigher(priority: string): boolean; - pageHandlesAllApplicationActivations(enabled: boolean): void; - suppressSubdownloadCredentialPrompts(suppress: boolean): void; - terminateApp(exceptionObject: any): void; - readonly CURRENT: string; - readonly HIGH: string; - readonly IDLE: string; - readonly NORMAL: string; -} -declare var MSApp: MSApp; - -interface MSAppAsyncOperation extends EventTarget { - readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - readonly readyState: number; - readonly result: any; - start(): void; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSAppAsyncOperation: { - prototype: MSAppAsyncOperation; - new(): MSAppAsyncOperation; - readonly COMPLETED: number; - readonly ERROR: number; - readonly STARTED: number; -} - -interface MSBlobBuilder { - append(data: any, endings?: string): void; - getBlob(contentType?: string): Blob; -} - -declare var MSBlobBuilder: { - prototype: MSBlobBuilder; - new(): MSBlobBuilder; -} - -interface MSStream { - readonly type: string; - msClose(): void; - msDetachStream(): any; -} - -declare var MSStream: { - prototype: MSStream; - new(): MSStream; -} - -interface MSStreamReader extends EventTarget, MSBaseReader { - readonly error: DOMError; - readAsArrayBuffer(stream: MSStream, size?: number): void; - readAsBinaryString(stream: MSStream, size?: number): void; - readAsBlob(stream: MSStream, size?: number): void; - readAsDataURL(stream: MSStream, size?: number): void; - readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MSStreamReader: { - prototype: MSStreamReader; - new(): MSStreamReader; -} - -interface MediaQueryList { - readonly matches: boolean; - readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} - -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; -} - -declare var MessageChannel: { - prototype: MessageChannel; - new(): MessageChannel; -} - -interface MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly ports: any; - readonly source: any; - initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} - -interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; - close(): void; - postMessage(message?: any, ports?: any): void; - start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface Position { - readonly coords: Coordinates; - readonly timestamp: number; -} - -declare var Position: { - prototype: Position; - new(): Position; -} - -interface PositionError { - readonly code: number; - readonly message: string; - toString(): string; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -declare var PositionError: { - prototype: PositionError; - new(): PositionError; - readonly PERMISSION_DENIED: number; - readonly POSITION_UNAVAILABLE: number; - readonly TIMEOUT: number; -} - -interface ProgressEvent extends Event { - readonly lengthComputable: boolean; - readonly loaded: number; - readonly total: number; - initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; -} - -declare var ProgressEvent: { - prototype: ProgressEvent; - new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} - -interface WebSocket extends EventTarget { - binaryType: string; - readonly bufferedAmount: number; - readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; - readonly protocol: string; - readonly readyState: number; - readonly url: string; - close(code?: number, reason?: string): void; - send(data: any): void; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WebSocket: { - prototype: WebSocket; - new(url: string, protocols?: string | string[]): WebSocket; - readonly CLOSED: number; - readonly CLOSING: number; - readonly CONNECTING: number; - readonly OPEN: number; -} - -interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; - postMessage(message: any, ports?: any): void; - terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var Worker: { - prototype: Worker; - new(stringUrl: string): Worker; -} - -interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly response: any; - readonly responseText: string; - responseType: string; - readonly responseXML: any; - readonly status: number; - readonly statusText: string; - timeout: number; - readonly upload: XMLHttpRequestUpload; - withCredentials: boolean; - msCaching?: string; - abort(): void; - getAllResponseHeaders(): string; - getResponseHeader(header: string): string | null; - msCachingEnabled(): boolean; - open(method: string, url: string, async?: boolean, user?: string, password?: string): void; - overrideMimeType(mime: string): void; - send(data?: string): void; - send(data?: any): void; - setRequestHeader(header: string, value: string): void; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequest: { - prototype: XMLHttpRequest; - new(): XMLHttpRequest; - readonly DONE: number; - readonly HEADERS_RECEIVED: number; - readonly LOADING: number; - readonly OPENED: number; - readonly UNSENT: number; - create(): XMLHttpRequest; -} - -interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var XMLHttpRequestUpload: { - prototype: XMLHttpRequestUpload; - new(): XMLHttpRequestUpload; -} - -interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - readonly readyState: number; - readonly result: any; - abort(): void; - readonly DONE: number; - readonly EMPTY: number; - readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface NavigatorID { - readonly appName: string; - readonly appVersion: string; - readonly platform: string; - readonly product: string; - readonly productSub: string; - readonly userAgent: string; - readonly vendor: string; - readonly vendorSub: string; -} - -interface NavigatorOnLine { - readonly onLine: boolean; -} - -interface WindowBase64 { - atob(encodedString: string): string; - btoa(rawString: string): string; -} - -interface WindowConsole { - readonly console: Console; -} - -interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface FileReaderSync { - readAsArrayBuffer(blob: Blob): any; - readAsBinaryString(blob: Blob): void; - readAsDataURL(blob: Blob): string; - readAsText(blob: Blob, encoding?: string): string; -} - -declare var FileReaderSync: { - prototype: FileReaderSync; - new(): FileReaderSync; -} - -interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole { - readonly location: WorkerLocation; - onerror: (this: this, ev: ErrorEvent) => any; - readonly self: WorkerGlobalScope; - close(): void; - msWriteProfilerMark(profilerMarkName: string): void; - toString(): string; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WorkerGlobalScope: { - prototype: WorkerGlobalScope; - new(): WorkerGlobalScope; -} - -interface WorkerLocation { - readonly hash: string; - readonly host: string; - readonly hostname: string; - readonly href: string; - readonly pathname: string; - readonly port: string; - readonly protocol: string; - readonly search: string; - toString(): string; -} - -declare var WorkerLocation: { - prototype: WorkerLocation; - new(): WorkerLocation; -} - -interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -declare var WorkerNavigator: { - prototype: WorkerNavigator; - new(): WorkerNavigator; -} - -interface DedicatedWorkerGlobalScope { - onmessage: (this: this, ev: MessageEvent) => any; - postMessage(data: any): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; -} - -interface WorkerUtils extends Object, WindowBase64 { - readonly indexedDB: IDBFactory; - readonly msIndexedDB: IDBFactory; - readonly navigator: WorkerNavigator; - clearImmediate(handle: number): void; - 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; -} - -interface BlobPropertyBag { - type?: string; - endings?: string; -} - -interface FilePropertyBag { - type?: string; - lastModified?: number; -} - -interface EventListenerObject { - handleEvent(evt: Event): void; -} - -interface MessageEventInit extends EventInit { - data?: any; - origin?: string; - lastEventId?: string; - channel?: string; - source?: any; - ports?: MessagePort[]; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -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 { - namedCurve: 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 { - (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; -} -interface PositionCallback { - (position: Position): void; -} -interface PositionErrorCallback { - (error: PositionError): void; -} -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} -interface MSLaunchUriCallback { - (): void; -} -interface MSUnsafeFunctionCallback { - (): any; -} -interface MSExecAtPriorityFunctionCallback { - (...args: any[]): any; -} -interface DecodeSuccessCallback { - (decodedData: AudioBuffer): void; -} -interface DecodeErrorCallback { - (error: DOMException): void; -} -interface FunctionStringCallback { - (data: string): void; -} -declare var location: WorkerLocation; -declare var onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any; -declare var self: WorkerGlobalScope; -declare function close(): void; -declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; -declare var indexedDB: IDBFactory; -declare var msIndexedDB: IDBFactory; -declare var navigator: WorkerNavigator; -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; -declare var onmessage: (this: WorkerGlobalScope, ev: MessageEvent) => any; -declare function postMessage(data: any): void; -declare var console: Console; -declare function addEventListener(type: "error", listener: (this: WorkerGlobalScope, ev: ErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: WorkerGlobalScope, 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; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + + +///////////////////////////// +/// IE Worker APIs +///////////////////////////// + +interface Algorithm { + name: string; +} + +interface EventInit { + scoped?: boolean; + bubbles?: boolean; + cancelable?: boolean; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: IDBKeyPath; +} + +interface KeyAlgorithm { + name?: string; +} + +interface EventListener { + (evt: Event): void; +} + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +} + +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: string, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string): void; + groupCollapsed(groupTitle?: string): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: any): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: any): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +} + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: 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; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly currentTarget: EventTarget; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly srcElement: any; + readonly target: EventTarget; + readonly timeStamp: number; + readonly type: string; + readonly scoped: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + deepPath(): EventTarget[]; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +interface EventTarget { + addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +} + +interface File extends Blob { + readonly lastModifiedDate: any; + readonly name: string; + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +} + +interface FileList { + readonly length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface FileReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +} + +interface IDBCursor { + readonly direction: string; + key: IDBKeyRange | IDBValidKey; + readonly primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: IDBKeyRange | IDBValidKey): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +interface IDBCursorWithValue extends IDBCursor { + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + +interface IDBDatabase extends EventTarget { + readonly name: string; + readonly objectStoreNames: DOMStringList; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; + version: number; + onversionchange: (ev: IDBVersionChangeEvent) => any; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; + addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface IDBIndex { + keyPath: string | string[]; + readonly name: string; + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + multiEntry: boolean; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + get(key: IDBKeyRange | IDBValidKey): IDBRequest; + getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface IDBKeyRange { + readonly lower: any; + readonly lowerOpen: boolean; + readonly upper: any; + readonly upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(lower: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(upper: any, open?: boolean): IDBKeyRange; +} + +interface IDBObjectStore { + readonly indexNames: DOMStringList; + keyPath: string | string[]; + readonly name: string; + readonly transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + clear(): IDBRequest; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest; + put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + +interface IDBRequest extends EventTarget { + readonly error: DOMError; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; + readonly readyState: string; + readonly result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + readonly transaction: IDBTransaction; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + +interface IDBTransaction extends EventTarget { + readonly db: IDBDatabase; + readonly error: DOMError; + readonly mode: string; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; +} + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface ImageData { + data: Uint8ClampedArray; + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +} + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + readonly CURRENT: string; + readonly HIGH: string; + readonly IDLE: string; + readonly NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + +interface MSAppAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; + readonly readyState: number; + readonly result: any; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +} + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MSStreamReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +} + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +} + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: any; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +} + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +} + +interface PositionError { + readonly code: number; + readonly message: string; + toString(): string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +} + +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (this: Worker, ev: MessageEvent) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +} + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: string; + readonly responseXML: any; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + msCaching?: string; + readonly responseURL: string; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + create(): XMLHttpRequest; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +} + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSBaseReader { + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; + readonly readyState: number; + readonly result: any; + abort(): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface NavigatorID { + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface FileReaderSync { + readAsArrayBuffer(blob: Blob): any; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): string; + readAsText(blob: Blob, encoding?: string): string; +} + +declare var FileReaderSync: { + prototype: FileReaderSync; + new(): FileReaderSync; +} + +interface WorkerGlobalScopeEventMap extends DedicatedWorkerGlobalScopeEventMap { + "error": ErrorEvent; +} + +interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole { + readonly location: WorkerLocation; + onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any; + readonly self: WorkerGlobalScope; + close(): void; + msWriteProfilerMark(profilerMarkName: string): void; + toString(): string; + addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WorkerGlobalScope: { + prototype: WorkerGlobalScope; + new(): WorkerGlobalScope; +} + +interface WorkerLocation { + readonly hash: string; + readonly host: string; + readonly hostname: string; + readonly href: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + toString(): string; +} + +declare var WorkerLocation: { + prototype: WorkerLocation; + new(): WorkerLocation; +} + +interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine { + readonly hardwareConcurrency: number; +} + +declare var WorkerNavigator: { + prototype: WorkerNavigator; + new(): WorkerNavigator; +} + +interface DedicatedWorkerGlobalScopeEventMap { + "message": MessageEvent; +} + +interface DedicatedWorkerGlobalScope { + onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; + postMessage(data: any): void; + addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface WorkerUtils extends Object, WindowBase64 { + readonly indexedDB: IDBFactory; + readonly msIndexedDB: IDBFactory; + readonly navigator: WorkerNavigator; + clearImmediate(handle: number): void; + 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; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag { + type?: string; + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface MessageEventInit extends EventInit { + data?: any; + origin?: string; + lastEventId?: string; + channel?: string; + source?: any; + ports?: MessagePort[]; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +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 { + namedCurve: 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 { + (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface FunctionStringCallback { + (data: string): void; +} +declare var location: WorkerLocation; +declare var onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any; +declare var self: WorkerGlobalScope; +declare function close(): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function toString(): string; +declare function dispatchEvent(evt: Event): boolean; +declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare var indexedDB: IDBFactory; +declare var msIndexedDB: IDBFactory; +declare var navigator: WorkerNavigator; +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; +declare var onmessage: (this: WorkerGlobalScope, ev: MessageEvent) => any; +declare function postMessage(data: any): void; +declare var console: Console; +declare function addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => 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; type BufferSource = ArrayBuffer | ArrayBufferView; \ No newline at end of file diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts new file mode 100644 index 00000000000..f3737c76c46 --- /dev/null +++ b/lib/protocol.d.ts @@ -0,0 +1,1881 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type Implementation = "implementation"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type Navto = "navto"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type References = "references"; + type Reload = "reload"; + type Rename = "rename"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * Contains error message if success === false. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes?: number[]; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and character offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + /** + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + * Kind is taken from HighlightSpanKind type. + */ + interface HighlightSpan extends TextSpan { + kind: string; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + interface RenameInfo { + /** + * True if item can be renamed. + */ + canRename: boolean; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicity. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ + typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + /** + * List of updated files + */ + updated: string[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + /** + * The host's additional supported file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: string[]; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. If present, + * this span should be used instead of the default one. + */ + replacementSpan?: TextSpan; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The error code of the diagnostic message. + */ + code?: number; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * exact, substring, or prefix. + */ + matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The file in which the symbol is found. + */ + file: string; + /** + * The location within file at which the symbol is found. + */ + start: Location; + /** + * One past the last character of the symbol. + */ + end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: string; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: ReadonlyArray; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + namespace IndentStyle { + type None = "None"; + type Block = "Block"; + type Smart = "Smart"; + } + type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + namespace JsxEmit { + type None = "None"; + type Preserve = "Preserve"; + type React = "React"; + } + type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React; + namespace ModuleKind { + type None = "None"; + type CommonJS = "CommonJS"; + type AMD = "AMD"; + type UMD = "UMD"; + type System = "System"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; + namespace ModuleResolutionKind { + type Classic = "Classic"; + type Node = "Node"; + } + type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; + namespace NewLineKind { + type Crlf = "Crlf"; + type Lf = "Lf"; + } + type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; + namespace ScriptTarget { + type ES3 = "ES3"; + type ES5 = "ES5"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + interface TypeAcquisition { + enableAutoDiscovery?: boolean; + enable?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } + + interface MapLike { + [index: string]: T; + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; +} +declare namespace ts { + // these types are empty stubs for types from services and should not be used directly + export type ScriptKind = never; + export type IndentStyle = never; + export type JsxEmit = never; + export type ModuleKind = never; + export type ModuleResolutionKind = never; + export type NewLineKind = never; + export type ScriptTarget = never; +} +import protocol = ts.server.protocol; +export = protocol; +export as namespace protocol; \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index aef54c957e6..840e832f3bf 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var ts; (function (ts) { var OperationCanceledException = (function () { @@ -21,12 +21,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; @@ -39,41 +40,47 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); })(ts || (ts = {})); var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -124,8 +131,12 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + ts.version = "2.2.0"; +})(ts || (ts = {})); (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -145,13 +156,21 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, - clear: clear + getKeys: getKeys, + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -192,6 +211,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; function every(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -323,13 +349,32 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; function flatten(array) { var result; if (array) { @@ -430,10 +475,27 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } @@ -442,8 +504,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -456,6 +518,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; function compact(array) { var result; if (array) { @@ -474,26 +571,62 @@ var ts; return result || array; } ts.compact = compact; + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1: break inner; + case 0: continue outer; + case 1: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) + .map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -510,6 +643,12 @@ var ts; : undefined; } ts.firstOrUndefined = firstOrUndefined; + function lastOrUndefined(array) { + return array && array.length > 0 + ? array[array.length - 1] + : undefined; + } + ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -522,22 +661,28 @@ var ts; : array; } ts.singleOrMany = singleOrMany; - function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; } - ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { - var low = 0; + ts.replaceElement = replaceElement; + function binarySearch(array, value, comparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -636,6 +781,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -659,15 +813,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -690,8 +835,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -760,6 +905,12 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function noop() { } + ts.noop = noop; + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -771,9 +922,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -798,11 +999,11 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -825,6 +1026,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -865,7 +1077,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1007,10 +1219,53 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1182,6 +1437,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -1209,68 +1468,83 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -1280,7 +1554,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -1295,7 +1569,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -1337,25 +1611,30 @@ var ts; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } 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; - } + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); } - basePaths.push(includeBasePath); + }; + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -1380,15 +1659,34 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; - function isSupportedSourceFileName(fileName, compilerOptions) { + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -1447,10 +1745,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -1460,10 +1754,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -1475,7 +1769,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1488,9 +1781,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1508,30 +1801,17 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; + return false; } - ts.getEnvironmentVariable = getEnvironmentVariable; + ts.orderedRemoveItem = orderedRemoveItem; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1562,6 +1842,94 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); var ts; (function (ts) { @@ -1755,9 +2123,15 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -1850,6 +2224,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -1859,7 +2234,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -1867,7 +2242,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -1881,6 +2256,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1956,7 +2334,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -1967,7 +2347,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { return ChakraHost.readFile(path); }, writeFile: function (path, data, writeByteOrderMark) { @@ -1983,28 +2363,52 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2050,7 +2454,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -2160,7 +2564,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -2223,6 +2626,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -2266,6 +2670,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -2276,16 +2681,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -2325,11 +2731,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2363,8 +2769,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2376,7 +2780,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -2398,9 +2802,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -2447,6 +2849,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2470,6 +2879,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -2490,7 +2900,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -2501,6 +2911,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -2571,7 +2986,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -2600,6 +3018,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2612,7 +3031,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -2683,7 +3102,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -2720,9 +3139,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2731,7 +3157,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -2747,6 +3174,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2764,6 +3192,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -2774,141 +3203,157 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { - return token >= 69; + return token >= 70; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115, - "any": 117, - "as": 116, - "boolean": 120, - "break": 70, - "case": 71, - "catch": 72, - "class": 73, - "continue": 75, - "const": 74, - "constructor": 121, - "debugger": 76, - "declare": 122, - "default": 77, - "delete": 78, - "do": 79, - "else": 80, - "enum": 81, - "export": 82, - "extends": 83, - "false": 84, - "finally": 85, - "for": 86, - "from": 136, - "function": 87, - "get": 123, - "if": 88, - "implements": 106, - "import": 89, - "in": 90, - "instanceof": 91, - "interface": 107, - "is": 124, - "let": 108, - "module": 125, - "namespace": 126, - "never": 127, - "new": 92, - "null": 93, - "number": 130, - "package": 109, - "private": 110, - "protected": 111, - "public": 112, - "readonly": 128, - "require": 129, - "global": 137, - "return": 94, - "set": 131, - "static": 113, - "string": 132, - "super": 95, - "switch": 96, - "symbol": 133, - "this": 97, - "throw": 98, - "true": 99, - "try": 100, - "type": 134, - "typeof": 101, - "undefined": 135, - "var": 102, - "void": 103, - "while": 104, - "with": 105, - "yield": 114, - "async": 118, - "await": 119, - "of": 138, - "{": 15, - "}": 16, - "(": 17, - ")": 18, - "[": 19, - "]": 20, - ".": 21, - "...": 22, - ";": 23, - ",": 24, - "<": 25, - ">": 27, - "<=": 28, - ">=": 29, - "==": 30, - "!=": 31, - "===": 32, - "!==": 33, - "=>": 34, - "+": 35, - "-": 36, - "**": 38, - "*": 37, - "/": 39, - "%": 40, - "++": 41, - "--": 42, - "<<": 43, - ">": 44, - ">>>": 45, - "&": 46, - "|": 47, - "^": 48, - "!": 49, - "~": 50, - "&&": 51, - "||": 52, - "?": 53, - ":": 54, - "=": 56, - "+=": 57, - "-=": 58, - "*=": 59, - "**=": 60, - "/=": 61, - "%=": 62, - "<<=": 63, - ">>=": 64, - ">>>=": 65, - "&=": 66, - "|=": 67, - "^=": 68, - "@": 55 + "abstract": 116, + "any": 118, + "as": 117, + "boolean": 121, + "break": 71, + "case": 72, + "catch": 73, + "class": 74, + "continue": 76, + "const": 75, + "constructor": 122, + "debugger": 77, + "declare": 123, + "default": 78, + "delete": 79, + "do": 80, + "else": 81, + "enum": 82, + "export": 83, + "extends": 84, + "false": 85, + "finally": 86, + "for": 87, + "from": 138, + "function": 88, + "get": 124, + "if": 89, + "implements": 107, + "import": 90, + "in": 91, + "instanceof": 92, + "interface": 108, + "is": 125, + "keyof": 126, + "let": 109, + "module": 127, + "namespace": 128, + "never": 129, + "new": 93, + "null": 94, + "number": 132, + "package": 110, + "private": 111, + "protected": 112, + "public": 113, + "readonly": 130, + "require": 131, + "global": 139, + "return": 95, + "set": 133, + "static": 114, + "string": 134, + "super": 96, + "switch": 97, + "symbol": 135, + "this": 98, + "throw": 99, + "true": 100, + "try": 101, + "type": 136, + "typeof": 102, + "undefined": 137, + "var": 103, + "void": 104, + "while": 105, + "with": 106, + "yield": 115, + "async": 119, + "await": 120, + "of": 140, + "{": 16, + "}": 17, + "(": 18, + ")": 19, + "[": 20, + "]": 21, + ".": 22, + "...": 23, + ";": 24, + ",": 25, + "<": 26, + ">": 28, + "<=": 29, + ">=": 30, + "==": 31, + "!=": 32, + "===": 33, + "!==": 34, + "=>": 35, + "+": 36, + "-": 37, + "**": 39, + "*": 38, + "/": 40, + "%": 41, + "++": 42, + "--": 43, + "<<": 44, + ">": 45, + ">>>": 46, + "&": 47, + "|": 48, + "^": 49, + "!": 50, + "~": 51, + "&&": 52, + "||": 53, + "?": 54, + ":": 55, + "=": 57, + "+=": 58, + "-=": 59, + "*=": 60, + "**=": 61, + "/=": 62, + "%=": 63, + "<<=": 64, + ">>=": 65, + ">>>=": 66, + "&=": 67, + "|=": 68, + "^=": 69, + "@": 56, }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -3305,7 +3750,7 @@ var ts; return iterateCommentRanges(true, text, pos, true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -3371,8 +3816,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 || token > 105; }, - isReservedWord: function () { return token >= 70 && token <= 105; }, + isIdentifier: function () { return token === 70 || token > 106; }, + isReservedWord: function () { return token >= 71 && token <= 106; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -3391,7 +3836,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -3508,20 +3953,20 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } var currChar = text.charCodeAt(pos); if (currChar === 96) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 : 13; + resultingToken = startedWithBacktick ? 13 : 14; break; } if (currChar === 92) { @@ -3683,10 +4128,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69; + return token = 70; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -3758,12 +4203,12 @@ var ts; case 33: if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 33; + return pos += 3, token = 34; } - return pos += 2, token = 31; + return pos += 2, token = 32; } pos++; - return token = 49; + return token = 50; case 34: case 39: tokenValue = scanString(); @@ -3772,51 +4217,39 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 62; + return pos += 2, token = 63; } pos++; - return token = 40; + return token = 41; case 38: if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 51; + return pos += 2, token = 52; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + return pos += 2, token = 67; } pos++; - return token = 46; + return token = 47; case 40: pos++; - return token = 17; + return token = 18; case 41: pos++; - return token = 18; + return token = 19; case 42: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; + return pos += 2, token = 60; } if (text.charCodeAt(pos + 1) === 42) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 60; + return pos += 3, token = 61; } - return pos += 2, token = 38; + return pos += 2, token = 39; } pos++; - return token = 37; + return token = 38; case 43: if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 41; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 57; - } - pos++; - return token = 35; - case 44: - pos++; - return token = 24; - case 45: - if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; } if (text.charCodeAt(pos + 1) === 61) { @@ -3824,16 +4257,28 @@ var ts; } pos++; return token = 36; + case 44: + pos++; + return token = 25; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 43; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 59; + } + pos++; + return token = 37; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 22; + return pos += 3, token = 23; } pos++; - return token = 21; + return token = 22; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -3877,10 +4322,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; + return pos += 2, token = 62; } pos++; - return token = 39; + return token = 40; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -3929,10 +4374,10 @@ var ts; return token = 8; case 58: pos++; - return token = 54; + return token = 55; case 59: pos++; - return token = 23; + return token = 24; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3945,20 +4390,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 63; + return pos += 3, token = 64; } - return pos += 2, token = 43; + return pos += 2, token = 44; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 28; + return pos += 2, token = 29; } if (languageVariant === 1 && text.charCodeAt(pos + 1) === 47 && text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 26; + return pos += 2, token = 27; } pos++; - return token = 25; + return token = 26; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3971,15 +4416,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 32; + return pos += 3, token = 33; } - return pos += 2, token = 30; + return pos += 2, token = 31; } if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 34; + return pos += 2, token = 35; } pos++; - return token = 56; + return token = 57; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3991,43 +4436,43 @@ var ts; } } pos++; - return token = 27; + return token = 28; case 63: pos++; - return token = 53; + return token = 54; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 94: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 69; + } + pos++; + return token = 49; + case 123: + pos++; + return token = 16; + case 124: + if (text.charCodeAt(pos + 1) === 124) { + return pos += 2, token = 53; + } if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } pos++; return token = 48; - case 123: - pos++; - return token = 15; - case 124: - if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 52; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 67; - } - pos++; - return token = 47; case 125: pos++; - return token = 16; + return token = 17; case 126: pos++; - return token = 50; + return token = 51; case 64: pos++; - return token = 55; + return token = 56; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -4065,29 +4510,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27) { + if (token === 28) { if (text.charCodeAt(pos) === 62) { if (text.charCodeAt(pos + 1) === 62) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + return pos += 3, token = 66; } - return pos += 2, token = 45; + return pos += 2, token = 46; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + return pos += 2, token = 65; } pos++; - return token = 44; + return token = 45; } if (text.charCodeAt(pos) === 61) { pos++; - return token = 29; + return token = 30; } } return token; } function reScanSlashToken() { - if (token === 39 || token === 61) { + if (token === 40 || token === 62) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -4126,12 +4571,12 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10; + token = 11; } return token; } function reScanTemplateToken() { - ts.Debug.assert(token === 16, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -4148,14 +4593,14 @@ var ts; if (char === 60) { if (text.charCodeAt(pos + 1) === 47) { pos += 2; - return token = 26; + return token = 27; } pos++; - return token = 25; + return token = 26; } if (char === 123) { pos++; - return token = 15; + return token = 16; } while (pos < end) { pos++; @@ -4164,7 +4609,7 @@ var ts; break; } } - return token = 244; + return token = 10; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -4211,39 +4656,42 @@ var ts; return token = 5; case 64: pos++; - return token = 55; + return token = 56; case 10: case 13: pos++; return token = 4; case 42: pos++; - return token = 37; + return token = 38; case 123: pos++; - return token = 15; + return token = 16; case 125: pos++; - return token = 16; + return token = 17; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 61: pos++; - return token = 56; + return token = 57; case 44: pos++; - return token = 24; + return token = 25; + case 46: + pos++; + return token = 22; } - if (isIdentifierStart(ch, 2)) { + if (isIdentifierStart(ch, 5)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { pos++; } - return token = 69; + return token = 70; } else { return pos += 1, token = 0; @@ -4356,13 +4804,14 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, - increaseIndent: function () { }, - decreaseIndent: function () { }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, clear: function () { return str_1 = ""; }, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; } return stringWriters.pop(); @@ -4377,22 +4826,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(array1, array2, equaler) { - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } @@ -4416,7 +4849,9 @@ var ts; } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function typeDirectiveIsEqualTo(oldResolution, newResolution) { @@ -4442,21 +4877,21 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 2097152) !== 0; + return (node.flags & 131072) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 4194304)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 2097152; + node.flags |= 131072; } - node.flags |= 4194304; + node.flags |= 262144; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 256) { + while (node && node.kind !== 261) { node = node.parent; } return node; @@ -4464,11 +4899,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: return true; } return false; @@ -4523,28 +4958,28 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function getTokenPosOfNode(node, sourceFile, includeJsDocComment) { + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; } if (isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); + if (node.kind === 292 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 262 && node.kind <= 288; } ts.isJSDocNode = isJSDocNode; function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; + return node.kind >= 278 && node.kind <= 291; } ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -4589,13 +5024,13 @@ var ts; switch (node.kind) { case 9: return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "`"); case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "${"); case 14: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 15: return getQuotedEscapedLiteralText("}", node.text, "`"); case 8: return node.text; @@ -4633,11 +5068,16 @@ var ts; ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 223 && node.parent.kind === 256; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 225 && + return node && node.kind === 230 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; @@ -4646,11 +5086,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node.kind === 225 && (!node.body); + return node.kind === 230 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 256 || - node.kind === 225 || + return node.kind === 261 || + node.kind === 230 || isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -4663,32 +5103,36 @@ var ts; return false; } switch (node.parent.kind) { - case 256: + case 261: return ts.isExternalModule(node.parent); - case 226: + case 231: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { + case 261: + case 232: case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - case 148: - case 147: - case 149: + case 230: + case 211: + case 212: + case 213: case 150: - case 220: - case 179: - case 180: + case 149: + case 151: + case 152: + case 225: + case 184: + case 185: return true; - case 199: + case 204: return parentNode && !isFunctionLike(parentNode); } return false; @@ -4704,23 +5148,46 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 218 && - declaration.parent && - declaration.parent.kind === 252; - } - ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 70: + return name.text; + case 9: + case 8: + return name.text; + case 142: + if (isStringOrNumericLiteral(name.expression)) { + return name.expression.text; + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 70: + return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name); + case 141: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 177: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; function createDiagnosticForNode(node, message, arg0, arg1, arg2) { var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { var span = getErrorSpanForNode(sourceFile, node); return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } - ts.createDiagnosticForNode = createDiagnosticForNode; + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -4743,7 +5210,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 199) { + if (node.body && node.body.kind === 204) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -4755,29 +5222,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 256: + case 261: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 218: - case 169: - case 221: - case 192: - case 222: - case 225: - case 224: - case 255: - case 220: - case 179: - case 147: - case 149: - case 150: case 223: + case 174: + case 226: + case 197: + case 227: + case 230: + case 229: + case 260: + case 225: + case 184: + case 149: + case 151: + case 152: + case 228: errorNode = node.name; break; - case 180: + case 185: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -4798,7 +5265,7 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 224 && isConst(node); + return node.kind === 229 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -4810,12 +5277,13 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { - return n.kind === 174 && n.expression.kind === 95; + function isSuperCall(n) { + return n.kind === 179 && n.expression.kind === 96; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { - return node.kind === 202 && node.expression.kind === 9; + return node.kind === 207 + && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -4826,92 +5294,87 @@ var ts; return ts.getLeadingCommentRanges(text, node.pos); } ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJsDocComments(node, sourceFileOfNode) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - ts.getJsDocComments = getJsDocComments; - function getJsDocCommentsFromText(node, text) { - var commentRanges = (node.kind === 142 || - node.kind === 141 || - node.kind === 179 || - node.kind === 180) ? + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 144 || + node.kind === 143 || + node.kind === 184 || + node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { + return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && text.charCodeAt(comment.pos + 3) !== 47; - } + }); } - ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (154 <= node.kind && node.kind <= 166) { + if (156 <= node.kind && node.kind <= 171) { return true; } switch (node.kind) { - case 117: - case 130: + case 118: case 132: - case 120: - case 133: + case 134: + case 121: case 135: - case 127: + case 137: + case 129: return true; - case 103: - return node.parent.kind !== 183; - case 194: + case 104: + return node.parent.kind !== 188; + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 69: - if (node.parent.kind === 139 && node.parent.right === node) { + case 70: + if (node.parent.kind === 141 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 172 && node.parent.name === node) { + else if (node.parent.kind === 177 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 139: - case 172: - case 97: + ts.Debug.assert(node.kind === 70 || node.kind === 141 || node.kind === 177, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 141: + case 177: + case 98: var parent_1 = node.parent; - if (parent_1.kind === 158) { + if (parent_1.kind === 160) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (156 <= parent_1.kind && parent_1.kind <= 171) { return true; } switch (parent_1.kind) { - case 194: + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 141: + case 143: return node === parent_1.constraint; - case 145: - case 144: - case 142: - case 218: - return node === parent_1.type; - case 220: - case 179: - case 180: - case 148: case 147: case 146: - case 149: - case 150: + case 144: + case 223: return node === parent_1.type; + case 225: + case 184: + case 185: + case 150: + case 149: + case 148: case 151: case 152: + return node === parent_1.type; case 153: + case 154: + case 155: return node === parent_1.type; - case 177: + case 182: return node === parent_1.type; - case 174: - case 175: + case 179: + case 180: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 176: + case 181: return false; } } @@ -4922,23 +5385,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 211: + case 216: return visitor(node); - case 227: - case 199: - case 203: + case 232: case 204: - case 205: - case 206: - case 207: case 208: + case 209: + case 210: + case 211: case 212: case 213: - case 249: - case 250: - case 214: - case 216: - case 252: + case 217: + case 218: + case 253: + case 254: + case 219: + case 221: + case 256: return ts.forEachChild(node, traverse); } } @@ -4948,23 +5411,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 190: + case 195: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 224: - case 222: - case 225: - case 223: - case 221: - case 192: + case 229: + case 227: + case 230: + case 228: + case 226: + case 197: return; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 140) { + if (name_5 && name_5.kind === 142) { traverse(name_5.expression); return; } @@ -4976,17 +5439,29 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { - case 169: - case 255: - case 142: - case 253: - case 145: + case 174: + case 260: case 144: - case 254: - case 218: + case 257: + case 147: + case 146: + case 258: + case 223: return true; } } @@ -4994,11 +5469,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 149 || node.kind === 150); + return node && (node.kind === 151 || node.kind === 152); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 221 || node.kind === 192); + return node && (node.kind === 226 || node.kind === 197); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -5007,19 +5482,19 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 148: - case 179: - case 220: - case 180: - case 147: - case 146: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return true; } return false; @@ -5027,13 +5502,13 @@ var ts; ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 179: + case 151: + case 152: + case 225: + case 184: return true; } return false; @@ -5041,26 +5516,32 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: + case 211: + case 212: + case 213: + case 209: + case 210: return true; - case 214: + case 219: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 199 && isFunctionLike(node.parent); + return node && node.kind === 204 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 147 && node.parent.kind === 171; + return node && node.kind === 149 && node.parent.kind === 176; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 149 && + (node.parent.kind === 176 || + node.parent.kind === 197); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -5094,39 +5575,39 @@ var ts; return undefined; } switch (node.kind) { - case 140: + case 142: if (isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 180: + case 185: if (!includeArrowFunctions) { continue; } - case 220: - case 179: case 225: - case 145: - case 144: + case 184: + case 230: case 147: case 146: - case 148: case 149: + case 148: case 150: case 151: case 152: case 153: - case 224: - case 256: + case 154: + case 155: + case 229: + case 261: return node; } } @@ -5139,25 +5620,25 @@ var ts; return node; } switch (node.kind) { - case 140: + case 142: node = node.parent; break; - case 220: - case 179: - case 180: + case 225: + case 184: + case 185: if (!stopOnFunctions) { continue; } - case 145: - case 144: case 147: case 146: - case 148: case 149: + case 148: case 150: + case 151: + case 152: return node; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { @@ -5169,14 +5650,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 179 || func.kind === 180) { + if (func.kind === 184 || func.kind === 185) { var prev = func; var parent_2 = func.parent; - while (parent_2.kind === 178) { + while (parent_2.kind === 183) { prev = parent_2; parent_2 = parent_2.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { + if (parent_2.kind === 179 && parent_2.expression === prev) { return parent_2; } } @@ -5184,32 +5665,32 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 172 || kind === 173) - && node.expression.kind === 95; + return (kind === 177 || kind === 178) + && node.expression.kind === 96; } ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { - if (node) { - switch (node.kind) { - case 155: - return node.typeName; - case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); - return node.expression; - case 69: - case 139: - return node; - } + switch (node.kind) { + case 157: + case 272: + return node.typeName; + case 199: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 70: + case 141: + return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function isCallLikeExpression(node) { switch (node.kind) { - case 174: - case 175: - case 176: - case 143: + case 179: + case 180: + case 181: + case 145: return true; default: return false; @@ -5217,7 +5698,7 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { - if (node.kind === 176) { + if (node.kind === 181) { return node.tag; } return node.expression; @@ -5225,21 +5706,21 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 221: + case 226: return true; - case 145: - return node.parent.kind === 221; - case 149: - case 150: case 147: + return node.parent.kind === 226; + case 151: + case 152: + case 149: return node.body !== undefined - && node.parent.kind === 221; - case 142: + && node.parent.kind === 226; + case 144: return node.parent.body !== undefined - && (node.parent.kind === 148 - || node.parent.kind === 147 - || node.parent.kind === 150) - && node.parent.parent.kind === 221; + && (node.parent.kind === 150 + || node.parent.kind === 149 + || node.parent.kind === 152) + && node.parent.parent.kind === 226; } return false; } @@ -5255,19 +5736,19 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 221: + case 226: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 147: - case 150: + case 149: + case 152: return ts.forEach(node.parameters, nodeIsDecorated); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 243 || - parent.kind === 242 || - parent.kind === 245) { + if (parent.kind === 248 || + parent.kind === 247 || + parent.kind === 249) { return parent.tagName === node; } return false; @@ -5275,97 +5756,98 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 97: - case 95: - case 93: - case 99: - case 84: - case 10: - case 170: - case 171: - case 172: - case 173: - case 174: + case 98: + case 96: + case 94: + case 100: + case 85: + case 11: case 175: case 176: - case 195: case 177: - case 196: case 178: case 179: - case 192: case 180: - case 183: case 181: + case 200: case 182: + case 201: + case 183: + case 184: + case 197: case 185: + case 188: case 186: case 187: - case 188: - case 191: - case 189: - case 11: - case 193: - case 241: - case 242: case 190: - case 184: + case 191: + case 192: + case 193: + case 196: + case 194: + case 12: + case 198: + case 246: + case 247: + case 195: + case 189: return true; - case 139: - while (node.parent.kind === 139) { + case 141: + while (node.parent.kind === 141) { node = node.parent; } - return node.parent.kind === 158 || isJSXTagName(node); - case 69: - if (node.parent.kind === 158 || isJSXTagName(node)) { + return node.parent.kind === 160 || isJSXTagName(node); + case 70: + if (node.parent.kind === 160 || isJSXTagName(node)) { return true; } case 8: case 9: - case 97: + case 98: var parent_3 = node.parent; switch (parent_3.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 255: - case 253: - case 169: + case 147: + case 146: + case 260: + case 257: + case 174: return parent_3.initializer === node; - case 202: - case 203: - case 204: - case 205: - case 211: - case 212: - case 213: - case 249: - case 215: - case 213: - return parent_3.expression === node; - case 206: - var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || - forStatement.condition === node || - forStatement.incrementor === node; case 207: case 208: + case 209: + case 210: + case 216: + case 217: + case 218: + case 253: + case 220: + case 218: + return parent_3.expression === node; + case 211: + var forStatement = parent_3; + return (forStatement.initializer === node && forStatement.initializer.kind !== 224) || + forStatement.condition === node || + forStatement.incrementor === node; + case 212: + case 213: var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224) || forInStatement.expression === node; - case 177: - case 195: + case 182: + case 200: return node === parent_3.expression; - case 197: + case 202: return node === parent_3.expression; - case 140: + case 142: return node === parent_3.expression; - case 143: - case 248: - case 247: + case 145: + case 252: + case 251: + case 259: return true; - case 194: + case 199: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: if (isPartOfExpression(parent_3)) { @@ -5376,10 +5858,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -5387,7 +5865,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind === 240; + return node.kind === 234 && node.moduleReference.kind === 245; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -5396,7 +5874,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind !== 240; + return node.kind === 234 && node.moduleReference.kind !== 245; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -5404,12 +5882,12 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 1048576); + return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { - var isRequire = expression.kind === 174 && - expression.expression.kind === 69 && + var isRequire = expression.kind === 179 && + expression.expression.kind === 70 && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9); @@ -5420,9 +5898,9 @@ var ts; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; function isDeclarationOfFunctionExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + if (s.valueDeclaration && s.valueDeclaration.kind === 223) { var declaration = s.valueDeclaration; - return declaration.initializer && declaration.initializer.kind === 179; + return declaration.initializer && declaration.initializer.kind === 184; } return false; } @@ -5431,15 +5909,15 @@ var ts; if (!isInJavaScriptFile(expression)) { return 0; } - if (expression.kind !== 187) { + if (expression.kind !== 192) { return 0; } var expr = expression; - if (expr.operatorToken.kind !== 56 || expr.left.kind !== 172) { + if (expr.operatorToken.kind !== 57 || expr.left.kind !== 177) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 69) { + if (lhs.expression.kind === 70) { var lhsId = lhs.expression; if (lhsId.text === "exports") { return 1; @@ -5448,12 +5926,12 @@ var ts; return 2; } } - else if (lhs.expression.kind === 97) { + else if (lhs.expression.kind === 98) { return 4; } - else if (lhs.expression.kind === 172) { + else if (lhs.expression.kind === 177) { var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 69) { + if (innerPropertyAccess.expression.kind === 70) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { return 1; @@ -5467,35 +5945,35 @@ var ts; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 230) { + if (node.kind === 235) { return node.moduleSpecifier; } - if (node.kind === 229) { + if (node.kind === 234) { var reference = node.moduleReference; - if (reference.kind === 240) { + if (reference.kind === 245) { return reference.expression; } } - if (node.kind === 236) { + if (node.kind === 241) { return node.moduleSpecifier; } - if (node.kind === 225 && node.name.kind === 9) { + if (node.kind === 230 && node.name.kind === 9) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 230 + return node.kind === 235 && node.importClause && !!node.importClause.name; } @@ -5503,13 +5981,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 142: + case 144: + case 149: + case 148: + case 258: + case 257: case 147: case 146: - case 254: - case 253: - case 145: - case 144: return node.questionToken !== undefined; } } @@ -5517,157 +5995,123 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 269 && + return node.kind === 274 && node.parameters.length > 0 && - node.parameters[0].type.kind === 271; + node.parameters[0].type.kind === 276; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getJSDocTag(node, kind, checkParentVariableStatement) { - if (!node) { - return undefined; - } - var jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { - var tag = jsDocTags_1[_i]; - if (tag.kind === kind) { - return tag; - } - } + function getCommentsFromJSDoc(node) { + return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } - function append(previous, additional) { - if (additional) { - if (!previous) { - previous = []; - } - for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { - var x = additional_1[_i]; - previous.push(x); - } - } - return previous; - } - function getJSDocComments(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); - } - ts.getJSDocComments = getJSDocComments; - function getJSDocTags(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { + ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function getJSDocTags(node, kind) { + var docs = getJSDocs(node); + if (docs) { var result = []; for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { var doc = docs_1[_i]; - if (doc.tags) { - result.push.apply(result, doc.tags); + if (doc.kind === 281) { + if (doc.kind === kind) { + result.push(doc); + } + } + else { + result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; })); } } return result; - }, function (tags) { return tags; }); + } } - function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { - var result = undefined; - if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === 200; + function getFirstJSDocTag(node, kind) { + return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + } + function getJSDocs(node) { + var cache = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + function getJSDocsWorker(node) { + var parent = node.parent; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 205; var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + parent.parent.kind === 205; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } - if (node.kind === 225 && - node.parent && node.parent.kind === 225) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); - } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 192 && + parent.operatorToken.kind === 57 && + parent.parent.kind === 207; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + var isModuleDeclaration = node.kind === 230 && + parent && parent.kind === 230; + var isPropertyAssignmentExpression = parent && parent.kind === 257; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } - if (node.kind === 142) { - var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + if (node.kind === 144) { + cache = ts.concatenate(cache, getJSDocParameterTags(node)); } + if (isVariableLike(node) && node.initializer) { + cache = ts.concatenate(cache, node.initializer.jsDoc); + } + cache = ts.concatenate(cache, node.jsDoc); } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); - } - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); - } - else { - return getDocs(node.jsDocComments); - } - } - return result; } - function getJSDocParameterTag(param, checkParentVariableStatement) { + function getJSDocParameterTags(param) { + if (!isParameter(param)) { + return undefined; + } var func = param.parent; - var tags = getJSDocTags(func, checkParentVariableStatement); + var tags = getJSDocTags(func, 281); if (!param.name) { var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281; }); if (paramTags && 0 <= i && i < paramTags.length) { return [paramTags[i]]; } } - else if (param.name.kind === 69) { + else if (param.name.kind === 70) { var name_6 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_6; }); - if (paramTags) { - return paramTags; - } + return ts.filter(tags, function (tag) { return tag.kind === 281 && tag.parameterName.text === name_6; }); } else { return undefined; } } - function getJSDocTypeTag(node) { - return getJSDocTag(node, 277, false); + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 283); + if (!tag && node.kind === 144) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; } - ts.getJSDocTypeTag = getJSDocTypeTag; + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 276, true); + return getFirstJSDocTag(node, 282); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 278, false); + return getFirstJSDocTag(node, 284); } ts.getJSDocTemplateTag = getJSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter) { - if (parameter.name && parameter.name.kind === 69) { - var parameterName = parameter.name.text; - var jsDocTags = getJSDocTags(parameter.parent, true); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { - var tag = jsDocTags_2[_i]; - if (tag.kind === 275) { - var parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } - } - } - return undefined; - } - ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -5677,14 +6121,11 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 1048576)) { - if (node.type && node.type.kind === 270) { + if (node && (node.flags & 65536)) { + if (node.type && node.type.kind === 275 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275; })) { return true; } - var paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 270; - } } return isDeclaredRestParam(node); } @@ -5693,27 +6134,44 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isAssignmentTarget(node) { - while (node.parent.kind === 178) { - node = node.parent; - } + function getAssignmentTargetKind(node) { + var parent = node.parent; while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; - continue; + switch (parent.kind) { + case 192: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 57 ? 1 : 2 : + 0; + case 190: + case 191: + var unaryOperator = parent.operator; + return unaryOperator === 42 || unaryOperator === 43 ? 2 : 0; + case 212: + case 213: + return parent.initializer === node ? 1 : 0; + case 183: + case 175: + case 196: + node = parent; + break; + case 258: + if (parent.name !== node) { + return 0; + } + case 257: + node = parent.parent; + break; + default: + return 0; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; - continue; - } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + parent = node.parent; } } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } ts.isAssignmentTarget = isAssignmentTarget; function isNodeDescendantOf(node, ancestor) { while (node) { @@ -5726,7 +6184,7 @@ var ts; ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 261 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -5735,11 +6193,11 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { + if (name.kind !== 70 && name.kind !== 9 && name.kind !== 8) { return false; } var parent = name.parent; - if (parent.kind === 234 || parent.kind === 238) { + if (parent.kind === 239 || parent.kind === 243) { if (parent.propertyName) { return true; } @@ -5752,48 +6210,48 @@ var ts; ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 140 && + node.parent.kind === 142 && isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 145: - case 144: case 147: case 146: case 149: - case 150: - case 255: - case 253: - case 172: + case 148: + case 151: + case 152: + case 260: + case 257: + case 177: return parent.name === node; - case 139: + case 141: if (parent.right === node) { - while (parent.kind === 139) { + while (parent.kind === 141) { parent = parent.parent; } - return parent.kind === 158; + return parent.kind === 160; } return false; - case 169: - case 234: + case 174: + case 239: return parent.propertyName === node; - case 238: + case 243: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 229 || - node.kind === 228 || - node.kind === 231 && !!node.name || - node.kind === 232 || - node.kind === 234 || - node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + return node.kind === 234 || + node.kind === 233 || + node.kind === 236 && !!node.name || + node.kind === 237 || + node.kind === 239 || + node.kind === 243 || + node.kind === 240 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -5801,17 +6259,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 106); + var heritageClause = getHeritageClause(node.heritageClauses, 107); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -5879,7 +6337,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 <= token && token <= 138; + return 71 <= token && token <= 140; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -5890,8 +6348,10 @@ var ts; return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; - function isStringOrNumericLiteral(kind) { - return kind === 9 || kind === 8; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { @@ -5899,8 +6359,8 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 140 && - !isStringOrNumericLiteral(name.expression.kind) && + return name.kind === 142 && + !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -5909,10 +6369,10 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { + if (name.kind === 70 || name.kind === 9 || name.kind === 8 || name.kind === 144) { return name.text; } - if (name.kind === 140) { + if (name.kind === 142) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -5930,22 +6390,26 @@ var ts; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function isESSymbolIdentifier(node) { - return node.kind === 69 && node.text === "Symbol"; + return node.kind === 70 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.text === "push" || node.text === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isModifierKind(token) { switch (token) { - case 115: - case 118: - case 74: - case 122: - case 77: - case 82: - case 112: - case 110: - case 111: - case 128: + case 116: + case 119: + case 75: + case 123: + case 78: + case 83: case 113: + case 111: + case 112: + case 130: + case 114: return true; } return false; @@ -5953,11 +6417,11 @@ var ts; ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 142; + return root.kind === 144; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 169) { + while (node.kind === 174) { node = node.parent.parent; } return node; @@ -5965,33 +6429,29 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 148 - || kind === 179 - || kind === 220 - || kind === 180 - || kind === 147 - || kind === 149 - || kind === 150 + return kind === 150 + || kind === 184 || kind === 225 - || kind === 256; + || kind === 185 + || kind === 149 + || kind === 151 + || kind === 152 + || kind === 230 + || kind === 261; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - function getOriginalNode(node) { + function getOriginalNode(node, nodeTest) { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; function isParseTreeNode(node) { @@ -6028,38 +6488,38 @@ var ts; ts.getOriginalNodeId = getOriginalNodeId; function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 175: + case 180: return hasArguments ? 0 : 1; - case 185: - case 182: - case 183: - case 181: - case 184: - case 188: case 190: - return 1; case 187: + case 188: + case 186: + case 189: + case 193: + case 195: + return 1; + case 192: switch (operator) { - case 38: - case 56: + case 39: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 1; } } @@ -6068,15 +6528,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 187) { + if (expression.kind === 192) { return expression.operatorToken.kind; } - else if (expression.kind === 185 || expression.kind === 186) { + else if (expression.kind === 190 || expression.kind === 191) { return expression.operator; } else { @@ -6086,106 +6546,107 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 97: - case 95: - case 69: - case 93: - case 99: - case 84: + case 98: + case 96: + case 70: + case 94: + case 100: + case 85: case 8: case 9: - case 170: - case 171: - case 179: - case 180: - case 192: - case 241: - case 242: - case 10: - case 11: - case 189: - case 178: - case 193: - return 19; - case 176: - case 172: - case 173: - return 18; case 175: - return hasArguments ? 18 : 17; - case 174: - return 17; - case 186: - return 16; - case 185: - case 182: - case 183: - case 181: + case 176: case 184: - return 15; + case 185: + case 197: + case 246: + case 247: + case 11: + case 12: + case 194: + case 183: + case 198: + case 297: + return 19; + case 181: + case 177: + case 178: + return 18; + case 180: + return hasArguments ? 18 : 17; + case 179: + return 17; + case 191: + return 16; + case 190: case 187: + case 188: + case 186: + case 189: + return 15; + case 192: switch (operatorKind) { - case 49: case 50: + case 51: return 15; - case 38: - case 37: case 39: + case 38: case 40: + case 41: return 14; - case 35: case 36: + case 37: return 13; - case 43: case 44: case 45: + case 46: return 12; - case 25: - case 28: - case 27: + case 26: case 29: - case 90: - case 91: - return 11; + case 28: case 30: - case 32: + case 91: + case 92: + return 11; case 31: case 33: + case 32: + case 34: return 10; - case 46: - return 9; - case 48: - return 8; case 47: + return 9; + case 49: + return 8; + case 48: return 7; - case 51: - return 6; case 52: + return 6; + case 53: return 5; - case 56: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 3; - case 24: + case 25: return 0; default: return -1; } - case 188: + case 193: return 4; - case 190: + case 195: return 2; - case 191: + case 196: return 1; default: return -1; @@ -6420,48 +6881,46 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - var sourceFiles = host.getSourceFiles(); + var sourceFiles = getAllEmittableSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, isNonDeclarationFile); + var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); }); + } + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles(); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) { + return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); }); + } + ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory; function isNonDeclarationFile(sourceFile) { return !isDeclarationFile(sourceFile); } - function isBundleEmitNonExternalModule(sourceFile) { - return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function isBundleEmitNonExternalModule(sourceFile) { + return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { @@ -6485,10 +6944,10 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } - function onBundledEmit(host, sourceFiles) { + function onBundledEmit(sourceFiles) { if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -6501,16 +6960,16 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) { onSingleFileEmit(host, sourceFile); } } @@ -6528,18 +6987,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { - var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -6547,7 +7007,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -6576,7 +7036,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 148 && nodeIsPresent(member.body)) { + if (member.kind === 150 && nodeIsPresent(member.body)) { return member; } }); @@ -6584,13 +7044,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 70 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 98; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -6598,10 +7077,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 149) { + if (accessor.kind === 151) { getAccessor = accessor; } - else if (accessor.kind === 150) { + else if (accessor.kind === 152) { setAccessor = accessor; } else { @@ -6610,7 +7089,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 149 || member.kind === 150) + if ((member.kind === 151 || member.kind === 152) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -6621,10 +7100,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 149 && !getAccessor) { + if (member.kind === 151 && !getAccessor) { getAccessor = member; } - if (member.kind === 150 && !setAccessor) { + if (member.kind === 152 && !setAccessor) { setAccessor = member; } } @@ -6807,7 +7286,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4) { + if (node.flags & 4 || (node.kind === 70 && node.isInJSDocNamespace)) { flags |= 1; } node.modifierFlagsCache = flags | 536870912; @@ -6816,46 +7295,52 @@ var ts; ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { - case 113: return 32; - case 112: return 4; - case 111: return 16; - case 110: return 8; - case 115: return 128; - case 82: return 1; - case 122: return 2; - case 74: return 2048; - case 77: return 512; - case 118: return 256; - case 128: return 64; + case 114: return 32; + case 113: return 4; + case 112: return 16; + case 111: return 8; + case 116: return 128; + case 83: return 1; + case 123: return 2; + case 75: return 2048; + case 78: return 512; + case 119: return 256; + case 130: return 64; } return 0; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 52 - || token === 51 - || token === 49; + return token === 53 + || token === 52 + || token === 50; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 56 && token <= 68; + return token >= 57 && token <= 69; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 194 && - node.parent.token === 83 && + if (node.kind === 199 && + node.parent.token === 84 && isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 57 + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === 56) { - var kind = node.left.kind; - return kind === 171 - || kind === 170; - } + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 176 + || kind === 175; } return false; } @@ -6865,7 +7350,7 @@ var ts; } ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { + if (node.kind === 70) { return true; } else if (isPropertyAccessExpression(node)) { @@ -6880,21 +7365,21 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + return node.kind === 70 || + node.kind === 177 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 139 && node.parent.right === node) || - (node.parent.kind === 172 && node.parent.name === node); + return (node.parent.kind === 141 && node.parent.right === node) || + (node.parent.kind === 177 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 171) { + if (kind === 176) { return expression.properties.length === 0; } - if (kind === 170) { + if (kind === 175) { return expression.elements.length === 0; } return false; @@ -6904,14 +7389,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - 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 tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -6945,39 +7422,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -7002,12 +7446,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7032,49 +7470,49 @@ var ts; var kind = node.kind; if (kind === 9 || kind === 8 - || kind === 10 || kind === 11 - || kind === 69 - || kind === 97 - || kind === 95 - || kind === 99 - || kind === 84 - || kind === 93) { + || kind === 12 + || kind === 70 + || kind === 98 + || kind === 96 + || kind === 100 + || kind === 85 + || kind === 94) { return true; } - else if (kind === 172) { + else if (kind === 177) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 173) { + else if (kind === 178) { return isSimpleExpressionWorker(node.expression, depth + 1) && isSimpleExpressionWorker(node.argumentExpression, depth + 1); } - else if (kind === 185 - || kind === 186) { + else if (kind === 190 + || kind === 191) { return isSimpleExpressionWorker(node.operand, depth + 1); } - else if (kind === 187) { - return node.operatorToken.kind !== 38 + else if (kind === 192) { + return node.operatorToken.kind !== 39 && isSimpleExpressionWorker(node.left, depth + 1) && isSimpleExpressionWorker(node.right, depth + 1); } - else if (kind === 188) { + else if (kind === 193) { return isSimpleExpressionWorker(node.condition, depth + 1) && isSimpleExpressionWorker(node.whenTrue, depth + 1) && isSimpleExpressionWorker(node.whenFalse, depth + 1); } - else if (kind === 183 - || kind === 182 - || kind === 181) { + else if (kind === 188 + || kind === 187 + || kind === 186) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 170) { + else if (kind === 175) { return node.elements.length === 0; } - else if (kind === 171) { + else if (kind === 176) { return node.properties.length === 0; } - else if (kind === 174) { + else if (kind === 179) { if (!isSimpleExpressionWorker(node.expression, depth + 1)) { return false; } @@ -7108,7 +7546,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -7177,58 +7615,21 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; - function collectExternalModuleInfo(sourceFile, resolver) { - var externalImports = []; - var exportSpecifiers = ts.createMap(); - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_8 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; + case 230: + return parseNode === parseNode.parent.name; } } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + return false; } - ts.collectExternalModuleInfo = collectExternalModuleInfo; + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; function getInitializedVariables(node) { return ts.filter(node.declarations, isInitializedVariable); } @@ -7240,7 +7641,7 @@ var ts; if (node.symbol) { for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 && declaration !== node) { + if (declaration.kind === 226 && declaration !== node) { return true; } } @@ -7258,15 +7659,15 @@ var ts; } ts.isNodeArray = isNodeArray; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 11; + return node.kind === 12; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; + return 8 <= kind && kind <= 12; } ts.isLiteralKind = isLiteralKind; function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; + return kind === 9 || kind === 12; } ts.isTextualLiteralKind = isTextualLiteralKind; function isLiteralExpression(node) { @@ -7274,20 +7675,21 @@ var ts; } ts.isLiteralExpression = isLiteralExpression; function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; + return 12 <= kind && kind <= 15; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 - || kind === 14; + function isTemplateHead(node) { + return node.kind === 13; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 14 + || kind === 15; } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { - return node.kind === 69; + return node.kind === 70; } ts.isIdentifier = isIdentifier; function isGeneratedIdentifier(node) { @@ -7299,183 +7701,240 @@ var ts; } ts.isModifier = isModifier; function isQualifiedName(node) { - return node.kind === 139; + return node.kind === 141; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 140; + return node.kind === 142; } ts.isComputedPropertyName = isComputedPropertyName; function isEntityName(node) { var kind = node.kind; - return kind === 139 - || kind === 69; + return kind === 141 + || kind === 70; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9 || kind === 8 - || kind === 140; + || kind === 142; } ts.isPropertyName = isPropertyName; function isModuleName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9; } ts.isModuleName = isModuleName; function isBindingName(node) { var kind = node.kind; - return kind === 69 - || kind === 167 - || kind === 168; + return kind === 70 + || kind === 172 + || kind === 173; } ts.isBindingName = isBindingName; function isTypeParameter(node) { - return node.kind === 141; + return node.kind === 143; } ts.isTypeParameter = isTypeParameter; function isParameter(node) { - return node.kind === 142; + return node.kind === 144; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 143; + return node.kind === 145; } ts.isDecorator = isDecorator; function isMethodDeclaration(node) { - return node.kind === 147; + return node.kind === 149; } ts.isMethodDeclaration = isMethodDeclaration; function isClassElement(node) { var kind = node.kind; - return kind === 148 - || kind === 145 + return kind === 150 || kind === 147 || kind === 149 - || kind === 150 - || kind === 153 - || kind === 198; + || kind === 151 + || kind === 152 + || kind === 155 + || kind === 203; } ts.isClassElement = isClassElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 253 - || kind === 254 - || kind === 147 + return kind === 257 + || kind === 258 + || kind === 259 || kind === 149 - || kind === 150 - || kind === 239; + || kind === 151 + || kind === 152 + || kind === 244; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 154 && kind <= 166) - || kind === 117 - || kind === 130 - || kind === 120 + return (kind >= 156 && kind <= 171) + || kind === 118 || kind === 132 - || kind === 133 - || kind === 103 - || kind === 127 - || kind === 194; + || kind === 121 + || kind === 134 + || kind === 135 + || kind === 104 + || kind === 129 + || kind === 199; } function isTypeNode(node) { return isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; + function isArrayBindingPattern(node) { + return node.kind === 173; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isObjectBindingPattern(node) { + return node.kind === 172; + } + ts.isObjectBindingPattern = isObjectBindingPattern; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 168 - || kind === 167; + return kind === 173 + || kind === 172; } return false; } ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 175 + || kind === 176; + } + ts.isAssignmentPattern = isAssignmentPattern; function isBindingElement(node) { - return node.kind === 169; + return node.kind === 174; } ts.isBindingElement = isBindingElement; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 169 - || kind === 193; + return kind === 174 + || kind === 198; } ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 223: + case 144: + case 174: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 172: + case 176: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isArrayLiteralExpression(node) { + return node.kind === 175; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 176; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 172; + return node.kind === 177; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 173; + return node.kind === 178; } ts.isElementAccessExpression = isElementAccessExpression; function isBinaryExpression(node) { - return node.kind === 187; + return node.kind === 192; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 188; + return node.kind === 193; } ts.isConditionalExpression = isConditionalExpression; function isCallExpression(node) { - return node.kind === 174; + return node.kind === 179; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; - return kind === 189 - || kind === 11; + return kind === 194 + || kind === 12; } - ts.isTemplate = isTemplate; - function isSpreadElementExpression(node) { - return node.kind === 191; + ts.isTemplateLiteral = isTemplateLiteral; + function isSpreadExpression(node) { + return node.kind === 196; } - ts.isSpreadElementExpression = isSpreadElementExpression; + ts.isSpreadExpression = isSpreadExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 194; + return node.kind === 199; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isLeftHandSideExpressionKind(kind) { - return kind === 172 - || kind === 173 - || kind === 175 - || kind === 174 - || kind === 241 - || kind === 242 - || kind === 176 - || kind === 170 + return kind === 177 || kind === 178 - || kind === 171 - || kind === 192 + || kind === 180 || kind === 179 - || kind === 69 - || kind === 10 + || kind === 246 + || kind === 247 + || kind === 181 + || kind === 175 + || kind === 183 + || kind === 176 + || kind === 197 + || kind === 184 + || kind === 70 + || kind === 11 || kind === 8 || kind === 9 - || kind === 11 - || kind === 189 - || kind === 84 - || kind === 93 - || kind === 97 - || kind === 99 - || kind === 95 - || kind === 196; + || kind === 12 + || kind === 194 + || kind === 85 + || kind === 94 + || kind === 98 + || kind === 100 + || kind === 96 + || kind === 201 + || kind === 297; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isUnaryExpressionKind(kind) { - return kind === 185 + return kind === 190 + || kind === 191 || kind === 186 - || kind === 181 + || kind === 187 + || kind === 188 + || kind === 189 || kind === 182 - || kind === 183 - || kind === 184 - || kind === 177 || isLeftHandSideExpressionKind(kind); } function isUnaryExpression(node) { @@ -7483,13 +7942,14 @@ var ts; } ts.isUnaryExpression = isUnaryExpression; function isExpressionKind(kind) { - return kind === 188 - || kind === 190 - || kind === 180 - || kind === 187 - || kind === 191 + return kind === 193 || kind === 195 - || kind === 193 + || kind === 185 + || kind === 192 + || kind === 196 + || kind === 200 + || kind === 198 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -7498,16 +7958,16 @@ var ts; ts.isExpression = isExpression; function isAssertionExpression(node) { var kind = node.kind; - return kind === 177 - || kind === 195; + return kind === 182 + || kind === 200; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 294; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 293; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -7516,15 +7976,15 @@ var ts; } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isOmittedExpression(node) { - return node.kind === 193; + return node.kind === 198; } ts.isOmittedExpression = isOmittedExpression; function isTemplateSpan(node) { - return node.kind === 197; + return node.kind === 202; } ts.isTemplateSpan = isTemplateSpan; function isBlock(node) { - return node.kind === 199; + return node.kind === 204; } ts.isBlock = isBlock; function isConciseBody(node) { @@ -7542,119 +8002,121 @@ var ts; } ts.isForInitializer = isForInitializer; function isVariableDeclaration(node) { - return node.kind === 218; + return node.kind === 223; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 219; + return node.kind === 224; } ts.isVariableDeclarationList = isVariableDeclarationList; function isCaseBlock(node) { - return node.kind === 227; + return node.kind === 232; } ts.isCaseBlock = isCaseBlock; function isModuleBody(node) { var kind = node.kind; - return kind === 226 - || kind === 225; + return kind === 231 + || kind === 230; } ts.isModuleBody = isModuleBody; function isImportEqualsDeclaration(node) { - return node.kind === 229; + return node.kind === 234; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportClause(node) { - return node.kind === 231; + return node.kind === 236; } ts.isImportClause = isImportClause; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 233 - || kind === 232; + return kind === 238 + || kind === 237; } ts.isNamedImportBindings = isNamedImportBindings; function isImportSpecifier(node) { - return node.kind === 234; + return node.kind === 239; } ts.isImportSpecifier = isImportSpecifier; function isNamedExports(node) { - return node.kind === 237; + return node.kind === 242; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 238; + return node.kind === 243; } ts.isExportSpecifier = isExportSpecifier; function isModuleOrEnumDeclaration(node) { - return node.kind === 225 || node.kind === 224; + return node.kind === 230 || node.kind === 229; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 180 - || kind === 169 - || kind === 221 - || kind === 192 - || kind === 148 - || kind === 224 - || kind === 255 - || kind === 238 - || kind === 220 - || kind === 179 - || kind === 149 - || kind === 231 + return kind === 185 + || kind === 174 + || kind === 226 + || kind === 197 + || kind === 150 || kind === 229 + || kind === 260 + || kind === 243 + || kind === 225 + || kind === 184 + || kind === 151 + || kind === 236 || kind === 234 - || kind === 222 + || kind === 239 + || kind === 227 + || kind === 149 + || kind === 148 + || kind === 230 + || kind === 233 + || kind === 237 + || kind === 144 + || kind === 257 || kind === 147 || kind === 146 - || kind === 225 + || kind === 152 + || kind === 258 || kind === 228 - || kind === 232 - || kind === 142 - || kind === 253 - || kind === 145 - || kind === 144 - || kind === 150 - || kind === 254 + || kind === 143 || kind === 223 - || kind === 141 - || kind === 218 - || kind === 279; + || kind === 285; } function isDeclarationStatementKind(kind) { - return kind === 220 - || kind === 239 - || kind === 221 - || kind === 222 - || kind === 223 - || kind === 224 - || kind === 225 - || kind === 230 + return kind === 225 + || kind === 244 + || kind === 226 + || kind === 227 + || kind === 228 || kind === 229 - || kind === 236 + || kind === 230 || kind === 235 - || kind === 228; + || kind === 234 + || kind === 241 + || kind === 240 + || kind === 233; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 210 - || kind === 209 - || kind === 217 - || kind === 204 - || kind === 202 - || kind === 201 - || kind === 207 - || kind === 208 - || kind === 206 - || kind === 203 + return kind === 215 || kind === 214 - || kind === 211 - || kind === 213 - || kind === 215 - || kind === 216 - || kind === 200 - || kind === 205 + || kind === 222 + || kind === 209 + || kind === 207 + || kind === 206 || kind === 212 - || kind === 287; + || kind === 213 + || kind === 211 + || kind === 208 + || kind === 219 + || kind === 216 + || kind === 218 + || kind === 220 + || kind === 221 + || kind === 205 + || kind === 210 + || kind === 217 + || kind === 293 + || kind === 296 + || kind === 295; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -7672,87 +8134,87 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 199; + || kind === 204; } ts.isStatement = isStatement; function isModuleReference(node) { var kind = node.kind; - return kind === 240 - || kind === 139 - || kind === 69; + return kind === 245 + || kind === 141 + || kind === 70; } ts.isModuleReference = isModuleReference; function isJsxOpeningElement(node) { - return node.kind === 243; + return node.kind === 248; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 245; + return node.kind === 249; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 97 - || kind === 69 - || kind === 172; + return kind === 98 + || kind === 70 + || kind === 177; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 241 - || kind === 248 - || kind === 242 - || kind === 244; + return kind === 246 + || kind === 252 + || kind === 247 + || kind === 10; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 246 - || kind === 247; + return kind === 250 + || kind === 251; } ts.isJsxAttributeLike = isJsxAttributeLike; function isJsxSpreadAttribute(node) { - return node.kind === 247; + return node.kind === 251; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxAttribute(node) { - return node.kind === 246; + return node.kind === 250; } ts.isJsxAttribute = isJsxAttribute; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 248; + || kind === 252; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 249 - || kind === 250; + return kind === 253 + || kind === 254; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isHeritageClause(node) { - return node.kind === 251; + return node.kind === 255; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 252; + return node.kind === 256; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 253; + return node.kind === 257; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 254; + return node.kind === 258; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 256; + return node.kind === 261; } ts.isSourceFile = isSourceFile; function isWatchSet(options) { @@ -7760,10 +8222,19 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { - return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case 5: + case 4: + return "lib.es2017.d.ts"; + case 3: + return "lib.es2016.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } } ts.getDefaultLibFileName = getDefaultLibFileName; function textSpanEnd(span) { @@ -7882,9 +8353,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 141) { + if (d && d.kind === 143) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 222) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227) { return current; } } @@ -7892,11 +8363,11 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 150 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + while (node && (node.kind === 174 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -7904,14 +8375,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= ts.getModifierFlags(node); } return flags; @@ -7920,26 +8391,73 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; })(ts || (ts = {})); var ts; (function (ts) { var NodeConstructor; var SourceFileConstructor; function createNode(kind, location, flags) { - var ConstructorForKind = kind === 256 + var ConstructorForKind = kind === 261 ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); var node = location @@ -7995,7 +8513,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -8020,14 +8538,14 @@ var ts; return node; } else if (typeof value === "boolean") { - return createNode(value ? 99 : 84, location, undefined); + return createNode(value ? 100 : 85, location, undefined); } else if (typeof value === "string") { var node = createNode(9, location, undefined); node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -8037,7 +8555,7 @@ var ts; ts.createLiteral = createLiteral; var nextAutoGenerateId = 0; function createIdentifier(text, location) { - var node = createNode(69, location); + var node = createNode(70, location); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = ts.stringToToken(text); node.autoGenerateKind = 0; @@ -8046,7 +8564,7 @@ var ts; } ts.createIdentifier = createIdentifier; function createTempVariable(recordTempVariable, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 1; @@ -8059,7 +8577,7 @@ var ts; } ts.createTempVariable = createTempVariable; function createLoopVariable(location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 2; @@ -8069,7 +8587,7 @@ var ts; } ts.createLoopVariable = createLoopVariable; function createUniqueName(text, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = text; name.originalKeywordKind = 0; name.autoGenerateKind = 3; @@ -8079,7 +8597,7 @@ var ts; } ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.original = node; name.text = ""; name.originalKeywordKind = 0; @@ -8094,22 +8612,22 @@ var ts; } ts.createToken = createToken; function createSuper() { - var node = createNode(95); + var node = createNode(96); return node; } ts.createSuper = createSuper; function createThis(location) { - var node = createNode(97, location); + var node = createNode(98, location); return node; } ts.createThis = createThis; function createNull() { - var node = createNode(93); + var node = createNode(94); return node; } ts.createNull = createNull; function createComputedPropertyName(expression, location) { - var node = createNode(140, location); + var node = createNode(142, location); node.expression = expression; return node; } @@ -8121,12 +8639,8 @@ var ts; return node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createParameter(name, initializer, location) { - return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); - } - ts.createParameter = createParameter; - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { - var node = createNode(142, location, flags); + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(144, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.dotDotDotToken = dotDotDotToken; @@ -8136,16 +8650,16 @@ var ts; node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; return node; } - ts.createParameterDeclaration = createParameterDeclaration; - function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); } return node; } - ts.updateParameterDeclaration = updateParameterDeclaration; + ts.updateParameter = updateParameter; function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { - var node = createNode(145, location); + var node = createNode(147, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -8163,7 +8677,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(147, location, flags); + var node = createNode(149, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -8183,7 +8697,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body, location, flags) { - var node = createNode(148, location, flags); + var node = createNode(150, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = undefined; @@ -8201,7 +8715,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { - var node = createNode(149, location, flags); + var node = createNode(151, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -8220,7 +8734,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { - var node = createNode(150, location, flags); + var node = createNode(152, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -8238,7 +8752,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createObjectBindingPattern(elements, location) { - var node = createNode(167, location); + var node = createNode(172, location); node.elements = createNodeArray(elements); return node; } @@ -8251,7 +8765,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements, location) { - var node = createNode(168, location); + var node = createNode(173, location); node.elements = createNodeArray(elements); return node; } @@ -8264,7 +8778,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { - var node = createNode(169, location); + var node = createNode(174, location); node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; node.dotDotDotToken = dotDotDotToken; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -8272,15 +8786,15 @@ var ts; return node; } ts.createBindingElement = createBindingElement; - function updateBindingElement(node, propertyName, name, initializer) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, location, multiLine) { - var node = createNode(170, location); + var node = createNode(175, location); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) { node.multiLine = true; @@ -8296,7 +8810,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, location, multiLine) { - var node = createNode(171, location); + var node = createNode(176, location); node.properties = createNodeArray(properties); if (multiLine) { node.multiLine = true; @@ -8312,9 +8826,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name, location, flags) { - var node = createNode(172, location, flags); + var node = createNode(177, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 65536; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -8322,14 +8836,14 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index, location) { - var node = createNode(173, location); + var node = createNode(178, location); node.expression = parenthesizeForAccess(expression); node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; return node; @@ -8343,7 +8857,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(174, location, flags); + var node = createNode(179, location, flags); node.expression = parenthesizeForAccess(expression); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -8360,7 +8874,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(175, location, flags); + var node = createNode(180, location, flags); node.expression = parenthesizeForNew(expression); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -8375,7 +8889,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template, location) { - var node = createNode(176, location); + var node = createNode(181, location); node.tag = parenthesizeForAccess(tag); node.template = template; return node; @@ -8389,7 +8903,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createParen(expression, location) { - var node = createNode(178, location); + var node = createNode(183, location); node.expression = expression; return node; } @@ -8401,9 +8915,9 @@ var ts; return node; } ts.updateParen = updateParen; - function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(179, location, flags); - node.modifiers = undefined; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(184, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -8413,20 +8927,20 @@ var ts; return node; } ts.createFunctionExpression = createFunctionExpression; - function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); } return node; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { - var node = createNode(180, location, flags); + var node = createNode(185, location, flags); node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35); node.body = parenthesizeConciseBody(body); return node; } @@ -8439,7 +8953,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression, location) { - var node = createNode(181, location); + var node = createNode(186, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -8452,7 +8966,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression, location) { - var node = createNode(182, location); + var node = createNode(187, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -8465,7 +8979,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression, location) { - var node = createNode(183, location); + var node = createNode(188, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -8478,7 +8992,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression, location) { - var node = createNode(184, location); + var node = createNode(189, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -8491,7 +9005,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand, location) { - var node = createNode(185, location); + var node = createNode(190, location); node.operator = operator; node.operand = parenthesizePrefixOperand(operand); return node; @@ -8505,7 +9019,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator, location) { - var node = createNode(186, location); + var node = createNode(191, location); node.operand = parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -8519,9 +9033,9 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; - var node = createNode(187, location); + var node = createNode(192, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); node.operatorToken = operatorToken; node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); @@ -8535,13 +9049,21 @@ var ts; return node; } ts.updateBinary = updateBinary; - function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { - var node = createNode(188, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) { + var node = createNode(193, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + node.questionToken = createToken(54); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(55); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } ts.createConditional = createConditional; @@ -8553,7 +9075,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans, location) { - var node = createNode(189, location); + var node = createNode(194, location); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -8567,7 +9089,7 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createYield(asteriskToken, expression, location) { - var node = createNode(190, location); + var node = createNode(195, location); node.asteriskToken = asteriskToken; node.expression = expression; return node; @@ -8581,7 +9103,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression, location) { - var node = createNode(191, location); + var node = createNode(196, location); node.expression = parenthesizeExpressionForList(expression); return node; } @@ -8594,7 +9116,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(192, location); + var node = createNode(197, location); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -8612,12 +9134,12 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression(location) { - var node = createNode(193, location); + var node = createNode(198, location); return node; } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression, location) { - var node = createNode(194, location); + var node = createNode(199, location); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.expression = parenthesizeForAccess(expression); return node; @@ -8631,7 +9153,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createTemplateSpan(expression, literal, location) { - var node = createNode(197, location); + var node = createNode(202, location); node.expression = expression; node.literal = literal; return node; @@ -8645,7 +9167,7 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createBlock(statements, location, multiLine, flags) { - var block = createNode(199, location, flags); + var block = createNode(204, location, flags); block.statements = createNodeArray(statements); if (multiLine) { block.multiLine = true; @@ -8661,7 +9183,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList, location, flags) { - var node = createNode(200, location, flags); + var node = createNode(205, location, flags); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -8676,7 +9198,7 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createVariableDeclarationList(declarations, location, flags) { - var node = createNode(219, location, flags); + var node = createNode(224, location, flags); node.declarations = createNodeArray(declarations); return node; } @@ -8689,7 +9211,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createVariableDeclaration(name, type, initializer, location, flags) { - var node = createNode(218, location, flags); + var node = createNode(223, location, flags); node.name = typeof name === "string" ? createIdentifier(name) : name; node.type = type; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -8704,11 +9226,11 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement(location) { - return createNode(201, location); + return createNode(206, location); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression, location, flags) { - var node = createNode(202, location, flags); + var node = createNode(207, location, flags); node.expression = parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -8721,7 +9243,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement, location) { - var node = createNode(203, location); + var node = createNode(208, location); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -8736,7 +9258,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression, location) { - var node = createNode(204, location); + var node = createNode(209, location); node.statement = statement; node.expression = expression; return node; @@ -8750,7 +9272,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement, location) { - var node = createNode(205, location); + var node = createNode(210, location); node.expression = expression; node.statement = statement; return node; @@ -8764,7 +9286,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement, location) { - var node = createNode(206, location, undefined); + var node = createNode(211, location, undefined); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -8780,7 +9302,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement, location) { - var node = createNode(207, location); + var node = createNode(212, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -8795,7 +9317,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(initializer, expression, statement, location) { - var node = createNode(208, location); + var node = createNode(213, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -8810,7 +9332,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label, location) { - var node = createNode(209, location); + var node = createNode(214, location); if (label) { node.label = label; } @@ -8825,7 +9347,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label, location) { - var node = createNode(210, location); + var node = createNode(215, location); if (label) { node.label = label; } @@ -8840,7 +9362,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression, location) { - var node = createNode(211, location); + var node = createNode(216, location); node.expression = expression; return node; } @@ -8853,7 +9375,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement, location) { - var node = createNode(212, location); + var node = createNode(217, location); node.expression = expression; node.statement = statement; return node; @@ -8867,7 +9389,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock, location) { - var node = createNode(213, location); + var node = createNode(218, location); node.expression = parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -8881,7 +9403,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement, location) { - var node = createNode(214, location); + var node = createNode(219, location); node.label = typeof label === "string" ? createIdentifier(label) : label; node.statement = statement; return node; @@ -8895,7 +9417,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression, location) { - var node = createNode(215, location); + var node = createNode(220, location); node.expression = expression; return node; } @@ -8908,7 +9430,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock, location) { - var node = createNode(216, location); + var node = createNode(221, location); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -8923,7 +9445,7 @@ var ts; } ts.updateTry = updateTry; function createCaseBlock(clauses, location) { - var node = createNode(227, location); + var node = createNode(232, location); node.clauses = createNodeArray(clauses); return node; } @@ -8936,7 +9458,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(220, location, flags); + var node = createNode(225, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -8956,7 +9478,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(221, location); + var node = createNode(226, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -8974,7 +9496,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { - var node = createNode(230, location); + var node = createNode(235, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.importClause = importClause; @@ -8990,7 +9512,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings, location) { - var node = createNode(231, location); + var node = createNode(236, location); node.name = name; node.namedBindings = namedBindings; return node; @@ -9004,7 +9526,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name, location) { - var node = createNode(232, location); + var node = createNode(237, location); node.name = name; return node; } @@ -9017,7 +9539,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements, location) { - var node = createNode(233, location); + var node = createNode(238, location); node.elements = createNodeArray(elements); return node; } @@ -9030,7 +9552,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name, location) { - var node = createNode(234, location); + var node = createNode(239, location); node.propertyName = propertyName; node.name = name; return node; @@ -9044,7 +9566,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { - var node = createNode(235, location); + var node = createNode(240, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.isExportEquals = isExportEquals; @@ -9060,7 +9582,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { - var node = createNode(236, location); + var node = createNode(241, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.exportClause = exportClause; @@ -9076,7 +9598,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements, location) { - var node = createNode(237, location); + var node = createNode(242, location); node.elements = createNodeArray(elements); return node; } @@ -9089,7 +9611,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(name, propertyName, location) { - var node = createNode(238, location); + var node = createNode(243, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; return node; @@ -9103,7 +9625,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createJsxElement(openingElement, children, closingElement, location) { - var node = createNode(241, location); + var node = createNode(246, location); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -9118,7 +9640,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes, location) { - var node = createNode(242, location); + var node = createNode(247, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -9132,7 +9654,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes, location) { - var node = createNode(243, location); + var node = createNode(248, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -9146,7 +9668,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName, location) { - var node = createNode(245, location); + var node = createNode(249, location); node.tagName = tagName; return node; } @@ -9159,7 +9681,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxAttribute(name, initializer, location) { - var node = createNode(246, location); + var node = createNode(250, location); node.name = name; node.initializer = initializer; return node; @@ -9173,7 +9695,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxSpreadAttribute(expression, location) { - var node = createNode(247, location); + var node = createNode(251, location); node.expression = expression; return node; } @@ -9186,7 +9708,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(expression, location) { - var node = createNode(248, location); + var node = createNode(252, location); node.expression = expression; return node; } @@ -9199,7 +9721,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createHeritageClause(token, types, location) { - var node = createNode(251, location); + var node = createNode(255, location); node.token = token; node.types = createNodeArray(types); return node; @@ -9213,7 +9735,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements, location) { - var node = createNode(249, location); + var node = createNode(253, location); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -9227,7 +9749,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements, location) { - var node = createNode(250, location); + var node = createNode(254, location); node.statements = createNodeArray(statements); return node; } @@ -9240,7 +9762,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createCatchClause(variableDeclaration, block, location) { - var node = createNode(252, location); + var node = createNode(256, location); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -9254,7 +9776,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer, location) { - var node = createNode(253, location); + var node = createNode(257, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.questionToken = undefined; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -9269,12 +9791,18 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { - var node = createNode(254, location); + var node = createNode(258, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function createSpreadAssignment(expression, location) { + var node = createNode(259, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -9282,9 +9810,16 @@ var ts; return node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSpreadAssignment(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createNode(256, node, node.flags); + var updated = createNode(261, node, node.flags); updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; @@ -9338,21 +9873,33 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) - updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } return node; } ts.updateSourceFileNode = updateSourceFileNode; function createNotEmittedStatement(original) { - var node = createNode(287, original); + var node = createNode(293, original); node.original = original; return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + function createEndOfDeclarationMarker(original) { + var node = createNode(296); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + function createMergeDeclarationMarker(original) { + var node = createNode(295); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original, location) { - var node = createNode(288, location || original); + var node = createNode(294, location || original); node.expression = expression; node.original = original; return node; @@ -9365,69 +9912,77 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createRawExpression(text) { + var node = createNode(297); + node.text = text; + return node; + } + ts.createRawExpression = createRawExpression; function createComma(left, right) { - return createBinary(left, 24, right); + return createBinary(left, 25, right); } ts.createComma = createComma; function createLessThan(left, right, location) { - return createBinary(left, 25, right, location); + return createBinary(left, 26, right, location); } ts.createLessThan = createLessThan; function createAssignment(left, right, location) { - return createBinary(left, 56, right, location); + return createBinary(left, 57, right, location); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 32, right); + return createBinary(left, 33, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 33, right); + return createBinary(left, 34, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 35, right); + return createBinary(left, 36, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 36, right); + return createBinary(left, 37, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand, location) { - return createPostfix(operand, 41, location); + return createPostfix(operand, 42, location); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 51, right); + return createBinary(left, 52, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 52, right); + return createBinary(left, 53, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(49, operand); + return createPrefix(50, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { return createVoid(createLiteral(0)); } ts.createVoidZero = createVoidZero; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; function createMemberAccessForPropertyName(target, memberName, location) { if (ts.isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 64; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; - function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); - } - ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { return createCall(createPropertyAccess(func, "call"), undefined, [ thisArg @@ -9460,10 +10015,26 @@ var ts; function createReactNamespace(reactNamespace, parent) { var react = createIdentifier(reactNamespace || "React"); react.flags &= ~8; - react.parent = parent; + react.parent = ts.getParseTreeNode(parent); return react; } - function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = createSynthesizedNode(70); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { var argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -9483,9 +10054,21 @@ var ts; argumentsList.push(children[0]); } } - return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList, location); } - ts.createReactCreateElement = createReactCreateElement; + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExportDefault(expression) { + return createExportAssignment(undefined, undefined, false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(undefined, undefined, createNamedExports([createExportSpecifier(exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function createLetStatement(name, initializer, location) { + return createVariableStatement(undefined, createLetDeclarationList([createVariableDeclaration(name, undefined, initializer)]), location); + } + ts.createLetStatement = createLetStatement; function createLetDeclarationList(declarations, location) { return createVariableDeclarationList(declarations, location, 1); } @@ -9494,130 +10077,26 @@ var ts; return createVariableDeclarationList(declarations, location, 2); } ts.createConstDeclarationList = createConstDeclarationList; - function createHelperName(externalHelpersModuleName, name) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + function getHelperName(name) { + return setEmitFlags(createIdentifier(name), 4096 | 2); } - ts.createHelperName = createHelperName; - function createExtendsHelper(externalHelpersModuleName, name) { - return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ - name, - createIdentifier("_super") - ]); - } - ts.createExtendsHelper = createExtendsHelper; - function createAssignHelper(externalHelpersModuleName, attributesSegments) { - return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); - } - ts.createAssignHelper = createAssignHelper; - function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { - return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ - createLiteral(parameterOffset), - expression - ], location); - } - ts.createParamHelper = createParamHelper; - function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { - return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ - createLiteral(metadataKey), - metadataValue - ]); - } - ts.createMetadataHelper = createMetadataHelper; - function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { - var argumentsArray = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); - } - ts.createDecorateHelper = createDecorateHelper; - function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; - return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ]); - } - ts.createAwaiterHelper = createAwaiterHelper; - function createHasOwnProperty(target, propertyName) { - return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); - } - ts.createHasOwnProperty = createHasOwnProperty; - function createObjectCreate(prototype) { - return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); - } - function createGeti(target) { - return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); - } - function createSeti(target) { - return createArrowFunction(undefined, undefined, [ - createParameter("name"), - createParameter("value") - ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); - } - function createAdvancedAsyncSuperHelper() { - var createCache = createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) - ])); - var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ - createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) - ])); - var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ - createStatement(createCall(createIdentifier("seti"), undefined, [ - createIdentifier("name"), - createIdentifier("v") - ])) - ])); - var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ - getter, - setter - ])))))); - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ - createParameter("geti"), - createParameter("seti") - ], undefined, createBlock([ - createCache, - getOrCreateAccessorsForName - ]))), undefined, [ - createGeti(createSuper()), - createSeti(createSuper()) - ])) - ])); - } - ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; - function createSimpleAsyncSuperHelper() { - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createGeti(createSuper())) - ])); - } - ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + ts.getHelperName = getHelperName; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 69: + case 70: return cacheIdentifiers; - case 97: + case 98: case 8: case 9: return false; - case 170: + case 175: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 171: + case 176: return target.properties.length > 0; default: return true; @@ -9631,13 +10110,13 @@ var ts; thisArg = createThis(); target = callee; } - else if (callee.kind === 95) { + else if (callee.kind === 96) { thisArg = createThis(); target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; } else { switch (callee.kind) { - case 172: { + case 177: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); @@ -9648,7 +10127,7 @@ var ts; } break; } - case 173: { + case 178: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); @@ -9698,14 +10177,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 149: - case 150: + case 151: + case 152: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 253: + case 257: return createExpressionForPropertyAssignment(property, receiver); - case 254: + case 258: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 147: + case 149: return createExpressionForMethodDeclaration(property, receiver); } } @@ -9715,13 +10194,13 @@ var ts; if (property === firstAccessor) { var properties_1 = []; if (getAccessor) { - var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + var getterFunction = createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); setOriginalNode(getterFunction, getAccessor); var getter = createPropertyAssignment("get", getterFunction); properties_1.push(getter); } if (setAccessor) { - var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + var setterFunction = createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); setOriginalNode(setterFunction, setAccessor); var setter = createPropertyAssignment("set", setterFunction); properties_1.push(setter); @@ -9744,13 +10223,70 @@ var ts; return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); } + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384); + } + ts.getLocalName = getLocalName; + function isLocalName(node) { + return (getEmitFlags(node) & 16384) !== 0; + } + ts.isLocalName = isLocalName; + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192); + } + ts.getExportName = getExportName; + function isExportName(node) { + return (getEmitFlags(node) & 8192) !== 0; + } + ts.isExportName = isExportName; + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { + var name_8 = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(name_8, emitFlags); + return name_8; + } + return getGeneratedNameForNode(node); + } + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), name); + var emitFlags; + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : createBlock([createReturn(node, node)], node, multiLine); + } + ts.convertToFunctionBody = convertToFunctionBody; function isUseStrictPrologue(node) { return node.expression.text === "use strict"; } function addPrologueDirectives(target, source, ensureUseStrict, visitor) { - ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; var statementOffset = 0; var numStatements = source.length; @@ -9763,25 +10299,58 @@ var ts; target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (statement.emitFlags & 8388608) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (getEmitFlags(statement) & 524288) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + function ensureUseStrict(statements) { + var foundUseStrict = false; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))) + ].concat(statements), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 178) { + if (skipped.kind === 183) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -9790,15 +10359,15 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(192, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(192, binaryOperator); var emittedOperand = skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 190) { + && operand.kind === 195) { return false; } return true; @@ -9814,7 +10383,7 @@ var ts; if (operatorHasAssociativeProperty(binaryOperator)) { return false; } - if (binaryOperator === 35) { + if (binaryOperator === 36) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -9827,17 +10396,17 @@ var ts; } } function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 37 + return binaryOperator === 38 + || binaryOperator === 48 || binaryOperator === 47 - || binaryOperator === 46 - || binaryOperator === 48; + || binaryOperator === 49; } function getLiteralKindOfBinaryPlusOperand(node) { node = skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.kind === 192 && node.operatorToken.kind === 36) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -9851,12 +10420,27 @@ var ts; } return 0; } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(193, 54); + var emittedCondition = skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + return createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + return e.kind === 192 && e.operatorToken.kind === 25 + ? createParen(e) + : e; + } function parenthesizeForNew(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { - case 174: + case 179: return createParen(expression); - case 175: + case 180: return emittedExpression.arguments ? expression : createParen(expression); @@ -9867,7 +10451,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && (emittedExpression.kind !== 180 || emittedExpression.arguments) && emittedExpression.kind !== 8) { return expression; } @@ -9905,7 +10489,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(187, 24); + var commaPrecedence = ts.getOperatorPrecedence(192, 25); return expressionPrecedence > commaPrecedence ? expression : createParen(expression, expression); @@ -9916,7 +10500,7 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 179 || kind === 180) { + if (kind === 184 || kind === 185) { var mutableCall = getMutableClone(emittedExpression); mutableCall.expression = createParen(callee, callee); return recreatePartiallyEmittedExpressions(expression, mutableCall); @@ -9924,7 +10508,7 @@ var ts; } else { var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + if (leftmostExpressionKind === 176 || leftmostExpressionKind === 184) { return createParen(expression, expression); } } @@ -9942,21 +10526,21 @@ var ts; function getLeftmostExpression(node) { while (true) { switch (node.kind) { - case 186: + case 191: node = node.operand; continue; - case 187: + case 192: node = node.left; continue; - case 188: + case 193: node = node.condition; continue; - case 174: - case 173: - case 172: + case 179: + case 178: + case 177: node = node.expression; continue; - case 288: + case 294: node = node.expression; continue; } @@ -9965,7 +10549,7 @@ var ts; } function parenthesizeConciseBody(body) { var emittedBody = skipPartiallyEmittedExpressions(body); - if (emittedBody.kind === 171) { + if (emittedBody.kind === 176) { return createParen(body, body); } return body; @@ -9990,7 +10574,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 178) { + while (node.kind === 183) { node = node.expression; } return node; @@ -10004,7 +10588,7 @@ var ts; } ts.skipAssertions = skipAssertions; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 294) { node = node.expression; } return node; @@ -10018,17 +10602,214 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + if (!destEmitNode) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 261) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { + if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var helpers = getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + if (!helper.scoped) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!ts.contains(emitNode.helpers, helper)) { + emitNode.helpers = ts.append(emitNode.helpers, helper); + } + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!ts.contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0; + if (x.priority === y.priority) + return 0; + if (x.priority === undefined) + return 1; + if (y.priority === undefined) + return -1; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -10058,10 +10839,10 @@ var ts; var name_9 = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } - if (node.kind === 230 && node.importClause) { + if (node.kind === 235 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 236 && node.moduleSpecifier) { + if (node.kind === 241 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; @@ -10099,6 +10880,291 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + return ts.isAssignmentExpression(bindingElement.initializer, true) + ? bindingElement.initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return bindingElement.right; + } + if (ts.isSpreadExpression(bindingElement)) { + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 257: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 258: + return bindingElement.name; + case 259: + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadExpression(bindingElement)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 144: + case 174: + return bindingElement.dotDotDotToken; + case 196: + case 259: + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 174: + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 257: + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 259: + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 172: + case 173: + case 175: + return name.elements; + case 176: + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return convertToArrayAssignmentPattern(node); + case 172: + case 176: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportedBindings = ts.createMap(); + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration(undefined, undefined, createImportClause(undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 235: + externalImports.push(node); + break; + case 234: + if (node.moduleReference.kind === 245) { + externalImports.push(node); + } + break; + case 241: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports[specifier.name.text]) { + var name_10 = specifier.propertyName || specifier.name; + ts.multiMapAdd(exportSpecifiers, name_10.text, specifier); + var decl = resolver.getReferencedImportDeclaration(name_10) + || resolver.getReferencedValueDeclaration(name_10); + if (decl) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); + } + uniqueExports[specifier.name.text] = true; + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 240: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 205: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 225: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_11 = node.name; + if (!uniqueExports[name_11.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_11); + uniqueExports[name_11.text] = true; + exportedNames = ts.append(exportedNames, name_11); + } + } + } + break; + case 226: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_12 = node.name; + if (!uniqueExports[name_12.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_12); + uniqueExports[name_12.text] = true; + exportedNames = ts.append(exportedNames, name_12); + } + } + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -10107,13 +11173,13 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 256) { + if (kind === 261) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { + else if (kind === 70) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } - else if (kind < 139) { + else if (kind < 141) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); } else { @@ -10149,26 +11215,28 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 139: + case 141: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 141: + case 143: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 254: + case 258: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 142: - case 145: + case 259: + return visitNode(cbNode, node.expression); case 144: - case 253: - case 218: - case 169: + case 147: + case 146: + case 257: + case 223: + case 174: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -10177,24 +11245,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 156: - case 157: - case 151: - case 152: + case 158: + case 159: case 153: + case 154: + case 155: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 179: - case 220: - case 180: + case 151: + case 152: + case 184: + case 225: + case 185: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -10205,308 +11273,320 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 155: + case 157: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 154: + case 156: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 158: - return visitNode(cbNode, node.exprName); - case 159: - return visitNodes(cbNodes, node.members); case 160: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 161: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 162: + return visitNode(cbNode, node.elementType); case 163: - return visitNodes(cbNodes, node.types); + return visitNodes(cbNodes, node.elementTypes); case 164: - return visitNode(cbNode, node.type); + case 165: + return visitNodes(cbNodes, node.types); case 166: - return visitNode(cbNode, node.literal); - case 167: case 168: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); + case 169: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); case 170: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); case 171: - return visitNodes(cbNodes, node.properties); + return visitNode(cbNode, node.literal); case 172: + case 173: + return visitNodes(cbNodes, node.elements); + case 175: + return visitNodes(cbNodes, node.elements); + case 176: + return visitNodes(cbNodes, node.properties); + case 177: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 173: + case 178: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 174: - case 175: + case 179: + case 180: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 176: + case 181: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 177: + case 182: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 178: - return visitNode(cbNode, node.expression); - case 181: - return visitNode(cbNode, node.expression); - case 182: - return visitNode(cbNode, node.expression); case 183: return visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.operand); + case 186: + return visitNode(cbNode, node.expression); + case 187: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); case 190: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 184: + case 189: return visitNode(cbNode, node.expression); - case 186: + case 191: return visitNode(cbNode, node.operand); - case 187: + case 192: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 195: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 196: + case 201: return visitNode(cbNode, node.expression); - case 188: + case 193: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 191: + case 196: return visitNode(cbNode, node.expression); - case 199: - case 226: + case 204: + case 231: return visitNodes(cbNodes, node.statements); - case 256: + case 261: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 200: + case 205: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 219: + case 224: return visitNodes(cbNodes, node.declarations); - case 202: + case 207: return visitNode(cbNode, node.expression); - case 203: + case 208: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 204: + case 209: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 205: + case 210: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206: + case 211: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 207: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 208: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 209: - case 210: - return visitNode(cbNode, node.label); - case 211: - return visitNode(cbNode, node.expression); case 212: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 213: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + case 215: + return visitNode(cbNode, node.label); + case 216: + return visitNode(cbNode, node.expression); + case 217: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 218: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 227: + case 232: return visitNodes(cbNodes, node.clauses); - case 249: + case 253: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 250: + case 254: return visitNodes(cbNodes, node.statements); - case 214: + case 219: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 215: + case 220: return visitNode(cbNode, node.expression); - case 216: + case 221: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 252: + case 256: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 143: + case 145: return visitNode(cbNode, node.expression); - case 221: - case 192: + case 226: + case 197: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 222: + case 227: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 223: + case 228: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 224: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 255: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 225: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); case 229: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNodes(cbNodes, node.members); + case 260: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 230: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 234: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 235: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 231: + case 236: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228: - return visitNode(cbNode, node.name); - case 232: - return visitNode(cbNode, node.name); case 233: + return visitNode(cbNode, node.name); case 237: + return visitNode(cbNode, node.name); + case 238: + case 242: return visitNodes(cbNodes, node.elements); - case 236: + case 241: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 234: - case 238: + case 239: + case 243: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 235: + case 240: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 197: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 140: - return visitNode(cbNode, node.expression); - case 251: - return visitNodes(cbNodes, node.types); case 194: + return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); + case 202: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 142: + return visitNode(cbNode, node.expression); + case 255: + return visitNodes(cbNodes, node.types); + case 199: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 240: + case 245: return visitNode(cbNode, node.expression); - case 239: + case 244: return visitNodes(cbNodes, node.decorators); - case 241: + case 246: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 242: - case 243: + case 247: + case 248: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 246: + case 250: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 247: + case 251: return visitNode(cbNode, node.expression); - case 248: + case 252: return visitNode(cbNode, node.expression); - case 245: + case 249: return visitNode(cbNode, node.tagName); - case 257: - return visitNode(cbNode, node.type); - case 261: - return visitNodes(cbNodes, node.types); case 262: - return visitNodes(cbNodes, node.types); - case 260: - return visitNode(cbNode, node.elementType); - case 264: - return visitNode(cbNode, node.type); - case 263: - return visitNode(cbNode, node.type); - case 265: - return visitNode(cbNode, node.literal); - case 267: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 268: - return visitNode(cbNode, node.type); - case 269: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 270: - return visitNode(cbNode, node.type); - case 271: - return visitNode(cbNode, node.type); - case 272: return visitNode(cbNode, node.type); case 266: + return visitNodes(cbNodes, node.types); + case 267: + return visitNodes(cbNodes, node.types); + case 265: + return visitNode(cbNode, node.elementType); + case 269: + return visitNode(cbNode, node.type); + case 268: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.literal); + case 272: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 273: + return visitNode(cbNode, node.type); + case 274: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 275: + return visitNode(cbNode, node.type); + case 276: + return visitNode(cbNode, node.type); + case 277: + return visitNode(cbNode, node.type); + case 271: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 273: + case 278: return visitNodes(cbNodes, node.tags); - case 275: + case 281: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 276: + case 282: return visitNode(cbNode, node.typeExpression); - case 277: + case 283: return visitNode(cbNode, node.typeExpression); - case 278: + case 280: + return visitNode(cbNode, node.typeExpression); + case 284: return visitNodes(cbNodes, node.typeParameters); - case 279: + case 285: return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.jsDocTypeLiteral); - case 281: + case 287: return visitNodes(cbNodes, node.jsDocPropertyTags); - case 280: + case 286: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 288: + case 294: return visitNode(cbNode, node.expression); - case 282: + case 288: return visitNode(cbNode, node.literal); } } @@ -10520,6 +11600,10 @@ var ts; return result; } ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } @@ -10542,8 +11626,8 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 32768 | 131072; + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -10559,18 +11643,27 @@ var ts; var parsingContext; var contextFlags; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; function getLanguageVariant(scriptKind) { return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; } - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); TokenConstructor = ts.objectAllocator.getTokenConstructor(); IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); @@ -10582,7 +11675,7 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -10617,7 +11710,7 @@ var ts; return sourceFile; } function addJSDocComment(node) { - var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; @@ -10625,10 +11718,10 @@ var ts; if (!jsDoc) { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } return node; @@ -10643,12 +11736,12 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -10657,7 +11750,7 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(261, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -10677,16 +11770,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 32768); + setContextFlag(val, 2048); } function setYieldContext(val) { - setContextFlag(val, 65536); + setContextFlag(val, 4096); } function setDecoratorContext(val) { - setContextFlag(val, 131072); + setContextFlag(val, 8192); } function setAwaitContext(val) { - setContextFlag(val, 262144); + setContextFlag(val, 16384); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -10709,40 +11802,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(32768, func); + return doOutsideOfContext(2048, func); } function disallowInAnd(func) { - return doInsideOfContext(32768, func); + return doInsideOfContext(2048, func); } function doInYieldContext(func) { - return doInsideOfContext(65536, func); + return doInsideOfContext(4096, func); } function doInDecoratorContext(func) { - return doInsideOfContext(131072, func); + return doInsideOfContext(8192, func); } function doInAwaitContext(func) { - return doInsideOfContext(262144, func); + return doInsideOfContext(16384, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(262144, func); + return doOutsideOfContext(16384, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(65536 | 262144, func); + return doInsideOfContext(4096 | 16384, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(65536); + return inContext(4096); } function inDisallowInContext() { - return inContext(32768); + return inContext(2048); } function inDecoratorContext() { - return inContext(131072); + return inContext(8192); } function inAwaitContext() { - return inContext(262144); + return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -10813,16 +11906,16 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token() === 70) { return true; } - if (token() === 114 && inYieldContext()) { + if (token() === 115 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token() === 120 && inAwaitContext()) { return false; } - return token() > 105; + return token() > 106; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -10863,20 +11956,20 @@ var ts; return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token() === 24) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token() === 17 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token() === 24) { nextToken(); } return true; } else { - return parseExpected(23); + return parseExpected(24); } } function createNode(kind, pos) { @@ -10884,8 +11977,8 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + return kind >= 141 ? new NodeConstructor(kind, pos, pos) : + kind === 70 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } function createNodeArray(elements, pos) { @@ -10904,7 +11997,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 524288; + node.flags |= 32768; } return node; } @@ -10926,15 +12019,15 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(69); - if (token() !== 69) { + var node = createNode(70); + if (token() !== 70) { node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); } - return createMissingNode(69, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(70, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -10951,7 +12044,7 @@ var ts; if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token() === 20) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -10966,10 +12059,10 @@ var ts; return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { - var node = createNode(140); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(142); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); return finishNode(node); } function parseContextualModifier(t) { @@ -10983,20 +12076,20 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { - return nextToken() === 81; + if (token() === 75) { + return nextToken() === 82; } - if (token() === 82) { + if (token() === 83) { nextToken(); - if (token() === 77) { + if (token() === 78) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token() !== 38 && token() !== 117 && token() !== 16 && canFollowModifier(); } - if (token() === 77) { + if (token() === 78) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token() === 114) { nextToken(); return canFollowModifier(); } @@ -11006,16 +12099,16 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token() === 20 + || token() === 16 + || token() === 38 + || token() === 23 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 74 || token() === 88 || + (token() === 119 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -11026,21 +12119,23 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 24 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token() === 72 || token() === 78; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 24 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token() === 20 || token() === 38 || token() === 23 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || token() === 23 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token() === 16) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -11052,39 +12147,39 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); - case 17: + return token() === 25 || token() === 23 || isIdentifierOrPattern(); + case 18: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token() === 25 || token() === 23 || isStartOfExpression(); case 16: return isStartOfParameter(); - case 18: case 19: - return token() === 24 || isStartOfType(); case 20: - return isHeritageClause(); + return token() === 25 || isStartOfType(); case 21: + return isHeritageClause(); + case 22: return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 16; case 14: return true; - case 22: case 23: - case 25: - return JSDocParser.isJSDocType(); case 24: + case 26: + return JSDocParser.isJSDocType(); + case 25: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); - if (nextToken() === 16) { + ts.Debug.assert(token() === 16); + if (nextToken() === 17) { var next = nextToken(); - return next === 24 || next === 15 || next === 83 || next === 106; + return next === 25 || next === 16 || next === 84 || next === 107; } return true; } @@ -11097,8 +12192,8 @@ var ts; return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token() === 107 || + token() === 84) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -11119,40 +12214,41 @@ var ts; case 6: case 12: case 9: - case 21: - return token() === 16; + case 22: + return token() === 17; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token() === 17 || token() === 72 || token() === 78; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token() === 16 || token() === 84 || token() === 107; case 8: return isVariableDeclaratorListTerminator(); - case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; - case 11: - return token() === 18 || token() === 23; - case 15: - case 19: - case 10: - return token() === 20; - case 16: - return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() === 28 || token() === 18 || token() === 16 || token() === 84 || token() === 107; + case 11: + return token() === 19 || token() === 24; + case 15: case 20: - return token() === 15 || token() === 16; + case 10: + return token() === 21; + case 16: + case 17: + return token() === 19 || token() === 21; + case 19: + return token() !== 25; + case 21: + return token() === 16 || token() === 17; case 13: - return token() === 27 || token() === 39; + return token() === 28 || token() === 40; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); - case 22: - return token() === 18 || token() === 54 || token() === 16; + return token() === 26 && lookAhead(nextTokenIsSlash); case 23: - return token() === 27 || token() === 16; - case 25: - return token() === 20 || token() === 16; + return token() === 19 || token() === 55 || token() === 17; case 24: - return token() === 16; + return token() === 28 || token() === 17; + case 26: + return token() === 21 || token() === 17; + case 25: + return token() === 17; } } function isVariableDeclaratorListTerminator() { @@ -11162,13 +12258,13 @@ var ts; if (isInOrOfKeyword(token())) { return true; } - if (token() === 34) { + if (token() === 35) { return true; } return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 26; kind++) { + for (var kind = 0; kind < 27; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -11219,7 +12315,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 1540096; + var nodeContextFlags = node.flags & 96256; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -11251,10 +12347,12 @@ var ts; return isReusableVariableDeclaration(node); case 16: return isReusableParameter(node); - case 20: case 17: - case 19: + return false; + case 21: case 18: + case 20: + case 19: case 11: case 12: case 7: @@ -11266,17 +12364,17 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 148: - case 153: - case 149: case 150: - case 145: - case 198: - return true; + case 155: + case 151: + case 152: case 147: + case 203: + return true; + case 149: var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 69 && - methodDeclaration.name.originalKeywordKind === 121; + var nameIsConstructor = methodDeclaration.name.kind === 70 && + methodDeclaration.name.originalKeywordKind === 122; return !nameIsConstructor; } } @@ -11285,8 +12383,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 249: - case 250: + case 253: + case 254: return true; } } @@ -11295,65 +12393,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 220: - case 200: - case 199: - case 203: - case 202: - case 215: - case 211: - case 213: - case 210: - case 209: - case 207: - case 208: - case 206: - case 205: - case 212: - case 201: - case 216: - case 214: - case 204: - case 217: - case 230: - case 229: - case 236: - case 235: case 225: + case 205: + case 204: + case 208: + case 207: + case 220: + case 216: + case 218: + case 215: + case 214: + case 212: + case 213: + case 211: + case 210: + case 217: + case 206: case 221: + case 219: + case 209: case 222: - case 224: - case 223: + case 235: + case 234: + case 241: + case 240: + case 230: + case 226: + case 227: + case 229: + case 228: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 152: + case 154: + case 148: + case 155: case 146: case 153: - case 144: - case 151: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 218) { + if (node.kind !== 223) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 142) { + if (node.kind !== 144) { return false; } var parameter = node; @@ -11373,6 +12471,7 @@ var ts; case 1: return ts.Diagnostics.Declaration_or_statement_expected; case 2: return ts.Diagnostics.case_or_default_expected; case 3: return ts.Diagnostics.Statement_expected; + case 17: case 4: return ts.Diagnostics.Property_or_signature_expected; case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6: return ts.Diagnostics.Enum_member_expected; @@ -11384,17 +12483,17 @@ var ts; case 12: return ts.Diagnostics.Property_assignment_expected; case 15: return ts.Diagnostics.Expression_or_comma_expected; case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 17: return ts.Diagnostics.Type_parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_argument_expected; - case 19: return ts.Diagnostics.Type_expected; - case 20: return ts.Diagnostics.Unexpected_token_expected; - case 21: return ts.Diagnostics.Identifier_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; - case 22: return ts.Diagnostics.Parameter_declaration_expected; - case 23: return ts.Diagnostics.Type_argument_expected; - case 25: return ts.Diagnostics.Type_expected; - case 24: return ts.Diagnostics.Property_assignment_expected; + case 23: return ts.Diagnostics.Parameter_declaration_expected; + case 24: return ts.Diagnostics.Type_argument_expected; + case 26: return ts.Diagnostics.Type_expected; + case 25: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -11407,15 +12506,15 @@ var ts; if (isListElement(kind, false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(24)) { + if (parseOptional(25)) { continue; } commaStart = -1; if (isListTerminator(kind)) { break; } - parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + parseExpected(25); + if (considerSemicolonAsDelimiter && token() === 24 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -11447,8 +12546,8 @@ var ts; } function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(21)) { - var node = createNode(139, entity.pos); + while (parseOptional(22)) { + var node = createNode(141, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -11459,33 +12558,33 @@ var ts; if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); + return createMissingNode(70, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(189); - template.head = parseTemplateLiteralFragment(); - ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); + var template = createNode(194); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 13, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 14); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(197); + var span = createNode(202); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token() === 17) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); + literal = parseExpectedToken(15, false, ts.Diagnostics._0_expected, ts.tokenToString(17)); } span.literal = literal; return finishNode(span); @@ -11493,8 +12592,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 14 || fragment.kind === 15, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -11518,35 +12624,35 @@ var ts; } function parseTypeReference() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - var node = createNode(155, typeName.pos); + var node = createNode(157, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (!scanner.hasPrecedingLineBreak() && token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(154, lhs.pos); + var node = createNode(156, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(165); + var node = createNode(167); nextToken(); return finishNode(node); } function parseTypeQuery() { - var node = createNode(158); - parseExpected(101); + var node = createNode(160); + parseExpected(102); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(141); + var node = createNode(143); node.name = parseIdentifier(); - if (parseOptional(83)) { + if (parseOptional(84)) { if (isStartOfType() || !isStartOfExpression()) { node.constraint = parseType(); } @@ -11557,34 +12663,34 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { - return parseBracketedList(17, parseTypeParameter, 25, 27); + if (token() === 26) { + return parseBracketedList(18, parseTypeParameter, 26, 28); } } function parseParameterType() { - if (parseOptional(54)) { + if (parseOptional(55)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token() === 23 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 || token() === 98; } function parseParameter() { - var node = createNode(142); - if (token() === 97) { + var node = createNode(144); + if (token() === 98) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(22); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } - node.questionToken = parseOptionalToken(53); + node.questionToken = parseOptionalToken(54); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(true); return addJSDocComment(finishNode(node)); @@ -11596,7 +12702,7 @@ var ts; return parseInitializer(true); } function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 34; + var returnTokenRequired = returnToken === 35; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { @@ -11608,7 +12714,7 @@ var ts; } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(17)) { + if (parseExpected(18)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); @@ -11616,7 +12722,7 @@ var ts; var result = parseDelimitedList(16, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(18) && requireCompleteParameterList) { + if (!parseExpected(19) && requireCompleteParameterList) { return undefined; } return result; @@ -11624,29 +12730,29 @@ var ts; return requireCompleteParameterList ? undefined : createMissingList(); } function parseTypeMemberSemicolon() { - if (parseOptional(24)) { + if (parseOptional(25)) { return; } parseSemicolon(); } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 152) { - parseExpected(92); + if (kind === 154) { + parseExpected(93); } - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token() !== 19) { + if (token() !== 20) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token() === 23 || token() === 21) { return true; } if (ts.isModifierKind(token())) { @@ -11661,43 +12767,43 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token() === 55 || token() === 25) { return true; } - if (token() !== 53) { + if (token() !== 54) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token() === 55 || token() === 25 || token() === 21; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(153, fullStart); + var node = createNode(155, fullStart); node.decorators = decorators; node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 19, 20); + node.parameters = parseBracketedList(16, parseParameter, 20, 21); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { - var method = createNode(146, fullStart); + var questionToken = parseOptionalToken(54); + if (token() === 18 || token() === 26) { + var method = createNode(148, fullStart); method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; - fillSignature(54, false, false, false, method); + fillSignature(55, false, false, false, method); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(method)); } else { - var property = createNode(144, fullStart); + var property = createNode(146, fullStart); property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token() === 57) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -11706,14 +12812,14 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token() === 18 || token() === 26) { return true; } while (ts.isModifierKind(token())) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (isLiteralPropertyName()) { @@ -11721,21 +12827,21 @@ var ts; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || + return token() === 18 || + token() === 26 || token() === 54 || - token() === 24 || + token() === 55 || + token() === 25 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { - return parseSignatureMember(151); + if (token() === 18 || token() === 26) { + return parseSignatureMember(153); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(152); + if (token() === 93 && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(154); } var fullStart = getNodePos(); var modifiers = parseModifiers(); @@ -11746,50 +12852,77 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token() === 18 || token() === 26; } function parseTypeLiteral() { - var node = createNode(159); + var node = createNode(161); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(15)) { + if (parseExpected(16)) { members = parseList(4, parseTypeMember); - parseExpected(16); + parseExpected(17); } else { members = createMissingList(); } return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === 130) { + nextToken(); + } + return token() === 20 && nextTokenIsIdentifier() && nextToken() === 91; + } + function parseMappedTypeParameter() { + var node = createNode(143); + node.name = parseIdentifier(); + parseExpected(91); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(170); + parseExpected(16); + node.readonlyToken = parseOptionalToken(130); + parseExpected(20); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(21); + node.questionToken = parseOptionalToken(54); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(17); + return finishNode(node); + } function parseTupleType() { - var node = createNode(161); - node.elementTypes = parseBracketedList(19, parseType, 19, 20); + var node = createNode(163); + node.elementTypes = parseBracketedList(20, parseType, 20, 21); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(164); - parseExpected(17); - node.type = parseType(); + var node = createNode(166); parseExpected(18); + node.type = parseType(); + parseExpected(19); return finishNode(node); } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 157) { - parseExpected(92); + if (kind === 159) { + parseExpected(93); } - fillSignature(34, false, false, false, node); + fillSignature(35, false, false, false, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; + return token() === 22 ? undefined : node; } function parseLiteralTypeNode() { - var node = createNode(166); + var node = createNode(171); node.literal = parseSimpleUnaryExpression(); finishNode(node); return node; @@ -11799,41 +12932,41 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: + case 121: case 135: - case 127: + case 137: + case 129: var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseLiteralTypeNode(); - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 103: - case 93: + case 104: + case 94: return parseTokenNode(); - case 97: { + case 98: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 101: + case 102: return parseTypeQuery(); - case 15: - return parseTypeLiteral(); - case 19: + case 16: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 20: return parseTupleType(); - case 17: + case 18: return parseParenthesizedType(); default: return parseTypeReference(); @@ -11841,29 +12974,31 @@ var ts; } function isStartOfType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: + case 104: + case 137: + case 94: + case 98: + case 102: + case 129: + case 16: + case 20: + case 26: + case 48: + case 47: case 93: - case 97: - case 101: - case 127: - case 15: - case 19: - case 25: - case 92: case 9: case 8: - case 99: - case 84: + case 100: + case 85: return true; - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral); - case 17: + case 18: return lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); @@ -11871,19 +13006,43 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token() === 19 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(19)) { - parseExpected(20); - var node = createNode(160, type.pos); - node.elementType = type; - type = finishNode(node); + while (!scanner.hasPrecedingLineBreak() && parseOptional(20)) { + if (isStartOfType()) { + var node = createNode(169, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(21); + type = finishNode(node); + } + else { + var node = createNode(162, type.pos); + node.elementType = type; + parseExpected(21); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator) { + var node = createNode(168); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 126: + return parseTypeOperator(126); + } + return parseArrayTypeOrHigher(); + } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { var types = createNodeArray([type], type.pos); @@ -11898,26 +13057,26 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(163, parseArrayTypeOrHigher, 46); + return parseUnionOrIntersectionType(165, parseTypeOperatorOrHigher, 47); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); + return parseUnionOrIntersectionType(164, parseIntersectionTypeOrHigher, 48); } function isStartOfFunctionType() { - if (token() === 25) { + if (token() === 26) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 18 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token() === 98) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token() === 20 || token() === 16) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -11926,17 +13085,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token() === 19 || token() === 23) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token() === 55 || token() === 25 || + token() === 54 || token() === 57) { return true; } - if (token() === 18) { + if (token() === 19) { nextToken(); - if (token() === 34) { + if (token() === 35) { return true; } } @@ -11947,7 +13106,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(154, typePredicateVariable.pos); + var node = createNode(156, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -11958,46 +13117,46 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(327680, parseTypeWorker); + return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(156); + return parseFunctionOrConstructorType(158); } - if (token() === 92) { - return parseFunctionOrConstructorType(157); + if (token() === 93) { + return parseFunctionOrConstructorType(159); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(54) ? parseType() : undefined; + return parseOptional(55) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { switch (token()) { - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: case 8: case 9: - case 11: case 12: - case 17: - case 19: - case 15: - case 87: - case 73: - case 92: - case 39: - case 61: - case 69: + case 13: + case 18: + case 20: + case 16: + case 88: + case 74: + case 93: + case 40: + case 62: + case 70: return true; default: return isIdentifier(); @@ -12008,18 +13167,18 @@ var ts; return true; } switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 41: + case 79: + case 102: + case 104: case 42: - case 25: - case 119: - case 114: + case 43: + case 26: + case 120: + case 115: return true; default: if (isBinaryOperator()) { @@ -12029,10 +13188,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token() !== 16 && + token() !== 88 && + token() !== 74 && + token() !== 56 && isStartOfExpression(); } function parseExpression() { @@ -12042,7 +13201,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(24))) { + while ((operatorToken = parseOptionalToken(25))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -12051,12 +13210,12 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token() !== 57) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 16) || !isStartOfExpression()) { return undefined; } } - parseExpected(56); + parseExpected(57); return parseAssignmentExpressionOrHigher(); } function parseAssignmentExpressionOrHigher() { @@ -12068,7 +13227,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 70 && token() === 35) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -12077,7 +13236,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token() === 115) { if (inYieldContext()) { return true; } @@ -12090,11 +13249,11 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(190); + var node = createNode(195); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(37); + (token() === 38 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(38); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -12103,21 +13262,21 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 35, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(180, asyncModifier.pos); + node = createNode(185, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(180, identifier.pos); + node = createNode(185, identifier.pos); } - var parameter = createNode(142, identifier.pos); + var parameter = createNode(144, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -12134,78 +13293,78 @@ var ts; } var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 34 || lastToken === 15) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 35 || lastToken === 16) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token() === 18 || token() === 26 || token() === 119) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token() === 35) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token() !== 18 && token() !== 26) { return 0; } } var first = token(); var second = nextToken(); - if (first === 17) { - if (second === 18) { + if (first === 18) { + if (second === 19) { var third = nextToken(); switch (third) { - case 34: - case 54: - case 15: + case 35: + case 55: + case 16: return 1; default: return 0; } } - if (second === 19 || second === 15) { + if (second === 20 || second === 16) { return 2; } - if (second === 22) { + if (second === 23) { return 1; } if (!isIdentifier()) { return 0; } - if (nextToken() === 54) { + if (nextToken() === 55) { return 1; } return 2; } else { - ts.Debug.assert(first === 25); + ts.Debug.assert(first === 26); if (!isIdentifier()) { return 0; } if (sourceFile.languageVariant === 1) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 83) { + if (third === 84) { var fourth = nextToken(); switch (fourth) { - case 56: - case 27: + case 57: + case 28: return false; default: return true; } } - else if (third === 24) { + else if (third === 25) { return true; } return false; @@ -12222,7 +13381,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token() === 119) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -12233,38 +13392,38 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 35) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 70 && token() === 35) { return 1; } } return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(180); + var node = createNode(185); node.modifiers = parseModifiersForArrowFunction(); var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(54, false, isAsync, !allowAmbiguity, node); + fillSignature(55, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token() !== 35 && token() !== 16) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token() === 16) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token() !== 24 && + token() !== 88 && + token() !== 74 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -12274,15 +13433,15 @@ var ts; : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); } function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(53); + var questionToken = parseOptionalToken(54); if (!questionToken) { return leftOperand; } - var node = createNode(188, leftOperand.pos); + var node = createNode(193, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(54, false, ts.Diagnostics._0_expected, ts.tokenToString(54)); + node.colonToken = parseExpectedToken(55, false, ts.Diagnostics._0_expected, ts.tokenToString(55)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -12291,22 +13450,22 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 || t === 138; + return t === 91 || t === 140; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token() === 39 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token() === 91 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token() === 117) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -12322,92 +13481,92 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token() === 91) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 52: + case 53: return 1; - case 51: + case 52: return 2; - case 47: - return 3; case 48: + return 3; + case 49: return 4; - case 46: + case 47: return 5; - case 30: case 31: case 32: case 33: + case 34: return 6; - case 25: - case 27: + case 26: case 28: case 29: + case 30: + case 92: case 91: - case 90: - case 116: + case 117: return 7; - case 43: case 44: case 45: + case 46: return 8; - case 35: case 36: - return 9; case 37: - case 39: - case 40: - return 10; + return 9; case 38: + case 40: + case 41: + return 10; + case 39: return 11; } return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(187, left.pos); + var node = createNode(192, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(195, left.pos); + var node = createNode(200, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(185); + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(181); + var node = createNode(186); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(182); + var node = createNode(187); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(183); + var node = createNode(188); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token() === 120) { if (inAwaitContext()) { return true; } @@ -12416,7 +13575,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(184); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -12424,15 +13583,15 @@ var ts; function parseUnaryExpressionOrHigher() { if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token() === 39 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token() === 39) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 177) { + if (simpleUnaryExpression.kind === 182) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -12443,20 +13602,20 @@ var ts; } function parseSimpleUnaryExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: return parsePrefixUnaryExpression(); - case 78: + case 79: return parseDeleteExpression(); - case 101: + case 102: return parseTypeOfExpression(); - case 103: + case 104: return parseVoidExpression(); - case 25: + case 26: return parseTypeAssertion(); - case 119: + case 120: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -12466,16 +13625,16 @@ var ts; } function isUpdateExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 119: + case 79: + case 102: + case 104: + case 120: return false; - case 25: + case 26: if (sourceFile.languageVariant !== 1) { return false; } @@ -12484,20 +13643,20 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { - var node = createNode(185); + if (token() === 42 || token() === 43) { + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 26 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(186, expression.pos); + if ((token() === 42 || token() === 43) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(191, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -12506,7 +13665,7 @@ var ts; return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token() === 96 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -12517,12 +13676,12 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token() === 18 || token() === 22 || token() === 20) { return expression; } - var node = createNode(172, expression.pos); + var node = createNode(177, expression.pos); node.expression = expression; - parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(22, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -12530,10 +13689,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 69) { + if (lhs.kind === 70) { return lhs.text === rhs.text; } - if (lhs.kind === 97) { + if (lhs.kind === 98) { return true; } return lhs.name.text === rhs.name.text && @@ -12542,8 +13701,8 @@ var ts; function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 243) { - var node = createNode(241, opening.pos); + if (opening.kind === 248) { + var node = createNode(246, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -12553,18 +13712,18 @@ var ts; result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 242); + ts.Debug.assert(opening.kind === 247); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token() === 26) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(187, result.pos); + var badNode = createNode(192, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(24, false, undefined); + badNode.operatorToken = createMissingNode(25, false, undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -12572,17 +13731,17 @@ var ts; return result; } function parseJsxText() { - var node = createNode(244, scanner.getStartPos()); + var node = createNode(10, scanner.getStartPos()); currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 244: + case 10: return parseJsxText(); - case 15: + case 16: return parseJsxExpression(false); - case 25: + case 26: return parseJsxElementOrSelfClosingElement(false); } ts.Debug.fail("Unknown JSX child kind " + token()); @@ -12593,7 +13752,7 @@ var ts; parsingContext |= 1 << 14; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + if (token() === 27) { break; } else if (token() === 1) { @@ -12608,24 +13767,24 @@ var ts; } function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(25); + parseExpected(26); var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { - node = createNode(243, fullStart); + if (token() === 28) { + node = createNode(248, fullStart); scanJsxText(); } else { - parseExpected(39); + parseExpected(40); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } - node = createNode(242, fullStart); + node = createNode(247, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -12633,10 +13792,10 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token() === 98 ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(21)) { - var propertyAccess = createNode(172, expression.pos); + while (parseOptional(22)) { + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -12644,28 +13803,28 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(248); - parseExpected(15); - if (token() !== 16) { + var node = createNode(252); + parseExpected(16); + if (token() !== 17) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(16); + parseExpected(17); } else { - parseExpected(16, undefined, false); + parseExpected(17, undefined, false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token() === 16) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(246); + var node = createNode(250); node.name = parseIdentifierName(); - if (token() === 56) { + if (token() === 57) { switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); @@ -12678,69 +13837,69 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(247); - parseExpected(15); - parseExpected(22); - node.expression = parseExpression(); + var node = createNode(251); parseExpected(16); + parseExpected(23); + node.expression = parseExpression(); + parseExpected(17); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(245); - parseExpected(26); + var node = createNode(249); + parseExpected(27); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(177); - parseExpected(25); + var node = createNode(182); + parseExpected(26); node.type = parseType(); - parseExpected(27); + parseExpected(28); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(21); + var dotToken = parseOptionalToken(22); if (dotToken) { - var propertyAccess = createNode(172, expression.pos); + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 50 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(196, expression.pos); + var nonNullExpression = createNode(201, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } - if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(173, expression.pos); + if (!inDecoratorContext() && parseOptional(20)) { + var indexedAccess = createNode(178, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token() !== 21) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(20); + parseExpected(21); expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { - var tagExpression = createNode(176, expression.pos); + if (token() === 12 || token() === 13) { + var tagExpression = createNode(181, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token() === 12 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -12752,20 +13911,20 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token() === 26) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - var callExpr = createNode(174, expression.pos); + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 17) { - var callExpr = createNode(174, expression.pos); + else if (token() === 18) { + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -12775,17 +13934,17 @@ var ts; } } function parseArgumentList() { - parseExpected(17); - var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(18); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(19); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(25)) { + if (!parseOptional(26)) { return undefined; } - var typeArguments = parseDelimitedList(18, parseType); - if (!parseExpected(27)) { + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(28)) { return undefined; } return typeArguments && canFollowTypeArgumentsInExpression() @@ -12794,27 +13953,27 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 17: - case 21: case 18: - case 20: + case 22: + case 19: + case 21: + case 55: + case 24: case 54: - case 23: - case 53: - case 30: - case 32: case 31: case 33: - case 51: + case 32: + case 34: case 52: - case 48: - case 46: + case 53: + case 49: case 47: - case 16: + case 48: + case 17: case 1: return true; - case 24: - case 15: + case 25: + case 16: default: return false; } @@ -12823,103 +13982,109 @@ var ts; switch (token()) { case 8: case 9: - case 11: + case 12: return parseLiteralNode(); - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: return parseTokenNode(); - case 17: + case 18: return parseParenthesizedExpression(); - case 19: + case 20: return parseArrayLiteralExpression(); - case 15: + case 16: return parseObjectLiteralExpression(); - case 118: + case 119: if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { break; } return parseFunctionExpression(); - case 73: + case 74: return parseClassExpression(); - case 87: + case 88: return parseFunctionExpression(); - case 92: + case 93: return parseNewExpression(); - case 39: - case 61: - if (reScanSlashToken() === 10) { + case 40: + case 62: + if (reScanSlashToken() === 11) { return parseLiteralNode(); } break; - case 12: + case 13: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(178); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(183); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); return finishNode(node); } function parseSpreadElement() { - var node = createNode(191); - parseExpected(22); + var node = createNode(196); + parseExpected(23); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token() === 23 ? parseSpreadElement() : + token() === 25 ? createNode(198) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(170); - parseExpected(19); + var node = createNode(175); + parseExpected(20); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(20); + parseExpected(21); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(123)) { - return parseAccessorDeclaration(149, fullStart, decorators, modifiers); + if (parseContextualModifier(124)) { + return parseAccessorDeclaration(151, fullStart, decorators, modifiers); } - else if (parseContextualModifier(131)) { - return parseAccessorDeclaration(150, fullStart, decorators, modifiers); + else if (parseContextualModifier(133)) { + return parseAccessorDeclaration(152, fullStart, decorators, modifiers); } return undefined; } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(23); + if (dotDotDotToken) { + var spreadElement = createNode(259, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } var decorators = parseDecorators(); var modifiers = parseModifiers(); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 || token() === 17 || token() === 57); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(254, fullStart); + var shorthandDeclaration = createNode(258, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(56); + var equalsToken = parseOptionalToken(57); if (equalsToken) { shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); @@ -12927,23 +14092,23 @@ var ts; return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(253, fullStart); + var propertyAssignment = createNode(257, fullStart); propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; - parseExpected(54); + parseExpected(55); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(171); - parseExpected(15); + var node = createNode(176); + parseExpected(16); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(16); + parseExpected(17); return finishNode(node); } function parseFunctionExpression() { @@ -12951,10 +14116,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(179); + var node = createNode(184); node.modifiers = parseModifiers(); - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); var isGenerator = !!node.asteriskToken; var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = @@ -12962,7 +14127,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlock(isGenerator, isAsync, false); if (saveDecoratorContext) { setDecoratorContext(true); @@ -12973,23 +14138,23 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(175); - parseExpected(92); + var node = createNode(180); + parseExpected(93); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token() === 18) { node.arguments = parseArgumentList(); } return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(199); - if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(204); + if (parseExpected(16, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -13014,47 +14179,47 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(201); - parseExpected(23); + var node = createNode(206); + parseExpected(24); return finishNode(node); } function parseIfStatement() { - var node = createNode(203); - parseExpected(88); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(208); + parseExpected(89); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(80) ? parseStatement() : undefined; + node.elseStatement = parseOptional(81) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(204); - parseExpected(79); + var node = createNode(209); + parseExpected(80); node.statement = parseStatement(); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + parseExpected(105); parseExpected(18); - parseOptional(23); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + parseOptional(24); return finishNode(node); } function parseWhileStatement() { - var node = createNode(205); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(210); + parseExpected(105); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(86); - parseExpected(17); + parseExpected(87); + parseExpected(18); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token() !== 24) { + if (token() === 103 || token() === 109 || token() === 75) { initializer = parseVariableDeclarationList(true); } else { @@ -13062,32 +14227,32 @@ var ts; } } var forOrForInOrForOfStatement; - if (parseOptional(90)) { - var forInStatement = createNode(207, pos); + if (parseOptional(91)) { + var forInStatement = createNode(212, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(138)) { - var forOfStatement = createNode(208, pos); + else if (parseOptional(140)) { + var forOfStatement = createNode(213, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(206, pos); + var forStatement = createNode(211, pos); forStatement.initializer = initializer; - parseExpected(23); - if (token() !== 23 && token() !== 18) { + parseExpected(24); + if (token() !== 24 && token() !== 19) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(23); - if (token() !== 18) { + parseExpected(24); + if (token() !== 19) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -13095,7 +14260,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 210 ? 70 : 75); + parseExpected(kind === 215 ? 71 : 76); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -13103,8 +14268,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(211); - parseExpected(94); + var node = createNode(216); + parseExpected(95); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -13112,90 +14277,90 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(212); - parseExpected(105); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(217); + parseExpected(106); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseCaseClause() { - var node = createNode(249); - parseExpected(71); + var node = createNode(253); + parseExpected(72); node.expression = allowInAnd(parseExpression); - parseExpected(54); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(250); - parseExpected(77); - parseExpected(54); + var node = createNode(254); + parseExpected(78); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 72 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(213); - parseExpected(96); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(218); + parseExpected(97); parseExpected(18); - var caseBlock = createNode(227, scanner.getStartPos()); - parseExpected(15); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + var caseBlock = createNode(232, scanner.getStartPos()); parseExpected(16); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(17); node.caseBlock = finishNode(caseBlock); return finishNode(node); } function parseThrowStatement() { - var node = createNode(215); - parseExpected(98); + var node = createNode(220); + parseExpected(99); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(216); - parseExpected(100); + var node = createNode(221); + parseExpected(101); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { - parseExpected(85); + node.catchClause = token() === 73 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 86) { + parseExpected(86); node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(252); - parseExpected(72); - if (parseExpected(17)) { + var result = createNode(256); + parseExpected(73); + if (parseExpected(18)) { result.variableDeclaration = parseVariableDeclaration(); } - parseExpected(18); + parseExpected(19); result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(217); - parseExpected(76); + var node = createNode(222); + parseExpected(77); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); - if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(214, fullStart); + if (expression.kind === 70 && parseOptional(55)) { + var labeledStatement = createNode(219, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(202, fullStart); + var expressionStatement = createNode(207, fullStart); expressionStatement.expression = expression; parseSemicolon(); return addJSDocComment(finishNode(expressionStatement)); @@ -13207,7 +14372,7 @@ var ts; } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 88 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); @@ -13216,47 +14381,47 @@ var ts; function isDeclaration() { while (true) { switch (token()) { - case 102: - case 108: + case 103: + case 109: + case 75: + case 88: case 74: - case 87: - case 73: - case 81: + case 82: return true; - case 107: - case 134: + case 108: + case 136: return nextTokenIsIdentifierOnSameLine(); - case 125: - case 126: + case 127: + case 128: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 115: - case 118: - case 122: - case 110: + case 116: + case 119: + case 123: case 111: case 112: - case 128: + case 113: + case 130: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 137: + case 139: nextToken(); - return token() === 15 || token() === 69 || token() === 82; - case 89: + return token() === 16 || token() === 70 || token() === 83; + case 90: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); - case 82: + return token() === 9 || token() === 38 || + token() === 16 || ts.tokenIsIdentifierOrKeyword(token()); + case 83: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token() === 57 || token() === 38 || + token() === 16 || token() === 78 || + token() === 117) { return true; } continue; - case 113: + case 114: nextToken(); continue; default: @@ -13269,46 +14434,46 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 55: - case 23: - case 15: - case 102: - case 108: - case 87: - case 73: - case 81: + case 56: + case 24: + case 16: + case 103: + case 109: case 88: - case 79: - case 104: - case 86: - case 75: - case 70: - case 94: - case 105: - case 96: - case 98: - case 100: - case 76: - case 72: - case 85: - return true; case 74: case 82: case 89: - return isStartOfDeclaration(); - case 118: - case 122: - case 107: - case 125: - case 126: - case 134: - case 137: + case 80: + case 105: + case 87: + case 76: + case 71: + case 95: + case 106: + case 97: + case 99: + case 101: + case 77: + case 73: + case 86: return true; - case 112: - case 110: - case 111: - case 113: + case 75: + case 83: + case 90: + return isStartOfDeclaration(); + case 119: + case 123: + case 108: + case 127: case 128: + case 136: + case 139: + return true; + case 113: + case 111: + case 112: + case 114: + case 130: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -13316,73 +14481,73 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token() === 16 || token() === 20; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token()) { - case 23: + case 24: return parseEmptyStatement(); - case 15: + case 16: return parseBlock(false); - case 102: + case 103: return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 108: + case 109: if (isLetDeclaration()) { return parseVariableStatement(scanner.getStartPos(), undefined, undefined); } break; - case 87: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 73: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 88: - return parseIfStatement(); - case 79: - return parseDoStatement(); - case 104: - return parseWhileStatement(); - case 86: - return parseForOrForInOrForOfStatement(); - case 75: - return parseBreakOrContinueStatement(209); - case 70: - return parseBreakOrContinueStatement(210); - case 94: - return parseReturnStatement(); - case 105: - return parseWithStatement(); - case 96: - return parseSwitchStatement(); - case 98: - return parseThrowStatement(); - case 100: - case 72: - case 85: - return parseTryStatement(); - case 76: - return parseDebuggerStatement(); - case 55: - return parseDeclaration(); - case 118: - case 107: - case 134: - case 125: - case 126: - case 122: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 74: - case 81: - case 82: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 89: - case 110: + return parseIfStatement(); + case 80: + return parseDoStatement(); + case 105: + return parseWhileStatement(); + case 87: + return parseForOrForInOrForOfStatement(); + case 76: + return parseBreakOrContinueStatement(214); + case 71: + return parseBreakOrContinueStatement(215); + case 95: + return parseReturnStatement(); + case 106: + return parseWithStatement(); + case 97: + return parseSwitchStatement(); + case 99: + return parseThrowStatement(); + case 101: + case 73: + case 86: + return parseTryStatement(); + case 77: + return parseDebuggerStatement(); + case 56: + return parseDeclaration(); + case 119: + case 108: + case 136: + case 127: + case 128: + case 123: + case 75: + case 82: + case 83: + case 90: case 111: case 112: - case 115: case 113: - case 128: - case 137: + case 116: + case 114: + case 130: + case 139: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -13395,40 +14560,40 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token()) { - case 102: - case 108: - case 74: + case 103: + case 109: + case 75: return parseVariableStatement(fullStart, decorators, modifiers); - case 87: + case 88: return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 73: + case 74: return parseClassDeclaration(fullStart, decorators, modifiers); - case 107: + case 108: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 134: + case 136: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 81: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 137: - case 125: - case 126: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 89: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 139: + case 127: + case 128: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 90: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 83: nextToken(); switch (token()) { - case 77: - case 56: + case 78: + case 57: return parseExportAssignment(fullStart, decorators, modifiers); - case 116: + case 117: return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); } default: if (decorators || modifiers) { - var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(244, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; node.modifiers = modifiers; @@ -13441,31 +14606,32 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token() !== 16 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { - return createNode(193); + if (token() === 25) { + return createNode(198); } - var node = createNode(169); - node.dotDotDotToken = parseOptionalToken(22); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(169); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token() !== 55) { node.name = propertyName; } else { - parseExpected(54); + parseExpected(55); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -13473,33 +14639,33 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(167); - parseExpected(15); - node.elements = parseDelimitedList(9, parseObjectBindingElement); + var node = createNode(172); parseExpected(16); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(17); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(168); - parseExpected(19); - node.elements = parseDelimitedList(10, parseArrayBindingElement); + var node = createNode(173); parseExpected(20); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(21); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token() === 16 || token() === 20 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token() === 20) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token() === 16) { return parseObjectBindingPattern(); } return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(218); + var node = createNode(223); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { @@ -13508,21 +14674,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(219); + var node = createNode(224); switch (token()) { - case 102: + case 103: break; - case 108: + case 109: node.flags |= 1; break; - case 74: + case 75: node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 140 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -13534,10 +14700,10 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 18; + return nextTokenIsIdentifier() && nextToken() === 19; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(200, fullStart); + var node = createNode(205, fullStart); node.decorators = decorators; node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); @@ -13545,29 +14711,29 @@ var ts; return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(220, fullStart); + var node = createNode(225, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; var isAsync = ts.hasModifier(node, 256); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(148, pos); + var node = createNode(150, pos); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(121); - fillSignature(54, false, false, false, node); + parseExpected(122); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(147, fullStart); + var method = createNode(149, fullStart); method.decorators = decorators; method.modifiers = modifiers; method.asteriskToken = asteriskToken; @@ -13575,12 +14741,12 @@ var ts; method.questionToken = questionToken; var isGenerator = !!asteriskToken; var isAsync = ts.hasModifier(method, 256); - fillSignature(54, isGenerator, isAsync, false, method); + fillSignature(55, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(145, fullStart); + var property = createNode(147, fullStart); property.decorators = decorators; property.modifiers = modifiers; property.name = name; @@ -13588,15 +14754,15 @@ var ts; property.type = parseTypeAnnotation(); property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); parseSemicolon(); return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -13611,17 +14777,17 @@ var ts; node.decorators = decorators; node.modifiers = modifiers; node.name = parsePropertyName(); - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { - case 112: - case 110: - case 111: case 113: - case 128: + case 111: + case 112: + case 114: + case 130: return true; default: return false; @@ -13629,7 +14795,7 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token() === 56) { return true; } while (ts.isModifierKind(token())) { @@ -13639,26 +14805,26 @@ var ts; } nextToken(); } - if (token() === 37) { + if (token() === 38) { return true; } if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { + if (!ts.isKeyword(idToken) || idToken === 133 || idToken === 124) { return true; } switch (token()) { - case 17: - case 25: + case 18: + case 26: + case 55: + case 57: case 54: - case 56: - case 53: return true; default: return canParseSemicolon(); @@ -13670,10 +14836,10 @@ var ts; var decorators; while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(55)) { + if (!parseOptional(56)) { break; } - var decorator = createNode(143, decoratorStart); + var decorator = createNode(145, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); if (!decorators) { @@ -13693,7 +14859,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + if (token() === 75 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -13718,7 +14884,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 118) { + if (token() === 119) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -13729,8 +14895,8 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { - var result = createNode(198); + if (token() === 24) { + var result = createNode(203); nextToken(); return finishNode(result); } @@ -13741,7 +14907,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token() === 122) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -13750,33 +14916,33 @@ var ts; if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || - token() === 37 || - token() === 19) { + token() === 38 || + token() === 20) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_10 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, undefined); + var name_13 = createMissingNode(70, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 192); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 197); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 221); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(73); + parseExpected(74); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(true); - if (parseExpected(15)) { + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(16)) { node.members = parseClassMembers(); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -13789,17 +14955,17 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 107 && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause) { + function parseHeritageClauses() { if (isHeritageClause()) { - return parseList(20, parseHeritageClause); + return parseList(21, parseHeritageClause); } return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { - var node = createNode(251); + if (token() === 84 || token() === 107) { + var node = createNode(255); node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -13808,57 +14974,57 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(194); + var node = createNode(199); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token() === 84 || token() === 107; } function parseClassMembers() { return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(222, fullStart); + var node = createNode(227, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(107); + parseExpected(108); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(223, fullStart); + var node = createNode(228, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(134); + parseExpected(136); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(56); + parseExpected(57); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { - var node = createNode(255, scanner.getStartPos()); + var node = createNode(260, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(224, fullStart); + var node = createNode(229, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(81); + parseExpected(82); node.name = parseIdentifier(); - if (parseExpected(15)) { + if (parseExpected(16)) { node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -13866,10 +15032,10 @@ var ts; return addJSDocComment(finishNode(node)); } function parseModuleBlock() { - var node = createNode(226, scanner.getStartPos()); - if (parseExpected(15)) { + var node = createNode(231, scanner.getStartPos()); + if (parseExpected(16)) { node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -13877,29 +15043,29 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); var namespaceFlag = flags & 16; node.decorators = decorators; node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(21) + node.body = parseOptional(22) ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (token() === 137) { + if (token() === 139) { node.name = parseIdentifier(); node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token() === 16) { node.body = parseModuleBlock(); } else { @@ -13909,14 +15075,14 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = 0; - if (token() === 137) { + if (token() === 139) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } - else if (parseOptional(126)) { + else if (parseOptional(128)) { flags |= 16; } else { - parseExpected(125); + parseExpected(127); if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -13924,63 +15090,63 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token() === 131 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 17; + return nextToken() === 18; } function nextTokenIsSlash() { - return nextToken() === 39; + return nextToken() === 40; } function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228, fullStart); + var exportDeclaration = createNode(233, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; - parseExpected(116); - parseExpected(126); + parseExpected(117); + parseExpected(128); exportDeclaration.name = parseIdentifier(); - parseExpected(23); + parseSemicolon(); return finishNode(exportDeclaration); } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(89); + parseExpected(90); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { - var importEqualsDeclaration = createNode(229, fullStart); + if (token() !== 25 && token() !== 138) { + var importEqualsDeclaration = createNode(234, fullStart); importEqualsDeclaration.decorators = decorators; importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; - parseExpected(56); + parseExpected(57); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); return addJSDocComment(finishNode(importEqualsDeclaration)); } } - var importDeclaration = createNode(230, fullStart); + var importDeclaration = createNode(235, fullStart); importDeclaration.decorators = decorators; importDeclaration.modifiers = modifiers; if (identifier || - token() === 37 || - token() === 15) { + token() === 38 || + token() === 16) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(136); + parseExpected(138); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(231, fullStart); + var importClause = createNode(236, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || - parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + parseOptional(25)) { + importClause.namedBindings = token() === 38 ? parseNamespaceImport() : parseNamedImportsOrExports(238); } return finishNode(importClause); } @@ -13990,11 +15156,11 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(240); - parseExpected(129); - parseExpected(17); - node.expression = parseModuleSpecifier(); + var node = createNode(245); + parseExpected(131); parseExpected(18); + node.expression = parseModuleSpecifier(); + parseExpected(19); return finishNode(node); } function parseModuleSpecifier() { @@ -14008,22 +15174,22 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(232); - parseExpected(37); - parseExpected(116); + var namespaceImport = createNode(237); + parseExpected(38); + parseExpected(117); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 233 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(22, kind === 238 ? parseImportSpecifier : parseExportSpecifier, 16, 17); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(238); + return parseImportOrExportSpecifier(243); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(234); + return parseImportOrExportSpecifier(239); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -14031,9 +15197,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token() === 117) { node.propertyName = identifierName; - parseExpected(116); + parseExpected(117); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -14042,23 +15208,23 @@ var ts; else { node.name = identifierName; } - if (kind === 234 && checkIdentifierIsKeyword) { + if (kind === 239 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(236, fullStart); + var node = createNode(241, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(37)) { - parseExpected(136); + if (parseOptional(38)) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(136); + node.exportClause = parseNamedImportsOrExports(242); + if (token() === 138 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -14066,14 +15232,14 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(235, fullStart); + var node = createNode(240, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(56)) { + if (parseOptional(57)) { node.isExportEquals = true; } else { - parseExpected(77); + parseExpected(78); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -14145,10 +15311,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 229 && node.moduleReference.kind === 240 - || node.kind === 230 + || node.kind === 234 && node.moduleReference.kind === 245 || node.kind === 235 - || node.kind === 236 + || node.kind === 240 + || node.kind === 241 ? node : undefined; }); @@ -14157,24 +15323,24 @@ var ts; (function (JSDocParser) { function isJSDocType() { switch (token()) { - case 37: - case 53: - case 17: - case 19: - case 49: - case 15: - case 87: - case 22: - case 92: - case 97: + case 38: + case 54: + case 18: + case 20: + case 50: + case 16: + case 88: + case 23: + case 93: + case 98: return true; } return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); - sourceFile = createSourceFile("file.js", 2, 1); + initializeState(content, 5, undefined, 1); + sourceFile = createSourceFile("file.js", 5, 1); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -14184,23 +15350,23 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression() { - var result = createNode(257, scanner.getTokenPos()); - parseExpected(15); - result.type = parseJSDocTopLevelType(); + var result = createNode(262, scanner.getTokenPos()); parseExpected(16); + result.type = parseJSDocTopLevelType(); + parseExpected(17); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { - var unionType = createNode(261, type.pos); + if (token() === 48) { + var unionType = createNode(266, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { - var optionalType = createNode(268, type.pos); + if (token() === 57) { + var optionalType = createNode(273, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -14210,21 +15376,21 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { - var arrayType = createNode(260, type.pos); + if (token() === 20) { + var arrayType = createNode(265, type.pos); arrayType.elementType = type; nextToken(); - parseExpected(20); + parseExpected(21); type = finishNode(arrayType); } - else if (token() === 53) { - var nullableType = createNode(263, type.pos); + else if (token() === 54) { + var nullableType = createNode(268, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { - var nonNullableType = createNode(264, type.pos); + else if (token() === 50) { + var nonNullableType = createNode(269, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -14237,94 +15403,94 @@ var ts; } function parseBasicTypeExpression() { switch (token()) { - case 37: + case 38: return parseJSDocAllType(); - case 53: + case 54: return parseJSDocUnknownOrNullableType(); - case 17: + case 18: return parseJSDocUnionType(); - case 19: + case 20: return parseJSDocTupleType(); - case 49: + case 50: return parseJSDocNonNullableType(); - case 15: + case 16: return parseJSDocRecordType(); - case 87: + case 88: return parseJSDocFunctionType(); - case 22: + case 23: return parseJSDocVariadicType(); - case 92: - return parseJSDocConstructorType(); - case 97: - return parseJSDocThisType(); - case 117: - case 132: - case 130: - case 120: - case 133: - case 103: case 93: + return parseJSDocConstructorType(); + case 98: + return parseJSDocThisType(); + case 118: + case 134: + case 132: + case 121: case 135: - case 127: + case 104: + case 94: + case 137: + case 129: return parseTokenNode(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(272); + var result = createNode(277); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(271); + var result = createNode(276); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(270); + var result = createNode(275); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(269); + var result = createNode(274); nextToken(); - parseExpected(17); - result.parameters = parseDelimitedList(22, parseJSDocParameter); - checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + result.parameters = parseDelimitedList(23, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(19); + if (token() === 55) { nextToken(); result.type = parseJSDocType(); } return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(142); + var parameter = createNode(144); parameter.type = parseJSDocType(); - if (parseOptional(56)) { - parameter.questionToken = createNode(56); + if (parseOptional(57)) { + parameter.questionToken = createNode(57); } return finishNode(parameter); } function parseJSDocTypeReference() { - var result = createNode(267); + var result = createNode(272); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); } else { - while (parseOptional(21)) { - if (token() === 25) { + while (parseOptional(22)) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); break; } @@ -14337,10 +15503,10 @@ var ts; } function parseTypeArguments() { nextToken(); - var typeArguments = parseDelimitedList(23, parseJSDocType); + var typeArguments = parseDelimitedList(24, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); - parseExpected(27); + parseExpected(28); return typeArguments; } function checkForEmptyTypeArgumentList(typeArguments) { @@ -14351,28 +15517,28 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(139, left.pos); + var result = createNode(141, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(265); + var result = createNode(270); result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(264); + var result = createNode(269); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(262); + var result = createNode(267); nextToken(); - result.types = parseDelimitedList(25, parseJSDocType); + result.types = parseDelimitedList(26, parseJSDocType); checkForTrailingComma(result.types); - parseExpected(20); + parseExpected(21); return finishNode(result); } function checkForTrailingComma(list) { @@ -14382,51 +15548,51 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(261); + var result = createNode(266); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18); + parseExpected(19); return finishNode(result); } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(47)) { + while (parseOptional(48)) { types.push(parseJSDocType()); } types.end = scanner.getStartPos(); return types; } function parseJSDocAllType() { - var result = createNode(258); + var result = createNode(263); nextToken(); return finishNode(result); } function parseJSDocLiteralType() { - var result = createNode(282); + var result = createNode(288); result.literal = parseLiteralTypeNode(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { - var result = createNode(259, pos); + if (token() === 25 || + token() === 17 || + token() === 19 || + token() === 28 || + token() === 57 || + token() === 48) { + var result = createNode(264, pos); return finishNode(result); } else { - var result = createNode(263, pos); + var result = createNode(268, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); + initializeState(content, 5, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -14480,11 +15646,12 @@ var ts; } if (token() === 4) { state = 0; + indent = 0; nextJSDocToken(); } while (token() !== 1) { switch (token()) { - case 55: + case 56: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); @@ -14502,9 +15669,9 @@ var ts; state = 0; indent = 0; break; - case 37: + case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -14513,13 +15680,16 @@ var ts; indent += asterisk.length; } break; - case 69: + case 70: pushComment(scanner.getTokenText()); state = 2; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -14527,6 +15697,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -14559,7 +15730,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(273, start); + var result = createNode(278, start); result.tags = tags; result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -14570,8 +15741,8 @@ var ts; } } function parseTag(indent) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getTokenPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -14582,6 +15753,9 @@ var ts; var tag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -14622,7 +15796,7 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 55 && token() !== 1) { + while (token() !== 56 && token() !== 1) { switch (token()) { case 4: if (state >= 1) { @@ -14631,7 +15805,7 @@ var ts; } indent = 0; break; - case 55: + case 56: break; case 5: if (state === 2) { @@ -14645,7 +15819,7 @@ var ts; indent += whitespace.length; } break; - case 37: + case 38: if (state === 0) { state = 1; indent += scanner.getTokenText().length; @@ -14656,7 +15830,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 55) { + if (token() === 56) { break; } nextJSDocToken(); @@ -14666,7 +15840,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(274, atToken.pos); + var result = createNode(279, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -14684,7 +15858,7 @@ var ts; function tryParseTypeExpression() { return tryParse(function () { skipWhitespace(); - if (token() !== 15) { + if (token() !== 16) { return undefined; } return parseJSDocTypeExpression(); @@ -14695,14 +15869,14 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (parseOptionalToken(19)) { + if (parseOptionalToken(20)) { name = parseJSDocIdentifierName(); skipWhitespace(); isBracketed = true; - if (parseOptionalToken(56)) { + if (parseOptionalToken(57)) { parseExpression(); } - parseExpected(20); + parseExpected(21); } else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); @@ -14721,7 +15895,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(275, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -14732,20 +15906,20 @@ var ts; return finishNode(result); } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 276; })) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(276, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 277; })) { + if (ts.forEach(tags, function (t) { return t.kind === 283; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(277, atToken.pos); + var result = createNode(283, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -14760,28 +15934,43 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(280, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.name = name; result.typeExpression = typeExpression; return finishNode(result); } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(279, atToken.pos); + var typedefTag = createNode(285, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (rightNode.kind !== 70) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); if (typeExpression) { - if (typeExpression.type.kind === 267) { + if (typeExpression.type.kind === 272) { var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 69) { - var name_11 = jsDocTypeReference.name; - if (name_11.text === "Object") { + if (jsDocTypeReference.name.kind === 70) { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -14795,7 +15984,7 @@ var ts; } return finishNode(typedefTag); function scanChildTags() { - var jsDocTypeLiteral = createNode(281, scanner.getStartPos()); + var jsDocTypeLiteral = createNode(287, scanner.getStartPos()); var resumePos = scanner.getStartPos(); var canParseTag = true; var seenAsterisk = false; @@ -14803,7 +15992,7 @@ var ts; while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); switch (token()) { - case 55: + case 56: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); if (!parentTagTerminated) { @@ -14817,13 +16006,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 37: + case 38: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 69: + case 70: canParseTag = false; case 1: break; @@ -14832,10 +16021,25 @@ var ts; scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(22)) { + var jsDocNamespaceNode = createNode(230, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return jsDocNamespaceNode; + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getStartPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -14852,32 +16056,35 @@ var ts; return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } var propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = []; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + return false; } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 278; })) { + if (ts.forEach(tags, function (t) { return t.kind === 284; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = createNodeArray(); while (true) { - var name_12 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_12) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_12.pos); - typeParameter.name = name_12; + var typeParameter = createNode(143, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token() === 25) { nextJSDocToken(); skipWhitespace(); } @@ -14885,7 +16092,7 @@ var ts; break; } } - var result = createNode(278, atToken.pos); + var result = createNode(284, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -14906,7 +16113,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(69, pos); + var result = createNode(70, pos); result.text = content.substring(pos, end); finishNode(result, end); nextJSDocToken(); @@ -14965,8 +16172,8 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); } @@ -14977,8 +16184,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += 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); } } @@ -14987,7 +16194,7 @@ var ts; switch (node.kind) { case 9: case 8: - case 69: + case 70: return true; } return false; @@ -15050,8 +16257,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -15204,16 +16411,16 @@ var ts; var ts; (function (ts) { function getModuleInstanceState(node) { - if (node.kind === 222 || node.kind === 223) { + if (node.kind === 227 || node.kind === 228) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { + else if ((node.kind === 235 || node.kind === 234) && !(ts.hasModifier(node, 1))) { return 0; } - else if (node.kind === 226) { + else if (node.kind === 231) { var state_1 = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -15229,10 +16436,13 @@ var ts; }); return state_1; } - else if (node.kind === 225) { + else if (node.kind === 230) { var body = node.body; return body ? getModuleInstanceState(body) : 1; } + else if (node.kind === 70 && node.isInJSDocNamespace) { + return 0; + } else { return 1; } @@ -15277,7 +16487,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -15307,6 +16517,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -15327,7 +16545,7 @@ var ts; if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 225)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230)) { symbol.valueDeclaration = node; } } @@ -15337,9 +16555,9 @@ var ts; if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 140) { + if (node.name.kind === 142) { var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -15348,21 +16566,21 @@ var ts; return node.name.text; } switch (node.kind) { - case 148: + case 150: return "__constructor"; - case 156: - case 151: - return "__call"; - case 157: - case 152: - return "__new"; + case 158: case 153: + return "__call"; + case 159: + case 154: + return "__new"; + case 155: return "__index"; - case 236: + case 241: return "__export"; - case 235: + case 240: return node.isExportEquals ? "export=" : "default"; - case 187: + case 192: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2: return "export="; @@ -15374,23 +16592,23 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 220: - case 221: + case 225: + case 226: return ts.hasModifier(node, 512) ? "default" : undefined; - case 269: + case 274: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 142: - ts.Debug.assert(node.parent.kind === 269); + case 144: + ts.Debug.assert(node.parent.kind === 274); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 279: + case 285: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 200) { + if (parentNode && parentNode.kind === 205) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { + if (nameIdentifier.kind === 70) { nameFromParentNode = nameIdentifier.text; } } @@ -15425,11 +16643,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 240 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -15445,7 +16669,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { - if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { + if (node.kind === 243 || (node.kind === 234 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -15453,7 +16677,11 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { + var isJSDocTypedefInJSDocNamespace = node.kind === 285 && + node.name && + node.name.kind === 70 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793064 ? 2097152 : 0) | (symbolFlags & 1920 ? 4194304 : 0); @@ -15488,13 +16716,13 @@ var ts; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !!ts.getImmediatelyInvokedFunctionExpression(node); + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -15504,13 +16732,13 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~32128; + node.flags &= ~1408; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { node.flags |= 128; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 256) { + if (node.kind === 261) { node.flags |= emitFlags; } if (isIIFE) { @@ -15545,6 +16773,7 @@ var ts; skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -15553,101 +16782,124 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - ts.forEach(node.jsDocComments, bind); + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + ts.forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - ts.forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { - case 205: + case 210: bindWhileStatement(node); break; - case 204: + case 209: bindDoStatement(node); break; - case 206: + case 211: bindForStatement(node); break; - case 207: - case 208: + case 212: + case 213: bindForInOrForOfStatement(node); break; - case 203: + case 208: bindIfStatement(node); break; - case 211: - case 215: + case 216: + case 220: bindReturnOrThrow(node); break; - case 210: - case 209: + case 215: + case 214: bindBreakOrContinueStatement(node); break; - case 216: + case 221: bindTryStatement(node); break; - case 213: + case 218: bindSwitchStatement(node); break; - case 227: + case 232: bindCaseBlock(node); break; - case 249: + case 253: bindCaseClause(node); break; - case 214: + case 219: bindLabeledStatement(node); break; - case 185: + case 190: bindPrefixUnaryExpressionFlow(node); break; - case 186: + case 191: bindPostfixUnaryExpressionFlow(node); break; - case 187: + case 192: bindBinaryExpressionFlow(node); break; - case 181: + case 186: bindDeleteExpressionFlow(node); break; - case 188: + case 193: bindConditionalExpressionFlow(node); break; - case 218: + case 223: bindVariableDeclarationFlow(node); break; - case 174: + case 179: bindCallExpressionFlow(node); break; default: - ts.forEachChild(node, bind); + bindEachChild(node); break; } } function isNarrowingExpression(expr) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return isNarrowableReference(expr); - case 174: + case 179: return hasNarrowableArgument(expr); - case 178: + case 183: return isNarrowingExpression(expr.expression); - case 187: + case 192: return isNarrowingBinaryExpression(expr); - case 185: - return expr.operator === 49 && isNarrowingExpression(expr.operand); + case 190: + return expr.operator === 50 && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); + return expr.kind === 70 || + expr.kind === 98 || + expr.kind === 177 && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -15658,41 +16910,41 @@ var ts; } } } - if (expr.expression.kind === 172 && + if (expr.expression.kind === 177 && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 187 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableReference(expr.left); - case 30: case 31: case 32: case 33: + case 34: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 91: + case 92: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 178: + case 183: return isNarrowableOperand(expr.expression); - case 187: + case 192: switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowableOperand(expr.right); } } @@ -15711,7 +16963,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 256 ? 512 : 256; + flow.flags |= flow.flags & 512 ? 1024 : 512; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -15726,8 +16978,8 @@ var ts; if (!expression) { return flags & 32 ? antecedent : unreachableFlow; } - if (expression.kind === 99 && flags & 64 || - expression.kind === 84 && flags & 32) { + if (expression.kind === 100 && flags & 64 || + expression.kind === 85 && flags & 32) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -15761,6 +17013,14 @@ var ts; node: node }; } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } function finishFlowLabel(flow) { var antecedents = flow.antecedents; if (!antecedents) { @@ -15774,34 +17034,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 203: - case 205: - case 204: + case 208: + case 210: + case 209: return parent.expression === node; - case 206: - case 188: + case 211: + case 193: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 178) { + if (node.kind === 183) { node = node.expression; } - else if (node.kind === 185 && node.operator === 49) { + else if (node.kind === 190 && node.operator === 50) { node = node.operand; } else { - return node.kind === 187 && (node.operatorToken.kind === 51 || - node.operatorToken.kind === 52); + return node.kind === 192 && (node.operatorToken.kind === 52 || + node.operatorToken.kind === 53); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 178 || - node.parent.kind === 185 && - node.parent.operator === 49) { + while (node.parent.kind === 183 || + node.parent.kind === 190 && + node.parent.operator === 50) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -15842,8 +17102,11 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var preConditionLabel = createBranchLabel(); - var postDoLabel = createBranchLabel(); + var enclosingLabeledStatement = node.parent.kind === 219 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -15874,7 +17137,7 @@ var ts; bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 219) { + if (node.initializer.kind !== 224) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -15896,7 +17159,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 211) { + if (node.kind === 216) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -15915,8 +17178,8 @@ var ts; } return undefined; } - function bindbreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 210 ? breakTarget : continueTarget; + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 215 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -15928,28 +17191,41 @@ var ts; var activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node) { - var postFinallyLabel = createBranchLabel(); + var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); } - currentFlow = finishFlowLabel(postFinallyLabel); } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -15960,7 +17236,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -15970,6 +17246,8 @@ var ts; currentFlow = finishFlowLabel(postSwitchLabel); } function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; var clauses = node.clauses; var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { @@ -15989,13 +17267,15 @@ var ts; errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { var saveCurrentFlow = currentFlow; currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - ts.forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name, breakTarget, continueTarget) { var activeLabel = { @@ -16021,11 +17301,13 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== 209) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node) { - if (node.kind === 187 && node.operatorToken.kind === 56) { + if (node.kind === 192 && node.operatorToken.kind === 57) { bindAssignmentTargetFlow(node.left); } else { @@ -16036,10 +17318,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 170) { + else if (node.kind === 175) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 191) { + if (e.kind === 196) { bindAssignmentTargetFlow(e.expression); } else { @@ -16047,21 +17329,24 @@ var ts; } } } - else if (node.kind === 171) { + else if (node.kind === 176) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 253) { + if (p.kind === 257) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 254) { + else if (p.kind === 258) { bindAssignmentTargetFlow(p.name); } + else if (p.kind === 259) { + bindAssignmentTargetFlow(p.expression); + } } } } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -16072,30 +17357,30 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 49) { + if (node.operator === 50) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - ts.forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.operator === 41 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 51 || operator === 52) { + if (operator === 52 || operator === 53) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -16106,15 +17391,21 @@ var ts; } } else { - ts.forEachChild(node, bind); - if (operator === 56 && !ts.isAssignmentTarget(node)) { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === 57 && node.left.kind === 178) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.expression.kind === 172) { + bindEachChild(node); + if (node.expression.kind === 177) { bindAssignmentTargetFlow(node.expression); } } @@ -16124,9 +17415,11 @@ var ts; var postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -16144,69 +17437,79 @@ var ts; } } function bindVariableDeclarationFlow(node) { - ts.forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === 207 || node.parent.parent.kind === 208) { + bindEachChild(node); + if (node.initializer || node.parent.parent.kind === 212 || node.parent.parent.kind === 213) { bindInitializedVariableFlow(node); } } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 178) { + while (expr.kind === 183) { expr = expr.expression; } - if (expr.kind === 179 || expr.kind === 180) { - ts.forEach(node.typeArguments, bind); - ts.forEach(node.arguments, bind); + if (expr.kind === 184 || expr.kind === 185) { + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - ts.forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === 177) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } function getContainerFlags(node) { switch (node.kind) { - case 192: - case 221: - case 224: - case 171: - case 159: - case 281: - case 265: + case 197: + case 226: + case 229: + case 176: + case 161: + case 287: + case 270: return 1; - case 222: + case 227: return 1 | 64; - case 269: - case 225: - case 223: + case 274: + case 230: + case 228: + case 170: return 1 | 32; - case 256: + case 261: return 1 | 4 | 32; - case 148: - case 220: - case 147: - case 146: case 149: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 150: + case 225: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return 1 | 4 | 32 | 8; - case 179: - case 180: + case 184: + case 185: return 1 | 4 | 32 | 8 | 16; - case 226: + case 231: return 4; - case 145: + case 147: return node.initializer ? 4 : 0; - case 252: - case 206: - case 207: - case 208: - case 227: + case 256: + case 211: + case 212: + case 213: + case 232: return 2; - case 199: + case 204: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -16222,36 +17525,37 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 225: + case 230: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 256: + case 261: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 192: - case 221: + case 197: + case 226: return declareClassMember(node, symbolFlags, symbolExcludes); - case 224: + case 229: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 159: - case 171: - case 222: - case 265: - case 281: + case 161: + case 176: + case 227: + case 270: + case 287: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 156: - case 157: + case 158: + case 159: + case 153: + case 154: + case 155: + case 149: + case 148: + case 150: case 151: case 152: - case 153: - case 147: - case 146: - case 148: - case 149: - case 150: - case 220: - case 179: - case 180: - case 269: - case 223: + case 225: + case 184: + case 185: + case 274: + case 228: + case 170: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -16266,11 +17570,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 256 ? node : node.body; - if (body && (body.kind === 256 || body.kind === 226)) { + var body = node.kind === 261 ? node : node.body; + if (body && (body.kind === 261 || body.kind === 231)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 236 || stat.kind === 235) { + if (stat.kind === 241 || stat.kind === 240) { return true; } } @@ -16346,11 +17650,11 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.name.kind !== 69) { + if (prop.kind === 259 || prop.name.kind !== 70) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 253 || prop.kind === 254 || prop.kind === 147 + var currentKind = prop.kind === 257 || prop.kind === 258 || prop.kind === 149 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -16372,10 +17676,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 225: + case 230: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 256: + case 261: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -16393,8 +17697,8 @@ var ts; } function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 106 && - node.originalKeywordKind <= 114 && + node.originalKeywordKind >= 107 && + node.originalKeywordKind <= 115 && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { if (!file.parseDiagnostics.length) { @@ -16422,17 +17726,17 @@ var ts; } } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 69) { + if (inStrictMode && node.expression.kind === 70) { var span_2 = ts.getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && + return node.kind === 70 && (node.text === "eval" || node.text === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69) { + if (name && name.kind === 70) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span_3 = ts.getErrorSpanForNode(file, name); @@ -16465,8 +17769,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 256 && - blockScopeContainer.kind !== 225 && + if (blockScopeContainer.kind !== 261 && + blockScopeContainer.kind !== 230 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -16485,7 +17789,7 @@ var ts; } function checkStrictModePrefixUnaryExpression(node) { if (inStrictMode) { - if (node.operator === 41 || node.operator === 42) { + if (node.operator === 42 || node.operator === 43) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -16509,7 +17813,7 @@ var ts; node.parent = parent; var saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 138) { + if (node.kind > 140) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -16528,8 +17832,8 @@ var ts; } function updateStrictModeStatementList(statements) { if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -16546,18 +17850,26 @@ var ts; } function bindWorker(node) { switch (node.kind) { - case 69: - case 97: - if (currentFlow && (ts.isExpression(node) || parent.kind === 254)) { + case 70: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 285) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 98: + if (currentFlow && (ts.isExpression(node) || parent.kind === 258)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 172: + case 177: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } break; - case 187: + case 192: if (ts.isInJavaScriptFile(node)) { var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { @@ -16580,120 +17892,137 @@ var ts; } } return checkStrictModeBinaryExpression(node); - case 252: + case 256: return checkStrictModeCatchClause(node); - case 181: + case 186: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 186: + case 191: return checkStrictModePostfixUnaryExpression(node); - case 185: + case 190: return checkStrictModePrefixUnaryExpression(node); - case 212: + case 217: return checkStrictModeWithStatement(node); - case 165: + case 167: seenThisKeyword = true; return; - case 154: + case 156: return checkTypePredicate(node); - case 141: + case 143: return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 142: - return bindParameter(node); - case 218: - case 169: - return bindVariableDeclarationOrBindingElement(node); - case 145: case 144: - case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); - case 280: - return bindJSDocProperty(node); - case 253: - case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 247: - emitFlags |= 16384; - return; - case 151: - case 152: - case 153: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); + return bindParameter(node); + case 223: + case 174: + return bindVariableDeclarationOrBindingElement(node); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 220: - return bindFunctionDeclaration(node); - case 148: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 271: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + case 286: + return bindJSDocProperty(node); + case 257: + case 258: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 260: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 259: + case 251: + var root = container; + var hasRest = false; + while (root.parent) { + if (root.kind === 176 && + root.parent.kind === 192 && + root.parent.operatorToken.kind === 57 && + root.parent.left === root) { + hasRest = true; + break; + } + root = root.parent; + } + return; + case 153: + case 154: + case 155: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 149: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 148: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 225: + return bindFunctionDeclaration(node); case 150: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 151: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 152: return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 156: - case 157: - case 269: - return bindFunctionOrConstructorType(node); + case 158: case 159: - case 281: - case 265: + case 274: + return bindFunctionOrConstructorType(node); + case 161: + case 170: + case 287: + case 270: return bindAnonymousDeclaration(node, 2048, "__type"); - case 171: + case 176: return bindObjectLiteralExpression(node); - case 179: - case 180: + case 184: + case 185: return bindFunctionExpression(node); - case 174: + case 179: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 192: - case 221: + case 197: + case 226: inStrictMode = true; return bindClassLikeDeclaration(node); - case 222: + case 227: return bindBlockScopedDeclaration(node, 64, 792968); - case 279: - case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 224: - return bindEnumDeclaration(node); - case 225: - return bindModuleDeclaration(node); - case 229: - case 232: - case 234: - case 238: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 285: + if (!node.fullName || node.fullName.kind === 70) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; case 228: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 229: + return bindEnumDeclaration(node); + case 230: + return bindModuleDeclaration(node); + case 234: + case 237: + case 239: + case 243: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 233: return bindNamespaceExportDeclaration(node); - case 231: - return bindImportClause(node); case 236: + return bindImportClause(node); + case 241: return bindExportDeclaration(node); - case 235: + case 240: return bindExportAssignment(node); - case 256: + case 261: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 199: + case 204: if (!ts.isFunctionLike(node.parent)) { return; } - case 226: + case 231: return updateStrictModeStatementList(node.statements); } } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 69) { + if (parameterName && parameterName.kind === 70) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 165) { + if (parameterName && parameterName.kind === 167) { seenThisKeyword = true; } bind(type); @@ -16712,27 +18041,27 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 240 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 256) { + if (node.parent.kind !== 261) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -16756,7 +18085,9 @@ var ts; function setCommonJsModuleIndicator(node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } function bindExportsPropertyAssignment(node) { @@ -16769,11 +18100,11 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { + if (container.kind === 225 || container.kind === 184) { container.symbol.members = container.symbol.members || ts.createMap(); declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } - else if (container.kind === 148) { + else if (container.kind === 150) { var saveContainer = container; container = container.parent; var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -16805,15 +18136,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 1024; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; - } - } - if (node.kind === 221) { + if (node.kind === 226) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -16856,11 +18179,6 @@ var ts; } } function bindParameter(node) { - if (!ts.isDeclarationFile(file) && - !ts.isInAmbientContext(node) && - ts.nodeIsDecorated(node)) { - emitFlags |= (2048 | 4096); - } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); } @@ -16878,7 +18196,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } checkStrictModeFunctionName(node); @@ -16893,7 +18211,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } if (currentFlow) { @@ -16906,12 +18224,12 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; + emitFlags |= 1024; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -16928,15 +18246,15 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || - node.kind === 221 || - (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 206) || + node.kind === 226 || + (node.kind === 230 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 229 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 200 || + (node.kind !== 205 || ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -16950,52 +18268,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 174: - return computeCallExpression(node, subtreeFlags); - case 225: - return computeModuleDeclaration(node, subtreeFlags); - case 178: - return computeParenthesizedExpression(node, subtreeFlags); - case 187: - return computeBinaryExpression(node, subtreeFlags); - case 202: - return computeExpressionStatement(node, subtreeFlags); - case 142: - return computeParameter(node, subtreeFlags); - case 180: - return computeArrowFunction(node, subtreeFlags); case 179: - return computeFunctionExpression(node, subtreeFlags); - case 220: - return computeFunctionDeclaration(node, subtreeFlags); - case 218: - return computeVariableDeclaration(node, subtreeFlags); - case 219: - return computeVariableDeclarationList(node, subtreeFlags); - case 200: - return computeVariableStatement(node, subtreeFlags); - case 214: - return computeLabeledStatement(node, subtreeFlags); - case 221: - return computeClassDeclaration(node, subtreeFlags); + return computeCallExpression(node, subtreeFlags); + case 180: + return computeNewExpression(node, subtreeFlags); + case 230: + return computeModuleDeclaration(node, subtreeFlags); + case 183: + return computeParenthesizedExpression(node, subtreeFlags); case 192: + return computeBinaryExpression(node, subtreeFlags); + case 207: + return computeExpressionStatement(node, subtreeFlags); + case 144: + return computeParameter(node, subtreeFlags); + case 185: + return computeArrowFunction(node, subtreeFlags); + case 184: + return computeFunctionExpression(node, subtreeFlags); + case 225: + return computeFunctionDeclaration(node, subtreeFlags); + case 223: + return computeVariableDeclaration(node, subtreeFlags); + case 224: + return computeVariableDeclarationList(node, subtreeFlags); + case 205: + return computeVariableStatement(node, subtreeFlags); + case 219: + return computeLabeledStatement(node, subtreeFlags); + case 226: + return computeClassDeclaration(node, subtreeFlags); + case 197: return computeClassExpression(node, subtreeFlags); - case 251: + case 255: return computeHeritageClause(node, subtreeFlags); - case 194: + case 256: + return computeCatchClause(node, subtreeFlags); + case 199: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 148: - return computeConstructor(node, subtreeFlags); - case 145: - return computePropertyDeclaration(node, subtreeFlags); - case 147: - return computeMethod(node, subtreeFlags); - case 149: case 150: + return computeConstructor(node, subtreeFlags); + case 147: + return computePropertyDeclaration(node, subtreeFlags); + case 149: + return computeMethod(node, subtreeFlags); + case 151: + case 152: return computeAccessor(node, subtreeFlags); - case 229: + case 234: return computeImportEquals(node, subtreeFlags); - case 172: + case 177: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -17006,40 +18328,55 @@ var ts; var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (subtreeFlags & 262144 + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288 || isSuperOrSuperProperty(expression, expressionKind)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537133909; + return transformFlags & ~537396545; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 95: + case 96: return true; - case 172: - case 173: + case 177: + case 178: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 95; + return expressionKind === 96; } return false; } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 56 - && (leftKind === 171 - || leftKind === 170)) { - transformFlags |= 192 | 256; + if (operatorTokenKind === 57 && leftKind === 176) { + transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 38 - || operatorTokenKind === 60) { - transformFlags |= 48; + else if (operatorTokenKind === 57 && leftKind === 175) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 39 + || operatorTokenKind === 61) { + transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17047,36 +18384,38 @@ var ts; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken) { - transformFlags |= 3; - } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { - transformFlags |= 3 | 131072; + transformFlags |= 3 | 262144; } - if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { - transformFlags |= 192 | 65536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~536872257; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 195 - || expressionKind === 177) { + if (expressionKind === 200 + || expressionKind === 182) { transformFlags |= 3; } - if (expressionTransformFlags & 256) { - transformFlags |= 256; + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -17086,35 +18425,36 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 137216) - || (modifierFlags & 1)) { + if ((subtreeFlags & 274432) + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 137216) { + if (subtreeFlags & 274432 + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 83: + case 84: transformFlags |= 192; break; - case 106: + case 107: transformFlags |= 3; break; default: @@ -17122,7 +18462,15 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -17130,127 +18478,155 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var body = node.body; - if (body === undefined) { + if (ts.hasModifier(node, 2270) + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - var typeParameters = node.typeParameters; - var asteriskToken = node.asteriskToken; - if (!body - || typeParameters - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer) { - transformFlags |= 4096; + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - var asteriskToken = node.asteriskToken; if (!body || (modifierFlags & 2)) { transformFlags = 3; } else { - transformFlags = subtreeFlags | 8388608; - if (modifierFlags & 1) { - transformFlags |= 3 | 192; - } - if (modifierFlags & 256) { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (modifierFlags & 256) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var asteriskToken = node.asteriskToken; - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 8192) { - transformFlags |= 16384; + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550710101; + return transformFlags & ~601249089; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (expressionKind === 95) { - transformFlags |= 8192; + if (expressionKind === 96) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - var nameKind = node.name.kind; - if (nameKind === 167 || nameKind === 168) { - transformFlags |= 192 | 2097152; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -17261,24 +18637,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (modifierFlags & 1) { - transformFlags |= 192 | 3; - } - if (declarationListTransformFlags & 2097152) { + if (declarationListTransformFlags & 8388608) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 1048576 + if (subtreeFlags & 4194304 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17286,15 +18659,15 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 256) { + if (node.expression.transformFlags & 1024) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -17303,78 +18676,76 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546335573; + return transformFlags & ~574674241; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608; - if (subtreeFlags & 2097152) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 1048576; + transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~546309441; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536871765; + var excludeFlags = 536872257; switch (kind) { - case 112: - case 110: + case 119: + case 189: + transformFlags |= 16; + break; + case 113: case 111: - case 115: - case 122: - case 118: - case 74: - case 184: - case 224: - case 255: - case 177: - case 195: - case 196: - case 128: + case 112: + case 116: + case 123: + case 75: + case 229: + case 260: + case 182: + case 200: + case 201: + case 130: transformFlags |= 3; break; - case 241: - case 242: - case 243: - case 244: - case 245: case 246: case 247: case 248: - transformFlags |= 12; + case 10: + case 249: + case 250: + case 251: + case 252: + transformFlags |= 4; break; - case 82: - transformFlags |= 192 | 3; - break; - case 77: - case 11: + case 213: + transformFlags |= 8; case 12: case 13: case 14: - case 189: - case 176: - case 254: - case 208: + case 15: + case 194: + case 181: + case 258: + case 114: transformFlags |= 192; break; - case 190: - transformFlags |= 192 | 4194304; + case 195: + transformFlags |= 192 | 16777216; break; - case 117: - case 130: - case 127: + case 118: case 132: - case 120: - case 133: - case 103: - case 141: - case 144: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: case 146: - case 151: - case 152: + case 148: case 153: case 154: case 155: @@ -17387,73 +18758,736 @@ var ts; case 162: case 163: case 164: - case 222: - case 223: case 165: case 166: + case 227: + case 228: + case 167: + case 168: + case 169: + case 170: + case 171: transformFlags = 3; excludeFlags = -3; break; - case 140: - transformFlags |= 524288; - if (subtreeFlags & 8192) { - transformFlags |= 32768; + case 142: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; } break; - case 191: - transformFlags |= 262144; + case 196: + transformFlags |= 192 | 524288; break; - case 95: + case 259: + transformFlags |= 8 | 1048576; + break; + case 96: transformFlags |= 192; break; - case 97: - transformFlags |= 8192; + case 98: + transformFlags |= 16384; break; - case 167: - case 168: - transformFlags |= 192 | 2097152; + case 172: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; break; - case 143: - transformFlags |= 3 | 2048; + case 173: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; break; - case 171: - excludeFlags = 537430869; + case 174: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 145: + transformFlags |= 3 | 4096; + break; + case 176: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 175: + case 180: + excludeFlags = 537396545; if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; - } break; - case 170: - case 175: - excludeFlags = 537133909; - if (subtreeFlags & 262144) { - transformFlags |= 192; - } - break; - case 204: - case 205: - case 206: - case 207: - if (subtreeFlags & 1048576) { - transformFlags |= 192; - } - break; - case 256: - if (subtreeFlags & 16384) { - transformFlags |= 192; - } - break; - case 211: case 209: case 210: - transformFlags |= 8388608; + case 211: + case 212: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 261: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 216: + case 214: + case 215: + transformFlags |= 33554432; break; } node.transformFlags = transformFlags | 536870912; return transformFlags & ~excludeFlags; } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 156 && kind <= 171) { + return -3; + } + switch (kind) { + case 179: + case 180: + case 175: + return 537396545; + case 230: + return 574674241; + case 144: + return 536872257; + case 185: + return 601249089; + case 184: + case 225: + return 601281857; + case 224: + return 546309441; + case 226: + case 197: + return 539358529; + case 150: + return 601015617; + case 149: + case 151: + case 152: + return 601015617; + case 118: + case 132: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: + case 146: + case 148: + case 153: + case 154: + case 155: + case 227: + case 228: + return -3; + case 176: + return 540087617; + case 256: + return 537920833; + case 172: + case 173: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2: + case 0: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === 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, typeRoots); + } + } + else { + 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, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, false, state); + return path_1 && { path: path_1, extension: tsExtension }; + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0) || tryResolve(1); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; + } + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case 2: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocations.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocations.push(packageJsonPath); + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(2, moduleName, directory, failedLookupLocations, state, true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== 1) { + return loadModuleFromNodeModulesFolder(2, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0) || tryResolve(1); + return createResolvedModuleWithFailedLookupLocations(resolved, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === 0) { + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -17480,6 +19514,8 @@ var ts; ts.getSymbolId = getSymbolId; function createTypeChecker(host, produceDiagnostics) { var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); @@ -17541,21 +19577,28 @@ var ts; getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + tryGetMemberInModuleExports: tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + } }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var stringLiteralTypes = ts.createMap(); var numericLiteralTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var trueType = createIntrinsicType(128, "true"); @@ -17566,10 +19609,13 @@ var ts; var neverType = createIntrinsicType(8192, "never"); var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + emptyTypeLiteralSymbol.members = ts.createMap(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); @@ -17590,6 +19636,7 @@ var ts; var globalBooleanType; var globalRegExpType; var anyArrayType; + var autoArrayType; var anyReadonlyArrayType; var getGlobalTemplateStringsArrayType; var getGlobalESSymbolType; @@ -17656,6 +19703,8 @@ var ts; "undefined": undefinedType }); var jsxElementType; + var _jsxNamespace; + var _jsxFactoryEntity; var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", @@ -17676,6 +19725,21 @@ var ts; builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; + function getJsxNamespace() { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } function getEmitResolver(sourceFile, cancellationToken) { getDiagnostics(sourceFile, cancellationToken); return emitResolver; @@ -17756,12 +19820,10 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 225 && source.valueDeclaration.kind !== 225))) { + (target.valueDeclaration.kind === 230 && source.valueDeclaration.kind !== 230))) { target.valueDeclaration = source.valueDeclaration; } - ts.forEach(source.declarations, function (node) { - target.declarations.push(node); - }); + ts.addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = ts.createMap(); @@ -17812,7 +19874,7 @@ var ts; var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); if (!mainModule) { return; } @@ -17849,8 +19911,11 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } function isGlobalSourceFile(node) { - return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 261 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -17887,36 +19952,39 @@ var ts; (!compilerOptions.outFile && !compilerOptions.out)) { return true; } + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } var sourceFiles = host.getSourceFiles(); return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 218 || + return declaration.kind !== 223 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 200: - case 206: - case 208: + case 205: + case 211: + case 213: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } break; } switch (declaration.parent.parent.kind) { - case 207: - case 208: + case 212: + case 213: if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { return true; } } return false; } - function isUsedInFunctionOrNonStaticProperty(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage, container) { var current = usage; while (current) { if (current === container) { @@ -17926,7 +19994,7 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 145 && + current.parent.kind === 147 && (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { @@ -17949,18 +20017,18 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 278) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 142 || - lastLocation.kind === 141 + lastLocation.kind === 144 || + lastLocation.kind === 143 : false; } if (meaning & 107455 && result.flags & 1) { useResult = - lastLocation.kind === 142 || + lastLocation.kind === 144 || (lastLocation === location.type && - result.valueDeclaration.kind === 142); + result.valueDeclaration.kind === 144); } } if (useResult) { @@ -17972,13 +20040,13 @@ var ts; } } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 225: + case 230: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 256 || ts.isAmbientModule(location)) { + if (location.kind === 261 || ts.isAmbientModule(location)) { if (result = moduleExports["default"]) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { @@ -17988,7 +20056,7 @@ var ts; } if (moduleExports[name] && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 238)) { + ts.getDeclarationOfKind(moduleExports[name], 243)) { break; } } @@ -17996,13 +20064,13 @@ var ts; break loop; } break; - case 224: + case 229: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 145: - case 144: + case 147: + case 146: if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -18012,9 +20080,9 @@ var ts; } } break; - case 221: - case 192: - case 222: + case 226: + case 197: + case 227: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -18022,7 +20090,7 @@ var ts; } break loop; } - if (location.kind === 192 && meaning & 32) { + if (location.kind === 197 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -18030,28 +20098,28 @@ var ts; } } break; - case 140: + case 142: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 222) { + if (ts.isClassLike(grandparent) || grandparent.kind === 227) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 180: + case 151: + case 152: + case 225: + case 185: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 179: + case 184: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -18064,8 +20132,8 @@ var ts; } } break; - case 143: - if (location.parent && location.parent.kind === 142) { + case 145: + if (location.parent && location.parent.kind === 144) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -18087,6 +20155,7 @@ var ts; if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } @@ -18107,15 +20176,15 @@ var ts; } if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + if (decls && decls.length === 1 && decls[0].kind === 233) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 70 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -18153,16 +20222,26 @@ var ts; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 69: - case 172: + case 70: + case 177: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: + case 199: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); @@ -18177,7 +20256,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -18194,23 +20273,23 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } - while (node && node.kind !== 230) { + while (node && node.kind !== 235) { node = node.parent; } return node; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 240) { + if (node.moduleReference.kind === 245) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -18268,28 +20347,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_13 = specifier.propertyName || specifier.name; - if (name_13.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -18311,19 +20390,19 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 229: - return getTargetOfImportEqualsDeclaration(node); - case 231: - return getTargetOfImportClause(node); - case 232: - return getTargetOfNamespaceImport(node); case 234: + return getTargetOfImportEqualsDeclaration(node); + case 236: + return getTargetOfImportClause(node); + case 237: + return getTargetOfNamespaceImport(node); + case 239: return getTargetOfImportSpecifier(node); - case 238: + case 243: return getTargetOfExportSpecifier(node); - case 235: + case 240: return getTargetOfExportAssignment(node); - case 228: + case 233: return getTargetOfNamespaceExportDeclaration(node); } } @@ -18367,10 +20446,10 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 235) { + if (node.kind === 240) { checkExpressionCached(node.expression); } - else if (node.kind === 238) { + else if (node.kind === 243) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -18378,15 +20457,15 @@ var ts; } } } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { - if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 70 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 69 || entityName.parent.kind === 139) { + if (entityName.kind === 70 || entityName.parent.kind === 141) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 229); + ts.Debug.assert(entityName.parent.kind === 234); return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } @@ -18398,16 +20477,16 @@ var ts; return undefined; } var symbol; - if (name.kind === 69) { + if (name.kind === 70) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } } - else if (name.kind === 139 || name.kind === 172) { - var left = name.kind === 139 ? name.left : name.expression; - var right = name.kind === 139 ? name.right : name.name; + else if (name.kind === 141 || name.kind === 177) { + var left = name.kind === 141 ? name.left : name.expression; + var right = name.kind === 141 ? name.right : name.name; var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -18432,27 +20511,28 @@ var ts; function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } if (moduleReferenceExpression.kind !== 9) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', 512); - if (symbol) { - return getMergedSymbol(symbol); - } + var ambientModule = tryFindAmbientModule(moduleName, true); + if (ambientModule) { + return ambientModule; } + var isRelative = ts.isExternalModuleNameRelative(moduleName); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); @@ -18468,14 +20548,29 @@ var ts; return getMergedSymbol(pattern.symbol); } } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + } + return undefined; + } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -18497,6 +20592,12 @@ var ts; function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } function getExportsOfSymbol(symbol) { return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -18526,6 +20627,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -18589,7 +20691,7 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 148 && ts.nodeIsPresent(member.body)) { + if (member.kind === 150 && ts.nodeIsPresent(member.body)) { return member; } } @@ -18611,8 +20713,9 @@ var ts; type.intrinsicName = "boolean"; return type; } - function createObjectType(kind, symbol) { - var type = createType(kind); + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -18636,7 +20739,7 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; @@ -18648,7 +20751,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -18659,11 +20762,11 @@ var ts; } } switch (location_1.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 225: + case 230: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } @@ -18677,6 +20780,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -18690,26 +20803,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -18727,7 +20842,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -18741,10 +20856,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 145: case 147: case 149: - case 150: + case 151: + case 152: continue; default: return false; @@ -18766,7 +20881,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, }; } return hasAccessibleDeclarations; @@ -18787,7 +20902,7 @@ var ts; } return { accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 }; @@ -18800,7 +20915,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 261 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -18834,11 +20949,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 158 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 160 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning = 107455 | 1048576; } - else if (entityName.kind === 139 || entityName.kind === 172 || - entityName.parent.kind === 229) { + else if (entityName.kind === 141 || entityName.kind === 177 || + entityName.parent.kind === 234) { meaning = 1920; } else { @@ -18930,10 +21045,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 164) { + while (node.kind === 166) { node = node.parent; } - if (node.kind === 223) { + if (node.kind === 228) { return getSymbolOfNode(node); } } @@ -18941,7 +21056,7 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 226 && + node.parent.kind === 231 && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { @@ -18955,10 +21070,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 192: + case 197: return "(Anonymous class)"; - case 179: - case 180: + case 184: + case 185: return "(Anonymous function)"; } } @@ -18972,17 +21087,17 @@ var ts; var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 19); + writePunctuation(writer, 20); if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } else { - writePunctuation(writer, 21); + writePunctuation(writer, 22); writer.writeSymbol(symbolName, symbol); } } @@ -19010,9 +21125,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_5) { + walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -19047,55 +21162,66 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { + else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } else if (type.flags & 256) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); + writePunctuation(writer, 22); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 2097152) { + else if (getObjectFlags(type) & (16 | 32)) { writeAnonymousType(type, nextFlags); } else if (type.flags & 96) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & 262144) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 64); + } + else if (type.flags & 524288) { + writeType(type.objectType, 64); + writePunctuation(writer, 20); + writeType(type.indexType, 0); + writePunctuation(writer, 21); + } else { - writePunctuation(writer, 15); - writeSpace(writer); - writePunctuation(writer, 22); - writeSpace(writer); writePunctuation(writer, 16); + writeSpace(writer); + writePunctuation(writer, 23); + writeSpace(writer); + writePunctuation(writer, 17); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 24) { + if (delimiter !== 25) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 24 ? 0 : 64); + writeType(types[i], delimiter === 25 ? 0 : 64); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { @@ -19103,29 +21229,29 @@ var ts; buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); writeType(typeArguments[pos], 256); pos++; while (pos < end) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); writeType(typeArguments[pos], 0); pos++; } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & 1)) { writeType(typeArguments[0], 64); - writePunctuation(writer, 19); writePunctuation(writer, 20); + writePunctuation(writer, 21); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + else if (type.target.objectFlags & 8) { writePunctuation(writer, 20); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 25); + writePunctuation(writer, 21); } else { var outerTypeParameters = type.target.outerTypeParameters; @@ -19134,13 +21260,13 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); - writePunctuation(writer, 21); + writeSymbolTypeReference(parent_6, typeArguments, start, i, flags); + writePunctuation(writer, 22); } } } @@ -19150,16 +21276,16 @@ var ts; } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 48); } else { - writeTypeList(type.types, 46); + writeTypeList(type.types, 47); } if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } } function writeAnonymousType(type, flags) { @@ -19177,7 +21303,7 @@ var ts; buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { - writeKeyword(writer, 117); + writeKeyword(writer, 118); } } else { @@ -19198,7 +21324,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 256 || declaration.parent.kind === 226; + return declaration.parent.kind === 261 || declaration.parent.kind === 231; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -19207,37 +21333,37 @@ var ts; } } function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 101); + writeKeyword(writer, 102); writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); } function writeIndexSignature(info, keyword) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } - writePunctuation(writer, 19); + writePunctuation(writer, 20); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeKeyword(writer, keyword); - writePunctuation(writer, 20); - writePunctuation(writer, 54); + writePunctuation(writer, 21); + writePunctuation(writer, 55); writeSpace(writer); writeType(info.type, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } buildSymbolDisplay(prop, writer); if (prop.flags & 536870912) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { @@ -19252,56 +21378,68 @@ var ts; return false; } function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 15); writePunctuation(writer, 16); + writePunctuation(writer, 17); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 15); + writePunctuation(writer, 16); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 17); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } - writeIndexSignature(resolved.stringIndexInfo, 132); - writeIndexSignature(resolved.numberIndexInfo, 130); + writeIndexSignature(resolved.stringIndexInfo, 134); + writeIndexSignature(resolved.numberIndexInfo, 132); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -19311,22 +21449,45 @@ var ts; var signature = signatures_1[_f]; writePropertyWithModifiers(p); buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeType(t, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } - writer.decreaseIndent(); + } + function writeMappedType(type) { writePunctuation(writer, 16); - inObjectTypeLiteral = saveInObjectTypeLiteral; + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 130); + writeSpace(writer); + } + writePunctuation(writer, 20); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 91); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 21); + if (type.declaration.questionToken) { + writePunctuation(writer, 54); + } + writePunctuation(writer, 55); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 24); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 17); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { @@ -19340,7 +21501,7 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 83); + writeKeyword(writer, 84); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } @@ -19348,7 +21509,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (ts.isRestParameter(parameterNode)) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } if (ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -19357,36 +21518,36 @@ var ts; appendSymbolNameOnly(p, writer); } if (isOptionalParameter(parameterNode)) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 167) { - writePunctuation(writer, 15); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (bindingPattern.kind === 172) { writePunctuation(writer, 16); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 17); } - else if (bindingPattern.kind === 168) { - writePunctuation(writer, 19); + else if (bindingPattern.kind === 173) { + writePunctuation(writer, 20); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 169); + ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); - writePunctuation(writer, 54); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 55); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -19394,75 +21555,75 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } action(list[i]); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); - var flags_1 = 256; + writePunctuation(writer, 26); + var flags = 256; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); - flags_1 = 0; + flags = 0; } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags_1); + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 18); + writePunctuation(writer, 19); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 97); + writeKeyword(writer, 98); } writeSpace(writer); - writeKeyword(writer, 124); + writeKeyword(writer, 125); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); - writePunctuation(writer, 34); + writePunctuation(writer, 35); } else { - writePunctuation(writer, 54); + writePunctuation(writer, 55); } writeSpace(writer); if (signature.typePredicate) { @@ -19475,7 +21636,7 @@ var ts; } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { if (kind === 1) { - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); } if (signature.target && (flags & 32)) { @@ -19511,63 +21672,63 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 169: + case 174: return isDeclarationVisible(node.parent.parent); - case 218: + case 223: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } + case 230: + case 226: + case 227: + case 228: case 225: - case 221: - case 222: - case 223: - case 220: - case 224: case 229: + case 234: if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_7 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 234 && parent_7.kind !== 261 && ts.isInAmbientContext(parent_7))) { + return isGlobalSourceFile(parent_7); } - return isDeclarationVisible(parent_9); - case 145: - case 144: - case 149: - case 150: + return isDeclarationVisible(parent_7); case 147: case 146: + case 151: + case 152: + case 149: + case 148: if (ts.getModifierFlags(node) & (8 | 16)) { return false; } - case 148: - case 152: - case 151: + case 150: + case 154: case 153: - case 142: - case 226: - case 156: - case 157: - case 159: case 155: - case 160: + case 144: + case 231: + case 158: + case 159: case 161: + case 157: case 162: case 163: case 164: + case 165: + case 166: return isDeclarationVisible(node.parent); - case 231: - case 232: - case 234: + case 236: + case 237: + case 239: return false; - case 141: - case 256: - case 228: + case 143: + case 261: + case 233: return true; - case 235: + case 240: return false; default: return false; @@ -19576,10 +21737,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 235) { + if (node.parent && node.parent.kind === 240) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 243) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -19641,7 +21802,6 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -19658,12 +21818,12 @@ var ts; node = ts.getRootDeclaration(node); while (node) { switch (node.kind) { - case 218: - case 219: - case 234: - case 233: - case 232: - case 231: + case 223: + case 224: + case 239: + case 238: + case 237: + case 236: node = node.parent; break; default: @@ -19689,22 +21849,36 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } - function getTextOfPropertyName(name) { - switch (name.kind) { - case 69: - return name.text; - case 9: - case 8: - return name.text; - case 140: - if (ts.isStringOrNumericLiteral(name.expression.kind)) { - return name.expression.text; - } - } - return undefined; - } function isComputedNonLiteralName(name) { - return name.kind === 140 && !ts.isStringOrNumericLiteral(name.expression.kind); + return name.kind === 142 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createMap(); + var names = ts.createMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name_17 = properties_2[_i]; + names[ts.getTextOfPropertyName(name_17)] = true; + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = prop.name in names; + var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isMethod = prop.flags & 8192; + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -19719,26 +21893,45 @@ var ts; return parentType; } var type; - if (pattern.kind === 167) { - var name_14 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_14)) { - return anyType; + if (pattern.kind === 172) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = getTextOfPropertyName(name_14); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); - return unknownType; + else { + var name_18 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_18)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name_18); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); + return unknownType; + } } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) @@ -19753,9 +21946,6 @@ var ts; return unknownType; } } - else { - type = createArrayType(elementType); - } } if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); @@ -19765,46 +21955,35 @@ var ts; type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); - } - } - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var typeTag = ts.getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - if (declaration.kind === 218 && - declaration.parent.kind === 219 && - declaration.parent.parent.kind === 200) { - var annotation = ts.getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === 142) { - var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } return undefined; } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 94 || expr.kind === 70 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 175 && expr.elements.length === 0; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.parent.parent.kind === 207) { - return stringType; + if (declaration.parent.parent.kind === 212) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; } - if (declaration.parent.parent.kind === 208) { + if (declaration.parent.parent.kind === 213) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -19813,10 +21992,20 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } - if (declaration.kind === 142) { + if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && + declaration.kind === 223 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 144) { var func = declaration.parent; - if (func.kind === 150 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149); + if (func.kind === 152 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -19829,8 +22018,7 @@ var ts; } var type = void 0; if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -19843,7 +22031,7 @@ var ts; var type = checkDeclarationInitializer(declaration); return addOptionality(type, declaration.questionToken && includeOptionality); } - if (declaration.kind === 254) { + if (declaration.kind === 258) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -19865,6 +22053,7 @@ var ts; } function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createMap(); + var stringIndexInfo; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -19872,19 +22061,23 @@ var ts; hasComputedProperties = true; return; } - var text = getTextOfPropertyName(name); + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.objectFlags |= 512; } return result; } @@ -19903,7 +22096,7 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 167 + return pattern.kind === 172 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -19913,7 +22106,7 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 253) { + if (declaration.kind === 257) { return type; } return getWidenedType(type); @@ -19928,7 +22121,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 142 ? root.parent : root; + var memberDeclaration = root.kind === 144 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -19938,28 +22131,28 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 252) { + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 235) { + if (declaration.kind === 240) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + if (declaration.flags & 65536 && declaration.kind === 286 && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } if (!pushTypeResolution(symbol, 0)) { return unknownType; } var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 1048576) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + if (declaration.kind === 192 || + declaration.kind === 177 && declaration.parent.kind === 192) { + if (declaration.flags & 65536) { + var jsdocType = ts.getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 ? checkExpressionCached(decl.right) : checkExpressionCached(decl.parent.right); }); type = getUnionType(declaredTypes, true); @@ -19968,16 +22161,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -19985,7 +22169,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 149) { + if (accessor.kind === 151) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -20005,9 +22189,9 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 149); - var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 1048576) { + var getter = ts.getDeclarationOfKind(symbol, 151); + var setter = ts.getDeclarationOfKind(symbol, 152); + if (getter && getter.flags & 65536) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -20047,7 +22231,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 149); + var getter_1 = ts.getDeclarationOfKind(symbol, 151); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -20058,11 +22242,11 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(16, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; } @@ -20089,10 +22273,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -20115,7 +22316,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return getObjectFlags(type) & 4 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -20143,9 +22344,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 221 || node.kind === 192 || - node.kind === 220 || node.kind === 179 || - node.kind === 147 || node.kind === 180) { + if (node.kind === 226 || node.kind === 197 || + node.kind === 225 || node.kind === 184 || + node.kind === 149 || node.kind === 185) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -20154,15 +22355,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 222); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 222 || node.kind === 221 || - node.kind === 192 || node.kind === 223) { + if (node.kind === 227 || node.kind === 226 || + node.kind === 197 || node.kind === 228) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -20175,7 +22376,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -20187,7 +22388,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -20202,7 +22403,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -20219,7 +22420,7 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { + if (type.objectFlags & 8) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (32 | 64)) { @@ -20239,7 +22440,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 32768)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -20257,15 +22458,22 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getObjectFlags(getTargetType(baseType)) & 3)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } if (type.resolvedBaseTypes === emptyArray) { @@ -20288,12 +22496,12 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 227 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getObjectFlags(getTargetType(baseType)) & 3) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -20317,7 +22525,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222) { + if (declaration.kind === 227) { if (declaration.flags & 64) { return false; } @@ -20340,12 +22548,12 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1 : 2; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -20353,7 +22561,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -20366,8 +22575,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); + var declaration = ts.getDeclarationOfKind(symbol, 285); var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -20378,14 +22586,15 @@ var ts; } } else { - declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + declaration = ts.getDeclarationOfKind(symbol, 228); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { + links.typeParameters = typeParameters; links.instantiations = ts.createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -20402,14 +22611,14 @@ var ts; return !ts.isInAmbientContext(member); } return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; + expr.kind === 70 && !!symbol.exports[expr.text]; } function enumHasLiteralMembers(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!isLiteralEnumMember(symbol, member)) { @@ -20437,7 +22646,7 @@ var ts; var memberTypes = ts.createMap(); for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { computeEnumMemberValues(declaration); for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; @@ -20452,7 +22661,7 @@ var ts; } enumType.memberTypes = memberTypes; if (memberTypeList.length > 1) { - enumType.flags |= 524288; + enumType.flags |= 65536; enumType.types = memberTypeList; unionTypes[getTypeListId(memberTypeList)] = enumType; } @@ -20464,7 +22673,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? + links.declaredType = enumType.flags & 65536 ? enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : enumType; } @@ -20475,7 +22684,7 @@ var ts; if (!links.declaredType) { var type = createType(16384); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 141).constraint) { + if (!ts.getDeclarationOfKind(symbol, 143).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -20524,20 +22733,20 @@ var ts; } function isIndependentType(node) { switch (node.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 166: + case 104: + case 137: + case 94: + case 129: + case 171: return true; - case 160: + case 162: return isIndependentType(node.elementType); - case 155: + case 157: return isIndependentTypeReference(node); } return false; @@ -20546,7 +22755,7 @@ var ts; return node.type && isIndependentType(node.type) || !node.type && !node.initializer; } function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 148 && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 150 && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -20562,12 +22771,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 145: - case 144: - return isIndependentVariableLikeDeclaration(declaration); case 147: case 146: + return isIndependentVariableLikeDeclaration(declaration); + case 149: case 148: + case 150: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -20610,7 +22819,7 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (getObjectFlags(type) & 4) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; @@ -20633,8 +22842,8 @@ var ts; else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -20654,7 +22863,7 @@ var ts; numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -20689,14 +22898,14 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -20781,7 +22990,7 @@ var ts; var constructSignatures = getUnionSignatures(type.types, 1); var stringIndexInfo = getUnionIndexInfo(type.types, 0); var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); @@ -20789,6 +22998,9 @@ var ts; function intersectIndexInfos(info1, info2) { return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { var callSignatures = emptyArray; var constructSignatures = emptyArray; @@ -20801,17 +23013,17 @@ var ts; stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { var members = symbol.members; @@ -20819,7 +23031,7 @@ var ts; var constructSignatures = getSignaturesOfSymbol(members["__new"]); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { var members = emptySymbols; @@ -20834,46 +23046,130 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } } } + function resolveMappedTypeMembers(type) { + var members = ts.createMap(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 168) { + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t) { + var iterationMapper = createUnaryTypeMapper(typeParameter, t); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = t.text; + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); + var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getErasedTemplateTypeFromMappedType(type) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32) { + var constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, 540672 | 262144); + } + return false; + } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { - resolveTypeReferenceMembers(type); + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } } - else if (type.flags & (32768 | 65536)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & 2097152) { - resolveAnonymousTypeMembers(type); - } - else if (type.flags & 524288) { + else if (type.flags & 65536) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 131072) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -20886,51 +23182,55 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 65536) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & 34) { - type = globalStringType; - } - else if (type.flags & 340) { - type = globalNumberType; - } - else if (type.flags & 136) { - type = globalBooleanType; - } - else if (type.flags & 512) { - type = getGlobalESSymbolType(); - } - return type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & 262178 ? globalStringType : + t.flags & 340 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -20948,21 +23248,21 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { - return undefined; + else if (containingType.flags & 65536) { + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -20973,22 +23273,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -20999,9 +23297,13 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -21015,13 +23317,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 196608) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -21031,7 +23333,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -21062,7 +23364,7 @@ var ts; return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -21090,21 +23392,31 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 1048576) { - if (node.type && node.type.kind === 268) { + if (node.flags & 65536) { + if (node.type && node.type.kind === 273) { return true; } - var paramTag = ts.getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 268; + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 273; + } } } } } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } function isOptionalParameter(node) { if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -21119,7 +23431,7 @@ var ts; return false; } function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 69) { + if (node.parameterName.kind === 70) { var parameterName = node.parameterName; return { kind: 1, @@ -21158,7 +23470,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166) { + if (param.type && param.type.kind === 171) { hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { @@ -21170,10 +23482,10 @@ var ts; minArgumentCount = -1; } } - if ((declaration.kind === 149 || declaration.kind === 150) && + if ((declaration.kind === 151 || declaration.kind === 152) && !ts.hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 149 ? 150 : 149; + var otherKind = declaration.kind === 151 ? 152 : 151; var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); @@ -21185,24 +23497,21 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } - var classType = declaration.kind === 148 ? + var classType = declaration.kind === 150 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 154 ? + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 156 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType) { + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -21212,14 +23521,14 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.kind === 149 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 150); + if (declaration.kind === 151 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 152); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -21233,20 +23542,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 269: + case 184: + case 185: + case 274: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -21307,13 +23616,18 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { return type.typeArguments[0]; } } return anyType; } function getSignatureInstantiation(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + function createSignatureInstantiation(signature, typeArguments) { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { @@ -21326,8 +23640,8 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var isConstructor = signature.declaration.kind === 150 || signature.declaration.kind === 154; + var type = createObjectType(16); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -21340,7 +23654,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 130 : 132; + var syntaxKind = kind === 1 ? 132 : 134; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -21367,11 +23681,11 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 141).constraint; + return ts.getDeclarationOfKind(type.symbol, 143).constraint; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -21399,8 +23713,13 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } function getTypeListId(types) { var result = ""; @@ -21433,22 +23752,23 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(4, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; type.target = target; type.typeArguments = typeArguments; } return type; } function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -21464,7 +23784,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -21472,18 +23792,23 @@ var ts; } return type; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeAliasInstantiation(symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); - var id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -21500,11 +23825,11 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 155: + case 157: return node.typeName; - case 267: + case 272: return node.name; - case 194: + case 199: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -21512,7 +23837,7 @@ var ts; } return undefined; } - function resolveTypeReferenceName(node, typeReferenceName) { + function resolveTypeReferenceName(typeReferenceName) { if (!typeReferenceName) { return unknownSymbol; } @@ -21528,7 +23853,7 @@ var ts; if (symbol.flags & 524288) { return getTypeFromTypeAliasReference(node, symbol); } - if (symbol.flags & 107455 && node.kind === 267) { + if (symbol.flags & 107455 && node.kind === 272) { return getTypeOfSymbol(symbol); } return getTypeFromNonGenericTypeReference(node, symbol); @@ -21538,13 +23863,13 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - if (node.kind === 267) { + if (node.kind === 272) { var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { - var typeNameOrExpression = node.kind === 155 + var typeNameOrExpression = node.kind === 157 ? node.typeName : ts.isEntityNameExpression(node.expression) ? node.expression @@ -21573,9 +23898,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 221: - case 222: - case 224: + case 226: + case 227: + case 229: return declaration; } } @@ -21584,7 +23909,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 32768)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -21647,7 +23972,7 @@ var ts; property.type = typeParameter; properties.push(property); } - var type = createObjectType(262144 | 131072); + var type = createObjectType(8 | 4); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -21655,7 +23980,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -21673,7 +23999,7 @@ var ts; function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -21701,7 +24027,7 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 524288) { + if (flags & 65536) { addTypesToUnion(typeSet, type.types); } else if (flags & 1) { @@ -21712,7 +24038,7 @@ var ts; typeSet.containsUndefined = true; if (flags & 4096) typeSet.containsNull = true; - if (!(flags & 33554432)) + if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } else if (!(flags & 8192)) { @@ -21725,7 +24051,8 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -21754,7 +24081,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -21770,7 +24114,7 @@ var ts; var t = types[i]; var remove = t.flags & 32 && types.containsString || t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -21812,28 +24156,31 @@ var ts; var type = unionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type = unionTypes[id] = createType(65536 | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { + if (type.flags & 131072) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1) { typeSet.containsAny = true; } else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -21855,43 +24202,303 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + type = intersectionTypes[id] = createType(131072 | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); } return links.resolvedType; } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + var propName = indexType.flags & (32 | 64 | 256) ? + indexType.text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : + undefined; + if (propName) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + var indexNode = accessNode.kind === 178 ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 | 64)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + } + else if (indexType.flags & (2 | 4)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (ts.isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 228 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right, isFromObjectLiteral) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + left = filterType(left, function (t) { return !(t.flags & 6144); }); + if (left.flags & 8192) { + return right; + } + right = filterType(right, function (t) { return !(t.flags & 6144); }); + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right, isFromObjectLiteral); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t, isFromObjectLiteral); }); + } + var members = ts.createMap(); + var skippedPrivateMembers = ts.createMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isOwnProperty = !(rightProp.flags & 8192) || isFromObjectLiteral; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + var rightProp = members[leftProp.name]; + var rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } function createLiteralType(flags, text) { var type = createType(flags); type.text = text; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 16777216)) { + if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 16777216, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.text); freshType.regularType = type; type.freshType = freshType; } @@ -21900,7 +24507,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } function getLiteralTypeForText(flags, text) { var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; @@ -21924,7 +24531,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); + var types = ts.map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -21932,9 +24539,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 227)) { if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 150 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -21948,85 +24555,88 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type) { - return getTypeFromTypeNode(type, undefined, undefined); - } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { - case 117: - case 258: - case 259: - return anyType; - case 132: - return stringType; - case 130: - return numberType; - case 120: - return booleanType; - case 133: - return esSymbolType; - case 103: - return voidType; - case 135: - return undefinedType; - case 93: - return nullType; - case 127: - return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; - case 165: - case 97: - return getTypeFromThisTypeNode(node); - case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); - case 155: - case 267: - return getTypeFromTypeReference(node); - case 154: - return booleanType; - case 194: - return getTypeFromTypeReference(node); - case 158: - return getTypeFromTypeQueryNode(node); - case 160: - case 260: - return getTypeFromArrayTypeNode(node); - case 161: - return getTypeFromTupleTypeNode(node); - case 162: - case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 164: + case 118: case 263: case 264: - case 271: - case 272: - case 268: - return getTypeFromTypeNode(node.type); - case 265: - return getTypeFromTypeNode(node.literal); - case 156: + return anyType; + case 134: + return stringType; + case 132: + return numberType; + case 121: + return booleanType; + case 135: + return esSymbolType; + case 104: + return voidType; + case 137: + return undefinedType; + case 94: + return nullType; + case 129: + return neverType; + case 289: + return nullType; + case 290: + return undefinedType; + case 291: + return neverType; + case 167: + case 98: + return getTypeFromThisTypeNode(node); + case 171: + return getTypeFromLiteralTypeNode(node); + case 288: + return getTypeFromLiteralTypeNode(node.literal); case 157: - case 159: - case 281: + case 272: + return getTypeFromTypeReference(node); + case 156: + return booleanType; + case 199: + return getTypeFromTypeReference(node); + case 160: + return getTypeFromTypeQueryNode(node); + case 162: + case 265: + return getTypeFromArrayTypeNode(node); + case 163: + return getTypeFromTupleTypeNode(node); + case 164: + case 266: + return getTypeFromUnionTypeNode(node); + case 165: + return getTypeFromIntersectionTypeNode(node); + case 166: + case 268: case 269: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); - case 69: - case 139: + case 276: + case 277: + case 273: + return getTypeFromTypeNode(node.type); + case 270: + return getTypeFromTypeNode(node.literal); + case 158: + case 159: + case 161: + case 287: + case 274: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 168: + return getTypeFromTypeOperatorNode(node); + case 169: + return getTypeFromIndexedAccessTypeNode(node); + case 170: + return getTypeFromMappedTypeNode(node); + case 70: + case 141: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 262: + case 267: return getTypeFromJSDocTupleType(node); - case 270: + case 275: return getTypeFromJSDocVariadicType(node); default: return unknownType; @@ -22043,6 +24653,16 @@ var ts; } return items; } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } function createUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -22065,7 +24685,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -22155,45 +24774,68 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - if (mapper.instantiations) { - var cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + var replacementMapper = createUnaryTypeMapper(typeVariable_1, t); + var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - var result = createObjectType(2097152 | 4194304, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } var mappedTypes = mapper.mappedTypes; var node = symbol.declarations[0].parent; while (node) { switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 221: - case 192: - case 222: - case 223: + case 184: + case 185: + case 226: + case 197: + case 227: + case 228: var declaration = node; if (declaration.typeParameters) { for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { @@ -22203,86 +24845,122 @@ var ts; } } } - if (ts.isClassLike(node) || node.kind === 222) { + if (ts.isClassLike(node) || node.kind === 227) { var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; if (thisType && ts.contains(mappedTypes, thisType)) { return true; } } break; - case 225: - case 256: + case 230: + case 261: return false; } node = node.parent; } return false; } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 261 || parentKind === 231; + } + return false; + } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { - return mapper(type); + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & 2097152) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & 131072) { - return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } return type; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 179: - case 180: + case 184: + case 185: return isContextSensitiveFunctionLikeDeclaration(node); - case 171: + case 176: return ts.forEach(node.properties, isContextSensitive); - case 170: + case 175: return ts.forEach(node.elements, isContextSensitive); - case 188: + case 193: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 187: - return node.operatorToken.kind === 52 && + case 192: + return node.operatorToken.kind === 53 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 253: + case 257: return isContextSensitive(node.initializer); - case 147: - case 146: + case 149: + case 148: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 183: return isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - var areAllParametersUntyped = !ts.forEach(node.parameters, function (p) { return p.type; }); - var isNullaryArrow = node.kind === 180 && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !p.type; })) { + return true; + } + if (node.kind === 185) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(16, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -22461,7 +25139,7 @@ var ts; } if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { + (source.flags & 65536) !== (target.flags & 65536)) { return enumRelation[id] = false; } var targetEnumType = getTypeOfSymbol(target.symbol); @@ -22484,7 +25162,7 @@ var ts; return false; if (target.flags & 1 || source.flags & 8192) return true; - if (source.flags & 34 && target.flags & 2) + if (source.flags & 262178 && target.flags & 2) return true; if (source.flags & 340 && target.flags & 4) return true; @@ -22518,23 +25196,23 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 32768 && target.flags & 32768) { var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { return related === 1; } } - if (source.flags & 4177920 || target.flags & 4177920) { + if (source.flags & 507904 || target.flags & 507904) { return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); } return false; @@ -22571,9 +25249,15 @@ var ts; targetType = typeToString(target, undefined, 128); } if (!message) { - message = relation === comparableRelation ? - ts.Diagnostics.Type_0_is_not_comparable_to_type_1 : - ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); } @@ -22587,12 +25271,29 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target) @@ -22602,19 +25303,19 @@ var ts; } if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (source.flags & 8388608 && source.flags & 16777216) { + if (getObjectFlags(source) & 128 && source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 65536) { if (relation === comparableRelation) { result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } @@ -22625,44 +25326,106 @@ var ts; return result; } } - else if (target.flags & 1048576) { - result = typeRelatedToEachType(source, target, reportErrors); - if (result) { + else if (target.flags & 65536) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } - else { - if (source.flags & 1048576) { - if (result = someTypeRelatedToType(source, target, false)) { + else if (target.flags & 131072) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else if (source.flags & 131072) { + if (result = someTypeRelatedToType(source, target, false)) { + return result; + } + } + else if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + var constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & 262144) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 524288) { + if (source.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & 16384) { - var constraint = getConstraintOfTypeParameter(source); - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + if (apparentSource.flags & (32768 | 131072) && target.flags & 32768) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; @@ -22671,10 +25434,10 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { + if (source.flags & 32768 && target.flags & 8190) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -22683,18 +25446,18 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 32768 && target.flags & 32768) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { - if (result = eachTypeRelatedToSomeType(source, target, false)) { - if (result &= eachTypeRelatedToSomeType(target, source, false)) { + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -22702,7 +25465,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -22711,7 +25474,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -22729,7 +25492,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -22744,7 +25507,7 @@ var ts; } return false; } - function eachTypeRelatedToSomeType(source, target, reportErrors) { + function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { @@ -22759,7 +25522,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { + if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } var len = targetTypes.length; @@ -22786,7 +25549,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { + if (source.flags & 65536 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -22873,6 +25636,9 @@ var ts; if (expandingFlags === 3) { result = 1; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -22900,15 +25666,42 @@ var ts; } return result; } + function mappedTypeRelatedTo(source, target, reportErrors) { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + var result_2; + if (relation === identityRelation) { + var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken; + var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) { + return -1; + } + return 0; + } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -22960,7 +25753,7 @@ var ts; return 0; } result &= related; - if (sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -22972,7 +25765,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 32768 && target.flags & 32768)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -23144,7 +25937,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (getObjectFlags(type) & 16) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -23156,12 +25949,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (getObjectFlags(type) & (4 | 64) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (getObjectFlags(t) & (4 | 64) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -23319,10 +26112,10 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return getObjectFlags(type) & 4 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { @@ -23333,7 +26126,7 @@ var ts; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -23341,19 +26134,19 @@ var ts; type.flags & 64 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 16777216 ? stringType : - type.flags & 64 && type.flags & 16777216 ? numberType : + return type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -23364,7 +26157,7 @@ var ts; return result; } function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 ? type.text === "" ? 32 : 0 : type.flags & 64 ? type.text === "0" ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : @@ -23375,7 +26168,7 @@ var ts; return type; } var types = [type]; - if (flags & 34) + if (flags & 262178) types.push(emptyStringType); if (flags & 340) types.push(zeroType); @@ -23425,7 +26218,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 8388608 && type.flags & 16777216)) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -23435,7 +26228,8 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; type.regularType = regularNew; return regularNew; } @@ -23452,25 +26246,25 @@ var ts; return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { + if (type.flags & 6291456) { if (type.flags & 6144) { return anyType; } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -23486,11 +26280,11 @@ var ts; } } } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -23504,25 +26298,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 145: - case 144: + case 147: + case 146: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 142: + case 144: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 169: + case 174: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 220: - case 147: - case 146: + case 225: case 149: - case 150: - case 179: - case 180: + case 148: + case 151: + case 152: + case 184: + case 185: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -23535,7 +26329,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -23567,7 +26361,7 @@ var ts; signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length), }; } function createTypeInferencesObject() { @@ -23575,26 +26369,72 @@ var ts; primary: undefined, secondary: undefined, topLevel: true, - isFixed: false + isFixed: false, }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypes(context, originalSource, originalTarget) { - var typeParameters = context.signature.typeParameters; + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var typeVariableArray = [typeVariable]; + var typeInferences = createTypeInferencesObject(); + var typeInferencesArray = [typeInferences]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var members = createSymbolTable(properties); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + var inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, true); + } + } + function inferTypesWithContext(context, originalSource, originalTarget) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { var sourceStack; var targetStack; var depth = 0; @@ -23610,11 +26450,19 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { return; } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -23641,13 +26489,13 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 540672) { + if (source.flags & 8388608) { return; } - for (var i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - var inferences = context.inferences[i]; + for (var i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + var inferences = typeInferences[i]; if (!inferences.isFixed) { var candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : @@ -23655,7 +26503,7 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -23663,7 +26511,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -23671,27 +26519,27 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (target.flags & 196608) { var targetTypes = target.types; - var typeParameterCount = 0; - var typeParameter = void 0; + var typeVariableCount = 0; + var typeVariable = void 0; for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & 540672 && ts.contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 196608) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -23700,7 +26548,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 32768) { if (isInProcess(source, target)) { return; } @@ -23719,18 +26567,41 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var index = ts.indexOf(typeVariables, constraintType.type); + if (index >= 0 && !typeInferences[index].isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -23796,7 +26667,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -23804,7 +26675,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; @@ -23816,7 +26687,7 @@ var ts; var widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; @@ -23857,10 +26728,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 158: + case 160: return true; - case 69: - case 139: + case 70: + case 141: node = node.parent; continue; default: @@ -23870,14 +26741,14 @@ var ts; ts.Debug.fail("should not get here"); } function getFlowCacheKey(node) { - if (node.kind === 69) { + if (node.kind === 70) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - if (node.kind === 97) { + if (node.kind === 98) { return "0"; } - if (node.kind === 172) { + if (node.kind === 177) { var key = getFlowCacheKey(node.expression); return key && key + "." + node.name.text; } @@ -23885,31 +26756,31 @@ var ts; } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { - case 69: - case 97: + case 70: + case 98: return node; - case 172: + case 177: return getLeftmostIdentifierOrThis(node.expression); } return undefined; } function isMatchingReference(source, target) { switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && + case 70: + return target.kind === 70 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 223 || target.kind === 174) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && + case 98: + return target.kind === 98; + case 177: + return target.kind === 177 && source.name.text === target.name.text && isMatchingReference(source.expression, target.expression); } return false; } function containsMatchingReference(source, target) { - while (source.kind === 172) { + while (source.kind === 177) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -23918,33 +26789,26 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && + return target.kind === 177 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { + if (expr.kind === 70) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 172) { + if (expr.kind === 177) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.text); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -23963,7 +26827,7 @@ var ts; } } } - if (callExpression.expression.kind === 172 && + if (callExpression.expression.kind === 177 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -23977,7 +26841,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 65536)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -24040,7 +26904,7 @@ var ts; type === falseType ? 3030404 : 1981828 : type === falseType ? 3145092 : 4193668; } - if (flags & 2588672) { + if (flags & 32768) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 : 8376288 : strictNullChecks ? 6166480 : 8378320; @@ -24058,7 +26922,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type); return getTypeFacts(constraint || emptyObjectType); } - if (flags & 1572864) { + if (flags & 196608) { return getTypeFactsOfTypes(type.types); } return 8388607; @@ -24068,13 +26932,13 @@ var ts; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { - var defaultType = checkExpression(defaultExpression); + var defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, 131072), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { - var text = getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || @@ -24085,19 +26949,19 @@ var ts; checkIteratedTypeOrElementType(type, undefined, false) || unknownType; } - function getTypeOfDestructuredSpreadElement(type) { + function getTypeOfDestructuredSpreadExpression(type) { return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 170 || node.parent.kind === 253 ? + return node.parent.kind === 175 || node.parent.kind === 257 ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node) { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node) { return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); @@ -24108,21 +26972,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 207: + case 212: return stringType; - case 208: + case 213: return checkRightHandSideOfForOf(parent.expression) || unknownType; - case 187: + case 192: return getAssignedTypeOfBinaryExpression(parent); - case 181: + case 186: return undefinedType; - case 170: + case 175: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 191: - return getAssignedTypeOfSpreadElement(parent); - case 253: + case 196: + return getAssignedTypeOfSpreadExpression(parent); + case 257: return getAssignedTypeOfPropertyAssignment(parent); - case 254: + case 258: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -24130,56 +26994,69 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 167 ? + var type = pattern.kind === 172 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { var links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 207) { + if (node.parent.parent.kind === 212) { return stringType; } - if (node.parent.parent.kind === 208) { + if (node.parent.parent.kind === 213) { return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 218 ? + return node.kind === 223 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? + return node.kind === 223 || node.kind === 174 ? getInitialType(node) : getAssignedType(node); } + function isEmptyArrayAssignment(node) { + return node.kind === 223 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 174 && node.parent.kind === 192 && + isEmptyArrayLiteral(node.parent.right); + } function getReferenceCandidate(node) { switch (node.kind) { - case 178: + case 183: return getReferenceCandidate(node.expression); - case 187: + case 192: switch (node.operatorToken.kind) { - case 56: + case 57: return getReferenceCandidate(node.left); - case 24: + case 25: return getReferenceCandidate(node.right); } } return node; } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 183 || + parent.kind === 192 && parent.operatorToken.kind === 57 && parent.left === node || + parent.kind === 192 && parent.operatorToken.kind === 25 && parent.right === node ? + getReferenceRoot(parent) : node; + } function getTypeOfSwitchClause(clause) { - if (clause.kind === 249) { - var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + if (clause.kind === 253) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -24193,13 +27070,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { + if (source.flags & 65536) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -24213,14 +27090,34 @@ var ts; } return containsType(target.types, source); } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } function filterType(type, f) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 65536 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -24230,22 +27127,105 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 177 && (parent.name.text === "length" || + parent.parent.kind === 179 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 178 && + parent.expression === root && + parent.parent.kind === 192 && + parent.parent.operatorToken.kind === 57 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 201 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 512) { + if (flow.flags & 1024) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -24275,18 +27255,25 @@ var ts; getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && container !== flowContainer && reference.kind !== 177) { flow = container.flowNode; continue; } type = initialType; } else { - type = declaredType; + type = convertAutoToAny(declaredType); } - if (flow.flags & 512) { + if (flow.flags & 1024) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -24297,27 +27284,70 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; } return undefined; } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 179 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 179) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (!(type.flags & 8192)) { - var assumeTrue = (flow.flags & 32) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & 8192 && isIncomplete(flowType)) { - type = silentNeverType; - } + if (type.flags & 8192) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); @@ -24352,7 +27382,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); @@ -24364,8 +27394,8 @@ var ts; return cache[key]; } for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); } } var antecedentTypes = []; @@ -24396,15 +27426,15 @@ var ts; break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, true); } return cache[key] = result; } function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && + return expr.kind === 177 && + declaredType.flags & 65536 && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(declaredType, expr.name.text); } @@ -24428,19 +27458,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 56: + case 57: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 30: case 31: case 32: case 33: + case 34: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { + if (left_1.kind === 187 && right_1.kind === 9) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { + if (right_1.kind === 187 && left_1.kind === 9) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -24459,9 +27489,9 @@ var ts; return declaredType; } break; - case 91: + case 92: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 24: + case 25: return narrowType(type, expr.right, assumeTrue); } return type; @@ -24470,28 +27500,28 @@ var ts; if (type.flags & 1) { return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); + var valueType = getTypeOfExpression(value); if (valueType.flags & 6144) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 30 || operator === 31; + var doubleEquals = operator === 31 || operator === 32; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - value.kind === 93 ? + value.kind === 94 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 33281) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -24507,10 +27537,10 @@ var ts; } return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { + if (assumeTrue && !(type.flags & 65536)) { var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; @@ -24529,7 +27559,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -24544,7 +27575,7 @@ var ts; } return type; } - var rightType = checkExpression(expr.right); + var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -24561,10 +27592,10 @@ var ts; } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (getObjectFlags(rightType) & 2) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (getObjectFlags(rightType) & 16) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -24572,16 +27603,16 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type, candidate, assumeTrue) { + function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); if (!(assignableType.flags & 8192)) { return assignableType; } @@ -24593,7 +27624,7 @@ var ts; getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } var signature = getResolvedSignature(callExpression); @@ -24608,7 +27639,7 @@ var ts; var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -24616,12 +27647,12 @@ var ts; } } else { - var invokedExpression = skipParenthesizedNodes(callExpression.expression); - if (invokedExpression.kind === 173 || invokedExpression.kind === 172) { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 178 || invokedExpression.kind === 177) { var accessExpression = invokedExpression; - var possibleReference = skipParenthesizedNodes(accessExpression.expression); + var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -24632,18 +27663,18 @@ var ts; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 174: + case 179: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 178: + case 183: return narrowType(type, expr.expression, assumeTrue); - case 187: + case 192: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 185: - if (expr.operator === 49) { + case 190: + if (expr.operator === 50) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -24652,12 +27683,12 @@ var ts; } } function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 69) { + if (location.kind === 70) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { - var type = checkExpression(location); + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -24665,19 +27696,13 @@ var ts; } return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression) { - while (expression.kind === 178) { - expression = expression.expression; - } - return expression; - } function getControlFlowContainer(node) { while (true) { node = node.parent; if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + node.kind === 231 || + node.kind === 261 || + node.kind === 147) { return node; } } @@ -24705,10 +27730,10 @@ var ts; } } function markParameterAssignments(node) { - if (node.kind === 69) { + if (node.kind === 70) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144) { symbol.isAssigned = true; } } @@ -24717,21 +27742,28 @@ var ts; ts.forEachChild(node, markParameterAssignments); } } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 180) { + if (container.kind === 185) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - if (node.flags & 262144) { + if (node.flags & 16384) { getNodeLinks(container).flags |= 8192; } + return getTypeOfSymbol(symbol); } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); @@ -24739,8 +27771,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); if (localOrExportSymbol.flags & 32) { var declaration_1 = localOrExportSymbol.valueDeclaration; - if (languageVersion === 2 - && declaration_1.kind === 221 + if (declaration_1.kind === 226 && ts.nodeIsDecorated(declaration_1)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -24752,11 +27783,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration_1.kind === 192) { + else if (declaration_1.kind === 197) { var container = ts.getThisContainer(node, false); while (container !== undefined) { if (container.parent === declaration_1) { - if (container.kind === 145 && ts.hasModifier(container, 32)) { + if (container.kind === 147 && ts.hasModifier(container, 32)) { getNodeLinks(declaration_1).flags |= 8388608; getNodeLinks(node).flags |= 16777216; } @@ -24771,26 +27802,47 @@ var ts; checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var isParameter = ts.getRootDeclaration(declaration).kind === 144; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === 184 || + flowContainer.kind === 185 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node, threshold) { var current = node; @@ -24805,7 +27857,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 252) { + symbol.valueDeclaration.parent.kind === 256) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -24823,8 +27875,8 @@ var ts; if (usedInFunction) { getNodeLinks(current).flags |= 65536; } - if (container.kind === 206 && - ts.getAncestor(symbol.valueDeclaration, 219).parent === container && + if (container.kind === 211 && + ts.getAncestor(symbol.valueDeclaration, 224).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152; } @@ -24836,16 +27888,16 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 178) { + while (current.parent.kind === 183) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 185 || current.parent.kind === 186)) { + else if ((current.parent.kind === 190 || current.parent.kind === 191)) { var expr = current.parent; - isAssigned = expr.operator === 41 || expr.operator === 42; + isAssigned = expr.operator === 42 || expr.operator === 43; } if (!isAssigned) { return false; @@ -24862,7 +27914,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 145 || container.kind === 148) { + if (container.kind === 147 || container.kind === 150) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -24871,7 +27923,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -24893,42 +27945,45 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 148) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + if (container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 180) { + if (container.kind === 185) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 225: + case 230: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 224: + case 229: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 148: + case 150: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 145: - case 144: + case 147: + case 146: if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 140: + case 142: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -24936,8 +27991,8 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { - if (container.kind === 179 && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 184 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { var className = container.parent @@ -24949,7 +28004,7 @@ var ts; return getInferredClassType(classSymbol); } } - var thisType = getThisTypeOfDeclaration(container); + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -24971,28 +28026,28 @@ var ts; return anyType; } function getTypeForThisExpressionFromJSDoc(node) { - var typeTag = ts.getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 269) { - var jsDocFunctionType = typeTag.typeExpression.type; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 272) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 274) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 142) { + if (n.kind === 144) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 174 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 179 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 180) { + while (container && container.kind === 185) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -25001,16 +28056,16 @@ var ts; var nodeCheckFlag = 0; if (!canUseSuperExpression) { var current = node; - while (current && current !== container && current.kind !== 140) { + while (current && current !== container && current.kind !== 142) { current = current.parent; } - if (current && current.kind === 140) { + if (current && current.kind === 142) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 171)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -25018,6 +28073,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -25025,7 +28083,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (container.kind === 149 && ts.getModifierFlags(container) & 256) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -25036,7 +28094,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 171) { + if (container.parent.kind === 176) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -25054,7 +28112,7 @@ var ts; } return unknownType; } - if (container.kind === 148 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 150 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -25066,35 +28124,38 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 148; + return container.kind === 150; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 171) { + if (ts.isClassLike(container.parent) || container.parent.kind === 176) { if (ts.getModifierFlags(container) & 32) { - return container.kind === 147 || - container.kind === 146 || - container.kind === 149 || - container.kind === 150; + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152; } else { - return container.kind === 147 || + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152 || + container.kind === 147 || container.kind === 146 || - container.kind === 149 || - container.kind === 150 || - container.kind === 145 || - container.kind === 144 || - container.kind === 148; + container.kind === 150; } } } return false; } } - function getContextualThisParameter(func) { - if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { + function getContextualThisParameterType(func) { + if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } return undefined; @@ -25144,7 +28205,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 142) { + if (declaration.kind === 144) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -25155,11 +28216,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_15 = declaration.propertyName || declaration.name; + var name_19 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_15)) { - var text = getTextOfPropertyName(name_15); + !ts.isBindingPattern(name_19)) { + var text = ts.getTextOfPropertyName(name_19); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -25196,7 +28257,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 142 && node.parent.initializer === node) { + if (node.parent.kind === 144 && node.parent.initializer === node) { return true; } node = node.parent; @@ -25205,8 +28266,8 @@ var ts; } function getContextualReturnType(functionDecl) { if (functionDecl.type || - functionDecl.kind === 148 || - functionDecl.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 150))) { + functionDecl.kind === 150 || + functionDecl.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); @@ -25225,7 +28286,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 176) { + if (template.parent.kind === 181) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -25233,22 +28294,22 @@ var ts; function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; - if (operator >= 56 && operator <= 68) { + if (operator >= 57 && operator <= 69) { if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { return undefined; } if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } - else if (operator === 52) { + else if (operator === 53) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } - else if (operator === 51 || operator === 24) { + else if (operator === 52 || operator === 25) { if (node === binaryExpression.right) { return getContextualType(binaryExpression); } @@ -25256,14 +28317,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 65536)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -25281,7 +28342,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -25289,7 +28350,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -25333,13 +28394,13 @@ var ts; var kind = attribute.kind; var jsxElement = attribute.parent; var attrsType = getJsxElementAttributesType(jsxElement); - if (attribute.kind === 246) { + if (attribute.kind === 250) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - else if (attribute.kind === 247) { + else if (attribute.kind === 251) { return attrsType; } ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); @@ -25357,56 +28418,70 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 169: - return getContextualTypeForInitializerExpression(node); - case 180: - case 211: - return getContextualTypeForReturnExpression(node); - case 190: - return getContextualTypeForYieldOperand(parent); + case 147: + case 146: case 174: - case 175: - return getContextualTypeForArgument(parent, node); - case 177: + return getContextualTypeForInitializerExpression(node); + case 185: + case 216: + return getContextualTypeForReturnExpression(node); case 195: + return getContextualTypeForYieldOperand(parent); + case 179: + case 180: + return getContextualTypeForArgument(parent, node); + case 182: + case 200: return getTypeFromTypeNode(parent.type); - case 187: + case 192: return getContextualTypeForBinaryOperand(node); - case 253: - case 254: + case 257: + case 258: return getContextualTypeForObjectLiteralElement(parent); - case 170: + case 175: return getContextualTypeForElementExpression(node); - case 188: + case 193: return getContextualTypeForConditionalOperand(node); - case 197: - ts.Debug.assert(parent.parent.kind === 189); + case 202: + ts.Debug.assert(parent.parent.kind === 194); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 178: + case 183: return getContextualType(parent); - case 248: + case 252: return getContextualType(parent); - case 246: - case 247: + case 250: + case 251: return getContextualTypeForJsxAttribute(parent); } return undefined; } - function getNonGenericSignature(type) { + function getNonGenericSignature(type, node) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 179 || node.kind === 180; + return node.kind === 184 || node.kind === 185; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -25419,19 +28494,19 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 524288)) { - return getNonGenericSignature(type); + if (!(type.flags & 65536)) { + return getNonGenericSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; - var signature = getNonGenericSignature(current); + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { signatureList = [signature]; @@ -25455,13 +28530,13 @@ var ts; function isInferentialContext(mapper) { return mapper && mapper.context; } - function checkSpreadElementExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node, contextualMapper) { + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 169 && !!node.initializer) || - (node.kind === 187 && node.operatorToken.kind === 56); + return (node.kind === 174 && !!node.initializer) || + (node.kind === 192 && node.operatorToken.kind === 57); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -25470,7 +28545,7 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 191) { + if (inDestructuringPattern && e.kind === 196) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -25482,7 +28557,7 @@ var ts; var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 191; + hasSpreadElement = hasSpreadElement || e.kind === 196; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -25493,7 +28568,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 168 || pattern.kind === 170)) { + if (pattern && (pattern.kind === 173 || pattern.kind === 175)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -25501,7 +28576,7 @@ var ts; elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 193) { + if (patternElement.kind !== 198) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -25518,7 +28593,7 @@ var ts; strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { - return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 142 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); @@ -25536,7 +28611,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -25545,10 +28620,10 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(node, properties, kind) { + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(node.properties[i].name)) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -25560,35 +28635,38 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createMap(); var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 167 || contextualType.pattern.kind === 171); + (contextualType.pattern.kind === 172 || contextualType.pattern.kind === 176); var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var memberDecl = _a[_i]; + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; var member = memberDecl.symbol; - if (memberDecl.kind === 253 || - memberDecl.kind === 254 || + if (memberDecl.kind === 257 || + memberDecl.kind === 258 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 253) { + if (memberDecl.kind === 257) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 147) { + else if (memberDecl.kind === 149) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 254); + ts.Debug.assert(memberDecl.kind === 258); type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 253 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 254 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 257 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 258 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } @@ -25596,12 +28674,12 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -25614,8 +28692,29 @@ var ts; prop.target = member; member = prop; } + else if (memberDecl.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + propertiesArray = []; + propertiesTable = ts.createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, false); + offset = i + 1; + continue; + } else { - ts.Debug.assert(memberDecl.kind === 149 || memberDecl.kind === 150); + ts.Debug.assert(memberDecl.kind === 151 || memberDecl.kind === 152); checkAccessorDeclaration(memberDecl); } if (ts.hasDynamicName(memberDecl)) { @@ -25632,8 +28731,8 @@ var ts; propertiesArray.push(member); } if (contextualTypeHasPattern) { - for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { - var prop = _c[_b]; + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); @@ -25643,15 +28742,40 @@ var ts; } } } - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); - if (inDestructuringPattern) { - result.pattern = node; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - return result; + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); @@ -25668,13 +28792,13 @@ var ts; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 248: + case 252: checkJsxExpression(child); break; - case 241: + case 246: checkJsxElement(child); break; - case 242: + case 247: checkJsxSelfClosingElement(child); break; } @@ -25685,7 +28809,7 @@ var ts; return name.indexOf("-") < 0; } function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 172 || tagName.kind === 97) { + if (tagName.kind === 177 || tagName.kind === 98) { return false; } else { @@ -25701,7 +28825,7 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); if (attributeType) { correspondingPropType = attributeType; } @@ -25727,6 +28851,9 @@ var ts; return exprType; } function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + if (compilerOptions.jsx === 2) { + checkExternalEmitHelpers(node, 2); + } var type = checkExpression(node.expression); var props = getPropertiesOfType(type); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { @@ -25776,7 +28903,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 65536)); if (isTypeAny(valueType)) { return anyType; } @@ -25788,7 +28915,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -25815,9 +28942,9 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 65536) { var types = elemType.types; - return getUnionType(types.map(function (type) { + return getUnionType(ts.map(types, function (type) { return getResolvedJsxType(node, type, elemClassType); }), true); } @@ -25877,7 +29004,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 65536) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -25954,20 +29081,23 @@ var ts; checkGrammarJsxElement(node); checkJsxPreconditions(node); var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactNamespace = getJsxNamespace(); var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + reactSym.isReferenced = true; + if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 246) { + if (node.attributes[i].kind === 250) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 247); + ts.Debug.assert(node.attributes[i].kind === 251); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -25993,7 +29123,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 145; + return s.valueDeclaration ? s.valueDeclaration.kind : 147; } function getDeclarationModifierFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; @@ -26004,11 +29134,11 @@ var ts; function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); - var errorNode = node.kind === 172 || node.kind === 218 ? + var errorNode = node.kind === 177 || node.kind === 223 ? node.name : node.right; - if (left.kind === 95) { - if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 147) { + if (left.kind === 96) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 149) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -26028,7 +29158,7 @@ var ts; } return true; } - if (left.kind === 95) { + if (left.kind === 96) { return true; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { @@ -26042,10 +29172,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -26071,6 +29201,33 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (prop.flags & 16777216) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -26083,48 +29240,33 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & 32) { checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (node.kind !== 172 || ts.isAssignmentTarget(node) || + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 177 || assignmentKind === 1 || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 65536)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 524288 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + var flowType = getFlowTypeOfReference(node, propType, true, undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 172 + var left = node.kind === 177 ? node.expression : node.left; var type = checkExpression(left); @@ -26138,13 +29280,13 @@ var ts; } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 219) { + if (initializer.kind === 224) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 69) { + else if (initializer.kind === 70) { return getResolvedSymbol(initializer); } return undefined; @@ -26153,17 +29295,17 @@ var ts; return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); } function isForInVariableForNumericPropertyNames(expr) { - var e = skipParenthesizedNodes(expr); - if (e.kind === 69) { + var e = ts.skipParentheses(expr); + if (e.kind === 70) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 207 && + if (node.kind === 212 && child === node.statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression(node.expression))) { + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { return true; } child = node; @@ -26174,9 +29316,11 @@ var ts; return false; } function checkIndexedAccess(node) { - if (!node.argumentExpression) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 175 && node.parent.expression === node) { + if (node.parent.kind === 180 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -26186,71 +29330,17 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } + return unknownType; } - var objectType = getApparentType(checkNonNullExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - var isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== 9)) { - error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - if (node.argumentExpression) { - var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_16 !== undefined) { - var prop = getPropertyOfType(objectType, name_16); - 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_16, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - var numberIndexInfo = getIndexInfoOfType(objectType, 1); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - var stringIndexInfo = getIndexInfoOfType(objectType, 0); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, 1) ? - ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - return anyType; - } - error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - return unknownType; - } - function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { - if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { - return indexArgumentExpression.text; - } - if (indexArgumentExpression.kind === 173 || indexArgumentExpression.kind === 172) { - var value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, false)) { - var rightHandSideName = indexArgumentExpression.name.text; - return ts.getPropertyNameForKnownSymbolName(rightHandSideName); - } - return undefined; + return getIndexedAccessType(objectType, indexType, node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { @@ -26283,10 +29373,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 176) { + if (node.kind === 181) { checkExpression(node.template); } - else if (node.kind !== 143) { + else if (node.kind !== 145) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -26308,19 +29398,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_8 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_8 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_8; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_8; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -26337,7 +29427,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 191) { + if (arg && arg.kind === 196) { return i; } } @@ -26350,11 +29440,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 176) { + if (node.kind === 181) { var tagExpression = node; argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 189) { + if (tagExpression.template.kind === 194) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -26362,11 +29452,11 @@ var ts; } else { var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 11); + ts.Debug.assert(templateLiteral.kind === 12); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 143) { + else if (node.kind === 145) { isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); @@ -26374,7 +29464,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 175); + ts.Debug.assert(callExpression.kind === 180); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -26397,7 +29487,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -26409,7 +29499,7 @@ var ts; function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -26428,19 +29518,19 @@ var ts; if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } if (excludeArgument) { @@ -26448,7 +29538,7 @@ var ts; if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -26480,7 +29570,7 @@ var ts; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 175) { + if (thisType && thisType !== voidType && node.kind !== 180) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -26493,9 +29583,9 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } @@ -26508,28 +29598,28 @@ var ts; return true; } function getThisArgumentOfCall(node) { - if (node.kind === 174) { + if (node.kind === 179) { var callee = node.expression; - if (callee.kind === 172) { + if (callee.kind === 177) { return callee.expression; } - else if (callee.kind === 173) { + else if (callee.kind === 178) { return callee.expression; } } } function getEffectiveCallArguments(node) { var args; - if (node.kind === 176) { + if (node.kind === 181) { var template = node.template; args = [undefined]; - if (template.kind === 189) { + if (template.kind === 194) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 143) { + else if (node.kind === 145) { return undefined; } else { @@ -26538,21 +29628,21 @@ var ts; return args; } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 143) { + if (node.kind === 145) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return 1; - case 145: - return 2; case 147: + return 2; case 149: - case 150: + case 151: + case 152: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 142: + case 144: return 3; } } @@ -26561,48 +29651,48 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { return anyType; } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { var element = node; switch (element.name.kind) { - case 69: + case 70: case 8: case 9: return getLiteralTypeForText(32, element.name.text); - case 140: + case 142: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { return nameType; @@ -26619,20 +29709,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { return numberType; } - if (node.kind === 145) { + if (node.kind === 147) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 147 || - node.kind === 149 || - node.kind === 150) { + if (node.kind === 149 || + node.kind === 151 || + node.kind === 152) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -26652,27 +29742,27 @@ var ts; ts.Debug.fail("Decorators should not have a fourth synthetic argument."); return unknownType; } - function getEffectiveArgumentType(node, argIndex, arg) { - if (node.kind === 143) { + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 145) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return getGlobalTemplateStringsArrayType(); } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 143 || - (argIndex === 0 && node.kind === 176)) { + if (node.kind === 145 || + (argIndex === 0 && node.kind === 181)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 143) { + if (node.kind === 145) { return node.expression; } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return node.template; } else { @@ -26680,12 +29770,12 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 176; - var isDecorator = node.kind === 143; + var isTaggedTemplate = node.kind === 181; + var isDecorator = node.kind === 145; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; - if (node.expression.kind !== 95) { + if (node.expression.kind !== 96) { ts.forEach(typeArguments, checkSourceElement); } } @@ -26711,7 +29801,7 @@ var ts; var candidateForTypeArgumentError; var resultOfFailedInference; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 174 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -26730,7 +29820,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -26751,7 +29841,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -26783,7 +29873,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -26826,7 +29916,7 @@ var ts; } } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); @@ -26872,7 +29962,7 @@ var ts; return true; } if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { + if (funcType.flags & 65536) { return false; } return isTypeAssignableTo(funcType, globalFunctionType); @@ -26942,12 +30032,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -26979,16 +30070,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 142: + case 144: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 145: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 147: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 149: - case 150: + case 151: + case 152: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -27015,13 +30106,13 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 174: + case 179: return resolveCallExpression(node, candidatesOutArray); - case 175: + case 180: return resolveNewExpression(node, candidatesOutArray); - case 176: + case 181: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 143: + case 145: return resolveDecorator(node, candidatesOutArray); } ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); @@ -27050,17 +30141,17 @@ var ts; function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { return voidType; } - if (node.kind === 175) { + if (node.kind === 180) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 148 && - declaration.kind !== 152 && - declaration.kind !== 157 && + declaration.kind !== 150 && + declaration.kind !== 154 && + declaration.kind !== 159 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 69 ? + var funcSymbol = node.expression.kind === 70 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { @@ -27072,11 +30163,33 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, true)) { + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 8388608) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 225 + : resolvedRequire.flags & 3 + ? 223 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } function checkTaggedTemplateExpression(node) { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -27112,21 +30225,36 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } function assignBindingElementTypes(node) { @@ -27134,7 +30262,7 @@ var ts; for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 69) { + if (element.name.kind === 70) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } assignBindingElementTypes(element); @@ -27147,14 +30275,14 @@ var ts; if (!links.type) { links.type = instantiateType(contextualType, mapper); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 167 || - parameter.valueDeclaration.name.kind === 168)) { + (parameter.valueDeclaration.name.kind === 172 || + parameter.valueDeclaration.name.kind === 173)) { links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); } assignBindingElementTypes(parameter.valueDeclaration); } else if (isInferentialContext(mapper)) { - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } function getReturnTypeFromJSDocComment(func) { @@ -27175,7 +30303,7 @@ var ts; 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); + error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } return promiseType; @@ -27187,7 +30315,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 199) { + if (func.body.kind !== 204) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -27223,7 +30351,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -27249,7 +30379,7 @@ var ts; if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(node.expression); + var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -27257,14 +30387,14 @@ var ts; if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + if (lastStatement && lastStatement.kind === 218 && isExhaustiveSwitchStatement(lastStatement)) { return false; } return true; @@ -27293,7 +30423,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 179 || func.kind === 180)) { + func.kind === 184 || func.kind === 185)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -27310,7 +30440,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; @@ -27337,9 +30467,9 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 179) { + if (!hasGrammarError && node.kind === 184) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -27373,14 +30503,14 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 149) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); if (!node.asteriskToken) { @@ -27390,7 +30520,7 @@ var ts; if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 199) { + if (node.body.kind === 204) { checkSourceElement(node.body); } else { @@ -27425,10 +30555,10 @@ var ts; function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 172 || expr.kind === 173) && - expr.expression.kind === 97) { + (expr.kind === 177 || expr.kind === 178) && + expr.expression.kind === 98) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 148)) + if (!(func && func.kind === 150)) return true; return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } @@ -27437,44 +30567,24 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 172 || expr.kind === 173) { - var node = skipParenthesizedNodes(expr.expression); - if (node.kind === 69) { + if (expr.kind === 177 || expr.kind === 178) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 70) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 8388608) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 232; + return declaration && declaration.kind === 237; } } } return false; } - function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { - var node = skipParenthesizedNodes(expr); - if (node.kind !== 69 && node.kind !== 172 && node.kind !== 173) { + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipParentheses(expr); + if (node.kind !== 70 && node.kind !== 177 && node.kind !== 178) { error(expr, invalidReferenceMessage); return false; } - var links = getNodeLinks(node); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - if (node.kind === 69 && !(symbol.flags & 3)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === 173) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } function checkDeleteExpression(node) { @@ -27491,7 +30601,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 262144)) { + if (!(node.flags & 16384)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -27506,27 +30616,27 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 36 && node.operand.kind === 8) { + if (node.operator === 37 && node.operand.kind === 8) { return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); } switch (node.operator) { - case 35: case 36: - case 50: + case 37: + case 51: if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 49: + case 50: var facts = getTypeFacts(operandType) & (1048576 | 2097152); return facts === 1048576 ? falseType : facts === 2097152 ? trueType : booleanType; - case 41: case 42: + case 43: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -27539,7 +30649,7 @@ var ts; } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -27547,10 +30657,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -27562,20 +30672,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { - var t = types_16[_a]; + for (var _a = 0, types_17 = types; _a < types_17.length; _a++) { + var t = types_17[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -27584,7 +30694,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -27605,39 +30715,39 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var p = properties_4[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { - if (property.kind === 253 || property.kind === 254) { - var name_17 = property.name; - if (name_17.kind === 140) { - checkComputedPropertyName(name_17); + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 257 || property.kind === 258) { + var name_20 = property.name; + if (name_20.kind === 142) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_17)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_17); + var text = ts.getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || getIndexTypeOfType(objectLiteralType, 0); if (type) { - if (property.kind === 254) { + if (property.kind === 258) { return checkDestructuringAssignment(property, type); } else { @@ -27645,9 +30755,22 @@ var ts; } } else { - error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } + else if (property.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, ts.Diagnostics.Property_assignment_expected); } @@ -27663,8 +30786,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 193) { - if (element.kind !== 191) { + if (element.kind !== 198) { + if (element.kind !== 196) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -27686,11 +30809,11 @@ var ts; } else { if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { var restExpression = element.expression; - if (restExpression.kind === 187 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 192 && restExpression.operatorToken.kind === 57) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -27703,7 +30826,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 254) { + if (exprOrAssignment.kind === 258) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && @@ -27717,21 +30840,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 187 && target.operatorToken.kind === 56) { + if (target.kind === 192 && target.operatorToken.kind === 57) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 171) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + if (target.kind === 176) { + return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 170) { + if (target.kind === 175) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + var error = target.parent.kind === 259 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); } return sourceType; @@ -27739,49 +30865,49 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 69: + case 70: case 9: - case 10: - case 176: - case 189: case 11: + case 181: + case 194: + case 12: case 8: - case 99: - case 84: - case 93: - case 135: - case 179: - case 192: - case 180: - case 170: - case 171: - case 182: - case 196: - case 242: - case 241: + case 100: + case 85: + case 94: + case 137: + case 184: + case 197: + case 185: + case 175: + case 176: + case 187: + case 201: + case 247: + case 246: return true; - case 188: + case 193: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 187: + case 192: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 185: - case 186: + case 190: + case 191: switch (node.operator) { - case 49: - case 35: - case 36: case 50: + case 36: + case 37: + case 51: return true; } return false; - case 183: - case 177: - case 195: + case 188: + case 182: + case 200: default: return false; } @@ -27801,34 +30927,34 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 171 || left.kind === 170)) { + if (operator === 57 && (left.kind === 176 || left.kind === 175)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); var rightType = checkExpression(right, contextualMapper); switch (operator) { - case 37: case 38: - case 59: - case 60: case 39: + case 60: case 61: case 40: case 62: - case 36: - case 58: - case 43: + case 41: case 63: + case 37: + case 59: case 44: case 64: case 45: case 65: - case 47: - case 67: - case 48: - case 68: case 46: case 66: + case 48: + case 68: + case 49: + case 69: + case 47: + case 67: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -27852,8 +30978,8 @@ var ts; } } return numberType; - case 35: - case 57: + case 36: + case 58: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -27868,7 +30994,7 @@ var ts; resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -27882,24 +31008,26 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 57) { + if (operator === 58) { checkAssignmentOperator(resultType); } return resultType; - case 25: - case 27: + case 26: case 28: case 29: + case 30: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } } return booleanType; - case 30: case 31: case 32: case 33: + case 34: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -27910,22 +31038,22 @@ var ts; reportOperatorError(); } return booleanType; - case 91: + case 92: return checkInstanceOfExpression(left, right, leftType, rightType); - case 90: + case 91: return checkInExpression(left, right, leftType, rightType); - case 51: + case 52: return getTypeFacts(leftType) & 1048576 ? includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; - case 52: + case 53: return getTypeFacts(leftType) & 2097152 ? getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : leftType; - case 56: + case 57: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 24: + case 25: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -27943,23 +31071,22 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { + case 48: + case 68: + return 53; + case 49: + case 69: + return 34; case 47: case 67: return 52; - case 48: - case 68: - return 33; - case 46: - case 66: - return 51; default: return undefined; } } function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 56 && operator <= 68) { - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - if (ok) { + if (produceDiagnostics && operator >= 57 && operator <= 69) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { checkTypeAssignableTo(valueType, leftType, left, undefined); } } @@ -27985,7 +31112,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -28029,9 +31156,9 @@ var ts; return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); case 8: return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); - case 99: + case 100: return trueType; - case 84: + case 85: return falseType; } } @@ -28059,25 +31186,25 @@ var ts; return links.resolvedType; } function isTypeAssertion(node) { - node = skipParenthesizedNodes(node); - return node.kind === 177 || node.kind === 195; + node = ts.skipParentheses(node); + return node.kind === 182 || node.kind === 200; } function checkDeclarationInitializer(declaration) { var type = checkExpressionCached(declaration.initializer); return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, 480); + return maybeTypeOfKind(contextualType, (480 | 262144)); } return false; } @@ -28086,14 +31213,14 @@ var ts; return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -28114,9 +31241,19 @@ var ts; } return type; } + function getTypeOfExpression(node) { + if (node.kind === 179 && node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return checkExpression(node); + } function checkExpression(node, contextualMapper) { var type; - if (node.kind === 139) { + if (node.kind === 141) { type = checkQualifiedName(node); } else { @@ -28124,9 +31261,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 172 && node.parent.expression === node) || - (node.parent.kind === 173 && node.parent.expression === node) || - ((node.kind === 69 || node.kind === 139) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 177 && node.parent.expression === node) || + (node.parent.kind === 178 && node.parent.expression === node) || + ((node.kind === 70 || node.kind === 141) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -28135,79 +31272,79 @@ var ts; } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { - case 69: + case 70: return checkIdentifier(node); - case 97: + case 98: return checkThisExpression(node); - case 95: + case 96: return checkSuperExpression(node); - case 93: + case 94: return nullWideningType; case 9: case 8: - case 99: - case 84: + case 100: + case 85: return checkLiteralExpression(node); - case 189: + case 194: return checkTemplateExpression(node); - case 11: + case 12: return stringType; - case 10: + case 11: return globalRegExpType; - case 170: - return checkArrayLiteral(node, contextualMapper); - case 171: - return checkObjectLiteral(node, contextualMapper); - case 172: - return checkPropertyAccessExpression(node); - case 173: - return checkIndexedAccess(node); - case 174: case 175: - return checkCallExpression(node); + return checkArrayLiteral(node, contextualMapper); case 176: - return checkTaggedTemplateExpression(node); + return checkObjectLiteral(node, contextualMapper); + case 177: + return checkPropertyAccessExpression(node); case 178: - return checkExpression(node.expression, contextualMapper); - case 192: - return checkClassExpression(node); + return checkIndexedAccess(node); case 179: case 180: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 182: - return checkTypeOfExpression(node); - case 177: - case 195: - return checkAssertion(node); - case 196: - return checkNonNullAssertion(node); + return checkCallExpression(node); case 181: - return checkDeleteExpression(node); + return checkTaggedTemplateExpression(node); case 183: - return checkVoidExpression(node); + return checkExpression(node.expression, contextualMapper); + case 197: + return checkClassExpression(node); case 184: - return checkAwaitExpression(node); case 185: - return checkPrefixUnaryExpression(node); - case 186: - return checkPostfixUnaryExpression(node); + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 187: - return checkBinaryExpression(node, contextualMapper); + return checkTypeOfExpression(node); + case 182: + case 200: + return checkAssertion(node); + case 201: + return checkNonNullAssertion(node); + case 186: + return checkDeleteExpression(node); case 188: - return checkConditionalExpression(node, contextualMapper); - case 191: - return checkSpreadElementExpression(node, contextualMapper); - case 193: - return undefinedWideningType; + return checkVoidExpression(node); + case 189: + return checkAwaitExpression(node); case 190: + return checkPrefixUnaryExpression(node); + case 191: + return checkPostfixUnaryExpression(node); + case 192: + return checkBinaryExpression(node, contextualMapper); + case 193: + return checkConditionalExpression(node, contextualMapper); + case 196: + return checkSpreadExpression(node, contextualMapper); + case 198: + return undefinedWideningType; + case 195: return checkYieldExpression(node); - case 248: + case 252: return checkJsxExpression(node); - case 241: + case 246: return checkJsxElement(node); - case 242: + case 247: return checkJsxSelfClosingElement(node); - case 243: + case 248: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -28228,7 +31365,7 @@ var ts; var func = ts.getContainingFunction(node); if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); - if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 150 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -28239,7 +31376,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); } - if (func.kind === 148 || func.kind === 152 || func.kind === 157) { + if (func.kind === 150 || func.kind === 154 || func.kind === 159) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -28251,15 +31388,15 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 147 || - node.kind === 220 || - node.kind === 179; + return node.kind === 149 || + node.kind === 225 || + node.kind === 184; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 69 && + if (param.name.kind === 70 && param.name.text === parameter.text) { return i; } @@ -28294,9 +31431,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_18 = _a[_i].name; - if (ts.isBindingPattern(name_18) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -28309,16 +31446,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 180: - case 151: - case 220: - case 179: - case 156: - case 147: - case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + case 185: + case 153: + case 225: + case 184: + case 158: + case 149: + case 148: + var parent_9 = node.parent; + if (node === parent_9.type) { + return parent_9; } } } @@ -28328,29 +31465,35 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_19 = element.name; - if (name_19.kind === 69 && - name_19.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 70 && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_19.kind === 168 || - name_19.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 173 || + name_22.kind === 172) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } } } function checkSignatureDeclaration(node) { - if (node.kind === 153) { + if (node.kind === 155) { checkGrammarIndexSignature(node); } - else if (node.kind === 156 || node.kind === 220 || node.kind === 157 || - node.kind === 151 || node.kind === 148 || - node.kind === 152) { + else if (node.kind === 158 || node.kind === 225 || node.kind === 159 || + node.kind === 153 || node.kind === 150 || + node.kind === 154) { checkGrammarFunctionLikeDeclaration(node); } + if (ts.isAsyncFunctionLike(node) && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { @@ -28360,10 +31503,10 @@ var ts; checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 152: + case 154: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 151: + case 153: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -28394,7 +31537,7 @@ var ts; var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { @@ -28403,18 +31546,18 @@ var ts; } } else { - var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114; }); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 149: + case 151: addName(names, member.name, memberName, 1); break; - case 150: + case 152: addName(names, member.name, memberName, 2); break; - case 145: + case 147: addName(names, member.name, memberName, 3); break; } @@ -28440,12 +31583,12 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind == 144) { + if (member.kind == 146) { var memberName = void 0; switch (member.name.kind) { case 9: case 8: - case 69: + case 70: memberName = member.name.text; break; default: @@ -28462,7 +31605,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 222) { + if (node.kind === 227) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -28477,7 +31620,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 132: + case 134: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -28485,7 +31628,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 130: + case 132: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -28529,7 +31672,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -28541,20 +31684,21 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function markThisReferencesAsErrors(n) { - if (n.kind === 97) { + if (n.kind === 98) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 179 && n.kind !== 220) { + else if (n.kind !== 184 && n.kind !== 225) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 145 && + return n.kind === 147 && !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -28566,9 +31710,9 @@ var ts; if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -28591,18 +31735,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 149) { + if (node.kind === 151) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 149 ? 150 : 149; + var otherKind = node.kind === 151 ? 152 : 151; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { @@ -28616,11 +31760,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { + if (node.kind === 151) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - if (node.parent.kind !== 171) { + if (node.parent.kind !== 176) { checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); } @@ -28650,7 +31794,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -28701,14 +31845,25 @@ var ts; function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node) { + getTypeFromIndexedAccessTypeNode(node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } function isPrivateWithinAmbient(node) { return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 222 && - n.parent.kind !== 221 && - n.parent.kind !== 192 && + if (n.parent.kind !== 227 && + n.parent.kind !== 226 && + n.parent.kind !== 197 && ts.isInAmbientContext(n)) { if (!(flags & 2)) { flags |= 1; @@ -28785,7 +31940,7 @@ var ts; if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 147 || node.kind === 146) && + var reportError = (node.kind === 149 || node.kind === 148) && (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -28818,11 +31973,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 222 || node.parent.kind === 159 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 227 || node.parent.kind === 161 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 220 || node.kind === 147 || node.kind === 146 || node.kind === 148) { + if (node.kind === 225 || node.kind === 149 || node.kind === 148 || node.kind === 150) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -28933,20 +32088,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 222: + case 227: return 2097152; - case 225: + case 230: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 221: - case 224: - return 2097152 | 1048576; + case 226: case 229: - var result_2 = 0; + return 2097152 | 1048576; + case 234: + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; default: return 1048576; } @@ -28969,7 +32124,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (getObjectFlags(promise) & 4) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -28987,7 +32142,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -29006,7 +32161,7 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -29034,51 +32189,50 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - error(location, diagnostic, typeName); - return unknownType; - } function checkAsyncFunctionReturnType(node) { + var returnType = getTypeFromTypeNode(node.type); if (languageVersion >= 2) { - var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - return unknownType; + else { + markTypeNodeAsReferenced(node.type); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } } - var promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - return unknownType; - } - var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - var typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } - checkReturnTypeAnnotationAsExpression(node); - var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } - var promiseName = ts.getEntityNameFromTypeNode(node.type); - var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); - return unknownType; - } - return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } function checkDecorator(node) { var signature = getResolvedSignature(node); @@ -29090,22 +32244,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 221: + case 226: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 142: + case 144: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 145: + case 147: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 147: case 149: - case 150: + case 151: + case 152: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -29113,30 +32267,19 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } - function checkTypeNodeAsExpression(node) { - if (node && node.kind === 155) { - var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; - var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); - if (rootSymbol && rootSymbol.flags & 8388608) { - var aliasTarget = resolveAlias(rootSymbol); - if (aliasTarget.flags & 107455 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } + function markTypeNodeAsReferenced(node) { + var typeName = node && ts.getEntityNameFromTypeNode(node); + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 70 ? 793064 : 1920) | 8388608, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 8388608 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } - function checkTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkReturnTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkParameterTypeAnnotationsAsExpressions(node) { - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - checkTypeAnnotationAsExpression(parameter); - } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } function checkDecorators(node) { if (!node.decorators) { @@ -29148,23 +32291,37 @@ var ts; if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 144) { + checkExternalEmitHelpers(firstDecorator, 32); + } if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 221: + case 226: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; - case 147: case 149: - case 150: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + case 151: + case 152: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markTypeNodeAsReferenced(node.type); break; - case 145: - case 142: - checkTypeAnnotationAsExpression(node); + case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + case 144: + markTypeNodeAsReferenced(node.type); break; } } @@ -29183,7 +32340,7 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (node.name && node.name.kind === 140) { + if (node.name && node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { @@ -29225,43 +32382,43 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 256: - case 225: + case 261: + case 230: checkUnusedModuleMembers(node); break; - case 221: - case 192: + case 226: + case 197: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 222: + case 227: checkUnusedTypeParameters(node); break; - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: checkUnusedLocalsAndParameters(node); break; - case 148: - case 179: - case 220: - case 180: - case 147: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 151: + case 152: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 146: - case 151: - case 152: + case 148: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: checkUnusedTypeParameters(node); break; } @@ -29270,46 +32427,66 @@ var ts; } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { + if (node.parent.kind !== 227 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + var _loop_2 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144) { + var parameter = ts.getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !ts.parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); } } }; for (var key in node.locals) { - _loop_1(key); + _loop_2(key); } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; } - function parameterNameStartsWithUnderscore(parameter) { - return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 223 && + (declaration.parent.parent.kind === 212 || + declaration.parent.parent.kind === 213)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 70 && node.text.charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 147 || member.kind === 145) { + if (member.kind === 149 || member.kind === 147) { if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } - else if (member.kind === 148) { + else if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { @@ -29354,7 +32531,7 @@ var ts; } } function checkBlock(node) { - if (node.kind === 199) { + if (node.kind === 204) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -29376,19 +32553,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 145 || - node.kind === 144 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 146 || node.kind === 149 || - node.kind === 150) { + node.kind === 148 || + node.kind === 151 || + node.kind === 152) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 142 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 144 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -29402,7 +32579,7 @@ var ts; var current = node; while (current) { if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 69; + var isDeclaration_1 = node.kind !== 70; if (isDeclaration_1) { error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -29423,7 +32600,7 @@ var ts; return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_2 = node.kind !== 69; + var isDeclaration_2 = node.kind !== 70; if (isDeclaration_2) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -29433,26 +32610,29 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -29460,7 +32640,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 218 && !node.initializer) { + if (node.kind === 223 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -29470,25 +32650,25 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); - var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224); + var container = varDeclList.parent.kind === 205 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 199 && ts.isFunctionLike(container.parent) || - container.kind === 226 || - container.kind === 225 || - container.kind === 256); + (container.kind === 204 && ts.isFunctionLike(container.parent) || + container.kind === 231 || + container.kind === 230 || + container.kind === 261); if (!namesShareScope) { - var name_20 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 142) { + if (ts.getRootDeclaration(node).kind !== 144) { return; } var func = ts.getContainingFunction(node); @@ -29497,10 +32677,10 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 172) { + if (n.kind === 177) { return visit(n.expression); } - else if (n.kind === 69) { + else if (n.kind === 70) { var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; @@ -29511,7 +32691,7 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 142) { + if (symbol.valueDeclaration.kind === 144) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -29520,7 +32700,7 @@ var ts; if (ts.isFunctionLike(current.parent)) { return; } - if (current.parent.kind === 145 && + if (current.parent.kind === 147 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; @@ -29536,51 +32716,58 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 169) { - if (node.propertyName && node.propertyName.kind === 140) { + if (node.kind === 174) { + if (node.parent.kind === 172 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 142) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_21 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_10 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_10); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_24)); + markPropertyAsReferenced(property); + if (parent_10.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 142 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 144 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -29592,9 +32779,9 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 145 && node.kind !== 144) { + if (node.kind !== 147 && node.kind !== 146) { checkExportsOnMergedDeclarations(node); - if (node.kind === 218 || node.kind === 169) { + if (node.kind === 223 || node.kind === 174) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -29604,8 +32791,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 142 && right.kind === 218) || - (left.kind === 218 && right.kind === 142)) { + if ((left.kind === 144 && right.kind === 223) || + (left.kind === 223 && right.kind === 144)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -29632,7 +32819,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 171) { + if (node.modifiers && node.parent.kind === 176) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -29651,7 +32838,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 201) { + if (node.thenStatement.kind === 206) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -29668,12 +32855,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 219) { + if (node.initializer && node.initializer.kind === 224) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -29691,18 +32878,18 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -29715,7 +32902,8 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 224) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -29725,18 +32913,17 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -29789,7 +32976,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -29815,7 +33002,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -29850,7 +33037,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -29859,10 +33046,14 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 65536) { + var arrayTypes = arrayOrStringType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 262178) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -29887,7 +33078,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 262178) { return stringType; } return getUnionType([arrayElementType, stringType], true); @@ -29898,7 +33089,7 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 150))); + return !!(node.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; @@ -29920,12 +33111,12 @@ var ts; if (func.asteriskToken) { return; } - if (func.kind === 150) { + if (func.kind === 152) { if (node.expression) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 148) { + else if (func.kind === 150) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -29943,27 +33134,33 @@ var ts; } } } - else if (func.kind !== 148 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 150 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 262144) { + if (node.flags & 16384) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 250 && !hasDuplicateDefaultClause) { + if (clause.kind === 254 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -29975,11 +33172,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 249) { + if (produceDiagnostics && clause.kind === 253) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { - checkTypeComparableTo(caseType, expressionType, caseClause.expression, undefined); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -29995,7 +33198,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 214 && current.label.text === node.label.text) { + if (current.kind === 219 && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -30021,22 +33224,20 @@ var ts; var catchClause = node.catchClause; if (catchClause) { if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== 69) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = catchClause.variableDeclaration.name.text; - var locals = catchClause.block.locals; - if (locals) { - var localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & 2) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + var blockLocals = catchClause.block.locals; + if (blockLocals) { + for (var caughtName in catchClause.locals) { + var blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -30058,7 +33259,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -30073,7 +33274,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -30089,13 +33290,13 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 140 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 142 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -30140,7 +33341,7 @@ var ts; var firstDecl; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 || declaration.kind === 222) { + if (declaration.kind === 226 || declaration.kind === 227) { if (!firstDecl) { firstDecl = declaration; } @@ -30186,6 +33387,9 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType_1 = baseTypes[0]; @@ -30203,7 +33407,9 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (baseType_1.symbol.valueDeclaration && + !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) && + baseType_1.symbol.valueDeclaration.kind === 226) { if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -30228,8 +33434,8 @@ var ts; if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = getObjectFlags(t) & 4 ? t.target : t; + if (getObjectFlags(declaredType) & 3) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -30251,7 +33457,7 @@ var ts; if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -30277,7 +33483,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 192) { + if (derivedClassDecl.kind === 197) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -30321,7 +33527,7 @@ var ts; } } function isAccessor(kind) { - return kind === 149 || kind === 150; + return kind === 151 || kind === 152; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -30359,8 +33565,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var prop = properties_5[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen[prop.name]; if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; @@ -30388,7 +33594,7 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(node, symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 222); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -30417,6 +33623,7 @@ var ts; function checkTypeAliasDeclaration(node) { checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } function computeEnumMemberValues(node) { @@ -30433,7 +33640,7 @@ var ts; error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - var text = getTextOfPropertyName(member.name); + var text = ts.getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -30483,18 +33690,18 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 185: + case 190: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; } switch (e.operator) { - case 35: return value_1; - case 36: return -value_1; - case 50: return ~value_1; + case 36: return value_1; + case 37: return -value_1; + case 51: return ~value_1; } return undefined; - case 187: + case 192: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -30504,37 +33711,37 @@ var ts; return undefined; } switch (e.operatorToken.kind) { - case 47: return left | right; - case 46: return left & right; - case 44: return left >> right; - case 45: return left >>> right; - case 43: return left << right; - case 48: return left ^ right; - case 37: return left * right; - case 39: return left / right; - case 35: return left + right; - case 36: return left - right; - case 40: return left % right; + case 48: return left | right; + case 47: return left & right; + case 45: return left >> right; + case 46: return left >>> right; + case 44: return left << right; + case 49: return left ^ right; + case 38: return left * right; + case 40: return left / right; + case 36: return left + right; + case 37: return left - right; + case 41: return left % right; } return undefined; case 8: return +e.text; - case 178: + case 183: return evalConstant(e.expression); - case 69: - case 173: - case 172: + case 70: + case 178: + case 177: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; var propertyName = void 0; - if (e.kind === 69) { + if (e.kind === 70) { enumType_1 = currentType; propertyName = e.text; } else { var expression = void 0; - if (e.kind === 173) { + if (e.kind === 178) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -30548,17 +33755,17 @@ var ts; } var current = expression; while (current) { - if (current.kind === 69) { + if (current.kind === 70) { break; } - else if (current.kind === 172) { + else if (current.kind === 177) { current = current.expression; } else { return undefined; } } - enumType_1 = checkExpression(expression); + enumType_1 = getTypeOfExpression(expression); if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { return undefined; } @@ -30611,7 +33818,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 224) { + if (declaration.kind !== 229) { return false; } var enumDeclaration = declaration; @@ -30634,8 +33841,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 221 || - (declaration.kind === 220 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 226 || + (declaration.kind === 225 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -30674,9 +33881,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -30692,7 +33901,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 221); + var mergedClass = ts.getDeclarationOfKind(symbol, 226); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -30735,36 +33944,36 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 200: + case 205: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 235: - case 236: + case 240: + case 241: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 229: - case 230: + case 234: + case 235: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 169: - case 218: - var name_22 = node.name; - if (ts.isBindingPattern(name_22)) { - for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { + case 174: + case 223: + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } - case 221: - case 224: - case 220: - case 222: + case 226: + case 229: case 225: - case 223: + case 227: + case 230: + case 228: if (isGlobalAugmentation) { return; } @@ -30780,17 +33989,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 69: + case 70: return node; - case 139: + case 141: do { node = node.left; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; - case 172: + case 177: do { node = node.expression; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; } } @@ -30800,9 +34009,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { - error(moduleName, node.kind === 236 ? + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { + error(moduleName, node.kind === 241 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -30823,7 +34032,7 @@ var ts; (symbol.flags & 793064 ? 793064 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 238 ? + var message = node.kind === 243 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -30850,7 +34059,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { + if (importClause.namedBindings.kind === 237) { checkImportBinding(importClause.namedBindings); } else { @@ -30885,7 +34094,7 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { grammarErrorOnNode(node, ts.Diagnostics.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); } } @@ -30901,8 +34110,8 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -30915,9 +34124,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 261 || node.parent.kind === 231 || node.parent.kind === 230; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -30936,15 +34147,15 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 256 ? node.parent : node.parent.parent; - if (container.kind === 225 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 261 ? node.parent : node.parent.parent; + if (container.kind === 230 && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { markExportAsReferenced(node); } else { @@ -30952,7 +34163,7 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES6) { + if (modulekind === ts.ModuleKind.ES2015) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { @@ -31004,7 +34215,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 225 && declaration.kind !== 149) || + !!declaration.body; } } function checkSourceElement(node) { @@ -31014,118 +34226,123 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { + case 230: + case 226: + case 227: case 225: - case 221: - case 222: - case 220: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 141: + case 143: return checkTypeParameter(node); - case 142: - return checkParameter(node); - case 145: case 144: - return checkPropertyDeclaration(node); - case 156: - case 157: - case 151: - case 152: - return checkSignatureDeclaration(node); - case 153: - return checkSignatureDeclaration(node); + return checkParameter(node); case 147: case 146: - return checkMethodDeclaration(node); - case 148: - return checkConstructorDeclaration(node); - case 149: - case 150: - return checkAccessorDeclaration(node); - case 155: - return checkTypeReferenceNode(node); - case 154: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 158: - return checkTypeQuery(node); case 159: - return checkTypeLiteral(node); + case 153: + case 154: + return checkSignatureDeclaration(node); + case 155: + return checkSignatureDeclaration(node); + case 149: + case 148: + return checkMethodDeclaration(node); + case 150: + return checkConstructorDeclaration(node); + case 151: + case 152: + return checkAccessorDeclaration(node); + case 157: + return checkTypeReferenceNode(node); + case 156: + return checkTypePredicate(node); case 160: - return checkArrayType(node); + return checkTypeQuery(node); case 161: - return checkTupleType(node); + return checkTypeLiteral(node); case 162: + return checkArrayType(node); case 163: - return checkUnionOrIntersectionType(node); + return checkTupleType(node); case 164: + case 165: + return checkUnionOrIntersectionType(node); + case 166: + case 168: return checkSourceElement(node.type); - case 220: - return checkFunctionDeclaration(node); - case 199: - case 226: - return checkBlock(node); - case 200: - return checkVariableStatement(node); - case 202: - return checkExpressionStatement(node); - case 203: - return checkIfStatement(node); - case 204: - return checkDoStatement(node); - case 205: - return checkWhileStatement(node); - case 206: - return checkForStatement(node); - case 207: - return checkForInStatement(node); - case 208: - return checkForOfStatement(node); - case 209: - case 210: - return checkBreakOrContinueStatement(node); - case 211: - return checkReturnStatement(node); - case 212: - return checkWithStatement(node); - case 213: - return checkSwitchStatement(node); - case 214: - return checkLabeledStatement(node); - case 215: - return checkThrowStatement(node); - case 216: - return checkTryStatement(node); - case 218: - return checkVariableDeclaration(node); case 169: - return checkBindingElement(node); - case 221: - return checkClassDeclaration(node); - case 222: - return checkInterfaceDeclaration(node); - case 223: - return checkTypeAliasDeclaration(node); - case 224: - return checkEnumDeclaration(node); + return checkIndexedAccessType(node); + case 170: + return checkMappedType(node); case 225: - return checkModuleDeclaration(node); - case 230: - return checkImportDeclaration(node); - case 229: - return checkImportEqualsDeclaration(node); - case 236: - return checkExportDeclaration(node); - case 235: - return checkExportAssignment(node); - case 201: - checkGrammarStatementInAmbientContext(node); - return; + return checkFunctionDeclaration(node); + case 204: + case 231: + return checkBlock(node); + case 205: + return checkVariableStatement(node); + case 207: + return checkExpressionStatement(node); + case 208: + return checkIfStatement(node); + case 209: + return checkDoStatement(node); + case 210: + return checkWhileStatement(node); + case 211: + return checkForStatement(node); + case 212: + return checkForInStatement(node); + case 213: + return checkForOfStatement(node); + case 214: + case 215: + return checkBreakOrContinueStatement(node); + case 216: + return checkReturnStatement(node); case 217: + return checkWithStatement(node); + case 218: + return checkSwitchStatement(node); + case 219: + return checkLabeledStatement(node); + case 220: + return checkThrowStatement(node); + case 221: + return checkTryStatement(node); + case 223: + return checkVariableDeclaration(node); + case 174: + return checkBindingElement(node); + case 226: + return checkClassDeclaration(node); + case 227: + return checkInterfaceDeclaration(node); + case 228: + return checkTypeAliasDeclaration(node); + case 229: + return checkEnumDeclaration(node); + case 230: + return checkModuleDeclaration(node); + case 235: + return checkImportDeclaration(node); + case 234: + return checkImportEqualsDeclaration(node); + case 241: + return checkExportDeclaration(node); + case 240: + return checkExportAssignment(node); + case 206: checkGrammarStatementInAmbientContext(node); return; - case 239: + case 222: + checkGrammarStatementInAmbientContext(node); + return; + case 244: return checkMissingDeclaration(node); } } @@ -31138,17 +34355,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 179: - case 180: - case 147: - case 146: + case 184: + case 185: + case 149: + case 148: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 149: - case 150: + case 151: + case 152: checkAccessorDeferred(node); break; - case 192: + case 197: checkClassExpressionDeferred(node); break; } @@ -31202,8 +34419,19 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; } ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); @@ -31220,7 +34448,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 212 && node.parent.statement === node) { + if (node.parent.kind === 217 && node.parent.statement === node) { return true; } node = node.parent; @@ -31242,28 +34470,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 225: + case 230: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 224: + case 229: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 192: + case 197: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 221: - case 222: + case 226: + case 227: if (!(memberFlags & 32)) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; - case 179: + case 184: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -31296,33 +34524,33 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 69 && + return name.kind === 70 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 141: - case 221: - case 222: - case 223: - case 224: + case 143: + case 226: + case 227: + case 228: + case 229: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 139) { + while (node.parent && node.parent.kind === 141) { node = node.parent; } - return node.parent && (node.parent.kind === 155 || node.parent.kind === 267); + return node.parent && (node.parent.kind === 157 || node.parent.kind === 272); } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 172) { + while (node.parent && node.parent.kind === 177) { node = node.parent; } - return node.parent && node.parent.kind === 194; + return node.parent && node.parent.kind === 199; } function forEachEnclosingClass(node, callback) { var result; @@ -31339,13 +34567,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 139) { + while (nodeOnRightSide.parent.kind === 141) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 229) { + if (nodeOnRightSide.parent.kind === 234) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 235) { + if (nodeOnRightSide.parent.kind === 240) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -31357,7 +34585,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 172) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: @@ -31369,20 +34597,20 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 240 && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); + if (entityName.kind !== 177 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 234); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 194) { + if (entityName.parent.kind === 199) { meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -31398,20 +34626,20 @@ var ts; if (ts.nodeIsMissing(entityName)) { return undefined; } - if (entityName.kind === 69) { + if (entityName.kind === 70) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } return resolveEntityName(entityName, 107455, false, true); } - else if (entityName.kind === 172) { + else if (entityName.kind === 177) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 139) { + else if (entityName.kind === 141) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -31420,19 +34648,19 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 157 || entityName.parent.kind === 272) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 246) { + else if (entityName.parent.kind === 250) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 154) { + if (entityName.parent.kind === 156) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 256) { + if (node.kind === 261) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } if (isInsideWithStatementBody(node)) { @@ -31444,12 +34672,12 @@ var ts; else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 69) { + if (node.kind === 70) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 169 && - node.parent.parent.kind === 167 && + else if (node.parent.kind === 174 && + node.parent.parent.kind === 172 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -31459,11 +34687,11 @@ var ts; } } switch (node.kind) { - case 69: - case 172: - case 139: + case 70: + case 177: + case 141: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 97: + case 98: var container = ts.getThisContainer(node, false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -31471,27 +34699,30 @@ var ts; return sig.thisParameter; } } - case 95: - var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + case 96: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; - case 165: + case 167: return getTypeFromTypeNode(node).symbol; - case 121: + case 122: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 148) { + if (constructorDeclaration && constructorDeclaration.kind === 150) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 230 || node.parent.kind === 236) && + ((node.parent.kind === 235 || node.parent.kind === 241) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: - if (node.parent.kind === 173 && node.parent.argumentExpression === node) { - var objectType = checkExpression(node.parent.expression); + if (node.parent.kind === 178 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); if (objectType === unknownType) return undefined; var apparentType = getApparentType(objectType); @@ -31504,7 +34735,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 254) { + if (location && location.kind === 258) { return resolveEntityName(location.name, 107455 | 8388608); } return undefined; @@ -31522,7 +34753,7 @@ var ts; return getTypeFromTypeNode(node); } if (ts.isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; @@ -31554,20 +34785,20 @@ var ts; return unknownType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 171 || expr.kind === 170); - if (expr.parent.kind === 208) { + ts.Debug.assert(expr.kind === 176 || expr.kind === 175); + if (expr.parent.kind === 213) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 187) { - var iteratedType = checkExpression(expr.parent.right); + if (expr.parent.kind === 192) { + var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 253) { + if (expr.parent.kind === 257) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 170); + ts.Debug.assert(expr.parent.kind === 175); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); @@ -31576,11 +34807,11 @@ var ts; var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr) { + function getRegularTypeOfExpression(expr) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); @@ -31603,9 +34834,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_23 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_23); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -31613,6 +34844,10 @@ var ts; return symbols_3; } else if (symbol.flags & 67108864) { + if (symbol.leftSpread) { + var links = symbol; + return [links.leftSpread, links.rightSpread]; + } var target = void 0; var next = symbol; while (next = getSymbolLinks(next).target) { @@ -31654,7 +34889,7 @@ var ts; } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; - return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } function getReferencedExportContainer(node, prefixLocals) { node = ts.getParseTreeNode(node, ts.isIdentifier); @@ -31670,7 +34905,7 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 261) { var symbolFile = parentSymbol.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -31708,7 +34943,7 @@ var ts; else if (nodeLinks_1.flags & 131072) { var isDeclaredInLoop = nodeLinks_1.flags & 262144; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 199 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 204 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -31748,18 +34983,18 @@ var ts; return true; } switch (node.kind) { - case 229: - case 231: - case 232: case 234: - case 238: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: + case 237: + case 239: + case 243: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 241: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 235: + case 240: return node.expression - && node.expression.kind === 69 + && node.expression.kind === 70 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -31767,7 +35002,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 261 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -31818,7 +35053,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 255) { + if (node.kind === 260) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -31830,7 +35065,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); @@ -31862,7 +35097,7 @@ var ts; else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { @@ -31893,7 +35128,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getTypeOfExpression(expr)); + var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { @@ -31912,9 +35147,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_11 = reference.parent; + if (ts.isDeclaration(parent_11) && reference === parent_11.name) { + location = getDeclarationContainer(parent_11); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -31934,7 +35169,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 16777216); + return !!(type.flags & 96 && type.flags & 1048576); } return false; } @@ -31985,13 +35220,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) + var meaning = (node.kind === 177) || (node.kind === 70 && isInTypeQuery(node)) ? 107455 | 1048576 : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); @@ -32013,6 +35249,9 @@ var ts; if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + return undefined; + } } } return typeReferenceDirectives; @@ -32023,15 +35262,15 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_12 = getParentOfSymbol(current); + if (parent_12) { + current = parent_12; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 256 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 261 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -32050,7 +35289,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 256); + return ts.getDeclarationOfKind(moduleSymbol, 261); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -32058,8 +35297,6 @@ var ts; ts.bindSourceFile(file, compilerOptions); } var augmentations; - var requestedExternalEmitHelpers = 0; - var firstFileRequestingExternalHelpers; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { @@ -32079,15 +35316,6 @@ var ts; } } } - if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { - var fileRequestedExternalEmitHelpers = file.flags & 31744; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { @@ -32138,43 +35366,50 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); - if (helpersModule) { - var exports = helpersModule.exports; - if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { - verifyHelperSymbol(exports, "__extends", 107455); - } - if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { - verifyHelperSymbol(exports, "__assign", 107455); - } - if (requestedExternalEmitHelpers & 2048) { - verifyHelperSymbol(exports, "__decorate", 107455); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455); - } - } - if (requestedExternalEmitHelpers & 4096) { - verifyHelperSymbol(exports, "__param", 107455); - } - if (requestedExternalEmitHelpers & 8192) { - verifyHelperSymbol(exports, "__awaiter", 107455); - if (languageVersion < 2) { - verifyHelperSymbol(exports, "__generator", 107455); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 128; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name_27 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name_27), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_27); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols, name, meaning) { - var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); - if (!symbol) { - error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; } } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -32185,7 +35420,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -32197,14 +35432,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 147 && !ts.nodeIsPresent(node.body)) { + if (node.kind === 149 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 149 || node.kind === 150) { + else if (node.kind === 151 || node.kind === 152) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -32221,28 +35456,28 @@ var ts; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 128) { - if (node.kind === 144 || node.kind === 146) { + if (modifier.kind !== 130) { + if (node.kind === 146 || node.kind === 148) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 153) { + if (node.kind === 155) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 74: - if (node.kind !== 224 && node.parent.kind === 221) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + case 75: + if (node.kind !== 229 && node.parent.kind === 226) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75)); } break; + case 113: case 112: case 111: - case 110: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 111) { + if (modifier.kind === 112) { lastProtected = modifier; } - else if (modifier.kind === 110) { + else if (modifier.kind === 111) { lastPrivate = modifier; } if (flags & 28) { @@ -32257,11 +35492,11 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { - if (modifier.kind === 110) { + if (modifier.kind === 111) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -32270,7 +35505,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 113: + case 114: if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -32280,10 +35515,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -32292,17 +35527,17 @@ var ts; flags |= 32; lastStatic = modifier; break; - case 128: + case 130: if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 145 && node.kind !== 144 && node.kind !== 153 && node.kind !== 142) { + else if (node.kind !== 147 && node.kind !== 146 && node.kind !== 155 && node.kind !== 144) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; lastReadonly = modifier; break; - case 82: + case 83: if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -32315,45 +35550,45 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; - case 122: + case 123: if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 226) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; lastDeclare = modifier; break; - case 115: + case 116: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 221) { - if (node.kind !== 147 && - node.kind !== 145 && - node.kind !== 149 && - node.kind !== 150) { + if (node.kind !== 226) { + if (node.kind !== 149 && + node.kind !== 147 && + node.kind !== 151 && + node.kind !== 152) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 226 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -32365,14 +35600,14 @@ var ts; } flags |= 128; break; - case 118: + case 119: if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -32380,7 +35615,7 @@ var ts; break; } } - if (node.kind === 148) { + if (node.kind === 150) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -32395,13 +35630,13 @@ var ts; } return; } - else if ((node.kind === 230 || node.kind === 229) && flags & 2) { + else if ((node.kind === 235 || node.kind === 234) && flags & 2) { 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)) { + else if (node.kind === 144 && (flags & 92) && ts.isBindingPattern(node.name)) { 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) { + else if (node.kind === 144 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -32417,38 +35652,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 149: + case 151: + case 152: case 150: - case 148: - case 145: - case 144: case 147: case 146: - case 153: - case 225: + case 149: + case 148: + case 155: case 230: - case 229: - case 236: case 235: - case 179: - case 180: - case 142: + case 234: + case 241: + case 240: + case 184: + case 185: + case 144: return false; default: - if (node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 231 || node.parent.kind === 261) { return false; } switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: + case 225: + return nodeHasAnyModifiersExcept(node, 119); + case 226: + return nodeHasAnyModifiersExcept(node, 116); + case 227: + case 205: + case 228: return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); + case 229: + return nodeHasAnyModifiersExcept(node, 75); default: ts.Debug.fail(); return false; @@ -32460,10 +35695,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 147: - case 220: - case 179: - case 180: + case 149: + case 225: + case 184: + case 185: if (!node.asteriskToken) { return false; } @@ -32479,7 +35714,7 @@ var ts; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } - function checkGrammarTypeParameterList(node, typeParameters, file) { + function checkGrammarTypeParameterList(typeParameters, file) { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -32521,11 +35756,11 @@ var ts; } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 180) { + if (node.kind === 185) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -32560,7 +35795,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 132 && parameter.type.kind !== 130) { + if (parameter.type.kind !== 134 && parameter.type.kind !== 132) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -32585,9 +35820,9 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 193) { + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; + if (arg.kind === 198) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -32613,7 +35848,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -32626,7 +35861,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -32641,14 +35876,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } checkGrammarHeritageClause(heritageClause); @@ -32657,19 +35892,19 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 140) { + if (node.kind !== 142) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 187 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 192 && computedPropertyName.expression.operatorToken.kind === 25) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 220 || - node.kind === 179 || - node.kind === 147); + ts.Debug.assert(node.kind === 225 || + node.kind === 184 || + node.kind === 149); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -32681,7 +35916,7 @@ var ts; } } } - function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + function checkGrammarForInvalidQuestionMark(questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -32694,43 +35929,45 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_24 = prop.name; - if (prop.kind === 193 || - name_24.kind === 140) { - checkGrammarComputedPropertyName(name_24); + if (prop.kind === 259) { + continue; } - if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { + var name_28 = prop.name; + if (name_28.kind === 142) { + checkGrammarComputedPropertyName(name_28); + } + if (prop.kind === 258 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 118 || prop.kind !== 147) { + if (mod.kind !== 119 || prop.kind !== 149) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } 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_24.kind === 8) { - checkGrammarNumericLiteral(name_24); + if (prop.kind === 257 || prop.kind === 258) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_28.kind === 8) { + checkGrammarNumericLiteral(name_28); } currentKind = Property; } - else if (prop.kind === 147) { + else if (prop.kind === 149) { currentKind = Property; } - else if (prop.kind === 149) { + else if (prop.kind === 151) { currentKind = GetAccessor; } - else if (prop.kind === 150) { + else if (prop.kind === 152) { currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_28); if (effectiveName === undefined) { continue; } @@ -32740,18 +35977,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); + grammarErrorOnNode(name_28, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_28)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -32760,19 +35997,19 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 247) { + if (attr.kind === 251) { continue; } var jsxAttr = attr; - var name_25 = jsxAttr.name; - if (!seen[name_25.text]) { - seen[name_25.text] = true; + var name_29 = jsxAttr.name; + if (!seen[name_29.text]) { + seen[name_29.text] = true; } else { - return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_29, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 248 && !initializer.expression) { + if (initializer && initializer.kind === 252 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -32781,7 +36018,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 219) { + if (forInOrOfStatement.initializer.kind === 224) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -32789,20 +36026,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -32822,15 +36059,18 @@ var ts; else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 149 ? + return grammarErrorOnNode(accessor.name, kind === 151 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 150) { + else if (kind === 152) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -32849,20 +36089,11 @@ var ts; } } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 151 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -32876,8 +36107,8 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 171) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (node.parent.kind === 176) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -32892,10 +36123,10 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -32906,9 +36137,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 214: + case 219: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 209 + var isMisplacedContinueLabel = node.kind === 214 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -32916,8 +36147,8 @@ var ts; return false; } break; - case 213: - if (node.kind === 210 && !node.label) { + case 218: + if (node.kind === 215 && !node.label) { return false; } break; @@ -32930,13 +36161,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -32946,9 +36177,9 @@ var ts; if (node.dotDotDotToken) { var elements = node.parent.elements; if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 168 || node.name.kind === 167) { + if (node.name.kind === 173 || node.name.kind === 172) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -32958,11 +36189,11 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 || expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { + if (node.parent.parent.kind !== 212 && node.parent.parent.kind !== 213) { if (ts.isInAmbientContext(node)) { if (node.initializer) { if (ts.isConst(node) && !node.type) { @@ -32993,8 +36224,8 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 69) { - if (name.originalKeywordKind === 108) { + if (name.kind === 70) { + if (name.originalKeywordKind === 109) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -33019,15 +36250,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 203: - case 204: - case 205: - case 212: - case 206: - case 207: case 208: + case 209: + case 210: + case 217: + case 211: + case 212: + case 213: return false; - case 214: + case 219: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -33082,7 +36313,7 @@ var ts; return true; } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -33090,7 +36321,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -33103,13 +36334,13 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 222 || - node.kind === 223 || - node.kind === 230 || - node.kind === 229 || - node.kind === 236 || - node.kind === 235 || + if (node.kind === 227 || node.kind === 228 || + node.kind === 235 || + node.kind === 234 || + node.kind === 241 || + node.kind === 240 || + node.kind === 233 || ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } @@ -33118,7 +36349,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 200) { + if (ts.isDeclaration(decl) || decl.kind === 205) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -33137,7 +36368,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 199 || node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 204 || node.parent.kind === 231 || node.parent.kind === 261) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -33176,381 +36407,388 @@ var ts; (function (ts) { ; var nodeEdgeTraversalMap = ts.createMap((_a = {}, - _a[139] = [ + _a[141] = [ { name: "left", test: ts.isEntityName }, { name: "right", test: ts.isIdentifier } ], - _a[143] = [ + _a[145] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[177] = [ + _a[182] = [ { name: "type", test: ts.isTypeNode }, { name: "expression", test: ts.isUnaryExpression } ], - _a[195] = [ + _a[200] = [ { name: "expression", test: ts.isExpression }, { name: "type", test: ts.isTypeNode } ], - _a[196] = [ + _a[201] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[224] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isIdentifier }, - { name: "members", test: ts.isEnumMember } - ], - _a[225] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isModuleName }, - { name: "body", test: ts.isModuleBody } - ], - _a[226] = [ - { name: "statements", test: ts.isStatement } - ], _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[230] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[231] = [ + { name: "statements", test: ts.isStatement } + ], + _a[234] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "moduleReference", test: ts.isModuleReference } ], - _a[240] = [ + _a[245] = [ { name: "expression", test: ts.isExpression, optional: true } ], - _a[255] = [ + _a[260] = [ { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], - _a - )); + _a)); function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } - function reduceEachChild(node, f, initial) { + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return initial; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return initial; } var result = initial; switch (node.kind) { + case 203: + case 206: case 198: - case 201: - case 193: - case 217: - case 287: - break; - case 140: - result = reduceNode(node.expression, f, result); + case 222: + case 293: break; case 142: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; - case 143: - result = reduceNode(node.expression, f, result); + case 144: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 145: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 147: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 148: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 149: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 150: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; - case 167: - case 168: - result = ts.reduceLeft(node.elements, f, result); + case 151: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 169: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; - case 170: - result = ts.reduceLeft(node.elements, f, result); - break; - case 171: - result = ts.reduceLeft(node.properties, f, result); + case 152: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; case 172: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.name, f, result); - break; case 173: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.argumentExpression, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 174: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 175: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 176: - result = reduceNode(node.tag, f, result); - result = reduceNode(node.template, f, result); + result = reduceNodes(node.properties, cbNodes, result); break; - case 179: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 180: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 177: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; case 178: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 179: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 180: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; case 181: - case 182: - case 183: + result = reduceNode(node.tag, cbNode, result); + result = reduceNode(node.template, cbNode, result); + break; case 184: - case 190: - case 191: - case 196: - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 185: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 183: case 186: - result = reduceNode(node.operand, f, result); - break; case 187: - result = reduceNode(node.left, f, result); - result = reduceNode(node.right, f, result); - break; case 188: - result = reduceNode(node.condition, f, result); - result = reduceNode(node.whenTrue, f, result); - result = reduceNode(node.whenFalse, f, result); - break; case 189: - result = reduceNode(node.head, f, result); - result = ts.reduceLeft(node.templateSpans, f, result); + case 195: + case 196: + case 201: + result = reduceNode(node.expression, cbNode, result); + break; + case 190: + case 191: + result = reduceNode(node.operand, cbNode, result); break; case 192: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 193: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); break; case 194: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); break; case 197: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.literal, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 199: - result = ts.reduceLeft(node.statements, f, result); - break; - case 200: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.declarationList, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); break; case 202: - result = reduceNode(node.expression, f, result); - break; - case 203: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.thenStatement, f, result); - result = reduceNode(node.elseStatement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); break; case 204: - result = reduceNode(node.statement, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.statements, cbNodes, result); break; case 205: - case 212: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); - break; - case 206: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.condition, f, result); - result = reduceNode(node.incrementor, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); break; case 207: + result = reduceNode(node.expression, cbNode, result); + break; case 208: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 209: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 210: + case 217: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 211: - case 215: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; + case 212: case 213: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.caseBlock, f, result); - break; - case 214: - result = reduceNode(node.label, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 216: - result = reduceNode(node.tryBlock, f, result); - result = reduceNode(node.catchClause, f, result); - result = reduceNode(node.finallyBlock, f, result); + case 220: + result = reduceNode(node.expression, cbNode, result); break; case 218: - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); break; case 219: - result = ts.reduceLeft(node.declarations, f, result); - break; - case 220: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 221: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); break; - case 227: - result = ts.reduceLeft(node.clauses, f, result); + case 223: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 230: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.importClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 224: + result = reduceNodes(node.declarations, cbNodes, result); break; - case 231: - result = reduceNode(node.name, f, result); - result = reduceNode(node.namedBindings, f, result); + case 225: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 226: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 232: - result = reduceNode(node.name, f, result); - break; - case 233: - case 237: - result = ts.reduceLeft(node.elements, f, result); - break; - case 234: - case 238: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); + result = reduceNodes(node.clauses, cbNodes, result); break; case 235: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 236: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.exportClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 237: + result = reduceNode(node.name, cbNode, result); + break; + case 238: + case 242: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 239: + case 243: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 240: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; case 241: - result = reduceNode(node.openingElement, f, result); - result = ts.reduceLeft(node.children, f, result); - result = reduceNode(node.closingElement, f, result); - break; - case 242: - case 243: - result = reduceNode(node.tagName, f, result); - result = ts.reduceLeft(node.attributes, f, result); - break; - case 245: - result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 246: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); break; case 247: - result = reduceNode(node.expression, f, result); - break; case 248: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.attributes, cbNodes, result); break; case 249: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + break; case 250: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 251: - result = ts.reduceLeft(node.types, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 252: - result = reduceNode(node.variableDeclaration, f, result); - result = reduceNode(node.block, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 253: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; + result = reduceNode(node.expression, cbNode, result); case 254: - result = reduceNode(node.name, f, result); - result = reduceNode(node.objectAssignmentInitializer, f, result); + result = reduceNodes(node.statements, cbNodes, result); + break; + case 255: + result = reduceNodes(node.types, cbNodes, result); break; case 256: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); break; - case 288: - result = reduceNode(node.expression, f, result); + case 257: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 258: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 259: + result = reduceNode(node.expression, cbNode, result); + break; + case 261: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 294: + result = reduceNode(node.expression, cbNode, result); break; default: var edgeTraversalPath = nodeEdgeTraversalMap[kind]; @@ -33560,8 +36798,8 @@ var ts; var value = node[edge.name]; if (value !== undefined) { result = ts.isArray(value) - ? ts.reduceLeft(value, f, result) - : f(result, value); + ? reduceNodes(value, cbNodes, result) + : cbNode(result, value); } } } @@ -33571,9 +36809,10 @@ var ts; } ts.reduceEachChild = reduceEachChild; function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); var visited = visitor(node); if (visited === node) { return node; @@ -33616,6 +36855,7 @@ var ts; } for (var i = 0; i < count; i++) { var node = nodes[i + start]; + aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -33647,183 +36887,213 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.createNodeArray(ts.concatenate(statements, declarations), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + function visitParameterList(nodes, visitor, context) { + context.startLexicalEnvironment(); + var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; function visitEachChild(node, visitor, context) { if (node === undefined) { return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return node; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return node; } switch (node.kind) { - case 198: - case 201: - case 193: - case 217: - return node; - case 140: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 142: - return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 145: - return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 147: - return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 148: - return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 149: - return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 150: - return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 167: - return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); - case 168: - return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); - case 169: - return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 170: - return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); - case 171: - return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 172: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 173: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 174: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 175: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); - case 178: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 179: - return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 180: - return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); - case 181: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 182: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 183: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 184: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 187: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); - case 185: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 186: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 188: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); - case 190: - return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192: - return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 194: - return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); - case 199: - return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 200: - return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 202: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 203: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); - case 204: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 205: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 206: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 198: + case 222: + return node; + case 142: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 144: + return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 149: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 150: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 151: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 172: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 173: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 174: + return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 175: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 176: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 177: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 178: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 179: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 180: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 181: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 183: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 185: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 186: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 188: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 189: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 190: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 191: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 193: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 194: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 195: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 199: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 202: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + case 204: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 205: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); case 207: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 208: - return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); case 209: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 210: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 211: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 212: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 213: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 214: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 215: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 216: - return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 217: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 218: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 219: - return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 220: - return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); case 221: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 223: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 224: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 225: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 226: return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 227: - return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 230: - return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 231: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 232: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 233: - return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); - case 234: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 235: - return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 236: - return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 237: - return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 238: - return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 239: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 240: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 241: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); case 242: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); case 243: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 245: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); case 246: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 247: - return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 248: - return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 249: - return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 250: - return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 251: - return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 252: - return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 253: - return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); case 254: - return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 255: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); case 256: - context.startLexicalEnvironment(); - return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); - case 288: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 257: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 258: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 259: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + case 261: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + case 294: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); default: var updated = void 0; @@ -33851,6 +37121,15 @@ var ts; } } ts.visitEachChild = visitEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.createNodeArray(ts.concatenate(statements, declarations), statements) + : ts.addRange(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function mergeFunctionBodyLexicalEnvironment(body, declarations) { if (body && declarations !== undefined && declarations.length > 0) { if (ts.isBlock(body)) { @@ -33881,85 +37160,61 @@ var ts; if (node === undefined) { return 0; } - else if (node.transformFlags & 536870912) { - return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + if (node.transformFlags & 536870912) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } - else { - var subtreeFlags = aggregateTransformFlagsForSubtree(node); - return ts.computeTransformFlagsForNode(node, subtreeFlags); + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0; } + var subtreeFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { return 0; } - return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } - function aggregateTransformFlagsForChildNode(transformFlags, child) { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 154 && kind <= 166) { - return -3; - } - switch (kind) { - case 174: - case 175: - case 170: - return 537133909; - case 225: - return 546335573; - case 142: - return 538968917; - case 180: - return 550710101; - case 179: - case 220: - return 550726485; - case 219: - return 538968917; - case 221: - case 192: - return 537590613; - case 148: - return 550593365; - case 147: - case 149: - case 150: - return 550593365; - case 117: - case 130: - case 127: - case 132: - case 120: - case 133: - case 103: - case 141: - case 144: - case 146: - case 151: - case 152: - case 153: - case 222: - case 223: - return -3; - case 171: - return 537430869; - default: - return 536871765; - } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } var Debug; (function (Debug) { Debug.failNotOptional = Debug.shouldAssert(1) ? function (message) { return Debug.assert(false, message || "Node not optional."); } - : function (message) { }; + : ts.noop; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."); }); } - : function (node, message) { }; + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + : ts.noop; + Debug.assertEachNode = Debug.shouldAssert(1) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."); }); } - : function (node, test, message) { }; + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + : ts.noop; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -33978,277 +37233,316 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { - if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { - var right = node.right; - if (ts.isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; - var value = node.right; - var expressions = []; - if (needsValue) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - else if (ts.nodeIsSynthesized(node)) { - location = value; + var expressions; + var flattenContext = { + context: context, + level: level, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (needsValue) { + value = ensureIdentifier(flattenContext, value, true, location); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); - if (needsValue) { + flattenBindingOrAssignmentElement(flattenContext, node, value, location, ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } expressions.push(value); } - var expression = ts.inlineExpressions(expressions); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location) { - var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + ts.setEmitFlags(expression, 64); ts.aggregateTransformFlags(expression); - expressions.push(expression); + expressions = ts.append(expressions, expression); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location); + expression.original = original; + emitExpression(expression); } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; - function flattenParameterDestructuring(context, node, value, visitor) { + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + var pendingExpressions; + var pendingDeclarations = []; var declarations = []; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + var flattenContext = { + context: context, + level: level, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, undefined, undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_30 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_30, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2); + variable.original = original; + if (ts.isIdentifier(name_30)) { + ts.setEmitFlags(variable, 64); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } return declarations; - function emitAssignment(name, value, location) { - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); - ts.aggregateTransformFlags(declaration); - declarations.push(declaration); + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(undefined); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); } } - ts.flattenParameterDestructuring = flattenParameterDestructuring; - function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { - var declarations = []; - var pendingAssignments; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - return declarations; - function emitAssignment(name, value, location, original) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = ts.inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); - declarations.push(declaration); - ts.aggregateTransformFlags(declaration); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - if (recordTempVariable) { - var assignment = ts.createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, undefined); - } - return name; - } - } - ts.flattenVariableDestructuring = flattenVariableDestructuring; - function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { - var pendingAssignments = []; - flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - var expression = ts.inlineExpressions(pendingAssignments); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location, original) { - var left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, undefined); - return name; - } - function emitPendingAssignment(name, value, location, original) { - var expression = ts.createAssignment(name, value, location); - expression.original = original; - context.setNodeEmitFlags(expression, 2048); - pendingAssignments.push(expression); - return expression; - } - } - ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; - function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { - if (value && visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); - } - if (ts.isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - function emitDestructuringAssignment(bindingTarget, value, location) { - var target; - if (ts.isShorthandPropertyAssignment(bindingTarget)) { - var initializer = visitor - ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) - : bindingTarget.objectAssignmentInitializer; - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - target = bindingTarget.name; - } - else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { - var initializer = visitor - ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) - : bindingTarget.right; - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, location); - } - else { - var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); - emitAssignment(name_26, value, location, undefined); - } - } - function emitObjectLiteralAssignment(target, value, location) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, location) { - var elements = target.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); - } - } - } - } - function emitBindingElement(target, value) { - var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + ts.flattenDestructuringBinding = flattenDestructuringBinding; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { value = ts.createVoidZero(); } - var name = target.name; - if (ts.isBindingPattern(name)) { - var elements = name.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (ts.isOmittedExpression(element)) { - continue; - } - else if (name.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - emitBindingElement(element, ts.createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, ts.createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - function createDefaultValueCheck(value, defaultValue, location) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } - function createDestructuringPropertyAccess(expression, propertyName) { - if (ts.isComputedPropertyName(propertyName)) { - return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); - } - else if (ts.isLiteralExpression(propertyName)) { - var clone_2 = ts.getSynthesizedClone(propertyName); - clone_2.text = ts.unescapeIdentifier(clone_2.text); - return ts.createElementAccess(expression, clone_2); - } - else { - if (ts.isGeneratedIdentifier(propertyName)) { - var clone_3 = ts.getSynthesizedClone(propertyName); - clone_3.text = ts.unescapeIdentifier(clone_3.text); - return ts.createPropertyAccess(expression, clone_3); + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, element); + } + } + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 + && !(element.transformFlags & (524288 | 1048576)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); } else { - return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1) { + if (element.transformFlags & 1048576) { + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } } } - function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteral(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + return ts.createElementAccess(value, argumentExpression); + } + else { + var name_31 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + return ts.createPropertyAccess(value, name_31); + } + } + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.createAssignment(temp, value, location)); } - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, undefined); + } + return temp; } } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(undefined, undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]); + } })(ts || (ts = {})); var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -34257,34 +37551,61 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(177); + context.enableSubstitution(178); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; - var currentSourceFileExternalHelpersModuleName; + var currentScopeFirstDeclarationsOfName; var enabledSubstitutions; var classAliases; var applicableSubstitutions; - var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { - return ts.visitNode(node, visitor, ts.isSourceFile); + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 261: + case 232: + case 231: + case 204: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 226: + case 225: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); + break; + } + } function visitor(node) { return saveStateAndInvoke(node, visitorWorker); } function visitorWorker(node) { - if (node.kind === 256) { - return visitSourceFile(node); - } - else if (node.transformFlags & 1) { + if (node.transformFlags & 1) { return visitTypeScript(node); } else if (node.transformFlags & 2) { @@ -34292,15 +37613,32 @@ var ts; } return node; } + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 240: + return visitExportAssignment(node); + case 241: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } function namespaceElementVisitor(node) { return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 236 || - node.kind === 230 || - node.kind === 231 || - (node.kind === 229 && - node.moduleReference.kind === 240)) { + if (node.kind === 241 || + node.kind === 235 || + node.kind === 236 || + (node.kind === 234 && + node.moduleReference.kind === 245)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -34316,145 +37654,129 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 148: - return undefined; - case 145: - case 153: - case 149: case 150: + return undefined; case 147: + case 155: + case 151: + case 152: + case 149: return visitorWorker(node); - case 198: + case 203: return node; default: ts.Debug.failBadSyntaxKind(node); return undefined; } } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270) { + return undefined; + } + else if (currentNamespace && node.kind === 83) { + return undefined; + } + return node; + } function visitTypeScript(node) { if (ts.hasModifier(node, 2) && ts.isStatement(node)) { return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 82: - case 77: + case 83: + case 78: return currentNamespace ? undefined : node; - case 112: - case 110: + case 113: case 111: - case 115: - case 118: - case 74: - case 122: - case 128: - case 160: - case 161: - case 159: - case 154: - case 141: - case 117: - case 120: - case 132: + case 112: + case 116: + case 75: + case 123: case 130: - case 127: - case 103: - case 133: - case 157: - case 156: - case 158: - case 155: case 162: case 163: + case 161: + case 156: + case 143: + case 118: + case 121: + case 134: + case 132: + case 129: + case 104: + case 135: + case 159: + case 158: + case 160: + case 157: case 164: case 165: case 166: - case 153: - case 143: - case 223: + case 167: + case 168: + case 169: + case 170: + case 171: + case 155: case 145: - case 148: - return undefined; - case 222: - return ts.createNotEmittedStatement(node); - case 221: - return visitClassDeclaration(node); - case 192: - return visitClassExpression(node); - case 251: - return visitHeritageClause(node); - case 194: - return visitExpressionWithTypeArguments(node); + case 228: case 147: - return visitMethodDeclaration(node); - case 149: - return visitGetAccessor(node); + return undefined; case 150: + return visitConstructor(node); + case 227: + return ts.createNotEmittedStatement(node); + case 226: + return visitClassDeclaration(node); + case 197: + return visitClassExpression(node); + case 255: + return visitHeritageClause(node); + case 199: + return visitExpressionWithTypeArguments(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessor(node); + case 152: return visitSetAccessor(node); - case 220: - return visitFunctionDeclaration(node); - case 179: - return visitFunctionExpression(node); - case 180: - return visitArrowFunction(node); - case 142: - return visitParameter(node); - case 178: - return visitParenthesizedExpression(node); - case 177: - case 195: - return visitAssertionExpression(node); - case 196: - return visitNonNullExpression(node); - case 224: - return visitEnumDeclaration(node); - case 184: - return visitAwaitExpression(node); - case 200: - return visitVariableStatement(node); case 225: - return visitModuleDeclaration(node); + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 183: + return visitParenthesizedExpression(node); + case 182: + case 200: + return visitAssertionExpression(node); + case 179: + return visitCallExpression(node); + case 180: + return visitNewExpression(node); + case 201: + return visitNonNullExpression(node); case 229: + return visitEnumDeclaration(node); + case 205: + return visitVariableStatement(node); + case 223: + return visitVariableDeclaration(node); + case 230: + return visitModuleDeclaration(node); + case 234: return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function onBeforeVisitNode(node) { - switch (node.kind) { - case 256: - case 227: - case 226: - case 199: - currentScope = node; - break; - } - } function visitSourceFile(node) { - currentSourceFile = node; - if (node.flags & 31744 - && compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); - var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); - var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~8; - statements.push(externalHelpersModuleImport); - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = ts.visitEachChild(node, visitor, context); - } - setNodeEmitFlags(node, 1 | node.emitFlags); - return node; + var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { if (node.decorators && node.decorators.length > 0) { @@ -34473,71 +37795,64 @@ var ts; var staticProperties = getInitializedProperties(node, true); var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var classAlias; var name = node.name; if (!name && staticProperties.length > 0) { name = ts.getGeneratedNameForNode(node); } - var statements = []; - if (!isDecoratedClass) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); - ts.setOriginalNode(classDeclaration, node); - if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); - } - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + var classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var statements = [classStatement]; if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); if (isNamespaceExport(node)) { addExportMemberAssignment(statements, node); } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } - return statements; + if (statements.length > 1) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + } + return ts.singleOrMany(statements); } - function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + var emitFlags = ts.getEmitFlags(node); + if (hasStaticProperties) { + emitFlags |= 32; + } + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { var location = ts.moveRangePastDecorators(node); - var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); - if (!name) { - name = ts.getGeneratedNameForNode(node); - } - var classAlias; - if (resolver.getNodeCheckFlags(node) & 8388608) { - enableSubstitutionForClassAliases(); - classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - } - var declaredName = getDeclarationName(node, true); - var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) - ]), location); - setCommentRange(transformedClassExpression, node); - statements.push(ts.setOriginalNode(transformedClassExpression, node)); - if (classAlias) { - statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(declaredName, undefined, classAlias) - ]), location), node)); - } - return classAlias; + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, false, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, hasExtendsClause); + var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members, location); + ts.setOriginalNode(classExpression, node); + var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location); + ts.setOriginalNode(statement, node); + ts.setCommentRange(statement, node); + return statement; } function visitClassExpression(node) { var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, heritageClauses !== undefined); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84; })); var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); if (staticProperties.length > 0) { var expressions = []; @@ -34546,9 +37861,9 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); - ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } @@ -34565,24 +37880,23 @@ var ts; } function transformConstructor(node, hasExtendsClause) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 131072; + var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + var body = transformConstructorBody(node, constructor, hasExtendsClause); return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); } function transformConstructorParameters(constructor) { - return constructor - ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) - : []; + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } - function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + function transformConstructorBody(node, constructor, hasExtendsClause) { var statements = []; var indexOfFirstStatement = 0; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); var propertyAssignments = getParametersWithPropertyAssignments(constructor); @@ -34592,12 +37906,12 @@ var ts; statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); - addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } ts.addRange(statements, endLexicalEnvironment()); - return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + return ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined, true); } function addPrologueDirectivesAndInitialSuperCall(ctor, result) { if (ctor.body) { @@ -34607,7 +37921,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -34626,9 +37940,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 1536 | 48); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 1536); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -34641,32 +37955,32 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 145 + return member.kind === 147 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } - function addInitializedPropertyStatements(statements, node, properties, receiver) { - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; - var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } - function generateInitializedPropertyExpressions(node, properties, receiver) { + function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { - var property = properties_8[_i]; - var expression = transformInitializedProperty(node, property, receiver); + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; } - function transformInitializedProperty(node, property, receiver) { + function transformInitializedProperty(property, receiver) { var propertyName = visitPropertyNameOfClassElement(property); var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); @@ -34714,12 +38028,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 149: - case 150: + case 151: + case 152: return getAllDecoratorsOfAccessors(node, member); - case 147: + case 149: return getAllDecoratorsOfMethod(member); - case 145: + case 147: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -34730,10 +38044,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -34758,14 +38073,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -34790,44 +38105,40 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 145 + ? member.kind === 147 ? ts.createVoidZero() : ts.createNull() : undefined; - var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536); return helper; } - function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { - var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } } - function generateConstructorDecorationExpression(node, decoratedClassAlias) { + function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - if (decoratedClassAlias) { - var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); - var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } - else { - var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, false, true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; } function transformDecorator(decorator) { return ts.visitNode(decorator.expression, visitor, ts.isExpression); @@ -34838,97 +38149,90 @@ var ts; expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, decorator.expression); + ts.setEmitFlags(helper, 1536); expressions.push(helper); } } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); } } } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 147 - || kind === 149 - || kind === 150 - || kind === 145; + return kind === 149 + || kind === 151 + || kind === 152 + || kind === 147; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 147; + return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 221 - || kind === 192 - || kind === 147 - || kind === 149 - || kind === 150; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { - case 145: - case 142: - case 149: - return serializeTypeNode(node.type); - case 150: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 221: - case 192: case 147: + case 144: + case 151: + return serializeTypeNode(node.type); + case 152: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 226: + case 197: + case 149: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 160) { - return node.elementType; - } - else if (node && node.kind === 155) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -34936,7 +38240,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -34944,7 +38248,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -34953,6 +38257,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -34967,49 +38280,75 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 103: + case 104: return ts.createVoidZero(); - case 164: - return serializeTypeNode(node.type); - case 156: - case 157: - return ts.createIdentifier("Function"); - case 160: - case 161: - return ts.createIdentifier("Array"); - case 154: - case 120: - return ts.createIdentifier("Boolean"); - case 132: - return ts.createIdentifier("String"); case 166: + return serializeTypeNode(node.type); + case 158: + case 159: + return ts.createIdentifier("Function"); + case 162: + case 163: + return ts.createIdentifier("Array"); + case 156: + case 121: + return ts.createIdentifier("Boolean"); + case 134: + return ts.createIdentifier("String"); + case 171: switch (node.literal.kind) { case 9: return ts.createIdentifier("String"); case 8: return ts.createIdentifier("Number"); - case 99: - case 84: + case 100: + case 85: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 130: + case 132: return ts.createIdentifier("Number"); - case 133: + case 135: return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 155: + case 157: return serializeTypeReferenceNode(node); - case 158: - case 159: - case 162: - case 163: - case 117: case 165: + case 164: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 70) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } + case 160: + case 168: + case 169: + case 170: + case 161: + case 118: + case 167: break; default: ts.Debug.failBadSyntaxKind(node); @@ -35022,7 +38361,7 @@ var ts; case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: return serializeEntityNameAsExpression(node.typeName, false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: @@ -35050,22 +38389,22 @@ var ts; } function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 69: - var name_27 = ts.getMutableClone(node); - name_27.flags &= ~8; - name_27.original = undefined; - name_27.parent = currentScope; + case 70: + var name_32 = ts.getMutableClone(node); + name_32.flags &= ~8; + name_32.original = undefined; + name_32.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_32), ts.createLiteral("undefined")), name_32); } - return name_27; - case 139: + return name_32; + case 141: return serializeQualifiedNameAsExpression(node, useFallback); } } function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 69) { + if (node.left.kind === 70) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { @@ -35078,7 +38417,7 @@ var ts; return ts.createPropertyAccess(left, node.right); } function getGlobalSymbolNameWithFallback() { - return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; @@ -35088,7 +38427,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeIdentifier(name.text)); } else { return ts.getSynthesizedClone(name); @@ -35110,9 +38449,9 @@ var ts; } } function visitHeritageClause(node) { - if (node.token === 83) { + if (node.token === 84) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.createHeritageClause(83, types, node); + return ts.createHeritageClause(84, types, node); } return undefined; } @@ -35123,15 +38462,22 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.visitEachChild(node, visitor, context); + } function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(method, node); - return method; + var updated = ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); @@ -35140,135 +38486,56 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateGetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateSetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); + var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isNamespaceExport(node)) { - var statements = [func]; + var statements = [updated]; addExportMemberAssignment(statements, node); return statements; } - return func; + return updated; } function visitFunctionExpression(node) { if (ts.nodeIsMissing(node.body)) { return ts.createOmittedExpression(); } - var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); - return func; + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitArrowFunction(node) { - var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); - ts.setOriginalNode(func, node); - return func; - } - function transformFunctionBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformFunctionBodyWorker(node.body); - } - function transformFunctionBodyWorker(body, start) { - if (start === void 0) { start = 0; } - var savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); - var visited = ts.updateBlock(body, statements); - var declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - function transformConciseBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformConciseBodyWorker(node.body, false); - } - function transformConciseBodyWorker(body, forceBlockFunctionBody) { - if (ts.isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - var visited = ts.visitNode(body, visitor, ts.isConciseBody); - var declarations = endLexicalEnvironment(); - var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !ts.isBlock(merged)) { - return ts.createBlock([ - ts.createReturn(merged) - ]); - } - else { - return merged; - } - } - } - function getPromiseConstructor(type) { - var typeName = ts.getEntityNameFromTypeNode(type); - if (typeName && ts.isEntityName(typeName)) { - var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - return undefined; - } - function transformAsyncFunctionBody(node) { - var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); - var block = ts.createBlock(statements, node.body, true); - if (languageVersion >= 2) { - if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); - } - } - return block; - } - else { - return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); - } + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32); return parameter; } function visitVariableStatement(node) { @@ -35286,14 +38553,14 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + return ts.flattenDestructuringAssignment(node, visitor, context, 0, false, createNamespaceExportExpression); } else { return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); } } - function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2); @@ -35311,42 +38578,43 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return ts.createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } function shouldEmitEnumDeclaration(node) { return !ts.isConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); - } - function addVarForEnumExportedFromNamespace(statements, node) { - var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); - statements.push(statement); - } function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { return undefined; } var statements = []; - var emitFlags = 64; - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); - ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); - statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); + moduleArg = ts.createAssignment(localName, moduleArg); } + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(enumStatement, node); + ts.setEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -35381,35 +38649,56 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); + function hasNamespaceQualifiedExportName(node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.System); } - function isES6ExportedDeclaration(node) { - return isExternalModuleExport(node) - && moduleKind === ts.ModuleKind.ES6; + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } } - function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_33 = node.symbol && node.symbol.name; + if (name_33) { + return currentScopeFirstDeclarationsOfName[name_33] === node; + } + } + return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) - ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) - : undefined, [ - ts.createVariableDeclaration(getDeclarationName(node, false, true)) + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + ts.createVariableDeclaration(ts.getLocalName(node, false, true)) ]); ts.setOriginalNode(statement, node); - if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + if (node.kind === 229) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 1024 | 2097152); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 | 2097152); + statements.push(mergeMarker); + return false; } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); - statements.push(statement); } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -35418,38 +38707,42 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; - var emitFlags = 64; - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); - if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { - var localName = getLocalName(node); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); moduleArg = ts.createAssignment(localName, moduleArg); } - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 226) { + if (body.kind === 231) { ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); statementsLocation = body.statements; blockLocation = body; @@ -35470,18 +38763,69 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); - if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + if (body.kind !== 231) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body.kind === 230) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + function visitImportDeclaration(node) { + if (!node.importClause) { + return node; + } + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, true); + return importClause + ? ts.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier) + : undefined; + } + function visitImportClause(node) { + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, true); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + function visitNamedImportBindings(node) { + if (node.kind === 237) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitExportAssignment(node) { + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, true); + return exportClause + ? ts.updateExportDeclaration(node, undefined, undefined, exportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } function shouldEmitImportEqualsDeclaration(node) { return resolver.isReferencedAliasDeclaration(node) || (!ts.isExternalModule(currentSourceFile) @@ -35489,16 +38833,18 @@ var ts; } function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { - return ts.visitEachChild(node, visitor, context); + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 1536 | 2048); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { - return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(node.name, undefined, moduleReference) + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ]), node), node); } else { @@ -35523,148 +38869,87 @@ var ts; return ts.createStatement(expression, undefined); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, false, true), exportValue), location); } - function createExternalModuleExport(exportName) { - return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ - ts.createExportSpecifier(exportName) - ])); - } - function getNamespaceMemberName(name, allowComments, allowSourceMaps) { - var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); - var emitFlags; - if (!allowComments) { - emitFlags |= 49152; - } - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return getNamespaceMemberName(name, false, true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, false, true); } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { return ts.getGeneratedNameForNode(node); } - function getLocalName(node, noSourceMaps, allowComments) { - return getDeclarationName(node, allowComments, !noSourceMaps, 262144); - } - function getExportName(node, noSourceMaps, allowComments) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - return getDeclarationName(node, allowComments, !noSourceMaps, 131072); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); - } - return name_28; - } - else { - return ts.getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } function getClassPrototype(node) { - return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { return ts.hasModifier(member, 32) - ? getDeclarationName(node) + ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8) === 0) { enabledSubstitutions |= 8; - context.enableSubstitution(69); - } - } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 4) === 0) { - enabledSubstitutions |= 4; - context.enableSubstitution(174); - context.enableSubstitution(172); - context.enableSubstitution(173); - context.enableEmitNotification(221); - context.enableEmitNotification(147); - context.enableEmitNotification(149); - context.enableEmitNotification(150); - context.enableEmitNotification(148); + context.enableSubstitution(70); } } function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(69); + context.enableSubstitution(70); classAliases = ts.createMap(); } } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(69); - context.enableSubstitution(254); - context.enableEmitNotification(225); + context.enableSubstitution(70); + context.enableSubstitution(258); + context.enableEmitNotification(230); } } - function isSuperContainer(node) { - var kind = node.kind; - return kind === 221 - || kind === 148 - || kind === 147 - || kind === 149 - || kind === 150; - } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 225; + return ts.getOriginalNode(node).kind === 230; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 224; + return ts.getOriginalNode(node).kind === 229; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; - var savedCurrentSuperContainer = currentSuperContainer; - if (enabledSubstitutions & 4 && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2; } if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -35674,32 +38959,26 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_34 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_34); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, node); + return ts.createPropertyAssignment(name_34, initializer, node); } - return ts.createPropertyAssignment(name_29, exportedName, node); + return ts.createPropertyAssignment(name_34, exportedName, node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: - return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); } return node; } @@ -35715,10 +38994,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); - return clone_4; + var clone_2 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -35726,11 +39005,11 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container) { - var substitute = (applicableSubstitutions & 2 && container.kind === 225) || - (applicableSubstitutions & 8 && container.kind === 224); + if (container && container.kind !== 261) { + var substitute = (applicableSubstitutions & 2 && container.kind === 230) || + (applicableSubstitutions & 8 && container.kind === 229); if (substitute) { return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); } @@ -35738,1594 +39017,354 @@ var ts; } return undefined; } - function substituteCallExpression(node) { - var expression = node.expression; - if (ts.isSuperProperty(expression)) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - var argumentExpression = ts.isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ - ts.createThis() - ].concat(node.arguments)); - } - } - return node; - } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); - } - } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; } + ts.setConstantValue(node, constantValue); + return substitute; } return node; } - function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { - if (flags & 4096) { - return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; } - else { - return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); - } - } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; } } ts.transformTypeScript = transformTypeScript; + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.createCall(ts.getHelperName("__param"), undefined, [ + ts.createLiteral(parameterOffset), + expression + ], location); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + context.requestEmitHelper(decorateHelper); + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray, location); + } })(ts || (ts = {})); var ts; (function (ts) { - function transformES6Module(context) { - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var currentSourceFile; + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; return transformSourceFile; function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return ts.visitEachChild(node, visitor, context); + if (ts.isDeclarationFile(node)) { + return node; } - return node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; } function visitor(node) { - switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 231: - return visitImportClause(node); - case 233: - case 232: - return visitNamedBindings(node); - case 234: - return visitImportSpecifier(node); - case 235: - return visitExportAssignment(node); - case 236: - return visitExportDeclaration(node); - case 237: - return visitNamedExports(node); - case 238: - return visitExportSpecifier(node); - } - return node; + return visitorWorker(node, false); } - function visitExportAssignment(node) { - if (node.isExportEquals) { - return undefined; - } - var original = ts.getOriginalNode(node); - return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + function visitorNoDestructuringValue(node) { + return visitorWorker(node, true); } - function visitExportDeclaration(node) { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; - } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; - } - var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); - if (node.exportClause === newExportClause) { + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8) === 0) { return node; } - return newExportClause - ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) - : undefined; - } - function visitNamedExports(node) { - var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? ts.createNamedExports(newExports) : undefined; - } - function visitExportSpecifier(node) { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - function visitImportEqualsDeclaration(node) { - return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - function visitImportDeclaration(node) { - if (node.importClause) { - var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); - } - } - return node; - } - function visitImportClause(node) { - var newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? ts.createImportClause(newDefaultImport, newNamedBindings) - : node; - } - function visitNamedBindings(node) { - if (node.kind === 232) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === node.elements) { - return node; - } - return ts.createNamedImports(newNamedImportElements); - } - } - function visitImportSpecifier(node) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - } - ts.transformES6Module = transformES6Module; -})(ts || (ts = {})); -var ts; -(function (ts) { - function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableEmitNotification(256); - var exportFunctionForFileMap = []; - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var exportFunctionForFile; - var contextObjectForFile; - var exportedLocalNames; - var exportedFunctionDeclarations; - var enclosingBlockScopedContainer; - var currentParent; - var currentNode; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; - var updated = transformSystemModuleWorker(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - return node; - } - function transformSystemModuleWorker(node) { - ts.Debug.assert(!exportFunctionForFile); - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - exportFunctionForFile = ts.createUniqueName("exports"); - contextObjectForFile = ts.createUniqueName("context"); - exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; - var dependencyGroups = collectDependencyGroups(externalImports); - var statements = []; - addSystemModuleBody(statements, node, dependencyGroups); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); - var body = ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter(exportFunctionForFile), - ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName - ? [moduleName, dependencies, body] - : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); - var _a; - } - function addSystemModuleBody(statements, node, dependencyGroups) { - startLexicalEnvironment(); - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) - ]))); - var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); - ts.addRange(statements, endLexicalEnvironment()); - ts.addRange(statements, exportedFunctionDeclarations); - var exportStarFunction = addExportStarIfNeeded(statements); - statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ - ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) - ]), true))); - } - function addExportStarIfNeeded(statements) { - if (!hasExportStarsToExportValues) { - return; - } - if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { - var externalImport = externalImports_1[_i]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return addExportStarFunction(statements, undefined); - } - } - var exportedNames = []; - if (exportedLocalNames) { - for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { - var exportedLocalName = exportedLocalNames_1[_a]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); - } - } - for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { - var externalImport = externalImports_2[_b]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { - var element = _d[_c]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); - } - } - var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) - ]))); - return addExportStarFunction(statements, exportedNamesStorageRef); - } - function generateSetters(exportStarFunction, dependencyGroups) { - var setters = []; - for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group = dependencyGroups_1[_i]; - var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); - var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); - var statements = []; - for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { - var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== undefined); - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); - break; - case 236: - ts.Debug.assert(importVariableName !== undefined); - if (entry.exportClause) { - var properties = []; - for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { - var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); - } - statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); - } - else { - statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); - } - break; - } - } - setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); - } - return ts.createArrayLiteral(setters, undefined, true); - } - function visitSourceElement(node) { switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); - case 235: - return visitExportAssignment(node); - default: - return visitNestedNode(node); - } - } - function visitNestedNode(node) { - var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; - } - var result = visitNestedNodeWorker(node); - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return result; - } - function visitNestedNodeWorker(node) { - switch (node.kind) { - case 200: - return visitVariableStatement(node); - case 220: - return visitFunctionDeclaration(node); - case 221: - return visitClassDeclaration(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 208: - return visitForOfStatement(node); - case 204: - return visitDoStatement(node); - case 205: - return visitWhileStatement(node); - case 214: - return visitLabeledStatement(node); - case 212: - return visitWithStatement(node); + case 176: + return visitObjectLiteralExpression(node); + case 192: + return visitBinaryExpression(node, noDestructuringValue); + case 223: + return visitVariableDeclaration(node); case 213: - return visitSwitchStatement(node); - case 227: - return visitCaseBlock(node); - case 249: - return visitCaseClause(node); - case 250: - return visitDefaultClause(node); - case 216: - return visitTryStatement(node); - case 252: - return visitCatchClause(node); - case 199: - return visitBlock(node); - case 202: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (node.importClause && ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitImportEqualsDeclaration(node) { - if (ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitExportDeclaration(node) { - if (!node.moduleSpecifier) { - var statements = []; - ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - return undefined; - } - function visitExportSpecifier(specifier) { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement(specifier.name, specifier.propertyName || specifier.name); - } - return undefined; - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement(ts.createLiteral("default"), node.expression); - } - } - return undefined; - } - function visitVariableStatement(node) { - var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || - enclosingBlockScopedContainer.kind === 256; - if (!shouldHoist) { - return node; - } - var isExported = ts.hasModifier(node, 1); - var expressions = []; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } - } - if (expressions.length) { - return ts.createStatement(ts.inlineExpressions(expressions), node); - } - return undefined; - } - function transformVariable(node, isExported) { - hoistBindingElement(node, isExported); - if (!node.initializer) { - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - return ts.createAssignment(name, node.initializer); - } - else { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1)) { - var name_30 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_30, undefined, node.parameters, undefined, node.body, node); - recordExportedFunctionDeclaration(node); - if (!ts.hasModifier(node, 512)) { - recordExportName(name_30); - } - ts.setOriginalNode(newNode, node); - node = newNode; - } - hoistFunctionDeclaration(node); - return undefined; - } - function visitExpressionStatement(node) { - var originalNode = ts.getOriginalNode(node); - if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_31 = getDeclarationName(originalNode); - if (originalNode.kind === 224) { - hoistVariableDeclaration(name_31); - } - return [ - node, - createExportStatement(name_31, name_31) - ]; - } - return node; - } - function visitClassDeclaration(node) { - var name = getDeclarationName(node); - hoistVariableDeclaration(name); - var statements = []; - statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); - if (ts.hasModifier(node, 1)) { - if (!ts.hasModifier(node, 512)) { - recordExportName(name); - } - statements.push(createDeclarationExport(node)); - } - return statements; - } - function shouldHoistLoopInitializer(node) { - return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; - } - function visitForStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var expressions = []; - for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, false); - if (visited) { - expressions.push(visited); - } - } - ; - return ts.createFor(expressions.length - ? ts.inlineExpressions(expressions) - : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function transformForBinding(node) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, false); - var name = firstDeclaration.name; - return ts.isIdentifier(name) - ? name - : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); - } - function visitForInStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitForOfStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitDoStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWhileStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitLabeledStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWithStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitSwitchStatement(node) { - var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); - if (caseBlock !== node.caseBlock) { - var updated = ts.getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; - } - function visitCaseBlock(node) { - var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); - if (clauses !== node.clauses) { - var updated = ts.getMutableClone(node); - updated.clauses = clauses; - return updated; - } - return node; - } - function visitCaseClause(node) { - var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); - if (statements !== node.statements) { - var updated = ts.getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; - } - function visitDefaultClause(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitTryStatement(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitCatchClause(node) { - var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); - if (block !== node.block) { - var updated = ts.getMutableClone(node); - updated.block = block; - return updated; - } - return node; - } - function visitBlock(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function onEmitNode(node, emit) { - if (node.kind === 256) { - exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - exportFunctionForFile = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69: - return substituteExpressionIdentifier(node); - case 187: - return substituteBinaryExpression(node); + return visitForOfStatement(node); + case 211: + return visitForStatement(node); + case 188: + return visitVoidExpression(node); + case 150: + return visitConstructorDeclaration(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessorDeclaration(node); + case 152: + return visitSetAccessorDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); case 185: - case 186: - return substituteUnaryExpression(node); + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 207: + return visitExpressionStatement(node); + case 183: + return visitParenthesizedExpression(node, noDestructuringValue); + default: + return ts.visitEachChild(node, visitor, context); } - return node; } - function substituteExpressionIdentifier(node) { - var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - var importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; - } - } - return node; - } - function substituteBinaryExpression(node) { - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); - } - return node; - } - function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); - var left = node.left; - switch (left.kind) { - case 69: - var exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; + if (e.kind === 259) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; } - break; - case 171: - case 170: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - return node; - } - function isExportedBinding(name) { - var container = resolver.getReferencedExportContainer(name); - return container && container.kind === 256; - } - function hasExportedReferenceInDestructuringPattern(node) { - switch (node.kind) { - case 69: - return isExportedBinding(node); - case 171: - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var property = _a[_i]; - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - break; - case 170: - for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - break; - } - return false; - } - function hasExportedReferenceInObjectDestructuringElement(node) { - if (ts.isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (ts.isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - function hasExportedReferenceInArrayDestructuringElement(node) { - if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - function hasExportedReferenceInDestructuringElement(node) { - if (ts.isBinaryExpression(node)) { - var left = node.left; - return node.operatorToken.kind === 56 - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (ts.isIdentifier(node)) { - return isExportedBinding(node); - } - else if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - function isDestructuringPattern(node) { - var kind = node.kind; - return kind === 69 - || kind === 171 - || kind === 170; - } - function substituteDestructuring(node) { - return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); - } - function substituteUnaryExpression(node) { - var operand = node.operand; - var operator = node.operator; - var substitute = ts.isIdentifier(operand) && - (node.kind === 186 || - (node.kind === 185 && (operator === 41 || operator === 42))); - if (substitute) { - var exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); - var call = createExportExpression(operand, expr); - if (node.kind === 185) { - return call; - } - else { - return operator === 41 - ? ts.createSubtract(call, ts.createLiteral(1)) - : ts.createAdd(call, ts.createLiteral(1)); - } - } - } - return node; - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function addExportStarFunction(statements, localNames) { - var exportStarFunction = ts.createUniqueName("exportStar"); - var m = ts.createIdentifier("m"); - var n = ts.createIdentifier("n"); - var exports = ts.createIdentifier("exports"); - var condition = ts.createStrictInequality(n, ts.createLiteral("default")); - if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); - } - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ - ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) - ])), - ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, undefined) - ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) - ])), - ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) - ], undefined, true))); - return exportStarFunction; - } - function createExportExpression(name, value) { - var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; - return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); - } - function createExportStatement(name, value) { - return ts.createStatement(createExportExpression(name, value)); - } - function createDeclarationExport(node) { - var declarationName = getDeclarationName(node); - var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - function createImportBinding(importDeclaration) { - var importAlias; - var name; - if (ts.isImportClause(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); - name = ts.createIdentifier("default"); - } - else if (ts.isImportSpecifier(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - if (name.originalKeywordKind && languageVersion === 0) { - return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); - } - else { - return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); - } - } - function collectDependencyGroups(externalImports) { - var groupIndices = ts.createMap(); - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; - var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); - var text = externalModuleName.text; - if (ts.hasProperty(groupIndices, text)) { - var groupIndex = groupIndices[text]; - dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - groupIndices[text] = dependencyGroups.length; - dependencyGroups.push({ - name: externalModuleName, - externalImports: [externalImport] - }); + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === 257) { + var p = e; + chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); + } + else { + chunkObject.push(e); + } } } - return dependencyGroups; - } - function getNameOfDependencyGroup(dependencyGroup) { - return dependencyGroup.name; - } - function recordExportName(name) { - if (!exportedLocalNames) { - exportedLocalNames = []; + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); } - exportedLocalNames.push(name); + return objects; } - function recordExportedFunctionDeclaration(node) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 1048576) { + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 176) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); } - exportedFunctionDeclarations.push(createDeclarationExport(node)); + return ts.visitEachChild(node, visitor, context); } - function hoistBindingElement(node, isExported) { - if (ts.isOmittedExpression(node)) { - return; + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); } - var name = node.name; - if (ts.isIdentifier(name)) { - hoistVariableDeclaration(ts.getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); + else if (node.operatorToken.kind === 25) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + return ts.flattenDestructuringBinding(node, visitor, context, 1); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitForOfStatement(node) { + var leadingStatements; + var temp; + var initializer = ts.skipParentheses(node.initializer); + if (initializer.transformFlags & 1048576) { + if (ts.isVariableDeclarationList(initializer)) { + temp = ts.createTempVariable(undefined); + var firstDeclaration = ts.firstOrUndefined(initializer.declarations); + var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(initializer, declarations), initializer); + leadingStatements = ts.append(leadingStatements, statement); + } + } + else if (ts.isAssignmentPattern(initializer)) { + temp = ts.createTempVariable(undefined); + var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, node.initializer)), visitor, context, 1); + leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, node.initializer)); } } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + if (temp) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var block = ts.isBlock(statement) + ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements)) + : ts.createBlock(ts.append(leadingStatements, statement), statement, true); + return ts.updateForOf(node, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, undefined, node.initializer) + ], node.initializer, 1), expression, block); } + return ts.visitEachChild(node, visitor, context); } - function hoistExportedBindingElement(node) { - hoistBindingElement(node, true); - } - function hoistNonExportedBindingElement(node) { - hoistBindingElement(node, false); - } - function updateSourceFile(node, statements, nodeEmitFlags) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); - return updated; - } - } - ts.transformSystemModule = transformSystemModule; -})(ts || (ts = {})); -var ts; -(function (ts) { - function transformModule(context) { - var transformModuleDelegates = ts.createMap((_a = {}, - _a[ts.ModuleKind.None] = transformCommonJSModule, - _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, - _a[ts.ModuleKind.AMD] = transformAMDModule, - _a[ts.ModuleKind.UMD] = transformUMDModule, - _a - )); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var moduleKind = ts.getEmitModuleKind(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableSubstitution(254); - context.enableEmitNotification(256); - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var bindingNameExportSpecifiersMap; - var bindingNameExportSpecifiersForFileMap = ts.createMap(); - var hasExportStarsToExportValues; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; - var updated = transformModule_1(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; + function visitParameter(node) { + if (node.transformFlags & 1048576) { + return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - return node; - var _a; + return ts.visitEachChild(node, visitor, context); } - function transformCommonJSModule(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - addExportEqualsIfNeeded(statements, false); - var updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + function visitConstructorDeclaration(node) { + return ts.updateConstructor(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitGetAccessorDeclaration(node) { + return ts.updateGetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitSetAccessorDeclaration(node) { + return ts.updateSetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var leadingStatements; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 1048576) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 524288); + leadingStatements = ts.append(leadingStatements, statement); + } + } } - return updated; - } - function transformAMDModule(node) { - var define = ts.createIdentifier("define"); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - return transformAsynchronousModule(node, define, moduleName, true); - } - function transformUMDModule(node) { - var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); - return transformAsynchronousModule(node, define, undefined, false); - } - function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { - var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ - ts.createArrayLiteral([ - ts.createLiteral("require"), - ts.createLiteral("exports") - ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter("require"), - ts.createParameter("exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) - ]))) - ]); - } - function transformAsynchronousModuleBody(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - addExportEqualsIfNeeded(statements, true); - var body = ts.createBlock(statements, undefined, true); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + var trailingStatements = endLexicalEnvironment(); + if (ts.some(leadingStatements) || ts.some(trailingStatements)) { + var block = ts.convertToFunctionBody(body, true); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); } return body; } - function addExportEqualsIfNeeded(statements, emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - if (emitAsReturn) { - var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); - statements.push(statement); - } - } - } - function visitor(node) { - switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); - case 235: - return visitExportAssignment(node); - case 200: - return visitVariableStatement(node); - case 220: - return visitFunctionDeclaration(node); - case 221: - return visitClassDeclaration(node); - case 202: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var statements = []; - var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); - if (moduleKind !== ts.ModuleKind.AMD) { - if (!node.importClause) { - statements.push(ts.createStatement(createRequireCall(node), node)); - } - else { - var variables = []; - if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); - } - else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); - if (namespaceDeclaration && ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); - } - } - statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); - } - } - else if (namespaceDeclaration && ts.isDefaultImport(node)) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) - ]))); - } - addExportImportAssignments(statements, node); - return ts.singleOrMany(statements); - } - function visitImportEqualsDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - setNodeEmitFlags(node.name, 128); - var statements = []; - if (moduleKind !== ts.ModuleKind.AMD) { - if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); - } - else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) - ], undefined, languageVersion >= 2 ? 2 : 0), node)); - } - } - else { - if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); - } - } - addExportImportAssignments(statements, node); - return statements; - } - function visitExportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var generatedName = ts.getGeneratedNameForNode(node); - if (node.exportClause) { - var statements = []; - if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) - ]), node)); - } - for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { - var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); - } - } - return ts.singleOrMany(statements); - } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ]), node); - } - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - var statements = []; - addExportDefault(statements, node.expression, node); - return statements; - } - } - return undefined; - } - function addExportDefault(statements, expression, location) { - tryAddExportDefaultCompat(statements); - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); - } - function tryAddExportDefaultCompat(statements) { - var original = ts.getOriginalNode(currentSourceFile); - ts.Debug.assert(original.kind === 256); - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === 0) { - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); - } - else { - statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) - ]) - ]))); - } - } - } - function addExportImportAssignments(statements, node) { - if (ts.isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); - } - else { - var names = ts.reduceEachChild(node, collectExportMembers, []); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); - } - } - } - function collectExportMembers(names, node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); - } - } - return ts.reduceEachChild(node, collectExportMembers, names); - } - function addExportMemberAssignments(statements, name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); - } - } - } - function addExportMemberAssignment(statements, node) { - if (ts.hasModifier(node, 512)) { - addExportDefault(statements, getDeclarationName(node), node); - } - else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); - } - } - function visitVariableStatement(node) { - var originalKind = ts.getOriginalNode(node).kind; - if (originalKind === 225 || - originalKind === 224 || - originalKind === 221) { - if (!ts.hasModifier(node, 1)) { - return node; - } - return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); - } - var resultStatements = []; - if (ts.hasModifier(node, 1)) { - var variables = ts.getInitializedVariables(node.declarationList); - if (variables.length > 0) { - var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - return resultStatements; - } - function addExportMemberAssignmentsForBindingName(resultStatements, name) { - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - var sourceFileId = ts.getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - function transformInitializedVariable(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); - } - else { - return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); - } - } - function visitFunctionDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - if (node.name) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitClassDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitExpressionStatement(node) { - var original = ts.getOriginalNode(node); - var origKind = original.kind; - if (origKind === 224 || origKind === 225) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === 221) { - var classDecl = original; - if (classDecl.name) { - var statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; - } - } - return node; - } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { - var statements = [node]; - if (ts.hasModifier(original, 1) && - original.kind === 224 && - ts.isFirstDeclarationOfKind(original, 224)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); - } - addExportMemberAssignments(statements, original.name); - return statements; - } - function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { - var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); - statements.push(transformedStatement); - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function onEmitNode(node, emit) { - if (node.kind === 256) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - bindingNameExportSpecifiersMap = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - else if (ts.isShorthandPropertyAssignment(node)) { - return substituteShorthandPropertyAssignment(node); - } - return node; - } - function substituteShorthandPropertyAssignment(node) { - var name = node.name; - var exportedOrImportedName = substituteExpressionIdentifier(name); - if (exportedOrImportedName !== name) { - if (node.objectAssignmentInitializer) { - var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name, initializer, node); - } - return ts.createPropertyAssignment(name, exportedOrImportedName, node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69: - return substituteExpressionIdentifier(node); - case 187: - return substituteBinaryExpression(node); - case 186: - case 185: - return substituteUnaryExpression(node); - } - return node; - } - function substituteExpressionIdentifier(node) { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; - } - function substituteBinaryExpression(node) { - var left = node.left; - if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); - } - return nestedExportAssignment; - } - } - return node; - } - function substituteUnaryExpression(node) { - var operator = node.operator; - var operand = node.operand; - if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); - var transformedUnaryExpression = void 0; - if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); - } - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; - } - } - return node; - } - function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); - if ((emitFlags & 262144) === 0) { - var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); - if (container) { - if (container.kind === 256) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); - } - } - } - return undefined; - } - function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (ts.isImportClause(declaration)) { - if (languageVersion >= 1) { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); - } - else { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); - } - } - else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), node); - } - else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), node); - } - } - } - } - return undefined; - } - function getModuleMemberName(name) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); - } - function createRequireCall(importNode) { - var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var args = []; - if (ts.isDefined(moduleName)) { - args.push(moduleName); - } - return ts.createCall(ts.createIdentifier("require"), undefined, args); - } - function createExportStatement(name, value, location) { - var statement = ts.createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - return statement; - } - function createExportAssignment(name, value) { - return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 - ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) - : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); - } - function collectAsynchronousDependencies(node, includeNonAmdDependencies) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - } - } - for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { - var importNode = externalImports_3[_b]; - var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function updateSourceFile(node, statements) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - return updated; - } - var _a; } - ts.transformModule = transformModule; + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + }; + function createAssignHelper(context, attributesSegments) { + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; })(ts || (ts = {})); var ts; (function (ts) { - var entities = createEntitiesMap(); function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; - return node; + return visited; } function visitor(node) { if (node.transformFlags & 4) { return visitorWorker(node); } - else if (node.transformFlags & 8) { - return ts.visitEachChild(node, visitor, context); - } else { return node; } } function visitorWorker(node) { switch (node.kind) { - case 241: + case 246: return visitJsxElement(node, false); - case 242: + case 247: return visitJsxSelfClosingElement(node, false); - case 248: + case 252: return visitJsxExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.visitEachChild(node, visitor, context); } } function transformJsxChildToExpression(node) { switch (node.kind) { - case 244: + case 10: return visitJsxText(node); - case 248: + case 252: return visitJsxExpression(node); - case 241: + case 246: return visitJsxElement(node, true); - case 242: + case 247: return visitJsxSelfClosingElement(node, true); default: ts.Debug.failBadSyntaxKind(node); @@ -37352,10 +39391,12 @@ var ts; if (ts.isJsxSpreadAttribute(attrs[0])) { segments.unshift(ts.createObjectLiteral()); } - objectProperties = ts.singleOrUndefined(segments) - || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } } - var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -37377,7 +39418,7 @@ var ts; var decoded = tryDecodeEntities(node.text); return decoded ? ts.createLiteral(decoded, node) : node; } - else if (node.kind === 248) { + else if (node.kind === 252) { return visitJsxExpression(node); } else { @@ -37442,7 +39483,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 241) { + if (node.kind === 246) { return getTagName(node.openingElement); } else { @@ -37469,325 +39510,2196 @@ var ts; } } ts.transformJsx = transformJsx; - function createEntitiesMap() { - return ts.createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + var entities = ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); })(ts || (ts = {})); var ts; (function (ts) { - function transformES7(context) { + function transformES2017(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var currentSourceFile; + var enabledSubstitutions; + var currentSuperContainer; + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16) === 0) { + return node; + } + switch (node.kind) { + case 119: + return undefined; + case 189: + return visitAwaitExpression(node); + case 149: + return visitMethodDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 185; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, asyncSuperHelper); + } + } + return block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements)); + } + return expression; + } + } + function transformFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); + var declarations = endLexicalEnvironment(); + return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(179); + context.enableSubstitution(177); + context.enableSubstitution(178); + context.enableEmitNotification(226); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(150); + } + } + function substituteExpression(node) { + switch (node.kind) { + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); + case 179: + if (enabledSubstitutions & 1) { + return substituteCallExpression(node); + } + break; + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 226 + || kind === 150 + || kind === 149 + || kind === 151 + || kind === 152; + } + function onEmitNode(emitContext, node, emitCallback) { + if (enabledSubstitutions & 1 && isSuperContainer(node)) { + var savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformES2017 = transformES2017; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(38), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: "\n const _super = name => super[name];" + }; + var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if (node.transformFlags & 16) { - return visitorWorker(node); + if ((node.transformFlags & 32) === 0) { + return node; } - else if (node.transformFlags & 32) { + switch (node.kind) { + case 192: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 61: + return visitExponentiationAssignmentExpression(node); + case 39: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + function visitExponentiationExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var isInConstructorWithCapturedSuper; + var convertedLoopState; + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + isInConstructorWithCapturedSuper = false; + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 185) { + enclosingNonArrowFunction = currentNode; + if (!(ts.getEmitFlags(currentNode) & 131072)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 205: + enclosingVariableStatement = currentNode; + break; + case 224: + case 223: + case 174: + case 172: + case 173: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return isInConstructorWithCapturedSuper && node.kind === 216 && !node.expression; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64) !== 0 || + node.kind === 219 || + (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128 || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) { return ts.visitEachChild(node, visitor, context); } else { return node; } } - function visitorWorker(node) { + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 187: - return visitBinaryExpression(node); + case 216: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; + return visitReturnStatement(node); + case 205: + return visitVariableStatement(node); + case 218: + return visitSwitchStatement(node); + case 215: + case 214: + return visitBreakOrContinueStatement(node); + case 98: + return visitThisKeyword(node); + case 70: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 114: + return undefined; + case 226: + return visitClassDeclaration(node); + case 197: + return visitClassExpression(node); + case 144: + return visitParameter(node); + case 225: + return visitFunctionDeclaration(node); + case 185: + return visitArrowFunction(node); + case 184: + return visitFunctionExpression(node); + case 223: + return visitVariableDeclaration(node); + case 70: + return visitIdentifier(node); + case 224: + return visitVariableDeclarationList(node); + case 219: + return visitLabeledStatement(node); + case 209: + return visitDoStatement(node); + case 210: + return visitWhileStatement(node); + case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 213: + return visitForOfStatement(node); + case 207: + return visitExpressionStatement(node); + case 176: + return visitObjectLiteralExpression(node); + case 256: + return visitCatchClause(node); + case 258: + return visitShorthandPropertyAssignment(node); + case 175: + return visitArrayLiteralExpression(node); + case 179: + return visitCallExpression(node); + case 180: + return visitNewExpression(node); + case 183: + return visitParenthesizedExpression(node, true); + case 192: + return visitBinaryExpression(node, true); + case 12: + case 13: + case 14: + case 15: + return visitTemplateLiteral(node); + case 181: + return visitTaggedTemplateExpression(node); + case 194: + return visitTemplateExpression(node); + case 195: + return visitYieldExpression(node); + case 196: + return visitSpreadElement(node); + case 96: + return visitSuperKeyword(); + case 195: + return ts.visitEachChild(node, visitor, context); + case 149: + return visitMethodDeclaration(node); + case 205: + return visitVariableStatement(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function visitBinaryExpression(node) { - var left = ts.visitNode(node.left, visitor, ts.isExpression); - var right = ts.visitNode(node.right, visitor, ts.isExpression); - if (node.operatorToken.kind === 60) { - var target = void 0; - var value = void 0; - if (ts.isElementAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); - value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); - } - else if (ts.isPropertyAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); - value = ts.createPropertyAccess(expressionTemp, left.name, left); - } - else { - target = left; - value = left; - } - return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + function visitSourceFile(node) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 185) { + convertedLoopState.containsLexicalThis = true; + return node; } - else if (node.operatorToken.kind === 38) { - return ts.createMathPow(left, right, node); + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; } - else { - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + var jump = node.kind === 215 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 215) { + convertedLoopState.nonLocalJumps |= 2; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4; + labelMarker = "continue"; + } + } + else { + if (node.kind === 215) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 25, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 25, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + var variable = ts.createVariableDeclaration(ts.getLocalName(node, true), undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([variable]), node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + if (ts.hasModifier(node, 1)) { + var exportStatement = ts.hasModifier(node, 512) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 2097152) === 0) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 2097152); + } + return ts.singleOrMany(statements); + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (ts.getEmitFlags(node) & 32768) { + ts.setEmitFlags(classFunction, 32768); + } + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536); + return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 17); + var localName = ts.getLocalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); + ts.setEmitFlags(block, 1536); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)), extendsClauseElement)); } } + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8); + } + statements.push(constructorFunction); + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; + } + if (constructor) { + var body = saveStateAndInvoke(constructor, function (constructor) { + isInConstructorWithCapturedSuper = superCaptureStatus === 1; + return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); + }); + ts.addRange(statements, body); + } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); + if (!constructor) { + ts.setEmitFlags(block, 1536); + } + return block; + } + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 216) { + return true; + } + else if (statement.kind === 208) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 204) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 207 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (16384 | 32768))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 192 + || superCallExpression.left.kind !== 179) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); + statements.push(returnStatement); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, ts.getGeneratedNameForNode(node), undefined, undefined, undefined, node), node); + } + else if (node.initializer) { + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, node.name, undefined, undefined, undefined, node), node); + } + else { + return node; + } + } + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 131072) !== 0; + } + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_36 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_36)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_36, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_36, initializer); + } + } + } + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); + } + } + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer)), parameter)) + ], parameter), 1 | 32 | 384), undefined, parameter); + statement.startsOnNewLine = true; + ts.setEmitFlags(statement, 384 | 32 | 524288); + statements.push(statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 70 && !inConstructorWithSynthesizedSuper; + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48); + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) + ]), parameter), 524288)); + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ])); + ts.setEmitFlags(forStatement, 524288); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 32768 && node.kind !== 185) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 203: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 149: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 151: + case 152: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 150: + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(member); + } + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); + var memberFunction = transformFunctionLikeToExpression(member, member, undefined); + ts.setEmitFlags(memberFunction, 1536); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction), member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 48); + return statement; + } + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 1536); + return statement; + } + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 | 32); + ts.setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 | 16); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, undefined, true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 16384) { + enableSubstitutionsForCapturedThis(); + } + var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8); + return func; + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 185) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + function transformFunctionBody(node) { + var multiLine = false; + var singleLine = false; + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, false); + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 185); + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, body); + ts.setEmitFlags(returnStatement, 384 | 32 | 1024); + statements.push(returnStatement); + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 17, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + function visitExpressionStatement(node) { + switch (node.expression.kind) { + case 183: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); + case 192: + return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, needsDestructuringValue) { + if (!needsDestructuringValue) { + switch (node.expression.kind) { + case 183: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); + case 192: + return ts.updateParen(node, visitBinaryExpression(node.expression, false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitBinaryExpression(node, needsDestructuringValue) { + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0, needsDestructuringValue); + } + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); + } + else { + assignment = ts.createBinary(decl.name, 57, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25, acc); }), node); + } + else { + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclarationList(node) { + if (node.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, node); + ts.setOriginalNode(declarationList, node); + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 8388608 + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 212 + && enclosingBlockScopeContainer.kind !== 213 + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, false))); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_3 = ts.getMutableClone(node); + clone_3.initializer = ts.createVoidZero(); + return clone_3; + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name)) { + var hoistTempVariables = enclosingVariableStatement + && ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenDestructuringBinding(node, visitor, context, 0, undefined, hoistTempVariables); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 70 + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(undefined); + var elementAccess = ts.createElementAccess(rhsReference, counter); + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, elementAccess); + var declarationList = ts.createVariableDeclarationList(declarations, initializer); + ts.setOriginalNode(declarationList, initializer); + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement(undefined, declarationList)); + } + else { + statements.push(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) + ], ts.moveRangePos(initializer, -1)), initializer), ts.moveRangeEnd(initializer, -1))); + } + } + else { + var assignment = ts.createAssignment(initializer, elementAccess); + if (ts.isDestructuringAssignment(assignment)) { + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0))); + } + else { + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + ts.setEmitFlags(expression, 48 | ts.getEmitFlags(expression)); + var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); + ts.setEmitFlags(body, 48 | 384); + var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) + ], node.expression), 1048576), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + ts.setEmitFlags(forStatement, 256); + return forStatement; + } + function visitObjectLiteralExpression(node) { + var properties = node.properties; + var numProperties = properties.length; + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 16777216 + || property.name.kind === 142) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 32768)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 70) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 | 4; + } + var result = convert ? convert(node, undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 211: + case 212: + case 213: + var initializer = node.initializer; + if (initializer && initializer.kind === 224) { + loopInitializer = initializer; + } + break; + } + var loopParameters = []; + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + if (outerConvertedLoopState.argumentsName) { + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + startLexicalEnvironment(); + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length || lexicalEnvironment) { + var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); + loopBody = ts.createBlock(statements_4, undefined, true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], undefined, true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072) !== 0 + && (node.statement.transformFlags & 16777216) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 8; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 131072; + } + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, isAsyncBlockContainingAwait ? ts.createToken(38) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ]), 1048576)); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + if (currentState.argumentsName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + if (outerConvertedLoopState) { + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + if (outerConvertedLoopState) { + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + loop.statement = undefined; + loop = ts.visitEachChild(loop, visitor, context); + loop.statement = ts.createBlock(convertedLoopBodyStatements, undefined, true); + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 219 + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 57, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + var isSimpleLoop = !(state.nonLocalJumps & ~4) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0, statements); + if (state.nonLocalJumps & 8) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 33, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 33, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); + if (resolver.getNodeCheckFlags(decl) & 2097152) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 151: + case 152: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 257: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 258: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 149: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitCatchClause(node) { + ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name)); + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0, temp); + var list = ts.createVariableDeclarationList(vars, node.variableDeclaration, node.variableDeclaration.flags); + var destructure = ts.createVariableStatement(undefined, list); + return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + function visitMethodDeclaration(node) { + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); + ts.setEmitFlags(functionExpression, 512 | ts.getEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, node); + } + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), node); + } + function visitYieldExpression(node) { + return ts.visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + } + function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 96) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall; + if (node.transformFlags & 524288) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + if (node.expression.kind === 96) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; + } + function visitNewExpression(node) { + ts.Debug.assert((node.transformFlags & 524288) !== 0); + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + } + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpread(node) { + return ts.isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, node); + } + function visitTaggedTemplateExpression(node) { + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + var temp = ts.createTempVariable(hoistVariableDeclaration); + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, undefined, templateArguments) + ])); + } + function getRawLiteral(node) { + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var isLast = node.kind === 12 || node.kind === 15; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, node); + } + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + function shouldAddTemplateHead(node) { + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + function visitSuperKeyword() { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) + && currentParent.kind !== 179 + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + function onEmitNode(emitContext, node, emitCallback) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { + enclosingFunction = node; + } + previousOnEmitNode(emitContext, node, emitCallback); + enclosingFunction = savedEnclosingFunction; + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2) === 0) { + enabledSubstitutions |= 2; + context.enableSubstitution(70); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(98); + context.enableEmitNotification(150); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(185); + context.enableEmitNotification(184); + context.enableEmitNotification(225); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 174: + case 226: + case 229: + case 223: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 70: + return substituteExpressionIdentifier(node); + case 98: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 + && enclosingFunction + && ts.getEmitFlags(enclosingFunction) & 8) { + return ts.createIdentifier("_this", node); + } + return node; + } + function getClassMemberPrefix(node, member) { + var expression = ts.getLocalName(node); + return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 96) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.text === "arguments"; + } } - ts.transformES7 = transformES7; + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), undefined, [ + name, + ts.createIdentifier("_super") + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -37797,10 +41709,9 @@ var ts; _a[4] = "yield", _a[5] = "yield*", _a[7] = "endfinally", - _a - )); + _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -37834,12 +41745,15 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (node.transformFlags & 1024) { - currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); - currentSourceFile = undefined; + if (ts.isDeclarationFile(node) + || (node.transformFlags & 512) === 0) { + return node; } - return node; + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function visitor(node) { var transformFlags = node.transformFlags; @@ -37849,10 +41763,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 512) { + else if (transformFlags & 256) { return visitGenerator(node); } - else if (transformFlags & 1024) { + else if (transformFlags & 512) { return ts.visitEachChild(node, visitor, context); } else { @@ -37861,13 +41775,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 204: + case 209: return visitDoStatement(node); - case 205: + case 210: return visitWhileStatement(node); - case 213: + case 218: return visitSwitchStatement(node); - case 214: + case 219: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -37875,30 +41789,30 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); - case 149: - case 150: + case 151: + case 152: return visitAccessorDeclaration(node); - case 200: + case 205: return visitVariableStatement(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 210: - return visitBreakStatement(node); - case 209: - return visitContinueStatement(node); case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 215: + return visitBreakStatement(node); + case 214: + return visitContinueStatement(node); + case 216: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 | 8388608)) { + else if (node.transformFlags & (512 | 33554432)) { return ts.visitEachChild(node, visitor, context); } else { @@ -37908,21 +41822,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 187: + case 192: return visitBinaryExpression(node); - case 188: + case 193: return visitConditionalExpression(node); - case 190: + case 195: return visitYieldExpression(node); - case 170: - return visitArrayLiteralExpression(node); - case 171: - return visitObjectLiteralExpression(node); - case 173: - return visitElementAccessExpression(node); - case 174: - return visitCallExpression(node); case 175: + return visitArrayLiteralExpression(node); + case 176: + return visitObjectLiteralExpression(node); + case 178: + return visitElementAccessExpression(node); + case 179: + return visitCallExpression(node); + case 180: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -37930,9 +41844,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -37940,8 +41854,8 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -37961,8 +41875,8 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -37992,6 +41906,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -38004,6 +41919,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -38011,7 +41927,7 @@ var ts; operationArguments = undefined; operationLocations = undefined; state = ts.createTempVariable(undefined); - startLexicalEnvironment(); + resumeLexicalEnvironment(); var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); @@ -38022,6 +41938,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -38032,12 +41949,12 @@ var ts; return ts.createBlock(statements, body, body.multiLine); } function visitVariableStatement(node) { - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 524288) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -38062,23 +41979,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 57 - && kind <= 68; + return kind >= 58 + && kind <= 69; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 57: return 35; case 58: return 36; case 59: return 37; case 60: return 38; case 61: return 39; case 62: return 40; - case 63: return 43; + case 63: return 41; case 64: return 44; case 65: return 45; case 66: return 46; case 67: return 47; case 68: return 48; + case 69: return 49; } } function visitRightAssociativeBinaryExpression(node) { @@ -38086,10 +42003,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 172: + case 177: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 173: + case 178: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -38098,7 +42015,7 @@ var ts; } var operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + return ts.createBinary(target, 57, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); } else { return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); @@ -38111,13 +42028,13 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 24) { + else if (node.operatorToken.kind === 25) { return visitCommaExpression(node); } - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -38125,7 +42042,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { emitBreakWhenFalse(resultLabel, resultLocal, node.left); } else { @@ -38141,7 +42058,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 25) { visit(node.left); visit(node.right); } @@ -38182,26 +42099,30 @@ var ts; return createGeneratorResume(); } function visitArrayLiteralExpression(node) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, undefined, undefined, node.multiLine); } - function visitElements(elements, multiLine) { + function visitElements(elements, leadingElement, location, multiLine) { var numInitialElements = countInitialNodesWithoutYield(elements); var temp = declareLocal(); var hasAssignedTemp = false; if (numInitialElements > 0) { - emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; hasAssignedTemp = true; } var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine); function reduceElement(expressions, element) { if (containsYield(element) && expressions.length > 0) { emitAssignment(temp, hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions)); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, undefined, multiLine)); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } expressions.push(ts.visitNode(element, visitor, ts.isExpression)); @@ -38235,24 +42156,24 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, ts.createVoidZero())), undefined, [], node), node); } return ts.visitEachChild(node, visitor, context); } @@ -38281,35 +42202,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 199: - return transformAndEmitBlock(node); - case 202: - return transformAndEmitExpressionStatement(node); - case 203: - return transformAndEmitIfStatement(node); case 204: - return transformAndEmitDoStatement(node); - case 205: - return transformAndEmitWhileStatement(node); - case 206: - return transformAndEmitForStatement(node); + return transformAndEmitBlock(node); case 207: - return transformAndEmitForInStatement(node); + return transformAndEmitExpressionStatement(node); + case 208: + return transformAndEmitIfStatement(node); case 209: - return transformAndEmitContinueStatement(node); + return transformAndEmitDoStatement(node); case 210: - return transformAndEmitBreakStatement(node); + return transformAndEmitWhileStatement(node); case 211: - return transformAndEmitReturnStatement(node); + return transformAndEmitForStatement(node); case 212: - return transformAndEmitWithStatement(node); - case 213: - return transformAndEmitSwitchStatement(node); + return transformAndEmitForInStatement(node); case 214: - return transformAndEmitLabeledStatement(node); + return transformAndEmitContinueStatement(node); case 215: - return transformAndEmitThrowStatement(node); + return transformAndEmitBreakStatement(node); case 216: + return transformAndEmitReturnStatement(node); + case 217: + return transformAndEmitWithStatement(node); + case 218: + return transformAndEmitSwitchStatement(node); + case 219: + return transformAndEmitLabeledStatement(node); + case 220: + return transformAndEmitThrowStatement(node); + case 221: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); @@ -38593,7 +42514,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 250 && defaultClauseIndex === -1) { + if (clause.kind === 254 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -38603,7 +42524,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 249) { + if (clause.kind === 253) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -38694,7 +42615,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 4194304) !== 0; + return node && (node.transformFlags & 16777216) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -38705,9 +42626,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -38724,12 +42645,12 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); - return clone_7; + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_6 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -38835,7 +42756,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = ts.createMap(); - context.enableSubstitution(69); + context.enableSubstitution(70); } renamedCatchVariables[text] = true; renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -39025,7 +42946,7 @@ var ts; if (labelExpressions === undefined) { labelExpressions = []; } - var expression = ts.createSynthesizedNode(8); + var expression = ts.createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -39034,7 +42955,7 @@ var ts; } return expression; } - return ts.createNode(193); + return ts.createOmittedExpression(); } function createInstruction(instruction) { var literal = ts.createLiteral(instruction); @@ -39120,10 +43041,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ - ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) - ]); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 262144)); } function buildStatements() { if (operations) { @@ -39386,1569 +43304,1660 @@ var ts; } } ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]); + } + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; var _a; })(ts || (ts = {})); var ts; (function (ts) { - function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; - var resolver = context.getEmitResolver(); + function transformES5(context) { var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; - var currentText; - var currentParent; - var currentNode; - var enclosingVariableStatement; - var enclosingBlockScopeContainer; - var enclosingBlockScopeContainerParent; - var enclosingFunction; - var enclosingNonArrowFunction; - var enclosingNonAsyncFunctionBody; - var convertedLoopState; - var enabledSubstitutions; + context.enableSubstitution(177); + context.enableSubstitution(257); return transformSourceFile; function transformSourceFile(node) { - currentSourceFile = node; - currentText = node.text; - return ts.visitNode(node, visitor, ts.isSourceFile); + return node; + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.createElementAccess(node.expression, literalName, node); + } + return node; + } + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + if (token >= 71 && token <= 106) { + return ts.createLiteral(name, name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(261); + context.enableSubstitution(70); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements); + ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } + } + return node; } function visitor(node) { - return saveStateAndInvoke(node, dispatcher); - } - function dispatcher(node) { - return convertedLoopState - ? visitorForConvertedLoopWorker(node) - : visitorWorker(node); - } - function saveStateAndInvoke(node, f) { - var savedEnclosingFunction = enclosingFunction; - var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; - var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; - var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; - var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; - var savedEnclosingVariableStatement = enclosingVariableStatement; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var savedConvertedLoopState = convertedLoopState; - if (ts.nodeStartsNewLexicalEnvironment(node)) { - convertedLoopState = undefined; - } - onBeforeVisitNode(node); - var visited = f(node); - convertedLoopState = savedConvertedLoopState; - enclosingFunction = savedEnclosingFunction; - enclosingNonArrowFunction = savedEnclosingNonArrowFunction; - enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; - enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; - enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; - enclosingVariableStatement = savedEnclosingVariableStatement; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return visited; - } - function shouldCheckNode(node) { - return (node.transformFlags & 64) !== 0 || - node.kind === 214 || - (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); - } - function visitorWorker(node) { - if (shouldCheckNode(node)) { - return visitJavaScript(node); - } - else if (node.transformFlags & 128) { - return ts.visitEachChild(node, visitor, context); - } - else { - return node; - } - } - function visitorForConvertedLoopWorker(node) { - var result; - if (shouldCheckNode(node)) { - result = visitJavaScript(node); - } - else { - result = visitNodesInConvertedLoop(node); - } - return result; - } - function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 211: - return visitReturnStatement(node); - case 200: - return visitVariableStatement(node); - case 213: - return visitSwitchStatement(node); - case 210: - case 209: - return visitBreakOrContinueStatement(node); - case 97: - return visitThisKeyword(node); - case 69: - return visitIdentifier(node); - default: - return ts.visitEachChild(node, visitor, context); - } - } - function visitJavaScript(node) { - switch (node.kind) { - case 82: - return node; - case 221: - return visitClassDeclaration(node); - case 192: - return visitClassExpression(node); - case 142: - return visitParameter(node); - case 220: - return visitFunctionDeclaration(node); - case 180: - return visitArrowFunction(node); - case 179: - return visitFunctionExpression(node); - case 218: - return visitVariableDeclaration(node); - case 69: - return visitIdentifier(node); - case 219: - return visitVariableDeclarationList(node); - case 214: - return visitLabeledStatement(node); - case 204: - return visitDoStatement(node); - case 205: - return visitWhileStatement(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 208: - return visitForOfStatement(node); - case 202: - return visitExpressionStatement(node); - case 171: - return visitObjectLiteralExpression(node); - case 254: - return visitShorthandPropertyAssignment(node); - case 170: - return visitArrayLiteralExpression(node); - case 174: - return visitCallExpression(node); - case 175: - return visitNewExpression(node); - case 178: - return visitParenthesizedExpression(node, true); - case 187: - return visitBinaryExpression(node, true); - case 11: - case 12: - case 13: - case 14: - return visitTemplateLiteral(node); - case 176: - return visitTaggedTemplateExpression(node); - case 189: - return visitTemplateExpression(node); - case 190: - return visitYieldExpression(node); - case 95: - return visitSuperKeyword(node); - case 190: - return ts.visitEachChild(node, visitor, context); - case 147: - return visitMethodDeclaration(node); - case 256: - return visitSourceFileNode(node); - case 200: - return visitVariableStatement(node); - default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); - } - } - function onBeforeVisitNode(node) { - if (currentNode) { - if (ts.isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - if (ts.isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== 180) { - enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - switch (currentNode.kind) { - case 200: - enclosingVariableStatement = currentNode; - break; - case 219: - case 218: - case 169: - case 167: - case 168: - break; - default: - enclosingVariableStatement = undefined; - } - } - currentParent = currentNode; - currentNode = node; - } - function visitSwitchStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps |= 2; - var result = ts.visitEachChild(node, visitor, context); - convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; - return result; - } - function visitReturnStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - convertedLoopState.nonLocalJumps |= 8; - return ts.createReturn(ts.createObjectLiteral([ - ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression - ? ts.visitNode(node.expression, visitor, ts.isExpression) - : ts.createVoidZero()) - ])); - } - function visitThisKeyword(node) { - ts.Debug.assert(convertedLoopState !== undefined); - if (enclosingFunction && enclosingFunction.kind === 180) { - convertedLoopState.containsLexicalThis = true; - return node; - } - return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); - } - function visitIdentifier(node) { - if (!convertedLoopState) { - return node; - } - if (ts.isGeneratedIdentifier(node)) { - return node; - } - if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { - return node; - } - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); - } - function visitBreakOrContinueStatement(node) { - if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - var labelMarker = void 0; - if (!node.label) { - if (node.kind === 210) { - convertedLoopState.nonLocalJumps |= 2; - labelMarker = "break"; - } - else { - convertedLoopState.nonLocalJumps |= 4; - labelMarker = "continue"; - } - } - else { - if (node.kind === 210) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); - } - } - var returnExpression = ts.createLiteral(labelMarker); - if (convertedLoopState.loopOutParameters.length) { - var outParams = convertedLoopState.loopOutParameters; - var expr = void 0; - for (var i = 0; i < outParams.length; i++) { - var copyExpr = copyOutParameter(outParams[i], 1); - if (i === 0) { - expr = copyExpr; - } - else { - expr = ts.createBinary(expr, 24, copyExpr); - } - } - returnExpression = ts.createBinary(expr, 24, returnExpression); - } - return ts.createReturn(returnExpression); - } - } - return ts.visitEachChild(node, visitor, context); - } - function visitClassDeclaration(node) { - var modifierFlags = ts.getModifierFlags(node); - var isExported = modifierFlags & 1; - var isDefault = modifierFlags & 512; - var modifiers = isExported && !isDefault - ? ts.filter(node.modifiers, isExportModifier) - : undefined; - var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) - ]), node); - ts.setOriginalNode(statement, node); - ts.startOnNewLine(statement); - if (isExported && isDefault) { - var statements = [statement]; - statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); - return statements; - } - return statement; - } - function isExportModifier(node) { - return node.kind === 82; - } - function visitClassExpression(node) { - return transformClassLikeDeclarationToExpression(node); - } - function transformClassLikeDeclarationToExpression(node) { - if (node.name) { - enableSubstitutionsForBlockScopedBindings(); - } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); - } - var inner = ts.createPartiallyEmittedExpression(classFunction); - inner.end = node.end; - setNodeEmitFlags(inner, 49152); - var outer = ts.createPartiallyEmittedExpression(inner); - outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); - return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement - ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] - : [])); - } - function transformClassBody(node, extendsClauseElement) { - var statements = []; - startLexicalEnvironment(); - addExtendsHelperIfNeeded(statements, node, extendsClauseElement); - addConstructor(statements, node, extendsClauseElement); - addClassMembers(statements, node); - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); - var localName = getLocalName(node); - var outer = ts.createPartiallyEmittedExpression(localName); - outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); - var statement = ts.createReturn(outer); - statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); - statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); - return block; - } - function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { - if (extendsClauseElement) { - statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); - } - } - function addConstructor(statements, node, extendsClauseElement) { - var constructor = ts.getFirstConstructorWithBody(node); - var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); - } - function transformConstructorParameters(constructor, hasSynthesizedSuper) { - if (constructor && !hasSynthesizedSuper) { - return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); - } - return []; - } - function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - startLexicalEnvironment(); - if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); - if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); - ts.addRange(statements, body); - } - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); - if (!constructor) { - setNodeEmitFlags(block, 49152); - } - return block; - } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); - } - } - function visitParameter(node) { - if (node.dotDotDotToken) { - return undefined; - } - else if (ts.isBindingPattern(node.name)) { - return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); - } - else if (node.initializer) { - return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); - } - else { - return node; - } - } - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536) !== 0; - } - function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; - if (dotDotDotToken) { - continue; - } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); - } - else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); - } - } - } - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); - if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); - } - else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); - } - } - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { - initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) - ], parameter), 32 | 1024 | 12288), undefined, parameter); - statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); - statements.push(statement); - } - function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; - } - function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { - var parameter = ts.lastOrUndefined(node.parameters); - if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; - } - var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); - var expressionName = ts.getSynthesizedClone(parameter.name); - var restIndex = node.parameters.length - 1; - var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ]), parameter), 8388608)); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) - ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ - ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) - ])); - setNodeEmitFlags(forStatement, 8388608); - ts.startOnNewLine(forStatement); - statements.push(forStatement); - } - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); - } - } - function addClassMembers(statements, node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 198: - statements.push(transformSemicolonClassElementToStatement(member)); - break; - case 147: - statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); - break; - case 149: - case 150: - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); - } - break; - case 148: - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - function transformSemicolonClassElementToStatement(member) { - return ts.createEmptyStatement(member); - } - function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); - var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); - var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); - ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); - return statement; - } - function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); - return statement; - } - function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { - var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); - var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); - var properties = []; - if (getAccessor) { - var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); - var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); - properties.push(getter); - } - if (setAccessor) { - var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); - var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); - properties.push(setter); - } - properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); - var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - target, - propertyName, - ts.createObjectLiteral(properties, undefined, true) - ]); - if (startsOnNewLine) { - call.startsOnNewLine = true; - } - return call; - } - function visitArrowFunction(node) { - if (node.transformFlags & 8192) { - enableSubstitutionsForCapturedThis(); - } - var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); - return func; - } - function visitFunctionExpression(node) { - return transformFunctionLikeToExpression(node, node, node.name); - } - function visitFunctionDeclaration(node) { - return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); - } - function transformFunctionLikeToExpression(node, location, name) { - var savedContainingNonArrowFunction = enclosingNonArrowFunction; - if (node.kind !== 180) { - enclosingNonArrowFunction = node; - } - var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); - enclosingNonArrowFunction = savedContainingNonArrowFunction; - return expression; - } - function transformFunctionBody(node) { - var multiLine = false; - var singleLine = false; - var statementsLocation; - var closeBraceLocation; - var statements = []; - var body = node.body; - var statementOffset; - startLexicalEnvironment(); - if (ts.isBlock(body)) { - statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, false); - if (!multiLine && statements.length > 0) { - multiLine = true; - } - if (ts.isBlock(body)) { - statementsLocation = body.statements; - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); - if (!multiLine && body.multiLine) { - multiLine = true; - } - } - else { - ts.Debug.assert(node.kind === 180); - statementsLocation = ts.moveRangeEnd(body, -1); - var equalsGreaterThanToken = node.equalsGreaterThanToken; - if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { - if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { - singleLine = true; - } - else { - multiLine = true; - } - } - var expression = ts.visitNode(body, visitor, ts.isExpression); - var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); - statements.push(returnStatement); - closeBraceLocation = body; - } - var lexicalEnvironment = endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { - multiLine = true; - } - var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); - if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); - } - if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); - } - ts.setOriginalNode(block, node.body); - return block; - } - function visitExpressionStatement(node) { - switch (node.expression.kind) { - case 178: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 187: - return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); - } - return ts.visitEachChild(node, visitor, context); - } - function visitParenthesizedExpression(node, needsDestructuringValue) { - if (needsDestructuringValue) { - switch (node.expression.kind) { - case 178: - return ts.createParen(visitParenthesizedExpression(node.expression, true), node); - case 187: - return ts.createParen(visitBinaryExpression(node.expression, true), node); - } - } - return ts.visitEachChild(node, visitor, context); - } - function visitBinaryExpression(node, needsDestructuringValue) { - ts.Debug.assert(ts.isDestructuringAssignment(node)); - return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); - } - function visitVariableStatement(node) { - if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { - var assignments = void 0; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); - if (decl.initializer) { - var assignment = void 0; - if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); - } - else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); - } - (assignments || (assignments = [])).push(assignment); - } - } - if (assignments) { - return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); - } - else { + case 234: return undefined; - } - } - return ts.visitEachChild(node, visitor, context); - } - function visitVariableDeclarationList(node) { - if (node.flags & 3) { - enableSubstitutionsForBlockScopedBindings(); - } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 - ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); - var declarationList = ts.createVariableDeclarationList(declarations, node); - ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { - var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - } - return declarationList; - } - function shouldEmitExplicitInitializerForLetDeclaration(node) { - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) - || (isCapturedInFunction - && isDeclaredInLoop - && ts.isBlock(enclosingBlockScopeContainer) - && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); - var emitExplicitInitializer = !emittedAsTopLevel - && enclosingBlockScopeContainer.kind !== 207 - && enclosingBlockScopeContainer.kind !== 208 - && (!resolver.isDeclarationWithCollidingName(node) - || (isDeclaredInLoop - && !isCapturedInFunction - && !ts.isIterationStatement(enclosingBlockScopeContainer, false))); - return emitExplicitInitializer; - } - function visitVariableDeclarationInLetDeclarationList(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return visitVariableDeclaration(node); - } - if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_8 = ts.getMutableClone(node); - clone_8.initializer = ts.createVoidZero(); - return clone_8; - } - return ts.visitEachChild(node, visitor, context); - } - function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - var recordTempVariablesInLine = !enclosingVariableStatement - || !ts.hasModifier(enclosingVariableStatement, 1); - return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); - } - return ts.visitEachChild(node, visitor, context); - } - function visitLabeledStatement(node) { - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - var result; - if (ts.isIterationStatement(node.statement, false) && shouldConvertIterationStatementBody(node.statement)) { - result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); - } - else { - result = ts.visitEachChild(node, visitor, context); - } - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - return result; - } - function visitDoStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitWhileStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForInStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForOfStatement(node) { - return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); - } - function convertForOfToFor(node, convertedLoopBodyStatements) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - var initializer = node.initializer; - var statements = []; - var counter = ts.createLoopVariable(); - var rhsReference = expression.kind === 69 - ? ts.createUniqueName(expression.text) - : ts.createTempVariable(undefined); - if (ts.isVariableDeclarationList(initializer)) { - if (initializer.flags & 3) { - enableSubstitutionsForBlockScopedBindings(); - } - var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); - if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); - var declarationList = ts.createVariableDeclarationList(declarations, initializer); - ts.setOriginalNode(declarationList, initializer); - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - statements.push(ts.createVariableStatement(undefined, declarationList)); - } - else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) - ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); - } - } - else { - var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); - if (ts.isDestructuringAssignment(assignment)) { - statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); - } - else { - assignment.end = initializer.end; - statements.push(ts.createStatement(assignment, ts.moveRangeEnd(initializer, -1))); - } - } - var bodyLocation; - var statementsLocation; - if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); - } - else { - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); - if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; - } - else { - statements.push(statement); - } - } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); - var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), - ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) - ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); - return forStatement; - } - function visitObjectLiteralExpression(node) { - var properties = node.properties; - var numProperties = properties.length; - var numInitialProperties = numProperties; - for (var i = 0; i < numProperties; i++) { - var property = properties[i]; - if (property.transformFlags & 4194304 - || property.name.kind === 140) { - numInitialProperties = i; - break; - } - } - ts.Debug.assert(numInitialProperties !== numProperties); - var temp = ts.createTempVariable(hoistVariableDeclaration); - var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); - if (node.multiLine) { - assignment.startsOnNewLine = true; - } - expressions.push(assignment); - addObjectLiteralMembers(expressions, node, temp, numInitialProperties); - expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); - return ts.inlineExpressions(expressions); - } - function shouldConvertIterationStatementBody(node) { - return (resolver.getNodeCheckFlags(node) & 65536) !== 0; - } - function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(node.name); - function visit(node) { - if (node.kind === 69) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - visit(element.name); - } - } - } - } - } - function convertIterationStatementBodyIfNecessary(node, convert) { - if (!shouldConvertIterationStatementBody(node)) { - var saveAllowedNonLabeledJumps = void 0; - if (convertedLoopState) { - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 | 4; - } - var result = convert ? convert(node, undefined) : ts.visitEachChild(node, visitor, context); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - return result; - } - var functionName = ts.createUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206: - case 207: - case 208: - var initializer = node.initializer; - if (initializer && initializer.kind === 219) { - loopInitializer = initializer; - } - break; - } - var loopParameters = []; - var loopOutParameters = []; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { - for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); - } - } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - if (outerConvertedLoopState.argumentsName) { - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; - } - if (outerConvertedLoopState.thisName) { - convertedLoopState.thisName = outerConvertedLoopState.thisName; - } - if (outerConvertedLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; - } - } - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { - var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_3); - loopBody = ts.createBlock(statements_3, undefined, true); - } - if (!ts.isBlock(loopBody)) { - loopBody = ts.createBlock([loopBody], undefined, true); - } - var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 - && (node.statement.transformFlags & 4194304) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 256; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 2097152; - } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ])); - var statements = [convertedLoopVariable]; - var extraVariableDeclarations; - if (currentState.argumentsName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.argumentsName = currentState.argumentsName; - } - else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); - } - } - if (currentState.thisName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.thisName = currentState.thisName; - } - else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); - } - } - if (currentState.hoistedLocalVariables) { - if (outerConvertedLoopState) { - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; - } - else { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; - extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); - } - } - } - if (loopOutParameters.length) { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; - extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); - } - } - if (extraVariableDeclarations) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); - } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); - var loop; - if (convert) { - loop = convert(node, convertedLoopBodyStatements); - } - else { - loop = ts.getMutableClone(node); - loop.statement = undefined; - loop = ts.visitEachChild(loop, visitor, context); - loop.statement = ts.createBlock(convertedLoopBodyStatements, undefined, true); - loop.transformFlags = 0; - ts.aggregateTransformFlags(loop); - } - statements.push(currentParent.kind === 214 - ? ts.createLabel(currentParent.label, loop) - : loop); - return statements; - } - function copyOutParameter(outParam, copyDirection) { - var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; - var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 56, source); - } - function copyOutParameters(outParams, copyDirection, statements) { - for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { - var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); - } - } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; - var statements = []; - var isSimpleLoop = !(state.nonLocalJumps & ~4) && - !state.labeledNonLocalBreaks && - !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; - if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0, statements); - } - else { - var loopResultName = ts.createUniqueName("state"); - var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); - statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0, statements); - if (state.nonLocalJumps & 8) { - var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8; - returnStatement = ts.createReturn(loopResultName); - } - else { - returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); - } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); - } - if (state.nonLocalJumps & 2) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); - } - if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { - var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); - statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); - } - } - return statements; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - var statements = []; - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - var label = ts.createIdentifier(labelText); - statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - statements.push(ts.createReturn(loopResultName)); - } - caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); - } - } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { - var name = decl.name; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); - } - } - } - else { - loopParameters.push(ts.createParameter(name)); - if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + name.text); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); - } - } - } - function addObjectLiteralMembers(expressions, node, receiver, start) { - var properties = node.properties; - var numProperties = properties.length; - for (var i = start; i < numProperties; i++) { - var property = properties[i]; - switch (property.kind) { - case 149: - case 150: - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); - } - break; - case 253: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 254: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 147: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - function visitMethodDeclaration(node) { - ts.Debug.assert(!ts.isComputedPropertyName(node.name)); - var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); - return ts.createPropertyAssignment(node.name, functionExpression, node); - } - function visitShorthandPropertyAssignment(node) { - return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), node); - } - function visitYieldExpression(node) { - return ts.visitEachChild(node, visitor, context); - } - function visitArrayLiteralExpression(node) { - return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); - } - function visitCallExpression(node) { - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); - } - else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); - } - } - function visitNewExpression(node) { - ts.Debug.assert((node.transformFlags & 262144) !== 0); - var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); - } - function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { - var numElements = elements.length; - var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { - return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); - })); - if (segments.length === 1) { - var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 - ? ts.createArraySlice(segments[0]) - : segments[0]; - } - return ts.createArrayConcat(segments.shift(), segments); - } - function partitionSpreadElement(node) { - return ts.isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; - } - function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.map(chunk, visitExpressionOfSpreadElement); - } - function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); - } - function visitExpressionOfSpreadElement(node) { - return ts.visitNode(node.expression, visitor, ts.isExpression); - } - function visitTemplateLiteral(node) { - return ts.createLiteral(node.text, node); - } - function visitTaggedTemplateExpression(node) { - var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - var temp = ts.createTempVariable(hoistVariableDeclaration); - var templateArguments = [temp]; - var cookedStrings = []; - var rawStrings = []; - var template = node.template; - if (ts.isNoSubstitutionTemplateLiteral(template)) { - cookedStrings.push(ts.createLiteral(template.text)); - rawStrings.push(getRawLiteral(template)); - } - else { - cookedStrings.push(ts.createLiteral(template.head.text)); - rawStrings.push(getRawLiteral(template.head)); - for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { - var templateSpan = _a[_i]; - cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); - rawStrings.push(getRawLiteral(templateSpan.literal)); - templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); - } - } - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, undefined, templateArguments) - ])); - } - function getRawLiteral(node) { - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - var isLast = node.kind === 11 || node.kind === 14; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - text = text.replace(/\r\n?/g, "\n"); - return ts.createLiteral(text, node); - } - function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - var expression = ts.reduceLeft(expressions, ts.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - function shouldAddTemplateHead(node) { - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(ts.createLiteral(node.head.text)); - } - function addTemplateSpans(expressions, node) { - for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { - var span_6 = _a[_i]; - expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); - } - } - } - function visitSuperKeyword(node) { - return enclosingNonAsyncFunctionBody - && ts.isClassElement(enclosingNonAsyncFunctionBody) - && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) - && currentParent.kind !== 174 - ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") - : ts.createIdentifier("_super"); - } - function visitSourceFileNode(node) { - var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; - var statements = []; - startLexicalEnvironment(); - ts.addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); - ts.addRange(statements, endLexicalEnvironment()); - var clone = ts.getMutableClone(node); - clone.statements = ts.createNodeArray(statements, node.statements); - return clone; - } - function onEmitNode(node, emit) { - var savedEnclosingFunction = enclosingFunction; - if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { - enclosingFunction = node; - } - previousOnEmitNode(node, emit); - enclosingFunction = savedEnclosingFunction; - } - function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & 2) === 0) { - enabledSubstitutions |= 2; - context.enableSubstitution(69); - } - } - function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(97); - context.enableEmitNotification(148); - context.enableEmitNotification(147); - context.enableEmitNotification(149); - context.enableEmitNotification(150); - context.enableEmitNotification(180); - context.enableEmitNotification(179); - context.enableEmitNotification(220); - } - } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - if (ts.isIdentifier(node)) { - return substituteIdentifier(node); + case 240: + return visitExportAssignment(node); } return node; } - function substituteIdentifier(node) { - if (enabledSubstitutions & 2) { - var original = ts.getParseTreeNode(node, ts.isIdentifier); - if (original && isNameOfDeclarationWithCollidingName(original)) { - return ts.getGeneratedNameForNode(original); - } - } - return node; + function visitExportAssignment(node) { + return node.isExportEquals ? undefined : node; } - function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { - case 169: - case 221: - case 224: - case 218: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + function onEmitNode(emitContext, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); } - return false; } - function substituteExpression(node) { - switch (node.kind) { - case 69: - return substituteExpressionIdentifier(node); - case 97: - return substituteThisKeyword(node); + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isIdentifier(node) && emitContext === 1) { + return substituteExpressionIdentifier(node); } return node; } function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.getGeneratedNameForNode(declaration.name); + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); } } return node; } - function substituteThisKeyword(node) { - if (enabledSubstitutions & 1 - && enclosingFunction - && enclosingFunction.emitFlags & 256) { - return ts.createIdentifier("_this", node); - } - return node; - } - function getLocalName(node, allowComments, allowSourceMaps) { - return getDeclarationName(node, allowComments, allowSourceMaps, 262144); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); - } - return name_39; - } - return ts.getGeneratedNameForNode(node); - } - function getClassMemberPrefix(node, member) { - var expression = getLocalName(node); - return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); - } - function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { - if (!constructor || !hasExtendsClause) { - return false; - } - var parameter = ts.singleOrUndefined(constructor.parameters); - if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { - return false; - } - var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { - return false; - } - var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { - return false; - } - var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { - return false; - } - var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { - return false; - } - var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression === parameter.name; - } } - ts.transformES6 = transformES6; + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); + var exportFunctionsMap = ts.createMap(); + var noSubstitutionMap = ts.createMap(); + var currentSourceFile; + var moduleInfo; + var exportFunction; + var contextObject; + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports"); + contextObject = ts.createUniqueName("context"); + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, exportFunction), + ts.createParameter(undefined, undefined, undefined, contextObject) + ], undefined, moduleBodyBlock); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ], node.statements)), 1024); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); + } + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + function createSystemModuleBody(node, dependencyGroups) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true); + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + ts.addRange(statements, hoistedStatements); + ts.addRange(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + return ts.createBlock(statements, undefined, true); + } + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 241 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + var exportStarFunction_1 = createExportStarFunction(undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.text === "default") { + continue; + } + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true))); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 241) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), undefined, [n]))); + } + return ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(undefined, undefined, undefined, m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1) + ])), + ts.createStatement(ts.createCall(exportFunction, undefined, [exports])) + ], undefined, true)); + } + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 235: + if (!entry.importClause) { + break; + } + case 234: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 241: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return undefined; + case 240: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, true); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + function visitClassDeclaration(node) { + var statements; + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement), node)), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + if (isMarkedDeclaration) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, false); + } + return ts.singleOrMany(statements); + } + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + function shouldHoistVariableDeclarationList(node) { + return (ts.getEmitFlags(node) & 1048576) === 0 + && (enclosingBlockScopedContainer.kind === 261 + || (ts.getOriginalNode(node).flags & 3) === 0); + } + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + } + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, true); + } + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, false); + } + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location))) + : preventSubstitution(ts.createAssignment(name, value, location)); + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = decl.name.text; + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = exportName.text; + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + function createExportStatement(name, value, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + return ts.createCall(exportFunction, undefined, [exportName, value]); + } + function nestedElementVisitor(node) { + switch (node.kind) { + case 205: + return visitVariableStatement(node); + case 225: + return visitFunctionDeclaration(node); + case 226: + return visitClassDeclaration(node); + case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 213: + return visitForOfStatement(node); + case 209: + return visitDoStatement(node); + case 210: + return visitWhileStatement(node); + case 219: + return visitLabeledStatement(node); + case 217: + return visitWithStatement(node); + case 218: + return visitSwitchStatement(node); + case 232: + return visitCaseBlock(node); + case 253: + return visitCaseClause(node); + case 254: + return visitDefaultClause(node); + case 221: + return visitTryStatement(node); + case 256: + return visitCatchClause(node); + case 204: + return visitBlock(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); + default: + return destructuringVisitor(node); + } + } + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + } + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function destructuringVisitor(node) { + if (node.transformFlags & 1024 + && node.kind === 192) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & 2048) { + return ts.visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + } + return ts.visitEachChild(node, destructuringVisitor, context); + } + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 261; + } + else { + return false; + } + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 70: + return substituteExpressionIdentifier(node); + case 192: + return substituteBinaryExpression(node); + case 190: + case 191: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createPrefix(node.operator, node.operand, node) + : node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 191) { + expression = node.operator === 42 + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, false); + if (exportContainer && exportContainer.kind === 261) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = ts.createMap(); + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } + } + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableSubstitution(258); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); + var currentSourceFile; + var currentModuleInfo; + var noSubstitution; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + return ts.aggregateTransformFlags(updated); + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, false); + var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(updated, exportStarHelper); + } + return updated; + } + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, true); + } + function transformUMDModule(node) { + var define = ts.createRawExpression(umdHelper); + return transformAsynchronousModule(node, define, undefined, false); + } + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + return ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ]))) + ], node.statements)); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + ts.setEmitFlags(importAliasName, 4); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, true); + var body = ts.createBlock(statements, undefined, true); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(body, exportStarHelper); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + if (emitAsReturn) { + var statement = ts.createReturn(currentModuleInfo.exportEquals.expression, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression), currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); + statements.push(statement); + } + } + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return visitExportDeclaration(node); + case 240: + return visitExportAssignment(node); + case 205: + return visitVariableStatement(node); + case 225: + return visitFunctionDeclaration(node); + case 226: + return visitClassDeclaration(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); + default: + return node; + } + } + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + return ts.createStatement(createRequireCall(node), node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + } + else { + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, undefined, languageVersion >= 2 ? 2 : 0), node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) + ], undefined, languageVersion >= 2 ? 2 : 0))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)), node)); + } + else { + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) + ], undefined, languageVersion >= 2 ? 2 : 0), node)); + } + } + else { + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)), node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) + ]), node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue), specifier)); + } + return ts.singleOrMany(statements); + } + else { + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), node); + } + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + } + return ts.singleOrMany(statements); + } + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body, node), node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members, node), node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1)) { + var modifiers = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + } + else { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name, node.name), node.initializer); + } + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, exportSpecifier.name); + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, location, allowComments) { + if (exportName.text === "default") { + var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createExportStatement(name, value, location, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value, location) { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location); + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = ts.createMap(); + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === 1) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 70: + return substituteExpressionIdentifier(node); + case 192: + return substituteBinaryExpression(node); + case 191: + case 190: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 261) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name_38 = importDeclaration.propertyName || importDeclaration.name; + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_38), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, node); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 ? 58 : 59), ts.createLiteral(1), node) + : node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + var _a; + } + ts.transformModule = transformModule; + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })"; })(ts || (ts = {})); var ts; (function (ts) { var moduleTransformerMap = ts.createMap((_a = {}, - _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.ES2015] = ts.transformES2015Module, _a[ts.ModuleKind.System] = ts.transformSystemModule, _a[ts.ModuleKind.AMD] = ts.transformModule, _a[ts.ModuleKind.CommonJS] = ts.transformModule, _a[ts.ModuleKind.UMD] = ts.transformModule, _a[ts.ModuleKind.None] = ts.transformModule, - _a - )); + _a)); function getTransformers(compilerOptions) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); var transformers = []; transformers.push(ts.transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); if (jsx === 2) { transformers.push(ts.transformJsx); } - transformers.push(ts.transformES7); + if (languageVersion < 5) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3) { + transformers.push(ts.transformES2016); + } if (languageVersion < 2) { - transformers.push(ts.transformES6); + transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (languageVersion < 1) { + transformers.push(ts.transformES5); + } return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); + var enabledSyntaxKindFeatures = new Array(298); + var lexicalEnvironmentDisabled = false; + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; - var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; - var hoistedVariableDeclarations; - var hoistedFunctionDeclarations; - var lexicalEnvironmentDisabled; + var lexicalEnvironmentSuspended = false; + var emitHelpers; var context = { getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, - startLexicalEnvironment: startLexicalEnvironment, - endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + onSubstituteNode: function (_emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -40960,112 +44969,86 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 4) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 2) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); var decl = ts.createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } function hoistFunctionDeclaration(func) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } function startLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + function suspendLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + function resumeLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } function endLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = hoistedFunctionDeclarations.slice(); + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); } - if (hoistedVariableDeclarations) { - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -41075,99 +45058,31 @@ var ts; } } lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + function requestEmitHelper(helper) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -41175,42 +45090,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, - getSourceMappingURL: getSourceMappingURL + getSourceMappingURL: getSourceMappingURL, }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -41250,6 +45161,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -41257,38 +45171,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -41319,7 +45201,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -41344,84 +45226,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 293 + && (emitFlags & 16) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 64) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 293 + && (emitFlags & 32) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 128) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -41437,18 +45303,24 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, sources: sourceMapData.sourceMapSources, names: sourceMapData.sourceMapNames, mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent + sourcesContent: sourceMapData.sourceMapSourcesContent, }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -41458,46 +45330,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -41545,31 +45378,33 @@ var ts; setSourceFile: setSourceFile, emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + var isEmittedNode = node.kind !== 293; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -41581,18 +45416,20 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 219) { + if (node.kind === 224) { declarationListContainerEnd = end; } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitNodeWithComment"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -41614,17 +45451,19 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -41634,6 +45473,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -41653,7 +45495,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -41671,7 +45513,7 @@ var ts; function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -41694,7 +45536,7 @@ var ts; ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } } - function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -41732,16 +45574,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -41793,11 +45625,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -41815,7 +45647,7 @@ var ts; var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; var noDeclare; var moduleElementDeclarationEmitInfo = []; @@ -41833,7 +45665,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -41859,7 +45691,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 230); + ts.Debug.assert(aliasEmitInfo.node.kind === 235); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -41890,7 +45722,7 @@ var ts; reportedDeclarationError: reportedDeclarationError, moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput + referencesOutput: referencesOutput, }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); @@ -41915,6 +45747,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -41930,10 +45763,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 218) { + if (declaration.kind === 223) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 233 || declaration.kind === 234 || declaration.kind === 231) { + else if (declaration.kind === 238 || declaration.kind === 239 || declaration.kind === 236) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -41944,7 +45777,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 230) { + if (moduleElementEmitInfo.node.kind === 235) { moduleElementEmitInfo.isVisible = true; } else { @@ -41952,12 +45785,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -42018,7 +45851,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42030,20 +45863,20 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } function emitLines(nodes) { - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -42058,7 +45891,7 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } @@ -42069,67 +45902,73 @@ var ts; } function emitType(type) { switch (type.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 165: - case 166: + case 104: + case 137: + case 94: + case 129: + case 167: + case 171: return writeTextOfNode(currentText, type); - case 194: + case 199: return emitExpressionWithTypeArguments(type); - case 155: - return emitTypeReference(type); - case 158: - return emitTypeQuery(type); - case 160: - return emitArrayType(type); - case 161: - return emitTupleType(type); - case 162: - return emitUnionType(type); - case 163: - return emitIntersectionType(type); - case 164: - return emitParenType(type); - case 156: case 157: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 160: + return emitTypeQuery(type); + case 162: + return emitArrayType(type); + case 163: + return emitTupleType(type); + case 164: + return emitUnionType(type); + case 165: + return emitIntersectionType(type); + case 166: + return emitParenType(type); + case 168: + return emitTypeOperator(type); + case 169: + return emitIndexedAccessType(type); + case 170: + return emitMappedType(type); + case 158: case 159: + return emitSignatureDeclarationWithJsDocComments(type); + case 161: return emitTypeLiteral(type); - case 69: + case 70: return emitEntityName(type); - case 139: + case 141: return emitEntityName(type); - case 154: + case 156: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 69) { + if (entityName.kind === 70) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 139 ? entityName.left : entityName.expression; - var right = entityName.kind === 139 ? entityName.right : entityName.name; + var left = entityName.kind === 141 ? entityName.left : entityName.expression; + var right = entityName.kind === 141 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 229 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 234 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); + ts.Debug.assert(node.expression.kind === 70 || node.expression.kind === 177); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -42175,6 +46014,42 @@ var ts; emitType(type.type); write(")"); } + function emitTypeOperator(type) { + write(ts.tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + function emitIndexedAccessType(node) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + function emitMappedType(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } function emitTypeLiteral(type) { write("{"); if (type.members.length) { @@ -42203,14 +46078,14 @@ var ts; var count = 0; while (true) { count++; - var name_40 = baseName + "_" + count; - if (!(name_40 in currentIdentifiers)) { - return name_40; + var name_39 = baseName + "_" + count; + if (!(name_39 in currentIdentifiers)) { + return name_39; } } } function emitExportAssignment(node) { - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -42223,7 +46098,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -42231,11 +46106,11 @@ var ts; } write(";"); writeLine(); - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic) { + function getDefaultExportAccessibilityDiagnostic() { return { diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -42249,10 +46124,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 229 || - (node.parent.kind === 256 && isCurrentFileExternalModule)) { + else if (node.kind === 234 || + (node.parent.kind === 261 && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 256) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -42261,7 +46136,7 @@ var ts; }); } else { - if (node.kind === 230) { + if (node.kind === 235) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -42279,30 +46154,30 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 220: - return writeFunctionDeclaration(node); - case 200: - return writeVariableStatement(node); - case 222: - return writeInterfaceDeclaration(node); - case 221: - return writeClassDeclaration(node); - case 223: - return writeTypeAliasDeclaration(node); - case 224: - return writeEnumDeclaration(node); case 225: - return writeModuleDeclaration(node); + return writeFunctionDeclaration(node); + case 205: + return writeVariableStatement(node); + case 227: + return writeInterfaceDeclaration(node); + case 226: + return writeClassDeclaration(node); + case 228: + return writeTypeAliasDeclaration(node); case 229: - return writeImportEqualsDeclaration(node); + return writeEnumDeclaration(node); case 230: + return writeModuleDeclaration(node); + case 234: + return writeImportEqualsDeclaration(node); + case 235: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 256) { + if (node.parent.kind === 261) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { write("export "); @@ -42310,7 +46185,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 222 && !noDeclare) { + else if (node.kind !== 227 && !noDeclare) { write("declare "); } } @@ -42350,7 +46225,7 @@ var ts; write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult) { + function getImportEntityNameVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -42360,7 +46235,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 232) { + if (namedBindings.kind === 237) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -42383,7 +46258,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 232) { + if (node.importClause.namedBindings.kind === 237) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -42400,13 +46275,13 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 225; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230; var moduleSpecifier; - if (parent.kind === 229) { + if (parent.kind === 234) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 225) { + else if (parent.kind === 230) { moduleSpecifier = parent.name; } else { @@ -42474,7 +46349,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 226) { + while (node.body && node.body.kind !== 231) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -42508,7 +46383,7 @@ var ts; write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + function getTypeAliasDeclarationVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -42544,7 +46419,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 149 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -42554,51 +46429,54 @@ var ts; writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - (node.parent.parent && node.parent.parent.kind === 159)) { - ts.Debug.assert(node.parent.kind === 147 || - node.parent.kind === 146 || - node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.kind === 151 || - node.parent.kind === 152); + if (node.parent.kind === 158 || + node.parent.kind === 159 || + (node.parent.parent && node.parent.parent.kind === 161)) { + ts.Debug.assert(node.parent.kind === 149 || + node.parent.kind === 148 || + node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.kind === 153 || + node.parent.kind === 154); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { + function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 221: + case 226: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 222: + case 227: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 152: + case 154: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151: + case 153: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 220: + case 225: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case 228: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; default: ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -42624,16 +46502,16 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 93) { + else if (!isImplementsList && node.expression.kind === 94) { write("null"); } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult) { + function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 221) { + if (node.parent.parent.kind === 226) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -42692,7 +46570,10 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); + var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, false); + } write(" {"); writeLine(); increaseIndent(); @@ -42713,17 +46594,17 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 218 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 223 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 147 || node.kind === 146 || + (node.kind === 144 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { + if ((node.kind === 147 || node.kind === 146) && node.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -42736,14 +46617,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 218) { + if (node.kind === 223) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 145 || node.kind === 144) { + else if (node.kind === 147 || node.kind === 146) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -42751,7 +46632,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -42777,7 +46658,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (element.kind !== 198) { elements.push(element); } } @@ -42843,7 +46724,7 @@ var ts; accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 149 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 151 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -42856,7 +46737,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 149 + return accessor.kind === 151 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -42865,7 +46746,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 150) { + if (accessorWithTypeAnnotation.kind === 152) { if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -42911,17 +46792,17 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 220) { + if (node.kind === 225) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 147 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 150) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 220) { + if (node.kind === 225) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 148) { + else if (node.kind === 150) { write("constructor"); } else { @@ -42941,15 +46822,15 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 153) { + if (node.kind === 155) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 || node.kind === 157) { + if (node.kind === 154 || node.kind === 159) { write("new "); } - else if (node.kind === 156) { + else if (node.kind === 158) { var currentOutput = writer.getText(); if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; @@ -42960,20 +46841,20 @@ var ts; write("("); } emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 153) { + if (node.kind === 155) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 156 || node.kind === 157; - if (isFunctionTypeOrConstructorType || node.parent.kind === 159) { + var isFunctionTypeOrConstructorType = node.kind === 158 || node.kind === 159; + if (isFunctionTypeOrConstructorType || node.parent.kind === 161) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 150 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -42987,23 +46868,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 152: + case 154: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151: + case 153: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 153: + case 155: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43011,7 +46892,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43024,7 +46905,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 220: + case 225: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43056,9 +46937,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.parent.kind === 159) { + if (node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8)) { @@ -43074,22 +46955,26 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 148: + case 150: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 152: + case 154: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151: + case 153: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 147: - case 146: + case 155: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43097,7 +46982,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43109,7 +46994,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 220: + case 225: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43120,12 +47005,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 167) { + if (bindingPattern.kind === 172) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 168) { + else if (bindingPattern.kind === 173) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -43136,10 +47021,10 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 193) { + if (bindingElement.kind === 198) { write(" "); } - else if (bindingElement.kind === 169) { + else if (bindingElement.kind === 174) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -43149,7 +47034,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 69); + ts.Debug.assert(bindingElement.name.kind === 70); if (bindingElement.dotDotDotToken) { write("..."); } @@ -43161,57 +47046,57 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 220: case 225: - case 229: - case 222: - case 221: - case 223: - case 224: - return emitModuleElement(node, isModuleElementVisible(node)); - case 200: - return emitModuleElement(node, isVariableStatementVisible(node)); case 230: + case 234: + case 227: + case 226: + case 228: + case 229: + return emitModuleElement(node, isModuleElementVisible(node)); + case 205: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 235: return emitModuleElement(node, !node.importClause); - case 236: + case 241: return emitExportDeclaration(node); + case 150: + case 149: case 148: + return writeFunctionDeclaration(node); + case 154: + case 153: + case 155: + return emitSignatureDeclarationWithJsDocComments(node); + case 151: + case 152: + return emitAccessorDeclaration(node); case 147: case 146: - return writeFunctionDeclaration(node); - case 152: - case 151: - case 153: - return emitSignatureDeclarationWithJsDocComments(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 145: - case 144: return emitPropertyDeclaration(node); - case 255: + case 260: return emitEnumMemberDeclaration(node); - case 235: + case 240: return emitExportAssignment(node); - case 256: + case 261: return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); referencesOutput += "/// " + newLine; } return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) { if (isBundledEmit && !addBundledFileReference) { return; } @@ -43221,8 +47106,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43248,20 +47133,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (_) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; - var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; - var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; - var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; - var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; - var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; - var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; - var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; - var superHelper = "\nconst _super = name => super[name];"; - var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -43269,11 +47145,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -43283,21 +47159,20 @@ var ts; var currentSourceFile; var currentText; var currentFileIdentifiers; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; + var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -43306,16 +47181,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -43329,11 +47208,12 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = ts.createMap(); + bundledHelpers = isBundledEmit ? ts.createMap() : undefined; isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; - emitEmitHelpers(sourceFile); + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; + emitHelpers(sourceFile, true); } } ts.forEach(sourceFiles, printSourceFile); @@ -43343,23 +47223,18 @@ var ts; write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); } if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); } if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); comments.reset(); writer.reset(); tempFlags = 0; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } function printSourceFile(node) { @@ -43368,360 +47243,369 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 261: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 70: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { - case 12: case 13: case 14: + case 15: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 74: - case 77: - case 82: - case 103: - case 110: + case 75: + case 78: + case 83: + case 104: case 111: case 112: case 113: - case 115: + case 114: + case 116: case 117: case 118: + case 119: case 120: + case 121: case 122: - case 130: + case 123: + case 124: + case 125: + case 127: case 128: + case 129: + case 130: + case 131: case 132: case 133: + case 134: + case 135: + case 136: case 137: - return writeTokenNode(node); + case 138: case 139: - return emitQualifiedName(node); case 140: - return emitComputedPropertyName(node); - case 141: - return emitTypeParameter(node); - case 142: - return emitParameter(node); - case 143: - return emitDecorator(node); - case 144: - return emitPropertySignature(node); - case 145: - return emitPropertyDeclaration(node); - case 146: - return emitMethodSignature(node); - case 147: - return emitMethodDeclaration(node); - case 148: - return emitConstructor(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 151: - return emitCallSignature(node); - case 152: - return emitConstructSignature(node); - case 153: - return emitIndexSignature(node); - case 154: - return emitTypePredicate(node); - case 155: - return emitTypeReference(node); - case 156: - return emitFunctionType(node); - case 157: - return emitConstructorType(node); - case 158: - return emitTypeQuery(node); - case 159: - return emitTypeLiteral(node); - case 160: - return emitArrayType(node); - case 161: - return emitTupleType(node); - case 162: - return emitUnionType(node); - case 163: - return emitIntersectionType(node); - case 164: - return emitParenthesizedType(node); - case 194: - return emitExpressionWithTypeArguments(node); - case 165: - return emitThisType(node); - case 166: - return emitLiteralType(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 197: - return emitTemplateSpan(node); - case 198: - return emitSemicolonClassElement(node); - case 199: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return emitEmptyStatement(node); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 207: - return emitForInStatement(node); - case 208: - return emitForOfStatement(node); - case 209: - return emitContinueStatement(node); - case 210: - return emitBreakStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 219: - return emitVariableDeclarationList(node); - case 220: - return emitFunctionDeclaration(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 223: - return emitTypeAliasDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 225: - return emitModuleDeclaration(node); - case 226: - return emitModuleBlock(node); - case 227: - return emitCaseBlock(node); - case 229: - return emitImportEqualsDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 231: - return emitImportClause(node); - case 232: - return emitNamespaceImport(node); - case 233: - return emitNamedImports(node); - case 234: - return emitImportSpecifier(node); - case 235: - return emitExportAssignment(node); - case 236: - return emitExportDeclaration(node); - case 237: - return emitNamedExports(node); - case 238: - return emitExportSpecifier(node); - case 239: + writeTokenText(kind); return; + case 141: + return emitQualifiedName(node); + case 142: + return emitComputedPropertyName(node); + case 143: + return emitTypeParameter(node); + case 144: + return emitParameter(node); + case 145: + return emitDecorator(node); + case 146: + return emitPropertySignature(node); + case 147: + return emitPropertyDeclaration(node); + case 148: + return emitMethodSignature(node); + case 149: + return emitMethodDeclaration(node); + case 150: + return emitConstructor(node); + case 151: + case 152: + return emitAccessorDeclaration(node); + case 153: + return emitCallSignature(node); + case 154: + return emitConstructSignature(node); + case 155: + return emitIndexSignature(node); + case 156: + return emitTypePredicate(node); + case 157: + return emitTypeReference(node); + case 158: + return emitFunctionType(node); + case 159: + return emitConstructorType(node); + case 160: + return emitTypeQuery(node); + case 161: + return emitTypeLiteral(node); + case 162: + return emitArrayType(node); + case 163: + return emitTupleType(node); + case 164: + return emitUnionType(node); + case 165: + return emitIntersectionType(node); + case 166: + return emitParenthesizedType(node); + case 199: + return emitExpressionWithTypeArguments(node); + case 167: + return emitThisType(); + case 168: + return emitTypeOperator(node); + case 169: + return emitIndexedAccessType(node); + case 170: + return emitMappedType(node); + case 171: + return emitLiteralType(node); + case 172: + return emitObjectBindingPattern(node); + case 173: + return emitArrayBindingPattern(node); + case 174: + return emitBindingElement(node); + case 202: + return emitTemplateSpan(node); + case 203: + return emitSemicolonClassElement(); + case 204: + return emitBlock(node); + case 205: + return emitVariableStatement(node); + case 206: + return emitEmptyStatement(); + case 207: + return emitExpressionStatement(node); + case 208: + return emitIfStatement(node); + case 209: + return emitDoStatement(node); + case 210: + return emitWhileStatement(node); + case 211: + return emitForStatement(node); + case 212: + return emitForInStatement(node); + case 213: + return emitForOfStatement(node); + case 214: + return emitContinueStatement(node); + case 215: + return emitBreakStatement(node); + case 216: + return emitReturnStatement(node); + case 217: + return emitWithStatement(node); + case 218: + return emitSwitchStatement(node); + case 219: + return emitLabeledStatement(node); + case 220: + return emitThrowStatement(node); + case 221: + return emitTryStatement(node); + case 222: + return emitDebuggerStatement(node); + case 223: + return emitVariableDeclaration(node); + case 224: + return emitVariableDeclarationList(node); + case 225: + return emitFunctionDeclaration(node); + case 226: + return emitClassDeclaration(node); + case 227: + return emitInterfaceDeclaration(node); + case 228: + return emitTypeAliasDeclaration(node); + case 229: + return emitEnumDeclaration(node); + case 230: + return emitModuleDeclaration(node); + case 231: + return emitModuleBlock(node); + case 232: + return emitCaseBlock(node); + case 234: + return emitImportEqualsDeclaration(node); + case 235: + return emitImportDeclaration(node); + case 236: + return emitImportClause(node); + case 237: + return emitNamespaceImport(node); + case 238: + return emitNamedImports(node); + case 239: + return emitImportSpecifier(node); case 240: - return emitExternalModuleReference(node); - case 244: - return emitJsxText(node); + return emitExportAssignment(node); + case 241: + return emitExportDeclaration(node); + case 242: + return emitNamedExports(node); case 243: - return emitJsxOpeningElement(node); + return emitExportSpecifier(node); + case 244: + return; case 245: - return emitJsxClosingElement(node); - case 246: - return emitJsxAttribute(node); - case 247: - return emitJsxSpreadAttribute(node); + return emitExternalModuleReference(node); + case 10: + return emitJsxText(node); case 248: - return emitJsxExpression(node); + return emitJsxOpeningElement(node); case 249: - return emitCaseClause(node); + return emitJsxClosingElement(node); case 250: - return emitDefaultClause(node); + return emitJsxAttribute(node); case 251: - return emitHeritageClause(node); + return emitJsxSpreadAttribute(node); case 252: - return emitCatchClause(node); + return emitJsxExpression(node); case 253: - return emitPropertyAssignment(node); + return emitCaseClause(node); case 254: - return emitShorthandPropertyAssignment(node); + return emitDefaultClause(node); case 255: - return emitEnumMember(node); + return emitHeritageClause(node); case 256: - return emitSourceFile(node); + return emitCatchClause(node); + case 257: + return emitPropertyAssignment(node); + case 258: + return emitShorthandPropertyAssignment(node); + case 259: + return emitSpreadAssignment(node); + case 260: + return emitEnumMember(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: return emitNumericLiteral(node); case 9: - case 10: case 11: + case 12: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 84: - case 93: - case 95: - case 99: - case 97: - return writeTokenNode(node); - case 170: - return emitArrayLiteralExpression(node); - case 171: - return emitObjectLiteralExpression(node); - case 172: - return emitPropertyAccessExpression(node); - case 173: - return emitElementAccessExpression(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - return emitTypeAssertionExpression(node); - case 178: - return emitParenthesizedExpression(node); - case 179: - return emitFunctionExpression(node); - case 180: - return emitArrowFunction(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 189: - return emitTemplateExpression(node); - case 190: - return emitYieldExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 192: - return emitClassExpression(node); - case 193: + case 85: + case 94: + case 96: + case 100: + case 98: + writeTokenText(kind); return; + case 175: + return emitArrayLiteralExpression(node); + case 176: + return emitObjectLiteralExpression(node); + case 177: + return emitPropertyAccessExpression(node); + case 178: + return emitElementAccessExpression(node); + case 179: + return emitCallExpression(node); + case 180: + return emitNewExpression(node); + case 181: + return emitTaggedTemplateExpression(node); + case 182: + return emitTypeAssertionExpression(node); + case 183: + return emitParenthesizedExpression(node); + case 184: + return emitFunctionExpression(node); + case 185: + return emitArrowFunction(node); + case 186: + return emitDeleteExpression(node); + case 187: + return emitTypeOfExpression(node); + case 188: + return emitVoidExpression(node); + case 189: + return emitAwaitExpression(node); + case 190: + return emitPrefixUnaryExpression(node); + case 191: + return emitPostfixUnaryExpression(node); + case 192: + return emitBinaryExpression(node); + case 193: + return emitConditionalExpression(node); + case 194: + return emitTemplateExpression(node); case 195: - return emitAsExpression(node); + return emitYieldExpression(node); case 196: + return emitSpreadExpression(node); + case 197: + return emitClassExpression(node); + case 198: + return; + case 200: + return emitAsExpression(node); + case 201: return emitNonNullExpression(node); - case 241: + case 246: return emitJsxElement(node); - case 242: + case 247: return emitJsxSelfClosingElement(node); - case 288: + case 294: return emitPartiallyEmittedExpression(node); + case 297: + return writeLines(node.text); } } function emitNumericLiteral(node) { @@ -43741,12 +47625,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, false)); - } + write(getTextOfNode(node, false)); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -43754,7 +47633,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -43824,7 +47703,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 149 ? "get " : "set "); + write(node.kind === 151 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -43852,7 +47731,7 @@ var ts; emitWithPrefix(": ", node.type); write(";"); } - function emitSemicolonClassElement(node) { + function emitSemicolonClassElement() { write(";"); } function emitTypePredicate(node) { @@ -43906,9 +47785,42 @@ var ts; emit(node.type); write(")"); } - function emitThisType(node) { + function emitThisType() { write("this"); } + function emitTypeOperator(node) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + function emitMappedType(node) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } function emitLiteralType(node) { emitExpression(node.literal); } @@ -43956,7 +47868,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -43969,21 +47881,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 65536)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = { kind: 22, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -43992,17 +47901,16 @@ var ts; function needsDotDotForPropertyAccess(expression) { if (expression.kind === 8) { var text = getLiteralTextOfNode(expression); - return text.indexOf(ts.tokenToString(21)) < 0; + return text.indexOf(ts.tokenToString(22)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -44010,11 +47918,13 @@ var ts; } function emitCallExpression(node) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { @@ -44074,16 +47984,16 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 185 - && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) - || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + return operand.kind === 190 + && ((node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) + || (node.operator === 37 && (operand.operator === 37 || operand.operator === 43))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 24; + var isCommaOperator = node.operatorToken.kind !== 25; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); @@ -44118,7 +48028,7 @@ var ts; write(node.asteriskToken ? "yield*" : "yield"); emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node) { + function emitSpreadExpression(node) { write("..."); emitExpression(node.expression); } @@ -44144,20 +48054,20 @@ var ts; emitExpression(node.expression); emit(node.literal); } - function emitBlock(node, format) { + function emitBlock(node) { if (isSingleLineEmptyBlock(node)) { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); write(" "); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } else { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); emitBlockStatements(node); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 1) { emitList(node, node.statements, 384); } else { @@ -44169,7 +48079,7 @@ var ts; emit(node.declarationList); write(";"); } - function emitEmptyStatement(node) { + function emitEmptyStatement() { write(";"); } function emitExpressionStatement(node) { @@ -44177,16 +48087,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(88, node.pos, node); + var openParenPos = writeToken(89, node.pos, node); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitExpression(node.expression); - writeToken(18, node.expression.end, node); + writeToken(19, node.expression.end, node); emitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { writeLine(); - writeToken(80, node.thenStatement.end, node); - if (node.elseStatement.kind === 203) { + writeToken(81, node.thenStatement.end, node); + if (node.elseStatement.kind === 208) { write(" "); emit(node.elseStatement); } @@ -44215,9 +48125,9 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -44227,28 +48137,28 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 219) { + if (node.kind === 224) { emit(node); } else { @@ -44257,17 +48167,17 @@ var ts; } } function emitContinueStatement(node) { - writeToken(75, node.pos); + writeToken(76, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(70, node.pos); + writeToken(71, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitReturnStatement(node) { - writeToken(94, node.pos, node); + writeToken(95, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -44278,11 +48188,11 @@ var ts; emitEmbeddedStatement(node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(96, node.pos); + var openParenPos = writeToken(97, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); write(" "); emit(node.caseBlock); } @@ -44307,11 +48217,12 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(76, node.pos); + writeToken(77, node.pos); write(";"); } function emitVariableDeclaration(node) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } function emitVariableDeclarationList(node) { @@ -44332,19 +48243,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 262144) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { var savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } if (indentedFlag) { @@ -44367,8 +48278,8 @@ var ts; emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (ts.getEmitFlags(body) & 1) { return true; } if (body.multiLine) { @@ -44391,14 +48302,14 @@ var ts; } return true; } - function emitBlockFunctionBody(parentNode, body) { + function emitBlockFunctionBody(body) { write(" {"); increaseIndent(); - emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); decreaseIndent(); - writeToken(16, body.statements.end, body); + writeToken(17, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -44423,7 +48334,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -44476,7 +48387,7 @@ var ts; write(node.flags & 16 ? "namespace " : "module "); emit(node.name); var body = node.body; - while (body.kind === 225) { + while (body.kind === 230) { write("."); emit(body.name); body = body.body; @@ -44485,7 +48396,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -44499,9 +48410,9 @@ var ts; } } function emitCaseBlock(node) { - writeToken(15, node.pos); + writeToken(16, node.pos); emitList(node, node.clauses, 65); - writeToken(16, node.clauses.end); + writeToken(17, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -44512,7 +48423,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -44632,7 +48543,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -44670,11 +48581,11 @@ var ts; } function emitCatchClause(node) { writeLine(); - var openParenPos = writeToken(72, node.pos); + var openParenPos = writeToken(73, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emit(node.variableDeclaration); - writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + writeToken(19, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); write(" "); emit(node.block); } @@ -44682,8 +48593,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 512) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -44695,6 +48606,12 @@ var ts; emitExpression(node.objectAssignmentInitializer); } } + function emitSpreadAssignment(node) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } function emitEnumMember(node) { emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); @@ -44730,64 +48647,31 @@ var ts; } return statements.length; } - function emitHelpers(node) { - var emitFlags = node.emitFlags; + function emitHelpers(node, isBundle) { + var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile; + var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit; var helpersEmitted = false; - if (emitFlags & 1) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - if (emitFlags & 2) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - if (emitFlags & 4) { - writeLines(superHelper); - helpersEmitted = true; - } - if (emitFlags & 8) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - return helpersEmitted; - } - function emitEmitHelpers(node) { - if (compilerOptions.noEmitHelpers) { - return false; - } - if (compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } - var helpersEmitted = false; - if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 2048) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + if (shouldSkip) + continue; + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + continue; + } + writeLines(helper.text); + helpersEmitted = true; } - decorateEmitted = true; - helpersEmitted = true; - } - if (!paramEmitted && node.flags & 4096) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - if (!awaiterEmitted && node.flags & 8192) { - writeLines(awaiterHelper); - if (languageVersion < 2) { - writeLines(generatorHelper); - } - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { writeLine(); @@ -44795,9 +48679,10 @@ var ts; return helpersEmitted; } function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); + var lines = text.split(/\r\n?|\n/g); + var indentation = guessIndentation(lines); for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + var line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -44806,6 +48691,21 @@ var ts; } } } + function guessIndentation(lines) { + var indentation; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var line = lines_1[_a]; + for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!ts.isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { @@ -44837,31 +48737,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -44961,7 +48836,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -45003,27 +48878,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -45130,7 +48990,7 @@ var ts; && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + while (node.kind === 183 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -45162,17 +49022,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -45192,21 +49047,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_41 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_41)) { + var name_40 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_40)) { tempFlags |= flags; - return name_41; + return name_40; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_42 = count < 26 + var name_41 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_42)) { - return name_42; + if (isUniqueName(name_41)) { + return name_41; } } } @@ -45242,19 +49097,19 @@ var ts; } function generateNameForNode(node) { switch (node.kind) { - case 69: + case 70: return makeUniqueName(getTextOfNode(node)); - case 225: - case 224: - return generateNameForModuleOrEnum(node); case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: + case 229: + return generateNameForModuleOrEnum(node); case 235: + case 241: + return generateNameForImportOrExportDeclaration(node); + case 225: + case 226: + case 240: return generateNameForExportDefault(); - case 192: + case 197: return generateNameForClassExpression(); default: return makeTempVariableName(0); @@ -45327,7 +49182,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.0"; var emptyArray = []; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -45382,581 +49236,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === 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, typeRoots); - } - } - else { - 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, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -46058,7 +49337,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); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -46117,42 +49396,15 @@ var ts; } var resolutions = []; var cache = ts.createMap(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var result = name_43 in cache - ? cache[name_43] - : cache[name_43] = loader(name_43, containingFile); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_42 = names_1[_i]; + var result = name_42 in cache + ? cache[name_42] + : cache[name_42] = loader(name_42, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -46162,7 +49414,7 @@ var ts; var classifiableNames; var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; var modulesWithElidedImports = ts.createMap(); var sourceFilesFoundSearchingNodeModules = ts.createMap(); @@ -46175,10 +49427,17 @@ var ts; var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -46186,16 +49445,17 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); 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 = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -46236,19 +49496,22 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { commonSourceDirectory += ts.directorySeparator; @@ -46267,25 +49530,85 @@ var ts; } return classifiableNames; } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var unknownModuleNames; + var result; + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + var isKnownToResolveToAmbientModule = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + result = new Array(moduleNames.length); + unknownModuleNames = moduleNames.slice(0, i); + } + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + unknownModuleNames.push(moduleName); + } + } + if (!unknownModuleNames) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState) { + return false; + } + var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + return false; + } + var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return false; } var oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + if (ts.changesAffectModuleResolution(oldOptions, options)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -46326,40 +49649,44 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { return false; } - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { newSourceFile = oldSourceFile; } newSourceFiles.push(newSourceFile); } + var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { - var modifiedFile = modifiedSourceFiles_1[_b]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { + var modifiedFile = modifiedSourceFiles_2[_d]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -46375,24 +49702,30 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked + isEmitBlocked: isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file) { + return sourceFilesFoundSearchingNodeModules[file.path]; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -46413,7 +49746,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -46452,7 +49785,13 @@ var ts; return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } } - function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSyntacticDiagnosticsForFile(sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } function runWithCancellationToken(func) { @@ -46472,183 +49811,170 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; + var parent = sourceFile; walk(sourceFile); return diagnostics; function walk(node) { - if (!node) { - return false; + switch (parent.kind) { + case 144: + case 147: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + case 149: + case 148: + case 150: + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + case 223: + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } } switch (node.kind) { - case 229: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 235: + case 234: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 240: if (node.isExportEquals) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; } break; - case 221: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 251: + case 255: var heritageClause = node; - if (heritageClause.token === 106) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; + if (heritageClause.token === 107) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; } break; - case 222: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 225: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 223: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 147: - case 146: - case 148: + case 227: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 230: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 228: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 229: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 182: + var typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 226: case 149: + case 148: case 150: - case 179: - case 220: - case 180: - case 220: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + case 205: + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 205); } break; - case 200: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 218: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 174: - case 175: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 142: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 145: - var propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + case 147: + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _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 (modifier.kind !== 114) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } - } - if (checkTypeAnnotation(node.type)) { - return true; + return; } break; - case 224: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 177: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 143: - if (!options.experimentalDecorators) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + case 144: + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112: - case 110: - case 111: - case 128: - case 122: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - case 113: - case 82: - case 74: - case 77: - case 115: + break; + case 179: + case 180: + case 199: + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 75: + if (isConstValid) { + continue; + } + case 113: + case 111: + case 112: + case 130: + case 123: + case 116: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + case 114: + case 83: + case 78: } } - return false; + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); - var writeFile = function () { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { @@ -46665,11 +49991,8 @@ var ts; ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName) { - return ts.getBaseFileName(fileName).indexOf(".") >= 0; - } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, true); + processSourceFile(ts.normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -46686,14 +50009,18 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; + var ambientModules; if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - var externalHelpersModuleReference = ts.createNode(9); + var externalHelpersModuleReference = ts.createSynthesizedNode(9); externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + var importDecl = ts.createSynthesizedNode(235); + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { @@ -46705,12 +50032,13 @@ var ts; } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 230: - case 229: - case 236: + case 235: + case 234: + case 241: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -46722,13 +50050,16 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 225: + case 230: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + (ambientModules || (ambientModules = [])).push(moduleName.text); + } var body = node.body; if (body) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { @@ -46749,15 +50080,15 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, isReference, refFile, refPos, refEnd) { + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { var diagnosticArgument; var diagnostic; - if (hasExtension(fileName)) { + if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -46767,13 +50098,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -46797,7 +50128,7 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, isReference, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { if (filesByName.contains(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -46806,16 +50137,16 @@ var ts; if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } } return file_1; @@ -46842,12 +50173,11 @@ var ts; } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - var basePath = ts.getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); } @@ -46857,10 +50187,10 @@ var ts; } return file; } - function processReferencedFiles(file, basePath, isDefaultLib) { + function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -46882,18 +50212,20 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } else { if (previousResolution) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } } saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } } } @@ -46919,28 +50251,35 @@ var ts; function getCanonicalFileName(fileName) { return host.getCanonicalFileName(fileName); } - function processImportedModules(file, basePath) { + function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = ts.createMap(); - var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); + var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; - var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -46950,12 +50289,11 @@ var ts; else { file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -46966,8 +50304,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -47010,7 +50348,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -47021,7 +50359,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -47060,6 +50398,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -47101,13 +50442,21 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); - ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); @@ -47116,10 +50465,15 @@ var ts; if (emitFileName) { var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + var chain_1; + if (!options.configFilePath) { + chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } if (emitFilesSeen.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -47127,35 +50481,58 @@ var ts; } } } - function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); } } ts.createProgram = createProgram; + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ts.Extension.Ts: + case ts.Extension.Dts: + return undefined; + case ts.Extension.Tsx: + return needJsx(); + case ts.Extension.Jsx: + return needJsx() || needAllowJs(); + case ts.Extension.Js: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -47170,7 +50547,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -47180,15 +50557,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -47197,27 +50574,32 @@ var ts; "react": 2 }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -47228,11 +50610,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -47241,12 +50623,12 @@ var ts; "lf": 1 }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -47255,7 +50637,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -47264,59 +50646,59 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -47339,30 +50721,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -47373,7 +50755,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -47388,22 +50770,25 @@ var ts; "es3": 0, "es5": 1, "es6": 2, - "es2015": 2 + "es2015": 2, + "es2016": 3, + "es2017": 4, + "esnext": 5, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -47420,10 +50805,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -47545,8 +50930,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -47563,12 +50949,21 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -47591,9 +50986,21 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -47611,22 +51018,12 @@ var ts; } ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -47688,7 +51085,11 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -47764,10 +51165,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -47805,9 +51207,9 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_44 in options) { - if (ts.hasProperty(options, name_44)) { - switch (name_44) { + for (var name_43 in options) { + if (ts.hasProperty(options, name_43)) { + switch (name_43) { case "init": case "watch": case "version": @@ -47815,12 +51217,12 @@ var ts; case "project": break; default: - var value = options[name_44]; - var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + var value = options[name_43]; + var optionDefinition = optionsNameMap[name_43.toLowerCase()]; if (optionDefinition) { var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap) { - result[name_44] = value; + result[name_43] = value; } else { if (optionDefinition.type === "list") { @@ -47829,10 +51231,10 @@ var ts; var element = _a[_i]; convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); } - result[name_44] = convertedValue; + result[name_43] = convertedValue; } else { - result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + result[name_43] = getNameOfCompilerOptionValue(value, customTypeMap); } } } @@ -47861,9 +51263,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -47871,14 +51274,15 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -47901,22 +51305,24 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = (extendedConfigPath + ".json"); + extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return; @@ -47944,6 +51350,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -47971,7 +51380,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -47980,33 +51389,49 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -48068,7 +51493,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -48080,7 +51505,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -48136,14 +51561,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_45 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_45)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_45); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_45) ? 1 : 0; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -48164,6 +51588,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 : 0 + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 }; + } + return undefined; + } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); @@ -48213,7 +51650,7 @@ var ts; reportDiagnostic(diagnostic, host); } } - function reportEmittedFiles(files, host) { + function reportEmittedFiles(files) { if (!files || files.length == 0) { return; } @@ -48224,47 +51661,6 @@ var ts; ts.sys.write("TSFILE: " + filepath + ts.sys.newLine); } } - function validateLocaleAndSetLanguage(locale, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); - if (!matchResult) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); - return false; - } - var language = matchResult[1]; - var territory = matchResult[3]; - if (!trySetLanguageAndTerritory(language, territory, errors)) { - trySetLanguageAndTerritory(language, undefined, errors); - } - return true; - } - function trySetLanguageAndTerritory(language, territory, errors) { - var compilerFilePath = ts.normalizePath(ts.sys.getExecutingFilePath()); - var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); - var filePath = ts.combinePaths(containingDirectoryPath, language); - if (territory) { - filePath = filePath + "-" + territory; - } - filePath = ts.sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); - if (!ts.sys.fileExists(filePath)) { - return false; - } - var fileContents = ""; - try { - fileContents = ts.sys.readFile(filePath); - } - catch (e) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); - return false; - } - try { - ts.localizedDiagnosticMessages = JSON.parse(fileContents); - } - catch (e) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); - return false; - } - return true; - } function countLines(program) { var count = 0; ts.forEach(program.getSourceFiles(), function (file) { @@ -48272,10 +51668,10 @@ var ts; }); return count; } - function getDiagnosticText(message) { - var args = []; + function getDiagnosticText(_message) { + var _args = []; for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + _args[_i - 1] = arguments[_i]; } var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; @@ -48294,8 +51690,7 @@ var ts; _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, - _a - )); + _a)); function formatAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } @@ -48394,7 +51789,7 @@ var ts; reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); + ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); } if (commandLine.errors.length > 0) { reportDiagnostics(commandLine.errors, compilerHost); @@ -48548,7 +51943,7 @@ var ts; } var sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && ts.isWatchSet(compilerOptions) && ts.sys.watchFile) { - sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (fileName, removed) { return sourceFileChanged(sourceFile, removed); }); + sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (_fileName, removed) { return sourceFileChanged(sourceFile, removed); }); } return sourceFile; } @@ -48586,10 +51981,13 @@ var ts; startTimerForHandlingDirectoryChanges(); } function startTimerForHandlingDirectoryChanges() { - if (timerHandleForDirectoryChanges) { - clearTimeout(timerHandleForDirectoryChanges); + if (!ts.sys.setTimeout || !ts.sys.clearTimeout) { + return; } - timerHandleForDirectoryChanges = setTimeout(directoryChangeHandler, 250); + if (timerHandleForDirectoryChanges) { + ts.sys.clearTimeout(timerHandleForDirectoryChanges); + } + timerHandleForDirectoryChanges = ts.sys.setTimeout(directoryChangeHandler, 250); } function directoryChangeHandler() { var parsedCommandLine = parseConfigFile(); @@ -48601,10 +51999,13 @@ var ts; } } function startTimerForRecompilation() { - if (timerHandleForRecompilation) { - clearTimeout(timerHandleForRecompilation); + if (!ts.sys.setTimeout || !ts.sys.clearTimeout) { + return; } - timerHandleForRecompilation = setTimeout(recompile, 250); + if (timerHandleForRecompilation) { + ts.sys.clearTimeout(timerHandleForRecompilation); + } + timerHandleForRecompilation = ts.sys.setTimeout(recompile, 250); } function recompile() { timerHandleForRecompilation = undefined; @@ -48670,7 +52071,7 @@ var ts; var emitOutput = program.emit(); diagnostics = diagnostics.concat(emitOutput.diagnostics); reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), compilerHost); - reportEmittedFiles(emitOutput.emittedFiles, compilerHost); + reportEmittedFiles(emitOutput.emittedFiles); if (emitOutput.emitSkipped && diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } @@ -48683,17 +52084,17 @@ var ts; var nameSize = 0; var valueSize = 0; for (var _i = 0, statistics_1 = statistics; _i < statistics_1.length; _i++) { - var _a = statistics_1[_i], name_46 = _a.name, value = _a.value; - if (name_46.length > nameSize) { - nameSize = name_46.length; + var _a = statistics_1[_i], name_44 = _a.name, value = _a.value; + if (name_44.length > nameSize) { + nameSize = name_44.length; } if (value.length > valueSize) { valueSize = value.length; } } for (var _b = 0, statistics_2 = statistics; _b < statistics_2.length; _b++) { - var _c = statistics_2[_b], name_47 = _c.name, value = _c.value; - ts.sys.write(padRight(name_47 + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); + var _c = statistics_2[_b], name_45 = _c.name, value = _c.value; + ts.sys.write(padRight(name_45 + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); } } function reportStatisticalValue(name, value) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 8bb071cf4a1..9c17684ed0a 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -26,12 +26,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; @@ -44,41 +45,47 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); })(ts || (ts = {})); var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -129,8 +136,12 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + ts.version = "2.2.0"; +})(ts || (ts = {})); (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -150,13 +161,21 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, - clear: clear + getKeys: getKeys, + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -197,6 +216,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; function every(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -328,13 +354,32 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; function flatten(array) { var result; if (array) { @@ -435,10 +480,27 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } @@ -447,8 +509,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -461,6 +523,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; function compact(array) { var result; if (array) { @@ -479,26 +576,62 @@ var ts; return result || array; } ts.compact = compact; + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1: break inner; + case 0: continue outer; + case 1: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) + .map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -515,6 +648,12 @@ var ts; : undefined; } ts.firstOrUndefined = firstOrUndefined; + function lastOrUndefined(array) { + return array && array.length > 0 + ? array[array.length - 1] + : undefined; + } + ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -527,22 +666,28 @@ var ts; : array; } ts.singleOrMany = singleOrMany; - function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; } - ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { - var low = 0; + ts.replaceElement = replaceElement; + function binarySearch(array, value, comparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -641,6 +786,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -664,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -695,8 +840,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -765,6 +910,12 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function noop() { } + ts.noop = noop; + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -776,9 +927,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -803,11 +1004,11 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -830,6 +1031,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -870,7 +1082,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1012,10 +1224,53 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1187,6 +1442,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -1214,68 +1473,83 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -1285,7 +1559,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -1300,7 +1574,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -1342,25 +1616,30 @@ var ts; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } 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; - } + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); } - basePaths.push(includeBasePath); + }; + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -1385,15 +1664,34 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; - function isSupportedSourceFileName(fileName, compilerOptions) { + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -1452,10 +1750,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -1465,10 +1759,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -1480,7 +1774,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1786,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1806,17 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; + return false; } - ts.getEnvironmentVariable = getEnvironmentVariable; + ts.orderedRemoveItem = orderedRemoveItem; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1847,94 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,9 +2128,15 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -1855,6 +2229,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -1864,7 +2239,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -1872,7 +2247,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -1886,6 +2261,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1961,7 +2339,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -1972,7 +2352,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { return ChakraHost.readFile(path); }, writeFile: function (path, data, writeByteOrderMark) { @@ -1988,28 +2368,52 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2055,7 +2459,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -2165,7 +2569,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -2228,6 +2631,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -2271,6 +2675,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -2281,16 +2686,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -2330,11 +2736,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2368,8 +2774,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2381,7 +2785,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -2403,9 +2807,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -2452,6 +2854,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2475,6 +2884,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -2495,7 +2905,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -2506,6 +2916,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -2576,7 +2991,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -2605,6 +3023,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2617,7 +3036,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -2688,7 +3107,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -2725,9 +3144,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2736,7 +3162,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -2752,6 +3179,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2769,6 +3197,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -2779,141 +3208,157 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { - return token >= 69; + return token >= 70; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115, - "any": 117, - "as": 116, - "boolean": 120, - "break": 70, - "case": 71, - "catch": 72, - "class": 73, - "continue": 75, - "const": 74, - "constructor": 121, - "debugger": 76, - "declare": 122, - "default": 77, - "delete": 78, - "do": 79, - "else": 80, - "enum": 81, - "export": 82, - "extends": 83, - "false": 84, - "finally": 85, - "for": 86, - "from": 136, - "function": 87, - "get": 123, - "if": 88, - "implements": 106, - "import": 89, - "in": 90, - "instanceof": 91, - "interface": 107, - "is": 124, - "let": 108, - "module": 125, - "namespace": 126, - "never": 127, - "new": 92, - "null": 93, - "number": 130, - "package": 109, - "private": 110, - "protected": 111, - "public": 112, - "readonly": 128, - "require": 129, - "global": 137, - "return": 94, - "set": 131, - "static": 113, - "string": 132, - "super": 95, - "switch": 96, - "symbol": 133, - "this": 97, - "throw": 98, - "true": 99, - "try": 100, - "type": 134, - "typeof": 101, - "undefined": 135, - "var": 102, - "void": 103, - "while": 104, - "with": 105, - "yield": 114, - "async": 118, - "await": 119, - "of": 138, - "{": 15, - "}": 16, - "(": 17, - ")": 18, - "[": 19, - "]": 20, - ".": 21, - "...": 22, - ";": 23, - ",": 24, - "<": 25, - ">": 27, - "<=": 28, - ">=": 29, - "==": 30, - "!=": 31, - "===": 32, - "!==": 33, - "=>": 34, - "+": 35, - "-": 36, - "**": 38, - "*": 37, - "/": 39, - "%": 40, - "++": 41, - "--": 42, - "<<": 43, - ">": 44, - ">>>": 45, - "&": 46, - "|": 47, - "^": 48, - "!": 49, - "~": 50, - "&&": 51, - "||": 52, - "?": 53, - ":": 54, - "=": 56, - "+=": 57, - "-=": 58, - "*=": 59, - "**=": 60, - "/=": 61, - "%=": 62, - "<<=": 63, - ">>=": 64, - ">>>=": 65, - "&=": 66, - "|=": 67, - "^=": 68, - "@": 55 + "abstract": 116, + "any": 118, + "as": 117, + "boolean": 121, + "break": 71, + "case": 72, + "catch": 73, + "class": 74, + "continue": 76, + "const": 75, + "constructor": 122, + "debugger": 77, + "declare": 123, + "default": 78, + "delete": 79, + "do": 80, + "else": 81, + "enum": 82, + "export": 83, + "extends": 84, + "false": 85, + "finally": 86, + "for": 87, + "from": 138, + "function": 88, + "get": 124, + "if": 89, + "implements": 107, + "import": 90, + "in": 91, + "instanceof": 92, + "interface": 108, + "is": 125, + "keyof": 126, + "let": 109, + "module": 127, + "namespace": 128, + "never": 129, + "new": 93, + "null": 94, + "number": 132, + "package": 110, + "private": 111, + "protected": 112, + "public": 113, + "readonly": 130, + "require": 131, + "global": 139, + "return": 95, + "set": 133, + "static": 114, + "string": 134, + "super": 96, + "switch": 97, + "symbol": 135, + "this": 98, + "throw": 99, + "true": 100, + "try": 101, + "type": 136, + "typeof": 102, + "undefined": 137, + "var": 103, + "void": 104, + "while": 105, + "with": 106, + "yield": 115, + "async": 119, + "await": 120, + "of": 140, + "{": 16, + "}": 17, + "(": 18, + ")": 19, + "[": 20, + "]": 21, + ".": 22, + "...": 23, + ";": 24, + ",": 25, + "<": 26, + ">": 28, + "<=": 29, + ">=": 30, + "==": 31, + "!=": 32, + "===": 33, + "!==": 34, + "=>": 35, + "+": 36, + "-": 37, + "**": 39, + "*": 38, + "/": 40, + "%": 41, + "++": 42, + "--": 43, + "<<": 44, + ">": 45, + ">>>": 46, + "&": 47, + "|": 48, + "^": 49, + "!": 50, + "~": 51, + "&&": 52, + "||": 53, + "?": 54, + ":": 55, + "=": 57, + "+=": 58, + "-=": 59, + "*=": 60, + "**=": 61, + "/=": 62, + "%=": 63, + "<<=": 64, + ">>=": 65, + ">>>=": 66, + "&=": 67, + "|=": 68, + "^=": 69, + "@": 56, }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -3310,7 +3755,7 @@ var ts; return iterateCommentRanges(true, text, pos, true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -3376,8 +3821,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 || token > 105; }, - isReservedWord: function () { return token >= 70 && token <= 105; }, + isIdentifier: function () { return token === 70 || token > 106; }, + isReservedWord: function () { return token >= 71 && token <= 106; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -3396,7 +3841,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -3513,20 +3958,20 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } var currChar = text.charCodeAt(pos); if (currChar === 96) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 : 13; + resultingToken = startedWithBacktick ? 13 : 14; break; } if (currChar === 92) { @@ -3688,10 +4133,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69; + return token = 70; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -3763,12 +4208,12 @@ var ts; case 33: if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 33; + return pos += 3, token = 34; } - return pos += 2, token = 31; + return pos += 2, token = 32; } pos++; - return token = 49; + return token = 50; case 34: case 39: tokenValue = scanString(); @@ -3777,51 +4222,39 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 62; + return pos += 2, token = 63; } pos++; - return token = 40; + return token = 41; case 38: if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 51; + return pos += 2, token = 52; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + return pos += 2, token = 67; } pos++; - return token = 46; + return token = 47; case 40: pos++; - return token = 17; + return token = 18; case 41: pos++; - return token = 18; + return token = 19; case 42: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; + return pos += 2, token = 60; } if (text.charCodeAt(pos + 1) === 42) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 60; + return pos += 3, token = 61; } - return pos += 2, token = 38; + return pos += 2, token = 39; } pos++; - return token = 37; + return token = 38; case 43: if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 41; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 57; - } - pos++; - return token = 35; - case 44: - pos++; - return token = 24; - case 45: - if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; } if (text.charCodeAt(pos + 1) === 61) { @@ -3829,16 +4262,28 @@ var ts; } pos++; return token = 36; + case 44: + pos++; + return token = 25; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 43; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 59; + } + pos++; + return token = 37; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 22; + return pos += 3, token = 23; } pos++; - return token = 21; + return token = 22; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -3882,10 +4327,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; + return pos += 2, token = 62; } pos++; - return token = 39; + return token = 40; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -3934,10 +4379,10 @@ var ts; return token = 8; case 58: pos++; - return token = 54; + return token = 55; case 59: pos++; - return token = 23; + return token = 24; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3950,20 +4395,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 63; + return pos += 3, token = 64; } - return pos += 2, token = 43; + return pos += 2, token = 44; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 28; + return pos += 2, token = 29; } if (languageVariant === 1 && text.charCodeAt(pos + 1) === 47 && text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 26; + return pos += 2, token = 27; } pos++; - return token = 25; + return token = 26; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3976,15 +4421,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 32; + return pos += 3, token = 33; } - return pos += 2, token = 30; + return pos += 2, token = 31; } if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 34; + return pos += 2, token = 35; } pos++; - return token = 56; + return token = 57; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3996,43 +4441,43 @@ var ts; } } pos++; - return token = 27; + return token = 28; case 63: pos++; - return token = 53; + return token = 54; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 94: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 69; + } + pos++; + return token = 49; + case 123: + pos++; + return token = 16; + case 124: + if (text.charCodeAt(pos + 1) === 124) { + return pos += 2, token = 53; + } if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } pos++; return token = 48; - case 123: - pos++; - return token = 15; - case 124: - if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 52; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 67; - } - pos++; - return token = 47; case 125: pos++; - return token = 16; + return token = 17; case 126: pos++; - return token = 50; + return token = 51; case 64: pos++; - return token = 55; + return token = 56; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -4070,29 +4515,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27) { + if (token === 28) { if (text.charCodeAt(pos) === 62) { if (text.charCodeAt(pos + 1) === 62) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + return pos += 3, token = 66; } - return pos += 2, token = 45; + return pos += 2, token = 46; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + return pos += 2, token = 65; } pos++; - return token = 44; + return token = 45; } if (text.charCodeAt(pos) === 61) { pos++; - return token = 29; + return token = 30; } } return token; } function reScanSlashToken() { - if (token === 39 || token === 61) { + if (token === 40 || token === 62) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -4131,12 +4576,12 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10; + token = 11; } return token; } function reScanTemplateToken() { - ts.Debug.assert(token === 16, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -4153,14 +4598,14 @@ var ts; if (char === 60) { if (text.charCodeAt(pos + 1) === 47) { pos += 2; - return token = 26; + return token = 27; } pos++; - return token = 25; + return token = 26; } if (char === 123) { pos++; - return token = 15; + return token = 16; } while (pos < end) { pos++; @@ -4169,7 +4614,7 @@ var ts; break; } } - return token = 244; + return token = 10; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -4216,39 +4661,42 @@ var ts; return token = 5; case 64: pos++; - return token = 55; + return token = 56; case 10: case 13: pos++; return token = 4; case 42: pos++; - return token = 37; + return token = 38; case 123: pos++; - return token = 15; + return token = 16; case 125: pos++; - return token = 16; + return token = 17; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 61: pos++; - return token = 56; + return token = 57; case 44: pos++; - return token = 24; + return token = 25; + case 46: + pos++; + return token = 22; } - if (isIdentifierStart(ch, 2)) { + if (isIdentifierStart(ch, 5)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { pos++; } - return token = 69; + return token = 70; } else { return pos += 1, token = 0; @@ -4334,26 +4782,28 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -4368,7 +4818,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -4378,15 +4828,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -4395,27 +4845,32 @@ var ts; "react": 2 }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -4426,11 +4881,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -4439,12 +4894,12 @@ var ts; "lf": 1 }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -4453,7 +4908,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -4462,59 +4917,59 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -4537,30 +4992,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -4571,7 +5026,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -4586,22 +5041,25 @@ var ts; "es3": 0, "es5": 1, "es6": 2, - "es2015": 2 + "es2015": 2, + "es2016": 3, + "es2017": 4, + "esnext": 5, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -4618,10 +5076,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -4743,8 +5201,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4761,12 +5220,21 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -4789,9 +5257,21 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -4809,22 +5289,12 @@ var ts; } ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -4886,7 +5356,11 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -4962,10 +5436,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5059,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5069,14 +5545,15 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -5099,17 +5576,19 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); @@ -5142,6 +5621,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -5169,7 +5651,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -5178,33 +5660,49 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -5266,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5278,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -5334,14 +5832,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_6 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_6)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_6); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_6) ? 1 : 0; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -5362,6 +5859,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 : 0 + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 }; + } + return undefined; + } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); @@ -5395,6 +5905,967 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + JsTyping.nodeCoreModuleList = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console" + ]; + var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { + var inferredTypings = ts.createMap(); + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + if (unresolvedImports) { + for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { + var moduleId = unresolvedImports_1[_a]; + var typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } + } + } + for (var name_6 in packageNameToTypingLocation) { + if (name_6 in inferredTypings && !inferredTypings[name_6]) { + inferredTypings[name_6] = packageNameToTypingLocation[name_6]; + } + } + for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { + var excludeTypingName = exclude_1[_b]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + 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; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LogLevel; + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(LogLevel = server.LogLevel || (server.LogLevel = {})); + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(true), + compilerOptions: project.getCompilerOptions(), + typeAcquisition: typeAcquisition, + unresolvedImports: unresolvedImports, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + function toSortedReadonlyArray(arr) { + arr.sort(); + return arr; + } + server.toSortedReadonlyArray = toSortedReadonlyArray; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2: + case 0: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === 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, typeRoots); + } + } + else { + 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, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, false, state); + return path_1 && { path: path_1, extension: tsExtension }; + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0) || tryResolve(1); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; + } + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case 2: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocations.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocations.push(packageJsonPath); + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(2, moduleName, directory, failedLookupLocations, state, true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== 1) { + return loadModuleFromNodeModulesFolder(2, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0) || tryResolve(1); + return createResolvedModuleWithFailedLookupLocations(resolved, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === 0) { + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5423,13 +6894,14 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, - increaseIndent: function () { }, - decreaseIndent: function () { }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, clear: function () { return str_1 = ""; }, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; } return stringWriters.pop(); @@ -5444,22 +6916,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(array1, array2, equaler) { - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } @@ -5483,7 +6939,9 @@ var ts; } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function typeDirectiveIsEqualTo(oldResolution, newResolution) { @@ -5509,21 +6967,21 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 2097152) !== 0; + return (node.flags & 131072) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 4194304)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 2097152; + node.flags |= 131072; } - node.flags |= 4194304; + node.flags |= 262144; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 256) { + while (node && node.kind !== 261) { node = node.parent; } return node; @@ -5531,11 +6989,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: return true; } return false; @@ -5590,28 +7048,28 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function getTokenPosOfNode(node, sourceFile, includeJsDocComment) { + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; } if (isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); + if (node.kind === 292 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 262 && node.kind <= 288; } ts.isJSDocNode = isJSDocNode; function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; + return node.kind >= 278 && node.kind <= 291; } ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -5656,13 +7114,13 @@ var ts; switch (node.kind) { case 9: return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "`"); case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "${"); case 14: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 15: return getQuotedEscapedLiteralText("}", node.text, "`"); case 8: return node.text; @@ -5700,11 +7158,16 @@ var ts; ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 223 && node.parent.kind === 256; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 225 && + return node && node.kind === 230 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; @@ -5713,11 +7176,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node.kind === 225 && (!node.body); + return node.kind === 230 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 256 || - node.kind === 225 || + return node.kind === 261 || + node.kind === 230 || isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -5730,32 +7193,36 @@ var ts; return false; } switch (node.parent.kind) { - case 256: + case 261: return ts.isExternalModule(node.parent); - case 226: + case 231: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { + case 261: + case 232: case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - case 148: - case 147: - case 149: + case 230: + case 211: + case 212: + case 213: case 150: - case 220: - case 179: - case 180: + case 149: + case 151: + case 152: + case 225: + case 184: + case 185: return true; - case 199: + case 204: return parentNode && !isFunctionLike(parentNode); } return false; @@ -5771,23 +7238,46 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 218 && - declaration.parent && - declaration.parent.kind === 252; - } - ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 70: + return name.text; + case 9: + case 8: + return name.text; + case 142: + if (isStringOrNumericLiteral(name.expression)) { + return name.expression.text; + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 70: + return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name); + case 141: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 177: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; function createDiagnosticForNode(node, message, arg0, arg1, arg2) { var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { var span = getErrorSpanForNode(sourceFile, node); return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } - ts.createDiagnosticForNode = createDiagnosticForNode; + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -5810,7 +7300,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 199) { + if (node.body && node.body.kind === 204) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -5822,29 +7312,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 256: + case 261: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 218: - case 169: - case 221: - case 192: - case 222: - case 225: - case 224: - case 255: - case 220: - case 179: - case 147: - case 149: - case 150: case 223: + case 174: + case 226: + case 197: + case 227: + case 230: + case 229: + case 260: + case 225: + case 184: + case 149: + case 151: + case 152: + case 228: errorNode = node.name; break; - case 180: + case 185: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -5865,7 +7355,7 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 224 && isConst(node); + return node.kind === 229 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -5877,12 +7367,13 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { - return n.kind === 174 && n.expression.kind === 95; + function isSuperCall(n) { + return n.kind === 179 && n.expression.kind === 96; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { - return node.kind === 202 && node.expression.kind === 9; + return node.kind === 207 + && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -5893,92 +7384,87 @@ var ts; return ts.getLeadingCommentRanges(text, node.pos); } ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJsDocComments(node, sourceFileOfNode) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - ts.getJsDocComments = getJsDocComments; - function getJsDocCommentsFromText(node, text) { - var commentRanges = (node.kind === 142 || - node.kind === 141 || - node.kind === 179 || - node.kind === 180) ? + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 144 || + node.kind === 143 || + node.kind === 184 || + node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { + return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && text.charCodeAt(comment.pos + 3) !== 47; - } + }); } - ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (154 <= node.kind && node.kind <= 166) { + if (156 <= node.kind && node.kind <= 171) { return true; } switch (node.kind) { - case 117: - case 130: + case 118: case 132: - case 120: - case 133: + case 134: + case 121: case 135: - case 127: + case 137: + case 129: return true; - case 103: - return node.parent.kind !== 183; - case 194: + case 104: + return node.parent.kind !== 188; + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 69: - if (node.parent.kind === 139 && node.parent.right === node) { + case 70: + if (node.parent.kind === 141 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 172 && node.parent.name === node) { + else if (node.parent.kind === 177 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 139: - case 172: - case 97: + ts.Debug.assert(node.kind === 70 || node.kind === 141 || node.kind === 177, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 141: + case 177: + case 98: var parent_1 = node.parent; - if (parent_1.kind === 158) { + if (parent_1.kind === 160) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (156 <= parent_1.kind && parent_1.kind <= 171) { return true; } switch (parent_1.kind) { - case 194: + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 141: + case 143: return node === parent_1.constraint; - case 145: - case 144: - case 142: - case 218: - return node === parent_1.type; - case 220: - case 179: - case 180: - case 148: case 147: case 146: - case 149: - case 150: + case 144: + case 223: return node === parent_1.type; + case 225: + case 184: + case 185: + case 150: + case 149: + case 148: case 151: case 152: + return node === parent_1.type; case 153: + case 154: + case 155: return node === parent_1.type; - case 177: + case 182: return node === parent_1.type; - case 174: - case 175: + case 179: + case 180: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 176: + case 181: return false; } } @@ -5989,23 +7475,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 211: + case 216: return visitor(node); - case 227: - case 199: - case 203: + case 232: case 204: - case 205: - case 206: - case 207: case 208: + case 209: + case 210: + case 211: case 212: case 213: - case 249: - case 250: - case 214: - case 216: - case 252: + case 217: + case 218: + case 253: + case 254: + case 219: + case 221: + case 256: return ts.forEachChild(node, traverse); } } @@ -6015,23 +7501,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 190: + case 195: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 224: - case 222: - case 225: - case 223: - case 221: - case 192: + case 229: + case 227: + case 230: + case 228: + case 226: + case 197: return; default: if (isFunctionLike(node)) { var name_7 = node.name; - if (name_7 && name_7.kind === 140) { + if (name_7 && name_7.kind === 142) { traverse(name_7.expression); return; } @@ -6043,17 +7529,29 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { - case 169: - case 255: - case 142: - case 253: - case 145: + case 174: + case 260: case 144: - case 254: - case 218: + case 257: + case 147: + case 146: + case 258: + case 223: return true; } } @@ -6061,11 +7559,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 149 || node.kind === 150); + return node && (node.kind === 151 || node.kind === 152); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 221 || node.kind === 192); + return node && (node.kind === 226 || node.kind === 197); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6074,19 +7572,19 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 148: - case 179: - case 220: - case 180: - case 147: - case 146: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return true; } return false; @@ -6094,13 +7592,13 @@ var ts; ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 179: + case 151: + case 152: + case 225: + case 184: return true; } return false; @@ -6108,26 +7606,32 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: + case 211: + case 212: + case 213: + case 209: + case 210: return true; - case 214: + case 219: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 199 && isFunctionLike(node.parent); + return node && node.kind === 204 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 147 && node.parent.kind === 171; + return node && node.kind === 149 && node.parent.kind === 176; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 149 && + (node.parent.kind === 176 || + node.parent.kind === 197); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6161,39 +7665,39 @@ var ts; return undefined; } switch (node.kind) { - case 140: + case 142: if (isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 180: + case 185: if (!includeArrowFunctions) { continue; } - case 220: - case 179: case 225: - case 145: - case 144: + case 184: + case 230: case 147: case 146: - case 148: case 149: + case 148: case 150: case 151: case 152: case 153: - case 224: - case 256: + case 154: + case 155: + case 229: + case 261: return node; } } @@ -6206,25 +7710,25 @@ var ts; return node; } switch (node.kind) { - case 140: + case 142: node = node.parent; break; - case 220: - case 179: - case 180: + case 225: + case 184: + case 185: if (!stopOnFunctions) { continue; } - case 145: - case 144: case 147: case 146: - case 148: case 149: + case 148: case 150: + case 151: + case 152: return node; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { @@ -6236,14 +7740,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 179 || func.kind === 180) { + if (func.kind === 184 || func.kind === 185) { var prev = func; var parent_2 = func.parent; - while (parent_2.kind === 178) { + while (parent_2.kind === 183) { prev = parent_2; parent_2 = parent_2.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { + if (parent_2.kind === 179 && parent_2.expression === prev) { return parent_2; } } @@ -6251,32 +7755,32 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 172 || kind === 173) - && node.expression.kind === 95; + return (kind === 177 || kind === 178) + && node.expression.kind === 96; } ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { - if (node) { - switch (node.kind) { - case 155: - return node.typeName; - case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); - return node.expression; - case 69: - case 139: - return node; - } + switch (node.kind) { + case 157: + case 272: + return node.typeName; + case 199: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 70: + case 141: + return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function isCallLikeExpression(node) { switch (node.kind) { - case 174: - case 175: - case 176: - case 143: + case 179: + case 180: + case 181: + case 145: return true; default: return false; @@ -6284,7 +7788,7 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { - if (node.kind === 176) { + if (node.kind === 181) { return node.tag; } return node.expression; @@ -6292,21 +7796,21 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 221: + case 226: return true; - case 145: - return node.parent.kind === 221; - case 149: - case 150: case 147: + return node.parent.kind === 226; + case 151: + case 152: + case 149: return node.body !== undefined - && node.parent.kind === 221; - case 142: + && node.parent.kind === 226; + case 144: return node.parent.body !== undefined - && (node.parent.kind === 148 - || node.parent.kind === 147 - || node.parent.kind === 150) - && node.parent.parent.kind === 221; + && (node.parent.kind === 150 + || node.parent.kind === 149 + || node.parent.kind === 152) + && node.parent.parent.kind === 226; } return false; } @@ -6322,19 +7826,19 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 221: + case 226: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 147: - case 150: + case 149: + case 152: return ts.forEach(node.parameters, nodeIsDecorated); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 243 || - parent.kind === 242 || - parent.kind === 245) { + if (parent.kind === 248 || + parent.kind === 247 || + parent.kind === 249) { return parent.tagName === node; } return false; @@ -6342,97 +7846,98 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 97: - case 95: - case 93: - case 99: - case 84: - case 10: - case 170: - case 171: - case 172: - case 173: - case 174: + case 98: + case 96: + case 94: + case 100: + case 85: + case 11: case 175: case 176: - case 195: case 177: - case 196: case 178: case 179: - case 192: case 180: - case 183: case 181: + case 200: case 182: + case 201: + case 183: + case 184: + case 197: case 185: + case 188: case 186: case 187: - case 188: - case 191: - case 189: - case 11: - case 193: - case 241: - case 242: case 190: - case 184: + case 191: + case 192: + case 193: + case 196: + case 194: + case 12: + case 198: + case 246: + case 247: + case 195: + case 189: return true; - case 139: - while (node.parent.kind === 139) { + case 141: + while (node.parent.kind === 141) { node = node.parent; } - return node.parent.kind === 158 || isJSXTagName(node); - case 69: - if (node.parent.kind === 158 || isJSXTagName(node)) { + return node.parent.kind === 160 || isJSXTagName(node); + case 70: + if (node.parent.kind === 160 || isJSXTagName(node)) { return true; } case 8: case 9: - case 97: + case 98: var parent_3 = node.parent; switch (parent_3.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 255: - case 253: - case 169: + case 147: + case 146: + case 260: + case 257: + case 174: return parent_3.initializer === node; - case 202: - case 203: - case 204: - case 205: - case 211: - case 212: - case 213: - case 249: - case 215: - case 213: - return parent_3.expression === node; - case 206: - var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || - forStatement.condition === node || - forStatement.incrementor === node; case 207: case 208: + case 209: + case 210: + case 216: + case 217: + case 218: + case 253: + case 220: + case 218: + return parent_3.expression === node; + case 211: + var forStatement = parent_3; + return (forStatement.initializer === node && forStatement.initializer.kind !== 224) || + forStatement.condition === node || + forStatement.incrementor === node; + case 212: + case 213: var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224) || forInStatement.expression === node; - case 177: - case 195: + case 182: + case 200: return node === parent_3.expression; - case 197: + case 202: return node === parent_3.expression; - case 140: + case 142: return node === parent_3.expression; - case 143: - case 248: - case 247: + case 145: + case 252: + case 251: + case 259: return true; - case 194: + case 199: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: if (isPartOfExpression(parent_3)) { @@ -6443,10 +7948,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6454,7 +7955,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind === 240; + return node.kind === 234 && node.moduleReference.kind === 245; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6463,7 +7964,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind !== 240; + return node.kind === 234 && node.moduleReference.kind !== 245; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -6471,12 +7972,12 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 1048576); + return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { - var isRequire = expression.kind === 174 && - expression.expression.kind === 69 && + var isRequire = expression.kind === 179 && + expression.expression.kind === 70 && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9); @@ -6487,9 +7988,9 @@ var ts; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; function isDeclarationOfFunctionExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + if (s.valueDeclaration && s.valueDeclaration.kind === 223) { var declaration = s.valueDeclaration; - return declaration.initializer && declaration.initializer.kind === 179; + return declaration.initializer && declaration.initializer.kind === 184; } return false; } @@ -6498,15 +7999,15 @@ var ts; if (!isInJavaScriptFile(expression)) { return 0; } - if (expression.kind !== 187) { + if (expression.kind !== 192) { return 0; } var expr = expression; - if (expr.operatorToken.kind !== 56 || expr.left.kind !== 172) { + if (expr.operatorToken.kind !== 57 || expr.left.kind !== 177) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 69) { + if (lhs.expression.kind === 70) { var lhsId = lhs.expression; if (lhsId.text === "exports") { return 1; @@ -6515,12 +8016,12 @@ var ts; return 2; } } - else if (lhs.expression.kind === 97) { + else if (lhs.expression.kind === 98) { return 4; } - else if (lhs.expression.kind === 172) { + else if (lhs.expression.kind === 177) { var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 69) { + if (innerPropertyAccess.expression.kind === 70) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { return 1; @@ -6534,35 +8035,35 @@ var ts; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 230) { + if (node.kind === 235) { return node.moduleSpecifier; } - if (node.kind === 229) { + if (node.kind === 234) { var reference = node.moduleReference; - if (reference.kind === 240) { + if (reference.kind === 245) { return reference.expression; } } - if (node.kind === 236) { + if (node.kind === 241) { return node.moduleSpecifier; } - if (node.kind === 225 && node.name.kind === 9) { + if (node.kind === 230 && node.name.kind === 9) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 230 + return node.kind === 235 && node.importClause && !!node.importClause.name; } @@ -6570,13 +8071,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 142: + case 144: + case 149: + case 148: + case 258: + case 257: case 147: case 146: - case 254: - case 253: - case 145: - case 144: return node.questionToken !== undefined; } } @@ -6584,157 +8085,123 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 269 && + return node.kind === 274 && node.parameters.length > 0 && - node.parameters[0].type.kind === 271; + node.parameters[0].type.kind === 276; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getJSDocTag(node, kind, checkParentVariableStatement) { - if (!node) { - return undefined; - } - var jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { - var tag = jsDocTags_1[_i]; - if (tag.kind === kind) { - return tag; - } - } + function getCommentsFromJSDoc(node) { + return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } - function append(previous, additional) { - if (additional) { - if (!previous) { - previous = []; - } - for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { - var x = additional_1[_i]; - previous.push(x); - } - } - return previous; - } - function getJSDocComments(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); - } - ts.getJSDocComments = getJSDocComments; - function getJSDocTags(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { + ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function getJSDocTags(node, kind) { + var docs = getJSDocs(node); + if (docs) { var result = []; for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { var doc = docs_1[_i]; - if (doc.tags) { - result.push.apply(result, doc.tags); + if (doc.kind === 281) { + if (doc.kind === kind) { + result.push(doc); + } + } + else { + result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; })); } } return result; - }, function (tags) { return tags; }); + } } - function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { - var result = undefined; - if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === 200; + function getFirstJSDocTag(node, kind) { + return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + } + function getJSDocs(node) { + var cache = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + function getJSDocsWorker(node) { + var parent = node.parent; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 205; var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + parent.parent.kind === 205; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } - if (node.kind === 225 && - node.parent && node.parent.kind === 225) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); - } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 192 && + parent.operatorToken.kind === 57 && + parent.parent.kind === 207; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + var isModuleDeclaration = node.kind === 230 && + parent && parent.kind === 230; + var isPropertyAssignmentExpression = parent && parent.kind === 257; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } - if (node.kind === 142) { - var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + if (node.kind === 144) { + cache = ts.concatenate(cache, getJSDocParameterTags(node)); } + if (isVariableLike(node) && node.initializer) { + cache = ts.concatenate(cache, node.initializer.jsDoc); + } + cache = ts.concatenate(cache, node.jsDoc); } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); - } - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); - } - else { - return getDocs(node.jsDocComments); - } - } - return result; } - function getJSDocParameterTag(param, checkParentVariableStatement) { + function getJSDocParameterTags(param) { + if (!isParameter(param)) { + return undefined; + } var func = param.parent; - var tags = getJSDocTags(func, checkParentVariableStatement); + var tags = getJSDocTags(func, 281); if (!param.name) { var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281; }); if (paramTags && 0 <= i && i < paramTags.length) { return [paramTags[i]]; } } - else if (param.name.kind === 69) { + else if (param.name.kind === 70) { var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); - if (paramTags) { - return paramTags; - } + return ts.filter(tags, function (tag) { return tag.kind === 281 && tag.parameterName.text === name_8; }); } else { return undefined; } } - function getJSDocTypeTag(node) { - return getJSDocTag(node, 277, false); + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 283); + if (!tag && node.kind === 144) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; } - ts.getJSDocTypeTag = getJSDocTypeTag; + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 276, true); + return getFirstJSDocTag(node, 282); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 278, false); + return getFirstJSDocTag(node, 284); } ts.getJSDocTemplateTag = getJSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter) { - if (parameter.name && parameter.name.kind === 69) { - var parameterName = parameter.name.text; - var jsDocTags = getJSDocTags(parameter.parent, true); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { - var tag = jsDocTags_2[_i]; - if (tag.kind === 275) { - var parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } - } - } - return undefined; - } - ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -6744,14 +8211,11 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 1048576)) { - if (node.type && node.type.kind === 270) { + if (node && (node.flags & 65536)) { + if (node.type && node.type.kind === 275 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275; })) { return true; } - var paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 270; - } } return isDeclaredRestParam(node); } @@ -6760,27 +8224,44 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isAssignmentTarget(node) { - while (node.parent.kind === 178) { - node = node.parent; - } + function getAssignmentTargetKind(node) { + var parent = node.parent; while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; - continue; + switch (parent.kind) { + case 192: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 57 ? 1 : 2 : + 0; + case 190: + case 191: + var unaryOperator = parent.operator; + return unaryOperator === 42 || unaryOperator === 43 ? 2 : 0; + case 212: + case 213: + return parent.initializer === node ? 1 : 0; + case 183: + case 175: + case 196: + node = parent; + break; + case 258: + if (parent.name !== node) { + return 0; + } + case 257: + node = parent.parent; + break; + default: + return 0; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; - continue; - } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + parent = node.parent; } } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } ts.isAssignmentTarget = isAssignmentTarget; function isNodeDescendantOf(node, ancestor) { while (node) { @@ -6793,7 +8274,7 @@ var ts; ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 261 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6802,11 +8283,11 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { + if (name.kind !== 70 && name.kind !== 9 && name.kind !== 8) { return false; } var parent = name.parent; - if (parent.kind === 234 || parent.kind === 238) { + if (parent.kind === 239 || parent.kind === 243) { if (parent.propertyName) { return true; } @@ -6819,48 +8300,48 @@ var ts; ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 140 && + node.parent.kind === 142 && isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 145: - case 144: case 147: case 146: case 149: - case 150: - case 255: - case 253: - case 172: + case 148: + case 151: + case 152: + case 260: + case 257: + case 177: return parent.name === node; - case 139: + case 141: if (parent.right === node) { - while (parent.kind === 139) { + while (parent.kind === 141) { parent = parent.parent; } - return parent.kind === 158; + return parent.kind === 160; } return false; - case 169: - case 234: + case 174: + case 239: return parent.propertyName === node; - case 238: + case 243: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 229 || - node.kind === 228 || - node.kind === 231 && !!node.name || - node.kind === 232 || - node.kind === 234 || - node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + return node.kind === 234 || + node.kind === 233 || + node.kind === 236 && !!node.name || + node.kind === 237 || + node.kind === 239 || + node.kind === 243 || + node.kind === 240 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -6868,17 +8349,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 106); + var heritageClause = getHeritageClause(node.heritageClauses, 107); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -6946,7 +8427,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 <= token && token <= 138; + return 71 <= token && token <= 140; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -6957,8 +8438,10 @@ var ts; return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; - function isStringOrNumericLiteral(kind) { - return kind === 9 || kind === 8; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { @@ -6966,8 +8449,8 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 140 && - !isStringOrNumericLiteral(name.expression.kind) && + return name.kind === 142 && + !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -6976,10 +8459,10 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { + if (name.kind === 70 || name.kind === 9 || name.kind === 8 || name.kind === 144) { return name.text; } - if (name.kind === 140) { + if (name.kind === 142) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -6997,22 +8480,26 @@ var ts; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function isESSymbolIdentifier(node) { - return node.kind === 69 && node.text === "Symbol"; + return node.kind === 70 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.text === "push" || node.text === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isModifierKind(token) { switch (token) { - case 115: - case 118: - case 74: - case 122: - case 77: - case 82: - case 112: - case 110: - case 111: - case 128: + case 116: + case 119: + case 75: + case 123: + case 78: + case 83: case 113: + case 111: + case 112: + case 130: + case 114: return true; } return false; @@ -7020,11 +8507,11 @@ var ts; ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 142; + return root.kind === 144; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 169) { + while (node.kind === 174) { node = node.parent.parent; } return node; @@ -7032,33 +8519,29 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 148 - || kind === 179 - || kind === 220 - || kind === 180 - || kind === 147 - || kind === 149 - || kind === 150 + return kind === 150 + || kind === 184 || kind === 225 - || kind === 256; + || kind === 185 + || kind === 149 + || kind === 151 + || kind === 152 + || kind === 230 + || kind === 261; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - function getOriginalNode(node) { + function getOriginalNode(node, nodeTest) { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; function isParseTreeNode(node) { @@ -7095,38 +8578,38 @@ var ts; ts.getOriginalNodeId = getOriginalNodeId; function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 175: + case 180: return hasArguments ? 0 : 1; - case 185: - case 182: - case 183: - case 181: - case 184: - case 188: case 190: - return 1; case 187: + case 188: + case 186: + case 189: + case 193: + case 195: + return 1; + case 192: switch (operator) { - case 38: - case 56: + case 39: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 1; } } @@ -7135,15 +8618,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 187) { + if (expression.kind === 192) { return expression.operatorToken.kind; } - else if (expression.kind === 185 || expression.kind === 186) { + else if (expression.kind === 190 || expression.kind === 191) { return expression.operator; } else { @@ -7153,106 +8636,107 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 97: - case 95: - case 69: - case 93: - case 99: - case 84: + case 98: + case 96: + case 70: + case 94: + case 100: + case 85: case 8: case 9: - case 170: - case 171: - case 179: - case 180: - case 192: - case 241: - case 242: - case 10: - case 11: - case 189: - case 178: - case 193: - return 19; - case 176: - case 172: - case 173: - return 18; case 175: - return hasArguments ? 18 : 17; - case 174: - return 17; - case 186: - return 16; - case 185: - case 182: - case 183: - case 181: + case 176: case 184: - return 15; + case 185: + case 197: + case 246: + case 247: + case 11: + case 12: + case 194: + case 183: + case 198: + case 297: + return 19; + case 181: + case 177: + case 178: + return 18; + case 180: + return hasArguments ? 18 : 17; + case 179: + return 17; + case 191: + return 16; + case 190: case 187: + case 188: + case 186: + case 189: + return 15; + case 192: switch (operatorKind) { - case 49: case 50: + case 51: return 15; - case 38: - case 37: case 39: + case 38: case 40: + case 41: return 14; - case 35: case 36: + case 37: return 13; - case 43: case 44: case 45: + case 46: return 12; - case 25: - case 28: - case 27: + case 26: case 29: - case 90: - case 91: - return 11; + case 28: case 30: - case 32: + case 91: + case 92: + return 11; case 31: case 33: + case 32: + case 34: return 10; - case 46: - return 9; - case 48: - return 8; case 47: + return 9; + case 49: + return 8; + case 48: return 7; - case 51: - return 6; case 52: + return 6; + case 53: return 5; - case 56: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 3; - case 24: + case 25: return 0; default: return -1; } - case 188: + case 193: return 4; - case 190: + case 195: return 2; - case 191: + case 196: return 1; default: return -1; @@ -7487,48 +8971,46 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - var sourceFiles = host.getSourceFiles(); + var sourceFiles = getAllEmittableSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, isNonDeclarationFile); + var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); }); + } + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles(); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) { + return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); }); + } + ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory; function isNonDeclarationFile(sourceFile) { return !isDeclarationFile(sourceFile); } - function isBundleEmitNonExternalModule(sourceFile) { - return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function isBundleEmitNonExternalModule(sourceFile) { + return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { @@ -7552,10 +9034,10 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } - function onBundledEmit(host, sourceFiles) { + function onBundledEmit(sourceFiles) { if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -7568,16 +9050,16 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) { onSingleFileEmit(host, sourceFile); } } @@ -7595,18 +9077,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { - var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +9097,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7643,7 +9126,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 148 && nodeIsPresent(member.body)) { + if (member.kind === 150 && nodeIsPresent(member.body)) { return member; } }); @@ -7651,13 +9134,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 70 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 98; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7665,10 +9167,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 149) { + if (accessor.kind === 151) { getAccessor = accessor; } - else if (accessor.kind === 150) { + else if (accessor.kind === 152) { setAccessor = accessor; } else { @@ -7677,7 +9179,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 149 || member.kind === 150) + if ((member.kind === 151 || member.kind === 152) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -7688,10 +9190,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 149 && !getAccessor) { + if (member.kind === 151 && !getAccessor) { getAccessor = member; } - if (member.kind === 150 && !setAccessor) { + if (member.kind === 152 && !setAccessor) { setAccessor = member; } } @@ -7874,7 +9376,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4) { + if (node.flags & 4 || (node.kind === 70 && node.isInJSDocNamespace)) { flags |= 1; } node.modifierFlagsCache = flags | 536870912; @@ -7883,46 +9385,52 @@ var ts; ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { - case 113: return 32; - case 112: return 4; - case 111: return 16; - case 110: return 8; - case 115: return 128; - case 82: return 1; - case 122: return 2; - case 74: return 2048; - case 77: return 512; - case 118: return 256; - case 128: return 64; + case 114: return 32; + case 113: return 4; + case 112: return 16; + case 111: return 8; + case 116: return 128; + case 83: return 1; + case 123: return 2; + case 75: return 2048; + case 78: return 512; + case 119: return 256; + case 130: return 64; } return 0; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 52 - || token === 51 - || token === 49; + return token === 53 + || token === 52 + || token === 50; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 56 && token <= 68; + return token >= 57 && token <= 69; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 194 && - node.parent.token === 83 && + if (node.kind === 199 && + node.parent.token === 84 && isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 57 + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === 56) { - var kind = node.left.kind; - return kind === 171 - || kind === 170; - } + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 176 + || kind === 175; } return false; } @@ -7932,7 +9440,7 @@ var ts; } ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { + if (node.kind === 70) { return true; } else if (isPropertyAccessExpression(node)) { @@ -7947,21 +9455,21 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + return node.kind === 70 || + node.kind === 177 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 139 && node.parent.right === node) || - (node.parent.kind === 172 && node.parent.name === node); + return (node.parent.kind === 141 && node.parent.right === node) || + (node.parent.kind === 177 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 171) { + if (kind === 176) { return expression.properties.length === 0; } - if (kind === 170) { + if (kind === 175) { return expression.elements.length === 0; } return false; @@ -7971,14 +9479,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - 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 tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8012,39 +9512,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -8069,12 +9536,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8099,49 +9560,49 @@ var ts; var kind = node.kind; if (kind === 9 || kind === 8 - || kind === 10 || kind === 11 - || kind === 69 - || kind === 97 - || kind === 95 - || kind === 99 - || kind === 84 - || kind === 93) { + || kind === 12 + || kind === 70 + || kind === 98 + || kind === 96 + || kind === 100 + || kind === 85 + || kind === 94) { return true; } - else if (kind === 172) { + else if (kind === 177) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 173) { + else if (kind === 178) { return isSimpleExpressionWorker(node.expression, depth + 1) && isSimpleExpressionWorker(node.argumentExpression, depth + 1); } - else if (kind === 185 - || kind === 186) { + else if (kind === 190 + || kind === 191) { return isSimpleExpressionWorker(node.operand, depth + 1); } - else if (kind === 187) { - return node.operatorToken.kind !== 38 + else if (kind === 192) { + return node.operatorToken.kind !== 39 && isSimpleExpressionWorker(node.left, depth + 1) && isSimpleExpressionWorker(node.right, depth + 1); } - else if (kind === 188) { + else if (kind === 193) { return isSimpleExpressionWorker(node.condition, depth + 1) && isSimpleExpressionWorker(node.whenTrue, depth + 1) && isSimpleExpressionWorker(node.whenFalse, depth + 1); } - else if (kind === 183 - || kind === 182 - || kind === 181) { + else if (kind === 188 + || kind === 187 + || kind === 186) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 170) { + else if (kind === 175) { return node.elements.length === 0; } - else if (kind === 171) { + else if (kind === 176) { return node.properties.length === 0; } - else if (kind === 174) { + else if (kind === 179) { if (!isSimpleExpressionWorker(node.expression, depth + 1)) { return false; } @@ -8175,7 +9636,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,58 +9705,21 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; - function collectExternalModuleInfo(sourceFile, resolver) { - var externalImports = []; - var exportSpecifiers = ts.createMap(); - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; + case 230: + return parseNode === parseNode.parent.name; } } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + return false; } - ts.collectExternalModuleInfo = collectExternalModuleInfo; + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; function getInitializedVariables(node) { return ts.filter(node.declarations, isInitializedVariable); } @@ -8307,7 +9731,7 @@ var ts; if (node.symbol) { for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 && declaration !== node) { + if (declaration.kind === 226 && declaration !== node) { return true; } } @@ -8325,15 +9749,15 @@ var ts; } ts.isNodeArray = isNodeArray; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 11; + return node.kind === 12; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; + return 8 <= kind && kind <= 12; } ts.isLiteralKind = isLiteralKind; function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; + return kind === 9 || kind === 12; } ts.isTextualLiteralKind = isTextualLiteralKind; function isLiteralExpression(node) { @@ -8341,20 +9765,21 @@ var ts; } ts.isLiteralExpression = isLiteralExpression; function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; + return 12 <= kind && kind <= 15; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 - || kind === 14; + function isTemplateHead(node) { + return node.kind === 13; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 14 + || kind === 15; } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { - return node.kind === 69; + return node.kind === 70; } ts.isIdentifier = isIdentifier; function isGeneratedIdentifier(node) { @@ -8366,183 +9791,240 @@ var ts; } ts.isModifier = isModifier; function isQualifiedName(node) { - return node.kind === 139; + return node.kind === 141; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 140; + return node.kind === 142; } ts.isComputedPropertyName = isComputedPropertyName; function isEntityName(node) { var kind = node.kind; - return kind === 139 - || kind === 69; + return kind === 141 + || kind === 70; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9 || kind === 8 - || kind === 140; + || kind === 142; } ts.isPropertyName = isPropertyName; function isModuleName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9; } ts.isModuleName = isModuleName; function isBindingName(node) { var kind = node.kind; - return kind === 69 - || kind === 167 - || kind === 168; + return kind === 70 + || kind === 172 + || kind === 173; } ts.isBindingName = isBindingName; function isTypeParameter(node) { - return node.kind === 141; + return node.kind === 143; } ts.isTypeParameter = isTypeParameter; function isParameter(node) { - return node.kind === 142; + return node.kind === 144; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 143; + return node.kind === 145; } ts.isDecorator = isDecorator; function isMethodDeclaration(node) { - return node.kind === 147; + return node.kind === 149; } ts.isMethodDeclaration = isMethodDeclaration; function isClassElement(node) { var kind = node.kind; - return kind === 148 - || kind === 145 + return kind === 150 || kind === 147 || kind === 149 - || kind === 150 - || kind === 153 - || kind === 198; + || kind === 151 + || kind === 152 + || kind === 155 + || kind === 203; } ts.isClassElement = isClassElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 253 - || kind === 254 - || kind === 147 + return kind === 257 + || kind === 258 + || kind === 259 || kind === 149 - || kind === 150 - || kind === 239; + || kind === 151 + || kind === 152 + || kind === 244; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 154 && kind <= 166) - || kind === 117 - || kind === 130 - || kind === 120 + return (kind >= 156 && kind <= 171) + || kind === 118 || kind === 132 - || kind === 133 - || kind === 103 - || kind === 127 - || kind === 194; + || kind === 121 + || kind === 134 + || kind === 135 + || kind === 104 + || kind === 129 + || kind === 199; } function isTypeNode(node) { return isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; + function isArrayBindingPattern(node) { + return node.kind === 173; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isObjectBindingPattern(node) { + return node.kind === 172; + } + ts.isObjectBindingPattern = isObjectBindingPattern; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 168 - || kind === 167; + return kind === 173 + || kind === 172; } return false; } ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 175 + || kind === 176; + } + ts.isAssignmentPattern = isAssignmentPattern; function isBindingElement(node) { - return node.kind === 169; + return node.kind === 174; } ts.isBindingElement = isBindingElement; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 169 - || kind === 193; + return kind === 174 + || kind === 198; } ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 223: + case 144: + case 174: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 172: + case 176: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isArrayLiteralExpression(node) { + return node.kind === 175; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 176; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 172; + return node.kind === 177; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 173; + return node.kind === 178; } ts.isElementAccessExpression = isElementAccessExpression; function isBinaryExpression(node) { - return node.kind === 187; + return node.kind === 192; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 188; + return node.kind === 193; } ts.isConditionalExpression = isConditionalExpression; function isCallExpression(node) { - return node.kind === 174; + return node.kind === 179; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; - return kind === 189 - || kind === 11; + return kind === 194 + || kind === 12; } - ts.isTemplate = isTemplate; - function isSpreadElementExpression(node) { - return node.kind === 191; + ts.isTemplateLiteral = isTemplateLiteral; + function isSpreadExpression(node) { + return node.kind === 196; } - ts.isSpreadElementExpression = isSpreadElementExpression; + ts.isSpreadExpression = isSpreadExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 194; + return node.kind === 199; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isLeftHandSideExpressionKind(kind) { - return kind === 172 - || kind === 173 - || kind === 175 - || kind === 174 - || kind === 241 - || kind === 242 - || kind === 176 - || kind === 170 + return kind === 177 || kind === 178 - || kind === 171 - || kind === 192 + || kind === 180 || kind === 179 - || kind === 69 - || kind === 10 + || kind === 246 + || kind === 247 + || kind === 181 + || kind === 175 + || kind === 183 + || kind === 176 + || kind === 197 + || kind === 184 + || kind === 70 + || kind === 11 || kind === 8 || kind === 9 - || kind === 11 - || kind === 189 - || kind === 84 - || kind === 93 - || kind === 97 - || kind === 99 - || kind === 95 - || kind === 196; + || kind === 12 + || kind === 194 + || kind === 85 + || kind === 94 + || kind === 98 + || kind === 100 + || kind === 96 + || kind === 201 + || kind === 297; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isUnaryExpressionKind(kind) { - return kind === 185 + return kind === 190 + || kind === 191 || kind === 186 - || kind === 181 + || kind === 187 + || kind === 188 + || kind === 189 || kind === 182 - || kind === 183 - || kind === 184 - || kind === 177 || isLeftHandSideExpressionKind(kind); } function isUnaryExpression(node) { @@ -8550,13 +10032,14 @@ var ts; } ts.isUnaryExpression = isUnaryExpression; function isExpressionKind(kind) { - return kind === 188 - || kind === 190 - || kind === 180 - || kind === 187 - || kind === 191 + return kind === 193 || kind === 195 - || kind === 193 + || kind === 185 + || kind === 192 + || kind === 196 + || kind === 200 + || kind === 198 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8565,16 +10048,16 @@ var ts; ts.isExpression = isExpression; function isAssertionExpression(node) { var kind = node.kind; - return kind === 177 - || kind === 195; + return kind === 182 + || kind === 200; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 294; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 293; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -8583,15 +10066,15 @@ var ts; } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isOmittedExpression(node) { - return node.kind === 193; + return node.kind === 198; } ts.isOmittedExpression = isOmittedExpression; function isTemplateSpan(node) { - return node.kind === 197; + return node.kind === 202; } ts.isTemplateSpan = isTemplateSpan; function isBlock(node) { - return node.kind === 199; + return node.kind === 204; } ts.isBlock = isBlock; function isConciseBody(node) { @@ -8609,119 +10092,121 @@ var ts; } ts.isForInitializer = isForInitializer; function isVariableDeclaration(node) { - return node.kind === 218; + return node.kind === 223; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 219; + return node.kind === 224; } ts.isVariableDeclarationList = isVariableDeclarationList; function isCaseBlock(node) { - return node.kind === 227; + return node.kind === 232; } ts.isCaseBlock = isCaseBlock; function isModuleBody(node) { var kind = node.kind; - return kind === 226 - || kind === 225; + return kind === 231 + || kind === 230; } ts.isModuleBody = isModuleBody; function isImportEqualsDeclaration(node) { - return node.kind === 229; + return node.kind === 234; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportClause(node) { - return node.kind === 231; + return node.kind === 236; } ts.isImportClause = isImportClause; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 233 - || kind === 232; + return kind === 238 + || kind === 237; } ts.isNamedImportBindings = isNamedImportBindings; function isImportSpecifier(node) { - return node.kind === 234; + return node.kind === 239; } ts.isImportSpecifier = isImportSpecifier; function isNamedExports(node) { - return node.kind === 237; + return node.kind === 242; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 238; + return node.kind === 243; } ts.isExportSpecifier = isExportSpecifier; function isModuleOrEnumDeclaration(node) { - return node.kind === 225 || node.kind === 224; + return node.kind === 230 || node.kind === 229; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 180 - || kind === 169 - || kind === 221 - || kind === 192 - || kind === 148 - || kind === 224 - || kind === 255 - || kind === 238 - || kind === 220 - || kind === 179 - || kind === 149 - || kind === 231 + return kind === 185 + || kind === 174 + || kind === 226 + || kind === 197 + || kind === 150 || kind === 229 + || kind === 260 + || kind === 243 + || kind === 225 + || kind === 184 + || kind === 151 + || kind === 236 || kind === 234 - || kind === 222 + || kind === 239 + || kind === 227 + || kind === 149 + || kind === 148 + || kind === 230 + || kind === 233 + || kind === 237 + || kind === 144 + || kind === 257 || kind === 147 || kind === 146 - || kind === 225 + || kind === 152 + || kind === 258 || kind === 228 - || kind === 232 - || kind === 142 - || kind === 253 - || kind === 145 - || kind === 144 - || kind === 150 - || kind === 254 + || kind === 143 || kind === 223 - || kind === 141 - || kind === 218 - || kind === 279; + || kind === 285; } function isDeclarationStatementKind(kind) { - return kind === 220 - || kind === 239 - || kind === 221 - || kind === 222 - || kind === 223 - || kind === 224 - || kind === 225 - || kind === 230 + return kind === 225 + || kind === 244 + || kind === 226 + || kind === 227 + || kind === 228 || kind === 229 - || kind === 236 + || kind === 230 || kind === 235 - || kind === 228; + || kind === 234 + || kind === 241 + || kind === 240 + || kind === 233; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 210 - || kind === 209 - || kind === 217 - || kind === 204 - || kind === 202 - || kind === 201 - || kind === 207 - || kind === 208 - || kind === 206 - || kind === 203 + return kind === 215 || kind === 214 - || kind === 211 - || kind === 213 - || kind === 215 - || kind === 216 - || kind === 200 - || kind === 205 + || kind === 222 + || kind === 209 + || kind === 207 + || kind === 206 || kind === 212 - || kind === 287; + || kind === 213 + || kind === 211 + || kind === 208 + || kind === 219 + || kind === 216 + || kind === 218 + || kind === 220 + || kind === 221 + || kind === 205 + || kind === 210 + || kind === 217 + || kind === 293 + || kind === 296 + || kind === 295; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8739,87 +10224,87 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 199; + || kind === 204; } ts.isStatement = isStatement; function isModuleReference(node) { var kind = node.kind; - return kind === 240 - || kind === 139 - || kind === 69; + return kind === 245 + || kind === 141 + || kind === 70; } ts.isModuleReference = isModuleReference; function isJsxOpeningElement(node) { - return node.kind === 243; + return node.kind === 248; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 245; + return node.kind === 249; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 97 - || kind === 69 - || kind === 172; + return kind === 98 + || kind === 70 + || kind === 177; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 241 - || kind === 248 - || kind === 242 - || kind === 244; + return kind === 246 + || kind === 252 + || kind === 247 + || kind === 10; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 246 - || kind === 247; + return kind === 250 + || kind === 251; } ts.isJsxAttributeLike = isJsxAttributeLike; function isJsxSpreadAttribute(node) { - return node.kind === 247; + return node.kind === 251; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxAttribute(node) { - return node.kind === 246; + return node.kind === 250; } ts.isJsxAttribute = isJsxAttribute; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 248; + || kind === 252; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 249 - || kind === 250; + return kind === 253 + || kind === 254; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isHeritageClause(node) { - return node.kind === 251; + return node.kind === 255; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 252; + return node.kind === 256; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 253; + return node.kind === 257; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 254; + return node.kind === 258; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 256; + return node.kind === 261; } ts.isSourceFile = isSourceFile; function isWatchSet(options) { @@ -8827,10 +10312,19 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { - return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case 5: + case 4: + return "lib.es2017.d.ts"; + case 3: + return "lib.es2016.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } } ts.getDefaultLibFileName = getDefaultLibFileName; function textSpanEnd(span) { @@ -8949,9 +10443,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 141) { + if (d && d.kind === 143) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 222) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227) { return current; } } @@ -8959,11 +10453,11 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 150 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + while (node && (node.kind === 174 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -8971,14 +10465,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= ts.getModifierFlags(node); } return flags; @@ -8987,26 +10481,73 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; })(ts || (ts = {})); var ts; (function (ts) { var NodeConstructor; var SourceFileConstructor; function createNode(kind, location, flags) { - var ConstructorForKind = kind === 256 + var ConstructorForKind = kind === 261 ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); var node = location @@ -9062,7 +10603,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9087,14 +10628,14 @@ var ts; return node; } else if (typeof value === "boolean") { - return createNode(value ? 99 : 84, location, undefined); + return createNode(value ? 100 : 85, location, undefined); } else if (typeof value === "string") { var node = createNode(9, location, undefined); node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9104,7 +10645,7 @@ var ts; ts.createLiteral = createLiteral; var nextAutoGenerateId = 0; function createIdentifier(text, location) { - var node = createNode(69, location); + var node = createNode(70, location); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = ts.stringToToken(text); node.autoGenerateKind = 0; @@ -9113,7 +10654,7 @@ var ts; } ts.createIdentifier = createIdentifier; function createTempVariable(recordTempVariable, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 1; @@ -9126,7 +10667,7 @@ var ts; } ts.createTempVariable = createTempVariable; function createLoopVariable(location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 2; @@ -9136,7 +10677,7 @@ var ts; } ts.createLoopVariable = createLoopVariable; function createUniqueName(text, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = text; name.originalKeywordKind = 0; name.autoGenerateKind = 3; @@ -9146,7 +10687,7 @@ var ts; } ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.original = node; name.text = ""; name.originalKeywordKind = 0; @@ -9161,22 +10702,22 @@ var ts; } ts.createToken = createToken; function createSuper() { - var node = createNode(95); + var node = createNode(96); return node; } ts.createSuper = createSuper; function createThis(location) { - var node = createNode(97, location); + var node = createNode(98, location); return node; } ts.createThis = createThis; function createNull() { - var node = createNode(93); + var node = createNode(94); return node; } ts.createNull = createNull; function createComputedPropertyName(expression, location) { - var node = createNode(140, location); + var node = createNode(142, location); node.expression = expression; return node; } @@ -9188,12 +10729,8 @@ var ts; return node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createParameter(name, initializer, location) { - return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); - } - ts.createParameter = createParameter; - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { - var node = createNode(142, location, flags); + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(144, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.dotDotDotToken = dotDotDotToken; @@ -9203,16 +10740,16 @@ var ts; node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; return node; } - ts.createParameterDeclaration = createParameterDeclaration; - function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); } return node; } - ts.updateParameterDeclaration = updateParameterDeclaration; + ts.updateParameter = updateParameter; function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { - var node = createNode(145, location); + var node = createNode(147, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9230,7 +10767,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(147, location, flags); + var node = createNode(149, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -9250,7 +10787,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body, location, flags) { - var node = createNode(148, location, flags); + var node = createNode(150, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = undefined; @@ -9268,7 +10805,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { - var node = createNode(149, location, flags); + var node = createNode(151, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9287,7 +10824,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { - var node = createNode(150, location, flags); + var node = createNode(152, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9305,7 +10842,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createObjectBindingPattern(elements, location) { - var node = createNode(167, location); + var node = createNode(172, location); node.elements = createNodeArray(elements); return node; } @@ -9318,7 +10855,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements, location) { - var node = createNode(168, location); + var node = createNode(173, location); node.elements = createNodeArray(elements); return node; } @@ -9331,7 +10868,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { - var node = createNode(169, location); + var node = createNode(174, location); node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; node.dotDotDotToken = dotDotDotToken; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9339,15 +10876,15 @@ var ts; return node; } ts.createBindingElement = createBindingElement; - function updateBindingElement(node, propertyName, name, initializer) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, location, multiLine) { - var node = createNode(170, location); + var node = createNode(175, location); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) { node.multiLine = true; @@ -9363,7 +10900,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, location, multiLine) { - var node = createNode(171, location); + var node = createNode(176, location); node.properties = createNodeArray(properties); if (multiLine) { node.multiLine = true; @@ -9379,9 +10916,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name, location, flags) { - var node = createNode(172, location, flags); + var node = createNode(177, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 65536; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,14 +10926,14 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index, location) { - var node = createNode(173, location); + var node = createNode(178, location); node.expression = parenthesizeForAccess(expression); node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; return node; @@ -9410,7 +10947,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(174, location, flags); + var node = createNode(179, location, flags); node.expression = parenthesizeForAccess(expression); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -9427,7 +10964,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(175, location, flags); + var node = createNode(180, location, flags); node.expression = parenthesizeForNew(expression); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -9442,7 +10979,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template, location) { - var node = createNode(176, location); + var node = createNode(181, location); node.tag = parenthesizeForAccess(tag); node.template = template; return node; @@ -9456,7 +10993,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createParen(expression, location) { - var node = createNode(178, location); + var node = createNode(183, location); node.expression = expression; return node; } @@ -9468,9 +11005,9 @@ var ts; return node; } ts.updateParen = updateParen; - function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(179, location, flags); - node.modifiers = undefined; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(184, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -9480,20 +11017,20 @@ var ts; return node; } ts.createFunctionExpression = createFunctionExpression; - function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); } return node; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { - var node = createNode(180, location, flags); + var node = createNode(185, location, flags); node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35); node.body = parenthesizeConciseBody(body); return node; } @@ -9506,7 +11043,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression, location) { - var node = createNode(181, location); + var node = createNode(186, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9519,7 +11056,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression, location) { - var node = createNode(182, location); + var node = createNode(187, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9532,7 +11069,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression, location) { - var node = createNode(183, location); + var node = createNode(188, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9545,7 +11082,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression, location) { - var node = createNode(184, location); + var node = createNode(189, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9558,7 +11095,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand, location) { - var node = createNode(185, location); + var node = createNode(190, location); node.operator = operator; node.operand = parenthesizePrefixOperand(operand); return node; @@ -9572,7 +11109,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator, location) { - var node = createNode(186, location); + var node = createNode(191, location); node.operand = parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -9586,9 +11123,9 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; - var node = createNode(187, location); + var node = createNode(192, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); node.operatorToken = operatorToken; node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); @@ -9602,13 +11139,21 @@ var ts; return node; } ts.updateBinary = updateBinary; - function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { - var node = createNode(188, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) { + var node = createNode(193, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + node.questionToken = createToken(54); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(55); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } ts.createConditional = createConditional; @@ -9620,7 +11165,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans, location) { - var node = createNode(189, location); + var node = createNode(194, location); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -9634,7 +11179,7 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createYield(asteriskToken, expression, location) { - var node = createNode(190, location); + var node = createNode(195, location); node.asteriskToken = asteriskToken; node.expression = expression; return node; @@ -9648,7 +11193,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression, location) { - var node = createNode(191, location); + var node = createNode(196, location); node.expression = parenthesizeExpressionForList(expression); return node; } @@ -9661,7 +11206,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(192, location); + var node = createNode(197, location); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -9679,12 +11224,12 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression(location) { - var node = createNode(193, location); + var node = createNode(198, location); return node; } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression, location) { - var node = createNode(194, location); + var node = createNode(199, location); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.expression = parenthesizeForAccess(expression); return node; @@ -9698,7 +11243,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createTemplateSpan(expression, literal, location) { - var node = createNode(197, location); + var node = createNode(202, location); node.expression = expression; node.literal = literal; return node; @@ -9712,7 +11257,7 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createBlock(statements, location, multiLine, flags) { - var block = createNode(199, location, flags); + var block = createNode(204, location, flags); block.statements = createNodeArray(statements); if (multiLine) { block.multiLine = true; @@ -9728,7 +11273,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList, location, flags) { - var node = createNode(200, location, flags); + var node = createNode(205, location, flags); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -9743,7 +11288,7 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createVariableDeclarationList(declarations, location, flags) { - var node = createNode(219, location, flags); + var node = createNode(224, location, flags); node.declarations = createNodeArray(declarations); return node; } @@ -9756,7 +11301,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createVariableDeclaration(name, type, initializer, location, flags) { - var node = createNode(218, location, flags); + var node = createNode(223, location, flags); node.name = typeof name === "string" ? createIdentifier(name) : name; node.type = type; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -9771,11 +11316,11 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement(location) { - return createNode(201, location); + return createNode(206, location); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression, location, flags) { - var node = createNode(202, location, flags); + var node = createNode(207, location, flags); node.expression = parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -9788,7 +11333,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement, location) { - var node = createNode(203, location); + var node = createNode(208, location); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -9803,7 +11348,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression, location) { - var node = createNode(204, location); + var node = createNode(209, location); node.statement = statement; node.expression = expression; return node; @@ -9817,7 +11362,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement, location) { - var node = createNode(205, location); + var node = createNode(210, location); node.expression = expression; node.statement = statement; return node; @@ -9831,7 +11376,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement, location) { - var node = createNode(206, location, undefined); + var node = createNode(211, location, undefined); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -9847,7 +11392,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement, location) { - var node = createNode(207, location); + var node = createNode(212, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -9862,7 +11407,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(initializer, expression, statement, location) { - var node = createNode(208, location); + var node = createNode(213, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -9877,7 +11422,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label, location) { - var node = createNode(209, location); + var node = createNode(214, location); if (label) { node.label = label; } @@ -9892,7 +11437,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label, location) { - var node = createNode(210, location); + var node = createNode(215, location); if (label) { node.label = label; } @@ -9907,7 +11452,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression, location) { - var node = createNode(211, location); + var node = createNode(216, location); node.expression = expression; return node; } @@ -9920,7 +11465,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement, location) { - var node = createNode(212, location); + var node = createNode(217, location); node.expression = expression; node.statement = statement; return node; @@ -9934,7 +11479,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock, location) { - var node = createNode(213, location); + var node = createNode(218, location); node.expression = parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -9948,7 +11493,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement, location) { - var node = createNode(214, location); + var node = createNode(219, location); node.label = typeof label === "string" ? createIdentifier(label) : label; node.statement = statement; return node; @@ -9962,7 +11507,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression, location) { - var node = createNode(215, location); + var node = createNode(220, location); node.expression = expression; return node; } @@ -9975,7 +11520,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock, location) { - var node = createNode(216, location); + var node = createNode(221, location); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -9990,7 +11535,7 @@ var ts; } ts.updateTry = updateTry; function createCaseBlock(clauses, location) { - var node = createNode(227, location); + var node = createNode(232, location); node.clauses = createNodeArray(clauses); return node; } @@ -10003,7 +11548,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(220, location, flags); + var node = createNode(225, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -10023,7 +11568,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(221, location); + var node = createNode(226, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -10041,7 +11586,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { - var node = createNode(230, location); + var node = createNode(235, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.importClause = importClause; @@ -10057,7 +11602,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings, location) { - var node = createNode(231, location); + var node = createNode(236, location); node.name = name; node.namedBindings = namedBindings; return node; @@ -10071,7 +11616,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name, location) { - var node = createNode(232, location); + var node = createNode(237, location); node.name = name; return node; } @@ -10084,7 +11629,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements, location) { - var node = createNode(233, location); + var node = createNode(238, location); node.elements = createNodeArray(elements); return node; } @@ -10097,7 +11642,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name, location) { - var node = createNode(234, location); + var node = createNode(239, location); node.propertyName = propertyName; node.name = name; return node; @@ -10111,7 +11656,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { - var node = createNode(235, location); + var node = createNode(240, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.isExportEquals = isExportEquals; @@ -10127,7 +11672,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { - var node = createNode(236, location); + var node = createNode(241, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.exportClause = exportClause; @@ -10143,7 +11688,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements, location) { - var node = createNode(237, location); + var node = createNode(242, location); node.elements = createNodeArray(elements); return node; } @@ -10156,7 +11701,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(name, propertyName, location) { - var node = createNode(238, location); + var node = createNode(243, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; return node; @@ -10170,7 +11715,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createJsxElement(openingElement, children, closingElement, location) { - var node = createNode(241, location); + var node = createNode(246, location); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -10185,7 +11730,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes, location) { - var node = createNode(242, location); + var node = createNode(247, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -10199,7 +11744,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes, location) { - var node = createNode(243, location); + var node = createNode(248, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -10213,7 +11758,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName, location) { - var node = createNode(245, location); + var node = createNode(249, location); node.tagName = tagName; return node; } @@ -10226,7 +11771,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxAttribute(name, initializer, location) { - var node = createNode(246, location); + var node = createNode(250, location); node.name = name; node.initializer = initializer; return node; @@ -10240,7 +11785,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxSpreadAttribute(expression, location) { - var node = createNode(247, location); + var node = createNode(251, location); node.expression = expression; return node; } @@ -10253,7 +11798,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(expression, location) { - var node = createNode(248, location); + var node = createNode(252, location); node.expression = expression; return node; } @@ -10266,7 +11811,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createHeritageClause(token, types, location) { - var node = createNode(251, location); + var node = createNode(255, location); node.token = token; node.types = createNodeArray(types); return node; @@ -10280,7 +11825,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements, location) { - var node = createNode(249, location); + var node = createNode(253, location); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -10294,7 +11839,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements, location) { - var node = createNode(250, location); + var node = createNode(254, location); node.statements = createNodeArray(statements); return node; } @@ -10307,7 +11852,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createCatchClause(variableDeclaration, block, location) { - var node = createNode(252, location); + var node = createNode(256, location); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -10321,7 +11866,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer, location) { - var node = createNode(253, location); + var node = createNode(257, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.questionToken = undefined; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -10336,12 +11881,18 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { - var node = createNode(254, location); + var node = createNode(258, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function createSpreadAssignment(expression, location) { + var node = createNode(259, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -10349,9 +11900,16 @@ var ts; return node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSpreadAssignment(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createNode(256, node, node.flags); + var updated = createNode(261, node, node.flags); updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; @@ -10405,21 +11963,33 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) - updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } return node; } ts.updateSourceFileNode = updateSourceFileNode; function createNotEmittedStatement(original) { - var node = createNode(287, original); + var node = createNode(293, original); node.original = original; return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + function createEndOfDeclarationMarker(original) { + var node = createNode(296); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + function createMergeDeclarationMarker(original) { + var node = createNode(295); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original, location) { - var node = createNode(288, location || original); + var node = createNode(294, location || original); node.expression = expression; node.original = original; return node; @@ -10432,69 +12002,77 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createRawExpression(text) { + var node = createNode(297); + node.text = text; + return node; + } + ts.createRawExpression = createRawExpression; function createComma(left, right) { - return createBinary(left, 24, right); + return createBinary(left, 25, right); } ts.createComma = createComma; function createLessThan(left, right, location) { - return createBinary(left, 25, right, location); + return createBinary(left, 26, right, location); } ts.createLessThan = createLessThan; function createAssignment(left, right, location) { - return createBinary(left, 56, right, location); + return createBinary(left, 57, right, location); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 32, right); + return createBinary(left, 33, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 33, right); + return createBinary(left, 34, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 35, right); + return createBinary(left, 36, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 36, right); + return createBinary(left, 37, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand, location) { - return createPostfix(operand, 41, location); + return createPostfix(operand, 42, location); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 51, right); + return createBinary(left, 52, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 52, right); + return createBinary(left, 53, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(49, operand); + return createPrefix(50, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { return createVoid(createLiteral(0)); } ts.createVoidZero = createVoidZero; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; function createMemberAccessForPropertyName(target, memberName, location) { if (ts.isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 64; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; - function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); - } - ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { return createCall(createPropertyAccess(func, "call"), undefined, [ thisArg @@ -10527,10 +12105,26 @@ var ts; function createReactNamespace(reactNamespace, parent) { var react = createIdentifier(reactNamespace || "React"); react.flags &= ~8; - react.parent = parent; + react.parent = ts.getParseTreeNode(parent); return react; } - function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = createSynthesizedNode(70); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { var argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -10550,9 +12144,21 @@ var ts; argumentsList.push(children[0]); } } - return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList, location); } - ts.createReactCreateElement = createReactCreateElement; + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExportDefault(expression) { + return createExportAssignment(undefined, undefined, false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(undefined, undefined, createNamedExports([createExportSpecifier(exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function createLetStatement(name, initializer, location) { + return createVariableStatement(undefined, createLetDeclarationList([createVariableDeclaration(name, undefined, initializer)]), location); + } + ts.createLetStatement = createLetStatement; function createLetDeclarationList(declarations, location) { return createVariableDeclarationList(declarations, location, 1); } @@ -10561,130 +12167,26 @@ var ts; return createVariableDeclarationList(declarations, location, 2); } ts.createConstDeclarationList = createConstDeclarationList; - function createHelperName(externalHelpersModuleName, name) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + function getHelperName(name) { + return setEmitFlags(createIdentifier(name), 4096 | 2); } - ts.createHelperName = createHelperName; - function createExtendsHelper(externalHelpersModuleName, name) { - return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ - name, - createIdentifier("_super") - ]); - } - ts.createExtendsHelper = createExtendsHelper; - function createAssignHelper(externalHelpersModuleName, attributesSegments) { - return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); - } - ts.createAssignHelper = createAssignHelper; - function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { - return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ - createLiteral(parameterOffset), - expression - ], location); - } - ts.createParamHelper = createParamHelper; - function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { - return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ - createLiteral(metadataKey), - metadataValue - ]); - } - ts.createMetadataHelper = createMetadataHelper; - function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { - var argumentsArray = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); - } - ts.createDecorateHelper = createDecorateHelper; - function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; - return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ]); - } - ts.createAwaiterHelper = createAwaiterHelper; - function createHasOwnProperty(target, propertyName) { - return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); - } - ts.createHasOwnProperty = createHasOwnProperty; - function createObjectCreate(prototype) { - return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); - } - function createGeti(target) { - return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); - } - function createSeti(target) { - return createArrowFunction(undefined, undefined, [ - createParameter("name"), - createParameter("value") - ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); - } - function createAdvancedAsyncSuperHelper() { - var createCache = createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) - ])); - var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ - createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) - ])); - var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ - createStatement(createCall(createIdentifier("seti"), undefined, [ - createIdentifier("name"), - createIdentifier("v") - ])) - ])); - var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ - getter, - setter - ])))))); - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ - createParameter("geti"), - createParameter("seti") - ], undefined, createBlock([ - createCache, - getOrCreateAccessorsForName - ]))), undefined, [ - createGeti(createSuper()), - createSeti(createSuper()) - ])) - ])); - } - ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; - function createSimpleAsyncSuperHelper() { - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createGeti(createSuper())) - ])); - } - ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + ts.getHelperName = getHelperName; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 69: + case 70: return cacheIdentifiers; - case 97: + case 98: case 8: case 9: return false; - case 170: + case 175: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 171: + case 176: return target.properties.length > 0; default: return true; @@ -10698,13 +12200,13 @@ var ts; thisArg = createThis(); target = callee; } - else if (callee.kind === 95) { + else if (callee.kind === 96) { thisArg = createThis(); target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; } else { switch (callee.kind) { - case 172: { + case 177: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); @@ -10715,7 +12217,7 @@ var ts; } break; } - case 173: { + case 178: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); @@ -10765,14 +12267,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 149: - case 150: + case 151: + case 152: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 253: + case 257: return createExpressionForPropertyAssignment(property, receiver); - case 254: + case 258: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 147: + case 149: return createExpressionForMethodDeclaration(property, receiver); } } @@ -10782,13 +12284,13 @@ var ts; if (property === firstAccessor) { var properties_1 = []; if (getAccessor) { - var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + var getterFunction = createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); setOriginalNode(getterFunction, getAccessor); var getter = createPropertyAssignment("get", getterFunction); properties_1.push(getter); } if (setAccessor) { - var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + var setterFunction = createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); setOriginalNode(setterFunction, setAccessor); var setter = createPropertyAssignment("set", setterFunction); properties_1.push(setter); @@ -10811,13 +12313,70 @@ var ts; return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); } + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384); + } + ts.getLocalName = getLocalName; + function isLocalName(node) { + return (getEmitFlags(node) & 16384) !== 0; + } + ts.isLocalName = isLocalName; + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192); + } + ts.getExportName = getExportName; + function isExportName(node) { + return (getEmitFlags(node) & 8192) !== 0; + } + ts.isExportName = isExportName; + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { + var name_10 = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(name_10, emitFlags); + return name_10; + } + return getGeneratedNameForNode(node); + } + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), name); + var emitFlags; + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : createBlock([createReturn(node, node)], node, multiLine); + } + ts.convertToFunctionBody = convertToFunctionBody; function isUseStrictPrologue(node) { return node.expression.text === "use strict"; } function addPrologueDirectives(target, source, ensureUseStrict, visitor) { - ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; var statementOffset = 0; var numStatements = source.length; @@ -10830,25 +12389,58 @@ var ts; target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (statement.emitFlags & 8388608) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (getEmitFlags(statement) & 524288) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + function ensureUseStrict(statements) { + var foundUseStrict = false; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))) + ].concat(statements), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 178) { + if (skipped.kind === 183) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -10857,15 +12449,15 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(192, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(192, binaryOperator); var emittedOperand = skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 190) { + && operand.kind === 195) { return false; } return true; @@ -10881,7 +12473,7 @@ var ts; if (operatorHasAssociativeProperty(binaryOperator)) { return false; } - if (binaryOperator === 35) { + if (binaryOperator === 36) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -10894,17 +12486,17 @@ var ts; } } function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 37 + return binaryOperator === 38 + || binaryOperator === 48 || binaryOperator === 47 - || binaryOperator === 46 - || binaryOperator === 48; + || binaryOperator === 49; } function getLiteralKindOfBinaryPlusOperand(node) { node = skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.kind === 192 && node.operatorToken.kind === 36) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -10918,12 +12510,27 @@ var ts; } return 0; } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(193, 54); + var emittedCondition = skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + return createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + return e.kind === 192 && e.operatorToken.kind === 25 + ? createParen(e) + : e; + } function parenthesizeForNew(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { - case 174: + case 179: return createParen(expression); - case 175: + case 180: return emittedExpression.arguments ? expression : createParen(expression); @@ -10934,7 +12541,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && (emittedExpression.kind !== 180 || emittedExpression.arguments) && emittedExpression.kind !== 8) { return expression; } @@ -10972,7 +12579,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(187, 24); + var commaPrecedence = ts.getOperatorPrecedence(192, 25); return expressionPrecedence > commaPrecedence ? expression : createParen(expression, expression); @@ -10983,7 +12590,7 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 179 || kind === 180) { + if (kind === 184 || kind === 185) { var mutableCall = getMutableClone(emittedExpression); mutableCall.expression = createParen(callee, callee); return recreatePartiallyEmittedExpressions(expression, mutableCall); @@ -10991,7 +12598,7 @@ var ts; } else { var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + if (leftmostExpressionKind === 176 || leftmostExpressionKind === 184) { return createParen(expression, expression); } } @@ -11009,21 +12616,21 @@ var ts; function getLeftmostExpression(node) { while (true) { switch (node.kind) { - case 186: + case 191: node = node.operand; continue; - case 187: + case 192: node = node.left; continue; - case 188: + case 193: node = node.condition; continue; - case 174: - case 173: - case 172: + case 179: + case 178: + case 177: node = node.expression; continue; - case 288: + case 294: node = node.expression; continue; } @@ -11032,7 +12639,7 @@ var ts; } function parenthesizeConciseBody(body) { var emittedBody = skipPartiallyEmittedExpressions(body); - if (emittedBody.kind === 171) { + if (emittedBody.kind === 176) { return createParen(body, body); } return body; @@ -11057,7 +12664,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 178) { + while (node.kind === 183) { node = node.expression; } return node; @@ -11071,7 +12678,7 @@ var ts; } ts.skipAssertions = skipAssertions; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 294) { node = node.expression; } return node; @@ -11085,17 +12692,214 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + if (!destEmitNode) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 261) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { + if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var helpers = getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + if (!helper.scoped) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!ts.contains(emitNode.helpers, helper)) { + emitNode.helpers = ts.append(emitNode.helpers, helper); + } + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!ts.contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0; + if (x.priority === y.priority) + return 0; + if (x.priority === undefined) + return 1; + if (y.priority === undefined) + return -1; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11125,10 +12929,10 @@ var ts; var name_11 = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } - if (node.kind === 230 && node.importClause) { + if (node.kind === 235 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 236 && node.moduleSpecifier) { + if (node.kind === 241 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; @@ -11166,6 +12970,291 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + return ts.isAssignmentExpression(bindingElement.initializer, true) + ? bindingElement.initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return bindingElement.right; + } + if (ts.isSpreadExpression(bindingElement)) { + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 257: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 258: + return bindingElement.name; + case 259: + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadExpression(bindingElement)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 144: + case 174: + return bindingElement.dotDotDotToken; + case 196: + case 259: + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 174: + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 257: + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 259: + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 172: + case 173: + case 175: + return name.elements; + case 176: + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return convertToArrayAssignmentPattern(node); + case 172: + case 176: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportedBindings = ts.createMap(); + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration(undefined, undefined, createImportClause(undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 235: + externalImports.push(node); + break; + case 234: + if (node.moduleReference.kind === 245) { + externalImports.push(node); + } + break; + case 241: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports[specifier.name.text]) { + var name_12 = specifier.propertyName || specifier.name; + ts.multiMapAdd(exportSpecifiers, name_12.text, specifier); + var decl = resolver.getReferencedImportDeclaration(name_12) + || resolver.getReferencedValueDeclaration(name_12); + if (decl) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); + } + uniqueExports[specifier.name.text] = true; + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 240: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 205: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 225: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_13 = node.name; + if (!uniqueExports[name_13.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_13); + uniqueExports[name_13.text] = true; + exportedNames = ts.append(exportedNames, name_13); + } + } + } + break; + case 226: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_14 = node.name; + if (!uniqueExports[name_14.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_14); + uniqueExports[name_14.text] = true; + exportedNames = ts.append(exportedNames, name_14); + } + } + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -11174,13 +13263,13 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 256) { + if (kind === 261) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { + else if (kind === 70) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } - else if (kind < 139) { + else if (kind < 141) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); } else { @@ -11216,26 +13305,28 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 139: + case 141: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 141: + case 143: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 254: + case 258: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 142: - case 145: + case 259: + return visitNode(cbNode, node.expression); case 144: - case 253: - case 218: - case 169: + case 147: + case 146: + case 257: + case 223: + case 174: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -11244,24 +13335,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 156: - case 157: - case 151: - case 152: + case 158: + case 159: case 153: + case 154: + case 155: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 179: - case 220: - case 180: + case 151: + case 152: + case 184: + case 225: + case 185: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -11272,308 +13363,320 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 155: + case 157: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 154: + case 156: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 158: - return visitNode(cbNode, node.exprName); - case 159: - return visitNodes(cbNodes, node.members); case 160: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 161: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 162: + return visitNode(cbNode, node.elementType); case 163: - return visitNodes(cbNodes, node.types); + return visitNodes(cbNodes, node.elementTypes); case 164: - return visitNode(cbNode, node.type); + case 165: + return visitNodes(cbNodes, node.types); case 166: - return visitNode(cbNode, node.literal); - case 167: case 168: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); + case 169: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); case 170: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); case 171: - return visitNodes(cbNodes, node.properties); + return visitNode(cbNode, node.literal); case 172: + case 173: + return visitNodes(cbNodes, node.elements); + case 175: + return visitNodes(cbNodes, node.elements); + case 176: + return visitNodes(cbNodes, node.properties); + case 177: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 173: + case 178: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 174: - case 175: + case 179: + case 180: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 176: + case 181: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 177: + case 182: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 178: - return visitNode(cbNode, node.expression); - case 181: - return visitNode(cbNode, node.expression); - case 182: - return visitNode(cbNode, node.expression); case 183: return visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.operand); + case 186: + return visitNode(cbNode, node.expression); + case 187: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); case 190: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 184: + case 189: return visitNode(cbNode, node.expression); - case 186: + case 191: return visitNode(cbNode, node.operand); - case 187: + case 192: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 195: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 196: + case 201: return visitNode(cbNode, node.expression); - case 188: + case 193: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 191: + case 196: return visitNode(cbNode, node.expression); - case 199: - case 226: + case 204: + case 231: return visitNodes(cbNodes, node.statements); - case 256: + case 261: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 200: + case 205: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 219: + case 224: return visitNodes(cbNodes, node.declarations); - case 202: + case 207: return visitNode(cbNode, node.expression); - case 203: + case 208: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 204: + case 209: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 205: + case 210: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206: + case 211: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 207: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 208: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 209: - case 210: - return visitNode(cbNode, node.label); - case 211: - return visitNode(cbNode, node.expression); case 212: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 213: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + case 215: + return visitNode(cbNode, node.label); + case 216: + return visitNode(cbNode, node.expression); + case 217: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 218: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 227: + case 232: return visitNodes(cbNodes, node.clauses); - case 249: + case 253: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 250: + case 254: return visitNodes(cbNodes, node.statements); - case 214: + case 219: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 215: + case 220: return visitNode(cbNode, node.expression); - case 216: + case 221: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 252: + case 256: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 143: + case 145: return visitNode(cbNode, node.expression); - case 221: - case 192: + case 226: + case 197: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 222: + case 227: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 223: + case 228: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 224: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 255: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 225: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); case 229: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNodes(cbNodes, node.members); + case 260: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 230: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 234: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 235: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 231: + case 236: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228: - return visitNode(cbNode, node.name); - case 232: - return visitNode(cbNode, node.name); case 233: + return visitNode(cbNode, node.name); case 237: + return visitNode(cbNode, node.name); + case 238: + case 242: return visitNodes(cbNodes, node.elements); - case 236: + case 241: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 234: - case 238: + case 239: + case 243: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 235: + case 240: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 197: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 140: - return visitNode(cbNode, node.expression); - case 251: - return visitNodes(cbNodes, node.types); case 194: + return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); + case 202: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 142: + return visitNode(cbNode, node.expression); + case 255: + return visitNodes(cbNodes, node.types); + case 199: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 240: + case 245: return visitNode(cbNode, node.expression); - case 239: + case 244: return visitNodes(cbNodes, node.decorators); - case 241: + case 246: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 242: - case 243: + case 247: + case 248: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 246: + case 250: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 247: + case 251: return visitNode(cbNode, node.expression); - case 248: + case 252: return visitNode(cbNode, node.expression); - case 245: + case 249: return visitNode(cbNode, node.tagName); - case 257: - return visitNode(cbNode, node.type); - case 261: - return visitNodes(cbNodes, node.types); case 262: - return visitNodes(cbNodes, node.types); - case 260: - return visitNode(cbNode, node.elementType); - case 264: - return visitNode(cbNode, node.type); - case 263: - return visitNode(cbNode, node.type); - case 265: - return visitNode(cbNode, node.literal); - case 267: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 268: - return visitNode(cbNode, node.type); - case 269: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 270: - return visitNode(cbNode, node.type); - case 271: - return visitNode(cbNode, node.type); - case 272: return visitNode(cbNode, node.type); case 266: + return visitNodes(cbNodes, node.types); + case 267: + return visitNodes(cbNodes, node.types); + case 265: + return visitNode(cbNode, node.elementType); + case 269: + return visitNode(cbNode, node.type); + case 268: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.literal); + case 272: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 273: + return visitNode(cbNode, node.type); + case 274: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 275: + return visitNode(cbNode, node.type); + case 276: + return visitNode(cbNode, node.type); + case 277: + return visitNode(cbNode, node.type); + case 271: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 273: + case 278: return visitNodes(cbNodes, node.tags); - case 275: + case 281: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 276: + case 282: return visitNode(cbNode, node.typeExpression); - case 277: + case 283: return visitNode(cbNode, node.typeExpression); - case 278: + case 280: + return visitNode(cbNode, node.typeExpression); + case 284: return visitNodes(cbNodes, node.typeParameters); - case 279: + case 285: return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.jsDocTypeLiteral); - case 281: + case 287: return visitNodes(cbNodes, node.jsDocPropertyTags); - case 280: + case 286: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 288: + case 294: return visitNode(cbNode, node.expression); - case 282: + case 288: return visitNode(cbNode, node.literal); } } @@ -11587,6 +13690,10 @@ var ts; return result; } ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } @@ -11609,8 +13716,8 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 32768 | 131072; + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -11626,18 +13733,27 @@ var ts; var parsingContext; var contextFlags; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; function getLanguageVariant(scriptKind) { return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; } - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); TokenConstructor = ts.objectAllocator.getTokenConstructor(); IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); @@ -11649,7 +13765,7 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -11684,7 +13800,7 @@ var ts; return sourceFile; } function addJSDocComment(node) { - var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; @@ -11692,10 +13808,10 @@ var ts; if (!jsDoc) { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } return node; @@ -11710,12 +13826,12 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -11724,7 +13840,7 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(261, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -11744,16 +13860,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 32768); + setContextFlag(val, 2048); } function setYieldContext(val) { - setContextFlag(val, 65536); + setContextFlag(val, 4096); } function setDecoratorContext(val) { - setContextFlag(val, 131072); + setContextFlag(val, 8192); } function setAwaitContext(val) { - setContextFlag(val, 262144); + setContextFlag(val, 16384); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -11776,40 +13892,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(32768, func); + return doOutsideOfContext(2048, func); } function disallowInAnd(func) { - return doInsideOfContext(32768, func); + return doInsideOfContext(2048, func); } function doInYieldContext(func) { - return doInsideOfContext(65536, func); + return doInsideOfContext(4096, func); } function doInDecoratorContext(func) { - return doInsideOfContext(131072, func); + return doInsideOfContext(8192, func); } function doInAwaitContext(func) { - return doInsideOfContext(262144, func); + return doInsideOfContext(16384, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(262144, func); + return doOutsideOfContext(16384, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(65536 | 262144, func); + return doInsideOfContext(4096 | 16384, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(65536); + return inContext(4096); } function inDisallowInContext() { - return inContext(32768); + return inContext(2048); } function inDecoratorContext() { - return inContext(131072); + return inContext(8192); } function inAwaitContext() { - return inContext(262144); + return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -11880,16 +13996,16 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token() === 70) { return true; } - if (token() === 114 && inYieldContext()) { + if (token() === 115 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token() === 120 && inAwaitContext()) { return false; } - return token() > 105; + return token() > 106; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -11930,20 +14046,20 @@ var ts; return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token() === 24) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token() === 17 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token() === 24) { nextToken(); } return true; } else { - return parseExpected(23); + return parseExpected(24); } } function createNode(kind, pos) { @@ -11951,8 +14067,8 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + return kind >= 141 ? new NodeConstructor(kind, pos, pos) : + kind === 70 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } function createNodeArray(elements, pos) { @@ -11971,7 +14087,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 524288; + node.flags |= 32768; } return node; } @@ -11993,15 +14109,15 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(69); - if (token() !== 69) { + var node = createNode(70); + if (token() !== 70) { node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); } - return createMissingNode(69, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(70, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -12018,7 +14134,7 @@ var ts; if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token() === 20) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -12033,10 +14149,10 @@ var ts; return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { - var node = createNode(140); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(142); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); return finishNode(node); } function parseContextualModifier(t) { @@ -12050,20 +14166,20 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { - return nextToken() === 81; + if (token() === 75) { + return nextToken() === 82; } - if (token() === 82) { + if (token() === 83) { nextToken(); - if (token() === 77) { + if (token() === 78) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token() !== 38 && token() !== 117 && token() !== 16 && canFollowModifier(); } - if (token() === 77) { + if (token() === 78) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token() === 114) { nextToken(); return canFollowModifier(); } @@ -12073,16 +14189,16 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token() === 20 + || token() === 16 + || token() === 38 + || token() === 23 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 74 || token() === 88 || + (token() === 119 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -12093,21 +14209,23 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 24 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token() === 72 || token() === 78; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 24 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token() === 20 || token() === 38 || token() === 23 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || token() === 23 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token() === 16) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -12119,39 +14237,39 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); - case 17: + return token() === 25 || token() === 23 || isIdentifierOrPattern(); + case 18: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token() === 25 || token() === 23 || isStartOfExpression(); case 16: return isStartOfParameter(); - case 18: case 19: - return token() === 24 || isStartOfType(); case 20: - return isHeritageClause(); + return token() === 25 || isStartOfType(); case 21: + return isHeritageClause(); + case 22: return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 16; case 14: return true; - case 22: case 23: - case 25: - return JSDocParser.isJSDocType(); case 24: + case 26: + return JSDocParser.isJSDocType(); + case 25: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); - if (nextToken() === 16) { + ts.Debug.assert(token() === 16); + if (nextToken() === 17) { var next = nextToken(); - return next === 24 || next === 15 || next === 83 || next === 106; + return next === 25 || next === 16 || next === 84 || next === 107; } return true; } @@ -12164,8 +14282,8 @@ var ts; return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token() === 107 || + token() === 84) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -12186,40 +14304,41 @@ var ts; case 6: case 12: case 9: - case 21: - return token() === 16; + case 22: + return token() === 17; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token() === 17 || token() === 72 || token() === 78; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token() === 16 || token() === 84 || token() === 107; case 8: return isVariableDeclaratorListTerminator(); - case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; - case 11: - return token() === 18 || token() === 23; - case 15: - case 19: - case 10: - return token() === 20; - case 16: - return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() === 28 || token() === 18 || token() === 16 || token() === 84 || token() === 107; + case 11: + return token() === 19 || token() === 24; + case 15: case 20: - return token() === 15 || token() === 16; + case 10: + return token() === 21; + case 16: + case 17: + return token() === 19 || token() === 21; + case 19: + return token() !== 25; + case 21: + return token() === 16 || token() === 17; case 13: - return token() === 27 || token() === 39; + return token() === 28 || token() === 40; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); - case 22: - return token() === 18 || token() === 54 || token() === 16; + return token() === 26 && lookAhead(nextTokenIsSlash); case 23: - return token() === 27 || token() === 16; - case 25: - return token() === 20 || token() === 16; + return token() === 19 || token() === 55 || token() === 17; case 24: - return token() === 16; + return token() === 28 || token() === 17; + case 26: + return token() === 21 || token() === 17; + case 25: + return token() === 17; } } function isVariableDeclaratorListTerminator() { @@ -12229,13 +14348,13 @@ var ts; if (isInOrOfKeyword(token())) { return true; } - if (token() === 34) { + if (token() === 35) { return true; } return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 26; kind++) { + for (var kind = 0; kind < 27; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -12286,7 +14405,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 1540096; + var nodeContextFlags = node.flags & 96256; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -12318,10 +14437,12 @@ var ts; return isReusableVariableDeclaration(node); case 16: return isReusableParameter(node); - case 20: case 17: - case 19: + return false; + case 21: case 18: + case 20: + case 19: case 11: case 12: case 7: @@ -12333,17 +14454,17 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 148: - case 153: - case 149: case 150: - case 145: - case 198: - return true; + case 155: + case 151: + case 152: case 147: + case 203: + return true; + case 149: var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 69 && - methodDeclaration.name.originalKeywordKind === 121; + var nameIsConstructor = methodDeclaration.name.kind === 70 && + methodDeclaration.name.originalKeywordKind === 122; return !nameIsConstructor; } } @@ -12352,8 +14473,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 249: - case 250: + case 253: + case 254: return true; } } @@ -12362,65 +14483,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 220: - case 200: - case 199: - case 203: - case 202: - case 215: - case 211: - case 213: - case 210: - case 209: - case 207: - case 208: - case 206: - case 205: - case 212: - case 201: - case 216: - case 214: - case 204: - case 217: - case 230: - case 229: - case 236: - case 235: case 225: + case 205: + case 204: + case 208: + case 207: + case 220: + case 216: + case 218: + case 215: + case 214: + case 212: + case 213: + case 211: + case 210: + case 217: + case 206: case 221: + case 219: + case 209: case 222: - case 224: - case 223: + case 235: + case 234: + case 241: + case 240: + case 230: + case 226: + case 227: + case 229: + case 228: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 152: + case 154: + case 148: + case 155: case 146: case 153: - case 144: - case 151: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 218) { + if (node.kind !== 223) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 142) { + if (node.kind !== 144) { return false; } var parameter = node; @@ -12440,6 +14561,7 @@ var ts; case 1: return ts.Diagnostics.Declaration_or_statement_expected; case 2: return ts.Diagnostics.case_or_default_expected; case 3: return ts.Diagnostics.Statement_expected; + case 17: case 4: return ts.Diagnostics.Property_or_signature_expected; case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6: return ts.Diagnostics.Enum_member_expected; @@ -12451,17 +14573,17 @@ var ts; case 12: return ts.Diagnostics.Property_assignment_expected; case 15: return ts.Diagnostics.Expression_or_comma_expected; case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 17: return ts.Diagnostics.Type_parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_argument_expected; - case 19: return ts.Diagnostics.Type_expected; - case 20: return ts.Diagnostics.Unexpected_token_expected; - case 21: return ts.Diagnostics.Identifier_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; - case 22: return ts.Diagnostics.Parameter_declaration_expected; - case 23: return ts.Diagnostics.Type_argument_expected; - case 25: return ts.Diagnostics.Type_expected; - case 24: return ts.Diagnostics.Property_assignment_expected; + case 23: return ts.Diagnostics.Parameter_declaration_expected; + case 24: return ts.Diagnostics.Type_argument_expected; + case 26: return ts.Diagnostics.Type_expected; + case 25: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -12474,15 +14596,15 @@ var ts; if (isListElement(kind, false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(24)) { + if (parseOptional(25)) { continue; } commaStart = -1; if (isListTerminator(kind)) { break; } - parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + parseExpected(25); + if (considerSemicolonAsDelimiter && token() === 24 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -12514,8 +14636,8 @@ var ts; } function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(21)) { - var node = createNode(139, entity.pos); + while (parseOptional(22)) { + var node = createNode(141, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -12526,33 +14648,33 @@ var ts; if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); + return createMissingNode(70, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(189); - template.head = parseTemplateLiteralFragment(); - ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); + var template = createNode(194); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 13, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 14); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(197); + var span = createNode(202); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token() === 17) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); + literal = parseExpectedToken(15, false, ts.Diagnostics._0_expected, ts.tokenToString(17)); } span.literal = literal; return finishNode(span); @@ -12560,8 +14682,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 14 || fragment.kind === 15, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -12585,35 +14714,35 @@ var ts; } function parseTypeReference() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - var node = createNode(155, typeName.pos); + var node = createNode(157, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (!scanner.hasPrecedingLineBreak() && token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(154, lhs.pos); + var node = createNode(156, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(165); + var node = createNode(167); nextToken(); return finishNode(node); } function parseTypeQuery() { - var node = createNode(158); - parseExpected(101); + var node = createNode(160); + parseExpected(102); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(141); + var node = createNode(143); node.name = parseIdentifier(); - if (parseOptional(83)) { + if (parseOptional(84)) { if (isStartOfType() || !isStartOfExpression()) { node.constraint = parseType(); } @@ -12624,34 +14753,34 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { - return parseBracketedList(17, parseTypeParameter, 25, 27); + if (token() === 26) { + return parseBracketedList(18, parseTypeParameter, 26, 28); } } function parseParameterType() { - if (parseOptional(54)) { + if (parseOptional(55)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token() === 23 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 || token() === 98; } function parseParameter() { - var node = createNode(142); - if (token() === 97) { + var node = createNode(144); + if (token() === 98) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(22); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } - node.questionToken = parseOptionalToken(53); + node.questionToken = parseOptionalToken(54); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(true); return addJSDocComment(finishNode(node)); @@ -12663,7 +14792,7 @@ var ts; return parseInitializer(true); } function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 34; + var returnTokenRequired = returnToken === 35; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { @@ -12675,7 +14804,7 @@ var ts; } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(17)) { + if (parseExpected(18)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); @@ -12683,7 +14812,7 @@ var ts; var result = parseDelimitedList(16, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(18) && requireCompleteParameterList) { + if (!parseExpected(19) && requireCompleteParameterList) { return undefined; } return result; @@ -12691,29 +14820,29 @@ var ts; return requireCompleteParameterList ? undefined : createMissingList(); } function parseTypeMemberSemicolon() { - if (parseOptional(24)) { + if (parseOptional(25)) { return; } parseSemicolon(); } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 152) { - parseExpected(92); + if (kind === 154) { + parseExpected(93); } - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token() !== 19) { + if (token() !== 20) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token() === 23 || token() === 21) { return true; } if (ts.isModifierKind(token())) { @@ -12728,43 +14857,43 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token() === 55 || token() === 25) { return true; } - if (token() !== 53) { + if (token() !== 54) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token() === 55 || token() === 25 || token() === 21; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(153, fullStart); + var node = createNode(155, fullStart); node.decorators = decorators; node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 19, 20); + node.parameters = parseBracketedList(16, parseParameter, 20, 21); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { - var method = createNode(146, fullStart); + var questionToken = parseOptionalToken(54); + if (token() === 18 || token() === 26) { + var method = createNode(148, fullStart); method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; - fillSignature(54, false, false, false, method); + fillSignature(55, false, false, false, method); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(method)); } else { - var property = createNode(144, fullStart); + var property = createNode(146, fullStart); property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token() === 57) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -12773,14 +14902,14 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token() === 18 || token() === 26) { return true; } while (ts.isModifierKind(token())) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (isLiteralPropertyName()) { @@ -12788,21 +14917,21 @@ var ts; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || + return token() === 18 || + token() === 26 || token() === 54 || - token() === 24 || + token() === 55 || + token() === 25 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { - return parseSignatureMember(151); + if (token() === 18 || token() === 26) { + return parseSignatureMember(153); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(152); + if (token() === 93 && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(154); } var fullStart = getNodePos(); var modifiers = parseModifiers(); @@ -12813,50 +14942,77 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token() === 18 || token() === 26; } function parseTypeLiteral() { - var node = createNode(159); + var node = createNode(161); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(15)) { + if (parseExpected(16)) { members = parseList(4, parseTypeMember); - parseExpected(16); + parseExpected(17); } else { members = createMissingList(); } return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === 130) { + nextToken(); + } + return token() === 20 && nextTokenIsIdentifier() && nextToken() === 91; + } + function parseMappedTypeParameter() { + var node = createNode(143); + node.name = parseIdentifier(); + parseExpected(91); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(170); + parseExpected(16); + node.readonlyToken = parseOptionalToken(130); + parseExpected(20); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(21); + node.questionToken = parseOptionalToken(54); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(17); + return finishNode(node); + } function parseTupleType() { - var node = createNode(161); - node.elementTypes = parseBracketedList(19, parseType, 19, 20); + var node = createNode(163); + node.elementTypes = parseBracketedList(20, parseType, 20, 21); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(164); - parseExpected(17); - node.type = parseType(); + var node = createNode(166); parseExpected(18); + node.type = parseType(); + parseExpected(19); return finishNode(node); } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 157) { - parseExpected(92); + if (kind === 159) { + parseExpected(93); } - fillSignature(34, false, false, false, node); + fillSignature(35, false, false, false, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; + return token() === 22 ? undefined : node; } function parseLiteralTypeNode() { - var node = createNode(166); + var node = createNode(171); node.literal = parseSimpleUnaryExpression(); finishNode(node); return node; @@ -12866,41 +15022,41 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: + case 121: case 135: - case 127: + case 137: + case 129: var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseLiteralTypeNode(); - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 103: - case 93: + case 104: + case 94: return parseTokenNode(); - case 97: { + case 98: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 101: + case 102: return parseTypeQuery(); - case 15: - return parseTypeLiteral(); - case 19: + case 16: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 20: return parseTupleType(); - case 17: + case 18: return parseParenthesizedType(); default: return parseTypeReference(); @@ -12908,29 +15064,31 @@ var ts; } function isStartOfType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: + case 104: + case 137: + case 94: + case 98: + case 102: + case 129: + case 16: + case 20: + case 26: + case 48: + case 47: case 93: - case 97: - case 101: - case 127: - case 15: - case 19: - case 25: - case 92: case 9: case 8: - case 99: - case 84: + case 100: + case 85: return true; - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral); - case 17: + case 18: return lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); @@ -12938,19 +15096,43 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token() === 19 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(19)) { - parseExpected(20); - var node = createNode(160, type.pos); - node.elementType = type; - type = finishNode(node); + while (!scanner.hasPrecedingLineBreak() && parseOptional(20)) { + if (isStartOfType()) { + var node = createNode(169, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(21); + type = finishNode(node); + } + else { + var node = createNode(162, type.pos); + node.elementType = type; + parseExpected(21); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator) { + var node = createNode(168); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 126: + return parseTypeOperator(126); + } + return parseArrayTypeOrHigher(); + } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { var types = createNodeArray([type], type.pos); @@ -12965,26 +15147,26 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(163, parseArrayTypeOrHigher, 46); + return parseUnionOrIntersectionType(165, parseTypeOperatorOrHigher, 47); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); + return parseUnionOrIntersectionType(164, parseIntersectionTypeOrHigher, 48); } function isStartOfFunctionType() { - if (token() === 25) { + if (token() === 26) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 18 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token() === 98) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token() === 20 || token() === 16) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -12993,17 +15175,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token() === 19 || token() === 23) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token() === 55 || token() === 25 || + token() === 54 || token() === 57) { return true; } - if (token() === 18) { + if (token() === 19) { nextToken(); - if (token() === 34) { + if (token() === 35) { return true; } } @@ -13014,7 +15196,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(154, typePredicateVariable.pos); + var node = createNode(156, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -13025,46 +15207,46 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(327680, parseTypeWorker); + return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(156); + return parseFunctionOrConstructorType(158); } - if (token() === 92) { - return parseFunctionOrConstructorType(157); + if (token() === 93) { + return parseFunctionOrConstructorType(159); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(54) ? parseType() : undefined; + return parseOptional(55) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { switch (token()) { - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: case 8: case 9: - case 11: case 12: - case 17: - case 19: - case 15: - case 87: - case 73: - case 92: - case 39: - case 61: - case 69: + case 13: + case 18: + case 20: + case 16: + case 88: + case 74: + case 93: + case 40: + case 62: + case 70: return true; default: return isIdentifier(); @@ -13075,18 +15257,18 @@ var ts; return true; } switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 41: + case 79: + case 102: + case 104: case 42: - case 25: - case 119: - case 114: + case 43: + case 26: + case 120: + case 115: return true; default: if (isBinaryOperator()) { @@ -13096,10 +15278,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token() !== 16 && + token() !== 88 && + token() !== 74 && + token() !== 56 && isStartOfExpression(); } function parseExpression() { @@ -13109,7 +15291,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(24))) { + while ((operatorToken = parseOptionalToken(25))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -13118,12 +15300,12 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token() !== 57) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 16) || !isStartOfExpression()) { return undefined; } } - parseExpected(56); + parseExpected(57); return parseAssignmentExpressionOrHigher(); } function parseAssignmentExpressionOrHigher() { @@ -13135,7 +15317,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 70 && token() === 35) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -13144,7 +15326,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token() === 115) { if (inYieldContext()) { return true; } @@ -13157,11 +15339,11 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(190); + var node = createNode(195); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(37); + (token() === 38 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(38); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -13170,21 +15352,21 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 35, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(180, asyncModifier.pos); + node = createNode(185, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(180, identifier.pos); + node = createNode(185, identifier.pos); } - var parameter = createNode(142, identifier.pos); + var parameter = createNode(144, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -13201,78 +15383,78 @@ var ts; } var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 34 || lastToken === 15) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 35 || lastToken === 16) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token() === 18 || token() === 26 || token() === 119) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token() === 35) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token() !== 18 && token() !== 26) { return 0; } } var first = token(); var second = nextToken(); - if (first === 17) { - if (second === 18) { + if (first === 18) { + if (second === 19) { var third = nextToken(); switch (third) { - case 34: - case 54: - case 15: + case 35: + case 55: + case 16: return 1; default: return 0; } } - if (second === 19 || second === 15) { + if (second === 20 || second === 16) { return 2; } - if (second === 22) { + if (second === 23) { return 1; } if (!isIdentifier()) { return 0; } - if (nextToken() === 54) { + if (nextToken() === 55) { return 1; } return 2; } else { - ts.Debug.assert(first === 25); + ts.Debug.assert(first === 26); if (!isIdentifier()) { return 0; } if (sourceFile.languageVariant === 1) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 83) { + if (third === 84) { var fourth = nextToken(); switch (fourth) { - case 56: - case 27: + case 57: + case 28: return false; default: return true; } } - else if (third === 24) { + else if (third === 25) { return true; } return false; @@ -13289,7 +15471,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token() === 119) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -13300,38 +15482,38 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 35) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 70 && token() === 35) { return 1; } } return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(180); + var node = createNode(185); node.modifiers = parseModifiersForArrowFunction(); var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(54, false, isAsync, !allowAmbiguity, node); + fillSignature(55, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token() !== 35 && token() !== 16) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token() === 16) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token() !== 24 && + token() !== 88 && + token() !== 74 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -13341,15 +15523,15 @@ var ts; : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); } function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(53); + var questionToken = parseOptionalToken(54); if (!questionToken) { return leftOperand; } - var node = createNode(188, leftOperand.pos); + var node = createNode(193, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(54, false, ts.Diagnostics._0_expected, ts.tokenToString(54)); + node.colonToken = parseExpectedToken(55, false, ts.Diagnostics._0_expected, ts.tokenToString(55)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -13358,22 +15540,22 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 || t === 138; + return t === 91 || t === 140; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token() === 39 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token() === 91 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token() === 117) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -13389,92 +15571,92 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token() === 91) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 52: + case 53: return 1; - case 51: + case 52: return 2; - case 47: - return 3; case 48: + return 3; + case 49: return 4; - case 46: + case 47: return 5; - case 30: case 31: case 32: case 33: + case 34: return 6; - case 25: - case 27: + case 26: case 28: case 29: + case 30: + case 92: case 91: - case 90: - case 116: + case 117: return 7; - case 43: case 44: case 45: + case 46: return 8; - case 35: case 36: - return 9; case 37: - case 39: - case 40: - return 10; + return 9; case 38: + case 40: + case 41: + return 10; + case 39: return 11; } return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(187, left.pos); + var node = createNode(192, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(195, left.pos); + var node = createNode(200, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(185); + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(181); + var node = createNode(186); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(182); + var node = createNode(187); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(183); + var node = createNode(188); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token() === 120) { if (inAwaitContext()) { return true; } @@ -13483,7 +15665,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(184); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13491,15 +15673,15 @@ var ts; function parseUnaryExpressionOrHigher() { if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token() === 39 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token() === 39) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 177) { + if (simpleUnaryExpression.kind === 182) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -13510,20 +15692,20 @@ var ts; } function parseSimpleUnaryExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: return parsePrefixUnaryExpression(); - case 78: + case 79: return parseDeleteExpression(); - case 101: + case 102: return parseTypeOfExpression(); - case 103: + case 104: return parseVoidExpression(); - case 25: + case 26: return parseTypeAssertion(); - case 119: + case 120: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -13533,16 +15715,16 @@ var ts; } function isUpdateExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 119: + case 79: + case 102: + case 104: + case 120: return false; - case 25: + case 26: if (sourceFile.languageVariant !== 1) { return false; } @@ -13551,20 +15733,20 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { - var node = createNode(185); + if (token() === 42 || token() === 43) { + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 26 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(186, expression.pos); + if ((token() === 42 || token() === 43) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(191, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -13573,7 +15755,7 @@ var ts; return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token() === 96 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -13584,12 +15766,12 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token() === 18 || token() === 22 || token() === 20) { return expression; } - var node = createNode(172, expression.pos); + var node = createNode(177, expression.pos); node.expression = expression; - parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(22, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -13597,10 +15779,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 69) { + if (lhs.kind === 70) { return lhs.text === rhs.text; } - if (lhs.kind === 97) { + if (lhs.kind === 98) { return true; } return lhs.name.text === rhs.name.text && @@ -13609,8 +15791,8 @@ var ts; function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 243) { - var node = createNode(241, opening.pos); + if (opening.kind === 248) { + var node = createNode(246, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -13620,18 +15802,18 @@ var ts; result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 242); + ts.Debug.assert(opening.kind === 247); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token() === 26) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(187, result.pos); + var badNode = createNode(192, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(24, false, undefined); + badNode.operatorToken = createMissingNode(25, false, undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -13639,17 +15821,17 @@ var ts; return result; } function parseJsxText() { - var node = createNode(244, scanner.getStartPos()); + var node = createNode(10, scanner.getStartPos()); currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 244: + case 10: return parseJsxText(); - case 15: + case 16: return parseJsxExpression(false); - case 25: + case 26: return parseJsxElementOrSelfClosingElement(false); } ts.Debug.fail("Unknown JSX child kind " + token()); @@ -13660,7 +15842,7 @@ var ts; parsingContext |= 1 << 14; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + if (token() === 27) { break; } else if (token() === 1) { @@ -13675,24 +15857,24 @@ var ts; } function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(25); + parseExpected(26); var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { - node = createNode(243, fullStart); + if (token() === 28) { + node = createNode(248, fullStart); scanJsxText(); } else { - parseExpected(39); + parseExpected(40); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } - node = createNode(242, fullStart); + node = createNode(247, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -13700,10 +15882,10 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token() === 98 ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(21)) { - var propertyAccess = createNode(172, expression.pos); + while (parseOptional(22)) { + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13711,28 +15893,28 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(248); - parseExpected(15); - if (token() !== 16) { + var node = createNode(252); + parseExpected(16); + if (token() !== 17) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(16); + parseExpected(17); } else { - parseExpected(16, undefined, false); + parseExpected(17, undefined, false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token() === 16) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(246); + var node = createNode(250); node.name = parseIdentifierName(); - if (token() === 56) { + if (token() === 57) { switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); @@ -13745,69 +15927,69 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(247); - parseExpected(15); - parseExpected(22); - node.expression = parseExpression(); + var node = createNode(251); parseExpected(16); + parseExpected(23); + node.expression = parseExpression(); + parseExpected(17); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(245); - parseExpected(26); + var node = createNode(249); + parseExpected(27); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(177); - parseExpected(25); + var node = createNode(182); + parseExpected(26); node.type = parseType(); - parseExpected(27); + parseExpected(28); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(21); + var dotToken = parseOptionalToken(22); if (dotToken) { - var propertyAccess = createNode(172, expression.pos); + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 50 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(196, expression.pos); + var nonNullExpression = createNode(201, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } - if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(173, expression.pos); + if (!inDecoratorContext() && parseOptional(20)) { + var indexedAccess = createNode(178, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token() !== 21) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(20); + parseExpected(21); expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { - var tagExpression = createNode(176, expression.pos); + if (token() === 12 || token() === 13) { + var tagExpression = createNode(181, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token() === 12 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -13819,20 +16001,20 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token() === 26) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - var callExpr = createNode(174, expression.pos); + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 17) { - var callExpr = createNode(174, expression.pos); + else if (token() === 18) { + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -13842,17 +16024,17 @@ var ts; } } function parseArgumentList() { - parseExpected(17); - var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(18); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(19); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(25)) { + if (!parseOptional(26)) { return undefined; } - var typeArguments = parseDelimitedList(18, parseType); - if (!parseExpected(27)) { + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(28)) { return undefined; } return typeArguments && canFollowTypeArgumentsInExpression() @@ -13861,27 +16043,27 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 17: - case 21: case 18: - case 20: + case 22: + case 19: + case 21: + case 55: + case 24: case 54: - case 23: - case 53: - case 30: - case 32: case 31: case 33: - case 51: + case 32: + case 34: case 52: - case 48: - case 46: + case 53: + case 49: case 47: - case 16: + case 48: + case 17: case 1: return true; - case 24: - case 15: + case 25: + case 16: default: return false; } @@ -13890,103 +16072,109 @@ var ts; switch (token()) { case 8: case 9: - case 11: + case 12: return parseLiteralNode(); - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: return parseTokenNode(); - case 17: + case 18: return parseParenthesizedExpression(); - case 19: + case 20: return parseArrayLiteralExpression(); - case 15: + case 16: return parseObjectLiteralExpression(); - case 118: + case 119: if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { break; } return parseFunctionExpression(); - case 73: + case 74: return parseClassExpression(); - case 87: + case 88: return parseFunctionExpression(); - case 92: + case 93: return parseNewExpression(); - case 39: - case 61: - if (reScanSlashToken() === 10) { + case 40: + case 62: + if (reScanSlashToken() === 11) { return parseLiteralNode(); } break; - case 12: + case 13: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(178); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(183); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); return finishNode(node); } function parseSpreadElement() { - var node = createNode(191); - parseExpected(22); + var node = createNode(196); + parseExpected(23); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token() === 23 ? parseSpreadElement() : + token() === 25 ? createNode(198) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(170); - parseExpected(19); + var node = createNode(175); + parseExpected(20); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(20); + parseExpected(21); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(123)) { - return parseAccessorDeclaration(149, fullStart, decorators, modifiers); + if (parseContextualModifier(124)) { + return parseAccessorDeclaration(151, fullStart, decorators, modifiers); } - else if (parseContextualModifier(131)) { - return parseAccessorDeclaration(150, fullStart, decorators, modifiers); + else if (parseContextualModifier(133)) { + return parseAccessorDeclaration(152, fullStart, decorators, modifiers); } return undefined; } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(23); + if (dotDotDotToken) { + var spreadElement = createNode(259, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } var decorators = parseDecorators(); var modifiers = parseModifiers(); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 || token() === 17 || token() === 57); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(254, fullStart); + var shorthandDeclaration = createNode(258, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(56); + var equalsToken = parseOptionalToken(57); if (equalsToken) { shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); @@ -13994,23 +16182,23 @@ var ts; return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(253, fullStart); + var propertyAssignment = createNode(257, fullStart); propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; - parseExpected(54); + parseExpected(55); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(171); - parseExpected(15); + var node = createNode(176); + parseExpected(16); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(16); + parseExpected(17); return finishNode(node); } function parseFunctionExpression() { @@ -14018,10 +16206,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(179); + var node = createNode(184); node.modifiers = parseModifiers(); - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); var isGenerator = !!node.asteriskToken; var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = @@ -14029,7 +16217,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlock(isGenerator, isAsync, false); if (saveDecoratorContext) { setDecoratorContext(true); @@ -14040,23 +16228,23 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(175); - parseExpected(92); + var node = createNode(180); + parseExpected(93); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token() === 18) { node.arguments = parseArgumentList(); } return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(199); - if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(204); + if (parseExpected(16, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -14081,47 +16269,47 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(201); - parseExpected(23); + var node = createNode(206); + parseExpected(24); return finishNode(node); } function parseIfStatement() { - var node = createNode(203); - parseExpected(88); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(208); + parseExpected(89); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(80) ? parseStatement() : undefined; + node.elseStatement = parseOptional(81) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(204); - parseExpected(79); + var node = createNode(209); + parseExpected(80); node.statement = parseStatement(); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + parseExpected(105); parseExpected(18); - parseOptional(23); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + parseOptional(24); return finishNode(node); } function parseWhileStatement() { - var node = createNode(205); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(210); + parseExpected(105); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(86); - parseExpected(17); + parseExpected(87); + parseExpected(18); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token() !== 24) { + if (token() === 103 || token() === 109 || token() === 75) { initializer = parseVariableDeclarationList(true); } else { @@ -14129,32 +16317,32 @@ var ts; } } var forOrForInOrForOfStatement; - if (parseOptional(90)) { - var forInStatement = createNode(207, pos); + if (parseOptional(91)) { + var forInStatement = createNode(212, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(138)) { - var forOfStatement = createNode(208, pos); + else if (parseOptional(140)) { + var forOfStatement = createNode(213, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(206, pos); + var forStatement = createNode(211, pos); forStatement.initializer = initializer; - parseExpected(23); - if (token() !== 23 && token() !== 18) { + parseExpected(24); + if (token() !== 24 && token() !== 19) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(23); - if (token() !== 18) { + parseExpected(24); + if (token() !== 19) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -14162,7 +16350,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 210 ? 70 : 75); + parseExpected(kind === 215 ? 71 : 76); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14170,8 +16358,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(211); - parseExpected(94); + var node = createNode(216); + parseExpected(95); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -14179,90 +16367,90 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(212); - parseExpected(105); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(217); + parseExpected(106); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseCaseClause() { - var node = createNode(249); - parseExpected(71); + var node = createNode(253); + parseExpected(72); node.expression = allowInAnd(parseExpression); - parseExpected(54); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(250); - parseExpected(77); - parseExpected(54); + var node = createNode(254); + parseExpected(78); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 72 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(213); - parseExpected(96); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(218); + parseExpected(97); parseExpected(18); - var caseBlock = createNode(227, scanner.getStartPos()); - parseExpected(15); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + var caseBlock = createNode(232, scanner.getStartPos()); parseExpected(16); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(17); node.caseBlock = finishNode(caseBlock); return finishNode(node); } function parseThrowStatement() { - var node = createNode(215); - parseExpected(98); + var node = createNode(220); + parseExpected(99); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(216); - parseExpected(100); + var node = createNode(221); + parseExpected(101); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { - parseExpected(85); + node.catchClause = token() === 73 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 86) { + parseExpected(86); node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(252); - parseExpected(72); - if (parseExpected(17)) { + var result = createNode(256); + parseExpected(73); + if (parseExpected(18)) { result.variableDeclaration = parseVariableDeclaration(); } - parseExpected(18); + parseExpected(19); result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(217); - parseExpected(76); + var node = createNode(222); + parseExpected(77); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); - if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(214, fullStart); + if (expression.kind === 70 && parseOptional(55)) { + var labeledStatement = createNode(219, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(202, fullStart); + var expressionStatement = createNode(207, fullStart); expressionStatement.expression = expression; parseSemicolon(); return addJSDocComment(finishNode(expressionStatement)); @@ -14274,7 +16462,7 @@ var ts; } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 88 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); @@ -14283,47 +16471,47 @@ var ts; function isDeclaration() { while (true) { switch (token()) { - case 102: - case 108: + case 103: + case 109: + case 75: + case 88: case 74: - case 87: - case 73: - case 81: + case 82: return true; - case 107: - case 134: + case 108: + case 136: return nextTokenIsIdentifierOnSameLine(); - case 125: - case 126: + case 127: + case 128: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 115: - case 118: - case 122: - case 110: + case 116: + case 119: + case 123: case 111: case 112: - case 128: + case 113: + case 130: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 137: + case 139: nextToken(); - return token() === 15 || token() === 69 || token() === 82; - case 89: + return token() === 16 || token() === 70 || token() === 83; + case 90: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); - case 82: + return token() === 9 || token() === 38 || + token() === 16 || ts.tokenIsIdentifierOrKeyword(token()); + case 83: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token() === 57 || token() === 38 || + token() === 16 || token() === 78 || + token() === 117) { return true; } continue; - case 113: + case 114: nextToken(); continue; default: @@ -14336,46 +16524,46 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 55: - case 23: - case 15: - case 102: - case 108: - case 87: - case 73: - case 81: + case 56: + case 24: + case 16: + case 103: + case 109: case 88: - case 79: - case 104: - case 86: - case 75: - case 70: - case 94: - case 105: - case 96: - case 98: - case 100: - case 76: - case 72: - case 85: - return true; case 74: case 82: case 89: - return isStartOfDeclaration(); - case 118: - case 122: - case 107: - case 125: - case 126: - case 134: - case 137: + case 80: + case 105: + case 87: + case 76: + case 71: + case 95: + case 106: + case 97: + case 99: + case 101: + case 77: + case 73: + case 86: return true; - case 112: - case 110: - case 111: - case 113: + case 75: + case 83: + case 90: + return isStartOfDeclaration(); + case 119: + case 123: + case 108: + case 127: case 128: + case 136: + case 139: + return true; + case 113: + case 111: + case 112: + case 114: + case 130: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -14383,73 +16571,73 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token() === 16 || token() === 20; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token()) { - case 23: + case 24: return parseEmptyStatement(); - case 15: + case 16: return parseBlock(false); - case 102: + case 103: return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 108: + case 109: if (isLetDeclaration()) { return parseVariableStatement(scanner.getStartPos(), undefined, undefined); } break; - case 87: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 73: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 88: - return parseIfStatement(); - case 79: - return parseDoStatement(); - case 104: - return parseWhileStatement(); - case 86: - return parseForOrForInOrForOfStatement(); - case 75: - return parseBreakOrContinueStatement(209); - case 70: - return parseBreakOrContinueStatement(210); - case 94: - return parseReturnStatement(); - case 105: - return parseWithStatement(); - case 96: - return parseSwitchStatement(); - case 98: - return parseThrowStatement(); - case 100: - case 72: - case 85: - return parseTryStatement(); - case 76: - return parseDebuggerStatement(); - case 55: - return parseDeclaration(); - case 118: - case 107: - case 134: - case 125: - case 126: - case 122: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 74: - case 81: - case 82: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 89: - case 110: + return parseIfStatement(); + case 80: + return parseDoStatement(); + case 105: + return parseWhileStatement(); + case 87: + return parseForOrForInOrForOfStatement(); + case 76: + return parseBreakOrContinueStatement(214); + case 71: + return parseBreakOrContinueStatement(215); + case 95: + return parseReturnStatement(); + case 106: + return parseWithStatement(); + case 97: + return parseSwitchStatement(); + case 99: + return parseThrowStatement(); + case 101: + case 73: + case 86: + return parseTryStatement(); + case 77: + return parseDebuggerStatement(); + case 56: + return parseDeclaration(); + case 119: + case 108: + case 136: + case 127: + case 128: + case 123: + case 75: + case 82: + case 83: + case 90: case 111: case 112: - case 115: case 113: - case 128: - case 137: + case 116: + case 114: + case 130: + case 139: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -14462,40 +16650,40 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token()) { - case 102: - case 108: - case 74: + case 103: + case 109: + case 75: return parseVariableStatement(fullStart, decorators, modifiers); - case 87: + case 88: return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 73: + case 74: return parseClassDeclaration(fullStart, decorators, modifiers); - case 107: + case 108: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 134: + case 136: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 81: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 137: - case 125: - case 126: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 89: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 139: + case 127: + case 128: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 90: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 83: nextToken(); switch (token()) { - case 77: - case 56: + case 78: + case 57: return parseExportAssignment(fullStart, decorators, modifiers); - case 116: + case 117: return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); } default: if (decorators || modifiers) { - var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(244, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; node.modifiers = modifiers; @@ -14508,31 +16696,32 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token() !== 16 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { - return createNode(193); + if (token() === 25) { + return createNode(198); } - var node = createNode(169); - node.dotDotDotToken = parseOptionalToken(22); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(169); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token() !== 55) { node.name = propertyName; } else { - parseExpected(54); + parseExpected(55); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -14540,33 +16729,33 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(167); - parseExpected(15); - node.elements = parseDelimitedList(9, parseObjectBindingElement); + var node = createNode(172); parseExpected(16); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(17); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(168); - parseExpected(19); - node.elements = parseDelimitedList(10, parseArrayBindingElement); + var node = createNode(173); parseExpected(20); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(21); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token() === 16 || token() === 20 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token() === 20) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token() === 16) { return parseObjectBindingPattern(); } return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(218); + var node = createNode(223); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { @@ -14575,21 +16764,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(219); + var node = createNode(224); switch (token()) { - case 102: + case 103: break; - case 108: + case 109: node.flags |= 1; break; - case 74: + case 75: node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 140 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -14601,10 +16790,10 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 18; + return nextTokenIsIdentifier() && nextToken() === 19; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(200, fullStart); + var node = createNode(205, fullStart); node.decorators = decorators; node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); @@ -14612,29 +16801,29 @@ var ts; return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(220, fullStart); + var node = createNode(225, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; var isAsync = ts.hasModifier(node, 256); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(148, pos); + var node = createNode(150, pos); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(121); - fillSignature(54, false, false, false, node); + parseExpected(122); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(147, fullStart); + var method = createNode(149, fullStart); method.decorators = decorators; method.modifiers = modifiers; method.asteriskToken = asteriskToken; @@ -14642,12 +16831,12 @@ var ts; method.questionToken = questionToken; var isGenerator = !!asteriskToken; var isAsync = ts.hasModifier(method, 256); - fillSignature(54, isGenerator, isAsync, false, method); + fillSignature(55, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(145, fullStart); + var property = createNode(147, fullStart); property.decorators = decorators; property.modifiers = modifiers; property.name = name; @@ -14655,15 +16844,15 @@ var ts; property.type = parseTypeAnnotation(); property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); parseSemicolon(); return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -14678,17 +16867,17 @@ var ts; node.decorators = decorators; node.modifiers = modifiers; node.name = parsePropertyName(); - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { - case 112: - case 110: - case 111: case 113: - case 128: + case 111: + case 112: + case 114: + case 130: return true; default: return false; @@ -14696,7 +16885,7 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token() === 56) { return true; } while (ts.isModifierKind(token())) { @@ -14706,26 +16895,26 @@ var ts; } nextToken(); } - if (token() === 37) { + if (token() === 38) { return true; } if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { + if (!ts.isKeyword(idToken) || idToken === 133 || idToken === 124) { return true; } switch (token()) { - case 17: - case 25: + case 18: + case 26: + case 55: + case 57: case 54: - case 56: - case 53: return true; default: return canParseSemicolon(); @@ -14737,10 +16926,10 @@ var ts; var decorators; while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(55)) { + if (!parseOptional(56)) { break; } - var decorator = createNode(143, decoratorStart); + var decorator = createNode(145, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); if (!decorators) { @@ -14760,7 +16949,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + if (token() === 75 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -14785,7 +16974,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 118) { + if (token() === 119) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -14796,8 +16985,8 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { - var result = createNode(198); + if (token() === 24) { + var result = createNode(203); nextToken(); return finishNode(result); } @@ -14808,7 +16997,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token() === 122) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -14817,33 +17006,33 @@ var ts; if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || - token() === 37 || - token() === 19) { + token() === 38 || + token() === 20) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_15 = createMissingNode(70, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_15, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 192); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 197); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 221); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(73); + parseExpected(74); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(true); - if (parseExpected(15)) { + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(16)) { node.members = parseClassMembers(); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -14856,17 +17045,17 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 107 && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause) { + function parseHeritageClauses() { if (isHeritageClause()) { - return parseList(20, parseHeritageClause); + return parseList(21, parseHeritageClause); } return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { - var node = createNode(251); + if (token() === 84 || token() === 107) { + var node = createNode(255); node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -14875,57 +17064,57 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(194); + var node = createNode(199); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token() === 84 || token() === 107; } function parseClassMembers() { return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(222, fullStart); + var node = createNode(227, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(107); + parseExpected(108); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(223, fullStart); + var node = createNode(228, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(134); + parseExpected(136); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(56); + parseExpected(57); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { - var node = createNode(255, scanner.getStartPos()); + var node = createNode(260, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(224, fullStart); + var node = createNode(229, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(81); + parseExpected(82); node.name = parseIdentifier(); - if (parseExpected(15)) { + if (parseExpected(16)) { node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -14933,10 +17122,10 @@ var ts; return addJSDocComment(finishNode(node)); } function parseModuleBlock() { - var node = createNode(226, scanner.getStartPos()); - if (parseExpected(15)) { + var node = createNode(231, scanner.getStartPos()); + if (parseExpected(16)) { node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -14944,29 +17133,29 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); var namespaceFlag = flags & 16; node.decorators = decorators; node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(21) + node.body = parseOptional(22) ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (token() === 137) { + if (token() === 139) { node.name = parseIdentifier(); node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token() === 16) { node.body = parseModuleBlock(); } else { @@ -14976,14 +17165,14 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = 0; - if (token() === 137) { + if (token() === 139) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } - else if (parseOptional(126)) { + else if (parseOptional(128)) { flags |= 16; } else { - parseExpected(125); + parseExpected(127); if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -14991,63 +17180,63 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token() === 131 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 17; + return nextToken() === 18; } function nextTokenIsSlash() { - return nextToken() === 39; + return nextToken() === 40; } function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228, fullStart); + var exportDeclaration = createNode(233, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; - parseExpected(116); - parseExpected(126); + parseExpected(117); + parseExpected(128); exportDeclaration.name = parseIdentifier(); - parseExpected(23); + parseSemicolon(); return finishNode(exportDeclaration); } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(89); + parseExpected(90); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { - var importEqualsDeclaration = createNode(229, fullStart); + if (token() !== 25 && token() !== 138) { + var importEqualsDeclaration = createNode(234, fullStart); importEqualsDeclaration.decorators = decorators; importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; - parseExpected(56); + parseExpected(57); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); return addJSDocComment(finishNode(importEqualsDeclaration)); } } - var importDeclaration = createNode(230, fullStart); + var importDeclaration = createNode(235, fullStart); importDeclaration.decorators = decorators; importDeclaration.modifiers = modifiers; if (identifier || - token() === 37 || - token() === 15) { + token() === 38 || + token() === 16) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(136); + parseExpected(138); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(231, fullStart); + var importClause = createNode(236, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || - parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + parseOptional(25)) { + importClause.namedBindings = token() === 38 ? parseNamespaceImport() : parseNamedImportsOrExports(238); } return finishNode(importClause); } @@ -15057,11 +17246,11 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(240); - parseExpected(129); - parseExpected(17); - node.expression = parseModuleSpecifier(); + var node = createNode(245); + parseExpected(131); parseExpected(18); + node.expression = parseModuleSpecifier(); + parseExpected(19); return finishNode(node); } function parseModuleSpecifier() { @@ -15075,22 +17264,22 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(232); - parseExpected(37); - parseExpected(116); + var namespaceImport = createNode(237); + parseExpected(38); + parseExpected(117); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 233 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(22, kind === 238 ? parseImportSpecifier : parseExportSpecifier, 16, 17); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(238); + return parseImportOrExportSpecifier(243); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(234); + return parseImportOrExportSpecifier(239); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -15098,9 +17287,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token() === 117) { node.propertyName = identifierName; - parseExpected(116); + parseExpected(117); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -15109,23 +17298,23 @@ var ts; else { node.name = identifierName; } - if (kind === 234 && checkIdentifierIsKeyword) { + if (kind === 239 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(236, fullStart); + var node = createNode(241, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(37)) { - parseExpected(136); + if (parseOptional(38)) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(136); + node.exportClause = parseNamedImportsOrExports(242); + if (token() === 138 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -15133,14 +17322,14 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(235, fullStart); + var node = createNode(240, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(56)) { + if (parseOptional(57)) { node.isExportEquals = true; } else { - parseExpected(77); + parseExpected(78); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -15212,10 +17401,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 229 && node.moduleReference.kind === 240 - || node.kind === 230 + || node.kind === 234 && node.moduleReference.kind === 245 || node.kind === 235 - || node.kind === 236 + || node.kind === 240 + || node.kind === 241 ? node : undefined; }); @@ -15224,24 +17413,24 @@ var ts; (function (JSDocParser) { function isJSDocType() { switch (token()) { - case 37: - case 53: - case 17: - case 19: - case 49: - case 15: - case 87: - case 22: - case 92: - case 97: + case 38: + case 54: + case 18: + case 20: + case 50: + case 16: + case 88: + case 23: + case 93: + case 98: return true; } return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); - sourceFile = createSourceFile("file.js", 2, 1); + initializeState(content, 5, undefined, 1); + sourceFile = createSourceFile("file.js", 5, 1); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15251,23 +17440,23 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression() { - var result = createNode(257, scanner.getTokenPos()); - parseExpected(15); - result.type = parseJSDocTopLevelType(); + var result = createNode(262, scanner.getTokenPos()); parseExpected(16); + result.type = parseJSDocTopLevelType(); + parseExpected(17); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { - var unionType = createNode(261, type.pos); + if (token() === 48) { + var unionType = createNode(266, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { - var optionalType = createNode(268, type.pos); + if (token() === 57) { + var optionalType = createNode(273, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -15277,21 +17466,21 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { - var arrayType = createNode(260, type.pos); + if (token() === 20) { + var arrayType = createNode(265, type.pos); arrayType.elementType = type; nextToken(); - parseExpected(20); + parseExpected(21); type = finishNode(arrayType); } - else if (token() === 53) { - var nullableType = createNode(263, type.pos); + else if (token() === 54) { + var nullableType = createNode(268, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { - var nonNullableType = createNode(264, type.pos); + else if (token() === 50) { + var nonNullableType = createNode(269, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -15304,94 +17493,94 @@ var ts; } function parseBasicTypeExpression() { switch (token()) { - case 37: + case 38: return parseJSDocAllType(); - case 53: + case 54: return parseJSDocUnknownOrNullableType(); - case 17: + case 18: return parseJSDocUnionType(); - case 19: + case 20: return parseJSDocTupleType(); - case 49: + case 50: return parseJSDocNonNullableType(); - case 15: + case 16: return parseJSDocRecordType(); - case 87: + case 88: return parseJSDocFunctionType(); - case 22: + case 23: return parseJSDocVariadicType(); - case 92: - return parseJSDocConstructorType(); - case 97: - return parseJSDocThisType(); - case 117: - case 132: - case 130: - case 120: - case 133: - case 103: case 93: + return parseJSDocConstructorType(); + case 98: + return parseJSDocThisType(); + case 118: + case 134: + case 132: + case 121: case 135: - case 127: + case 104: + case 94: + case 137: + case 129: return parseTokenNode(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(272); + var result = createNode(277); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(271); + var result = createNode(276); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(270); + var result = createNode(275); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(269); + var result = createNode(274); nextToken(); - parseExpected(17); - result.parameters = parseDelimitedList(22, parseJSDocParameter); - checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + result.parameters = parseDelimitedList(23, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(19); + if (token() === 55) { nextToken(); result.type = parseJSDocType(); } return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(142); + var parameter = createNode(144); parameter.type = parseJSDocType(); - if (parseOptional(56)) { - parameter.questionToken = createNode(56); + if (parseOptional(57)) { + parameter.questionToken = createNode(57); } return finishNode(parameter); } function parseJSDocTypeReference() { - var result = createNode(267); + var result = createNode(272); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); } else { - while (parseOptional(21)) { - if (token() === 25) { + while (parseOptional(22)) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); break; } @@ -15404,10 +17593,10 @@ var ts; } function parseTypeArguments() { nextToken(); - var typeArguments = parseDelimitedList(23, parseJSDocType); + var typeArguments = parseDelimitedList(24, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); - parseExpected(27); + parseExpected(28); return typeArguments; } function checkForEmptyTypeArgumentList(typeArguments) { @@ -15418,28 +17607,28 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(139, left.pos); + var result = createNode(141, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(265); + var result = createNode(270); result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(264); + var result = createNode(269); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(262); + var result = createNode(267); nextToken(); - result.types = parseDelimitedList(25, parseJSDocType); + result.types = parseDelimitedList(26, parseJSDocType); checkForTrailingComma(result.types); - parseExpected(20); + parseExpected(21); return finishNode(result); } function checkForTrailingComma(list) { @@ -15449,51 +17638,51 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(261); + var result = createNode(266); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18); + parseExpected(19); return finishNode(result); } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(47)) { + while (parseOptional(48)) { types.push(parseJSDocType()); } types.end = scanner.getStartPos(); return types; } function parseJSDocAllType() { - var result = createNode(258); + var result = createNode(263); nextToken(); return finishNode(result); } function parseJSDocLiteralType() { - var result = createNode(282); + var result = createNode(288); result.literal = parseLiteralTypeNode(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { - var result = createNode(259, pos); + if (token() === 25 || + token() === 17 || + token() === 19 || + token() === 28 || + token() === 57 || + token() === 48) { + var result = createNode(264, pos); return finishNode(result); } else { - var result = createNode(263, pos); + var result = createNode(268, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); + initializeState(content, 5, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -15547,11 +17736,12 @@ var ts; } if (token() === 4) { state = 0; + indent = 0; nextJSDocToken(); } while (token() !== 1) { switch (token()) { - case 55: + case 56: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); @@ -15569,9 +17759,9 @@ var ts; state = 0; indent = 0; break; - case 37: + case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -15580,13 +17770,16 @@ var ts; indent += asterisk.length; } break; - case 69: + case 70: pushComment(scanner.getTokenText()); state = 2; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -15594,6 +17787,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -15626,7 +17820,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(273, start); + var result = createNode(278, start); result.tags = tags; result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -15637,8 +17831,8 @@ var ts; } } function parseTag(indent) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getTokenPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15649,6 +17843,9 @@ var ts; var tag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -15689,7 +17886,7 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 55 && token() !== 1) { + while (token() !== 56 && token() !== 1) { switch (token()) { case 4: if (state >= 1) { @@ -15698,7 +17895,7 @@ var ts; } indent = 0; break; - case 55: + case 56: break; case 5: if (state === 2) { @@ -15712,7 +17909,7 @@ var ts; indent += whitespace.length; } break; - case 37: + case 38: if (state === 0) { state = 1; indent += scanner.getTokenText().length; @@ -15723,7 +17920,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 55) { + if (token() === 56) { break; } nextJSDocToken(); @@ -15733,7 +17930,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(274, atToken.pos); + var result = createNode(279, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -15751,7 +17948,7 @@ var ts; function tryParseTypeExpression() { return tryParse(function () { skipWhitespace(); - if (token() !== 15) { + if (token() !== 16) { return undefined; } return parseJSDocTypeExpression(); @@ -15762,14 +17959,14 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (parseOptionalToken(19)) { + if (parseOptionalToken(20)) { name = parseJSDocIdentifierName(); skipWhitespace(); isBracketed = true; - if (parseOptionalToken(56)) { + if (parseOptionalToken(57)) { parseExpression(); } - parseExpected(20); + parseExpected(21); } else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); @@ -15788,7 +17985,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(275, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -15799,20 +17996,20 @@ var ts; return finishNode(result); } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 276; })) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(276, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 277; })) { + if (ts.forEach(tags, function (t) { return t.kind === 283; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(277, atToken.pos); + var result = createNode(283, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -15827,28 +18024,43 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(280, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.name = name; result.typeExpression = typeExpression; return finishNode(result); } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(279, atToken.pos); + var typedefTag = createNode(285, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (rightNode.kind !== 70) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); if (typeExpression) { - if (typeExpression.type.kind === 267) { + if (typeExpression.type.kind === 272) { var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + if (jsDocTypeReference.name.kind === 70) { + var name_16 = jsDocTypeReference.name; + if (name_16.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15862,7 +18074,7 @@ var ts; } return finishNode(typedefTag); function scanChildTags() { - var jsDocTypeLiteral = createNode(281, scanner.getStartPos()); + var jsDocTypeLiteral = createNode(287, scanner.getStartPos()); var resumePos = scanner.getStartPos(); var canParseTag = true; var seenAsterisk = false; @@ -15870,7 +18082,7 @@ var ts; while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); switch (token()) { - case 55: + case 56: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); if (!parentTagTerminated) { @@ -15884,13 +18096,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 37: + case 38: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 69: + case 70: canParseTag = false; case 1: break; @@ -15899,10 +18111,25 @@ var ts; scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(22)) { + var jsDocNamespaceNode = createNode(230, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return jsDocNamespaceNode; + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getStartPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15919,32 +18146,35 @@ var ts; return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } var propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = []; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + return false; } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 278; })) { + if (ts.forEach(tags, function (t) { return t.kind === 284; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_17 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_17) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(143, name_17.pos); + typeParameter.name = name_17; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token() === 25) { nextJSDocToken(); skipWhitespace(); } @@ -15952,7 +18182,7 @@ var ts; break; } } - var result = createNode(278, atToken.pos); + var result = createNode(284, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -15973,7 +18203,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(69, pos); + var result = createNode(70, pos); result.text = content.substring(pos, end); finishNode(result, end); nextJSDocToken(); @@ -16032,8 +18262,8 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); } @@ -16044,8 +18274,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += 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); } } @@ -16054,7 +18284,7 @@ var ts; switch (node.kind) { case 9: case 8: - case 69: + case 70: return true; } return false; @@ -16117,8 +18347,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -16271,16 +18501,16 @@ var ts; var ts; (function (ts) { function getModuleInstanceState(node) { - if (node.kind === 222 || node.kind === 223) { + if (node.kind === 227 || node.kind === 228) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { + else if ((node.kind === 235 || node.kind === 234) && !(ts.hasModifier(node, 1))) { return 0; } - else if (node.kind === 226) { + else if (node.kind === 231) { var state_1 = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -16296,10 +18526,13 @@ var ts; }); return state_1; } - else if (node.kind === 225) { + else if (node.kind === 230) { var body = node.body; return body ? getModuleInstanceState(body) : 1; } + else if (node.kind === 70 && node.isInJSDocNamespace) { + return 0; + } else { return 1; } @@ -16344,7 +18577,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +18607,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16394,7 +18635,7 @@ var ts; if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 225)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230)) { symbol.valueDeclaration = node; } } @@ -16404,9 +18645,9 @@ var ts; if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 140) { + if (node.name.kind === 142) { var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -16415,21 +18656,21 @@ var ts; return node.name.text; } switch (node.kind) { - case 148: + case 150: return "__constructor"; - case 156: - case 151: - return "__call"; - case 157: - case 152: - return "__new"; + case 158: case 153: + return "__call"; + case 159: + case 154: + return "__new"; + case 155: return "__index"; - case 236: + case 241: return "__export"; - case 235: + case 240: return node.isExportEquals ? "export=" : "default"; - case 187: + case 192: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2: return "export="; @@ -16441,23 +18682,23 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 220: - case 221: + case 225: + case 226: return ts.hasModifier(node, 512) ? "default" : undefined; - case 269: + case 274: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 142: - ts.Debug.assert(node.parent.kind === 269); + case 144: + ts.Debug.assert(node.parent.kind === 274); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 279: + case 285: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 200) { + if (parentNode && parentNode.kind === 205) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { + if (nameIdentifier.kind === 70) { nameFromParentNode = nameIdentifier.text; } } @@ -16492,11 +18733,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 240 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16512,7 +18759,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { - if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { + if (node.kind === 243 || (node.kind === 234 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -16520,7 +18767,11 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { + var isJSDocTypedefInJSDocNamespace = node.kind === 285 && + node.name && + node.name.kind === 70 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793064 ? 2097152 : 0) | (symbolFlags & 1920 ? 4194304 : 0); @@ -16555,13 +18806,13 @@ var ts; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !!ts.getImmediatelyInvokedFunctionExpression(node); + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -16571,13 +18822,13 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~32128; + node.flags &= ~1408; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { node.flags |= 128; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 256) { + if (node.kind === 261) { node.flags |= emitFlags; } if (isIIFE) { @@ -16612,6 +18863,7 @@ var ts; skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -16620,101 +18872,124 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - ts.forEach(node.jsDocComments, bind); + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + ts.forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - ts.forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { - case 205: + case 210: bindWhileStatement(node); break; - case 204: + case 209: bindDoStatement(node); break; - case 206: + case 211: bindForStatement(node); break; - case 207: - case 208: + case 212: + case 213: bindForInOrForOfStatement(node); break; - case 203: + case 208: bindIfStatement(node); break; - case 211: - case 215: + case 216: + case 220: bindReturnOrThrow(node); break; - case 210: - case 209: + case 215: + case 214: bindBreakOrContinueStatement(node); break; - case 216: + case 221: bindTryStatement(node); break; - case 213: + case 218: bindSwitchStatement(node); break; - case 227: + case 232: bindCaseBlock(node); break; - case 249: + case 253: bindCaseClause(node); break; - case 214: + case 219: bindLabeledStatement(node); break; - case 185: + case 190: bindPrefixUnaryExpressionFlow(node); break; - case 186: + case 191: bindPostfixUnaryExpressionFlow(node); break; - case 187: + case 192: bindBinaryExpressionFlow(node); break; - case 181: + case 186: bindDeleteExpressionFlow(node); break; - case 188: + case 193: bindConditionalExpressionFlow(node); break; - case 218: + case 223: bindVariableDeclarationFlow(node); break; - case 174: + case 179: bindCallExpressionFlow(node); break; default: - ts.forEachChild(node, bind); + bindEachChild(node); break; } } function isNarrowingExpression(expr) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return isNarrowableReference(expr); - case 174: + case 179: return hasNarrowableArgument(expr); - case 178: + case 183: return isNarrowingExpression(expr.expression); - case 187: + case 192: return isNarrowingBinaryExpression(expr); - case 185: - return expr.operator === 49 && isNarrowingExpression(expr.operand); + case 190: + return expr.operator === 50 && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); + return expr.kind === 70 || + expr.kind === 98 || + expr.kind === 177 && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -16725,41 +19000,41 @@ var ts; } } } - if (expr.expression.kind === 172 && + if (expr.expression.kind === 177 && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 187 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableReference(expr.left); - case 30: case 31: case 32: case 33: + case 34: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 91: + case 92: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 178: + case 183: return isNarrowableOperand(expr.expression); - case 187: + case 192: switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowableOperand(expr.right); } } @@ -16778,7 +19053,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 256 ? 512 : 256; + flow.flags |= flow.flags & 512 ? 1024 : 512; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -16793,8 +19068,8 @@ var ts; if (!expression) { return flags & 32 ? antecedent : unreachableFlow; } - if (expression.kind === 99 && flags & 64 || - expression.kind === 84 && flags & 32) { + if (expression.kind === 100 && flags & 64 || + expression.kind === 85 && flags & 32) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -16828,6 +19103,14 @@ var ts; node: node }; } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } function finishFlowLabel(flow) { var antecedents = flow.antecedents; if (!antecedents) { @@ -16841,34 +19124,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 203: - case 205: - case 204: + case 208: + case 210: + case 209: return parent.expression === node; - case 206: - case 188: + case 211: + case 193: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 178) { + if (node.kind === 183) { node = node.expression; } - else if (node.kind === 185 && node.operator === 49) { + else if (node.kind === 190 && node.operator === 50) { node = node.operand; } else { - return node.kind === 187 && (node.operatorToken.kind === 51 || - node.operatorToken.kind === 52); + return node.kind === 192 && (node.operatorToken.kind === 52 || + node.operatorToken.kind === 53); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 178 || - node.parent.kind === 185 && - node.parent.operator === 49) { + while (node.parent.kind === 183 || + node.parent.kind === 190 && + node.parent.operator === 50) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -16909,8 +19192,11 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var preConditionLabel = createBranchLabel(); - var postDoLabel = createBranchLabel(); + var enclosingLabeledStatement = node.parent.kind === 219 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -16941,7 +19227,7 @@ var ts; bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 219) { + if (node.initializer.kind !== 224) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -16963,7 +19249,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 211) { + if (node.kind === 216) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -16982,8 +19268,8 @@ var ts; } return undefined; } - function bindbreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 210 ? breakTarget : continueTarget; + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 215 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -16995,28 +19281,41 @@ var ts; var activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node) { - var postFinallyLabel = createBranchLabel(); + var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); } - currentFlow = finishFlowLabel(postFinallyLabel); } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17027,7 +19326,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -17037,6 +19336,8 @@ var ts; currentFlow = finishFlowLabel(postSwitchLabel); } function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; var clauses = node.clauses; var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { @@ -17056,13 +19357,15 @@ var ts; errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { var saveCurrentFlow = currentFlow; currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - ts.forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name, breakTarget, continueTarget) { var activeLabel = { @@ -17088,11 +19391,13 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== 209) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node) { - if (node.kind === 187 && node.operatorToken.kind === 56) { + if (node.kind === 192 && node.operatorToken.kind === 57) { bindAssignmentTargetFlow(node.left); } else { @@ -17103,10 +19408,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 170) { + else if (node.kind === 175) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 191) { + if (e.kind === 196) { bindAssignmentTargetFlow(e.expression); } else { @@ -17114,21 +19419,24 @@ var ts; } } } - else if (node.kind === 171) { + else if (node.kind === 176) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 253) { + if (p.kind === 257) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 254) { + else if (p.kind === 258) { bindAssignmentTargetFlow(p.name); } + else if (p.kind === 259) { + bindAssignmentTargetFlow(p.expression); + } } } } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -17139,30 +19447,30 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 49) { + if (node.operator === 50) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - ts.forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.operator === 41 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 51 || operator === 52) { + if (operator === 52 || operator === 53) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -17173,15 +19481,21 @@ var ts; } } else { - ts.forEachChild(node, bind); - if (operator === 56 && !ts.isAssignmentTarget(node)) { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === 57 && node.left.kind === 178) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.expression.kind === 172) { + bindEachChild(node); + if (node.expression.kind === 177) { bindAssignmentTargetFlow(node.expression); } } @@ -17191,9 +19505,11 @@ var ts; var postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -17211,69 +19527,79 @@ var ts; } } function bindVariableDeclarationFlow(node) { - ts.forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === 207 || node.parent.parent.kind === 208) { + bindEachChild(node); + if (node.initializer || node.parent.parent.kind === 212 || node.parent.parent.kind === 213) { bindInitializedVariableFlow(node); } } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 178) { + while (expr.kind === 183) { expr = expr.expression; } - if (expr.kind === 179 || expr.kind === 180) { - ts.forEach(node.typeArguments, bind); - ts.forEach(node.arguments, bind); + if (expr.kind === 184 || expr.kind === 185) { + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - ts.forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === 177) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } function getContainerFlags(node) { switch (node.kind) { - case 192: - case 221: - case 224: - case 171: - case 159: - case 281: - case 265: + case 197: + case 226: + case 229: + case 176: + case 161: + case 287: + case 270: return 1; - case 222: + case 227: return 1 | 64; - case 269: - case 225: - case 223: + case 274: + case 230: + case 228: + case 170: return 1 | 32; - case 256: + case 261: return 1 | 4 | 32; - case 148: - case 220: - case 147: - case 146: case 149: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 150: + case 225: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return 1 | 4 | 32 | 8; - case 179: - case 180: + case 184: + case 185: return 1 | 4 | 32 | 8 | 16; - case 226: + case 231: return 4; - case 145: + case 147: return node.initializer ? 4 : 0; - case 252: - case 206: - case 207: - case 208: - case 227: + case 256: + case 211: + case 212: + case 213: + case 232: return 2; - case 199: + case 204: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -17289,36 +19615,37 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 225: + case 230: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 256: + case 261: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 192: - case 221: + case 197: + case 226: return declareClassMember(node, symbolFlags, symbolExcludes); - case 224: + case 229: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 159: - case 171: - case 222: - case 265: - case 281: + case 161: + case 176: + case 227: + case 270: + case 287: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 156: - case 157: + case 158: + case 159: + case 153: + case 154: + case 155: + case 149: + case 148: + case 150: case 151: case 152: - case 153: - case 147: - case 146: - case 148: - case 149: - case 150: - case 220: - case 179: - case 180: - case 269: - case 223: + case 225: + case 184: + case 185: + case 274: + case 228: + case 170: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -17333,11 +19660,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 256 ? node : node.body; - if (body && (body.kind === 256 || body.kind === 226)) { + var body = node.kind === 261 ? node : node.body; + if (body && (body.kind === 261 || body.kind === 231)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 236 || stat.kind === 235) { + if (stat.kind === 241 || stat.kind === 240) { return true; } } @@ -17413,11 +19740,11 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.name.kind !== 69) { + if (prop.kind === 259 || prop.name.kind !== 70) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 253 || prop.kind === 254 || prop.kind === 147 + var currentKind = prop.kind === 257 || prop.kind === 258 || prop.kind === 149 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -17439,10 +19766,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 225: + case 230: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 256: + case 261: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -17460,8 +19787,8 @@ var ts; } function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 106 && - node.originalKeywordKind <= 114 && + node.originalKeywordKind >= 107 && + node.originalKeywordKind <= 115 && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { if (!file.parseDiagnostics.length) { @@ -17489,17 +19816,17 @@ var ts; } } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 69) { + if (inStrictMode && node.expression.kind === 70) { var span_2 = ts.getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && + return node.kind === 70 && (node.text === "eval" || node.text === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69) { + if (name && name.kind === 70) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span_3 = ts.getErrorSpanForNode(file, name); @@ -17532,8 +19859,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 256 && - blockScopeContainer.kind !== 225 && + if (blockScopeContainer.kind !== 261 && + blockScopeContainer.kind !== 230 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -17552,7 +19879,7 @@ var ts; } function checkStrictModePrefixUnaryExpression(node) { if (inStrictMode) { - if (node.operator === 41 || node.operator === 42) { + if (node.operator === 42 || node.operator === 43) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -17576,7 +19903,7 @@ var ts; node.parent = parent; var saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 138) { + if (node.kind > 140) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -17595,8 +19922,8 @@ var ts; } function updateStrictModeStatementList(statements) { if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -17613,18 +19940,26 @@ var ts; } function bindWorker(node) { switch (node.kind) { - case 69: - case 97: - if (currentFlow && (ts.isExpression(node) || parent.kind === 254)) { + case 70: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 285) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 98: + if (currentFlow && (ts.isExpression(node) || parent.kind === 258)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 172: + case 177: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } break; - case 187: + case 192: if (ts.isInJavaScriptFile(node)) { var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { @@ -17647,120 +19982,137 @@ var ts; } } return checkStrictModeBinaryExpression(node); - case 252: + case 256: return checkStrictModeCatchClause(node); - case 181: + case 186: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 186: + case 191: return checkStrictModePostfixUnaryExpression(node); - case 185: + case 190: return checkStrictModePrefixUnaryExpression(node); - case 212: + case 217: return checkStrictModeWithStatement(node); - case 165: + case 167: seenThisKeyword = true; return; - case 154: + case 156: return checkTypePredicate(node); - case 141: + case 143: return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 142: - return bindParameter(node); - case 218: - case 169: - return bindVariableDeclarationOrBindingElement(node); - case 145: case 144: - case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); - case 280: - return bindJSDocProperty(node); - case 253: - case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 247: - emitFlags |= 16384; - return; - case 151: - case 152: - case 153: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); + return bindParameter(node); + case 223: + case 174: + return bindVariableDeclarationOrBindingElement(node); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 220: - return bindFunctionDeclaration(node); - case 148: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 271: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + case 286: + return bindJSDocProperty(node); + case 257: + case 258: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 260: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 259: + case 251: + var root = container; + var hasRest = false; + while (root.parent) { + if (root.kind === 176 && + root.parent.kind === 192 && + root.parent.operatorToken.kind === 57 && + root.parent.left === root) { + hasRest = true; + break; + } + root = root.parent; + } + return; + case 153: + case 154: + case 155: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 149: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 148: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 225: + return bindFunctionDeclaration(node); case 150: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 151: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 152: return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 156: - case 157: - case 269: - return bindFunctionOrConstructorType(node); + case 158: case 159: - case 281: - case 265: + case 274: + return bindFunctionOrConstructorType(node); + case 161: + case 170: + case 287: + case 270: return bindAnonymousDeclaration(node, 2048, "__type"); - case 171: + case 176: return bindObjectLiteralExpression(node); - case 179: - case 180: + case 184: + case 185: return bindFunctionExpression(node); - case 174: + case 179: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 192: - case 221: + case 197: + case 226: inStrictMode = true; return bindClassLikeDeclaration(node); - case 222: + case 227: return bindBlockScopedDeclaration(node, 64, 792968); - case 279: - case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 224: - return bindEnumDeclaration(node); - case 225: - return bindModuleDeclaration(node); - case 229: - case 232: - case 234: - case 238: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 285: + if (!node.fullName || node.fullName.kind === 70) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; case 228: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 229: + return bindEnumDeclaration(node); + case 230: + return bindModuleDeclaration(node); + case 234: + case 237: + case 239: + case 243: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 233: return bindNamespaceExportDeclaration(node); - case 231: - return bindImportClause(node); case 236: + return bindImportClause(node); + case 241: return bindExportDeclaration(node); - case 235: + case 240: return bindExportAssignment(node); - case 256: + case 261: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 199: + case 204: if (!ts.isFunctionLike(node.parent)) { return; } - case 226: + case 231: return updateStrictModeStatementList(node.statements); } } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 69) { + if (parameterName && parameterName.kind === 70) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 165) { + if (parameterName && parameterName.kind === 167) { seenThisKeyword = true; } bind(type); @@ -17779,27 +20131,27 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 240 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 256) { + if (node.parent.kind !== 261) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17823,7 +20175,9 @@ var ts; function setCommonJsModuleIndicator(node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } function bindExportsPropertyAssignment(node) { @@ -17836,11 +20190,11 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { + if (container.kind === 225 || container.kind === 184) { container.symbol.members = container.symbol.members || ts.createMap(); declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } - else if (container.kind === 148) { + else if (container.kind === 150) { var saveContainer = container; container = container.parent; var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -17872,15 +20226,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 1024; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; - } - } - if (node.kind === 221) { + if (node.kind === 226) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -17923,11 +20269,6 @@ var ts; } } function bindParameter(node) { - if (!ts.isDeclarationFile(file) && - !ts.isInAmbientContext(node) && - ts.nodeIsDecorated(node)) { - emitFlags |= (2048 | 4096); - } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); } @@ -17945,7 +20286,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } checkStrictModeFunctionName(node); @@ -17960,7 +20301,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } if (currentFlow) { @@ -17973,12 +20314,12 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; + emitFlags |= 1024; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -17995,15 +20336,15 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || - node.kind === 221 || - (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 206) || + node.kind === 226 || + (node.kind === 230 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 229 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 200 || + (node.kind !== 205 || ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -18017,52 +20358,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 174: - return computeCallExpression(node, subtreeFlags); - case 225: - return computeModuleDeclaration(node, subtreeFlags); - case 178: - return computeParenthesizedExpression(node, subtreeFlags); - case 187: - return computeBinaryExpression(node, subtreeFlags); - case 202: - return computeExpressionStatement(node, subtreeFlags); - case 142: - return computeParameter(node, subtreeFlags); - case 180: - return computeArrowFunction(node, subtreeFlags); case 179: - return computeFunctionExpression(node, subtreeFlags); - case 220: - return computeFunctionDeclaration(node, subtreeFlags); - case 218: - return computeVariableDeclaration(node, subtreeFlags); - case 219: - return computeVariableDeclarationList(node, subtreeFlags); - case 200: - return computeVariableStatement(node, subtreeFlags); - case 214: - return computeLabeledStatement(node, subtreeFlags); - case 221: - return computeClassDeclaration(node, subtreeFlags); + return computeCallExpression(node, subtreeFlags); + case 180: + return computeNewExpression(node, subtreeFlags); + case 230: + return computeModuleDeclaration(node, subtreeFlags); + case 183: + return computeParenthesizedExpression(node, subtreeFlags); case 192: + return computeBinaryExpression(node, subtreeFlags); + case 207: + return computeExpressionStatement(node, subtreeFlags); + case 144: + return computeParameter(node, subtreeFlags); + case 185: + return computeArrowFunction(node, subtreeFlags); + case 184: + return computeFunctionExpression(node, subtreeFlags); + case 225: + return computeFunctionDeclaration(node, subtreeFlags); + case 223: + return computeVariableDeclaration(node, subtreeFlags); + case 224: + return computeVariableDeclarationList(node, subtreeFlags); + case 205: + return computeVariableStatement(node, subtreeFlags); + case 219: + return computeLabeledStatement(node, subtreeFlags); + case 226: + return computeClassDeclaration(node, subtreeFlags); + case 197: return computeClassExpression(node, subtreeFlags); - case 251: + case 255: return computeHeritageClause(node, subtreeFlags); - case 194: + case 256: + return computeCatchClause(node, subtreeFlags); + case 199: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 148: - return computeConstructor(node, subtreeFlags); - case 145: - return computePropertyDeclaration(node, subtreeFlags); - case 147: - return computeMethod(node, subtreeFlags); - case 149: case 150: + return computeConstructor(node, subtreeFlags); + case 147: + return computePropertyDeclaration(node, subtreeFlags); + case 149: + return computeMethod(node, subtreeFlags); + case 151: + case 152: return computeAccessor(node, subtreeFlags); - case 229: + case 234: return computeImportEquals(node, subtreeFlags); - case 172: + case 177: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -18073,40 +20418,55 @@ var ts; var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (subtreeFlags & 262144 + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288 || isSuperOrSuperProperty(expression, expressionKind)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537133909; + return transformFlags & ~537396545; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 95: + case 96: return true; - case 172: - case 173: + case 177: + case 178: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 95; + return expressionKind === 96; } return false; } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 56 - && (leftKind === 171 - || leftKind === 170)) { - transformFlags |= 192 | 256; + if (operatorTokenKind === 57 && leftKind === 176) { + transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 38 - || operatorTokenKind === 60) { - transformFlags |= 48; + else if (operatorTokenKind === 57 && leftKind === 175) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 39 + || operatorTokenKind === 61) { + transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18114,36 +20474,38 @@ var ts; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken) { - transformFlags |= 3; - } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { - transformFlags |= 3 | 131072; + transformFlags |= 3 | 262144; } - if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { - transformFlags |= 192 | 65536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~536872257; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 195 - || expressionKind === 177) { + if (expressionKind === 200 + || expressionKind === 182) { transformFlags |= 3; } - if (expressionTransformFlags & 256) { - transformFlags |= 256; + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -18153,35 +20515,36 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 137216) - || (modifierFlags & 1)) { + if ((subtreeFlags & 274432) + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 137216) { + if (subtreeFlags & 274432 + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 83: + case 84: transformFlags |= 192; break; - case 106: + case 107: transformFlags |= 3; break; default: @@ -18189,7 +20552,15 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18197,127 +20568,155 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var body = node.body; - if (body === undefined) { + if (ts.hasModifier(node, 2270) + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - var typeParameters = node.typeParameters; - var asteriskToken = node.asteriskToken; - if (!body - || typeParameters - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer) { - transformFlags |= 4096; + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - var asteriskToken = node.asteriskToken; if (!body || (modifierFlags & 2)) { transformFlags = 3; } else { - transformFlags = subtreeFlags | 8388608; - if (modifierFlags & 1) { - transformFlags |= 3 | 192; - } - if (modifierFlags & 256) { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (modifierFlags & 256) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var asteriskToken = node.asteriskToken; - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 8192) { - transformFlags |= 16384; + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550710101; + return transformFlags & ~601249089; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (expressionKind === 95) { - transformFlags |= 8192; + if (expressionKind === 96) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - var nameKind = node.name.kind; - if (nameKind === 167 || nameKind === 168) { - transformFlags |= 192 | 2097152; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -18328,24 +20727,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (modifierFlags & 1) { - transformFlags |= 192 | 3; - } - if (declarationListTransformFlags & 2097152) { + if (declarationListTransformFlags & 8388608) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 1048576 + if (subtreeFlags & 4194304 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18353,15 +20749,15 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 256) { + if (node.expression.transformFlags & 1024) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -18370,78 +20766,76 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546335573; + return transformFlags & ~574674241; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608; - if (subtreeFlags & 2097152) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 1048576; + transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~546309441; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536871765; + var excludeFlags = 536872257; switch (kind) { - case 112: - case 110: + case 119: + case 189: + transformFlags |= 16; + break; + case 113: case 111: - case 115: - case 122: - case 118: - case 74: - case 184: - case 224: - case 255: - case 177: - case 195: - case 196: - case 128: + case 112: + case 116: + case 123: + case 75: + case 229: + case 260: + case 182: + case 200: + case 201: + case 130: transformFlags |= 3; break; - case 241: - case 242: - case 243: - case 244: - case 245: case 246: case 247: case 248: - transformFlags |= 12; + case 10: + case 249: + case 250: + case 251: + case 252: + transformFlags |= 4; break; - case 82: - transformFlags |= 192 | 3; - break; - case 77: - case 11: + case 213: + transformFlags |= 8; case 12: case 13: case 14: - case 189: - case 176: - case 254: - case 208: + case 15: + case 194: + case 181: + case 258: + case 114: transformFlags |= 192; break; - case 190: - transformFlags |= 192 | 4194304; + case 195: + transformFlags |= 192 | 16777216; break; - case 117: - case 130: - case 127: + case 118: case 132: - case 120: - case 133: - case 103: - case 141: - case 144: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: case 146: - case 151: - case 152: + case 148: case 153: case 154: case 155: @@ -18454,73 +20848,154 @@ var ts; case 162: case 163: case 164: - case 222: - case 223: case 165: case 166: + case 227: + case 228: + case 167: + case 168: + case 169: + case 170: + case 171: transformFlags = 3; excludeFlags = -3; break; - case 140: - transformFlags |= 524288; - if (subtreeFlags & 8192) { - transformFlags |= 32768; + case 142: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; } break; - case 191: - transformFlags |= 262144; + case 196: + transformFlags |= 192 | 524288; break; - case 95: + case 259: + transformFlags |= 8 | 1048576; + break; + case 96: transformFlags |= 192; break; - case 97: - transformFlags |= 8192; + case 98: + transformFlags |= 16384; break; - case 167: - case 168: - transformFlags |= 192 | 2097152; + case 172: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; break; - case 143: - transformFlags |= 3 | 2048; + case 173: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; break; - case 171: - excludeFlags = 537430869; + case 174: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 145: + transformFlags |= 3 | 4096; + break; + case 176: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 175: + case 180: + excludeFlags = 537396545; if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; - } break; - case 170: - case 175: - excludeFlags = 537133909; - if (subtreeFlags & 262144) { - transformFlags |= 192; - } - break; - case 204: - case 205: - case 206: - case 207: - if (subtreeFlags & 1048576) { - transformFlags |= 192; - } - break; - case 256: - if (subtreeFlags & 16384) { - transformFlags |= 192; - } - break; - case 211: case 209: case 210: - transformFlags |= 8388608; + case 211: + case 212: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 261: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 216: + case 214: + case 215: + transformFlags |= 33554432; break; } node.transformFlags = transformFlags | 536870912; return transformFlags & ~excludeFlags; } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 156 && kind <= 171) { + return -3; + } + switch (kind) { + case 179: + case 180: + case 175: + return 537396545; + case 230: + return 574674241; + case 144: + return 536872257; + case 185: + return 601249089; + case 184: + case 225: + return 601281857; + case 224: + return 546309441; + case 226: + case 197: + return 539358529; + case 150: + return 601015617; + case 149: + case 151: + case 152: + return 601015617; + case 118: + case 132: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: + case 146: + case 148: + case 153: + case 154: + case 155: + case 227: + case 228: + return -3; + case 176: + return 540087617; + case 256: + return 537920833; + case 172: + case 173: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; })(ts || (ts = {})); var ts; (function (ts) { @@ -18547,6 +21022,8 @@ var ts; ts.getSymbolId = getSymbolId; function createTypeChecker(host, produceDiagnostics) { var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); @@ -18608,21 +21085,28 @@ var ts; getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + tryGetMemberInModuleExports: tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + } }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var stringLiteralTypes = ts.createMap(); var numericLiteralTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var trueType = createIntrinsicType(128, "true"); @@ -18633,10 +21117,13 @@ var ts; var neverType = createIntrinsicType(8192, "never"); var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + emptyTypeLiteralSymbol.members = ts.createMap(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); @@ -18657,6 +21144,7 @@ var ts; var globalBooleanType; var globalRegExpType; var anyArrayType; + var autoArrayType; var anyReadonlyArrayType; var getGlobalTemplateStringsArrayType; var getGlobalESSymbolType; @@ -18723,6 +21211,8 @@ var ts; "undefined": undefinedType }); var jsxElementType; + var _jsxNamespace; + var _jsxFactoryEntity; var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", @@ -18743,6 +21233,21 @@ var ts; builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; + function getJsxNamespace() { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } function getEmitResolver(sourceFile, cancellationToken) { getDiagnostics(sourceFile, cancellationToken); return emitResolver; @@ -18823,12 +21328,10 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 225 && source.valueDeclaration.kind !== 225))) { + (target.valueDeclaration.kind === 230 && source.valueDeclaration.kind !== 230))) { target.valueDeclaration = source.valueDeclaration; } - ts.forEach(source.declarations, function (node) { - target.declarations.push(node); - }); + ts.addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = ts.createMap(); @@ -18879,7 +21382,7 @@ var ts; var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); if (!mainModule) { return; } @@ -18916,8 +21419,11 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } function isGlobalSourceFile(node) { - return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 261 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -18954,36 +21460,39 @@ var ts; (!compilerOptions.outFile && !compilerOptions.out)) { return true; } + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } var sourceFiles = host.getSourceFiles(); return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 218 || + return declaration.kind !== 223 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 200: - case 206: - case 208: + case 205: + case 211: + case 213: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } break; } switch (declaration.parent.parent.kind) { - case 207: - case 208: + case 212: + case 213: if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { return true; } } return false; } - function isUsedInFunctionOrNonStaticProperty(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage, container) { var current = usage; while (current) { if (current === container) { @@ -18993,7 +21502,7 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 145 && + current.parent.kind === 147 && (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { @@ -19016,18 +21525,18 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 278) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 142 || - lastLocation.kind === 141 + lastLocation.kind === 144 || + lastLocation.kind === 143 : false; } if (meaning & 107455 && result.flags & 1) { useResult = - lastLocation.kind === 142 || + lastLocation.kind === 144 || (lastLocation === location.type && - result.valueDeclaration.kind === 142); + result.valueDeclaration.kind === 144); } } if (useResult) { @@ -19039,13 +21548,13 @@ var ts; } } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 225: + case 230: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 256 || ts.isAmbientModule(location)) { + if (location.kind === 261 || ts.isAmbientModule(location)) { if (result = moduleExports["default"]) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { @@ -19055,7 +21564,7 @@ var ts; } if (moduleExports[name] && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 238)) { + ts.getDeclarationOfKind(moduleExports[name], 243)) { break; } } @@ -19063,13 +21572,13 @@ var ts; break loop; } break; - case 224: + case 229: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 145: - case 144: + case 147: + case 146: if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -19079,9 +21588,9 @@ var ts; } } break; - case 221: - case 192: - case 222: + case 226: + case 197: + case 227: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -19089,7 +21598,7 @@ var ts; } break loop; } - if (location.kind === 192 && meaning & 32) { + if (location.kind === 197 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -19097,28 +21606,28 @@ var ts; } } break; - case 140: + case 142: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 222) { + if (ts.isClassLike(grandparent) || grandparent.kind === 227) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 180: + case 151: + case 152: + case 225: + case 185: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 179: + case 184: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -19131,8 +21640,8 @@ var ts; } } break; - case 143: - if (location.parent && location.parent.kind === 142) { + case 145: + if (location.parent && location.parent.kind === 144) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -19154,6 +21663,7 @@ var ts; if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } @@ -19174,15 +21684,15 @@ var ts; } if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + if (decls && decls.length === 1 && decls[0].kind === 233) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 70 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -19220,16 +21730,26 @@ var ts; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 69: - case 172: + case 70: + case 177: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: + case 199: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); @@ -19244,7 +21764,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -19261,23 +21781,23 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } - while (node && node.kind !== 230) { + while (node && node.kind !== 235) { node = node.parent; } return node; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 240) { + if (node.moduleReference.kind === 245) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -19335,28 +21855,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_18 = specifier.propertyName || specifier.name; + if (name_18.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_18.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_18.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_18.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_18.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_18, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_18)); } return symbol; } @@ -19378,19 +21898,19 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 229: - return getTargetOfImportEqualsDeclaration(node); - case 231: - return getTargetOfImportClause(node); - case 232: - return getTargetOfNamespaceImport(node); case 234: + return getTargetOfImportEqualsDeclaration(node); + case 236: + return getTargetOfImportClause(node); + case 237: + return getTargetOfNamespaceImport(node); + case 239: return getTargetOfImportSpecifier(node); - case 238: + case 243: return getTargetOfExportSpecifier(node); - case 235: + case 240: return getTargetOfExportAssignment(node); - case 228: + case 233: return getTargetOfNamespaceExportDeclaration(node); } } @@ -19434,10 +21954,10 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 235) { + if (node.kind === 240) { checkExpressionCached(node.expression); } - else if (node.kind === 238) { + else if (node.kind === 243) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -19445,15 +21965,15 @@ var ts; } } } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { - if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 70 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 69 || entityName.parent.kind === 139) { + if (entityName.kind === 70 || entityName.parent.kind === 141) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 229); + ts.Debug.assert(entityName.parent.kind === 234); return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } @@ -19465,16 +21985,16 @@ var ts; return undefined; } var symbol; - if (name.kind === 69) { + if (name.kind === 70) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } } - else if (name.kind === 139 || name.kind === 172) { - var left = name.kind === 139 ? name.left : name.expression; - var right = name.kind === 139 ? name.right : name.name; + else if (name.kind === 141 || name.kind === 177) { + var left = name.kind === 141 ? name.left : name.expression; + var right = name.kind === 141 ? name.right : name.name; var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -19499,27 +22019,28 @@ var ts; function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } if (moduleReferenceExpression.kind !== 9) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', 512); - if (symbol) { - return getMergedSymbol(symbol); - } + var ambientModule = tryFindAmbientModule(moduleName, true); + if (ambientModule) { + return ambientModule; } + var isRelative = ts.isExternalModuleNameRelative(moduleName); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); @@ -19535,14 +22056,29 @@ var ts; return getMergedSymbol(pattern.symbol); } } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + } + return undefined; + } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -19564,6 +22100,12 @@ var ts; function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } function getExportsOfSymbol(symbol) { return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -19593,6 +22135,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -19656,7 +22199,7 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 148 && ts.nodeIsPresent(member.body)) { + if (member.kind === 150 && ts.nodeIsPresent(member.body)) { return member; } } @@ -19678,8 +22221,9 @@ var ts; type.intrinsicName = "boolean"; return type; } - function createObjectType(kind, symbol) { - var type = createType(kind); + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -19703,7 +22247,7 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; @@ -19715,7 +22259,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -19726,11 +22270,11 @@ var ts; } } switch (location_1.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 225: + case 230: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } @@ -19744,6 +22288,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -19757,26 +22311,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -19794,7 +22350,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -19808,10 +22364,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 145: case 147: case 149: - case 150: + case 151: + case 152: continue; default: return false; @@ -19833,7 +22389,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, }; } return hasAccessibleDeclarations; @@ -19854,7 +22410,7 @@ var ts; } return { accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 }; @@ -19867,7 +22423,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 261 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -19901,11 +22457,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 158 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 160 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning = 107455 | 1048576; } - else if (entityName.kind === 139 || entityName.kind === 172 || - entityName.parent.kind === 229) { + else if (entityName.kind === 141 || entityName.kind === 177 || + entityName.parent.kind === 234) { meaning = 1920; } else { @@ -19997,10 +22553,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 164) { + while (node.kind === 166) { node = node.parent; } - if (node.kind === 223) { + if (node.kind === 228) { return getSymbolOfNode(node); } } @@ -20008,7 +22564,7 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 226 && + node.parent.kind === 231 && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { @@ -20022,10 +22578,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 192: + case 197: return "(Anonymous class)"; - case 179: - case 180: + case 184: + case 185: return "(Anonymous function)"; } } @@ -20039,17 +22595,17 @@ var ts; var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 19); + writePunctuation(writer, 20); if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } else { - writePunctuation(writer, 21); + writePunctuation(writer, 22); writer.writeSymbol(symbolName, symbol); } } @@ -20077,9 +22633,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_5) { + walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,55 +22670,66 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { + else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } else if (type.flags & 256) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); + writePunctuation(writer, 22); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 2097152) { + else if (getObjectFlags(type) & (16 | 32)) { writeAnonymousType(type, nextFlags); } else if (type.flags & 96) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & 262144) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 64); + } + else if (type.flags & 524288) { + writeType(type.objectType, 64); + writePunctuation(writer, 20); + writeType(type.indexType, 0); + writePunctuation(writer, 21); + } else { - writePunctuation(writer, 15); - writeSpace(writer); - writePunctuation(writer, 22); - writeSpace(writer); writePunctuation(writer, 16); + writeSpace(writer); + writePunctuation(writer, 23); + writeSpace(writer); + writePunctuation(writer, 17); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 24) { + if (delimiter !== 25) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 24 ? 0 : 64); + writeType(types[i], delimiter === 25 ? 0 : 64); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { @@ -20170,29 +22737,29 @@ var ts; buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); writeType(typeArguments[pos], 256); pos++; while (pos < end) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); writeType(typeArguments[pos], 0); pos++; } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & 1)) { writeType(typeArguments[0], 64); - writePunctuation(writer, 19); writePunctuation(writer, 20); + writePunctuation(writer, 21); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + else if (type.target.objectFlags & 8) { writePunctuation(writer, 20); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 25); + writePunctuation(writer, 21); } else { var outerTypeParameters = type.target.outerTypeParameters; @@ -20201,13 +22768,13 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); - writePunctuation(writer, 21); + writeSymbolTypeReference(parent_6, typeArguments, start, i, flags); + writePunctuation(writer, 22); } } } @@ -20217,16 +22784,16 @@ var ts; } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 48); } else { - writeTypeList(type.types, 46); + writeTypeList(type.types, 47); } if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } } function writeAnonymousType(type, flags) { @@ -20244,7 +22811,7 @@ var ts; buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { - writeKeyword(writer, 117); + writeKeyword(writer, 118); } } else { @@ -20265,7 +22832,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 256 || declaration.parent.kind === 226; + return declaration.parent.kind === 261 || declaration.parent.kind === 231; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -20274,37 +22841,37 @@ var ts; } } function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 101); + writeKeyword(writer, 102); writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); } function writeIndexSignature(info, keyword) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } - writePunctuation(writer, 19); + writePunctuation(writer, 20); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeKeyword(writer, keyword); - writePunctuation(writer, 20); - writePunctuation(writer, 54); + writePunctuation(writer, 21); + writePunctuation(writer, 55); writeSpace(writer); writeType(info.type, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } buildSymbolDisplay(prop, writer); if (prop.flags & 536870912) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { @@ -20319,56 +22886,68 @@ var ts; return false; } function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 15); writePunctuation(writer, 16); + writePunctuation(writer, 17); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 15); + writePunctuation(writer, 16); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 17); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } - writeIndexSignature(resolved.stringIndexInfo, 132); - writeIndexSignature(resolved.numberIndexInfo, 130); + writeIndexSignature(resolved.stringIndexInfo, 134); + writeIndexSignature(resolved.numberIndexInfo, 132); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -20378,22 +22957,45 @@ var ts; var signature = signatures_1[_f]; writePropertyWithModifiers(p); buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeType(t, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } - writer.decreaseIndent(); + } + function writeMappedType(type) { writePunctuation(writer, 16); - inObjectTypeLiteral = saveInObjectTypeLiteral; + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 130); + writeSpace(writer); + } + writePunctuation(writer, 20); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 91); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 21); + if (type.declaration.questionToken) { + writePunctuation(writer, 54); + } + writePunctuation(writer, 55); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 24); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 17); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { @@ -20407,7 +23009,7 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 83); + writeKeyword(writer, 84); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } @@ -20415,7 +23017,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (ts.isRestParameter(parameterNode)) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } if (ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -20424,36 +23026,36 @@ var ts; appendSymbolNameOnly(p, writer); } if (isOptionalParameter(parameterNode)) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 167) { - writePunctuation(writer, 15); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (bindingPattern.kind === 172) { writePunctuation(writer, 16); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 17); } - else if (bindingPattern.kind === 168) { - writePunctuation(writer, 19); + else if (bindingPattern.kind === 173) { + writePunctuation(writer, 20); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 169); + ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); - writePunctuation(writer, 54); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 55); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -20461,75 +23063,75 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } action(list[i]); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); - var flags_1 = 256; + writePunctuation(writer, 26); + var flags = 256; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); - flags_1 = 0; + flags = 0; } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags_1); + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 18); + writePunctuation(writer, 19); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 97); + writeKeyword(writer, 98); } writeSpace(writer); - writeKeyword(writer, 124); + writeKeyword(writer, 125); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); - writePunctuation(writer, 34); + writePunctuation(writer, 35); } else { - writePunctuation(writer, 54); + writePunctuation(writer, 55); } writeSpace(writer); if (signature.typePredicate) { @@ -20542,7 +23144,7 @@ var ts; } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { if (kind === 1) { - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); } if (signature.target && (flags & 32)) { @@ -20578,63 +23180,63 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 169: + case 174: return isDeclarationVisible(node.parent.parent); - case 218: + case 223: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } + case 230: + case 226: + case 227: + case 228: case 225: - case 221: - case 222: - case 223: - case 220: - case 224: case 229: + case 234: if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_7 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 234 && parent_7.kind !== 261 && ts.isInAmbientContext(parent_7))) { + return isGlobalSourceFile(parent_7); } - return isDeclarationVisible(parent_9); - case 145: - case 144: - case 149: - case 150: + return isDeclarationVisible(parent_7); case 147: case 146: + case 151: + case 152: + case 149: + case 148: if (ts.getModifierFlags(node) & (8 | 16)) { return false; } - case 148: - case 152: - case 151: + case 150: + case 154: case 153: - case 142: - case 226: - case 156: - case 157: - case 159: case 155: - case 160: + case 144: + case 231: + case 158: + case 159: case 161: + case 157: case 162: case 163: case 164: + case 165: + case 166: return isDeclarationVisible(node.parent); - case 231: - case 232: - case 234: + case 236: + case 237: + case 239: return false; - case 141: - case 256: - case 228: + case 143: + case 261: + case 233: return true; - case 235: + case 240: return false; default: return false; @@ -20643,10 +23245,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 235) { + if (node.parent && node.parent.kind === 240) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 243) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -20708,7 +23310,6 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -20725,12 +23326,12 @@ var ts; node = ts.getRootDeclaration(node); while (node) { switch (node.kind) { - case 218: - case 219: - case 234: - case 233: - case 232: - case 231: + case 223: + case 224: + case 239: + case 238: + case 237: + case 236: node = node.parent; break; default: @@ -20756,22 +23357,36 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } - function getTextOfPropertyName(name) { - switch (name.kind) { - case 69: - return name.text; - case 9: - case 8: - return name.text; - case 140: - if (ts.isStringOrNumericLiteral(name.expression.kind)) { - return name.expression.text; - } - } - return undefined; - } function isComputedNonLiteralName(name) { - return name.kind === 140 && !ts.isStringOrNumericLiteral(name.expression.kind); + return name.kind === 142 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createMap(); + var names = ts.createMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name_19 = properties_2[_i]; + names[ts.getTextOfPropertyName(name_19)] = true; + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = prop.name in names; + var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isMethod = prop.flags & 8192; + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -20786,26 +23401,45 @@ var ts; return parentType; } var type; - if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { - return anyType; + if (pattern.kind === 172) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = getTextOfPropertyName(name_16); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); - return unknownType; + else { + var name_20 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_20)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name_20); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_20)); + return unknownType; + } } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) @@ -20820,9 +23454,6 @@ var ts; return unknownType; } } - else { - type = createArrayType(elementType); - } } if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); @@ -20832,46 +23463,35 @@ var ts; type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); - } - } - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var typeTag = ts.getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - if (declaration.kind === 218 && - declaration.parent.kind === 219 && - declaration.parent.parent.kind === 200) { - var annotation = ts.getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === 142) { - var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } return undefined; } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 94 || expr.kind === 70 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 175 && expr.elements.length === 0; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.parent.parent.kind === 207) { - return stringType; + if (declaration.parent.parent.kind === 212) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; } - if (declaration.parent.parent.kind === 208) { + if (declaration.parent.parent.kind === 213) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -20880,10 +23500,20 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } - if (declaration.kind === 142) { + if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && + declaration.kind === 223 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 144) { var func = declaration.parent; - if (func.kind === 150 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149); + if (func.kind === 152 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -20896,8 +23526,7 @@ var ts; } var type = void 0; if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -20910,7 +23539,7 @@ var ts; var type = checkDeclarationInitializer(declaration); return addOptionality(type, declaration.questionToken && includeOptionality); } - if (declaration.kind === 254) { + if (declaration.kind === 258) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -20932,6 +23561,7 @@ var ts; } function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createMap(); + var stringIndexInfo; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -20939,19 +23569,23 @@ var ts; hasComputedProperties = true; return; } - var text = getTextOfPropertyName(name); + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.objectFlags |= 512; } return result; } @@ -20970,7 +23604,7 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 167 + return pattern.kind === 172 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -20980,7 +23614,7 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 253) { + if (declaration.kind === 257) { return type; } return getWidenedType(type); @@ -20995,7 +23629,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 142 ? root.parent : root; + var memberDeclaration = root.kind === 144 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -21005,28 +23639,28 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 252) { + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 235) { + if (declaration.kind === 240) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + if (declaration.flags & 65536 && declaration.kind === 286 && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } if (!pushTypeResolution(symbol, 0)) { return unknownType; } var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 1048576) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + if (declaration.kind === 192 || + declaration.kind === 177 && declaration.parent.kind === 192) { + if (declaration.flags & 65536) { + var jsdocType = ts.getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 ? checkExpressionCached(decl.right) : checkExpressionCached(decl.parent.right); }); type = getUnionType(declaredTypes, true); @@ -21035,16 +23669,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -21052,7 +23677,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 149) { + if (accessor.kind === 151) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -21072,9 +23697,9 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 149); - var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 1048576) { + var getter = ts.getDeclarationOfKind(symbol, 151); + var setter = ts.getDeclarationOfKind(symbol, 152); + if (getter && getter.flags & 65536) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -21114,7 +23739,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 149); + var getter_1 = ts.getDeclarationOfKind(symbol, 151); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -21125,11 +23750,11 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(16, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; } @@ -21156,10 +23781,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -21182,7 +23824,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return getObjectFlags(type) & 4 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -21210,9 +23852,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 221 || node.kind === 192 || - node.kind === 220 || node.kind === 179 || - node.kind === 147 || node.kind === 180) { + if (node.kind === 226 || node.kind === 197 || + node.kind === 225 || node.kind === 184 || + node.kind === 149 || node.kind === 185) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -21221,15 +23863,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 222); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 222 || node.kind === 221 || - node.kind === 192 || node.kind === 223) { + if (node.kind === 227 || node.kind === 226 || + node.kind === 197 || node.kind === 228) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -21242,7 +23884,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -21254,7 +23896,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -21269,7 +23911,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -21286,7 +23928,7 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { + if (type.objectFlags & 8) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (32 | 64)) { @@ -21306,7 +23948,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 32768)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -21324,15 +23966,22 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getObjectFlags(getTargetType(baseType)) & 3)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } if (type.resolvedBaseTypes === emptyArray) { @@ -21355,12 +24004,12 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 227 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getObjectFlags(getTargetType(baseType)) & 3) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -21384,7 +24033,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222) { + if (declaration.kind === 227) { if (declaration.flags & 64) { return false; } @@ -21407,12 +24056,12 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1 : 2; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -21420,7 +24069,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21433,8 +24083,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); + var declaration = ts.getDeclarationOfKind(symbol, 285); var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -21445,14 +24094,15 @@ var ts; } } else { - declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + declaration = ts.getDeclarationOfKind(symbol, 228); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { + links.typeParameters = typeParameters; links.instantiations = ts.createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -21469,14 +24119,14 @@ var ts; return !ts.isInAmbientContext(member); } return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; + expr.kind === 70 && !!symbol.exports[expr.text]; } function enumHasLiteralMembers(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!isLiteralEnumMember(symbol, member)) { @@ -21504,7 +24154,7 @@ var ts; var memberTypes = ts.createMap(); for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { computeEnumMemberValues(declaration); for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; @@ -21519,7 +24169,7 @@ var ts; } enumType.memberTypes = memberTypes; if (memberTypeList.length > 1) { - enumType.flags |= 524288; + enumType.flags |= 65536; enumType.types = memberTypeList; unionTypes[getTypeListId(memberTypeList)] = enumType; } @@ -21531,7 +24181,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? + links.declaredType = enumType.flags & 65536 ? enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : enumType; } @@ -21542,7 +24192,7 @@ var ts; if (!links.declaredType) { var type = createType(16384); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 141).constraint) { + if (!ts.getDeclarationOfKind(symbol, 143).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -21591,20 +24241,20 @@ var ts; } function isIndependentType(node) { switch (node.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 166: + case 104: + case 137: + case 94: + case 129: + case 171: return true; - case 160: + case 162: return isIndependentType(node.elementType); - case 155: + case 157: return isIndependentTypeReference(node); } return false; @@ -21613,7 +24263,7 @@ var ts; return node.type && isIndependentType(node.type) || !node.type && !node.initializer; } function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 148 && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 150 && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -21629,12 +24279,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 145: - case 144: - return isIndependentVariableLikeDeclaration(declaration); case 147: case 146: + return isIndependentVariableLikeDeclaration(declaration); + case 149: case 148: + case 150: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -21677,7 +24327,7 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (getObjectFlags(type) & 4) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; @@ -21700,8 +24350,8 @@ var ts; else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -21721,7 +24371,7 @@ var ts; numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -21756,14 +24406,14 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -21848,7 +24498,7 @@ var ts; var constructSignatures = getUnionSignatures(type.types, 1); var stringIndexInfo = getUnionIndexInfo(type.types, 0); var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); @@ -21856,6 +24506,9 @@ var ts; function intersectIndexInfos(info1, info2) { return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { var callSignatures = emptyArray; var constructSignatures = emptyArray; @@ -21868,17 +24521,17 @@ var ts; stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { var members = symbol.members; @@ -21886,7 +24539,7 @@ var ts; var constructSignatures = getSignaturesOfSymbol(members["__new"]); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { var members = emptySymbols; @@ -21901,46 +24554,130 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } } } + function resolveMappedTypeMembers(type) { + var members = ts.createMap(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 168) { + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t) { + var iterationMapper = createUnaryTypeMapper(typeParameter, t); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = t.text; + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); + var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getErasedTemplateTypeFromMappedType(type) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32) { + var constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, 540672 | 262144); + } + return false; + } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { - resolveTypeReferenceMembers(type); + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } } - else if (type.flags & (32768 | 65536)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & 2097152) { - resolveAnonymousTypeMembers(type); - } - else if (type.flags & 524288) { + else if (type.flags & 65536) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 131072) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -21953,51 +24690,55 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 65536) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & 34) { - type = globalStringType; - } - else if (type.flags & 340) { - type = globalNumberType; - } - else if (type.flags & 136) { - type = globalBooleanType; - } - else if (type.flags & 512) { - type = getGlobalESSymbolType(); - } - return type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & 262178 ? globalStringType : + t.flags & 340 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22015,21 +24756,21 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { - return undefined; + else if (containingType.flags & 65536) { + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +24781,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,9 +24805,13 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -22082,13 +24825,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 196608) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -22098,7 +24841,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -22129,7 +24872,7 @@ var ts; return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -22157,21 +24900,31 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 1048576) { - if (node.type && node.type.kind === 268) { + if (node.flags & 65536) { + if (node.type && node.type.kind === 273) { return true; } - var paramTag = ts.getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 268; + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 273; + } } } } } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } function isOptionalParameter(node) { if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -22186,7 +24939,7 @@ var ts; return false; } function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 69) { + if (node.parameterName.kind === 70) { var parameterName = node.parameterName; return { kind: 1, @@ -22225,7 +24978,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166) { + if (param.type && param.type.kind === 171) { hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { @@ -22237,10 +24990,10 @@ var ts; minArgumentCount = -1; } } - if ((declaration.kind === 149 || declaration.kind === 150) && + if ((declaration.kind === 151 || declaration.kind === 152) && !ts.hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 149 ? 150 : 149; + var otherKind = declaration.kind === 151 ? 152 : 151; var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); @@ -22252,24 +25005,21 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } - var classType = declaration.kind === 148 ? + var classType = declaration.kind === 150 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 154 ? + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 156 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType) { + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -22279,14 +25029,14 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.kind === 149 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 150); + if (declaration.kind === 151 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 152); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -22300,20 +25050,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 269: + case 184: + case 185: + case 274: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -22374,13 +25124,18 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { return type.typeArguments[0]; } } return anyType; } function getSignatureInstantiation(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + function createSignatureInstantiation(signature, typeArguments) { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { @@ -22393,8 +25148,8 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var isConstructor = signature.declaration.kind === 150 || signature.declaration.kind === 154; + var type = createObjectType(16); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -22407,7 +25162,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 130 : 132; + var syntaxKind = kind === 1 ? 132 : 134; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -22434,11 +25189,11 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 141).constraint; + return ts.getDeclarationOfKind(type.symbol, 143).constraint; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22466,8 +25221,13 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } function getTypeListId(types) { var result = ""; @@ -22500,22 +25260,23 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(4, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; type.target = target; type.typeArguments = typeArguments; } return type; } function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -22531,7 +25292,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -22539,18 +25300,23 @@ var ts; } return type; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeAliasInstantiation(symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); - var id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -22567,11 +25333,11 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 155: + case 157: return node.typeName; - case 267: + case 272: return node.name; - case 194: + case 199: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -22579,7 +25345,7 @@ var ts; } return undefined; } - function resolveTypeReferenceName(node, typeReferenceName) { + function resolveTypeReferenceName(typeReferenceName) { if (!typeReferenceName) { return unknownSymbol; } @@ -22595,7 +25361,7 @@ var ts; if (symbol.flags & 524288) { return getTypeFromTypeAliasReference(node, symbol); } - if (symbol.flags & 107455 && node.kind === 267) { + if (symbol.flags & 107455 && node.kind === 272) { return getTypeOfSymbol(symbol); } return getTypeFromNonGenericTypeReference(node, symbol); @@ -22605,13 +25371,13 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - if (node.kind === 267) { + if (node.kind === 272) { var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { - var typeNameOrExpression = node.kind === 155 + var typeNameOrExpression = node.kind === 157 ? node.typeName : ts.isEntityNameExpression(node.expression) ? node.expression @@ -22640,9 +25406,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 221: - case 222: - case 224: + case 226: + case 227: + case 229: return declaration; } } @@ -22651,7 +25417,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 32768)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -22714,7 +25480,7 @@ var ts; property.type = typeParameter; properties.push(property); } - var type = createObjectType(262144 | 131072); + var type = createObjectType(8 | 4); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -22722,7 +25488,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22740,7 +25507,7 @@ var ts; function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -22768,7 +25535,7 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 524288) { + if (flags & 65536) { addTypesToUnion(typeSet, type.types); } else if (flags & 1) { @@ -22779,7 +25546,7 @@ var ts; typeSet.containsUndefined = true; if (flags & 4096) typeSet.containsNull = true; - if (!(flags & 33554432)) + if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } else if (!(flags & 8192)) { @@ -22792,7 +25559,8 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -22821,7 +25589,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -22837,7 +25622,7 @@ var ts; var t = types[i]; var remove = t.flags & 32 && types.containsString || t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -22879,28 +25664,31 @@ var ts; var type = unionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type = unionTypes[id] = createType(65536 | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { + if (type.flags & 131072) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1) { typeSet.containsAny = true; } else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -22922,43 +25710,303 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + type = intersectionTypes[id] = createType(131072 | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); } return links.resolvedType; } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + var propName = indexType.flags & (32 | 64 | 256) ? + indexType.text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : + undefined; + if (propName) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + var indexNode = accessNode.kind === 178 ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 | 64)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + } + else if (indexType.flags & (2 | 4)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (ts.isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 228 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right, isFromObjectLiteral) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + left = filterType(left, function (t) { return !(t.flags & 6144); }); + if (left.flags & 8192) { + return right; + } + right = filterType(right, function (t) { return !(t.flags & 6144); }); + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right, isFromObjectLiteral); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t, isFromObjectLiteral); }); + } + var members = ts.createMap(); + var skippedPrivateMembers = ts.createMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isOwnProperty = !(rightProp.flags & 8192) || isFromObjectLiteral; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + var rightProp = members[leftProp.name]; + var rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } function createLiteralType(flags, text) { var type = createType(flags); type.text = text; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 16777216)) { + if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 16777216, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.text); freshType.regularType = type; type.freshType = freshType; } @@ -22967,7 +26015,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } function getLiteralTypeForText(flags, text) { var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; @@ -22991,7 +26039,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); + var types = ts.map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -22999,9 +26047,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 227)) { if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 150 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -23015,85 +26063,88 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type) { - return getTypeFromTypeNode(type, undefined, undefined); - } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { - case 117: - case 258: - case 259: - return anyType; - case 132: - return stringType; - case 130: - return numberType; - case 120: - return booleanType; - case 133: - return esSymbolType; - case 103: - return voidType; - case 135: - return undefinedType; - case 93: - return nullType; - case 127: - return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; - case 165: - case 97: - return getTypeFromThisTypeNode(node); - case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); - case 155: - case 267: - return getTypeFromTypeReference(node); - case 154: - return booleanType; - case 194: - return getTypeFromTypeReference(node); - case 158: - return getTypeFromTypeQueryNode(node); - case 160: - case 260: - return getTypeFromArrayTypeNode(node); - case 161: - return getTypeFromTupleTypeNode(node); - case 162: - case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 164: + case 118: case 263: case 264: - case 271: - case 272: - case 268: - return getTypeFromTypeNode(node.type); - case 265: - return getTypeFromTypeNode(node.literal); - case 156: + return anyType; + case 134: + return stringType; + case 132: + return numberType; + case 121: + return booleanType; + case 135: + return esSymbolType; + case 104: + return voidType; + case 137: + return undefinedType; + case 94: + return nullType; + case 129: + return neverType; + case 289: + return nullType; + case 290: + return undefinedType; + case 291: + return neverType; + case 167: + case 98: + return getTypeFromThisTypeNode(node); + case 171: + return getTypeFromLiteralTypeNode(node); + case 288: + return getTypeFromLiteralTypeNode(node.literal); case 157: - case 159: - case 281: + case 272: + return getTypeFromTypeReference(node); + case 156: + return booleanType; + case 199: + return getTypeFromTypeReference(node); + case 160: + return getTypeFromTypeQueryNode(node); + case 162: + case 265: + return getTypeFromArrayTypeNode(node); + case 163: + return getTypeFromTupleTypeNode(node); + case 164: + case 266: + return getTypeFromUnionTypeNode(node); + case 165: + return getTypeFromIntersectionTypeNode(node); + case 166: + case 268: case 269: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); - case 69: - case 139: + case 276: + case 277: + case 273: + return getTypeFromTypeNode(node.type); + case 270: + return getTypeFromTypeNode(node.literal); + case 158: + case 159: + case 161: + case 287: + case 274: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 168: + return getTypeFromTypeOperatorNode(node); + case 169: + return getTypeFromIndexedAccessTypeNode(node); + case 170: + return getTypeFromMappedTypeNode(node); + case 70: + case 141: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 262: + case 267: return getTypeFromJSDocTupleType(node); - case 270: + case 275: return getTypeFromJSDocVariadicType(node); default: return unknownType; @@ -23110,6 +26161,16 @@ var ts; } return items; } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } function createUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -23132,7 +26193,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -23222,45 +26282,68 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - if (mapper.instantiations) { - var cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + var replacementMapper = createUnaryTypeMapper(typeVariable_1, t); + var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - var result = createObjectType(2097152 | 4194304, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } var mappedTypes = mapper.mappedTypes; var node = symbol.declarations[0].parent; while (node) { switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 221: - case 192: - case 222: - case 223: + case 184: + case 185: + case 226: + case 197: + case 227: + case 228: var declaration = node; if (declaration.typeParameters) { for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { @@ -23270,86 +26353,122 @@ var ts; } } } - if (ts.isClassLike(node) || node.kind === 222) { + if (ts.isClassLike(node) || node.kind === 227) { var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; if (thisType && ts.contains(mappedTypes, thisType)) { return true; } } break; - case 225: - case 256: + case 230: + case 261: return false; } node = node.parent; } return false; } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 261 || parentKind === 231; + } + return false; + } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { - return mapper(type); + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & 2097152) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & 131072) { - return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } return type; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 179: - case 180: + case 184: + case 185: return isContextSensitiveFunctionLikeDeclaration(node); - case 171: + case 176: return ts.forEach(node.properties, isContextSensitive); - case 170: + case 175: return ts.forEach(node.elements, isContextSensitive); - case 188: + case 193: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 187: - return node.operatorToken.kind === 52 && + case 192: + return node.operatorToken.kind === 53 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 253: + case 257: return isContextSensitive(node.initializer); - case 147: - case 146: + case 149: + case 148: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 183: return isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - var areAllParametersUntyped = !ts.forEach(node.parameters, function (p) { return p.type; }); - var isNullaryArrow = node.kind === 180 && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !p.type; })) { + return true; + } + if (node.kind === 185) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(16, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -23528,7 +26647,7 @@ var ts; } if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { + (source.flags & 65536) !== (target.flags & 65536)) { return enumRelation[id] = false; } var targetEnumType = getTypeOfSymbol(target.symbol); @@ -23551,7 +26670,7 @@ var ts; return false; if (target.flags & 1 || source.flags & 8192) return true; - if (source.flags & 34 && target.flags & 2) + if (source.flags & 262178 && target.flags & 2) return true; if (source.flags & 340 && target.flags & 4) return true; @@ -23585,23 +26704,23 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 32768 && target.flags & 32768) { var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { return related === 1; } } - if (source.flags & 4177920 || target.flags & 4177920) { + if (source.flags & 507904 || target.flags & 507904) { return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); } return false; @@ -23638,9 +26757,15 @@ var ts; targetType = typeToString(target, undefined, 128); } if (!message) { - message = relation === comparableRelation ? - ts.Diagnostics.Type_0_is_not_comparable_to_type_1 : - ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); } @@ -23654,12 +26779,29 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target) @@ -23669,19 +26811,19 @@ var ts; } if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (source.flags & 8388608 && source.flags & 16777216) { + if (getObjectFlags(source) & 128 && source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 65536) { if (relation === comparableRelation) { result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } @@ -23692,44 +26834,106 @@ var ts; return result; } } - else if (target.flags & 1048576) { - result = typeRelatedToEachType(source, target, reportErrors); - if (result) { + else if (target.flags & 65536) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } - else { - if (source.flags & 1048576) { - if (result = someTypeRelatedToType(source, target, false)) { + else if (target.flags & 131072) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else if (source.flags & 131072) { + if (result = someTypeRelatedToType(source, target, false)) { + return result; + } + } + else if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + var constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & 262144) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 524288) { + if (source.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & 16384) { - var constraint = getConstraintOfTypeParameter(source); - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + if (apparentSource.flags & (32768 | 131072) && target.flags & 32768) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; @@ -23738,10 +26942,10 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { + if (source.flags & 32768 && target.flags & 8190) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -23750,18 +26954,18 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 32768 && target.flags & 32768) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { - if (result = eachTypeRelatedToSomeType(source, target, false)) { - if (result &= eachTypeRelatedToSomeType(target, source, false)) { + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -23769,7 +26973,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -23778,7 +26982,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -23796,7 +27000,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23811,7 +27015,7 @@ var ts; } return false; } - function eachTypeRelatedToSomeType(source, target, reportErrors) { + function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { @@ -23826,7 +27030,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { + if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } var len = targetTypes.length; @@ -23853,7 +27057,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { + if (source.flags & 65536 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -23940,6 +27144,9 @@ var ts; if (expandingFlags === 3) { result = 1; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -23967,15 +27174,42 @@ var ts; } return result; } + function mappedTypeRelatedTo(source, target, reportErrors) { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + var result_2; + if (relation === identityRelation) { + var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken; + var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) { + return -1; + } + return 0; + } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -24027,7 +27261,7 @@ var ts; return 0; } result &= related; - if (sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -24039,7 +27273,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 32768 && target.flags & 32768)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -24211,7 +27445,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (getObjectFlags(type) & 16) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -24223,12 +27457,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (getObjectFlags(type) & (4 | 64) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (getObjectFlags(t) & (4 | 64) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -24386,10 +27620,10 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return getObjectFlags(type) & 4 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { @@ -24400,7 +27634,7 @@ var ts; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -24408,19 +27642,19 @@ var ts; type.flags & 64 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 16777216 ? stringType : - type.flags & 64 && type.flags & 16777216 ? numberType : + return type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -24431,7 +27665,7 @@ var ts; return result; } function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 ? type.text === "" ? 32 : 0 : type.flags & 64 ? type.text === "0" ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : @@ -24442,7 +27676,7 @@ var ts; return type; } var types = [type]; - if (flags & 34) + if (flags & 262178) types.push(emptyStringType); if (flags & 340) types.push(zeroType); @@ -24492,7 +27726,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 8388608 && type.flags & 16777216)) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -24502,7 +27736,8 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; type.regularType = regularNew; return regularNew; } @@ -24519,25 +27754,25 @@ var ts; return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { + if (type.flags & 6291456) { if (type.flags & 6144) { return anyType; } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -24553,11 +27788,11 @@ var ts; } } } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -24571,25 +27806,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 145: - case 144: + case 147: + case 146: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 142: + case 144: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 169: + case 174: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 220: - case 147: - case 146: + case 225: case 149: - case 150: - case 179: - case 180: + case 148: + case 151: + case 152: + case 184: + case 185: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -24602,7 +27837,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -24634,7 +27869,7 @@ var ts; signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length), }; } function createTypeInferencesObject() { @@ -24642,26 +27877,72 @@ var ts; primary: undefined, secondary: undefined, topLevel: true, - isFixed: false + isFixed: false, }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypes(context, originalSource, originalTarget) { - var typeParameters = context.signature.typeParameters; + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var typeVariableArray = [typeVariable]; + var typeInferences = createTypeInferencesObject(); + var typeInferencesArray = [typeInferences]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var members = createSymbolTable(properties); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + var inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, true); + } + } + function inferTypesWithContext(context, originalSource, originalTarget) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { var sourceStack; var targetStack; var depth = 0; @@ -24677,11 +27958,19 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { return; } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -24708,13 +27997,13 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 540672) { + if (source.flags & 8388608) { return; } - for (var i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - var inferences = context.inferences[i]; + for (var i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + var inferences = typeInferences[i]; if (!inferences.isFixed) { var candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : @@ -24722,7 +28011,7 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -24730,7 +28019,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -24738,27 +28027,27 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (target.flags & 196608) { var targetTypes = target.types; - var typeParameterCount = 0; - var typeParameter = void 0; + var typeVariableCount = 0; + var typeVariable = void 0; for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & 540672 && ts.contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 196608) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -24767,7 +28056,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 32768) { if (isInProcess(source, target)) { return; } @@ -24786,18 +28075,41 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var index = ts.indexOf(typeVariables, constraintType.type); + if (index >= 0 && !typeInferences[index].isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -24863,7 +28175,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -24871,7 +28183,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; @@ -24883,7 +28195,7 @@ var ts; var widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; @@ -24924,10 +28236,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 158: + case 160: return true; - case 69: - case 139: + case 70: + case 141: node = node.parent; continue; default: @@ -24937,14 +28249,14 @@ var ts; ts.Debug.fail("should not get here"); } function getFlowCacheKey(node) { - if (node.kind === 69) { + if (node.kind === 70) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - if (node.kind === 97) { + if (node.kind === 98) { return "0"; } - if (node.kind === 172) { + if (node.kind === 177) { var key = getFlowCacheKey(node.expression); return key && key + "." + node.name.text; } @@ -24952,31 +28264,31 @@ var ts; } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { - case 69: - case 97: + case 70: + case 98: return node; - case 172: + case 177: return getLeftmostIdentifierOrThis(node.expression); } return undefined; } function isMatchingReference(source, target) { switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && + case 70: + return target.kind === 70 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 223 || target.kind === 174) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && + case 98: + return target.kind === 98; + case 177: + return target.kind === 177 && source.name.text === target.name.text && isMatchingReference(source.expression, target.expression); } return false; } function containsMatchingReference(source, target) { - while (source.kind === 172) { + while (source.kind === 177) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -24985,33 +28297,26 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && + return target.kind === 177 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { + if (expr.kind === 70) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 172) { + if (expr.kind === 177) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.text); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25030,7 +28335,7 @@ var ts; } } } - if (callExpression.expression.kind === 172 && + if (callExpression.expression.kind === 177 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -25044,7 +28349,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 65536)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -25107,7 +28412,7 @@ var ts; type === falseType ? 3030404 : 1981828 : type === falseType ? 3145092 : 4193668; } - if (flags & 2588672) { + if (flags & 32768) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 : 8376288 : strictNullChecks ? 6166480 : 8378320; @@ -25125,7 +28430,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type); return getTypeFacts(constraint || emptyObjectType); } - if (flags & 1572864) { + if (flags & 196608) { return getTypeFactsOfTypes(type.types); } return 8388607; @@ -25135,13 +28440,13 @@ var ts; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { - var defaultType = checkExpression(defaultExpression); + var defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, 131072), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { - var text = getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || @@ -25152,19 +28457,19 @@ var ts; checkIteratedTypeOrElementType(type, undefined, false) || unknownType; } - function getTypeOfDestructuredSpreadElement(type) { + function getTypeOfDestructuredSpreadExpression(type) { return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 170 || node.parent.kind === 253 ? + return node.parent.kind === 175 || node.parent.kind === 257 ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node) { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node) { return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); @@ -25175,21 +28480,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 207: + case 212: return stringType; - case 208: + case 213: return checkRightHandSideOfForOf(parent.expression) || unknownType; - case 187: + case 192: return getAssignedTypeOfBinaryExpression(parent); - case 181: + case 186: return undefinedType; - case 170: + case 175: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 191: - return getAssignedTypeOfSpreadElement(parent); - case 253: + case 196: + return getAssignedTypeOfSpreadExpression(parent); + case 257: return getAssignedTypeOfPropertyAssignment(parent); - case 254: + case 258: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -25197,56 +28502,69 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 167 ? + var type = pattern.kind === 172 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { var links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 207) { + if (node.parent.parent.kind === 212) { return stringType; } - if (node.parent.parent.kind === 208) { + if (node.parent.parent.kind === 213) { return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 218 ? + return node.kind === 223 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? + return node.kind === 223 || node.kind === 174 ? getInitialType(node) : getAssignedType(node); } + function isEmptyArrayAssignment(node) { + return node.kind === 223 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 174 && node.parent.kind === 192 && + isEmptyArrayLiteral(node.parent.right); + } function getReferenceCandidate(node) { switch (node.kind) { - case 178: + case 183: return getReferenceCandidate(node.expression); - case 187: + case 192: switch (node.operatorToken.kind) { - case 56: + case 57: return getReferenceCandidate(node.left); - case 24: + case 25: return getReferenceCandidate(node.right); } } return node; } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 183 || + parent.kind === 192 && parent.operatorToken.kind === 57 && parent.left === node || + parent.kind === 192 && parent.operatorToken.kind === 25 && parent.right === node ? + getReferenceRoot(parent) : node; + } function getTypeOfSwitchClause(clause) { - if (clause.kind === 249) { - var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + if (clause.kind === 253) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -25260,13 +28578,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { + if (source.flags & 65536) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -25280,14 +28598,34 @@ var ts; } return containsType(target.types, source); } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } function filterType(type, f) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 65536 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25297,22 +28635,105 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 177 && (parent.name.text === "length" || + parent.parent.kind === 179 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 178 && + parent.expression === root && + parent.parent.kind === 192 && + parent.parent.operatorToken.kind === 57 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 201 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 512) { + if (flow.flags & 1024) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -25342,18 +28763,25 @@ var ts; getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && container !== flowContainer && reference.kind !== 177) { flow = container.flowNode; continue; } type = initialType; } else { - type = declaredType; + type = convertAutoToAny(declaredType); } - if (flow.flags & 512) { + if (flow.flags & 1024) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -25364,27 +28792,70 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; } return undefined; } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 179 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 179) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (!(type.flags & 8192)) { - var assumeTrue = (flow.flags & 32) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & 8192 && isIncomplete(flowType)) { - type = silentNeverType; - } + if (type.flags & 8192) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); @@ -25419,7 +28890,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); @@ -25431,8 +28902,8 @@ var ts; return cache[key]; } for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); } } var antecedentTypes = []; @@ -25463,15 +28934,15 @@ var ts; break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, true); } return cache[key] = result; } function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && + return expr.kind === 177 && + declaredType.flags & 65536 && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(declaredType, expr.name.text); } @@ -25495,19 +28966,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 56: + case 57: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 30: case 31: case 32: case 33: + case 34: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { + if (left_1.kind === 187 && right_1.kind === 9) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { + if (right_1.kind === 187 && left_1.kind === 9) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -25526,9 +28997,9 @@ var ts; return declaredType; } break; - case 91: + case 92: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 24: + case 25: return narrowType(type, expr.right, assumeTrue); } return type; @@ -25537,28 +29008,28 @@ var ts; if (type.flags & 1) { return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); + var valueType = getTypeOfExpression(value); if (valueType.flags & 6144) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 30 || operator === 31; + var doubleEquals = operator === 31 || operator === 32; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - value.kind === 93 ? + value.kind === 94 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 33281) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25574,10 +29045,10 @@ var ts; } return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { + if (assumeTrue && !(type.flags & 65536)) { var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; @@ -25596,7 +29067,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25611,7 +29083,7 @@ var ts; } return type; } - var rightType = checkExpression(expr.right); + var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -25628,10 +29100,10 @@ var ts; } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (getObjectFlags(rightType) & 2) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (getObjectFlags(rightType) & 16) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -25639,16 +29111,16 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type, candidate, assumeTrue) { + function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); if (!(assignableType.flags & 8192)) { return assignableType; } @@ -25660,7 +29132,7 @@ var ts; getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } var signature = getResolvedSignature(callExpression); @@ -25675,7 +29147,7 @@ var ts; var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -25683,12 +29155,12 @@ var ts; } } else { - var invokedExpression = skipParenthesizedNodes(callExpression.expression); - if (invokedExpression.kind === 173 || invokedExpression.kind === 172) { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 178 || invokedExpression.kind === 177) { var accessExpression = invokedExpression; - var possibleReference = skipParenthesizedNodes(accessExpression.expression); + var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -25699,18 +29171,18 @@ var ts; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 174: + case 179: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 178: + case 183: return narrowType(type, expr.expression, assumeTrue); - case 187: + case 192: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 185: - if (expr.operator === 49) { + case 190: + if (expr.operator === 50) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -25719,12 +29191,12 @@ var ts; } } function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 69) { + if (location.kind === 70) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { - var type = checkExpression(location); + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -25732,19 +29204,13 @@ var ts; } return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression) { - while (expression.kind === 178) { - expression = expression.expression; - } - return expression; - } function getControlFlowContainer(node) { while (true) { node = node.parent; if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + node.kind === 231 || + node.kind === 261 || + node.kind === 147) { return node; } } @@ -25772,10 +29238,10 @@ var ts; } } function markParameterAssignments(node) { - if (node.kind === 69) { + if (node.kind === 70) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144) { symbol.isAssigned = true; } } @@ -25784,21 +29250,28 @@ var ts; ts.forEachChild(node, markParameterAssignments); } } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 180) { + if (container.kind === 185) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - if (node.flags & 262144) { + if (node.flags & 16384) { getNodeLinks(container).flags |= 8192; } + return getTypeOfSymbol(symbol); } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); @@ -25806,8 +29279,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); if (localOrExportSymbol.flags & 32) { var declaration_1 = localOrExportSymbol.valueDeclaration; - if (languageVersion === 2 - && declaration_1.kind === 221 + if (declaration_1.kind === 226 && ts.nodeIsDecorated(declaration_1)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -25819,11 +29291,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration_1.kind === 192) { + else if (declaration_1.kind === 197) { var container = ts.getThisContainer(node, false); while (container !== undefined) { if (container.parent === declaration_1) { - if (container.kind === 145 && ts.hasModifier(container, 32)) { + if (container.kind === 147 && ts.hasModifier(container, 32)) { getNodeLinks(declaration_1).flags |= 8388608; getNodeLinks(node).flags |= 16777216; } @@ -25838,26 +29310,47 @@ var ts; checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var isParameter = ts.getRootDeclaration(declaration).kind === 144; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === 184 || + flowContainer.kind === 185 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node, threshold) { var current = node; @@ -25872,7 +29365,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 252) { + symbol.valueDeclaration.parent.kind === 256) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -25890,8 +29383,8 @@ var ts; if (usedInFunction) { getNodeLinks(current).flags |= 65536; } - if (container.kind === 206 && - ts.getAncestor(symbol.valueDeclaration, 219).parent === container && + if (container.kind === 211 && + ts.getAncestor(symbol.valueDeclaration, 224).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152; } @@ -25903,16 +29396,16 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 178) { + while (current.parent.kind === 183) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 185 || current.parent.kind === 186)) { + else if ((current.parent.kind === 190 || current.parent.kind === 191)) { var expr = current.parent; - isAssigned = expr.operator === 41 || expr.operator === 42; + isAssigned = expr.operator === 42 || expr.operator === 43; } if (!isAssigned) { return false; @@ -25929,7 +29422,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 145 || container.kind === 148) { + if (container.kind === 147 || container.kind === 150) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -25938,7 +29431,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -25960,42 +29453,45 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 148) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + if (container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 180) { + if (container.kind === 185) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 225: + case 230: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 224: + case 229: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 148: + case 150: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 145: - case 144: + case 147: + case 146: if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 140: + case 142: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -26003,8 +29499,8 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { - if (container.kind === 179 && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 184 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { var className = container.parent @@ -26016,7 +29512,7 @@ var ts; return getInferredClassType(classSymbol); } } - var thisType = getThisTypeOfDeclaration(container); + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -26038,28 +29534,28 @@ var ts; return anyType; } function getTypeForThisExpressionFromJSDoc(node) { - var typeTag = ts.getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 269) { - var jsDocFunctionType = typeTag.typeExpression.type; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 272) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 274) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 142) { + if (n.kind === 144) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 174 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 179 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 180) { + while (container && container.kind === 185) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -26068,16 +29564,16 @@ var ts; var nodeCheckFlag = 0; if (!canUseSuperExpression) { var current = node; - while (current && current !== container && current.kind !== 140) { + while (current && current !== container && current.kind !== 142) { current = current.parent; } - if (current && current.kind === 140) { + if (current && current.kind === 142) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 171)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -26085,6 +29581,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -26092,7 +29591,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (container.kind === 149 && ts.getModifierFlags(container) & 256) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -26103,7 +29602,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 171) { + if (container.parent.kind === 176) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -26121,7 +29620,7 @@ var ts; } return unknownType; } - if (container.kind === 148 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 150 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -26133,35 +29632,38 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 148; + return container.kind === 150; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 171) { + if (ts.isClassLike(container.parent) || container.parent.kind === 176) { if (ts.getModifierFlags(container) & 32) { - return container.kind === 147 || - container.kind === 146 || - container.kind === 149 || - container.kind === 150; + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152; } else { - return container.kind === 147 || + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152 || + container.kind === 147 || container.kind === 146 || - container.kind === 149 || - container.kind === 150 || - container.kind === 145 || - container.kind === 144 || - container.kind === 148; + container.kind === 150; } } } return false; } } - function getContextualThisParameter(func) { - if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { + function getContextualThisParameterType(func) { + if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } return undefined; @@ -26211,7 +29713,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 142) { + if (declaration.kind === 144) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -26222,11 +29724,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_21 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_21)) { + var text = ts.getTextOfPropertyName(name_21); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26263,7 +29765,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 142 && node.parent.initializer === node) { + if (node.parent.kind === 144 && node.parent.initializer === node) { return true; } node = node.parent; @@ -26272,8 +29774,8 @@ var ts; } function getContextualReturnType(functionDecl) { if (functionDecl.type || - functionDecl.kind === 148 || - functionDecl.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 150))) { + functionDecl.kind === 150 || + functionDecl.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); @@ -26292,7 +29794,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 176) { + if (template.parent.kind === 181) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -26300,22 +29802,22 @@ var ts; function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; - if (operator >= 56 && operator <= 68) { + if (operator >= 57 && operator <= 69) { if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { return undefined; } if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } - else if (operator === 52) { + else if (operator === 53) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } - else if (operator === 51 || operator === 24) { + else if (operator === 52 || operator === 25) { if (node === binaryExpression.right) { return getContextualType(binaryExpression); } @@ -26323,14 +29825,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 65536)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -26348,7 +29850,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -26356,7 +29858,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -26400,13 +29902,13 @@ var ts; var kind = attribute.kind; var jsxElement = attribute.parent; var attrsType = getJsxElementAttributesType(jsxElement); - if (attribute.kind === 246) { + if (attribute.kind === 250) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - else if (attribute.kind === 247) { + else if (attribute.kind === 251) { return attrsType; } ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); @@ -26424,56 +29926,70 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 169: - return getContextualTypeForInitializerExpression(node); - case 180: - case 211: - return getContextualTypeForReturnExpression(node); - case 190: - return getContextualTypeForYieldOperand(parent); + case 147: + case 146: case 174: - case 175: - return getContextualTypeForArgument(parent, node); - case 177: + return getContextualTypeForInitializerExpression(node); + case 185: + case 216: + return getContextualTypeForReturnExpression(node); case 195: + return getContextualTypeForYieldOperand(parent); + case 179: + case 180: + return getContextualTypeForArgument(parent, node); + case 182: + case 200: return getTypeFromTypeNode(parent.type); - case 187: + case 192: return getContextualTypeForBinaryOperand(node); - case 253: - case 254: + case 257: + case 258: return getContextualTypeForObjectLiteralElement(parent); - case 170: + case 175: return getContextualTypeForElementExpression(node); - case 188: + case 193: return getContextualTypeForConditionalOperand(node); - case 197: - ts.Debug.assert(parent.parent.kind === 189); + case 202: + ts.Debug.assert(parent.parent.kind === 194); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 178: + case 183: return getContextualType(parent); - case 248: + case 252: return getContextualType(parent); - case 246: - case 247: + case 250: + case 251: return getContextualTypeForJsxAttribute(parent); } return undefined; } - function getNonGenericSignature(type) { + function getNonGenericSignature(type, node) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 179 || node.kind === 180; + return node.kind === 184 || node.kind === 185; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -26486,19 +30002,19 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 524288)) { - return getNonGenericSignature(type); + if (!(type.flags & 65536)) { + return getNonGenericSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; - var signature = getNonGenericSignature(current); + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { signatureList = [signature]; @@ -26522,13 +30038,13 @@ var ts; function isInferentialContext(mapper) { return mapper && mapper.context; } - function checkSpreadElementExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node, contextualMapper) { + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 169 && !!node.initializer) || - (node.kind === 187 && node.operatorToken.kind === 56); + return (node.kind === 174 && !!node.initializer) || + (node.kind === 192 && node.operatorToken.kind === 57); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -26537,7 +30053,7 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 191) { + if (inDestructuringPattern && e.kind === 196) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -26549,7 +30065,7 @@ var ts; var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 191; + hasSpreadElement = hasSpreadElement || e.kind === 196; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -26560,7 +30076,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 168 || pattern.kind === 170)) { + if (pattern && (pattern.kind === 173 || pattern.kind === 175)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -26568,7 +30084,7 @@ var ts; elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 193) { + if (patternElement.kind !== 198) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -26585,7 +30101,7 @@ var ts; strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { - return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 142 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); @@ -26603,7 +30119,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -26612,10 +30128,10 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(node, properties, kind) { + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(node.properties[i].name)) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -26627,35 +30143,38 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createMap(); var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 167 || contextualType.pattern.kind === 171); + (contextualType.pattern.kind === 172 || contextualType.pattern.kind === 176); var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var memberDecl = _a[_i]; + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; var member = memberDecl.symbol; - if (memberDecl.kind === 253 || - memberDecl.kind === 254 || + if (memberDecl.kind === 257 || + memberDecl.kind === 258 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 253) { + if (memberDecl.kind === 257) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 147) { + else if (memberDecl.kind === 149) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 254); + ts.Debug.assert(memberDecl.kind === 258); type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 253 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 254 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 257 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 258 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } @@ -26663,12 +30182,12 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -26681,8 +30200,29 @@ var ts; prop.target = member; member = prop; } + else if (memberDecl.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + propertiesArray = []; + propertiesTable = ts.createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, false); + offset = i + 1; + continue; + } else { - ts.Debug.assert(memberDecl.kind === 149 || memberDecl.kind === 150); + ts.Debug.assert(memberDecl.kind === 151 || memberDecl.kind === 152); checkAccessorDeclaration(memberDecl); } if (ts.hasDynamicName(memberDecl)) { @@ -26699,8 +30239,8 @@ var ts; propertiesArray.push(member); } if (contextualTypeHasPattern) { - for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { - var prop = _c[_b]; + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); @@ -26710,15 +30250,40 @@ var ts; } } } - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); - if (inDestructuringPattern) { - result.pattern = node; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - return result; + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); @@ -26735,13 +30300,13 @@ var ts; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 248: + case 252: checkJsxExpression(child); break; - case 241: + case 246: checkJsxElement(child); break; - case 242: + case 247: checkJsxSelfClosingElement(child); break; } @@ -26752,7 +30317,7 @@ var ts; return name.indexOf("-") < 0; } function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 172 || tagName.kind === 97) { + if (tagName.kind === 177 || tagName.kind === 98) { return false; } else { @@ -26768,7 +30333,7 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); if (attributeType) { correspondingPropType = attributeType; } @@ -26794,6 +30359,9 @@ var ts; return exprType; } function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + if (compilerOptions.jsx === 2) { + checkExternalEmitHelpers(node, 2); + } var type = checkExpression(node.expression); var props = getPropertiesOfType(type); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { @@ -26843,7 +30411,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 65536)); if (isTypeAny(valueType)) { return anyType; } @@ -26855,7 +30423,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -26882,9 +30450,9 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 65536) { var types = elemType.types; - return getUnionType(types.map(function (type) { + return getUnionType(ts.map(types, function (type) { return getResolvedJsxType(node, type, elemClassType); }), true); } @@ -26944,7 +30512,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 65536) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -27021,20 +30589,23 @@ var ts; checkGrammarJsxElement(node); checkJsxPreconditions(node); var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactNamespace = getJsxNamespace(); var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + reactSym.isReferenced = true; + if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 246) { + if (node.attributes[i].kind === 250) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 247); + ts.Debug.assert(node.attributes[i].kind === 251); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -27060,7 +30631,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 145; + return s.valueDeclaration ? s.valueDeclaration.kind : 147; } function getDeclarationModifierFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; @@ -27071,11 +30642,11 @@ var ts; function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); - var errorNode = node.kind === 172 || node.kind === 218 ? + var errorNode = node.kind === 177 || node.kind === 223 ? node.name : node.right; - if (left.kind === 95) { - if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 147) { + if (left.kind === 96) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 149) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -27095,7 +30666,7 @@ var ts; } return true; } - if (left.kind === 95) { + if (left.kind === 96) { return true; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { @@ -27109,10 +30680,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -27138,6 +30709,33 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (prop.flags & 16777216) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -27150,48 +30748,33 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & 32) { checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (node.kind !== 172 || ts.isAssignmentTarget(node) || + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 177 || assignmentKind === 1 || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 65536)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 524288 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + var flowType = getFlowTypeOfReference(node, propType, true, undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 172 + var left = node.kind === 177 ? node.expression : node.left; var type = checkExpression(left); @@ -27205,13 +30788,13 @@ var ts; } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 219) { + if (initializer.kind === 224) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 69) { + else if (initializer.kind === 70) { return getResolvedSymbol(initializer); } return undefined; @@ -27220,17 +30803,17 @@ var ts; return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); } function isForInVariableForNumericPropertyNames(expr) { - var e = skipParenthesizedNodes(expr); - if (e.kind === 69) { + var e = ts.skipParentheses(expr); + if (e.kind === 70) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 207 && + if (node.kind === 212 && child === node.statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression(node.expression))) { + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { return true; } child = node; @@ -27241,9 +30824,11 @@ var ts; return false; } function checkIndexedAccess(node) { - if (!node.argumentExpression) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 175 && node.parent.expression === node) { + if (node.parent.kind === 180 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -27253,71 +30838,17 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } + return unknownType; } - var objectType = getApparentType(checkNonNullExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - var isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== 9)) { - error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); - 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_18, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - var numberIndexInfo = getIndexInfoOfType(objectType, 1); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - var stringIndexInfo = getIndexInfoOfType(objectType, 0); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, 1) ? - ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - return anyType; - } - error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - return unknownType; - } - function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { - if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { - return indexArgumentExpression.text; - } - if (indexArgumentExpression.kind === 173 || indexArgumentExpression.kind === 172) { - var value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, false)) { - var rightHandSideName = indexArgumentExpression.name.text; - return ts.getPropertyNameForKnownSymbolName(rightHandSideName); - } - return undefined; + return getIndexedAccessType(objectType, indexType, node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { @@ -27350,10 +30881,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 176) { + if (node.kind === 181) { checkExpression(node.template); } - else if (node.kind !== 143) { + else if (node.kind !== 145) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -27375,19 +30906,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_8 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_8 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_8; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_8; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -27404,7 +30935,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 191) { + if (arg && arg.kind === 196) { return i; } } @@ -27417,11 +30948,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 176) { + if (node.kind === 181) { var tagExpression = node; argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 189) { + if (tagExpression.template.kind === 194) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -27429,11 +30960,11 @@ var ts; } else { var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 11); + ts.Debug.assert(templateLiteral.kind === 12); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 143) { + else if (node.kind === 145) { isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); @@ -27441,7 +30972,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 175); + ts.Debug.assert(callExpression.kind === 180); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -27464,7 +30995,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -27476,7 +31007,7 @@ var ts; function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -27495,19 +31026,19 @@ var ts; if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } if (excludeArgument) { @@ -27515,7 +31046,7 @@ var ts; if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -27547,7 +31078,7 @@ var ts; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 175) { + if (thisType && thisType !== voidType && node.kind !== 180) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -27560,9 +31091,9 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } @@ -27575,28 +31106,28 @@ var ts; return true; } function getThisArgumentOfCall(node) { - if (node.kind === 174) { + if (node.kind === 179) { var callee = node.expression; - if (callee.kind === 172) { + if (callee.kind === 177) { return callee.expression; } - else if (callee.kind === 173) { + else if (callee.kind === 178) { return callee.expression; } } } function getEffectiveCallArguments(node) { var args; - if (node.kind === 176) { + if (node.kind === 181) { var template = node.template; args = [undefined]; - if (template.kind === 189) { + if (template.kind === 194) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 143) { + else if (node.kind === 145) { return undefined; } else { @@ -27605,21 +31136,21 @@ var ts; return args; } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 143) { + if (node.kind === 145) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return 1; - case 145: - return 2; case 147: + return 2; case 149: - case 150: + case 151: + case 152: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 142: + case 144: return 3; } } @@ -27628,48 +31159,48 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { return anyType; } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { var element = node; switch (element.name.kind) { - case 69: + case 70: case 8: case 9: return getLiteralTypeForText(32, element.name.text); - case 140: + case 142: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { return nameType; @@ -27686,20 +31217,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { return numberType; } - if (node.kind === 145) { + if (node.kind === 147) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 147 || - node.kind === 149 || - node.kind === 150) { + if (node.kind === 149 || + node.kind === 151 || + node.kind === 152) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -27719,27 +31250,27 @@ var ts; ts.Debug.fail("Decorators should not have a fourth synthetic argument."); return unknownType; } - function getEffectiveArgumentType(node, argIndex, arg) { - if (node.kind === 143) { + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 145) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return getGlobalTemplateStringsArrayType(); } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 143 || - (argIndex === 0 && node.kind === 176)) { + if (node.kind === 145 || + (argIndex === 0 && node.kind === 181)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 143) { + if (node.kind === 145) { return node.expression; } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return node.template; } else { @@ -27747,12 +31278,12 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 176; - var isDecorator = node.kind === 143; + var isTaggedTemplate = node.kind === 181; + var isDecorator = node.kind === 145; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; - if (node.expression.kind !== 95) { + if (node.expression.kind !== 96) { ts.forEach(typeArguments, checkSourceElement); } } @@ -27778,7 +31309,7 @@ var ts; var candidateForTypeArgumentError; var resultOfFailedInference; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 174 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -27797,7 +31328,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -27818,7 +31349,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -27850,7 +31381,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -27893,7 +31424,7 @@ var ts; } } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); @@ -27939,7 +31470,7 @@ var ts; return true; } if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { + if (funcType.flags & 65536) { return false; } return isTypeAssignableTo(funcType, globalFunctionType); @@ -28009,12 +31540,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -28046,16 +31578,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 142: + case 144: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 145: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 147: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 149: - case 150: + case 151: + case 152: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -28082,13 +31614,13 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 174: + case 179: return resolveCallExpression(node, candidatesOutArray); - case 175: + case 180: return resolveNewExpression(node, candidatesOutArray); - case 176: + case 181: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 143: + case 145: return resolveDecorator(node, candidatesOutArray); } ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); @@ -28117,17 +31649,17 @@ var ts; function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { return voidType; } - if (node.kind === 175) { + if (node.kind === 180) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 148 && - declaration.kind !== 152 && - declaration.kind !== 157 && + declaration.kind !== 150 && + declaration.kind !== 154 && + declaration.kind !== 159 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 69 ? + var funcSymbol = node.expression.kind === 70 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { @@ -28139,11 +31671,33 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, true)) { + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 8388608) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 225 + : resolvedRequire.flags & 3 + ? 223 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } function checkTaggedTemplateExpression(node) { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -28179,21 +31733,36 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } function assignBindingElementTypes(node) { @@ -28201,7 +31770,7 @@ var ts; for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 69) { + if (element.name.kind === 70) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } assignBindingElementTypes(element); @@ -28214,14 +31783,14 @@ var ts; if (!links.type) { links.type = instantiateType(contextualType, mapper); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 167 || - parameter.valueDeclaration.name.kind === 168)) { + (parameter.valueDeclaration.name.kind === 172 || + parameter.valueDeclaration.name.kind === 173)) { links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); } assignBindingElementTypes(parameter.valueDeclaration); } else if (isInferentialContext(mapper)) { - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } function getReturnTypeFromJSDocComment(func) { @@ -28242,7 +31811,7 @@ var ts; 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); + error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } return promiseType; @@ -28254,7 +31823,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 199) { + if (func.body.kind !== 204) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -28290,7 +31859,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28316,7 +31887,7 @@ var ts; if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(node.expression); + var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -28324,14 +31895,14 @@ var ts; if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + if (lastStatement && lastStatement.kind === 218 && isExhaustiveSwitchStatement(lastStatement)) { return false; } return true; @@ -28360,7 +31931,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 179 || func.kind === 180)) { + func.kind === 184 || func.kind === 185)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -28377,7 +31948,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; @@ -28404,9 +31975,9 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 179) { + if (!hasGrammarError && node.kind === 184) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -28440,14 +32011,14 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 149) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); if (!node.asteriskToken) { @@ -28457,7 +32028,7 @@ var ts; if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 199) { + if (node.body.kind === 204) { checkSourceElement(node.body); } else { @@ -28492,10 +32063,10 @@ var ts; function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 172 || expr.kind === 173) && - expr.expression.kind === 97) { + (expr.kind === 177 || expr.kind === 178) && + expr.expression.kind === 98) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 148)) + if (!(func && func.kind === 150)) return true; return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } @@ -28504,44 +32075,24 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 172 || expr.kind === 173) { - var node = skipParenthesizedNodes(expr.expression); - if (node.kind === 69) { + if (expr.kind === 177 || expr.kind === 178) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 70) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 8388608) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 232; + return declaration && declaration.kind === 237; } } } return false; } - function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { - var node = skipParenthesizedNodes(expr); - if (node.kind !== 69 && node.kind !== 172 && node.kind !== 173) { + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipParentheses(expr); + if (node.kind !== 70 && node.kind !== 177 && node.kind !== 178) { error(expr, invalidReferenceMessage); return false; } - var links = getNodeLinks(node); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - if (node.kind === 69 && !(symbol.flags & 3)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === 173) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } function checkDeleteExpression(node) { @@ -28558,7 +32109,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 262144)) { + if (!(node.flags & 16384)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -28573,27 +32124,27 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 36 && node.operand.kind === 8) { + if (node.operator === 37 && node.operand.kind === 8) { return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); } switch (node.operator) { - case 35: case 36: - case 50: + case 37: + case 51: if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 49: + case 50: var facts = getTypeFacts(operandType) & (1048576 | 2097152); return facts === 1048576 ? falseType : facts === 2097152 ? trueType : booleanType; - case 41: case 42: + case 43: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -28606,7 +32157,7 @@ var ts; } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -28614,10 +32165,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -28629,20 +32180,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { - var t = types_16[_a]; + for (var _a = 0, types_17 = types; _a < types_17.length; _a++) { + var t = types_17[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -28651,7 +32202,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -28672,39 +32223,39 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var p = properties_4[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { - if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 257 || property.kind === 258) { + var name_22 = property.name; + if (name_22.kind === 142) { + checkComputedPropertyName(name_22); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_22)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = ts.getTextOfPropertyName(name_22); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || getIndexTypeOfType(objectLiteralType, 0); if (type) { - if (property.kind === 254) { + if (property.kind === 258) { return checkDestructuringAssignment(property, type); } else { @@ -28712,9 +32263,22 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_22, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_22)); } } + else if (property.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, ts.Diagnostics.Property_assignment_expected); } @@ -28730,8 +32294,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 193) { - if (element.kind !== 191) { + if (element.kind !== 198) { + if (element.kind !== 196) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -28753,11 +32317,11 @@ var ts; } else { if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { var restExpression = element.expression; - if (restExpression.kind === 187 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 192 && restExpression.operatorToken.kind === 57) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -28770,7 +32334,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 254) { + if (exprOrAssignment.kind === 258) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && @@ -28784,21 +32348,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 187 && target.operatorToken.kind === 56) { + if (target.kind === 192 && target.operatorToken.kind === 57) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 171) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + if (target.kind === 176) { + return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 170) { + if (target.kind === 175) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + var error = target.parent.kind === 259 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); } return sourceType; @@ -28806,49 +32373,49 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 69: + case 70: case 9: - case 10: - case 176: - case 189: case 11: + case 181: + case 194: + case 12: case 8: - case 99: - case 84: - case 93: - case 135: - case 179: - case 192: - case 180: - case 170: - case 171: - case 182: - case 196: - case 242: - case 241: + case 100: + case 85: + case 94: + case 137: + case 184: + case 197: + case 185: + case 175: + case 176: + case 187: + case 201: + case 247: + case 246: return true; - case 188: + case 193: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 187: + case 192: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 185: - case 186: + case 190: + case 191: switch (node.operator) { - case 49: - case 35: - case 36: case 50: + case 36: + case 37: + case 51: return true; } return false; - case 183: - case 177: - case 195: + case 188: + case 182: + case 200: default: return false; } @@ -28868,34 +32435,34 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 171 || left.kind === 170)) { + if (operator === 57 && (left.kind === 176 || left.kind === 175)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); var rightType = checkExpression(right, contextualMapper); switch (operator) { - case 37: case 38: - case 59: - case 60: case 39: + case 60: case 61: case 40: case 62: - case 36: - case 58: - case 43: + case 41: case 63: + case 37: + case 59: case 44: case 64: case 45: case 65: - case 47: - case 67: - case 48: - case 68: case 46: case 66: + case 48: + case 68: + case 49: + case 69: + case 47: + case 67: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -28919,8 +32486,8 @@ var ts; } } return numberType; - case 35: - case 57: + case 36: + case 58: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -28935,7 +32502,7 @@ var ts; resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -28949,24 +32516,26 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 57) { + if (operator === 58) { checkAssignmentOperator(resultType); } return resultType; - case 25: - case 27: + case 26: case 28: case 29: + case 30: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } } return booleanType; - case 30: case 31: case 32: case 33: + case 34: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -28977,22 +32546,22 @@ var ts; reportOperatorError(); } return booleanType; - case 91: + case 92: return checkInstanceOfExpression(left, right, leftType, rightType); - case 90: + case 91: return checkInExpression(left, right, leftType, rightType); - case 51: + case 52: return getTypeFacts(leftType) & 1048576 ? includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; - case 52: + case 53: return getTypeFacts(leftType) & 2097152 ? getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : leftType; - case 56: + case 57: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 24: + case 25: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -29010,23 +32579,22 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { + case 48: + case 68: + return 53; + case 49: + case 69: + return 34; case 47: case 67: return 52; - case 48: - case 68: - return 33; - case 46: - case 66: - return 51; default: return undefined; } } function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 56 && operator <= 68) { - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - if (ok) { + if (produceDiagnostics && operator >= 57 && operator <= 69) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { checkTypeAssignableTo(valueType, leftType, left, undefined); } } @@ -29052,7 +32620,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -29096,9 +32664,9 @@ var ts; return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); case 8: return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); - case 99: + case 100: return trueType; - case 84: + case 85: return falseType; } } @@ -29126,25 +32694,25 @@ var ts; return links.resolvedType; } function isTypeAssertion(node) { - node = skipParenthesizedNodes(node); - return node.kind === 177 || node.kind === 195; + node = ts.skipParentheses(node); + return node.kind === 182 || node.kind === 200; } function checkDeclarationInitializer(declaration) { var type = checkExpressionCached(declaration.initializer); return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, 480); + return maybeTypeOfKind(contextualType, (480 | 262144)); } return false; } @@ -29153,14 +32721,14 @@ var ts; return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -29181,9 +32749,19 @@ var ts; } return type; } + function getTypeOfExpression(node) { + if (node.kind === 179 && node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return checkExpression(node); + } function checkExpression(node, contextualMapper) { var type; - if (node.kind === 139) { + if (node.kind === 141) { type = checkQualifiedName(node); } else { @@ -29191,9 +32769,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 172 && node.parent.expression === node) || - (node.parent.kind === 173 && node.parent.expression === node) || - ((node.kind === 69 || node.kind === 139) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 177 && node.parent.expression === node) || + (node.parent.kind === 178 && node.parent.expression === node) || + ((node.kind === 70 || node.kind === 141) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -29202,79 +32780,79 @@ var ts; } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { - case 69: + case 70: return checkIdentifier(node); - case 97: + case 98: return checkThisExpression(node); - case 95: + case 96: return checkSuperExpression(node); - case 93: + case 94: return nullWideningType; case 9: case 8: - case 99: - case 84: + case 100: + case 85: return checkLiteralExpression(node); - case 189: + case 194: return checkTemplateExpression(node); - case 11: + case 12: return stringType; - case 10: + case 11: return globalRegExpType; - case 170: - return checkArrayLiteral(node, contextualMapper); - case 171: - return checkObjectLiteral(node, contextualMapper); - case 172: - return checkPropertyAccessExpression(node); - case 173: - return checkIndexedAccess(node); - case 174: case 175: - return checkCallExpression(node); + return checkArrayLiteral(node, contextualMapper); case 176: - return checkTaggedTemplateExpression(node); + return checkObjectLiteral(node, contextualMapper); + case 177: + return checkPropertyAccessExpression(node); case 178: - return checkExpression(node.expression, contextualMapper); - case 192: - return checkClassExpression(node); + return checkIndexedAccess(node); case 179: case 180: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 182: - return checkTypeOfExpression(node); - case 177: - case 195: - return checkAssertion(node); - case 196: - return checkNonNullAssertion(node); + return checkCallExpression(node); case 181: - return checkDeleteExpression(node); + return checkTaggedTemplateExpression(node); case 183: - return checkVoidExpression(node); + return checkExpression(node.expression, contextualMapper); + case 197: + return checkClassExpression(node); case 184: - return checkAwaitExpression(node); case 185: - return checkPrefixUnaryExpression(node); - case 186: - return checkPostfixUnaryExpression(node); + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 187: - return checkBinaryExpression(node, contextualMapper); + return checkTypeOfExpression(node); + case 182: + case 200: + return checkAssertion(node); + case 201: + return checkNonNullAssertion(node); + case 186: + return checkDeleteExpression(node); case 188: - return checkConditionalExpression(node, contextualMapper); - case 191: - return checkSpreadElementExpression(node, contextualMapper); - case 193: - return undefinedWideningType; + return checkVoidExpression(node); + case 189: + return checkAwaitExpression(node); case 190: + return checkPrefixUnaryExpression(node); + case 191: + return checkPostfixUnaryExpression(node); + case 192: + return checkBinaryExpression(node, contextualMapper); + case 193: + return checkConditionalExpression(node, contextualMapper); + case 196: + return checkSpreadExpression(node, contextualMapper); + case 198: + return undefinedWideningType; + case 195: return checkYieldExpression(node); - case 248: + case 252: return checkJsxExpression(node); - case 241: + case 246: return checkJsxElement(node); - case 242: + case 247: return checkJsxSelfClosingElement(node); - case 243: + case 248: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -29295,7 +32873,7 @@ var ts; var func = ts.getContainingFunction(node); if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); - if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 150 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -29306,7 +32884,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); } - if (func.kind === 148 || func.kind === 152 || func.kind === 157) { + if (func.kind === 150 || func.kind === 154 || func.kind === 159) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -29318,15 +32896,15 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 147 || - node.kind === 220 || - node.kind === 179; + return node.kind === 149 || + node.kind === 225 || + node.kind === 184; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 69 && + if (param.name.kind === 70 && param.name.text === parameter.text) { return i; } @@ -29361,9 +32939,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_23 = _a[_i].name; + if (ts.isBindingPattern(name_23) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_23, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29376,16 +32954,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 180: - case 151: - case 220: - case 179: - case 156: - case 147: - case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + case 185: + case 153: + case 225: + case 184: + case 158: + case 149: + case 148: + var parent_9 = node.parent; + if (node === parent_9.type) { + return parent_9; } } } @@ -29395,29 +32973,35 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_24 = element.name; + if (name_24.kind === 70 && + name_24.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_24.kind === 173 || + name_24.kind === 172) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_24, predicateVariableNode, predicateVariableName)) { return true; } } } } function checkSignatureDeclaration(node) { - if (node.kind === 153) { + if (node.kind === 155) { checkGrammarIndexSignature(node); } - else if (node.kind === 156 || node.kind === 220 || node.kind === 157 || - node.kind === 151 || node.kind === 148 || - node.kind === 152) { + else if (node.kind === 158 || node.kind === 225 || node.kind === 159 || + node.kind === 153 || node.kind === 150 || + node.kind === 154) { checkGrammarFunctionLikeDeclaration(node); } + if (ts.isAsyncFunctionLike(node) && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { @@ -29427,10 +33011,10 @@ var ts; checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 152: + case 154: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 151: + case 153: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -29461,7 +33045,7 @@ var ts; var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { @@ -29470,18 +33054,18 @@ var ts; } } else { - var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114; }); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 149: + case 151: addName(names, member.name, memberName, 1); break; - case 150: + case 152: addName(names, member.name, memberName, 2); break; - case 145: + case 147: addName(names, member.name, memberName, 3); break; } @@ -29507,12 +33091,12 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind == 144) { + if (member.kind == 146) { var memberName = void 0; switch (member.name.kind) { case 9: case 8: - case 69: + case 70: memberName = member.name.text; break; default: @@ -29529,7 +33113,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 222) { + if (node.kind === 227) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -29544,7 +33128,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 132: + case 134: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -29552,7 +33136,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 130: + case 132: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -29596,7 +33180,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29608,20 +33192,21 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function markThisReferencesAsErrors(n) { - if (n.kind === 97) { + if (n.kind === 98) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 179 && n.kind !== 220) { + else if (n.kind !== 184 && n.kind !== 225) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 145 && + return n.kind === 147 && !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29633,9 +33218,9 @@ var ts; if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -29658,18 +33243,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 149) { + if (node.kind === 151) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 149 ? 150 : 149; + var otherKind = node.kind === 151 ? 152 : 151; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { @@ -29683,11 +33268,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { + if (node.kind === 151) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - if (node.parent.kind !== 171) { + if (node.parent.kind !== 176) { checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); } @@ -29717,7 +33302,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -29768,14 +33353,25 @@ var ts; function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node) { + getTypeFromIndexedAccessTypeNode(node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } function isPrivateWithinAmbient(node) { return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 222 && - n.parent.kind !== 221 && - n.parent.kind !== 192 && + if (n.parent.kind !== 227 && + n.parent.kind !== 226 && + n.parent.kind !== 197 && ts.isInAmbientContext(n)) { if (!(flags & 2)) { flags |= 1; @@ -29852,7 +33448,7 @@ var ts; if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 147 || node.kind === 146) && + var reportError = (node.kind === 149 || node.kind === 148) && (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -29885,11 +33481,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 222 || node.parent.kind === 159 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 227 || node.parent.kind === 161 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 220 || node.kind === 147 || node.kind === 146 || node.kind === 148) { + if (node.kind === 225 || node.kind === 149 || node.kind === 148 || node.kind === 150) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -30000,20 +33596,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 222: + case 227: return 2097152; - case 225: + case 230: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 221: - case 224: - return 2097152 | 1048576; + case 226: case 229: - var result_2 = 0; + return 2097152 | 1048576; + case 234: + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; default: return 1048576; } @@ -30036,7 +33632,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (getObjectFlags(promise) & 4) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -30054,7 +33650,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -30073,7 +33669,7 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -30101,51 +33697,50 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - error(location, diagnostic, typeName); - return unknownType; - } function checkAsyncFunctionReturnType(node) { + var returnType = getTypeFromTypeNode(node.type); if (languageVersion >= 2) { - var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - return unknownType; + else { + markTypeNodeAsReferenced(node.type); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } } - var promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - return unknownType; - } - var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - var typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } - checkReturnTypeAnnotationAsExpression(node); - var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } - var promiseName = ts.getEntityNameFromTypeNode(node.type); - var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); - return unknownType; - } - return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } function checkDecorator(node) { var signature = getResolvedSignature(node); @@ -30157,22 +33752,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 221: + case 226: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 142: + case 144: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 145: + case 147: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 147: case 149: - case 150: + case 151: + case 152: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -30180,30 +33775,19 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } - function checkTypeNodeAsExpression(node) { - if (node && node.kind === 155) { - var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; - var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); - if (rootSymbol && rootSymbol.flags & 8388608) { - var aliasTarget = resolveAlias(rootSymbol); - if (aliasTarget.flags & 107455 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } + function markTypeNodeAsReferenced(node) { + var typeName = node && ts.getEntityNameFromTypeNode(node); + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 70 ? 793064 : 1920) | 8388608, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 8388608 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } - function checkTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkReturnTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkParameterTypeAnnotationsAsExpressions(node) { - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - checkTypeAnnotationAsExpression(parameter); - } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } function checkDecorators(node) { if (!node.decorators) { @@ -30215,23 +33799,37 @@ var ts; if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 144) { + checkExternalEmitHelpers(firstDecorator, 32); + } if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 221: + case 226: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; - case 147: case 149: - case 150: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + case 151: + case 152: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markTypeNodeAsReferenced(node.type); break; - case 145: - case 142: - checkTypeAnnotationAsExpression(node); + case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + case 144: + markTypeNodeAsReferenced(node.type); break; } } @@ -30250,7 +33848,7 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (node.name && node.name.kind === 140) { + if (node.name && node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { @@ -30292,43 +33890,43 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 256: - case 225: + case 261: + case 230: checkUnusedModuleMembers(node); break; - case 221: - case 192: + case 226: + case 197: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 222: + case 227: checkUnusedTypeParameters(node); break; - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: checkUnusedLocalsAndParameters(node); break; - case 148: - case 179: - case 220: - case 180: - case 147: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 151: + case 152: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 146: - case 151: - case 152: + case 148: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: checkUnusedTypeParameters(node); break; } @@ -30337,46 +33935,66 @@ var ts; } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function (key) { + if (node.parent.kind !== 227 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + var _loop_2 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144) { + var parameter = ts.getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !ts.parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); } } }; for (var key in node.locals) { - _loop_1(key); + _loop_2(key); } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; } - function parameterNameStartsWithUnderscore(parameter) { - return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 223 && + (declaration.parent.parent.kind === 212 || + declaration.parent.parent.kind === 213)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 70 && node.text.charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 147 || member.kind === 145) { + if (member.kind === 149 || member.kind === 147) { if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } - else if (member.kind === 148) { + else if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { @@ -30421,7 +34039,7 @@ var ts; } } function checkBlock(node) { - if (node.kind === 199) { + if (node.kind === 204) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -30443,19 +34061,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 145 || - node.kind === 144 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 146 || node.kind === 149 || - node.kind === 150) { + node.kind === 148 || + node.kind === 151 || + node.kind === 152) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 142 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 144 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -30469,7 +34087,7 @@ var ts; var current = node; while (current) { if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 69; + var isDeclaration_1 = node.kind !== 70; if (isDeclaration_1) { error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -30490,7 +34108,7 @@ var ts; return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_2 = node.kind !== 69; + var isDeclaration_2 = node.kind !== 70; if (isDeclaration_2) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -30500,26 +34118,29 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -30527,7 +34148,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 218 && !node.initializer) { + if (node.kind === 223 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -30537,25 +34158,25 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); - var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224); + var container = varDeclList.parent.kind === 205 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 199 && ts.isFunctionLike(container.parent) || - container.kind === 226 || - container.kind === 225 || - container.kind === 256); + (container.kind === 204 && ts.isFunctionLike(container.parent) || + container.kind === 231 || + container.kind === 230 || + container.kind === 261); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_25 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_25, name_25); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 142) { + if (ts.getRootDeclaration(node).kind !== 144) { return; } var func = ts.getContainingFunction(node); @@ -30564,10 +34185,10 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 172) { + if (n.kind === 177) { return visit(n.expression); } - else if (n.kind === 69) { + else if (n.kind === 70) { var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; @@ -30578,7 +34199,7 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 142) { + if (symbol.valueDeclaration.kind === 144) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -30587,7 +34208,7 @@ var ts; if (ts.isFunctionLike(current.parent)) { return; } - if (current.parent.kind === 145 && + if (current.parent.kind === 147 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; @@ -30603,51 +34224,58 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 169) { - if (node.propertyName && node.propertyName.kind === 140) { + if (node.kind === 174) { + if (node.parent.kind === 172 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 142) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_10 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_10); + var name_26 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_26)); + markPropertyAsReferenced(property); + if (parent_10.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 142 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 144 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -30659,9 +34287,9 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 145 && node.kind !== 144) { + if (node.kind !== 147 && node.kind !== 146) { checkExportsOnMergedDeclarations(node); - if (node.kind === 218 || node.kind === 169) { + if (node.kind === 223 || node.kind === 174) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -30671,8 +34299,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 142 && right.kind === 218) || - (left.kind === 218 && right.kind === 142)) { + if ((left.kind === 144 && right.kind === 223) || + (left.kind === 223 && right.kind === 144)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -30699,7 +34327,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 171) { + if (node.modifiers && node.parent.kind === 176) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -30718,7 +34346,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 201) { + if (node.thenStatement.kind === 206) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -30735,12 +34363,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 219) { + if (node.initializer && node.initializer.kind === 224) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -30758,18 +34386,18 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -30782,7 +34410,8 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 224) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -30792,18 +34421,17 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -30856,7 +34484,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -30882,7 +34510,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -30917,7 +34545,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -30926,10 +34554,14 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 65536) { + var arrayTypes = arrayOrStringType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 262178) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -30954,7 +34586,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 262178) { return stringType; } return getUnionType([arrayElementType, stringType], true); @@ -30965,7 +34597,7 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 150))); + return !!(node.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; @@ -30987,12 +34619,12 @@ var ts; if (func.asteriskToken) { return; } - if (func.kind === 150) { + if (func.kind === 152) { if (node.expression) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 148) { + else if (func.kind === 150) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -31010,27 +34642,33 @@ var ts; } } } - else if (func.kind !== 148 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 150 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 262144) { + if (node.flags & 16384) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 250 && !hasDuplicateDefaultClause) { + if (clause.kind === 254 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -31042,11 +34680,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 249) { + if (produceDiagnostics && clause.kind === 253) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { - checkTypeComparableTo(caseType, expressionType, caseClause.expression, undefined); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -31062,7 +34706,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 214 && current.label.text === node.label.text) { + if (current.kind === 219 && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -31088,22 +34732,20 @@ var ts; var catchClause = node.catchClause; if (catchClause) { if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== 69) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = catchClause.variableDeclaration.name.text; - var locals = catchClause.block.locals; - if (locals) { - var localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & 2) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + var blockLocals = catchClause.block.locals; + if (blockLocals) { + for (var caughtName in catchClause.locals) { + var blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -31125,7 +34767,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -31140,7 +34782,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -31156,13 +34798,13 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 140 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 142 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -31207,7 +34849,7 @@ var ts; var firstDecl; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 || declaration.kind === 222) { + if (declaration.kind === 226 || declaration.kind === 227) { if (!firstDecl) { firstDecl = declaration; } @@ -31253,6 +34895,9 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType_1 = baseTypes[0]; @@ -31270,7 +34915,9 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (baseType_1.symbol.valueDeclaration && + !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) && + baseType_1.symbol.valueDeclaration.kind === 226) { if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -31295,8 +34942,8 @@ var ts; if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = getObjectFlags(t) & 4 ? t.target : t; + if (getObjectFlags(declaredType) & 3) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -31318,7 +34965,7 @@ var ts; if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -31344,7 +34991,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 192) { + if (derivedClassDecl.kind === 197) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -31388,7 +35035,7 @@ var ts; } } function isAccessor(kind) { - return kind === 149 || kind === 150; + return kind === 151 || kind === 152; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -31426,8 +35073,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var prop = properties_5[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen[prop.name]; if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; @@ -31455,7 +35102,7 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(node, symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 222); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -31484,6 +35131,7 @@ var ts; function checkTypeAliasDeclaration(node) { checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } function computeEnumMemberValues(node) { @@ -31500,7 +35148,7 @@ var ts; error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - var text = getTextOfPropertyName(member.name); + var text = ts.getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -31550,18 +35198,18 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 185: + case 190: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; } switch (e.operator) { - case 35: return value_1; - case 36: return -value_1; - case 50: return ~value_1; + case 36: return value_1; + case 37: return -value_1; + case 51: return ~value_1; } return undefined; - case 187: + case 192: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -31571,37 +35219,37 @@ var ts; return undefined; } switch (e.operatorToken.kind) { - case 47: return left | right; - case 46: return left & right; - case 44: return left >> right; - case 45: return left >>> right; - case 43: return left << right; - case 48: return left ^ right; - case 37: return left * right; - case 39: return left / right; - case 35: return left + right; - case 36: return left - right; - case 40: return left % right; + case 48: return left | right; + case 47: return left & right; + case 45: return left >> right; + case 46: return left >>> right; + case 44: return left << right; + case 49: return left ^ right; + case 38: return left * right; + case 40: return left / right; + case 36: return left + right; + case 37: return left - right; + case 41: return left % right; } return undefined; case 8: return +e.text; - case 178: + case 183: return evalConstant(e.expression); - case 69: - case 173: - case 172: + case 70: + case 178: + case 177: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; var propertyName = void 0; - if (e.kind === 69) { + if (e.kind === 70) { enumType_1 = currentType; propertyName = e.text; } else { var expression = void 0; - if (e.kind === 173) { + if (e.kind === 178) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -31615,17 +35263,17 @@ var ts; } var current = expression; while (current) { - if (current.kind === 69) { + if (current.kind === 70) { break; } - else if (current.kind === 172) { + else if (current.kind === 177) { current = current.expression; } else { return undefined; } } - enumType_1 = checkExpression(expression); + enumType_1 = getTypeOfExpression(expression); if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { return undefined; } @@ -31678,7 +35326,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 224) { + if (declaration.kind !== 229) { return false; } var enumDeclaration = declaration; @@ -31701,8 +35349,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 221 || - (declaration.kind === 220 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 226 || + (declaration.kind === 225 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -31741,9 +35389,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31759,7 +35409,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 221); + var mergedClass = ts.getDeclarationOfKind(symbol, 226); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -31802,36 +35452,36 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 200: + case 205: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 235: - case 236: + case 240: + case 241: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 229: - case 230: + case 234: + case 235: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 169: - case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + case 174: + case 223: + var name_27 = node.name; + if (ts.isBindingPattern(name_27)) { + for (var _b = 0, _c = name_27.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } - case 221: - case 224: - case 220: - case 222: + case 226: + case 229: case 225: - case 223: + case 227: + case 230: + case 228: if (isGlobalAugmentation) { return; } @@ -31847,17 +35497,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 69: + case 70: return node; - case 139: + case 141: do { node = node.left; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; - case 172: + case 177: do { node = node.expression; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; } } @@ -31867,9 +35517,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { - error(moduleName, node.kind === 236 ? + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { + error(moduleName, node.kind === 241 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -31890,7 +35540,7 @@ var ts; (symbol.flags & 793064 ? 793064 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 238 ? + var message = node.kind === 243 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -31917,7 +35567,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { + if (importClause.namedBindings.kind === 237) { checkImportBinding(importClause.namedBindings); } else { @@ -31952,7 +35602,7 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { grammarErrorOnNode(node, ts.Diagnostics.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); } } @@ -31968,8 +35618,8 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -31982,9 +35632,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 261 || node.parent.kind === 231 || node.parent.kind === 230; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32003,15 +35655,15 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 256 ? node.parent : node.parent.parent; - if (container.kind === 225 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 261 ? node.parent : node.parent.parent; + if (container.kind === 230 && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { markExportAsReferenced(node); } else { @@ -32019,7 +35671,7 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES6) { + if (modulekind === ts.ModuleKind.ES2015) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { @@ -32071,7 +35723,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 225 && declaration.kind !== 149) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32081,118 +35734,123 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { + case 230: + case 226: + case 227: case 225: - case 221: - case 222: - case 220: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 141: + case 143: return checkTypeParameter(node); - case 142: - return checkParameter(node); - case 145: case 144: - return checkPropertyDeclaration(node); - case 156: - case 157: - case 151: - case 152: - return checkSignatureDeclaration(node); - case 153: - return checkSignatureDeclaration(node); + return checkParameter(node); case 147: case 146: - return checkMethodDeclaration(node); - case 148: - return checkConstructorDeclaration(node); - case 149: - case 150: - return checkAccessorDeclaration(node); - case 155: - return checkTypeReferenceNode(node); - case 154: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 158: - return checkTypeQuery(node); case 159: - return checkTypeLiteral(node); + case 153: + case 154: + return checkSignatureDeclaration(node); + case 155: + return checkSignatureDeclaration(node); + case 149: + case 148: + return checkMethodDeclaration(node); + case 150: + return checkConstructorDeclaration(node); + case 151: + case 152: + return checkAccessorDeclaration(node); + case 157: + return checkTypeReferenceNode(node); + case 156: + return checkTypePredicate(node); case 160: - return checkArrayType(node); + return checkTypeQuery(node); case 161: - return checkTupleType(node); + return checkTypeLiteral(node); case 162: + return checkArrayType(node); case 163: - return checkUnionOrIntersectionType(node); + return checkTupleType(node); case 164: + case 165: + return checkUnionOrIntersectionType(node); + case 166: + case 168: return checkSourceElement(node.type); - case 220: - return checkFunctionDeclaration(node); - case 199: - case 226: - return checkBlock(node); - case 200: - return checkVariableStatement(node); - case 202: - return checkExpressionStatement(node); - case 203: - return checkIfStatement(node); - case 204: - return checkDoStatement(node); - case 205: - return checkWhileStatement(node); - case 206: - return checkForStatement(node); - case 207: - return checkForInStatement(node); - case 208: - return checkForOfStatement(node); - case 209: - case 210: - return checkBreakOrContinueStatement(node); - case 211: - return checkReturnStatement(node); - case 212: - return checkWithStatement(node); - case 213: - return checkSwitchStatement(node); - case 214: - return checkLabeledStatement(node); - case 215: - return checkThrowStatement(node); - case 216: - return checkTryStatement(node); - case 218: - return checkVariableDeclaration(node); case 169: - return checkBindingElement(node); - case 221: - return checkClassDeclaration(node); - case 222: - return checkInterfaceDeclaration(node); - case 223: - return checkTypeAliasDeclaration(node); - case 224: - return checkEnumDeclaration(node); + return checkIndexedAccessType(node); + case 170: + return checkMappedType(node); case 225: - return checkModuleDeclaration(node); - case 230: - return checkImportDeclaration(node); - case 229: - return checkImportEqualsDeclaration(node); - case 236: - return checkExportDeclaration(node); - case 235: - return checkExportAssignment(node); - case 201: - checkGrammarStatementInAmbientContext(node); - return; + return checkFunctionDeclaration(node); + case 204: + case 231: + return checkBlock(node); + case 205: + return checkVariableStatement(node); + case 207: + return checkExpressionStatement(node); + case 208: + return checkIfStatement(node); + case 209: + return checkDoStatement(node); + case 210: + return checkWhileStatement(node); + case 211: + return checkForStatement(node); + case 212: + return checkForInStatement(node); + case 213: + return checkForOfStatement(node); + case 214: + case 215: + return checkBreakOrContinueStatement(node); + case 216: + return checkReturnStatement(node); case 217: + return checkWithStatement(node); + case 218: + return checkSwitchStatement(node); + case 219: + return checkLabeledStatement(node); + case 220: + return checkThrowStatement(node); + case 221: + return checkTryStatement(node); + case 223: + return checkVariableDeclaration(node); + case 174: + return checkBindingElement(node); + case 226: + return checkClassDeclaration(node); + case 227: + return checkInterfaceDeclaration(node); + case 228: + return checkTypeAliasDeclaration(node); + case 229: + return checkEnumDeclaration(node); + case 230: + return checkModuleDeclaration(node); + case 235: + return checkImportDeclaration(node); + case 234: + return checkImportEqualsDeclaration(node); + case 241: + return checkExportDeclaration(node); + case 240: + return checkExportAssignment(node); + case 206: checkGrammarStatementInAmbientContext(node); return; - case 239: + case 222: + checkGrammarStatementInAmbientContext(node); + return; + case 244: return checkMissingDeclaration(node); } } @@ -32205,17 +35863,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 179: - case 180: - case 147: - case 146: + case 184: + case 185: + case 149: + case 148: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 149: - case 150: + case 151: + case 152: checkAccessorDeferred(node); break; - case 192: + case 197: checkClassExpressionDeferred(node); break; } @@ -32269,8 +35927,19 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; } ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); @@ -32287,7 +35956,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 212 && node.parent.statement === node) { + if (node.parent.kind === 217 && node.parent.statement === node) { return true; } node = node.parent; @@ -32309,28 +35978,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 225: + case 230: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 224: + case 229: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 192: + case 197: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 221: - case 222: + case 226: + case 227: if (!(memberFlags & 32)) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; - case 179: + case 184: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -32363,33 +36032,33 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 69 && + return name.kind === 70 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 141: - case 221: - case 222: - case 223: - case 224: + case 143: + case 226: + case 227: + case 228: + case 229: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 139) { + while (node.parent && node.parent.kind === 141) { node = node.parent; } - return node.parent && (node.parent.kind === 155 || node.parent.kind === 267); + return node.parent && (node.parent.kind === 157 || node.parent.kind === 272); } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 172) { + while (node.parent && node.parent.kind === 177) { node = node.parent; } - return node.parent && node.parent.kind === 194; + return node.parent && node.parent.kind === 199; } function forEachEnclosingClass(node, callback) { var result; @@ -32406,13 +36075,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 139) { + while (nodeOnRightSide.parent.kind === 141) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 229) { + if (nodeOnRightSide.parent.kind === 234) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 235) { + if (nodeOnRightSide.parent.kind === 240) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -32424,7 +36093,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 172) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: @@ -32436,20 +36105,20 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 240 && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); + if (entityName.kind !== 177 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 234); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 194) { + if (entityName.parent.kind === 199) { meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -32465,20 +36134,20 @@ var ts; if (ts.nodeIsMissing(entityName)) { return undefined; } - if (entityName.kind === 69) { + if (entityName.kind === 70) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } return resolveEntityName(entityName, 107455, false, true); } - else if (entityName.kind === 172) { + else if (entityName.kind === 177) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 139) { + else if (entityName.kind === 141) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -32487,19 +36156,19 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 157 || entityName.parent.kind === 272) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 246) { + else if (entityName.parent.kind === 250) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 154) { + if (entityName.parent.kind === 156) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 256) { + if (node.kind === 261) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } if (isInsideWithStatementBody(node)) { @@ -32511,12 +36180,12 @@ var ts; else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 69) { + if (node.kind === 70) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 169 && - node.parent.parent.kind === 167 && + else if (node.parent.kind === 174 && + node.parent.parent.kind === 172 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -32526,11 +36195,11 @@ var ts; } } switch (node.kind) { - case 69: - case 172: - case 139: + case 70: + case 177: + case 141: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 97: + case 98: var container = ts.getThisContainer(node, false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -32538,27 +36207,30 @@ var ts; return sig.thisParameter; } } - case 95: - var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + case 96: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; - case 165: + case 167: return getTypeFromTypeNode(node).symbol; - case 121: + case 122: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 148) { + if (constructorDeclaration && constructorDeclaration.kind === 150) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 230 || node.parent.kind === 236) && + ((node.parent.kind === 235 || node.parent.kind === 241) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: - if (node.parent.kind === 173 && node.parent.argumentExpression === node) { - var objectType = checkExpression(node.parent.expression); + if (node.parent.kind === 178 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); if (objectType === unknownType) return undefined; var apparentType = getApparentType(objectType); @@ -32571,7 +36243,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 254) { + if (location && location.kind === 258) { return resolveEntityName(location.name, 107455 | 8388608); } return undefined; @@ -32589,7 +36261,7 @@ var ts; return getTypeFromTypeNode(node); } if (ts.isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; @@ -32621,20 +36293,20 @@ var ts; return unknownType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 171 || expr.kind === 170); - if (expr.parent.kind === 208) { + ts.Debug.assert(expr.kind === 176 || expr.kind === 175); + if (expr.parent.kind === 213) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 187) { - var iteratedType = checkExpression(expr.parent.right); + if (expr.parent.kind === 192) { + var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 253) { + if (expr.parent.kind === 257) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 170); + ts.Debug.assert(expr.parent.kind === 175); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); @@ -32643,11 +36315,11 @@ var ts; var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr) { + function getRegularTypeOfExpression(expr) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); @@ -32670,9 +36342,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_28 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_28); if (symbol) { symbols_3.push(symbol); } @@ -32680,6 +36352,10 @@ var ts; return symbols_3; } else if (symbol.flags & 67108864) { + if (symbol.leftSpread) { + var links = symbol; + return [links.leftSpread, links.rightSpread]; + } var target = void 0; var next = symbol; while (next = getSymbolLinks(next).target) { @@ -32721,7 +36397,7 @@ var ts; } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; - return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } function getReferencedExportContainer(node, prefixLocals) { node = ts.getParseTreeNode(node, ts.isIdentifier); @@ -32737,7 +36413,7 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 261) { var symbolFile = parentSymbol.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -32775,7 +36451,7 @@ var ts; else if (nodeLinks_1.flags & 131072) { var isDeclaredInLoop = nodeLinks_1.flags & 262144; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 199 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 204 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -32815,18 +36491,18 @@ var ts; return true; } switch (node.kind) { - case 229: - case 231: - case 232: case 234: - case 238: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: + case 237: + case 239: + case 243: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 241: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 235: + case 240: return node.expression - && node.expression.kind === 69 + && node.expression.kind === 70 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -32834,7 +36510,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 261 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -32885,7 +36561,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 255) { + if (node.kind === 260) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -32897,7 +36573,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); @@ -32929,7 +36605,7 @@ var ts; else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { @@ -32960,7 +36636,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getTypeOfExpression(expr)); + var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { @@ -32979,9 +36655,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_11 = reference.parent; + if (ts.isDeclaration(parent_11) && reference === parent_11.name) { + location = getDeclarationContainer(parent_11); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33001,7 +36677,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 16777216); + return !!(type.flags & 96 && type.flags & 1048576); } return false; } @@ -33052,13 +36728,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) + var meaning = (node.kind === 177) || (node.kind === 70 && isInTypeQuery(node)) ? 107455 | 1048576 : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); @@ -33080,6 +36757,9 @@ var ts; if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + return undefined; + } } } return typeReferenceDirectives; @@ -33090,15 +36770,15 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_12 = getParentOfSymbol(current); + if (parent_12) { + current = parent_12; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 256 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 261 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -33117,7 +36797,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 256); + return ts.getDeclarationOfKind(moduleSymbol, 261); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -33125,8 +36805,6 @@ var ts; ts.bindSourceFile(file, compilerOptions); } var augmentations; - var requestedExternalEmitHelpers = 0; - var firstFileRequestingExternalHelpers; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { @@ -33146,15 +36824,6 @@ var ts; } } } - if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { - var fileRequestedExternalEmitHelpers = file.flags & 31744; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { @@ -33205,43 +36874,50 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); - if (helpersModule) { - var exports_2 = helpersModule.exports; - if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { - verifyHelperSymbol(exports_2, "__extends", 107455); - } - if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { - verifyHelperSymbol(exports_2, "__assign", 107455); - } - if (requestedExternalEmitHelpers & 2048) { - verifyHelperSymbol(exports_2, "__decorate", 107455); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports_2, "__metadata", 107455); - } - } - if (requestedExternalEmitHelpers & 4096) { - verifyHelperSymbol(exports_2, "__param", 107455); - } - if (requestedExternalEmitHelpers & 8192) { - verifyHelperSymbol(exports_2, "__awaiter", 107455); - if (languageVersion < 2) { - verifyHelperSymbol(exports_2, "__generator", 107455); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 128; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name_29 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name_29), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_29); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols, name, meaning) { - var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); - if (!symbol) { - error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; } } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -33252,7 +36928,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -33264,14 +36940,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 147 && !ts.nodeIsPresent(node.body)) { + if (node.kind === 149 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 149 || node.kind === 150) { + else if (node.kind === 151 || node.kind === 152) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -33288,28 +36964,28 @@ var ts; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 128) { - if (node.kind === 144 || node.kind === 146) { + if (modifier.kind !== 130) { + if (node.kind === 146 || node.kind === 148) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 153) { + if (node.kind === 155) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 74: - if (node.kind !== 224 && node.parent.kind === 221) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + case 75: + if (node.kind !== 229 && node.parent.kind === 226) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75)); } break; + case 113: case 112: case 111: - case 110: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 111) { + if (modifier.kind === 112) { lastProtected = modifier; } - else if (modifier.kind === 110) { + else if (modifier.kind === 111) { lastPrivate = modifier; } if (flags & 28) { @@ -33324,11 +37000,11 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { - if (modifier.kind === 110) { + if (modifier.kind === 111) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -33337,7 +37013,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 113: + case 114: if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -33347,10 +37023,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -33359,17 +37035,17 @@ var ts; flags |= 32; lastStatic = modifier; break; - case 128: + case 130: if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 145 && node.kind !== 144 && node.kind !== 153 && node.kind !== 142) { + else if (node.kind !== 147 && node.kind !== 146 && node.kind !== 155 && node.kind !== 144) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; lastReadonly = modifier; break; - case 82: + case 83: if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -33382,45 +37058,45 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; - case 122: + case 123: if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 226) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; lastDeclare = modifier; break; - case 115: + case 116: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 221) { - if (node.kind !== 147 && - node.kind !== 145 && - node.kind !== 149 && - node.kind !== 150) { + if (node.kind !== 226) { + if (node.kind !== 149 && + node.kind !== 147 && + node.kind !== 151 && + node.kind !== 152) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 226 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -33432,14 +37108,14 @@ var ts; } flags |= 128; break; - case 118: + case 119: if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -33447,7 +37123,7 @@ var ts; break; } } - if (node.kind === 148) { + if (node.kind === 150) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -33462,13 +37138,13 @@ var ts; } return; } - else if ((node.kind === 230 || node.kind === 229) && flags & 2) { + else if ((node.kind === 235 || node.kind === 234) && flags & 2) { 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)) { + else if (node.kind === 144 && (flags & 92) && ts.isBindingPattern(node.name)) { 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) { + else if (node.kind === 144 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -33484,38 +37160,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 149: + case 151: + case 152: case 150: - case 148: - case 145: - case 144: case 147: case 146: - case 153: - case 225: + case 149: + case 148: + case 155: case 230: - case 229: - case 236: case 235: - case 179: - case 180: - case 142: + case 234: + case 241: + case 240: + case 184: + case 185: + case 144: return false; default: - if (node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 231 || node.parent.kind === 261) { return false; } switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: + case 225: + return nodeHasAnyModifiersExcept(node, 119); + case 226: + return nodeHasAnyModifiersExcept(node, 116); + case 227: + case 205: + case 228: return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); + case 229: + return nodeHasAnyModifiersExcept(node, 75); default: ts.Debug.fail(); return false; @@ -33527,10 +37203,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 147: - case 220: - case 179: - case 180: + case 149: + case 225: + case 184: + case 185: if (!node.asteriskToken) { return false; } @@ -33546,7 +37222,7 @@ var ts; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } - function checkGrammarTypeParameterList(node, typeParameters, file) { + function checkGrammarTypeParameterList(typeParameters, file) { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -33588,11 +37264,11 @@ var ts; } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 180) { + if (node.kind === 185) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -33627,7 +37303,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 132 && parameter.type.kind !== 130) { + if (parameter.type.kind !== 134 && parameter.type.kind !== 132) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -33652,9 +37328,9 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 193) { + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; + if (arg.kind === 198) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -33680,7 +37356,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -33693,7 +37369,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -33708,14 +37384,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } checkGrammarHeritageClause(heritageClause); @@ -33724,19 +37400,19 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 140) { + if (node.kind !== 142) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 187 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 192 && computedPropertyName.expression.operatorToken.kind === 25) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 220 || - node.kind === 179 || - node.kind === 147); + ts.Debug.assert(node.kind === 225 || + node.kind === 184 || + node.kind === 149); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -33748,7 +37424,7 @@ var ts; } } } - function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + function checkGrammarForInvalidQuestionMark(questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -33761,43 +37437,45 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + if (prop.kind === 259) { + continue; } - if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { + var name_30 = prop.name; + if (name_30.kind === 142) { + checkGrammarComputedPropertyName(name_30); + } + if (prop.kind === 258 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 118 || prop.kind !== 147) { + if (mod.kind !== 119 || prop.kind !== 149) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } 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_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (prop.kind === 257 || prop.kind === 258) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_30.kind === 8) { + checkGrammarNumericLiteral(name_30); } currentKind = Property; } - else if (prop.kind === 147) { + else if (prop.kind === 149) { currentKind = Property; } - else if (prop.kind === 149) { + else if (prop.kind === 151) { currentKind = GetAccessor; } - else if (prop.kind === 150) { + else if (prop.kind === 152) { currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_30); if (effectiveName === undefined) { continue; } @@ -33807,18 +37485,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_30, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_30)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_30, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_30, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33827,19 +37505,19 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 247) { + if (attr.kind === 251) { continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_31 = jsxAttr.name; + if (!seen[name_31.text]) { + seen[name_31.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_31, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 248 && !initializer.expression) { + if (initializer && initializer.kind === 252 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -33848,7 +37526,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 219) { + if (forInOrOfStatement.initializer.kind === 224) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -33856,20 +37534,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -33889,15 +37567,18 @@ var ts; else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 149 ? + return grammarErrorOnNode(accessor.name, kind === 151 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 150) { + else if (kind === 152) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -33916,20 +37597,11 @@ var ts; } } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 151 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -33943,8 +37615,8 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 171) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (node.parent.kind === 176) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -33959,10 +37631,10 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -33973,9 +37645,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 214: + case 219: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 209 + var isMisplacedContinueLabel = node.kind === 214 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -33983,8 +37655,8 @@ var ts; return false; } break; - case 213: - if (node.kind === 210 && !node.label) { + case 218: + if (node.kind === 215 && !node.label) { return false; } break; @@ -33997,13 +37669,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -34013,9 +37685,9 @@ var ts; if (node.dotDotDotToken) { var elements = node.parent.elements; if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 168 || node.name.kind === 167) { + if (node.name.kind === 173 || node.name.kind === 172) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -34025,11 +37697,11 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 || expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { + if (node.parent.parent.kind !== 212 && node.parent.parent.kind !== 213) { if (ts.isInAmbientContext(node)) { if (node.initializer) { if (ts.isConst(node) && !node.type) { @@ -34060,8 +37732,8 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 69) { - if (name.originalKeywordKind === 108) { + if (name.kind === 70) { + if (name.originalKeywordKind === 109) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -34086,15 +37758,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 203: - case 204: - case 205: - case 212: - case 206: - case 207: case 208: + case 209: + case 210: + case 217: + case 211: + case 212: + case 213: return false; - case 214: + case 219: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -34149,7 +37821,7 @@ var ts; return true; } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -34157,7 +37829,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -34170,13 +37842,13 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 222 || - node.kind === 223 || - node.kind === 230 || - node.kind === 229 || - node.kind === 236 || - node.kind === 235 || + if (node.kind === 227 || node.kind === 228 || + node.kind === 235 || + node.kind === 234 || + node.kind === 241 || + node.kind === 240 || + node.kind === 233 || ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } @@ -34185,7 +37857,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 200) { + if (ts.isDeclaration(decl) || decl.kind === 205) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -34204,7 +37876,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 199 || node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 204 || node.parent.kind === 231 || node.parent.kind === 261) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -34243,49 +37915,49 @@ var ts; (function (ts) { ; var nodeEdgeTraversalMap = ts.createMap((_a = {}, - _a[139] = [ + _a[141] = [ { name: "left", test: ts.isEntityName }, { name: "right", test: ts.isIdentifier } ], - _a[143] = [ + _a[145] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[177] = [ + _a[182] = [ { name: "type", test: ts.isTypeNode }, { name: "expression", test: ts.isUnaryExpression } ], - _a[195] = [ + _a[200] = [ { name: "expression", test: ts.isExpression }, { name: "type", test: ts.isTypeNode } ], - _a[196] = [ + _a[201] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[224] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isIdentifier }, - { name: "members", test: ts.isEnumMember } - ], - _a[225] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isModuleName }, - { name: "body", test: ts.isModuleBody } - ], - _a[226] = [ - { name: "statements", test: ts.isStatement } - ], _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[230] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[231] = [ + { name: "statements", test: ts.isStatement } + ], + _a[234] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "moduleReference", test: ts.isModuleReference } ], - _a[240] = [ + _a[245] = [ { name: "expression", test: ts.isExpression, optional: true } ], - _a[255] = [ + _a[260] = [ { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], @@ -34293,330 +37965,338 @@ var ts; function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } - function reduceEachChild(node, f, initial) { + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return initial; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return initial; } var result = initial; switch (node.kind) { + case 203: + case 206: case 198: - case 201: - case 193: - case 217: - case 287: - break; - case 140: - result = reduceNode(node.expression, f, result); + case 222: + case 293: break; case 142: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; - case 143: - result = reduceNode(node.expression, f, result); + case 144: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 145: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 147: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 148: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 149: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 150: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; - case 167: - case 168: - result = ts.reduceLeft(node.elements, f, result); + case 151: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 169: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; - case 170: - result = ts.reduceLeft(node.elements, f, result); - break; - case 171: - result = ts.reduceLeft(node.properties, f, result); + case 152: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; case 172: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.name, f, result); - break; case 173: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.argumentExpression, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 174: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 175: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 176: - result = reduceNode(node.tag, f, result); - result = reduceNode(node.template, f, result); + result = reduceNodes(node.properties, cbNodes, result); break; - case 179: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 180: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 177: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; case 178: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 179: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 180: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; case 181: - case 182: - case 183: + result = reduceNode(node.tag, cbNode, result); + result = reduceNode(node.template, cbNode, result); + break; case 184: - case 190: - case 191: - case 196: - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 185: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 183: case 186: - result = reduceNode(node.operand, f, result); - break; case 187: - result = reduceNode(node.left, f, result); - result = reduceNode(node.right, f, result); - break; case 188: - result = reduceNode(node.condition, f, result); - result = reduceNode(node.whenTrue, f, result); - result = reduceNode(node.whenFalse, f, result); - break; case 189: - result = reduceNode(node.head, f, result); - result = ts.reduceLeft(node.templateSpans, f, result); + case 195: + case 196: + case 201: + result = reduceNode(node.expression, cbNode, result); + break; + case 190: + case 191: + result = reduceNode(node.operand, cbNode, result); break; case 192: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 193: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); break; case 194: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); break; case 197: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.literal, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 199: - result = ts.reduceLeft(node.statements, f, result); - break; - case 200: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.declarationList, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); break; case 202: - result = reduceNode(node.expression, f, result); - break; - case 203: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.thenStatement, f, result); - result = reduceNode(node.elseStatement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); break; case 204: - result = reduceNode(node.statement, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.statements, cbNodes, result); break; case 205: - case 212: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); - break; - case 206: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.condition, f, result); - result = reduceNode(node.incrementor, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); break; case 207: + result = reduceNode(node.expression, cbNode, result); + break; case 208: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 209: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 210: + case 217: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 211: - case 215: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; + case 212: case 213: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.caseBlock, f, result); - break; - case 214: - result = reduceNode(node.label, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 216: - result = reduceNode(node.tryBlock, f, result); - result = reduceNode(node.catchClause, f, result); - result = reduceNode(node.finallyBlock, f, result); + case 220: + result = reduceNode(node.expression, cbNode, result); break; case 218: - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); break; case 219: - result = ts.reduceLeft(node.declarations, f, result); - break; - case 220: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 221: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); break; - case 227: - result = ts.reduceLeft(node.clauses, f, result); + case 223: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 230: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.importClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 224: + result = reduceNodes(node.declarations, cbNodes, result); break; - case 231: - result = reduceNode(node.name, f, result); - result = reduceNode(node.namedBindings, f, result); + case 225: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 226: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 232: - result = reduceNode(node.name, f, result); - break; - case 233: - case 237: - result = ts.reduceLeft(node.elements, f, result); - break; - case 234: - case 238: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); + result = reduceNodes(node.clauses, cbNodes, result); break; case 235: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 236: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.exportClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 237: + result = reduceNode(node.name, cbNode, result); + break; + case 238: + case 242: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 239: + case 243: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 240: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; case 241: - result = reduceNode(node.openingElement, f, result); - result = ts.reduceLeft(node.children, f, result); - result = reduceNode(node.closingElement, f, result); - break; - case 242: - case 243: - result = reduceNode(node.tagName, f, result); - result = ts.reduceLeft(node.attributes, f, result); - break; - case 245: - result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 246: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); break; case 247: - result = reduceNode(node.expression, f, result); - break; case 248: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.attributes, cbNodes, result); break; case 249: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + break; case 250: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 251: - result = ts.reduceLeft(node.types, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 252: - result = reduceNode(node.variableDeclaration, f, result); - result = reduceNode(node.block, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 253: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; + result = reduceNode(node.expression, cbNode, result); case 254: - result = reduceNode(node.name, f, result); - result = reduceNode(node.objectAssignmentInitializer, f, result); + result = reduceNodes(node.statements, cbNodes, result); + break; + case 255: + result = reduceNodes(node.types, cbNodes, result); break; case 256: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); break; - case 288: - result = reduceNode(node.expression, f, result); + case 257: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 258: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 259: + result = reduceNode(node.expression, cbNode, result); + break; + case 261: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 294: + result = reduceNode(node.expression, cbNode, result); break; default: var edgeTraversalPath = nodeEdgeTraversalMap[kind]; @@ -34626,8 +38306,8 @@ var ts; var value = node[edge.name]; if (value !== undefined) { result = ts.isArray(value) - ? ts.reduceLeft(value, f, result) - : f(result, value); + ? reduceNodes(value, cbNodes, result) + : cbNode(result, value); } } } @@ -34637,9 +38317,10 @@ var ts; } ts.reduceEachChild = reduceEachChild; function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); var visited = visitor(node); if (visited === node) { return node; @@ -34682,6 +38363,7 @@ var ts; } for (var i = 0; i < count; i++) { var node = nodes[i + start]; + aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -34713,183 +38395,213 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.createNodeArray(ts.concatenate(statements, declarations), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + function visitParameterList(nodes, visitor, context) { + context.startLexicalEnvironment(); + var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; function visitEachChild(node, visitor, context) { if (node === undefined) { return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return node; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return node; } switch (node.kind) { - case 198: - case 201: - case 193: - case 217: - return node; - case 140: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 142: - return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 145: - return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 147: - return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 148: - return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 149: - return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 150: - return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 167: - return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); - case 168: - return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); - case 169: - return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 170: - return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); - case 171: - return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 172: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 173: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 174: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 175: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); - case 178: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 179: - return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 180: - return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); - case 181: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 182: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 183: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 184: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 187: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); - case 185: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 186: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 188: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); - case 190: - return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192: - return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 194: - return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); - case 199: - return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 200: - return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 202: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 203: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); - case 204: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 205: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 206: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 198: + case 222: + return node; + case 142: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 144: + return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 149: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 150: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 151: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 172: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 173: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 174: + return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 175: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 176: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 177: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 178: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 179: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 180: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 181: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 183: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 185: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 186: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 188: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 189: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 190: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 191: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 193: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 194: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 195: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 199: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 202: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + case 204: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 205: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); case 207: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 208: - return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); case 209: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 210: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 211: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 212: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 213: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 214: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 215: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 216: - return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 217: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 218: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 219: - return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 220: - return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); case 221: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 223: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 224: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 225: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 226: return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 227: - return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 230: - return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 231: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 232: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 233: - return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); - case 234: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 235: - return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 236: - return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 237: - return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 238: - return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 239: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 240: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 241: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); case 242: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); case 243: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 245: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); case 246: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 247: - return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 248: - return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 249: - return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 250: - return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 251: - return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 252: - return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 253: - return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); case 254: - return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 255: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); case 256: - context.startLexicalEnvironment(); - return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); - case 288: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 257: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 258: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 259: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + case 261: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + case 294: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); default: var updated = void 0; @@ -34917,6 +38629,15 @@ var ts; } } ts.visitEachChild = visitEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.createNodeArray(ts.concatenate(statements, declarations), statements) + : ts.addRange(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function mergeFunctionBodyLexicalEnvironment(body, declarations) { if (body && declarations !== undefined && declarations.length > 0) { if (ts.isBlock(body)) { @@ -34947,85 +38668,61 @@ var ts; if (node === undefined) { return 0; } - else if (node.transformFlags & 536870912) { - return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + if (node.transformFlags & 536870912) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } - else { - var subtreeFlags = aggregateTransformFlagsForSubtree(node); - return ts.computeTransformFlagsForNode(node, subtreeFlags); + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0; } + var subtreeFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { return 0; } - return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } - function aggregateTransformFlagsForChildNode(transformFlags, child) { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 154 && kind <= 166) { - return -3; - } - switch (kind) { - case 174: - case 175: - case 170: - return 537133909; - case 225: - return 546335573; - case 142: - return 538968917; - case 180: - return 550710101; - case 179: - case 220: - return 550726485; - case 219: - return 538968917; - case 221: - case 192: - return 537590613; - case 148: - return 550593365; - case 147: - case 149: - case 150: - return 550593365; - case 117: - case 130: - case 127: - case 132: - case 120: - case 133: - case 103: - case 141: - case 144: - case 146: - case 151: - case 152: - case 153: - case 222: - case 223: - return -3; - case 171: - return 537430869; - default: - return 536871765; - } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } var Debug; (function (Debug) { Debug.failNotOptional = Debug.shouldAssert(1) ? function (message) { return Debug.assert(false, message || "Node not optional."); } - : function (message) { }; + : ts.noop; Debug.failBadSyntaxKind = Debug.shouldAssert(1) ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } - : function (node, message) { }; + : ts.noop; + Debug.assertEachNode = Debug.shouldAssert(1) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; Debug.assertNode = Debug.shouldAssert(1) ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } - : function (node, test, message) { }; + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + : ts.noop; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -35044,277 +38741,316 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { - if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { - var right = node.right; - if (ts.isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; - var value = node.right; - var expressions = []; - if (needsValue) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - else if (ts.nodeIsSynthesized(node)) { - location = value; + var expressions; + var flattenContext = { + context: context, + level: level, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (needsValue) { + value = ensureIdentifier(flattenContext, value, true, location); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); - if (needsValue) { + flattenBindingOrAssignmentElement(flattenContext, node, value, location, ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } expressions.push(value); } - var expression = ts.inlineExpressions(expressions); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location) { - var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + ts.setEmitFlags(expression, 64); ts.aggregateTransformFlags(expression); - expressions.push(expression); + expressions = ts.append(expressions, expression); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location); + expression.original = original; + emitExpression(expression); } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; - function flattenParameterDestructuring(context, node, value, visitor) { + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + var pendingExpressions; + var pendingDeclarations = []; var declarations = []; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + var flattenContext = { + context: context, + level: level, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, undefined, undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_32 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_32, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2); + variable.original = original; + if (ts.isIdentifier(name_32)) { + ts.setEmitFlags(variable, 64); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } return declarations; - function emitAssignment(name, value, location) { - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); - ts.aggregateTransformFlags(declaration); - declarations.push(declaration); + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(undefined); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); } } - ts.flattenParameterDestructuring = flattenParameterDestructuring; - function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { - var declarations = []; - var pendingAssignments; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - return declarations; - function emitAssignment(name, value, location, original) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = ts.inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); - declarations.push(declaration); - ts.aggregateTransformFlags(declaration); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - if (recordTempVariable) { - var assignment = ts.createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, undefined); - } - return name; - } - } - ts.flattenVariableDestructuring = flattenVariableDestructuring; - function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { - var pendingAssignments = []; - flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - var expression = ts.inlineExpressions(pendingAssignments); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location, original) { - var left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, undefined); - return name; - } - function emitPendingAssignment(name, value, location, original) { - var expression = ts.createAssignment(name, value, location); - expression.original = original; - context.setNodeEmitFlags(expression, 2048); - pendingAssignments.push(expression); - return expression; - } - } - ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; - function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { - if (value && visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); - } - if (ts.isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - function emitDestructuringAssignment(bindingTarget, value, location) { - var target; - if (ts.isShorthandPropertyAssignment(bindingTarget)) { - var initializer = visitor - ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) - : bindingTarget.objectAssignmentInitializer; - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - target = bindingTarget.name; - } - else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { - var initializer = visitor - ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) - : bindingTarget.right; - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, location); - } - else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); - } - } - function emitObjectLiteralAssignment(target, value, location) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, location) { - var elements = target.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); - } - } - } - } - function emitBindingElement(target, value) { - var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + ts.flattenDestructuringBinding = flattenDestructuringBinding; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { value = ts.createVoidZero(); } - var name = target.name; - if (ts.isBindingPattern(name)) { - var elements = name.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (ts.isOmittedExpression(element)) { - continue; - } - else if (name.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - emitBindingElement(element, ts.createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, ts.createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - function createDefaultValueCheck(value, defaultValue, location) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } - function createDestructuringPropertyAccess(expression, propertyName) { - if (ts.isComputedPropertyName(propertyName)) { - return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); - } - else if (ts.isLiteralExpression(propertyName)) { - var clone_2 = ts.getSynthesizedClone(propertyName); - clone_2.text = ts.unescapeIdentifier(clone_2.text); - return ts.createElementAccess(expression, clone_2); - } - else { - if (ts.isGeneratedIdentifier(propertyName)) { - var clone_3 = ts.getSynthesizedClone(propertyName); - clone_3.text = ts.unescapeIdentifier(clone_3.text); - return ts.createPropertyAccess(expression, clone_3); + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, element); + } + } + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 + && !(element.transformFlags & (524288 | 1048576)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); } else { - return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1) { + if (element.transformFlags & 1048576) { + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } } } - function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteral(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + return ts.createElementAccess(value, argumentExpression); + } + else { + var name_33 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + return ts.createPropertyAccess(value, name_33); + } + } + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.createAssignment(temp, value, location)); } - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, undefined); + } + return temp; } } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(undefined, undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]); + } })(ts || (ts = {})); var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,34 +39059,61 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(177); + context.enableSubstitution(178); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; - var currentSourceFileExternalHelpersModuleName; + var currentScopeFirstDeclarationsOfName; var enabledSubstitutions; var classAliases; var applicableSubstitutions; - var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { - return ts.visitNode(node, visitor, ts.isSourceFile); + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 261: + case 232: + case 231: + case 204: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 226: + case 225: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); + break; + } + } function visitor(node) { return saveStateAndInvoke(node, visitorWorker); } function visitorWorker(node) { - if (node.kind === 256) { - return visitSourceFile(node); - } - else if (node.transformFlags & 1) { + if (node.transformFlags & 1) { return visitTypeScript(node); } else if (node.transformFlags & 2) { @@ -35358,15 +39121,32 @@ var ts; } return node; } + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 240: + return visitExportAssignment(node); + case 241: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } function namespaceElementVisitor(node) { return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 236 || - node.kind === 230 || - node.kind === 231 || - (node.kind === 229 && - node.moduleReference.kind === 240)) { + if (node.kind === 241 || + node.kind === 235 || + node.kind === 236 || + (node.kind === 234 && + node.moduleReference.kind === 245)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -35382,145 +39162,129 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 148: - return undefined; - case 145: - case 153: - case 149: case 150: + return undefined; case 147: + case 155: + case 151: + case 152: + case 149: return visitorWorker(node); - case 198: + case 203: return node; default: ts.Debug.failBadSyntaxKind(node); return undefined; } } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270) { + return undefined; + } + else if (currentNamespace && node.kind === 83) { + return undefined; + } + return node; + } function visitTypeScript(node) { if (ts.hasModifier(node, 2) && ts.isStatement(node)) { return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 82: - case 77: + case 83: + case 78: return currentNamespace ? undefined : node; - case 112: - case 110: + case 113: case 111: - case 115: - case 118: - case 74: - case 122: - case 128: - case 160: - case 161: - case 159: - case 154: - case 141: - case 117: - case 120: - case 132: + case 112: + case 116: + case 75: + case 123: case 130: - case 127: - case 103: - case 133: - case 157: - case 156: - case 158: - case 155: case 162: case 163: + case 161: + case 156: + case 143: + case 118: + case 121: + case 134: + case 132: + case 129: + case 104: + case 135: + case 159: + case 158: + case 160: + case 157: case 164: case 165: case 166: - case 153: - case 143: - case 223: + case 167: + case 168: + case 169: + case 170: + case 171: + case 155: case 145: - case 148: - return undefined; - case 222: - return ts.createNotEmittedStatement(node); - case 221: - return visitClassDeclaration(node); - case 192: - return visitClassExpression(node); - case 251: - return visitHeritageClause(node); - case 194: - return visitExpressionWithTypeArguments(node); + case 228: case 147: - return visitMethodDeclaration(node); - case 149: - return visitGetAccessor(node); + return undefined; case 150: + return visitConstructor(node); + case 227: + return ts.createNotEmittedStatement(node); + case 226: + return visitClassDeclaration(node); + case 197: + return visitClassExpression(node); + case 255: + return visitHeritageClause(node); + case 199: + return visitExpressionWithTypeArguments(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessor(node); + case 152: return visitSetAccessor(node); - case 220: - return visitFunctionDeclaration(node); - case 179: - return visitFunctionExpression(node); - case 180: - return visitArrowFunction(node); - case 142: - return visitParameter(node); - case 178: - return visitParenthesizedExpression(node); - case 177: - case 195: - return visitAssertionExpression(node); - case 196: - return visitNonNullExpression(node); - case 224: - return visitEnumDeclaration(node); - case 184: - return visitAwaitExpression(node); - case 200: - return visitVariableStatement(node); case 225: - return visitModuleDeclaration(node); + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 183: + return visitParenthesizedExpression(node); + case 182: + case 200: + return visitAssertionExpression(node); + case 179: + return visitCallExpression(node); + case 180: + return visitNewExpression(node); + case 201: + return visitNonNullExpression(node); case 229: + return visitEnumDeclaration(node); + case 205: + return visitVariableStatement(node); + case 223: + return visitVariableDeclaration(node); + case 230: + return visitModuleDeclaration(node); + case 234: return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function onBeforeVisitNode(node) { - switch (node.kind) { - case 256: - case 227: - case 226: - case 199: - currentScope = node; - break; - } - } function visitSourceFile(node) { - currentSourceFile = node; - if (node.flags & 31744 - && compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); - var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); - var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~8; - statements.push(externalHelpersModuleImport); - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = ts.visitEachChild(node, visitor, context); - } - setNodeEmitFlags(node, 1 | node.emitFlags); - return node; + var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { if (node.decorators && node.decorators.length > 0) { @@ -35539,71 +39303,64 @@ var ts; var staticProperties = getInitializedProperties(node, true); var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var classAlias; var name = node.name; if (!name && staticProperties.length > 0) { name = ts.getGeneratedNameForNode(node); } - var statements = []; - if (!isDecoratedClass) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); - ts.setOriginalNode(classDeclaration, node); - if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); - } - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + var classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var statements = [classStatement]; if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); if (isNamespaceExport(node)) { addExportMemberAssignment(statements, node); } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } - return statements; + if (statements.length > 1) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + } + return ts.singleOrMany(statements); } - function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + var emitFlags = ts.getEmitFlags(node); + if (hasStaticProperties) { + emitFlags |= 32; + } + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { var location = ts.moveRangePastDecorators(node); - var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); - if (!name) { - name = ts.getGeneratedNameForNode(node); - } - var classAlias; - if (resolver.getNodeCheckFlags(node) & 8388608) { - enableSubstitutionForClassAliases(); - classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - } - var declaredName = getDeclarationName(node, true); - var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) - ]), location); - setCommentRange(transformedClassExpression, node); - statements.push(ts.setOriginalNode(transformedClassExpression, node)); - if (classAlias) { - statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(declaredName, undefined, classAlias) - ]), location), node)); - } - return classAlias; + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, false, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, hasExtendsClause); + var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members, location); + ts.setOriginalNode(classExpression, node); + var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location); + ts.setOriginalNode(statement, node); + ts.setCommentRange(statement, node); + return statement; } function visitClassExpression(node) { var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, heritageClauses !== undefined); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84; })); var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); if (staticProperties.length > 0) { var expressions = []; @@ -35612,9 +39369,9 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); - ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } @@ -35631,24 +39388,23 @@ var ts; } function transformConstructor(node, hasExtendsClause) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 131072; + var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + var body = transformConstructorBody(node, constructor, hasExtendsClause); return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); } function transformConstructorParameters(constructor) { - return constructor - ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) - : []; + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } - function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + function transformConstructorBody(node, constructor, hasExtendsClause) { var statements = []; var indexOfFirstStatement = 0; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); var propertyAssignments = getParametersWithPropertyAssignments(constructor); @@ -35658,12 +39414,12 @@ var ts; statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); - addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } ts.addRange(statements, endLexicalEnvironment()); - return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + return ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined, true); } function addPrologueDirectivesAndInitialSuperCall(ctor, result) { if (ctor.body) { @@ -35673,7 +39429,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +39448,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 1536 | 48); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 1536); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35707,32 +39463,32 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 145 + return member.kind === 147 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } - function addInitializedPropertyStatements(statements, node, properties, receiver) { - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; - var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } - function generateInitializedPropertyExpressions(node, properties, receiver) { + function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { - var property = properties_8[_i]; - var expression = transformInitializedProperty(node, property, receiver); + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; } - function transformInitializedProperty(node, property, receiver) { + function transformInitializedProperty(property, receiver) { var propertyName = visitPropertyNameOfClassElement(property); var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); @@ -35780,12 +39536,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 149: - case 150: + case 151: + case 152: return getAllDecoratorsOfAccessors(node, member); - case 147: + case 149: return getAllDecoratorsOfMethod(member); - case 145: + case 147: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -35796,10 +39552,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -35824,14 +39581,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -35856,44 +39613,40 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 145 + ? member.kind === 147 ? ts.createVoidZero() : ts.createNull() : undefined; - var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536); return helper; } - function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { - var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } } - function generateConstructorDecorationExpression(node, decoratedClassAlias) { + function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - if (decoratedClassAlias) { - var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); - var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } - else { - var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, false, true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; } function transformDecorator(decorator) { return ts.visitNode(decorator.expression, visitor, ts.isExpression); @@ -35904,97 +39657,90 @@ var ts; expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, decorator.expression); + ts.setEmitFlags(helper, 1536); expressions.push(helper); } } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); } } } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 147 - || kind === 149 - || kind === 150 - || kind === 145; + return kind === 149 + || kind === 151 + || kind === 152 + || kind === 147; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 147; + return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 221 - || kind === 192 - || kind === 147 - || kind === 149 - || kind === 150; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { - case 145: - case 142: - case 149: - return serializeTypeNode(node.type); - case 150: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 221: - case 192: case 147: + case 144: + case 151: + return serializeTypeNode(node.type); + case 152: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 226: + case 197: + case 149: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 160) { - return node.elementType; - } - else if (node && node.kind === 155) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -36002,7 +39748,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -36010,7 +39756,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -36019,6 +39765,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -36033,49 +39788,75 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 103: + case 104: return ts.createVoidZero(); - case 164: - return serializeTypeNode(node.type); - case 156: - case 157: - return ts.createIdentifier("Function"); - case 160: - case 161: - return ts.createIdentifier("Array"); - case 154: - case 120: - return ts.createIdentifier("Boolean"); - case 132: - return ts.createIdentifier("String"); case 166: + return serializeTypeNode(node.type); + case 158: + case 159: + return ts.createIdentifier("Function"); + case 162: + case 163: + return ts.createIdentifier("Array"); + case 156: + case 121: + return ts.createIdentifier("Boolean"); + case 134: + return ts.createIdentifier("String"); + case 171: switch (node.literal.kind) { case 9: return ts.createIdentifier("String"); case 8: return ts.createIdentifier("Number"); - case 99: - case 84: + case 100: + case 85: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 130: + case 132: return ts.createIdentifier("Number"); - case 133: + case 135: return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 155: + case 157: return serializeTypeReferenceNode(node); - case 158: - case 159: - case 162: - case 163: - case 117: case 165: + case 164: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 70) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } + case 160: + case 168: + case 169: + case 170: + case 161: + case 118: + case 167: break; default: ts.Debug.failBadSyntaxKind(node); @@ -36088,7 +39869,7 @@ var ts; case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: return serializeEntityNameAsExpression(node.typeName, false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: @@ -36116,22 +39897,22 @@ var ts; } function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + case 70: + var name_34 = ts.getMutableClone(node); + name_34.flags &= ~8; + name_34.original = undefined; + name_34.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_34), ts.createLiteral("undefined")), name_34); } - return name_29; - case 139: + return name_34; + case 141: return serializeQualifiedNameAsExpression(node, useFallback); } } function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 69) { + if (node.left.kind === 70) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { @@ -36144,7 +39925,7 @@ var ts; return ts.createPropertyAccess(left, node.right); } function getGlobalSymbolNameWithFallback() { - return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; @@ -36154,7 +39935,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeIdentifier(name.text)); } else { return ts.getSynthesizedClone(name); @@ -36176,9 +39957,9 @@ var ts; } } function visitHeritageClause(node) { - if (node.token === 83) { + if (node.token === 84) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.createHeritageClause(83, types, node); + return ts.createHeritageClause(84, types, node); } return undefined; } @@ -36189,15 +39970,22 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.visitEachChild(node, visitor, context); + } function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(method, node); - return method; + var updated = ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); @@ -36206,135 +39994,56 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateGetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateSetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); + var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isNamespaceExport(node)) { - var statements = [func]; + var statements = [updated]; addExportMemberAssignment(statements, node); return statements; } - return func; + return updated; } function visitFunctionExpression(node) { if (ts.nodeIsMissing(node.body)) { return ts.createOmittedExpression(); } - var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); - return func; + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitArrowFunction(node) { - var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); - ts.setOriginalNode(func, node); - return func; - } - function transformFunctionBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformFunctionBodyWorker(node.body); - } - function transformFunctionBodyWorker(body, start) { - if (start === void 0) { start = 0; } - var savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); - var visited = ts.updateBlock(body, statements); - var declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - function transformConciseBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformConciseBodyWorker(node.body, false); - } - function transformConciseBodyWorker(body, forceBlockFunctionBody) { - if (ts.isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - var visited = ts.visitNode(body, visitor, ts.isConciseBody); - var declarations = endLexicalEnvironment(); - var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !ts.isBlock(merged)) { - return ts.createBlock([ - ts.createReturn(merged) - ]); - } - else { - return merged; - } - } - } - function getPromiseConstructor(type) { - var typeName = ts.getEntityNameFromTypeNode(type); - if (typeName && ts.isEntityName(typeName)) { - var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - return undefined; - } - function transformAsyncFunctionBody(node) { - var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); - var block = ts.createBlock(statements, node.body, true); - if (languageVersion >= 2) { - if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); - } - } - return block; - } - else { - return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); - } + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32); return parameter; } function visitVariableStatement(node) { @@ -36352,14 +40061,14 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + return ts.flattenDestructuringAssignment(node, visitor, context, 0, false, createNamespaceExportExpression); } else { return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); } } - function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2); @@ -36377,42 +40086,43 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return ts.createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } function shouldEmitEnumDeclaration(node) { return !ts.isConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); - } - function addVarForEnumExportedFromNamespace(statements, node) { - var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); - statements.push(statement); - } function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { return undefined; } var statements = []; - var emitFlags = 64; - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); - ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); - statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); + moduleArg = ts.createAssignment(localName, moduleArg); } + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(enumStatement, node); + ts.setEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -36447,35 +40157,56 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); + function hasNamespaceQualifiedExportName(node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.System); } - function isES6ExportedDeclaration(node) { - return isExternalModuleExport(node) - && moduleKind === ts.ModuleKind.ES6; + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } } - function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_35 = node.symbol && node.symbol.name; + if (name_35) { + return currentScopeFirstDeclarationsOfName[name_35] === node; + } + } + return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) - ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) - : undefined, [ - ts.createVariableDeclaration(getDeclarationName(node, false, true)) + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + ts.createVariableDeclaration(ts.getLocalName(node, false, true)) ]); ts.setOriginalNode(statement, node); - if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + if (node.kind === 229) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 1024 | 2097152); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 | 2097152); + statements.push(mergeMarker); + return false; } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); - statements.push(statement); } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -36484,38 +40215,42 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; - var emitFlags = 64; - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); - if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { - var localName = getLocalName(node); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); moduleArg = ts.createAssignment(localName, moduleArg); } - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 226) { + if (body.kind === 231) { ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); statementsLocation = body.statements; blockLocation = body; @@ -36536,18 +40271,69 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); - if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + if (body.kind !== 231) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body.kind === 230) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + function visitImportDeclaration(node) { + if (!node.importClause) { + return node; + } + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, true); + return importClause + ? ts.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier) + : undefined; + } + function visitImportClause(node) { + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, true); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + function visitNamedImportBindings(node) { + if (node.kind === 237) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitExportAssignment(node) { + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, true); + return exportClause + ? ts.updateExportDeclaration(node, undefined, undefined, exportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } function shouldEmitImportEqualsDeclaration(node) { return resolver.isReferencedAliasDeclaration(node) || (!ts.isExternalModule(currentSourceFile) @@ -36555,16 +40341,18 @@ var ts; } function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { - return ts.visitEachChild(node, visitor, context); + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 1536 | 2048); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { - return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(node.name, undefined, moduleReference) + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ]), node), node); } else { @@ -36589,148 +40377,87 @@ var ts; return ts.createStatement(expression, undefined); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, false, true), exportValue), location); } - function createExternalModuleExport(exportName) { - return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ - ts.createExportSpecifier(exportName) - ])); - } - function getNamespaceMemberName(name, allowComments, allowSourceMaps) { - var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); - var emitFlags; - if (!allowComments) { - emitFlags |= 49152; - } - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return getNamespaceMemberName(name, false, true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, false, true); } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { return ts.getGeneratedNameForNode(node); } - function getLocalName(node, noSourceMaps, allowComments) { - return getDeclarationName(node, allowComments, !noSourceMaps, 262144); - } - function getExportName(node, noSourceMaps, allowComments) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - return getDeclarationName(node, allowComments, !noSourceMaps, 131072); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); - } - return name_30; - } - else { - return ts.getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } function getClassPrototype(node) { - return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { return ts.hasModifier(member, 32) - ? getDeclarationName(node) + ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8) === 0) { enabledSubstitutions |= 8; - context.enableSubstitution(69); - } - } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 4) === 0) { - enabledSubstitutions |= 4; - context.enableSubstitution(174); - context.enableSubstitution(172); - context.enableSubstitution(173); - context.enableEmitNotification(221); - context.enableEmitNotification(147); - context.enableEmitNotification(149); - context.enableEmitNotification(150); - context.enableEmitNotification(148); + context.enableSubstitution(70); } } function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(69); + context.enableSubstitution(70); classAliases = ts.createMap(); } } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(69); - context.enableSubstitution(254); - context.enableEmitNotification(225); + context.enableSubstitution(70); + context.enableSubstitution(258); + context.enableEmitNotification(230); } } - function isSuperContainer(node) { - var kind = node.kind; - return kind === 221 - || kind === 148 - || kind === 147 - || kind === 149 - || kind === 150; - } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 225; + return ts.getOriginalNode(node).kind === 230; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 224; + return ts.getOriginalNode(node).kind === 229; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; - var savedCurrentSuperContainer = currentSuperContainer; - if (enabledSubstitutions & 4 && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2; } if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,32 +40467,26 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_36 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_36); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_36, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_36, exportedName, node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: - return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); } return node; } @@ -36781,10 +40502,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); - return clone_4; + var clone_2 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -36792,11 +40513,11 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container) { - var substitute = (applicableSubstitutions & 2 && container.kind === 225) || - (applicableSubstitutions & 8 && container.kind === 224); + if (container && container.kind !== 261) { + var substitute = (applicableSubstitutions & 2 && container.kind === 230) || + (applicableSubstitutions & 8 && container.kind === 229); if (substitute) { return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); } @@ -36804,100 +40525,354 @@ var ts; } return undefined; } - function substituteCallExpression(node) { - var expression = node.expression; - if (ts.isSuperProperty(expression)) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - var argumentExpression = ts.isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ - ts.createThis() - ].concat(node.arguments)); - } - } - return node; - } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); - } - } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; } + ts.setConstantValue(node, constantValue); + return substitute; } return node; } - function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { - if (flags & 4096) { - return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; } - else { - return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); - } - } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; } } ts.transformTypeScript = transformTypeScript; + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.createCall(ts.getHelperName("__param"), undefined, [ + ts.createLiteral(parameterOffset), + expression + ], location); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + context.requestEmitHelper(decorateHelper); + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray, location); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, true); + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8) === 0) { + return node; + } + switch (node.kind) { + case 176: + return visitObjectLiteralExpression(node); + case 192: + return visitBinaryExpression(node, noDestructuringValue); + case 223: + return visitVariableDeclaration(node); + case 213: + return visitForOfStatement(node); + case 211: + return visitForStatement(node); + case 188: + return visitVoidExpression(node); + case 150: + return visitConstructorDeclaration(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessorDeclaration(node); + case 152: + return visitSetAccessorDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 207: + return visitExpressionStatement(node); + case 183: + return visitParenthesizedExpression(node, noDestructuringValue); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; + if (e.kind === 259) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === 257) { + var p = e; + chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); + } + else { + chunkObject.push(e); + } + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 1048576) { + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 176) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); + } + else if (node.operatorToken.kind === 25) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + return ts.flattenDestructuringBinding(node, visitor, context, 1); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitForOfStatement(node) { + var leadingStatements; + var temp; + var initializer = ts.skipParentheses(node.initializer); + if (initializer.transformFlags & 1048576) { + if (ts.isVariableDeclarationList(initializer)) { + temp = ts.createTempVariable(undefined); + var firstDeclaration = ts.firstOrUndefined(initializer.declarations); + var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(initializer, declarations), initializer); + leadingStatements = ts.append(leadingStatements, statement); + } + } + else if (ts.isAssignmentPattern(initializer)) { + temp = ts.createTempVariable(undefined); + var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, node.initializer)), visitor, context, 1); + leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, node.initializer)); + } + } + if (temp) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var block = ts.isBlock(statement) + ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements)) + : ts.createBlock(ts.append(leadingStatements, statement), statement, true); + return ts.updateForOf(node, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, undefined, node.initializer) + ], node.initializer, 1), expression, block); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParameter(node) { + if (node.transformFlags & 1048576) { + return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + return ts.updateConstructor(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitGetAccessorDeclaration(node) { + return ts.updateGetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitSetAccessorDeclaration(node) { + return ts.updateSetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var leadingStatements; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 1048576) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 524288); + leadingStatements = ts.append(leadingStatements, statement); + } + } + } + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + var trailingStatements = endLexicalEnvironment(); + if (ts.some(leadingStatements) || ts.some(trailingStatements)) { + var block = ts.convertToFunctionBody(body, true); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); + } + return body; + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + }; + function createAssignHelper(context, attributesSegments) { + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; })(ts || (ts = {})); var ts; (function (ts) { - var entities = createEntitiesMap(); function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; - return node; + return visited; } function visitor(node) { if (node.transformFlags & 4) { return visitorWorker(node); } - else if (node.transformFlags & 8) { - return ts.visitEachChild(node, visitor, context); - } else { return node; } } function visitorWorker(node) { switch (node.kind) { - case 241: + case 246: return visitJsxElement(node, false); - case 242: + case 247: return visitJsxSelfClosingElement(node, false); - case 248: + case 252: return visitJsxExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.visitEachChild(node, visitor, context); } } function transformJsxChildToExpression(node) { switch (node.kind) { - case 244: + case 10: return visitJsxText(node); - case 248: + case 252: return visitJsxExpression(node); - case 241: + case 246: return visitJsxElement(node, true); - case 242: + case 247: return visitJsxSelfClosingElement(node, true); default: ts.Debug.failBadSyntaxKind(node); @@ -36924,10 +40899,12 @@ var ts; if (ts.isJsxSpreadAttribute(attrs[0])) { segments.unshift(ts.createObjectLiteral()); } - objectProperties = ts.singleOrUndefined(segments) - || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } } - var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -36949,7 +40926,7 @@ var ts; var decoded = tryDecodeEntities(node.text); return decoded ? ts.createLiteral(decoded, node) : node; } - else if (node.kind === 248) { + else if (node.kind === 252) { return visitJsxExpression(node); } else { @@ -37014,16 +40991,16 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 241) { + if (node.kind === 246) { return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_37 = node.tagName; + if (ts.isIdentifier(name_37) && ts.isIntrinsicJsxName(name_37.text)) { + return ts.createLiteral(name_37.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_37); } } } @@ -37041,330 +41018,585 @@ var ts; } } ts.transformJsx = transformJsx; - function createEntitiesMap() { - return ts.createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + var entities = ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); })(ts || (ts = {})); var ts; (function (ts) { - function transformES7(context) { + function transformES2017(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var currentSourceFile; + var enabledSubstitutions; + var currentSuperContainer; + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16) === 0) { + return node; + } + switch (node.kind) { + case 119: + return undefined; + case 189: + return visitAwaitExpression(node); + case 149: + return visitMethodDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 185; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, asyncSuperHelper); + } + } + return block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements)); + } + return expression; + } + } + function transformFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); + var declarations = endLexicalEnvironment(); + return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(179); + context.enableSubstitution(177); + context.enableSubstitution(178); + context.enableEmitNotification(226); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(150); + } + } + function substituteExpression(node) { + switch (node.kind) { + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); + case 179: + if (enabledSubstitutions & 1) { + return substituteCallExpression(node); + } + break; + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 226 + || kind === 150 + || kind === 149 + || kind === 151 + || kind === 152; + } + function onEmitNode(emitContext, node, emitCallback) { + if (enabledSubstitutions & 1 && isSuperContainer(node)) { + var savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformES2017 = transformES2017; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(38), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: "\n const _super = name => super[name];" + }; + var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if (node.transformFlags & 16) { - return visitorWorker(node); - } - else if (node.transformFlags & 32) { - return ts.visitEachChild(node, visitor, context); - } - else { + if ((node.transformFlags & 32) === 0) { return node; } - } - function visitorWorker(node) { switch (node.kind) { - case 187: + case 192: return visitBinaryExpression(node); default: - ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } function visitBinaryExpression(node) { - var left = ts.visitNode(node.left, visitor, ts.isExpression); - var right = ts.visitNode(node.right, visitor, ts.isExpression); - if (node.operatorToken.kind === 60) { - var target = void 0; - var value = void 0; - if (ts.isElementAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); - value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); - } - else if (ts.isPropertyAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); - value = ts.createPropertyAccess(expressionTemp, left.name, left); - } - else { - target = left; - value = left; - } - return ts.createAssignment(target, ts.createMathPow(value, right, node), node); - } - else if (node.operatorToken.kind === 38) { - return ts.createMathPow(left, right, node); - } - else { - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + switch (node.operatorToken.kind) { + case 61: + return visitExponentiationAssignmentExpression(node); + case 39: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); } } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + function visitExponentiationExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, node); + } } - ts.transformES7 = transformES7; + ts.transformES2016 = transformES2016; })(ts || (ts = {})); var ts; (function (ts) { - function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37380,13 +41612,21 @@ var ts; var enclosingFunction; var enclosingNonArrowFunction; var enclosingNonAsyncFunctionBody; + var isInConstructorWithCapturedSuper; var convertedLoopState; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; - return ts.visitNode(node, visitor, ts.isSourceFile); + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + return visited; } function visitor(node) { return saveStateAndInvoke(node, dispatcher); @@ -37406,11 +41646,14 @@ var ts; var savedCurrentParent = currentParent; var savedCurrentNode = currentNode; var savedConvertedLoopState = convertedLoopState; + var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; if (ts.nodeStartsNewLexicalEnvironment(node)) { + isInConstructorWithCapturedSuper = false; convertedLoopState = undefined; } onBeforeVisitNode(node); var visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; convertedLoopState = savedConvertedLoopState; enclosingFunction = savedEnclosingFunction; enclosingNonArrowFunction = savedEnclosingNonArrowFunction; @@ -37422,16 +41665,57 @@ var ts; currentNode = savedCurrentNode; return visited; } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 185) { + enclosingNonArrowFunction = currentNode; + if (!(ts.getEmitFlags(currentNode) & 131072)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 205: + enclosingVariableStatement = currentNode; + break; + case 224: + case 223: + case 174: + case 172: + case 173: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return isInConstructorWithCapturedSuper && node.kind === 216 && !node.expression; + } function shouldCheckNode(node) { return (node.transformFlags & 64) !== 0 || - node.kind === 214 || + node.kind === 219 || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); } function visitorWorker(node) { - if (shouldCheckNode(node)) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { return visitJavaScript(node); } - else if (node.transformFlags & 128) { + else if (node.transformFlags & 128 || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) { return ts.visitEachChild(node, visitor, context); } else { @@ -37450,18 +41734,19 @@ var ts; } function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 211: + case 216: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; return visitReturnStatement(node); - case 200: + case 205: return visitVariableStatement(node); - case 213: + case 218: return visitSwitchStatement(node); - case 210: - case 209: + case 215: + case 214: return visitBreakOrContinueStatement(node); - case 97: + case 98: return visitThisKeyword(node); - case 69: + case 70: return visitIdentifier(node); default: return ts.visitEachChild(node, visitor, context); @@ -37469,111 +41754,90 @@ var ts; } function visitJavaScript(node) { switch (node.kind) { - case 82: - return node; - case 221: + case 114: + return undefined; + case 226: return visitClassDeclaration(node); - case 192: + case 197: return visitClassExpression(node); - case 142: + case 144: return visitParameter(node); - case 220: + case 225: return visitFunctionDeclaration(node); - case 180: + case 185: return visitArrowFunction(node); - case 179: + case 184: return visitFunctionExpression(node); - case 218: + case 223: return visitVariableDeclaration(node); - case 69: + case 70: return visitIdentifier(node); - case 219: + case 224: return visitVariableDeclarationList(node); - case 214: + case 219: return visitLabeledStatement(node); - case 204: + case 209: return visitDoStatement(node); - case 205: + case 210: return visitWhileStatement(node); - case 206: + case 211: return visitForStatement(node); - case 207: + case 212: return visitForInStatement(node); - case 208: + case 213: return visitForOfStatement(node); - case 202: + case 207: return visitExpressionStatement(node); - case 171: + case 176: return visitObjectLiteralExpression(node); - case 254: + case 256: + return visitCatchClause(node); + case 258: return visitShorthandPropertyAssignment(node); - case 170: - return visitArrayLiteralExpression(node); - case 174: - return visitCallExpression(node); case 175: + return visitArrayLiteralExpression(node); + case 179: + return visitCallExpression(node); + case 180: return visitNewExpression(node); - case 178: + case 183: return visitParenthesizedExpression(node, true); - case 187: + case 192: return visitBinaryExpression(node, true); - case 11: case 12: case 13: case 14: + case 15: return visitTemplateLiteral(node); - case 176: + case 181: return visitTaggedTemplateExpression(node); - case 189: + case 194: return visitTemplateExpression(node); - case 190: + case 195: return visitYieldExpression(node); - case 95: - return visitSuperKeyword(node); - case 190: + case 196: + return visitSpreadElement(node); + case 96: + return visitSuperKeyword(); + case 195: return ts.visitEachChild(node, visitor, context); - case 147: + case 149: return visitMethodDeclaration(node); - case 256: - return visitSourceFileNode(node); - case 200: + case 205: return visitVariableStatement(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function onBeforeVisitNode(node) { - if (currentNode) { - if (ts.isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - if (ts.isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== 180) { - enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - switch (currentNode.kind) { - case 200: - enclosingVariableStatement = currentNode; - break; - case 219: - case 218: - case 169: - case 167: - case 168: - break; - default: - enclosingVariableStatement = undefined; - } - } - currentParent = currentNode; - currentNode = node; + function visitSourceFile(node) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); } function visitSwitchStatement(node) { ts.Debug.assert(convertedLoopState !== undefined); @@ -37594,7 +41858,7 @@ var ts; } function visitThisKeyword(node) { ts.Debug.assert(convertedLoopState !== undefined); - if (enclosingFunction && enclosingFunction.kind === 180) { + if (enclosingFunction && enclosingFunction.kind === 185) { convertedLoopState.containsLexicalThis = true; return node; } @@ -37614,13 +41878,13 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; + var jump = node.kind === 215 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 210) { + if (node.kind === 215) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -37630,7 +41894,7 @@ var ts; } } else { - if (node.kind === 210) { + if (node.kind === 215) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -37649,10 +41913,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 24, copyExpr); + expr = ts.createBinary(expr, 25, copyExpr); } } - returnExpression = ts.createBinary(expr, 24, returnExpression); + returnExpression = ts.createBinary(expr, 25, returnExpression); } return ts.createReturn(returnExpression); } @@ -37660,26 +41924,26 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitClassDeclaration(node) { - var modifierFlags = ts.getModifierFlags(node); - var isExported = modifierFlags & 1; - var isDefault = modifierFlags & 512; - var modifiers = isExported && !isDefault - ? ts.filter(node.modifiers, isExportModifier) - : undefined; - var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) - ]), node); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, true), undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([variable]), node); ts.setOriginalNode(statement, node); ts.startOnNewLine(statement); - if (isExported && isDefault) { - var statements = [statement]; - statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); - return statements; + statements.push(statement); + if (ts.hasModifier(node, 1)) { + var exportStatement = ts.hasModifier(node, 512) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); } - return statement; - } - function isExportModifier(node) { - return node.kind === 82; + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 2097152) === 0) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 2097152); + } + return ts.singleOrMany(statements); } function visitClassExpression(node) { return transformClassLikeDeclarationToExpression(node); @@ -37689,16 +41953,16 @@ var ts; enableSubstitutionsForBlockScopedBindings(); } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (ts.getEmitFlags(node) & 32768) { + ts.setEmitFlags(classFunction, 32768); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 1536); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 1536); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37709,83 +41973,161 @@ var ts; addExtendsHelperIfNeeded(statements, node, extendsClauseElement); addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); - var localName = getLocalName(node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 17); + var localName = ts.getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 1536); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 1536); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); + statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { - if (constructor && !hasSynthesizedSuper) { - return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); - } - return []; + return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; - startLexicalEnvironment(); + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { + isInConstructorWithCapturedSuper = superCaptureStatus === 1; + return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); + }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 1536); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 216) { + return true; } + else if (statement.kind === 208) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 204) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 207 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (16384 | 32768))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 192 + || superCallExpression.left.kind !== 179) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); + statements.push(returnStatement); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { return undefined; } else if (ts.isBindingPattern(node.name)) { - return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, ts.getGeneratedNameForNode(node), undefined, undefined, undefined, node), node); } else if (node.initializer) { - return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, node.name, undefined, undefined, undefined, node), node); } else { return node; } } function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536) !== 0; + return (node.transformFlags & 131072) !== 0; } function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { @@ -37793,38 +42135,38 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) - ], parameter), 32 | 1024 | 12288), undefined, parameter); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer)), parameter)) + ], parameter), 1 | 32 | 384), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 384 | 32 | 524288); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 70 && !inConstructorWithSynthesizedSuper; } function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { var parameter = ts.lastOrUndefined(node.parameters); @@ -37832,51 +42174,56 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 48); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ]), parameter), 8388608)); + ]), parameter), 524288)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ - ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 524288); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + if (node.transformFlags & 32768 && node.kind !== 185) { + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 198: + case 203: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 147: + case 149: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); break; - case 149: - case 150: + case 151: + case 152: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); } break; - case 148: + case 150: break; default: ts.Debug.failBadSyntaxKind(node); @@ -37888,43 +42235,46 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); - var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); - var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); + var memberFunction = transformFunctionLikeToExpression(member, member, undefined); + ts.setEmitFlags(memberFunction, 1536); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 48); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 1536 | 32); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 1536 | 16); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37939,25 +42289,30 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 8192) { + if (node.transformFlags & 16384) { enableSubstitutionsForCapturedThis(); } - var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8); return func; } function visitFunctionExpression(node) { - return transformFunctionLikeToExpression(node, node, node.name); + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); } function visitFunctionDeclaration(node) { - return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); } function transformFunctionLikeToExpression(node, location, name) { var savedContainingNonArrowFunction = enclosingNonArrowFunction; - if (node.kind !== 180) { + if (node.kind !== 185) { enclosingNonArrowFunction = node; } - var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + var expression = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); enclosingNonArrowFunction = savedContainingNonArrowFunction; return expression; } @@ -37969,7 +42324,7 @@ var ts; var statements = []; var body = node.body; var statementOffset; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (ts.isBlock(body)) { statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); } @@ -37987,7 +42342,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 180); + ts.Debug.assert(node.kind === 185); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -38000,48 +42355,49 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 384 | 32 | 1024); statements.push(returnStatement); closeBraceLocation = body; } - var lexicalEnvironment = endLexicalEnvironment(); + var lexicalEnvironment = context.endLexicalEnvironment(); ts.addRange(statements, lexicalEnvironment); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 1); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 17, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; } function visitExpressionStatement(node) { switch (node.expression.kind) { - case 178: + case 183: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 187: + case 192: return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); } return ts.visitEachChild(node, visitor, context); } function visitParenthesizedExpression(node, needsDestructuringValue) { - if (needsDestructuringValue) { + if (!needsDestructuringValue) { switch (node.expression.kind) { - case 178: - return ts.createParen(visitParenthesizedExpression(node.expression, true), node); - case 187: - return ts.createParen(visitBinaryExpression(node.expression, true), node); + case 183: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); + case 192: + return ts.updateParen(node, visitBinaryExpression(node.expression, false)); } } return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node, needsDestructuringValue) { - ts.Debug.assert(ts.isDestructuringAssignment(node)); - return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0, needsDestructuringValue); + } } function visitVariableStatement(node) { if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { @@ -38052,16 +42408,16 @@ var ts; if (decl.initializer) { var assignment = void 0; if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 57, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } } if (assignments) { - return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25, acc); }), node); } else { return undefined; @@ -38078,13 +42434,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 8388608 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38098,8 +42454,8 @@ var ts; && ts.isBlock(enclosingBlockScopeContainer) && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); var emitExplicitInitializer = !emittedAsTopLevel - && enclosingBlockScopeContainer.kind !== 207 - && enclosingBlockScopeContainer.kind !== 208 + && enclosingBlockScopeContainer.kind !== 212 + && enclosingBlockScopeContainer.kind !== 213 && (!resolver.isDeclarationWithCollidingName(node) || (isDeclaredInLoop && !isCapturedInFunction @@ -38112,17 +42468,17 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_5 = ts.getMutableClone(node); - clone_5.initializer = ts.createVoidZero(); - return clone_5; + var clone_3 = ts.getMutableClone(node); + clone_3.initializer = ts.createVoidZero(); + return clone_3; } return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { if (ts.isBindingPattern(node.name)) { - var recordTempVariablesInLine = !enclosingVariableStatement - || !ts.hasModifier(enclosingVariableStatement, 1); - return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + var hoistTempVariables = enclosingVariableStatement + && ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenDestructuringBinding(node, visitor, context, 0, undefined, hoistTempVariables); } return ts.visitEachChild(node, visitor, context); } @@ -38165,33 +42521,34 @@ var ts; var initializer = node.initializer; var statements = []; var counter = ts.createLoopVariable(); - var rhsReference = expression.kind === 69 + var rhsReference = expression.kind === 70 ? ts.createUniqueName(expression.text) : ts.createTempVariable(undefined); + var elementAccess = ts.createElementAccess(rhsReference, counter); if (ts.isVariableDeclarationList(initializer)) { if (initializer.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, elementAccess); var declarationList = ts.createVariableDeclarationList(declarations, initializer); ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) - ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); + ], ts.moveRangePos(initializer, -1)), initializer), ts.moveRangeEnd(initializer, -1))); } } else { - var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + var assignment = ts.createAssignment(initializer, elementAccess); if (ts.isDestructuringAssignment(assignment)) { - statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0))); } else { assignment.end = initializer.end; @@ -38214,14 +42571,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 48 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.setEmitFlags(body, 48 | 384); + var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) - ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ], node.expression), 1048576), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + ts.setEmitFlags(forStatement, 256); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38230,8 +42587,8 @@ var ts; var numInitialProperties = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if (property.transformFlags & 4194304 - || property.name.kind === 140) { + if (property.transformFlags & 16777216 + || property.name.kind === 142) { numInitialProperties = i; break; } @@ -38239,7 +42596,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 32768)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38257,7 +42614,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 69) { + if (node.kind === 70) { state.hoistedLocalVariables.push(node); } else { @@ -38286,11 +42643,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 206: - case 207: - case 208: + case 211: + case 212: + case 213: var initializer = node.initializer; - if (initializer && initializer.kind === 219) { + if (initializer && initializer.kind === 224) { loopInitializer = initializer; } break; @@ -38316,30 +42673,35 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { - var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_3); - loopBody = ts.createBlock(statements_3, undefined, true); + if (loopOutParameters.length || lexicalEnvironment) { + var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); + loopBody = ts.createBlock(statements_4, undefined, true); } if (!ts.isBlock(loopBody)) { loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 - && (node.statement.transformFlags & 4194304) !== 0; + && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072) !== 0 + && (node.statement.transformFlags & 16777216) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { - loopBodyFlags |= 256; + loopBodyFlags |= 8; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 2097152; + loopBodyFlags |= 131072; } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ])); + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, isAsyncBlockContainingAwait ? ts.createToken(38) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ]), 1048576)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; if (currentState.argumentsName) { @@ -38366,8 +42728,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +42738,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38397,7 +42759,7 @@ var ts; loop.transformFlags = 0; ts.aggregateTransformFlags(loop); } - statements.push(currentParent.kind === 214 + statements.push(currentParent.kind === 219 ? ts.createLabel(currentParent.label, loop) : loop); return statements; @@ -38405,7 +42767,7 @@ var ts; function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 56, source); + return ts.createBinary(target, 57, source); } function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { @@ -38420,7 +42782,7 @@ var ts; !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38), call) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); copyOutParameters(state.loopOutParameters, 0, statements); @@ -38439,10 +42801,10 @@ var ts; else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 33, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 33, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; @@ -38496,7 +42858,7 @@ var ts; } } else { - loopParameters.push(ts.createParameter(name)); + loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { var outParamName = ts.createUniqueName("out_" + name.text); loopOutParameters.push({ originalName: name, outParamName: outParamName }); @@ -38509,21 +42871,21 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 149: - case 150: + case 151: + case 152: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); } break; - case 253: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + case 257: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 254: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + case 258: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 147: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + case 149: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); break; default: ts.Debug.failBadSyntaxKind(node); @@ -38531,31 +42893,44 @@ var ts; } } } - function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } - function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } - function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } + function visitCatchClause(node) { + ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name)); + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0, temp); + var list = ts.createVariableDeclarationList(vars, node.variableDeclaration, node.variableDeclaration.flags); + var destructure = ts.createVariableStatement(undefined, list); + return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 512 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,44 +42943,66 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + if (node.expression.kind === 96) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall; + if (node.transformFlags & 524288) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 96) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { - ts.Debug.assert((node.transformFlags & 262144) !== 0); + ts.Debug.assert((node.transformFlags & 524288) !== 0); var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { var numElements = elements.length; - var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); })); if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 + return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 ? ts.createArraySlice(segments[0]) : segments[0]; } return ts.createArrayConcat(segments.shift(), segments); } - function partitionSpreadElement(node) { - return ts.isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; + function partitionSpread(node) { + return ts.isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; } - function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.map(chunk, visitExpressionOfSpreadElement); + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); } - function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); } - function visitExpressionOfSpreadElement(node) { + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitExpressionOfSpread(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } function visitTemplateLiteral(node) { @@ -38640,7 +43037,7 @@ var ts; } function getRawLiteral(node) { var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - var isLast = node.kind === 11 || node.kind === 14; + var isLast = node.kind === 12 || node.kind === 15; text = text.substring(1, text.length - (isLast ? 1 : 2)); text = text.replace(/\r\n?/g, "\n"); return ts.createLiteral(text, node); @@ -38674,56 +43071,44 @@ var ts; } } } - function visitSuperKeyword(node) { + function visitSuperKeyword() { return enclosingNonAsyncFunctionBody && ts.isClassElement(enclosingNonAsyncFunctionBody) && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) - && currentParent.kind !== 174 + && currentParent.kind !== 179 ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") : ts.createIdentifier("_super"); } - function visitSourceFileNode(node) { - var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; - var statements = []; - startLexicalEnvironment(); - ts.addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); - ts.addRange(statements, endLexicalEnvironment()); - var clone = ts.getMutableClone(node); - clone.statements = ts.createNodeArray(statements, node.statements); - return clone; - } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(69); + context.enableSubstitution(70); } } function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(97); - context.enableEmitNotification(148); - context.enableEmitNotification(147); - context.enableEmitNotification(149); + context.enableSubstitution(98); context.enableEmitNotification(150); - context.enableEmitNotification(180); - context.enableEmitNotification(179); - context.enableEmitNotification(220); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(185); + context.enableEmitNotification(184); + context.enableEmitNotification(225); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38743,10 +43128,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 169: - case 221: - case 224: - case 218: + case 174: + case 226: + case 229: + case 223: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -38754,9 +43139,9 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - case 97: + case 98: return substituteThisKeyword(node); } return node; @@ -38773,64 +43158,56 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 8) { return ts.createIdentifier("_this", node); } return node; } - function getLocalName(node, allowComments, allowSourceMaps) { - return getDeclarationName(node, allowComments, allowSourceMaps, 262144); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); - } - return name_35; - } - return ts.getGeneratedNameForNode(node); - } function getClassMemberPrefix(node, member) { - var expression = getLocalName(node); + var expression = ts.getLocalName(node); return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { return false; } - var parameter = ts.singleOrUndefined(constructor.parameters); - if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + if (ts.some(constructor.parameters)) { return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 96) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196) { return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression === parameter.name; + return ts.isIdentifier(expression) && expression.text === "arguments"; } } - ts.transformES6 = transformES6; + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), undefined, [ + name, + ts.createIdentifier("_super") + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -38842,7 +43219,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,12 +43253,15 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (node.transformFlags & 1024) { - currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); - currentSourceFile = undefined; + if (ts.isDeclarationFile(node) + || (node.transformFlags & 512) === 0) { + return node; } - return node; + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function visitor(node) { var transformFlags = node.transformFlags; @@ -38891,10 +43271,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 512) { + else if (transformFlags & 256) { return visitGenerator(node); } - else if (transformFlags & 1024) { + else if (transformFlags & 512) { return ts.visitEachChild(node, visitor, context); } else { @@ -38903,13 +43283,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 204: + case 209: return visitDoStatement(node); - case 205: + case 210: return visitWhileStatement(node); - case 213: + case 218: return visitSwitchStatement(node); - case 214: + case 219: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -38917,30 +43297,30 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); - case 149: - case 150: + case 151: + case 152: return visitAccessorDeclaration(node); - case 200: + case 205: return visitVariableStatement(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 210: - return visitBreakStatement(node); - case 209: - return visitContinueStatement(node); case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 215: + return visitBreakStatement(node); + case 214: + return visitContinueStatement(node); + case 216: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 | 8388608)) { + else if (node.transformFlags & (512 | 33554432)) { return ts.visitEachChild(node, visitor, context); } else { @@ -38950,21 +43330,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 187: + case 192: return visitBinaryExpression(node); - case 188: + case 193: return visitConditionalExpression(node); - case 190: + case 195: return visitYieldExpression(node); - case 170: - return visitArrayLiteralExpression(node); - case 171: - return visitObjectLiteralExpression(node); - case 173: - return visitElementAccessExpression(node); - case 174: - return visitCallExpression(node); case 175: + return visitArrayLiteralExpression(node); + case 176: + return visitObjectLiteralExpression(node); + case 178: + return visitElementAccessExpression(node); + case 179: + return visitCallExpression(node); + case 180: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -38972,9 +43352,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -38982,8 +43362,8 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -39003,8 +43383,8 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -39034,6 +43414,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +43427,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39053,7 +43435,7 @@ var ts; operationArguments = undefined; operationLocations = undefined; state = ts.createTempVariable(undefined); - startLexicalEnvironment(); + resumeLexicalEnvironment(); var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); @@ -39064,6 +43446,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39074,12 +43457,12 @@ var ts; return ts.createBlock(statements, body, body.multiLine); } function visitVariableStatement(node) { - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 524288) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39104,23 +43487,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 57 - && kind <= 68; + return kind >= 58 + && kind <= 69; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 57: return 35; case 58: return 36; case 59: return 37; case 60: return 38; case 61: return 39; case 62: return 40; - case 63: return 43; + case 63: return 41; case 64: return 44; case 65: return 45; case 66: return 46; case 67: return 47; case 68: return 48; + case 69: return 49; } } function visitRightAssociativeBinaryExpression(node) { @@ -39128,10 +43511,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 172: + case 177: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 173: + case 178: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -39140,7 +43523,7 @@ var ts; } var operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + return ts.createBinary(target, 57, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); } else { return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); @@ -39153,13 +43536,13 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 24) { + else if (node.operatorToken.kind === 25) { return visitCommaExpression(node); } - var clone_6 = ts.getMutableClone(node); - clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_6; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -39167,7 +43550,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { emitBreakWhenFalse(resultLabel, resultLocal, node.left); } else { @@ -39183,7 +43566,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 25) { visit(node.left); visit(node.right); } @@ -39224,26 +43607,30 @@ var ts; return createGeneratorResume(); } function visitArrayLiteralExpression(node) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, undefined, undefined, node.multiLine); } - function visitElements(elements, multiLine) { + function visitElements(elements, leadingElement, location, multiLine) { var numInitialElements = countInitialNodesWithoutYield(elements); var temp = declareLocal(); var hasAssignedTemp = false; if (numInitialElements > 0) { - emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; hasAssignedTemp = true; } var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine); function reduceElement(expressions, element) { if (containsYield(element) && expressions.length > 0) { emitAssignment(temp, hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions)); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, undefined, multiLine)); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } expressions.push(ts.visitNode(element, visitor, ts.isExpression)); @@ -39277,24 +43664,24 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_7 = ts.getMutableClone(node); - clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_7; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, ts.createVoidZero())), undefined, [], node), node); } return ts.visitEachChild(node, visitor, context); } @@ -39323,35 +43710,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 199: - return transformAndEmitBlock(node); - case 202: - return transformAndEmitExpressionStatement(node); - case 203: - return transformAndEmitIfStatement(node); case 204: - return transformAndEmitDoStatement(node); - case 205: - return transformAndEmitWhileStatement(node); - case 206: - return transformAndEmitForStatement(node); + return transformAndEmitBlock(node); case 207: - return transformAndEmitForInStatement(node); + return transformAndEmitExpressionStatement(node); + case 208: + return transformAndEmitIfStatement(node); case 209: - return transformAndEmitContinueStatement(node); + return transformAndEmitDoStatement(node); case 210: - return transformAndEmitBreakStatement(node); + return transformAndEmitWhileStatement(node); case 211: - return transformAndEmitReturnStatement(node); + return transformAndEmitForStatement(node); case 212: - return transformAndEmitWithStatement(node); - case 213: - return transformAndEmitSwitchStatement(node); + return transformAndEmitForInStatement(node); case 214: - return transformAndEmitLabeledStatement(node); + return transformAndEmitContinueStatement(node); case 215: - return transformAndEmitThrowStatement(node); + return transformAndEmitBreakStatement(node); case 216: + return transformAndEmitReturnStatement(node); + case 217: + return transformAndEmitWithStatement(node); + case 218: + return transformAndEmitSwitchStatement(node); + case 219: + return transformAndEmitLabeledStatement(node); + case 220: + return transformAndEmitThrowStatement(node); + case 221: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); @@ -39635,7 +44022,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 250 && defaultClauseIndex === -1) { + if (clause.kind === 254 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -39645,7 +44032,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 249) { + if (clause.kind === 253) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -39736,7 +44123,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 4194304) !== 0; + return node && (node.transformFlags & 16777216) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -39747,9 +44134,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,12 +44153,12 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); - return clone_8; + var name_39 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_39) { + var clone_6 = ts.getMutableClone(name_39); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -39877,7 +44264,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = ts.createMap(); - context.enableSubstitution(69); + context.enableSubstitution(70); } renamedCatchVariables[text] = true; renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -40067,7 +44454,7 @@ var ts; if (labelExpressions === undefined) { labelExpressions = []; } - var expression = ts.createSynthesizedNode(8); + var expression = ts.createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -40076,7 +44463,7 @@ var ts; } return expression; } - return ts.createNode(193); + return ts.createOmittedExpression(); } function createInstruction(instruction) { var literal = ts.createLiteral(instruction); @@ -40162,10 +44549,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ - ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) - ]); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 262144)); } function buildStatements() { if (operations) { @@ -40428,9 +44812,64 @@ var ts; } } ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]); + } + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; var _a; })(ts || (ts = {})); var ts; +(function (ts) { + function transformES5(context) { + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(177); + context.enableSubstitution(257); + return transformSourceFile; + function transformSourceFile(node) { + return node; + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.createElementAccess(node.expression, literalName, node); + } + return node; + } + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + if (token >= 71 && token <= 106) { + return ts.createLiteral(name, name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +var ts; (function (ts) { function transformModule(context) { var transformModuleDelegates = ts.createMap((_a = {}, @@ -40439,7 +44878,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40449,47 +44888,43 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableSubstitution(254); - context.enableEmitNotification(256); + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableSubstitution(258); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var bindingNameExportSpecifiersMap; - var bindingNameExportSpecifiersForFileMap = ts.createMap(); - var hasExportStarsToExportValues; + var currentModuleInfo; + var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; - var updated = transformModule_1(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; } - return node; - var _a; + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + return ts.aggregateTransformFlags(updated); } function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); addExportEqualsIfNeeded(statements, false); - var updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(updated, exportStarHelper); } return updated; } @@ -40499,83 +44934,111 @@ var ts; return transformAsynchronousModule(node, define, moduleName, true); } function transformUMDModule(node) { - var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + var define = ts.createRawExpression(umdHelper); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return updateSourceFile(node, [ + return ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter("require"), - ts.createParameter("exports") + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) - ]); + ], node.statements)); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + ts.setEmitFlags(importAliasName, 4); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(body, exportStarHelper); } return body; } function addExportEqualsIfNeeded(statements, emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (currentModuleInfo.exportEquals) { if (emitAsReturn) { - var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + var statement = ts.createReturn(currentModuleInfo.exportEquals.expression, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); statements.push(statement); } else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression), currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); statements.push(statement); } } } - function visitor(node) { + function sourceElementVisitor(node) { switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return visitExportDeclaration(node); + case 240: return visitExportAssignment(node); - case 200: + case 205: return visitVariableStatement(node); - case 220: + case 225: return visitFunctionDeclaration(node); - case 221: + case 226: return visitClassDeclaration(node); - case 202: - return visitExpressionStatement(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); default: return node; } } function visitImportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var statements = []; + var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { - statements.push(ts.createStatement(createRequireCall(node), node)); + return ts.createStatement(createRequireCall(node), node); } else { var variables = []; @@ -40588,43 +45051,60 @@ var ts; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } } - statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, undefined, languageVersion >= 2 ? 2 : 0), node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) - ]))); + ], undefined, languageVersion >= 2 ? 2 : 0))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); } - addExportImportAssignments(statements, node); return ts.singleOrMany(statements); } - function visitImportEqualsDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); } - setNodeEmitFlags(node.name, 128); - var statements = []; + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); + statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)), node)); } else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) ], undefined, languageVersion >= 2 ? 2 : 0), node)); } } else { if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)), node)); } } - addExportImportAssignments(statements, node); - return statements; + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); } function visitExportDeclaration(node) { - if (!ts.contains(externalImports, node)) { + if (!node.moduleSpecifier) { return undefined; } var generatedName = ts.getGeneratedNameForNode(node); @@ -40637,14 +45117,12 @@ var ts; } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); - } + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue), specifier)); } return ts.singleOrMany(statements); } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + else { return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) @@ -40653,207 +45131,262 @@ var ts; } } function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - var statements = []; - addExportDefault(statements, node.expression, node); - return statements; - } + if (node.isExportEquals) { + return undefined; } - return undefined; - } - function addExportDefault(statements, expression, location) { - tryAddExportDefaultCompat(statements); - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); - } - function tryAddExportDefaultCompat(statements) { - var original = ts.getOriginalNode(currentSourceFile); - ts.Debug.assert(original.kind === 256); - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === 0) { - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); - } - else { - statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) - ]) - ]))); - } - } - } - function addExportImportAssignments(statements, node) { - if (ts.isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); } else { - var names = ts.reduceEachChild(node, collectExportMembers, []); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); - } - } - } - function collectExportMembers(names, node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); - } - } - return ts.reduceEachChild(node, collectExportMembers, names); - } - function addExportMemberAssignments(statements, name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); - } - } - } - function addExportMemberAssignment(statements, node) { - if (ts.hasModifier(node, 512)) { - addExportDefault(statements, getDeclarationName(node), node); - } - else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); - } - } - function visitVariableStatement(node) { - var originalKind = ts.getOriginalNode(node).kind; - if (originalKind === 225 || - originalKind === 224 || - originalKind === 221) { - if (!ts.hasModifier(node, 1)) { - return node; - } - return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); - } - var resultStatements = []; - if (ts.hasModifier(node, 1)) { - var variables = ts.getInitializedVariables(node.declarationList); - if (variables.length > 0) { - var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - return resultStatements; - } - function addExportMemberAssignmentsForBindingName(resultStatements, name) { - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - var sourceFileId = ts.getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - function transformInitializedVariable(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); - } - else { - return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); } + return ts.singleOrMany(statements); } function visitFunctionDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); + var statements; if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); - addExportMemberAssignment(statements, node); + statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body, node), node)); } else { - statements.push(node); + statements = ts.append(statements, node); } - if (node.name) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return ts.singleOrMany(statements); } function visitClassDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); + var statements; if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); - addExportMemberAssignment(statements, node); + statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members, node), node)); } else { - statements.push(node); + statements = ts.append(statements, node); } - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return ts.singleOrMany(statements); } - function visitExpressionStatement(node) { - var original = ts.getOriginalNode(node); - var origKind = original.kind; - if (origKind === 224 || origKind === 225) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === 221) { - var classDecl = original; - if (classDecl.name) { - var statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1)) { + var modifiers = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + } + else { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name, node.name), node.initializer); + } + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } return node; } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { - var statements = [node]; - if (ts.hasModifier(original, 1) && - original.kind === 224 && - ts.isFirstDeclarationOfKind(original, 224)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } } - addExportMemberAssignments(statements, original.name); return statements; } - function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { - var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); - statements.push(transformedStatement); + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; } - function onEmitNode(node, emit) { - if (node.kind === 256) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - bindingNameExportSpecifiersMap = undefined; + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, exportSpecifier.name); + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, location, allowComments) { + if (exportName.text === "default") { + var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createExportStatement(name, value, location, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value, location) { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location); + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = ts.createMap(); + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40875,870 +45408,169 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - case 187: + case 192: return substituteBinaryExpression(node); - case 186: - case 185: + case 191: + case 190: return substituteUnaryExpression(node); } return node; } function substituteExpressionIdentifier(node) { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 261) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name_40 = importDeclaration.propertyName || importDeclaration.name; + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); + } + } + } + return node; } function substituteBinaryExpression(node) { - var left = node.left; - if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, node); } - return nestedExportAssignment; + return expression; } } return node; } function substituteUnaryExpression(node) { - var operator = node.operator; - var operand = node.operand; - if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); - var transformedUnaryExpression = void 0; - if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 ? 58 : 59), ts.createLiteral(1), node) + : node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); } - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; + return expression; } } return node; } - function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); - if ((emitFlags & 262144) === 0) { - var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); - if (container) { - if (container.kind === 256) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); - } + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; } } - return undefined; - } - function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (ts.isImportClause(declaration)) { - if (languageVersion >= 1) { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); - } - else { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); - } - } - else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); - } - else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); - } - } - } - } - return undefined; - } - function getModuleMemberName(name) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); - } - function createRequireCall(importNode) { - var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var args = []; - if (ts.isDefined(moduleName)) { - args.push(moduleName); - } - return ts.createCall(ts.createIdentifier("require"), undefined, args); - } - function createExportStatement(name, value, location) { - var statement = ts.createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - return statement; - } - function createExportAssignment(name, value) { - return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 - ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) - : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); - } - function collectAsynchronousDependencies(node, includeNonAmdDependencies) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - } - } - for (var _b = 0, externalImports_1 = externalImports; _b < externalImports_1.length; _b++) { - var importNode = externalImports_1[_b]; - var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function updateSourceFile(node, statements) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - return updated; } var _a; } ts.transformModule = transformModule; + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })"; })(ts || (ts = {})); var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableEmitNotification(256); - var exportFunctionForFileMap = []; + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); + var exportFunctionsMap = ts.createMap(); + var noSubstitutionMap = ts.createMap(); var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var exportFunctionForFile; - var contextObjectForFile; - var exportedLocalNames; - var exportedFunctionDeclarations; + var moduleInfo; + var exportFunction; + var contextObject; + var hoistedStatements; var enclosingBlockScopedContainer; - var currentParent; - var currentNode; + var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; - var updated = transformSystemModuleWorker(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - return node; - } - function transformSystemModuleWorker(node) { - ts.Debug.assert(!exportFunctionForFile); - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - exportFunctionForFile = ts.createUniqueName("exports"); - contextObjectForFile = ts.createUniqueName("context"); - exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; - var dependencyGroups = collectDependencyGroups(externalImports); - var statements = []; - addSystemModuleBody(statements, node, dependencyGroups); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); - var body = ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter(exportFunctionForFile), - ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName - ? [moduleName, dependencies, body] - : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); - var _a; - } - function addSystemModuleBody(statements, node, dependencyGroups) { - startLexicalEnvironment(); - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) - ]))); - var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); - ts.addRange(statements, endLexicalEnvironment()); - ts.addRange(statements, exportedFunctionDeclarations); - var exportStarFunction = addExportStarIfNeeded(statements); - statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ - ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) - ]), true))); - } - function addExportStarIfNeeded(statements) { - if (!hasExportStarsToExportValues) { - return; - } - if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _i = 0, externalImports_2 = externalImports; _i < externalImports_2.length; _i++) { - var externalImport = externalImports_2[_i]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return addExportStarFunction(statements, undefined); - } - } - var exportedNames = []; - if (exportedLocalNames) { - for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { - var exportedLocalName = exportedLocalNames_1[_a]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); - } - } - for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { - var externalImport = externalImports_3[_b]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { - var element = _d[_c]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); - } - } - var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) - ]))); - return addExportStarFunction(statements, exportedNamesStorageRef); - } - function generateSetters(exportStarFunction, dependencyGroups) { - var setters = []; - for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group = dependencyGroups_1[_i]; - var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); - var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); - var statements = []; - for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { - var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== undefined); - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); - break; - case 236: - ts.Debug.assert(importVariableName !== undefined); - if (entry.exportClause) { - var properties = []; - for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { - var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); - } - statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); - } - else { - statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); - } - break; - } - } - setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); - } - return ts.createArrayLiteral(setters, undefined, true); - } - function visitSourceElement(node) { - switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); - case 235: - return visitExportAssignment(node); - default: - return visitNestedNode(node); - } - } - function visitNestedNode(node) { - var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; - } - var result = visitNestedNodeWorker(node); - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return result; - } - function visitNestedNodeWorker(node) { - switch (node.kind) { - case 200: - return visitVariableStatement(node); - case 220: - return visitFunctionDeclaration(node); - case 221: - return visitClassDeclaration(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 208: - return visitForOfStatement(node); - case 204: - return visitDoStatement(node); - case 205: - return visitWhileStatement(node); - case 214: - return visitLabeledStatement(node); - case 212: - return visitWithStatement(node); - case 213: - return visitSwitchStatement(node); - case 227: - return visitCaseBlock(node); - case 249: - return visitCaseClause(node); - case 250: - return visitDefaultClause(node); - case 216: - return visitTryStatement(node); - case 252: - return visitCatchClause(node); - case 199: - return visitBlock(node); - case 202: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (node.importClause && ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitImportEqualsDeclaration(node) { - if (ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitExportDeclaration(node) { - if (!node.moduleSpecifier) { - var statements = []; - ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - return undefined; - } - function visitExportSpecifier(specifier) { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement(specifier.name, specifier.propertyName || specifier.name); - } - return undefined; - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement(ts.createLiteral("default"), node.expression); - } - } - return undefined; - } - function visitVariableStatement(node) { - var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || - enclosingBlockScopedContainer.kind === 256; - if (!shouldHoist) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { return node; } - var isExported = ts.hasModifier(node, 1); - var expressions = []; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports"); + contextObject = ts.createUniqueName("context"); + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, exportFunction), + ts.createParameter(undefined, undefined, undefined, contextObject) + ], undefined, moduleBodyBlock); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ], node.statements)), 1024); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } - if (expressions.length) { - return ts.createStatement(ts.inlineExpressions(expressions), node); - } - return undefined; - } - function transformVariable(node, isExported) { - hoistBindingElement(node, isExported); - if (!node.initializer) { - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - return ts.createAssignment(name, node.initializer); - } - else { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); - recordExportedFunctionDeclaration(node); - if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); - } - ts.setOriginalNode(newNode, node); - node = newNode; - } - hoistFunctionDeclaration(node); - return undefined; - } - function visitExpressionStatement(node) { - var originalNode = ts.getOriginalNode(node); - if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); - if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); - } - return [ - node, - createExportStatement(name_41, name_41) - ]; - } - return node; - } - function visitClassDeclaration(node) { - var name = getDeclarationName(node); - hoistVariableDeclaration(name); - var statements = []; - statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); - if (ts.hasModifier(node, 1)) { - if (!ts.hasModifier(node, 512)) { - recordExportName(name); - } - statements.push(createDeclarationExport(node)); - } - return statements; - } - function shouldHoistLoopInitializer(node) { - return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; - } - function visitForStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var expressions = []; - for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, false); - if (visited) { - expressions.push(visited); - } - } - ; - return ts.createFor(expressions.length - ? ts.inlineExpressions(expressions) - : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function transformForBinding(node) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, false); - var name = firstDeclaration.name; - return ts.isIdentifier(name) - ? name - : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); - } - function visitForInStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitForOfStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitDoStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWhileStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitLabeledStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWithStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitSwitchStatement(node) { - var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); - if (caseBlock !== node.caseBlock) { - var updated = ts.getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; - } - function visitCaseBlock(node) { - var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); - if (clauses !== node.clauses) { - var updated = ts.getMutableClone(node); - updated.clauses = clauses; - return updated; - } - return node; - } - function visitCaseClause(node) { - var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); - if (statements !== node.statements) { - var updated = ts.getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; - } - function visitDefaultClause(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitTryStatement(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitCatchClause(node) { - var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); - if (block !== node.block) { - var updated = ts.getMutableClone(node); - updated.block = block; - return updated; - } - return node; - } - function visitBlock(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function onEmitNode(node, emit) { - if (node.kind === 256) { - exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - exportFunctionForFile = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69: - return substituteExpressionIdentifier(node); - case 187: - return substituteBinaryExpression(node); - case 185: - case 186: - return substituteUnaryExpression(node); - } - return node; - } - function substituteExpressionIdentifier(node) { - var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - var importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; - } - } - return node; - } - function substituteBinaryExpression(node) { - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); - } - return node; - } - function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); - var left = node.left; - switch (left.kind) { - case 69: - var exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); - } - break; - case 171: - case 170: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - return node; - } - function isExportedBinding(name) { - var container = resolver.getReferencedExportContainer(name); - return container && container.kind === 256; - } - function hasExportedReferenceInDestructuringPattern(node) { - switch (node.kind) { - case 69: - return isExportedBinding(node); - case 171: - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var property = _a[_i]; - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - break; - case 170: - for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - break; - } - return false; - } - function hasExportedReferenceInObjectDestructuringElement(node) { - if (ts.isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (ts.isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - function hasExportedReferenceInArrayDestructuringElement(node) { - if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - function hasExportedReferenceInDestructuringElement(node) { - if (ts.isBinaryExpression(node)) { - var left = node.left; - return node.operatorToken.kind === 56 - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (ts.isIdentifier(node)) { - return isExportedBinding(node); - } - else if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - function isDestructuringPattern(node) { - var kind = node.kind; - return kind === 69 - || kind === 171 - || kind === 170; - } - function substituteDestructuring(node) { - return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); - } - function substituteUnaryExpression(node) { - var operand = node.operand; - var operator = node.operator; - var substitute = ts.isIdentifier(operand) && - (node.kind === 186 || - (node.kind === 185 && (operator === 41 || operator === 42))); - if (substitute) { - var exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); - var call = createExportExpression(operand, expr); - if (node.kind === 185) { - return call; - } - else { - return operator === 41 - ? ts.createSubtract(call, ts.createLiteral(1)) - : ts.createAdd(call, ts.createLiteral(1)); - } - } - } - return node; - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function addExportStarFunction(statements, localNames) { - var exportStarFunction = ts.createUniqueName("exportStar"); - var m = ts.createIdentifier("m"); - var n = ts.createIdentifier("n"); - var exports = ts.createIdentifier("exports"); - var condition = ts.createStrictInequality(n, ts.createLiteral("default")); - if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); - } - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ - ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) - ])), - ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, undefined) - ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) - ])), - ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) - ], undefined, true))); - return exportStarFunction; - } - function createExportExpression(name, value) { - var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; - return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); - } - function createExportStatement(name, value) { - return ts.createStatement(createExportExpression(name, value)); - } - function createDeclarationExport(node) { - var declarationName = getDeclarationName(node); - var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - function createImportBinding(importDeclaration) { - var importAlias; - var name; - if (ts.isImportClause(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); - name = ts.createIdentifier("default"); - } - else if (ts.isImportSpecifier(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - if (name.originalKeywordKind && languageVersion === 0) { - return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); - } - else { - return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); } function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); @@ -41750,7 +45582,6 @@ var ts; if (ts.hasProperty(groupIndices, text)) { var groupIndex = groupIndices[text]; dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; } else { groupIndices[text] = dependencyGroups.length; @@ -41762,171 +45593,808 @@ var ts; } return dependencyGroups; } - function getNameOfDependencyGroup(dependencyGroup) { - return dependencyGroup.name; + function createSystemModuleBody(node, dependencyGroups) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true); + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + ts.addRange(statements, hoistedStatements); + ts.addRange(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + return ts.createBlock(statements, undefined, true); } - function recordExportName(name) { - if (!exportedLocalNames) { - exportedLocalNames = []; - } - exportedLocalNames.push(name); - } - function recordExportedFunctionDeclaration(node) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; - } - exportedFunctionDeclarations.push(createDeclarationExport(node)); - } - function hoistBindingElement(node, isExported) { - if (ts.isOmittedExpression(node)) { + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { return; } - var name = node.name; - if (ts.isIdentifier(name)) { - hoistVariableDeclaration(ts.getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); + if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 241 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + var exportStarFunction_1 = createExportStarFunction(undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; } } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.text === "default") { + continue; + } + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true))); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 241) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), undefined, [n]))); + } + return ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(undefined, undefined, undefined, m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1) + ])), + ts.createStatement(ts.createCall(exportFunction, undefined, [exports])) + ], undefined, true)); + } + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 235: + if (!entry.importClause) { + break; + } + case 234: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 241: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return undefined; + case 240: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); } } - function hoistExportedBindingElement(node) { - hoistBindingElement(node, true); + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); } - function hoistNonExportedBindingElement(node) { - hoistBindingElement(node, false); + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); } - function updateSourceFile(node, statements, nodeEmitFlags) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); - return updated; + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, true); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + function visitClassDeclaration(node) { + var statements; + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement), node)), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + if (isMarkedDeclaration) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, false); + } + return ts.singleOrMany(statements); + } + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + function shouldHoistVariableDeclarationList(node) { + return (ts.getEmitFlags(node) & 1048576) === 0 + && (enclosingBlockScopedContainer.kind === 261 + || (ts.getOriginalNode(node).flags & 3) === 0); + } + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + } + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, true); + } + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, false); + } + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location))) + : preventSubstitution(ts.createAssignment(name, value, location)); + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = decl.name.text; + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = exportName.text; + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + function createExportStatement(name, value, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + return ts.createCall(exportFunction, undefined, [exportName, value]); + } + function nestedElementVisitor(node) { + switch (node.kind) { + case 205: + return visitVariableStatement(node); + case 225: + return visitFunctionDeclaration(node); + case 226: + return visitClassDeclaration(node); + case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 213: + return visitForOfStatement(node); + case 209: + return visitDoStatement(node); + case 210: + return visitWhileStatement(node); + case 219: + return visitLabeledStatement(node); + case 217: + return visitWithStatement(node); + case 218: + return visitSwitchStatement(node); + case 232: + return visitCaseBlock(node); + case 253: + return visitCaseClause(node); + case 254: + return visitDefaultClause(node); + case 221: + return visitTryStatement(node); + case 256: + return visitCatchClause(node); + case 204: + return visitBlock(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); + default: + return destructuringVisitor(node); + } + } + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + } + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function destructuringVisitor(node) { + if (node.transformFlags & 1024 + && node.kind === 192) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & 2048) { + return ts.visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + } + return ts.visitEachChild(node, destructuringVisitor, context); + } + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 261; + } + else { + return false; + } + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 70: + return substituteExpressionIdentifier(node); + case 192: + return substituteBinaryExpression(node); + case 190: + case 191: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createPrefix(node.operator, node.operand, node) + : node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 191) { + expression = node.operator === 42 + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, false); + if (exportContainer && exportContainer.kind === 261) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = ts.createMap(); + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; } } ts.transformSystemModule = transformSystemModule; })(ts || (ts = {})); var ts; (function (ts) { - function transformES6Module(context) { + function transformES2015Module(context) { var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(261); + context.enableSubstitution(70); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return ts.visitEachChild(node, visitor, context); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements); + ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } } return node; } function visitor(node) { switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 231: - return visitImportClause(node); - case 233: - case 232: - return visitNamedBindings(node); case 234: - return visitImportSpecifier(node); - case 235: + return undefined; + case 240: return visitExportAssignment(node); - case 236: - return visitExportDeclaration(node); - case 237: - return visitNamedExports(node); - case 238: - return visitExportSpecifier(node); } return node; } function visitExportAssignment(node) { - if (node.isExportEquals) { - return undefined; - } - var original = ts.getOriginalNode(node); - return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + return node.isExportEquals ? undefined : node; } - function visitExportDeclaration(node) { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + function onEmitNode(emitContext, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; + else { + previousOnEmitNode(emitContext, node, emitCallback); } - var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); - if (node.exportClause === newExportClause) { - return node; + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isIdentifier(node) && emitContext === 1) { + return substituteExpressionIdentifier(node); } - return newExportClause - ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) - : undefined; + return node; } - function visitNamedExports(node) { - var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? ts.createNamedExports(newExports) : undefined; - } - function visitExportSpecifier(node) { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - function visitImportEqualsDeclaration(node) { - return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - function visitImportDeclaration(node) { - if (node.importClause) { - var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); } } return node; } - function visitImportClause(node) { - var newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? ts.createImportClause(newDefaultImport, newNamedBindings) - : node; - } - function visitNamedBindings(node) { - if (node.kind === 232) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === node.elements) { - return node; - } - return ts.createNamedImports(newNamedImportElements); - } - } - function visitImportSpecifier(node) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } } - ts.transformES6Module = transformES6Module; + ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); var ts; (function (ts) { var moduleTransformerMap = ts.createMap((_a = {}, - _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.ES2015] = ts.transformES2015Module, _a[ts.ModuleKind.System] = ts.transformSystemModule, _a[ts.ModuleKind.AMD] = ts.transformModule, _a[ts.ModuleKind.CommonJS] = ts.transformModule, @@ -41939,79 +46407,65 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var transformers = []; transformers.push(ts.transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); if (jsx === 2) { transformers.push(ts.transformJsx); } - transformers.push(ts.transformES7); + if (languageVersion < 5) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3) { + transformers.push(ts.transformES2016); + } if (languageVersion < 2) { - transformers.push(ts.transformES6); + transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (languageVersion < 1) { + transformers.push(ts.transformES5); + } return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); + var enabledSyntaxKindFeatures = new Array(298); + var lexicalEnvironmentDisabled = false; + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; - var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; - var hoistedVariableDeclarations; - var hoistedFunctionDeclarations; - var lexicalEnvironmentDisabled; + var lexicalEnvironmentSuspended = false; + var emitHelpers; var context = { getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, - startLexicalEnvironment: startLexicalEnvironment, - endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + onSubstituteNode: function (_emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,112 +46477,86 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 4) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 2) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); var decl = ts.createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } function hoistFunctionDeclaration(func) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } function startLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + function suspendLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + function resumeLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } function endLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = hoistedFunctionDeclarations.slice(); + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); } - if (hoistedVariableDeclarations) { - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -42138,60 +46566,27 @@ var ts; } } lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + function requestEmitHelper(helper) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +46597,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42224,7 +46619,7 @@ var ts; var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; var noDeclare; var moduleElementDeclarationEmitInfo = []; @@ -42242,7 +46637,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42268,7 +46663,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 230); + ts.Debug.assert(aliasEmitInfo.node.kind === 235); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -42299,7 +46694,7 @@ var ts; reportedDeclarationError: reportedDeclarationError, moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput + referencesOutput: referencesOutput, }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); @@ -42324,6 +46719,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -42339,10 +46735,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 218) { + if (declaration.kind === 223) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 233 || declaration.kind === 234 || declaration.kind === 231) { + else if (declaration.kind === 238 || declaration.kind === 239 || declaration.kind === 236) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -42353,7 +46749,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 230) { + if (moduleElementEmitInfo.node.kind === 235) { moduleElementEmitInfo.isVisible = true; } else { @@ -42361,12 +46757,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -42427,7 +46823,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,20 +46835,20 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } function emitLines(nodes) { - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -42467,7 +46863,7 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } @@ -42478,67 +46874,73 @@ var ts; } function emitType(type) { switch (type.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 165: - case 166: + case 104: + case 137: + case 94: + case 129: + case 167: + case 171: return writeTextOfNode(currentText, type); - case 194: + case 199: return emitExpressionWithTypeArguments(type); - case 155: - return emitTypeReference(type); - case 158: - return emitTypeQuery(type); - case 160: - return emitArrayType(type); - case 161: - return emitTupleType(type); - case 162: - return emitUnionType(type); - case 163: - return emitIntersectionType(type); - case 164: - return emitParenType(type); - case 156: case 157: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 160: + return emitTypeQuery(type); + case 162: + return emitArrayType(type); + case 163: + return emitTupleType(type); + case 164: + return emitUnionType(type); + case 165: + return emitIntersectionType(type); + case 166: + return emitParenType(type); + case 168: + return emitTypeOperator(type); + case 169: + return emitIndexedAccessType(type); + case 170: + return emitMappedType(type); + case 158: case 159: + return emitSignatureDeclarationWithJsDocComments(type); + case 161: return emitTypeLiteral(type); - case 69: + case 70: return emitEntityName(type); - case 139: + case 141: return emitEntityName(type); - case 154: + case 156: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 69) { + if (entityName.kind === 70) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 139 ? entityName.left : entityName.expression; - var right = entityName.kind === 139 ? entityName.right : entityName.name; + var left = entityName.kind === 141 ? entityName.left : entityName.expression; + var right = entityName.kind === 141 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 229 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 234 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); + ts.Debug.assert(node.expression.kind === 70 || node.expression.kind === 177); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -42584,6 +46986,42 @@ var ts; emitType(type.type); write(")"); } + function emitTypeOperator(type) { + write(ts.tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + function emitIndexedAccessType(node) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + function emitMappedType(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } function emitTypeLiteral(type) { write("{"); if (type.members.length) { @@ -42612,14 +47050,14 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_41 = baseName + "_" + count; + if (!(name_41 in currentIdentifiers)) { + return name_41; } } } function emitExportAssignment(node) { - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -42632,7 +47070,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -42640,11 +47078,11 @@ var ts; } write(";"); writeLine(); - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic) { + function getDefaultExportAccessibilityDiagnostic() { return { diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -42658,10 +47096,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 229 || - (node.parent.kind === 256 && isCurrentFileExternalModule)) { + else if (node.kind === 234 || + (node.parent.kind === 261 && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 256) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -42670,7 +47108,7 @@ var ts; }); } else { - if (node.kind === 230) { + if (node.kind === 235) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -42688,30 +47126,30 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 220: - return writeFunctionDeclaration(node); - case 200: - return writeVariableStatement(node); - case 222: - return writeInterfaceDeclaration(node); - case 221: - return writeClassDeclaration(node); - case 223: - return writeTypeAliasDeclaration(node); - case 224: - return writeEnumDeclaration(node); case 225: - return writeModuleDeclaration(node); + return writeFunctionDeclaration(node); + case 205: + return writeVariableStatement(node); + case 227: + return writeInterfaceDeclaration(node); + case 226: + return writeClassDeclaration(node); + case 228: + return writeTypeAliasDeclaration(node); case 229: - return writeImportEqualsDeclaration(node); + return writeEnumDeclaration(node); case 230: + return writeModuleDeclaration(node); + case 234: + return writeImportEqualsDeclaration(node); + case 235: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 256) { + if (node.parent.kind === 261) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { write("export "); @@ -42719,7 +47157,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 222 && !noDeclare) { + else if (node.kind !== 227 && !noDeclare) { write("declare "); } } @@ -42759,7 +47197,7 @@ var ts; write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult) { + function getImportEntityNameVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -42769,7 +47207,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 232) { + if (namedBindings.kind === 237) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -42792,7 +47230,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 232) { + if (node.importClause.namedBindings.kind === 237) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -42809,13 +47247,13 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 225; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230; var moduleSpecifier; - if (parent.kind === 229) { + if (parent.kind === 234) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 225) { + else if (parent.kind === 230) { moduleSpecifier = parent.name; } else { @@ -42883,7 +47321,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 226) { + while (node.body && node.body.kind !== 231) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -42917,7 +47355,7 @@ var ts; write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + function getTypeAliasDeclarationVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -42953,7 +47391,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 149 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -42963,51 +47401,54 @@ var ts; writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - (node.parent.parent && node.parent.parent.kind === 159)) { - ts.Debug.assert(node.parent.kind === 147 || - node.parent.kind === 146 || - node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.kind === 151 || - node.parent.kind === 152); + if (node.parent.kind === 158 || + node.parent.kind === 159 || + (node.parent.parent && node.parent.parent.kind === 161)) { + ts.Debug.assert(node.parent.kind === 149 || + node.parent.kind === 148 || + node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.kind === 153 || + node.parent.kind === 154); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { + function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 221: + case 226: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 222: + case 227: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 152: + case 154: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151: + case 153: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 220: + case 225: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case 228: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; default: ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -43033,16 +47474,16 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 93) { + else if (!isImplementsList && node.expression.kind === 94) { write("null"); } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult) { + function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 221) { + if (node.parent.parent.kind === 226) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -43101,7 +47542,10 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); + var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, false); + } write(" {"); writeLine(); increaseIndent(); @@ -43122,17 +47566,17 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 218 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 223 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 147 || node.kind === 146 || + (node.kind === 144 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { + if ((node.kind === 147 || node.kind === 146) && node.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -43145,14 +47589,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 218) { + if (node.kind === 223) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 145 || node.kind === 144) { + else if (node.kind === 147 || node.kind === 146) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43160,7 +47604,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43186,7 +47630,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (element.kind !== 198) { elements.push(element); } } @@ -43252,7 +47696,7 @@ var ts; accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 149 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 151 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -43265,7 +47709,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 149 + return accessor.kind === 151 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -43274,7 +47718,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 150) { + if (accessorWithTypeAnnotation.kind === 152) { if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -43320,17 +47764,17 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 220) { + if (node.kind === 225) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 147 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 150) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 220) { + if (node.kind === 225) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 148) { + else if (node.kind === 150) { write("constructor"); } else { @@ -43350,15 +47794,15 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 153) { + if (node.kind === 155) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 || node.kind === 157) { + if (node.kind === 154 || node.kind === 159) { write("new "); } - else if (node.kind === 156) { + else if (node.kind === 158) { var currentOutput = writer.getText(); if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; @@ -43369,20 +47813,20 @@ var ts; write("("); } emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 153) { + if (node.kind === 155) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 156 || node.kind === 157; - if (isFunctionTypeOrConstructorType || node.parent.kind === 159) { + var isFunctionTypeOrConstructorType = node.kind === 158 || node.kind === 159; + if (isFunctionTypeOrConstructorType || node.parent.kind === 161) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 150 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -43396,23 +47840,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 152: + case 154: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151: + case 153: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 153: + case 155: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43420,7 +47864,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43433,7 +47877,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 220: + case 225: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43465,9 +47909,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.parent.kind === 159) { + if (node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8)) { @@ -43483,22 +47927,26 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 148: + case 150: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 152: + case 154: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151: + case 153: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 147: - case 146: + case 155: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43506,7 +47954,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43518,7 +47966,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 220: + case 225: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43529,12 +47977,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 167) { + if (bindingPattern.kind === 172) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 168) { + else if (bindingPattern.kind === 173) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -43545,10 +47993,10 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 193) { + if (bindingElement.kind === 198) { write(" "); } - else if (bindingElement.kind === 169) { + else if (bindingElement.kind === 174) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -43558,7 +48006,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 69); + ts.Debug.assert(bindingElement.name.kind === 70); if (bindingElement.dotDotDotToken) { write("..."); } @@ -43570,57 +48018,57 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 220: case 225: - case 229: - case 222: - case 221: - case 223: - case 224: - return emitModuleElement(node, isModuleElementVisible(node)); - case 200: - return emitModuleElement(node, isVariableStatementVisible(node)); case 230: + case 234: + case 227: + case 226: + case 228: + case 229: + return emitModuleElement(node, isModuleElementVisible(node)); + case 205: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 235: return emitModuleElement(node, !node.importClause); - case 236: + case 241: return emitExportDeclaration(node); + case 150: + case 149: case 148: + return writeFunctionDeclaration(node); + case 154: + case 153: + case 155: + return emitSignatureDeclarationWithJsDocComments(node); + case 151: + case 152: + return emitAccessorDeclaration(node); case 147: case 146: - return writeFunctionDeclaration(node); - case 152: - case 151: - case 153: - return emitSignatureDeclarationWithJsDocComments(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 145: - case 144: return emitPropertyDeclaration(node); - case 255: + case 260: return emitEnumMemberDeclaration(node); - case 235: + case 240: return emitExportAssignment(node); - case 256: + case 261: return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); referencesOutput += "/// " + newLine; } return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) { if (isBundledEmit && !addBundledFileReference) { return; } @@ -43630,8 +48078,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +48105,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +48112,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, - getSourceMappingURL: getSourceMappingURL + getSourceMappingURL: getSourceMappingURL, }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +48183,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +48193,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +48223,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +48248,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 293 + && (emitFlags & 16) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 64) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 293 + && (emitFlags & 32) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 128) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,18 +48325,24 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, sources: sourceMapData.sourceMapSources, names: sourceMapData.sourceMapNames, mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent + sourcesContent: sourceMapData.sourceMapSourcesContent, }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +48352,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44069,31 +48400,33 @@ var ts; setSourceFile: setSourceFile, emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + var isEmittedNode = node.kind !== 293; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -44105,18 +48438,20 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 219) { + if (node.kind === 224) { declarationListContainerEnd = end; } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitNodeWithComment"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,17 +48473,19 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44158,6 +48495,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -44177,7 +48517,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -44195,7 +48535,7 @@ var ts; function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -44218,7 +48558,7 @@ var ts; ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } } - function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -44256,16 +48596,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,20 +48641,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (_) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; - var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; - var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; - var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; - var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; - var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; - var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; - var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; - var superHelper = "\nconst _super = name => super[name];"; - var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -44332,11 +48653,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44346,21 +48667,20 @@ var ts; var currentSourceFile; var currentText; var currentFileIdentifiers; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; + var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +48689,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44392,11 +48716,12 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = ts.createMap(); + bundledHelpers = isBundledEmit ? ts.createMap() : undefined; isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; - emitEmitHelpers(sourceFile); + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; + emitHelpers(sourceFile, true); } } ts.forEach(sourceFiles, printSourceFile); @@ -44406,23 +48731,18 @@ var ts; write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); } if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); } if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); comments.reset(); writer.reset(); tempFlags = 0; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } function printSourceFile(node) { @@ -44431,360 +48751,369 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 261: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 70: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { - case 12: case 13: case 14: + case 15: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 74: - case 77: - case 82: - case 103: - case 110: + case 75: + case 78: + case 83: + case 104: case 111: case 112: case 113: - case 115: + case 114: + case 116: case 117: case 118: + case 119: case 120: + case 121: case 122: - case 130: + case 123: + case 124: + case 125: + case 127: case 128: + case 129: + case 130: + case 131: case 132: case 133: + case 134: + case 135: + case 136: case 137: - return writeTokenNode(node); + case 138: case 139: - return emitQualifiedName(node); case 140: - return emitComputedPropertyName(node); - case 141: - return emitTypeParameter(node); - case 142: - return emitParameter(node); - case 143: - return emitDecorator(node); - case 144: - return emitPropertySignature(node); - case 145: - return emitPropertyDeclaration(node); - case 146: - return emitMethodSignature(node); - case 147: - return emitMethodDeclaration(node); - case 148: - return emitConstructor(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 151: - return emitCallSignature(node); - case 152: - return emitConstructSignature(node); - case 153: - return emitIndexSignature(node); - case 154: - return emitTypePredicate(node); - case 155: - return emitTypeReference(node); - case 156: - return emitFunctionType(node); - case 157: - return emitConstructorType(node); - case 158: - return emitTypeQuery(node); - case 159: - return emitTypeLiteral(node); - case 160: - return emitArrayType(node); - case 161: - return emitTupleType(node); - case 162: - return emitUnionType(node); - case 163: - return emitIntersectionType(node); - case 164: - return emitParenthesizedType(node); - case 194: - return emitExpressionWithTypeArguments(node); - case 165: - return emitThisType(node); - case 166: - return emitLiteralType(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 197: - return emitTemplateSpan(node); - case 198: - return emitSemicolonClassElement(node); - case 199: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return emitEmptyStatement(node); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 207: - return emitForInStatement(node); - case 208: - return emitForOfStatement(node); - case 209: - return emitContinueStatement(node); - case 210: - return emitBreakStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 219: - return emitVariableDeclarationList(node); - case 220: - return emitFunctionDeclaration(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 223: - return emitTypeAliasDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 225: - return emitModuleDeclaration(node); - case 226: - return emitModuleBlock(node); - case 227: - return emitCaseBlock(node); - case 229: - return emitImportEqualsDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 231: - return emitImportClause(node); - case 232: - return emitNamespaceImport(node); - case 233: - return emitNamedImports(node); - case 234: - return emitImportSpecifier(node); - case 235: - return emitExportAssignment(node); - case 236: - return emitExportDeclaration(node); - case 237: - return emitNamedExports(node); - case 238: - return emitExportSpecifier(node); - case 239: + writeTokenText(kind); return; + case 141: + return emitQualifiedName(node); + case 142: + return emitComputedPropertyName(node); + case 143: + return emitTypeParameter(node); + case 144: + return emitParameter(node); + case 145: + return emitDecorator(node); + case 146: + return emitPropertySignature(node); + case 147: + return emitPropertyDeclaration(node); + case 148: + return emitMethodSignature(node); + case 149: + return emitMethodDeclaration(node); + case 150: + return emitConstructor(node); + case 151: + case 152: + return emitAccessorDeclaration(node); + case 153: + return emitCallSignature(node); + case 154: + return emitConstructSignature(node); + case 155: + return emitIndexSignature(node); + case 156: + return emitTypePredicate(node); + case 157: + return emitTypeReference(node); + case 158: + return emitFunctionType(node); + case 159: + return emitConstructorType(node); + case 160: + return emitTypeQuery(node); + case 161: + return emitTypeLiteral(node); + case 162: + return emitArrayType(node); + case 163: + return emitTupleType(node); + case 164: + return emitUnionType(node); + case 165: + return emitIntersectionType(node); + case 166: + return emitParenthesizedType(node); + case 199: + return emitExpressionWithTypeArguments(node); + case 167: + return emitThisType(); + case 168: + return emitTypeOperator(node); + case 169: + return emitIndexedAccessType(node); + case 170: + return emitMappedType(node); + case 171: + return emitLiteralType(node); + case 172: + return emitObjectBindingPattern(node); + case 173: + return emitArrayBindingPattern(node); + case 174: + return emitBindingElement(node); + case 202: + return emitTemplateSpan(node); + case 203: + return emitSemicolonClassElement(); + case 204: + return emitBlock(node); + case 205: + return emitVariableStatement(node); + case 206: + return emitEmptyStatement(); + case 207: + return emitExpressionStatement(node); + case 208: + return emitIfStatement(node); + case 209: + return emitDoStatement(node); + case 210: + return emitWhileStatement(node); + case 211: + return emitForStatement(node); + case 212: + return emitForInStatement(node); + case 213: + return emitForOfStatement(node); + case 214: + return emitContinueStatement(node); + case 215: + return emitBreakStatement(node); + case 216: + return emitReturnStatement(node); + case 217: + return emitWithStatement(node); + case 218: + return emitSwitchStatement(node); + case 219: + return emitLabeledStatement(node); + case 220: + return emitThrowStatement(node); + case 221: + return emitTryStatement(node); + case 222: + return emitDebuggerStatement(node); + case 223: + return emitVariableDeclaration(node); + case 224: + return emitVariableDeclarationList(node); + case 225: + return emitFunctionDeclaration(node); + case 226: + return emitClassDeclaration(node); + case 227: + return emitInterfaceDeclaration(node); + case 228: + return emitTypeAliasDeclaration(node); + case 229: + return emitEnumDeclaration(node); + case 230: + return emitModuleDeclaration(node); + case 231: + return emitModuleBlock(node); + case 232: + return emitCaseBlock(node); + case 234: + return emitImportEqualsDeclaration(node); + case 235: + return emitImportDeclaration(node); + case 236: + return emitImportClause(node); + case 237: + return emitNamespaceImport(node); + case 238: + return emitNamedImports(node); + case 239: + return emitImportSpecifier(node); case 240: - return emitExternalModuleReference(node); - case 244: - return emitJsxText(node); + return emitExportAssignment(node); + case 241: + return emitExportDeclaration(node); + case 242: + return emitNamedExports(node); case 243: - return emitJsxOpeningElement(node); + return emitExportSpecifier(node); + case 244: + return; case 245: - return emitJsxClosingElement(node); - case 246: - return emitJsxAttribute(node); - case 247: - return emitJsxSpreadAttribute(node); + return emitExternalModuleReference(node); + case 10: + return emitJsxText(node); case 248: - return emitJsxExpression(node); + return emitJsxOpeningElement(node); case 249: - return emitCaseClause(node); + return emitJsxClosingElement(node); case 250: - return emitDefaultClause(node); + return emitJsxAttribute(node); case 251: - return emitHeritageClause(node); + return emitJsxSpreadAttribute(node); case 252: - return emitCatchClause(node); + return emitJsxExpression(node); case 253: - return emitPropertyAssignment(node); + return emitCaseClause(node); case 254: - return emitShorthandPropertyAssignment(node); + return emitDefaultClause(node); case 255: - return emitEnumMember(node); + return emitHeritageClause(node); case 256: - return emitSourceFile(node); + return emitCatchClause(node); + case 257: + return emitPropertyAssignment(node); + case 258: + return emitShorthandPropertyAssignment(node); + case 259: + return emitSpreadAssignment(node); + case 260: + return emitEnumMember(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: return emitNumericLiteral(node); case 9: - case 10: case 11: + case 12: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 84: - case 93: - case 95: - case 99: - case 97: - return writeTokenNode(node); - case 170: - return emitArrayLiteralExpression(node); - case 171: - return emitObjectLiteralExpression(node); - case 172: - return emitPropertyAccessExpression(node); - case 173: - return emitElementAccessExpression(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - return emitTypeAssertionExpression(node); - case 178: - return emitParenthesizedExpression(node); - case 179: - return emitFunctionExpression(node); - case 180: - return emitArrowFunction(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 189: - return emitTemplateExpression(node); - case 190: - return emitYieldExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 192: - return emitClassExpression(node); - case 193: + case 85: + case 94: + case 96: + case 100: + case 98: + writeTokenText(kind); return; + case 175: + return emitArrayLiteralExpression(node); + case 176: + return emitObjectLiteralExpression(node); + case 177: + return emitPropertyAccessExpression(node); + case 178: + return emitElementAccessExpression(node); + case 179: + return emitCallExpression(node); + case 180: + return emitNewExpression(node); + case 181: + return emitTaggedTemplateExpression(node); + case 182: + return emitTypeAssertionExpression(node); + case 183: + return emitParenthesizedExpression(node); + case 184: + return emitFunctionExpression(node); + case 185: + return emitArrowFunction(node); + case 186: + return emitDeleteExpression(node); + case 187: + return emitTypeOfExpression(node); + case 188: + return emitVoidExpression(node); + case 189: + return emitAwaitExpression(node); + case 190: + return emitPrefixUnaryExpression(node); + case 191: + return emitPostfixUnaryExpression(node); + case 192: + return emitBinaryExpression(node); + case 193: + return emitConditionalExpression(node); + case 194: + return emitTemplateExpression(node); case 195: - return emitAsExpression(node); + return emitYieldExpression(node); case 196: + return emitSpreadExpression(node); + case 197: + return emitClassExpression(node); + case 198: + return; + case 200: + return emitAsExpression(node); + case 201: return emitNonNullExpression(node); - case 241: + case 246: return emitJsxElement(node); - case 242: + case 247: return emitJsxSelfClosingElement(node); - case 288: + case 294: return emitPartiallyEmittedExpression(node); + case 297: + return writeLines(node.text); } } function emitNumericLiteral(node) { @@ -44804,12 +49133,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, false)); - } + write(getTextOfNode(node, false)); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -44817,7 +49141,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -44887,7 +49211,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 149 ? "get " : "set "); + write(node.kind === 151 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -44915,7 +49239,7 @@ var ts; emitWithPrefix(": ", node.type); write(";"); } - function emitSemicolonClassElement(node) { + function emitSemicolonClassElement() { write(";"); } function emitTypePredicate(node) { @@ -44969,9 +49293,42 @@ var ts; emit(node.type); write(")"); } - function emitThisType(node) { + function emitThisType() { write("this"); } + function emitTypeOperator(node) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + function emitMappedType(node) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } function emitLiteralType(node) { emitExpression(node.literal); } @@ -45019,7 +49376,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +49389,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 65536)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = { kind: 22, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45055,17 +49409,16 @@ var ts; function needsDotDotForPropertyAccess(expression) { if (expression.kind === 8) { var text = getLiteralTextOfNode(expression); - return text.indexOf(ts.tokenToString(21)) < 0; + return text.indexOf(ts.tokenToString(22)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45073,11 +49426,13 @@ var ts; } function emitCallExpression(node) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { @@ -45137,16 +49492,16 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 185 - && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) - || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + return operand.kind === 190 + && ((node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) + || (node.operator === 37 && (operand.operator === 37 || operand.operator === 43))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 24; + var isCommaOperator = node.operatorToken.kind !== 25; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); @@ -45181,7 +49536,7 @@ var ts; write(node.asteriskToken ? "yield*" : "yield"); emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node) { + function emitSpreadExpression(node) { write("..."); emitExpression(node.expression); } @@ -45207,20 +49562,20 @@ var ts; emitExpression(node.expression); emit(node.literal); } - function emitBlock(node, format) { + function emitBlock(node) { if (isSingleLineEmptyBlock(node)) { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); write(" "); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } else { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); emitBlockStatements(node); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 1) { emitList(node, node.statements, 384); } else { @@ -45232,7 +49587,7 @@ var ts; emit(node.declarationList); write(";"); } - function emitEmptyStatement(node) { + function emitEmptyStatement() { write(";"); } function emitExpressionStatement(node) { @@ -45240,16 +49595,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(88, node.pos, node); + var openParenPos = writeToken(89, node.pos, node); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitExpression(node.expression); - writeToken(18, node.expression.end, node); + writeToken(19, node.expression.end, node); emitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { writeLine(); - writeToken(80, node.thenStatement.end, node); - if (node.elseStatement.kind === 203) { + writeToken(81, node.thenStatement.end, node); + if (node.elseStatement.kind === 208) { write(" "); emit(node.elseStatement); } @@ -45278,9 +49633,9 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -45290,28 +49645,28 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 219) { + if (node.kind === 224) { emit(node); } else { @@ -45320,17 +49675,17 @@ var ts; } } function emitContinueStatement(node) { - writeToken(75, node.pos); + writeToken(76, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(70, node.pos); + writeToken(71, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitReturnStatement(node) { - writeToken(94, node.pos, node); + writeToken(95, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -45341,11 +49696,11 @@ var ts; emitEmbeddedStatement(node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(96, node.pos); + var openParenPos = writeToken(97, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); write(" "); emit(node.caseBlock); } @@ -45370,11 +49725,12 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(76, node.pos); + writeToken(77, node.pos); write(";"); } function emitVariableDeclaration(node) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } function emitVariableDeclarationList(node) { @@ -45395,19 +49751,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 262144) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { var savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } if (indentedFlag) { @@ -45430,8 +49786,8 @@ var ts; emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (ts.getEmitFlags(body) & 1) { return true; } if (body.multiLine) { @@ -45454,14 +49810,14 @@ var ts; } return true; } - function emitBlockFunctionBody(parentNode, body) { + function emitBlockFunctionBody(body) { write(" {"); increaseIndent(); - emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); decreaseIndent(); - writeToken(16, body.statements.end, body); + writeToken(17, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -45486,7 +49842,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -45539,7 +49895,7 @@ var ts; write(node.flags & 16 ? "namespace " : "module "); emit(node.name); var body = node.body; - while (body.kind === 225) { + while (body.kind === 230) { write("."); emit(body.name); body = body.body; @@ -45548,7 +49904,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45562,9 +49918,9 @@ var ts; } } function emitCaseBlock(node) { - writeToken(15, node.pos); + writeToken(16, node.pos); emitList(node, node.clauses, 65); - writeToken(16, node.clauses.end); + writeToken(17, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -45575,7 +49931,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -45695,7 +50051,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -45733,11 +50089,11 @@ var ts; } function emitCatchClause(node) { writeLine(); - var openParenPos = writeToken(72, node.pos); + var openParenPos = writeToken(73, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emit(node.variableDeclaration); - writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + writeToken(19, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); write(" "); emit(node.block); } @@ -45745,8 +50101,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 512) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45758,6 +50114,12 @@ var ts; emitExpression(node.objectAssignmentInitializer); } } + function emitSpreadAssignment(node) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } function emitEnumMember(node) { emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); @@ -45793,64 +50155,31 @@ var ts; } return statements.length; } - function emitHelpers(node) { - var emitFlags = node.emitFlags; + function emitHelpers(node, isBundle) { + var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile; + var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit; var helpersEmitted = false; - if (emitFlags & 1) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - if (emitFlags & 2) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - if (emitFlags & 4) { - writeLines(superHelper); - helpersEmitted = true; - } - if (emitFlags & 8) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - return helpersEmitted; - } - function emitEmitHelpers(node) { - if (compilerOptions.noEmitHelpers) { - return false; - } - if (compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } - var helpersEmitted = false; - if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 2048) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + if (shouldSkip) + continue; + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + continue; + } + writeLines(helper.text); + helpersEmitted = true; } - decorateEmitted = true; - helpersEmitted = true; - } - if (!paramEmitted && node.flags & 4096) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - if (!awaiterEmitted && node.flags & 8192) { - writeLines(awaiterHelper); - if (languageVersion < 2) { - writeLines(generatorHelper); - } - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { writeLine(); @@ -45858,9 +50187,10 @@ var ts; return helpersEmitted; } function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); + var lines = text.split(/\r\n?|\n/g); + var indentation = guessIndentation(lines); for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + var line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -45869,6 +50199,21 @@ var ts; } } } + function guessIndentation(lines) { + var indentation; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var line = lines_1[_a]; + for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!ts.isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { @@ -45900,31 +50245,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +50344,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +50386,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46193,7 +50498,7 @@ var ts; && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + while (node.kind === 183 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -46225,17 +50530,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +50555,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_42 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_42)) { tempFlags |= flags; - return name_43; + return name_42; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_43 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_43)) { + return name_43; } } } @@ -46305,19 +50605,19 @@ var ts; } function generateNameForNode(node) { switch (node.kind) { - case 69: + case 70: return makeUniqueName(getTextOfNode(node)); - case 225: - case 224: - return generateNameForModuleOrEnum(node); case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: + case 229: + return generateNameForModuleOrEnum(node); case 235: + case 241: + return generateNameForImportOrExportDeclaration(node); + case 225: + case 226: + case 240: return generateNameForExportDefault(); - case 192: + case 197: return generateNameForClassExpression(); default: return makeTempVariableName(0); @@ -46390,7 +50690,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.0"; var emptyArray = []; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -46445,581 +50744,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === 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, typeRoots); - } - } - else { - 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, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +50845,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); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47180,42 +50904,15 @@ var ts; } var resolutions = []; var cache = ts.createMap(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_44 = names_1[_i]; + var result = name_44 in cache + ? cache[name_44] + : cache[name_44] = loader(name_44, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47225,7 +50922,7 @@ var ts; var classifiableNames; var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; var modulesWithElidedImports = ts.createMap(); var sourceFilesFoundSearchingNodeModules = ts.createMap(); @@ -47238,10 +50935,17 @@ var ts; var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,16 +50953,17 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); 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 = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -47299,19 +51004,22 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { commonSourceDirectory += ts.directorySeparator; @@ -47330,25 +51038,85 @@ var ts; } return classifiableNames; } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var unknownModuleNames; + var result; + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + var isKnownToResolveToAmbientModule = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + result = new Array(moduleNames.length); + unknownModuleNames = moduleNames.slice(0, i); + } + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + unknownModuleNames.push(moduleName); + } + } + if (!unknownModuleNames) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState) { + return false; + } + var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + return false; + } + var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return false; } var oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + if (ts.changesAffectModuleResolution(oldOptions, options)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -47389,40 +51157,44 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { return false; } - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { newSourceFile = oldSourceFile; } newSourceFiles.push(newSourceFile); } + var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { - var modifiedFile = modifiedSourceFiles_1[_b]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { + var modifiedFile = modifiedSourceFiles_2[_d]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -47438,24 +51210,30 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked + isEmitBlocked: isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file) { + return sourceFilesFoundSearchingNodeModules[file.path]; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +51254,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47515,7 +51293,13 @@ var ts; return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } } - function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSyntacticDiagnosticsForFile(sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } function runWithCancellationToken(func) { @@ -47535,183 +51319,170 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; + var parent = sourceFile; walk(sourceFile); return diagnostics; function walk(node) { - if (!node) { - return false; + switch (parent.kind) { + case 144: + case 147: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + case 149: + case 148: + case 150: + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + case 223: + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } } switch (node.kind) { - case 229: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 235: + case 234: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 240: if (node.isExportEquals) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; } break; - case 221: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 251: + case 255: var heritageClause = node; - if (heritageClause.token === 106) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; + if (heritageClause.token === 107) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; } break; - case 222: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 225: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 223: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 147: - case 146: - case 148: + case 227: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 230: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 228: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 229: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 182: + var typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 226: case 149: + case 148: case 150: - case 179: - case 220: - case 180: - case 220: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + case 205: + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 205); } break; - case 200: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 218: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 174: - case 175: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 142: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 145: - var propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + case 147: + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _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 (modifier.kind !== 114) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } - } - if (checkTypeAnnotation(node.type)) { - return true; + return; } break; - case 224: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 177: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 143: - if (!options.experimentalDecorators) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + case 144: + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112: - case 110: - case 111: - case 128: - case 122: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - case 113: - case 82: - case 74: - case 77: - case 115: + break; + case 179: + case 180: + case 199: + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 75: + if (isConstValid) { + continue; + } + case 113: + case 111: + case 112: + case 130: + case 123: + case 116: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + case 114: + case 83: + case 78: } } - return false; + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); - var writeFile = function () { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { @@ -47728,11 +51499,8 @@ var ts; ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName) { - return ts.getBaseFileName(fileName).indexOf(".") >= 0; - } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, true); + processSourceFile(ts.normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -47749,14 +51517,18 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; + var ambientModules; if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - var externalHelpersModuleReference = ts.createNode(9); + var externalHelpersModuleReference = ts.createSynthesizedNode(9); externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + var importDecl = ts.createSynthesizedNode(235); + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { @@ -47768,12 +51540,13 @@ var ts; } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 230: - case 229: - case 236: + case 235: + case 234: + case 241: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -47785,13 +51558,16 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 225: + case 230: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + (ambientModules || (ambientModules = [])).push(moduleName.text); + } var body = node.body; if (body) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { @@ -47812,15 +51588,15 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, isReference, refFile, refPos, refEnd) { + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { var diagnosticArgument; var diagnostic; - if (hasExtension(fileName)) { + if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -47830,13 +51606,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -47860,7 +51636,7 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, isReference, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { if (filesByName.contains(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -47869,16 +51645,16 @@ var ts; if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } } return file_1; @@ -47905,12 +51681,11 @@ var ts; } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - var basePath = ts.getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); } @@ -47920,10 +51695,10 @@ var ts; } return file; } - function processReferencedFiles(file, basePath, isDefaultLib) { + function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -47945,18 +51720,20 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } else { if (previousResolution) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } } saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } } } @@ -47982,28 +51759,35 @@ var ts; function getCanonicalFileName(fileName) { return host.getCanonicalFileName(fileName); } - function processImportedModules(file, basePath) { + function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = ts.createMap(); - var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); + var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; - var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48013,12 +51797,11 @@ var ts; else { file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +51812,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +51856,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +51867,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +51906,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48164,13 +51950,21 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); - ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); @@ -48179,10 +51973,15 @@ var ts; if (emitFileName) { var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + var chain_1; + if (!options.configFilePath) { + chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } if (emitFilesSeen.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -48190,12 +51989,33 @@ var ts; } } } - function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); } } ts.createProgram = createProgram; + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ts.Extension.Ts: + case ts.Extension.Dts: + return undefined; + case ts.Extension.Tsx: + return needJsx(); + case ts.Extension.Jsx: + return needJsx() || needAllowJs(); + case ts.Extension.Js: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; })(ts || (ts = {})); var ts; (function (ts) { @@ -48206,12 +52026,14 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + StringScriptSnapshot.prototype.getChangeRange = function () { return undefined; }; return StringScriptSnapshot; @@ -48234,12 +52056,13 @@ var ts; HighlightSpanKind.reference = "reference"; HighlightSpanKind.writtenReference = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; (function (IndentStyle) { IndentStyle[IndentStyle["None"] = 0] = "None"; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -48263,8 +52086,8 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -48275,8 +52098,7 @@ var ts; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { ScriptElementKind.unknown = ""; @@ -48355,37 +52177,37 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.scanner = ts.createScanner(2, true); + ts.scanner = ts.createScanner(5, true); ts.emptyArray = []; function getMeaningFromDeclaration(node) { switch (node.kind) { - case 142: - case 218: - case 169: - case 145: case 144: - case 253: - case 254: - case 255: + case 223: + case 174: case 147: case 146: - case 148: + case 257: + case 258: + case 260: case 149: + case 148: case 150: - case 220: - case 179: - case 180: - case 252: - return 1; - case 141: - case 222: - case 223: - case 159: - return 2; - case 221: - case 224: - return 1 | 2; + case 151: + case 152: case 225: + case 184: + case 185: + case 256: + return 1; + case 143: + case 227: + case 228: + case 161: + return 2; + case 226: + case 229: + return 1 | 2; + case 230: if (ts.isAmbientModule(node)) { return 4 | 1; } @@ -48395,21 +52217,21 @@ var ts; else { return 4; } - case 233: + case 238: + case 239: case 234: - case 229: - case 230: case 235: - case 236: + case 240: + case 241: return 1 | 2 | 4; - case 256: + case 261: return 4 | 1; } return 1 | 2 | 4; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.parent.kind === 235) { + if (node.parent.kind === 240) { return 1 | 2 | 4; } else if (isInRightSideOfImport(node)) { @@ -48430,16 +52252,16 @@ var ts; } ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69); - if (node.parent.kind === 139 && + ts.Debug.assert(node.kind === 70); + if (node.parent.kind === 141 && node.parent.right === node && - node.parent.parent.kind === 229) { + node.parent.parent.kind === 234) { return 1 | 2 | 4; } return 4; } function isInRightSideOfImport(node) { - while (node.parent.kind === 139) { + while (node.parent.kind === 141) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -48450,27 +52272,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 139) { - while (root.parent && root.parent.kind === 139) { + if (root.parent.kind === 141) { + while (root.parent && root.parent.kind === 141) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 155 && !isLastClause; + return root.parent.kind === 157 && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 172) { - while (root.parent && root.parent.kind === 172) { + if (root.parent.kind === 177) { + while (root.parent && root.parent.kind === 177) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { + if (!isLastClause && root.parent.kind === 199 && root.parent.parent.kind === 255) { var decl = root.parent.parent.parent; - return (decl.kind === 221 && root.parent.parent.token === 106) || - (decl.kind === 222 && root.parent.parent.token === 83); + return (decl.kind === 226 && root.parent.parent.token === 107) || + (decl.kind === 227 && root.parent.parent.token === 84); } return false; } @@ -48478,17 +52300,17 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 155 || - (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 && !ts.isPartOfExpression(node)) || - node.kind === 165; + return node.parent.kind === 157 || + (node.parent.kind === 199 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 98 && !ts.isPartOfExpression(node)) || + node.kind === 167; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 174); + return isCallOrNewExpressionTarget(node, 179); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 175); + return isCallOrNewExpressionTarget(node, 180); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -48501,7 +52323,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 219 && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -48510,14 +52332,14 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 69 && - (node.parent.kind === 210 || node.parent.kind === 209) && + return node.kind === 70 && + (node.parent.kind === 215 || node.parent.kind === 214) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 69 && - node.parent.kind === 214 && + return node.kind === 70 && + node.parent.kind === 219 && node.parent.label === node; } function isLabelName(node) { @@ -48525,38 +52347,38 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 && node.parent.right === node; + return node.parent.kind === 141 && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 && node.parent.name === node; + return node && node.parent && node.parent.kind === 177 && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 && node.parent.name === node; + return node.parent.kind === 230 && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 69 && + return node.kind === 70 && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 || node.kind === 8) { switch (node.parent.kind) { - case 145: - case 144: - case 253: - case 255: case 147: case 146: + case 257: + case 260: case 149: - case 150: - case 225: + case 148: + case 151: + case 152: + case 230: return node.parent.name === node; - case 173: + case 178: return node.parent.argumentExpression === node; - case 140: + case 142: return true; } } @@ -48600,17 +52422,17 @@ var ts; return undefined; } switch (node.kind) { - case 256: - case 147: - case 146: - case 220: - case 179: + case 261: case 149: - case 150: - case 221: - case 222: - case 224: + case 148: case 225: + case 184: + case 151: + case 152: + case 226: + case 227: + case 229: + case 230: return node; } } @@ -48618,46 +52440,46 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 256: + case 261: return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; - case 225: + case 230: return ts.ScriptElementKind.moduleElement; - case 221: - case 192: + case 226: + case 197: return ts.ScriptElementKind.classElement; - case 222: return ts.ScriptElementKind.interfaceElement; - case 223: return ts.ScriptElementKind.typeElement; - case 224: return ts.ScriptElementKind.enumElement; - case 218: + case 227: return ts.ScriptElementKind.interfaceElement; + case 228: return ts.ScriptElementKind.typeElement; + case 229: return ts.ScriptElementKind.enumElement; + case 223: return getKindOfVariableDeclaration(node); - case 169: + case 174: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: return ts.ScriptElementKind.functionElement; - case 149: return ts.ScriptElementKind.memberGetAccessorElement; - case 150: return ts.ScriptElementKind.memberSetAccessorElement; + case 151: return ts.ScriptElementKind.memberGetAccessorElement; + case 152: return ts.ScriptElementKind.memberSetAccessorElement; + case 149: + case 148: + return ts.ScriptElementKind.memberFunctionElement; case 147: case 146: - return ts.ScriptElementKind.memberFunctionElement; - case 145: - case 144: return ts.ScriptElementKind.memberVariableElement; - case 153: return ts.ScriptElementKind.indexSignatureElement; - case 152: return ts.ScriptElementKind.constructSignatureElement; - case 151: return ts.ScriptElementKind.callSignatureElement; - case 148: return ts.ScriptElementKind.constructorImplementationElement; - case 141: return ts.ScriptElementKind.typeParameterElement; - case 255: return ts.ScriptElementKind.enumMemberElement; - case 142: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; - case 229: + case 155: return ts.ScriptElementKind.indexSignatureElement; + case 154: return ts.ScriptElementKind.constructSignatureElement; + case 153: return ts.ScriptElementKind.callSignatureElement; + case 150: return ts.ScriptElementKind.constructorImplementationElement; + case 143: return ts.ScriptElementKind.typeParameterElement; + case 260: return ts.ScriptElementKind.enumMemberElement; + case 144: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; case 234: - case 231: - case 238: - case 232: + case 239: + case 236: + case 243: + case 237: return ts.ScriptElementKind.alias; - case 279: + case 285: return ts.ScriptElementKind.typeElement; default: return ts.ScriptElementKind.unknown; @@ -48672,7 +52494,7 @@ var ts; } ts.getNodeKind = getNodeKind; function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 ? node.parent : node; + var searchNode = node.parent.kind === 171 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); if (type && type.flags & 32) { return type; @@ -48682,10 +52504,10 @@ var ts; ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; function isThis(node) { switch (node.kind) { - case 97: + case 98: return true; - case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + case 70: + return ts.identifierIsThisKeyword(node) && node.parent.kind === 144; default: return false; } @@ -48729,107 +52551,107 @@ var ts; return false; } switch (n.kind) { - case 221: - case 222: - case 224: - case 171: - case 167: - case 159: - case 199: case 226: case 227: - case 233: - case 237: - return nodeEndsWith(n, 16, sourceFile); - case 252: + case 229: + case 176: + case 172: + case 161: + case 204: + case 231: + case 232: + case 238: + case 242: + return nodeEndsWith(n, 17, sourceFile); + case 256: return isCompletedNode(n.block, sourceFile); - case 175: + case 180: if (!n.arguments) { return true; } - case 174: - case 178: - case 164: - return nodeEndsWith(n, 18, sourceFile); - case 156: - case 157: - return isCompletedNode(n.type, sourceFile); - case 148: - case 149: - case 150: - case 220: case 179: - case 147: - case 146: - case 152: + case 183: + case 166: + return nodeEndsWith(n, 19, sourceFile); + case 158: + case 159: + return isCompletedNode(n.type, sourceFile); + case 150: case 151: - case 180: + case 152: + case 225: + case 184: + case 149: + case 148: + case 154: + case 153: + case 185: if (n.body) { return isCompletedNode(n.body, sourceFile); } if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 18, sourceFile); - case 225: + return hasChildOfKind(n, 19, sourceFile); + case 230: return n.body && isCompletedNode(n.body, sourceFile); - case 203: + case 208: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 202: + case 207: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23); - case 170: - case 168: + hasChildOfKind(n, 24); + case 175: case 173: - case 140: - case 161: - return nodeEndsWith(n, 20, sourceFile); - case 153: + case 178: + case 142: + case 163: + return nodeEndsWith(n, 21, sourceFile); + case 155: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 20, sourceFile); - case 249: - case 250: + return hasChildOfKind(n, 21, sourceFile); + case 253: + case 254: return false; - case 206: - case 207: - case 208: - case 205: + case 211: + case 212: + case 213: + case 210: return isCompletedNode(n.statement, sourceFile); - case 204: - var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); + case 209: + var hasWhileKeyword = findChildOfKind(n, 105, sourceFile); if (hasWhileKeyword) { - return nodeEndsWith(n, 18, sourceFile); + return nodeEndsWith(n, 19, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 158: + case 160: return isCompletedNode(n.exprName, sourceFile); - case 182: - case 181: - case 183: - case 190: - case 191: + case 187: + case 186: + case 188: + case 195: + case 196: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176: + case 181: return isCompletedNode(n.template, sourceFile); - case 189: + case 194: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 197: + case 202: return ts.nodeIsPresent(n.literal); - case 236: - case 230: + case 241: + case 235: return ts.nodeIsPresent(n.moduleSpecifier); - case 185: + case 190: return isCompletedNode(n.operand, sourceFile); - case 187: + case 192: return isCompletedNode(n.right, sourceFile); - case 188: + case 193: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -48843,7 +52665,7 @@ var ts; if (last.kind === expectedLastToken) { return true; } - else if (last.kind === 23 && children.length !== 1) { + else if (last.kind === 24 && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -48872,7 +52694,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 292 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -48980,7 +52802,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 244) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -48988,16 +52810,16 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 244) { + if (isToken(n)) { return n; } var children = n.getChildren(); for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 244 && start === child.end); + (child.kind === 10 && start === child.end); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -49007,7 +52829,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 256); + ts.Debug.assert(startNode !== undefined || n.kind === 261); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -49046,19 +52868,19 @@ var ts; if (!token) { return false; } - if (token.kind === 244) { + if (token.kind === 10) { return true; } - if (token.kind === 25 && token.parent.kind === 244) { + if (token.kind === 26 && token.parent.kind === 10) { return true; } - if (token.kind === 25 && token.parent.kind === 248) { + if (token.kind === 26 && token.parent.kind === 252) { return true; } - if (token && token.kind === 16 && token.parent.kind === 248) { + if (token && token.kind === 17 && token.parent.kind === 252) { return true; } - if (token.kind === 25 && token.parent.kind === 245) { + if (token.kind === 26 && token.parent.kind === 249) { return true; } return false; @@ -49097,9 +52919,9 @@ var ts; var node = ts.getTokenAtPosition(sourceFile, position); if (isToken(node)) { switch (node.kind) { - case 102: - case 108: - case 74: + case 103: + case 109: + case 75: node = node.parent === undefined ? undefined : node.parent.parent; break; default: @@ -49108,11 +52930,11 @@ var ts; } } if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - if (jsDocComment.tags) { - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (jsDoc.tags) { + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; if (tag.pos <= position && position <= tag.end) { return tag; @@ -49149,21 +52971,21 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 || node.kind === 174) { + if (node.kind === 157 || node.kind === 179) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { + if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 227) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 && n.kind <= 138; + return n.kind >= 0 && n.kind <= 140; } ts.isToken = isToken; function isWord(kind) { - return kind === 69 || ts.isKeyword(kind); + return kind === 70 || ts.isKeyword(kind); } ts.isWord = isWord; function isPropertyName(kind) { @@ -49175,7 +52997,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 - || kind === 10 + || kind === 11 || ts.isTemplateLiteralKind(kind)) { return true; } @@ -49183,7 +53005,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 15 <= kind && kind <= 68; + return 16 <= kind && kind <= 69; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position) { @@ -49193,9 +53015,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 112: - case 110: + case 113: case 111: + case 112: return true; } return false; @@ -49218,18 +53040,18 @@ var ts; } ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 || - node.kind === 171) { - if (node.parent.kind === 187 && + if (node.kind === 175 || + node.kind === 176) { + if (node.parent.kind === 192 && node.parent.left === node && - node.parent.operatorToken.kind === 56) { + node.parent.operatorToken.kind === 57) { return true; } - if (node.parent.kind === 208 && + if (node.parent.kind === 213 && node.parent.initializer === node) { return true; } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 257 ? node.parent.parent : node.parent)) { return true; } } @@ -49258,10 +53080,9 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 144; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -49278,13 +53099,14 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; function writeIndent() { if (lineStart) { @@ -49314,7 +53136,7 @@ var ts; } } function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); + return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol) { var flags = symbol.flags; if (flags & 3) { @@ -49363,7 +53185,7 @@ var ts; } } ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { + function displayPart(text, kind) { return { text: text, kind: ts.SymbolDisplayPartKind[kind] @@ -49435,8 +53257,8 @@ var ts; if (isImportOrExportSpecifierName(location)) { return location.getText(); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140) { + else if (ts.isStringOrNumericLiteral(location) && + location.parent.kind === 142) { return location.text; } var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); @@ -49446,7 +53268,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 234 || location.parent.kind === 238) && + (location.parent.kind === 239 || location.parent.kind === 243) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -49481,7 +53303,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +53314,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -49548,176 +53373,176 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 200: + case 205: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 218: - case 145: - case 144: - return spanInVariableDeclaration(node); - case 142: - return spanInParameterDeclaration(node); - case 220: + case 223: case 147: case 146: + return spanInVariableDeclaration(node); + case 144: + return spanInParameterDeclaration(node); + case 225: case 149: - case 150: case 148: - case 179: - case 180: + case 151: + case 152: + case 150: + case 184: + case 185: return spanInFunctionDeclaration(node); - case 199: + case 204: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 226: + case 231: return spanInBlock(node); - case 252: + case 256: return spanInBlock(node.block); - case 202: - return textSpan(node.expression); - case 211: - return textSpan(node.getChildAt(0), node.expression); - case 205: - return textSpanEndingAtNextToken(node, node.expression); - case 204: - return spanInNode(node.statement); - case 217: - return textSpan(node.getChildAt(0)); - case 203: - return textSpanEndingAtNextToken(node, node.expression); - case 214: - return spanInNode(node.statement); - case 210: - case 209: - return textSpan(node.getChildAt(0), node.label); - case 206: - return spanInForStatement(node); case 207: - return textSpanEndingAtNextToken(node, node.expression); - case 208: - return spanInInitializerOfForLike(node); - case 213: - return textSpanEndingAtNextToken(node, node.expression); - case 249: - case 250: - return spanInNode(node.statements[0]); + return textSpan(node.expression); case 216: - return spanInBlock(node.tryBlock); + return textSpan(node.getChildAt(0), node.expression); + case 210: + return textSpanEndingAtNextToken(node, node.expression); + case 209: + return spanInNode(node.statement); + case 222: + return textSpan(node.getChildAt(0)); + case 208: + return textSpanEndingAtNextToken(node, node.expression); + case 219: + return spanInNode(node.statement); case 215: + case 214: + return textSpan(node.getChildAt(0), node.label); + case 211: + return spanInForStatement(node); + case 212: + return textSpanEndingAtNextToken(node, node.expression); + case 213: + return spanInInitializerOfForLike(node); + case 218: + return textSpanEndingAtNextToken(node, node.expression); + case 253: + case 254: + return spanInNode(node.statements[0]); + case 221: + return spanInBlock(node.tryBlock); + case 220: return textSpan(node, node.expression); - case 235: + case 240: return textSpan(node, node.expression); - case 229: + case 234: return textSpan(node, node.moduleReference); + case 235: + return textSpan(node, node.moduleSpecifier); + case 241: + return textSpan(node, node.moduleSpecifier); case 230: - return textSpan(node, node.moduleSpecifier); - case 236: - return textSpan(node, node.moduleSpecifier); - case 225: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 221: - case 224: - case 255: - case 169: + case 226: + case 229: + case 260: + case 174: return textSpan(node); - case 212: + case 217: return spanInNode(node.statement); - case 143: + case 145: return spanInNodeArray(node.parent.decorators); - case 167: - case 168: + case 172: + case 173: return spanInBindingPattern(node); - case 222: - case 223: + case 227: + case 228: return undefined; - case 23: + case 24: case 1: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 24: - return spanInPreviousNode(node); - case 15: - return spanInOpenBraceToken(node); - case 16: - return spanInCloseBraceToken(node); - case 20: - return spanInCloseBracketToken(node); - case 17: - return spanInOpenParenToken(node); - case 18: - return spanInCloseParenToken(node); - case 54: - return spanInColonToken(node); - case 27: case 25: + return spanInPreviousNode(node); + case 16: + return spanInOpenBraceToken(node); + case 17: + return spanInCloseBraceToken(node); + case 21: + return spanInCloseBracketToken(node); + case 18: + return spanInOpenParenToken(node); + case 19: + return spanInCloseParenToken(node); + case 55: + return spanInColonToken(node); + case 28: + case 26: return spanInGreaterThanOrLessThanToken(node); - case 104: + case 105: return spanInWhileKeyword(node); - case 80: - case 72: - case 85: + case 81: + case 73: + case 86: return spanInNextNode(node); - case 138: + case 140: return spanInOfKeyword(node); default: if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } - if ((node.kind === 69 || - node.kind == 191 || - node.kind === 253 || - node.kind === 254) && + if ((node.kind === 70 || + node.kind == 196 || + node.kind === 257 || + node.kind === 258) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 187) { + if (node.kind === 192) { var binaryExpression = node; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); } - if (binaryExpression.operatorToken.kind === 56 && + if (binaryExpression.operatorToken.kind === 57 && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { return textSpan(node); } - if (binaryExpression.operatorToken.kind === 24) { + if (binaryExpression.operatorToken.kind === 25) { return spanInNode(binaryExpression.left); } } if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { - case 204: + case 209: return spanInPreviousNode(node); - case 143: + case 145: return spanInNode(node.parent); - case 206: - case 208: + case 211: + case 213: return textSpan(node); - case 187: - if (node.parent.operatorToken.kind === 24) { + case 192: + if (node.parent.operatorToken.kind === 25) { return textSpan(node); } break; - case 180: + case 185: if (node.parent.body === node) { return textSpan(node); } break; } } - if (node.parent.kind === 253 && + if (node.parent.kind === 257 && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 177 && node.parent.type === node) { + if (node.parent.kind === 182 && node.parent.type === node) { return spanInNextNode(node.parent.type); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } - if ((node.parent.kind === 218 || - node.parent.kind === 142)) { + if ((node.parent.kind === 223 || + node.parent.kind === 144)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -49725,7 +53550,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 187) { + if (node.parent.kind === 192) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -49746,7 +53571,7 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 207) { + if (variableDeclaration.parent.parent.kind === 212) { return spanInNode(variableDeclaration.parent.parent); } if (ts.isBindingPattern(variableDeclaration.name)) { @@ -49754,7 +53579,7 @@ var ts; } if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1) || - variableDeclaration.parent.parent.kind === 208) { + variableDeclaration.parent.parent.kind === 213) { return textSpanFromVariableDeclaration(variableDeclaration); } var declarations = variableDeclaration.parent.declarations; @@ -49786,7 +53611,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1) || - (functionDeclaration.parent.kind === 221 && functionDeclaration.kind !== 148); + (functionDeclaration.parent.kind === 226 && functionDeclaration.kind !== 150); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -49806,22 +53631,22 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 225: + case 230: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 205: - case 203: - case 207: - return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 206: + case 210: case 208: + case 212: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + case 211: + case 213: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 219) { + if (forLikeStatement.initializer.kind === 224) { var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -49843,62 +53668,62 @@ var ts; } } function spanInBindingPattern(bindingPattern) { - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 193 ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 198 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - if (bindingPattern.parent.kind === 169) { + if (bindingPattern.parent.kind === 174) { return textSpan(bindingPattern.parent); } return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 168 && node.kind !== 167); - var elements = node.kind === 170 ? + ts.Debug.assert(node.kind !== 173 && node.kind !== 172); + var elements = node.kind === 175 ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 193 ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 198 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - return textSpan(node.parent.kind === 187 ? node.parent : node); + return textSpan(node.parent.kind === 192 ? node.parent : node); } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 224: + case 229: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 221: + case 226: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 227: + case 232: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 226: + case 231: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 224: - case 221: + case 229: + case 226: return textSpan(node); - case 199: + case 204: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 252: + case 256: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 227: + case 232: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 167: + case 172: var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -49911,7 +53736,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 168: + case 173: var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -49923,33 +53748,33 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 204 || - node.parent.kind === 174 || - node.parent.kind === 175) { + if (node.parent.kind === 209 || + node.parent.kind === 179 || + node.parent.kind === 180) { return spanInPreviousNode(node); } - if (node.parent.kind === 178) { + if (node.parent.kind === 183) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 179: - case 220: - case 180: - case 147: - case 146: + case 184: + case 225: + case 185: case 149: - case 150: case 148: - case 205: - case 204: - case 206: - case 208: - case 174: - case 175: - case 178: + case 151: + case 152: + case 150: + case 210: + case 209: + case 211: + case 213: + case 179: + case 180: + case 183: return spanInPreviousNode(node); default: return spanInNode(node.parent); @@ -49957,26 +53782,26 @@ var ts; } function spanInColonToken(node) { if (ts.isFunctionLike(node.parent) || - node.parent.kind === 253 || - node.parent.kind === 142) { + node.parent.kind === 257 || + node.parent.kind === 144) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 177) { + if (node.parent.kind === 182) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 204) { + if (node.parent.kind === 209) { return textSpanEndingAtNextToken(node, node.parent.expression); } return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 208) { + if (node.parent.kind === 213) { return spanInNextNode(node); } return spanInNode(node.parent); @@ -49989,27 +53814,27 @@ var ts; var ts; (function (ts) { function createClassifier() { - var scanner = ts.createScanner(2, false); + var scanner = ts.createScanner(5, false); var noRegexTable = []; - noRegexTable[69] = true; + noRegexTable[70] = true; noRegexTable[9] = true; noRegexTable[8] = true; - noRegexTable[10] = true; - noRegexTable[97] = true; - noRegexTable[41] = true; + noRegexTable[11] = true; + noRegexTable[98] = true; noRegexTable[42] = true; - noRegexTable[18] = true; - noRegexTable[20] = true; - noRegexTable[16] = true; - noRegexTable[99] = true; - noRegexTable[84] = true; + noRegexTable[43] = true; + noRegexTable[19] = true; + noRegexTable[21] = true; + noRegexTable[17] = true; + noRegexTable[100] = true; + noRegexTable[85] = true; var templateStack = []; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 || - keyword2 === 131 || - keyword2 === 121 || - keyword2 === 113) { + if (keyword2 === 124 || + keyword2 === 133 || + keyword2 === 122 || + keyword2 === 114) { return true; } return false; @@ -50092,7 +53917,7 @@ var ts; text = "}\n" + text; offset = 2; case 6: - templateStack.push(12); + templateStack.push(13); break; } scanner.setText(text); @@ -50104,55 +53929,55 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10) { - token = 10; + if ((token === 40 || token === 62) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 11) { + token = 11; } } - else if (lastNonTriviaToken === 21 && isKeyword(token)) { - token = 69; + else if (lastNonTriviaToken === 22 && isKeyword(token)) { + token = 70; } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 69; + token = 70; } - else if (lastNonTriviaToken === 69 && - token === 25) { + else if (lastNonTriviaToken === 70 && + token === 26) { angleBracketStack++; } - else if (token === 27 && angleBracketStack > 0) { + else if (token === 28 && angleBracketStack > 0) { angleBracketStack--; } - else if (token === 117 || + else if (token === 118 || + token === 134 || token === 132 || - token === 130 || - token === 120 || - token === 133) { + token === 121 || + token === 135) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - token = 69; + token = 70; } } - else if (token === 12) { + else if (token === 13) { templateStack.push(token); } - else if (token === 15) { + else if (token === 16) { if (templateStack.length > 0) { templateStack.push(token); } } - else if (token === 16) { + else if (token === 17) { if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12) { + if (lastTemplateStackToken === 13) { token = scanner.reScanTemplateToken(); - if (token === 14) { + if (token === 15) { templateStack.pop(); } else { - ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); + ts.Debug.assert(token === 14, "Should have been a template middle. Was " + token); } } else { - ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); + ts.Debug.assert(lastTemplateStackToken === 16, "Should have been an open brace. Was: " + token); templateStack.pop(); } } @@ -50190,10 +54015,10 @@ var ts; } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { - if (token === 14) { + if (token === 15) { result.endOfLineState = 5; } - else if (token === 11) { + else if (token === 12) { result.endOfLineState = 4; } else { @@ -50201,7 +54026,7 @@ var ts; } } } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 13) { result.endOfLineState = 6; } } @@ -50225,43 +54050,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 37: - case 39: + case 38: case 40: - case 35: + case 41: case 36: - case 43: + case 37: case 44: case 45: - case 25: - case 27: + case 46: + case 26: case 28: case 29: - case 91: - case 90: - case 116: case 30: + case 92: + case 91: + case 117: case 31: case 32: case 33: - case 46: - case 48: + case 34: case 47: - case 51: + case 49: + case 48: case 52: - case 67: - case 66: + case 53: case 68: - case 63: + case 67: + case 69: case 64: case 65: - case 57: + case 66: case 58: case 59: - case 61: + case 60: case 62: - case 56: - case 24: + case 63: + case 57: + case 25: return true; default: return false; @@ -50269,19 +54094,19 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 41: case 42: + case 43: return true; default: return false; } } function isKeyword(token) { - return token >= 70 && token <= 138; + return token >= 71 && token <= 140; } function classFromKind(token) { if (isKeyword(token)) { @@ -50290,7 +54115,7 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5; } - else if (token >= 15 && token <= 68) { + else if (token >= 16 && token <= 69) { return 10; } switch (token) { @@ -50298,7 +54123,7 @@ var ts; return 4; case 9: return 6; - case 10: + case 11: return 7; case 7: case 3: @@ -50307,7 +54132,7 @@ var ts; case 5: case 4: return 8; - case 69: + case 70: default: if (ts.isTemplateLiteralKind(token)) { return 6; @@ -50327,10 +54152,10 @@ var ts; ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { switch (kind) { + case 230: + case 226: + case 227: case 225: - case 221: - case 222: - case 220: cancellationToken.throwIfCancellationRequested(); } } @@ -50374,7 +54199,7 @@ var ts; return undefined; function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 && + return declaration.kind === 230 && ts.getModuleInstanceState(declaration) === 1; }); } @@ -50383,7 +54208,7 @@ var ts; if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { var kind = node.kind; checkForClassificationCancellation(cancellationToken, kind); - if (kind === 69 && !ts.nodeIsMissing(node)) { + if (kind === 70 && !ts.nodeIsMissing(node)) { var identifier = node; if (classifiableNames[identifier.text]) { var symbol = typeChecker.getSymbolAtLocation(node); @@ -50446,8 +54271,8 @@ var ts; function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { var spanStart = span.start; var spanLength = span.length; - var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 }; @@ -50515,16 +54340,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 275: + case 281: processJSDocParameterTag(tag); break; - case 278: + case 284: processJSDocTemplateTag(tag); break; - case 277: + case 283: processElement(tag.typeExpression); break; - case 276: + case 282: processElement(tag.typeExpression); break; } @@ -50589,10 +54414,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 10 && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 10 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -50605,22 +54430,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 243: + case 248: if (token.parent.tagName === token) { return 19; } break; - case 245: + case 249: if (token.parent.tagName === token) { return 20; } break; - case 242: + case 247: if (token.parent.tagName === token) { return 21; } break; - case 246: + case 250: if (token.parent.name === token) { return 22; } @@ -50632,25 +54457,25 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3; } - if (tokenKind === 25 || tokenKind === 27) { + if (tokenKind === 26 || tokenKind === 28) { if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return 10; } } if (ts.isPunctuation(tokenKind)) { if (token) { - if (tokenKind === 56) { - if (token.parent.kind === 218 || - token.parent.kind === 145 || - token.parent.kind === 142 || - token.parent.kind === 246) { + if (tokenKind === 57) { + if (token.parent.kind === 223 || + token.parent.kind === 147 || + token.parent.kind === 144 || + token.parent.kind === 250) { return 5; } } - if (token.parent.kind === 187 || - token.parent.kind === 185 || - token.parent.kind === 186 || - token.parent.kind === 188) { + if (token.parent.kind === 192 || + token.parent.kind === 190 || + token.parent.kind === 191 || + token.parent.kind === 193) { return 5; } } @@ -50660,49 +54485,48 @@ var ts; return 4; } else if (tokenKind === 9) { - return token.parent.kind === 246 ? 24 : 6; + return token.parent.kind === 250 ? 24 : 6; } - else if (tokenKind === 10) { + else if (tokenKind === 11) { return 6; } else if (ts.isTemplateLiteralKind(tokenKind)) { return 6; } - else if (tokenKind === 244) { + else if (tokenKind === 10) { return 23; } - else if (tokenKind === 69) { + else if (tokenKind === 70) { if (token) { switch (token.parent.kind) { - case 221: + case 226: if (token.parent.name === token) { return 11; } return; - case 141: + case 143: if (token.parent.name === token) { return 15; } return; - case 222: + case 227: if (token.parent.name === token) { return 13; } return; - case 224: + case 229: if (token.parent.name === token) { return 12; } return; - case 225: + case 230: if (token.parent.name === token) { return 14; } return; - case 142: + case 144: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,25 +54567,25 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 245) { + location.parent && location.parent.kind === 249) { var tagName = location.parent.parent.openingElement.tagName; entries.push({ name: tagName.text, kind: undefined, kindModifiers: undefined, - sortText: "0" + sortText: "0", }); } else { @@ -50773,17 +54597,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_45 in nameTable) { + if (nameTable[name_45] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_45]) { + uniqueNames[name_45] = name_45; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_45), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50806,7 +54630,7 @@ var ts; name: displayName, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - sortText: "0" + sortText: "0", }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { @@ -50833,19 +54657,21 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 257 && + node.parent.parent.kind === 176 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { return getStringLiteralCompletionEntriesFromElementAccess(node.parent); } - else if (node.parent.kind === 230 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + else if (node.parent.kind === 235 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { return getStringLiteralCompletionEntriesFromModuleNames(node); } else { var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); } return getStringLiteralCompletionEntriesFromContextualType(node); } @@ -50856,11 +54682,11 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { var candidates = []; var entries = []; typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); @@ -50872,7 +54698,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +54708,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +54719,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50902,7 +54728,7 @@ var ts; if (!type) { return; } - if (type.flags & 524288) { + if (type.flags & 65536) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { @@ -50934,6 +54760,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +54791,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +54955,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +54968,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51167,7 +54996,7 @@ var ts; if (typeRoots) { for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); + getCompletionEntriesFromDirectories(host, root, span, result); } } } @@ -51175,12 +55004,12 @@ var ts; for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { var packageJson = _d[_c]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + getCompletionEntriesFromDirectories(host, typesDir, span, result); } } return result; } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + function getCompletionEntriesFromDirectories(host, directory, span, result) { if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { @@ -51200,11 +55029,11 @@ var ts; if (currentConfigPath) { paths.push(currentConfigPath); currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_16 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_16) { + var parent_13 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_13) { break; } - currentDir = parent_16; + currentDir = parent_13; } else { break; @@ -51281,10 +55110,10 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location_3 = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -51310,8 +55139,8 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location_4 = completionData.location; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_4) === entryName ? s : undefined; }); } return undefined; } @@ -51336,9 +55165,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 277: - case 275: - case 276: + case 283: + case 281: + case 282: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -51347,7 +55176,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51373,13 +55202,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21) { - if (parent_17.kind === 172) { + var parent_14 = contextToken.parent, kind = contextToken.kind; + if (kind === 22) { + if (parent_14.kind === 177) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_17.kind === 139) { + else if (parent_14.kind === 141) { node = contextToken.parent.left; isRightOfDot = true; } @@ -51388,17 +55217,18 @@ var ts; } } else if (sourceFile.languageVariant === 1) { - if (kind === 25) { + if (kind === 26) { isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 && contextToken.parent.kind === 245) { + else if (kind === 40 && contextToken.parent.kind === 249) { isStartingCloseTag = true; location = contextToken; } } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51431,11 +55261,12 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 139 || node.kind === 172) { + if (node.kind === 70 || node.kind === 141 || node.kind === 177) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { symbol = typeChecker.getAliasedSymbol(symbol); @@ -51460,7 +55291,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 524288) { + if (isJavaScriptFile && type.flags & 65536) { var unionType = type; for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { var elementType = _c[_b]; @@ -51481,7 +55312,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { + if ((jsxContainer.kind === 247) || (jsxContainer.kind === 248)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); @@ -51500,6 +55331,13 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + if (scopeNode) { + isGlobalCompletion = + scopeNode.kind === 261 || + scopeNode.kind === 194 || + scopeNode.kind === 252 || + ts.isStatement(scopeNode); + } var symbolMeanings = 793064 | 107455 | 1920 | 8388608; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; @@ -51521,15 +55359,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 244) { + if (contextToken.kind === 10) { return true; } - if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 243) { + if (contextToken.kind === 28 && contextToken.parent) { + if (contextToken.parent.kind === 248) { return true; } - if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241; + if (contextToken.parent.kind === 249 || contextToken.parent.kind === 247) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 246; } } return false; @@ -51538,41 +55376,41 @@ var ts; if (previousToken) { var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { - case 24: - return containingNodeKind === 174 - || containingNodeKind === 148 + case 25: + return containingNodeKind === 179 + || containingNodeKind === 150 + || containingNodeKind === 180 || containingNodeKind === 175 - || containingNodeKind === 170 - || containingNodeKind === 187 - || containingNodeKind === 156; - case 17: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 178 - || containingNodeKind === 164; - case 19: - return containingNodeKind === 170 - || containingNodeKind === 153 - || containingNodeKind === 140; - case 125: - case 126: + || containingNodeKind === 192 + || containingNodeKind === 158; + case 18: + return containingNodeKind === 179 + || containingNodeKind === 150 + || containingNodeKind === 180 + || containingNodeKind === 183 + || containingNodeKind === 166; + case 20: + return containingNodeKind === 175 + || containingNodeKind === 155 + || containingNodeKind === 142; + case 127: + case 128: return true; - case 21: - return containingNodeKind === 225; - case 15: - return containingNodeKind === 221; - case 56: - return containingNodeKind === 218 - || containingNodeKind === 187; - case 12: - return containingNodeKind === 189; + case 22: + return containingNodeKind === 230; + case 16: + return containingNodeKind === 226; + case 57: + return containingNodeKind === 223 + || containingNodeKind === 192; case 13: - return containingNodeKind === 197; - case 112: - case 110: + return containingNodeKind === 194; + case 14: + return containingNodeKind === 202; + case 113: case 111: - return containingNodeKind === 145; + case 112: + return containingNodeKind === 147; } switch (previousToken.getText()) { case "public": @@ -51585,7 +55423,7 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 - || contextToken.kind === 10 + || contextToken.kind === 11 || ts.isTemplateLiteralKind(contextToken.kind)) { var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); @@ -51594,7 +55432,7 @@ var ts; } if (position === end) { return !!contextToken.isUnterminated - || contextToken.kind === 10; + || contextToken.kind === 11; } } return false; @@ -51603,22 +55441,22 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 171) { + if (objectLikeContainer.kind === 176) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 167) { + else if (objectLikeContainer.kind === 172) { isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142) { + if (!canGetType && rootDeclaration.kind === 144) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { + else if (rootDeclaration.parent.kind === 149 || rootDeclaration.parent.kind === 152) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -51644,9 +55482,9 @@ var ts; return true; } function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 ? - 230 : - 236; + var declarationKind = namedImportsOrExports.kind === 238 ? + 235 : + 241; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -51665,11 +55503,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15: - case 24: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { - return parent_18; + case 16: + case 25: + var parent_15 = contextToken.parent; + if (parent_15 && (parent_15.kind === 176 || parent_15.kind === 172)) { + return parent_15; } break; } @@ -51679,11 +55517,11 @@ var ts; function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15: - case 24: + case 16: + case 25: switch (contextToken.parent.kind) { - case 233: - case 237: + case 238: + case 242: return contextToken.parent; } } @@ -51692,34 +55530,34 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_19 = contextToken.parent; + var parent_16 = contextToken.parent; switch (contextToken.kind) { - case 26: - case 39: - case 69: - case 246: - case 247: - if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { - return parent_19; + case 27: + case 40: + case 70: + case 250: + case 251: + if (parent_16 && (parent_16.kind === 247 || parent_16.kind === 248)) { + return parent_16; } - else if (parent_19.kind === 246) { - return parent_19.parent; + else if (parent_16.kind === 250) { + return parent_16.parent; } break; case 9: - if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { - return parent_19.parent; + if (parent_16 && ((parent_16.kind === 250) || (parent_16.kind === 251))) { + return parent_16.parent; } break; - case 16: - if (parent_19 && - parent_19.kind === 248 && - parent_19.parent && - (parent_19.parent.kind === 246)) { - return parent_19.parent.parent; + case 17: + if (parent_16 && + parent_16.kind === 252 && + parent_16.parent && + (parent_16.parent.kind === 250)) { + return parent_16.parent.parent; } - if (parent_19 && parent_19.kind === 247) { - return parent_19.parent; + if (parent_16 && parent_16.kind === 251) { + return parent_16.parent; } break; } @@ -51728,16 +55566,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 179: - case 180: - case 220: - case 147: - case 146: + case 184: + case 185: + case 225: case 149: - case 150: + case 148: case 151: case 152: case 153: + case 154: + case 155: return true; } return false; @@ -51745,67 +55583,67 @@ var ts; function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { - case 24: - return containingNodeKind === 218 || - containingNodeKind === 219 || - containingNodeKind === 200 || - containingNodeKind === 224 || - isFunction(containingNodeKind) || - containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 168 || - containingNodeKind === 223; - case 21: - return containingNodeKind === 168; - case 54: - return containingNodeKind === 169; - case 19: - return containingNodeKind === 168; - case 17: - return containingNodeKind === 252 || - isFunction(containingNodeKind); - case 15: - return containingNodeKind === 224 || - containingNodeKind === 222 || - containingNodeKind === 159; - case 23: - return containingNodeKind === 144 && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 || - contextToken.parent.parent.kind === 159); case 25: - return containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 223 || - isFunction(containingNodeKind); - case 113: - return containingNodeKind === 145; + return containingNodeKind === 223 || + containingNodeKind === 224 || + containingNodeKind === 205 || + containingNodeKind === 229 || + isFunction(containingNodeKind) || + containingNodeKind === 226 || + containingNodeKind === 197 || + containingNodeKind === 227 || + containingNodeKind === 173 || + containingNodeKind === 228; case 22: - return containingNodeKind === 142 || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168); - case 112: - case 110: - case 111: - return containingNodeKind === 142; - case 116: - return containingNodeKind === 234 || - containingNodeKind === 238 || - containingNodeKind === 232; - case 73: - case 81: - case 107: - case 87: - case 102: - case 123: - case 131: - case 89: - case 108: - case 74: + return containingNodeKind === 173; + case 55: + return containingNodeKind === 174; + case 20: + return containingNodeKind === 173; + case 18: + return containingNodeKind === 256 || + isFunction(containingNodeKind); + case 16: + return containingNodeKind === 229 || + containingNodeKind === 227 || + containingNodeKind === 161; + case 24: + return containingNodeKind === 146 && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 227 || + contextToken.parent.parent.kind === 161); + case 26: + return containingNodeKind === 226 || + containingNodeKind === 197 || + containingNodeKind === 227 || + containingNodeKind === 228 || + isFunction(containingNodeKind); case 114: - case 134: + return containingNodeKind === 147; + case 23: + return containingNodeKind === 144 || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 173); + case 113: + case 111: + case 112: + return containingNodeKind === 144; + case 117: + return containingNodeKind === 239 || + containingNodeKind === 243 || + containingNodeKind === 237; + case 74: + case 82: + case 108: + case 88: + case 103: + case 124: + case 133: + case 90: + case 109: + case 75: + case 115: + case 136: return true; } switch (contextToken.getText()) { @@ -51842,8 +55680,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_46 = element.propertyName || element.name; + existingImportsOrExports[name_46.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51857,18 +55695,20 @@ var ts; var existingMemberNames = ts.createMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 253 && - m.kind !== 254 && - m.kind !== 169 && - m.kind !== 147) { + if (m.kind !== 257 && + m.kind !== 258 && + m.kind !== 174 && + m.kind !== 149 && + m.kind !== 151 && + m.kind !== 152) { continue; } if (m.getStart() <= position && position <= m.getEnd()) { continue; } var existingName = void 0; - if (m.kind === 169 && m.propertyName) { - if (m.propertyName.kind === 69) { + if (m.kind === 174 && m.propertyName) { + if (m.propertyName.kind === 70) { existingName = m.propertyName.text; } } @@ -51886,7 +55726,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 246) { + if (attr.kind === 250) { seenNames[attr.name.text] = true; } } @@ -51919,7 +55759,7 @@ var ts; return name; } var keywordCompletions = []; - for (var i = 70; i <= 138; i++) { + for (var i = 71; i <= 140; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ts.ScriptElementKind.keyword, @@ -51927,7 +55767,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104)) { + if (pushKeywordIf(keywords, loopTokens[i], 105)) { break; } } @@ -52330,7 +56170,7 @@ var ts; var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); + pushKeywordIf(keywords, statement.getFirstToken(), 71, 76); } }); return ts.map(keywords, getHighlightSpanForNode); @@ -52339,13 +56179,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: - return getLoopBreakContinueOccurrences(owner); + case 211: + case 212: case 213: + case 209: + case 210: + return getLoopBreakContinueOccurrences(owner); + case 218: return getSwitchCaseDefaultOccurrences(owner); } } @@ -52353,13 +56193,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 97); ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); + pushKeywordIf(keywords, clause.getFirstToken(), 72, 78); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70); + pushKeywordIf(keywords, statement.getFirstToken(), 71); } }); }); @@ -52367,13 +56207,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 101); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 86); } return ts.map(keywords, getHighlightSpanForNode); } @@ -52384,50 +56224,50 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99); }); if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95); }); } return ts.map(keywords, getHighlightSpanForNode); } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 199))) { + if (!(func && hasKind(func.body, 204))) { return undefined; } var keywords = []; ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95); }); ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99); }); return ts.map(keywords, getHighlightSpanForNode); } function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 208) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88); + pushKeywordIf(keywords, children[0], 89); for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80)) { + if (pushKeywordIf(keywords, children[i], 81)) { break; } } - if (!hasKind(ifStatement.elseStatement, 203)) { + if (!hasKind(ifStatement.elseStatement, 208)) { break; } ifStatement = ifStatement.elseStatement; } var result = []; for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 && i < keywords.length - 1) { + if (keywords[i].kind === 81 && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; var shouldCombindElseAndIf = true; @@ -52455,7 +56295,7 @@ var ts; } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 219; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -52580,9 +56420,9 @@ var ts; if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { break; } - case 69: - case 97: - case 121: + case 70: + case 98: + case 122: case 9: return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, false); } @@ -52603,7 +56443,7 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } - if (node.kind === 95) { + if (node.kind === 96) { return getReferencesForSuperKeyword(node); } } @@ -52628,9 +56468,9 @@ var ts; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var internedName = getInternedName(symbol, node); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = ts.getNameTable(sourceFile); if (nameTable[internedName] !== undefined) { @@ -52659,16 +56499,16 @@ var ts; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { if (symbol.flags & 8388608) { - var defaultImport = ts.getDeclarationOfKind(symbol, 231); + var defaultImport = ts.getDeclarationOfKind(symbol, 236); if (defaultImport) { return typeChecker.getAliasedSymbol(symbol); } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || - declaration.kind === 238) ? declaration : undefined; }); + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 239 || + declaration.kind === 243) ? declaration : undefined; }); if (importOrExportSpecifier && (!importOrExportSpecifier.propertyName || importOrExportSpecifier.propertyName === location)) { - return importOrExportSpecifier.kind === 234 ? + return importOrExportSpecifier.kind === 239 ? typeChecker.getAliasedSymbol(symbol) : typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); } @@ -52683,20 +56523,20 @@ var ts; typeChecker.getPropertySymbolOfDestructuringAssignment(location); } function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var bindingElement = ts.getDeclarationOfKind(symbol, 174); return bindingElement && - bindingElement.parent.kind === 167 && + bindingElement.parent.kind === 172 && !bindingElement.propertyName; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var bindingElement = ts.getDeclarationOfKind(symbol, 174); var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } return undefined; } - function getInternedName(symbol, location, declarations) { + function getInternedName(symbol, location) { if (ts.isImportOrExportSpecifierName(location)) { return location.getText(); } @@ -52706,13 +56546,13 @@ var ts; } function getSymbolScope(symbol) { var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { + if (valueDeclaration && (valueDeclaration.kind === 184 || valueDeclaration.kind === 197)) { return valueDeclaration; } if (symbol.flags & (4 | 8192)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221); + return ts.getAncestor(privateDeclaration, 226); } } if (symbol.flags & 8388608) { @@ -52736,7 +56576,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (container.kind === 256 && !ts.isExternalModule(container)) { + if (container.kind === 261 && !ts.isExternalModule(container)) { return undefined; } scope = container; @@ -52758,8 +56598,8 @@ var ts; if (position > end) break; var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5))) { positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); @@ -52796,7 +56636,7 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { if (node) { switch (node.kind) { - case 69: + case 70: return node.getWidth() === searchSymbolName.length; case 9: if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || @@ -52846,14 +56686,14 @@ var ts; if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 121, parents, inheritsFromCache); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 122, parents, inheritsFromCache); if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } else if (!(referenceSymbol.flags & 67108864) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } - else if (searchLocation.kind === 121) { + else if (searchLocation.kind === 122) { findAdditionalConstructorReferences(referenceSymbol, referenceLocation); } } @@ -52869,7 +56709,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== searchSymbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 1572864) { + else if (localParentType.flags & 196608) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -52903,17 +56743,17 @@ var ts; var result = []; for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148); + ts.Debug.assert(decl.kind === 150); var ctrKeyword = decl.getChildAt(0); - ts.Debug.assert(ctrKeyword.kind === 121); + ts.Debug.assert(ctrKeyword.kind === 122); result.push(ctrKeyword); } ts.forEachProperty(classSymbol.exports, function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 147) { + if (decl && decl.kind === 149) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97, function (thisKeyword) { + forEachDescendantOfKind(body, 98, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { result.push(thisKeyword); } @@ -52932,10 +56772,10 @@ var ts; var result = []; for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148); + ts.Debug.assert(decl.kind === 150); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 95, function (node) { + forEachDescendantOfKind(body, 96, function (node) { if (ts.isCallExpressionTarget(node)) { result.push(node); } @@ -52972,8 +56812,8 @@ var ts; if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { result.push(getReferenceEntryFromNode(refNode.parent)); } - else if (refNode.kind === 69) { - if (refNode.parent.kind === 254) { + else if (refNode.kind === 70) { + if (refNode.parent.kind === 258) { getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); } var containingClass = getContainingClassIfInHeritageClause(refNode); @@ -52983,24 +56823,24 @@ var ts; } var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference) { - var parent_21 = containingTypeReference.parent; - if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { - maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + var parent_18 = containingTypeReference.parent; + if (ts.isVariableLike(parent_18) && parent_18.type === containingTypeReference && parent_18.initializer && isImplementationExpression(parent_18.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_18.initializer)); } - else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { - if (parent_21.body.kind === 199) { - ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + else if (ts.isFunctionLike(parent_18) && parent_18.type === containingTypeReference && parent_18.body) { + if (parent_18.body.kind === 204) { + ts.forEachReturnStatement(parent_18.body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); } }); } - else if (isImplementationExpression(parent_21.body)) { - maybeAdd(getReferenceEntryFromNode(parent_21.body)); + else if (isImplementationExpression(parent_18.body)) { + maybeAdd(getReferenceEntryFromNode(parent_18.body)); } } - else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { - maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + else if (ts.isAssertionExpression(parent_18) && isImplementationExpression(parent_18.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_18.expression)); } } } @@ -53017,7 +56857,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 1572864) { + if (componentType.getFlags() & 196608) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -53035,26 +56875,26 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 194 - && node.parent.kind === 251 + if (node.kind === 199 + && node.parent.kind === 255 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 69 || node.kind === 172) { + else if (node.kind === 70 || node.kind === 177) { return getContainingClassIfInHeritageClause(node.parent); } } return undefined; } function isImplementationExpression(node) { - if (node.kind === 178) { + if (node.kind === 183) { return isImplementationExpression(node.expression); } - return node.kind === 180 || - node.kind === 179 || - node.kind === 171 || - node.kind === 192 || - node.kind === 170; + return node.kind === 185 || + node.kind === 184 || + node.kind === 176 || + node.kind === 197 || + node.kind === 175; } function explicitlyInheritsFrom(child, parent, cachedResults) { var parentIsInterface = parent.getFlags() & 64; @@ -53083,7 +56923,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 222) { + else if (declaration.kind === 227) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -53110,13 +56950,13 @@ var ts; } var staticFlag = 32; switch (searchSpaceNode.kind) { - case 145: - case 144: case 147: case 146: - case 148: case 149: + case 148: case 150: + case 151: + case 152: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; @@ -53129,7 +56969,7 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95) { + if (!node || node.kind !== 96) { return; } var container = ts.getSuperContainer(node, false); @@ -53144,32 +56984,32 @@ var ts; var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); var staticFlag = 32; switch (searchSpaceNode.kind) { - case 147: - case 146: + case 149: + case 148: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } - case 145: - case 144: - case 148: - case 149: + case 147: + case 146: case 150: + case 151: + case 152: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; - case 256: + case 261: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 220: - case 179: + case 225: + case 184: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 256) { + if (searchSpaceNode.kind === 261) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -53203,26 +57043,26 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 179: - case 220: + case 184: + case 225: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 147: - case 146: + case 149: + case 148: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 192: - case 221: + case 197: + case 226: if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 256: - if (container.kind === 256 && !ts.isExternalModule(container)) { + case 261: + if (container.kind === 261 && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -53236,8 +57076,8 @@ var ts; return undefined; } var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var sourceFile = sourceFiles_9[_i]; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); } @@ -53271,7 +57111,7 @@ var ts; function populateSearchSymbolSet(symbol, location) { var result = [symbol]; var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 258) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); if (propertySymbol) { result.push(propertySymbol); @@ -53290,7 +57130,7 @@ var ts; result.push(shorthandValueSymbol); } } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 144 && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); } @@ -53321,7 +57161,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 222) { + else if (declaration.kind === 227) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -53376,17 +57216,17 @@ var ts; return undefined; } } - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, ts.createMap()); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, ts.createMap()); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140) { + if (node.name.kind === 142) { var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } return undefined; @@ -53398,20 +57238,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_4 = []; + var result_5 = []; var symbol_2 = contextualType.getProperty(name); if (symbol_2) { - result_4.push(symbol_2); + result_5.push(symbol_2); } - if (contextualType.flags & 524288) { + if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); } - return result_4; + return result_5; } return undefined; } @@ -53453,7 +57293,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 218) { + else if (node.kind === 223) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2); } @@ -53463,18 +57303,18 @@ var ts; } else { switch (node.kind) { - case 221: - case 192: - case 224: - case 225: + case 226: + case 197: + case 229: + case 230: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 200) { - ts.Debug.assert(node.parent.kind === 219); + if (node.parent && node.parent.parent && node.parent.parent.kind === 205) { + ts.Debug.assert(node.parent.kind === 224); return node.parent.parent; } } @@ -53507,17 +57347,17 @@ var ts; } FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; function isWriteAccess(node) { - if (node.kind === 69 && ts.isDeclarationName(node)) { + if (node.kind === 70 && ts.isDeclarationName(node)) { return true; } var parent = node.parent; if (parent) { - if (parent.kind === 186 || parent.kind === 185) { + if (parent.kind === 191 || parent.kind === 190) { return true; } - else if (parent.kind === 187 && parent.left === node) { + else if (parent.kind === 192 && parent.left === node) { var operator = parent.operatorToken.kind; - return 56 <= operator && operator <= 68; + return 57 <= operator && operator <= 69; } } return false; @@ -53534,21 +57374,21 @@ var ts; switch (node.kind) { case 9: case 8: - if (node.parent.kind === 140) { + if (node.parent.kind === 142) { return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; } - case 69: + case 70: return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; } return undefined; } function isObjectLiteralPropertyDeclaration(node) { switch (node.kind) { - case 253: - case 254: - case 147: + case 257: + case 258: case 149: - case 150: + case 151: + case 152: return true; } return false; @@ -53605,13 +57445,13 @@ var ts; } if (symbol.flags & 8388608) { var declaration = symbol.declarations[0]; - if (node.kind === 69 && + if (node.kind === 70 && (node.parent === declaration || - (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { + (declaration.kind === 239 && declaration.parent && declaration.parent.kind === 238))) { symbol = typeChecker.getAliasedSymbol(symbol); } } - if (node.parent.kind === 254) { + if (node.parent.kind === 258) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -53638,14 +57478,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 && !(type.flags & 16)) { - var result_5 = []; + if (type.flags & 65536 && !(type.flags & 16)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_5, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_5; + return result_6; } if (!type.symbol) { return undefined; @@ -53665,7 +57505,7 @@ var ts; } return result; function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isNewExpressionTarget(location) || location.kind === 121) { + if (ts.isNewExpressionTarget(location) || location.kind === 122) { if (symbol.flags & 32) { for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; @@ -53688,8 +57528,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148) || - (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { + if ((selectConstructors && d.kind === 150) || + (!selectConstructors && (d.kind === 225 || d.kind === 149 || d.kind === 148))) { declarations.push(d); if (d.body) definition = d; @@ -53765,12 +57605,12 @@ var ts; var GoToImplementation; (function (GoToImplementation) { function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { - if (node.parent.kind === 254) { + if (node.parent.kind === 258) { var result = []; ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); return result.length > 0 ? result : undefined; } - else if (node.kind === 95 || ts.isSuperProperty(node.parent)) { + else if (node.kind === 96 || ts.isSuperProperty(node.parent)) { var symbol = typeChecker.getSymbolAtLocation(node); return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; } @@ -53815,6 +57655,7 @@ var ts; "lends", "link", "memberOf", + "method", "name", "namespace", "param", @@ -53834,10 +57675,10 @@ var ts; "version" ]; var jsDocCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getJSDocComments(declaration, true); + var comments = ts.getCommentsFromJSDoc(declaration); if (!comments) { return; } @@ -53873,7 +57714,7 @@ var ts; name: tagName, kind: ts.ScriptElementKind.keyword, kindModifiers: "", - sortText: "0" + sortText: "0", }; })); } @@ -53890,16 +57731,16 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 220: - case 147: - case 148: - case 221: - case 200: - break findOwner; - case 256: - return undefined; case 225: - if (commentOwner.parent.kind === 225) { + case 149: + case 150: + case 226: + case 205: + break findOwner; + case 261: + return undefined; + case 230: + if (commentOwner.parent.kind === 230) { return undefined; } break findOwner; @@ -53912,13 +57753,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; - var paramName = currentName.kind === 69 ? + var paramName = currentName.kind === 70 ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } var preamble = "/**" + newLine + indentationStr + " * "; @@ -53933,7 +57780,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 200) { + if (commentOwner.kind === 205) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -53943,17 +57790,17 @@ var ts; return ts.emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178) { + while (rightHandSide.kind === 183) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 179: - case 180: + case 184: + case 185: return rightHandSide.parameters; - case 192: + case 197: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 150) { return member.parameters; } } @@ -53964,160 +57811,22 @@ var ts; })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); })(ts || (ts = {})); var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_48 in packageNameToTypingLocation) { - if (name_48 in inferredTypings && !inferredTypings[name_48]) { - inferredTypings[name_48] = packageNameToTypingLocation[name_48]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - 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; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var baseSensitivity = { sensitivity: "base" }; ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_49 in nameToDeclarations) { - var declarations = nameToDeclarations[name_49]; + for (var name_47 in nameToDeclarations) { + var declarations = nameToDeclarations[name_47]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_47); if (!matches) { continue; } @@ -54128,21 +57837,21 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_49); + matches = patternMatcher.getMatches(containers, name_47); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_47, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } }); rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; - if (decl.kind === 231 || decl.kind === 234 || decl.kind === 229) { + if (decl.kind === 236 || decl.kind === 239 || decl.kind === 234) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; @@ -54169,7 +57878,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || node.kind === 8) { return node.text; @@ -54183,7 +57892,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 140) { + else if (declaration.name.kind === 142) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -54200,7 +57909,7 @@ var ts; } return true; } - if (expression.kind === 172) { + if (expression.kind === 177) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -54211,7 +57920,7 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 140) { + if (declaration.name.kind === 142) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -54239,8 +57948,8 @@ var ts; } function compareNavigateToItems(i1, i2) { return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -54272,6 +57981,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; var curSourceFile; function nodeText(node) { return node.getText(curSourceFile); @@ -54336,7 +58052,7 @@ var ts; return; } switch (node.kind) { - case 148: + case 150: var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { @@ -54346,28 +58062,28 @@ var ts; } } break; - case 147: case 149: - case 150: - case 146: + case 151: + case 152: + case 148: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 145: - case 144: + case 147: + case 146: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 231: + case 236: var importClause = node; if (importClause.name) { addLeafNode(importClause); } var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 232) { + if (namedBindings.kind === 237) { addLeafNode(namedBindings); } else { @@ -54378,12 +58094,12 @@ var ts; } } break; - case 169: - case 218: + case 174: + case 223: var decl = node; - var name_50 = decl.name; - if (ts.isBindingPattern(name_50)) { - addChildrenRecursively(name_50); + var name_48 = decl.name; + if (ts.isBindingPattern(name_48)) { + addChildrenRecursively(name_48); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -54392,12 +58108,12 @@ var ts; addNodeWithRecursiveChild(decl, decl.initializer); } break; - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: addNodeWithRecursiveChild(node, node.body); break; - case 224: + case 229: startNode(node); for (var _d = 0, _e = node.members; _d < _e.length; _d++) { var member = _e[_d]; @@ -54407,9 +58123,9 @@ var ts; } endNode(); break; - case 221: - case 192: - case 222: + case 226: + case 197: + case 227: startNode(node); for (var _f = 0, _g = node.members; _f < _g.length; _f++) { var member = _g[_f]; @@ -54417,21 +58133,21 @@ var ts; } endNode(); break; - case 225: + case 230: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 238: - case 229: + case 243: + case 234: + case 155: case 153: - case 151: - case 152: - case 223: + case 154: + case 228: addLeafNode(node); break; default: - ts.forEach(node.jsDocComments, function (jsDocComment) { - ts.forEach(jsDocComment.tags, function (tag) { - if (tag.kind === 279) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 285) { addLeafNode(tag); } }); @@ -54479,12 +58195,12 @@ var ts; } }); function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + return a.kind === b.kind && (a.kind !== 230 || areSameModule(a, b)); function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } - if (a.body.kind !== 225) { + if (a.body.kind !== 230) { return true; } return areSameModule(a.body, b.body); @@ -54517,9 +58233,8 @@ var ts; 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) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.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 === "'") { @@ -54528,7 +58243,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -54536,7 +58251,7 @@ var ts; return a.length - b.length; }; function tryGetName(node) { - if (node.kind === 225) { + if (node.kind === 230) { return getModuleName(node); } var decl = node; @@ -54544,18 +58259,18 @@ var ts; return ts.getPropertyNameForPropertyNameNode(decl.name); } switch (node.kind) { - case 179: - case 180: - case 192: + case 184: + case 185: + case 197: return getFunctionOrClassName(node); - case 279: + case 285: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 225) { + if (node.kind === 230) { return getModuleName(node); } var name = node.name; @@ -54566,29 +58281,29 @@ var ts; } } switch (node.kind) { - case 256: + case 261: 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: + case 185: + case 225: + case 184: + case 226: + case 197: if (ts.getModifierFlags(node) & 512) { return "default"; } return getFunctionOrClassName(node); - case 148: + case 150: return "constructor"; - case 152: + case 154: return "new()"; - case 151: - return "()"; case 153: + return "()"; + case 155: return "[]"; - case 279: + case 285: return getJSDocTypedefTagName(node); default: return ""; @@ -54600,10 +58315,10 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { + if (parentNode && parentNode.kind === 205) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { + if (nameIdentifier.kind === 70) { return nameIdentifier.text; } } @@ -54628,24 +58343,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 221: - case 192: - case 224: - case 222: - case 225: - case 256: - case 223: - case 279: + case 226: + case 197: + case 229: + case 227: + case 230: + case 261: + case 228: + case 285: return true; - case 148: - case 147: - case 149: case 150: - case 218: + case 149: + case 151: + case 152: + case 223: return hasSomeImportantChild(item); - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: return isTopLevelFunctionDeclaration(item); default: return false; @@ -54655,10 +58370,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 226: - case 256: - case 147: - case 148: + case 231: + case 261: + case 149: + case 150: return true; default: return hasSomeImportantChild(item); @@ -54667,12 +58382,21 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 218 && childKind !== 169; + return childKind !== 223 && childKind !== 174; }); } } } var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -54696,16 +58420,16 @@ var ts; grayed: false }; } - 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)); - } + } + 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 spans; } + return spans; } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { @@ -54713,20 +58437,20 @@ var ts; } var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 230) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } return result.join("."); } function getInteriorModule(decl) { - return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 230 ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 140; + return !member.name || member.name.kind === 142; } function getNodeSpan(node) { - return node.kind === 256 + return node.kind === 261 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); } @@ -54734,14 +58458,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 218) { + else if (node.parent.kind === 223) { 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 === 192 && + node.parent.operatorToken.kind === 57) { + return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 253 && node.parent.name) { + else if (node.parent.kind === 257 && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512) { @@ -54752,8 +58476,9 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 179 || node.kind === 180 || node.kind === 192; + return node.kind === 184 || node.kind === 185 || node.kind === 197; } + var whiteSpaceRegex = /\s+/g; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -54824,7 +58549,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180; + return ts.isFunctionBlock(node) && node.parent.kind !== 185; } var depth = 0; var maxDepth = 20; @@ -54836,30 +58561,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 199: + case 204: if (!ts.isFunctionBlock(n)) { - var parent_22 = n.parent; - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_22.kind === 204 || - parent_22.kind === 207 || - parent_22.kind === 208 || - parent_22.kind === 206 || - parent_22.kind === 203 || - parent_22.kind === 205 || - parent_22.kind === 212 || - parent_22.kind === 252) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + var parent_19 = n.parent; + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); + if (parent_19.kind === 209 || + parent_19.kind === 212 || + parent_19.kind === 213 || + parent_19.kind === 211 || + parent_19.kind === 208 || + parent_19.kind === 210 || + parent_19.kind === 217 || + parent_19.kind === 256) { + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_22.kind === 216) { - var tryStatement = parent_22; + if (parent_19.kind === 221) { + var tryStatement = parent_19; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86, sourceFile); if (finallyKeyword) { addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); break; @@ -54875,25 +58600,25 @@ var ts; }); break; } - case 226: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + case 231: { + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 221: - case 222: - case 224: - case 171: - case 227: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + case 226: + case 227: + case 229: + case 176: + case 232: { + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 170: - var openBracket = ts.findChildOfKind(n, 19, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20, sourceFile); + case 175: + var openBracket = ts.findChildOfKind(n, 20, sourceFile); + var closeBracket = ts.findChildOfKind(n, 21, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); break; } @@ -54909,13 +58634,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var PatternMatchKind; (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; - })(ts.PatternMatchKind || (ts.PatternMatchKind = {})); - var PatternMatchKind = ts.PatternMatchKind; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { return { kind: kind, @@ -55136,7 +58861,7 @@ var ts; if (ch >= 65 && ch <= 90) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 2)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { return false; } var str = String.fromCharCode(ch); @@ -55146,7 +58871,7 @@ var ts; if (ch >= 97 && ch <= 122) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 2)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { return false; } var str = String.fromCharCode(ch); @@ -55329,10 +59054,10 @@ var ts; var externalModule = false; function nextToken() { var token = ts.scanner.scan(); - if (token === 15) { + if (token === 16) { braceNesting++; } - else if (token === 16) { + else if (token === 17) { braceNesting--; } return token; @@ -55380,9 +59105,9 @@ var ts; } function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 122) { + if (token === 123) { token = nextToken(); - if (token === 125) { + if (token === 127) { token = nextToken(); if (token === 9) { recordAmbientExternalModule(); @@ -55394,42 +59119,42 @@ var ts; } function tryConsumeImport() { var token = ts.scanner.getToken(); - if (token === 89) { + if (token === 90) { token = nextToken(); if (token === 9) { recordModuleName(); return true; } else { - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); return true; } } - else if (token === 56) { + else if (token === 57) { if (tryConsumeRequireCall(true)) { return true; } } - else if (token === 24) { + else if (token === 25) { token = nextToken(); } else { return true; } } - if (token === 15) { + if (token === 16) { token = nextToken(); - while (token !== 16 && token !== 1) { + while (token !== 17 && token !== 1) { token = nextToken(); } - if (token === 16) { + if (token === 17) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55437,13 +59162,13 @@ var ts; } } } - else if (token === 37) { + else if (token === 38) { token = nextToken(); - if (token === 116) { + if (token === 117) { token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55459,17 +59184,17 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 82) { + if (token === 83) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 15) { + if (token === 16) { token = nextToken(); - while (token !== 16 && token !== 1) { + while (token !== 17 && token !== 1) { token = nextToken(); } - if (token === 16) { + if (token === 17) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55477,20 +59202,20 @@ var ts; } } } - else if (token === 37) { + else if (token === 38) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); } } } - else if (token === 89) { + else if (token === 90) { token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 56) { + if (token === 57) { if (tryConsumeRequireCall(true)) { return true; } @@ -55503,9 +59228,9 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 129) { + if (token === 131) { token = nextToken(); - if (token === 17) { + if (token === 18) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55517,27 +59242,27 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 69 && ts.scanner.getTokenValue() === "define") { + if (token === 70 && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 17) { + if (token !== 18) { return true; } token = nextToken(); if (token === 9) { token = nextToken(); - if (token === 24) { + if (token === 25) { token = nextToken(); } else { return true; } } - if (token !== 19) { + if (token !== 20) { return true; } token = nextToken(); var i = 0; - while (token !== 20 && token !== 1) { + while (token !== 21 && token !== 1) { if (token === 9) { recordModuleName(); i++; @@ -55609,7 +59334,7 @@ var ts; var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); var node = ts.getTouchingWord(sourceFile, position, true); if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || ts.isThis(node)) { @@ -55722,14 +59447,14 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 174) { + if (argumentInfo.invocation.kind !== 179) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; - var name = expression.kind === 69 + var name = expression.kind === 70 ? expression - : expression.kind === 172 + : expression.kind === 177 ? expression.name : undefined; if (!name || !name.text) { @@ -55758,10 +59483,10 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 174 || node.parent.kind === 175) { + if (node.parent.kind === 179 || node.parent.kind === 180) { var callExpression = node.parent; - if (node.kind === 25 || - node.kind === 17) { + if (node.kind === 26 || + node.kind === 18) { var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; ts.Debug.assert(list !== undefined); @@ -55790,24 +59515,24 @@ var ts; } return undefined; } - else if (node.kind === 11 && node.parent.kind === 176) { + else if (node.kind === 12 && node.parent.kind === 181) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0, sourceFile); } } - else if (node.kind === 12 && node.parent.parent.kind === 176) { + else if (node.kind === 13 && node.parent.parent.kind === 181) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189); + ts.Debug.assert(templateExpression.kind === 194); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 197 && node.parent.parent.parent.kind === 176) { + else if (node.parent.kind === 202 && node.parent.parent.parent.kind === 181) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189); - if (node.kind === 14 && !ts.isInsideTemplateLiteral(node, position)) { + ts.Debug.assert(templateExpression.kind === 194); + if (node.kind === 15 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); @@ -55824,7 +59549,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 24) { + if (child.kind !== 25) { argumentIndex++; } } @@ -55832,8 +59557,8 @@ var ts; } function getArgumentCount(argumentsList) { var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 24; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 24) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 25; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 25) { argumentCount++; } return argumentCount; @@ -55849,7 +59574,7 @@ var ts; return spanIndex + 1; } function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { - var argumentCount = tagExpression.template.kind === 11 + var argumentCount = tagExpression.template.kind === 12 ? 1 : tagExpression.template.templateSpans.length + 1; ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); @@ -55870,7 +59595,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 189) { + if (template.kind === 194) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -55879,7 +59604,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 256; n = n.parent) { + for (var n = node; n.kind !== 261; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -55929,35 +59654,38 @@ var ts; if (callTargetDisplayParts) { ts.addRange(prefixDisplayParts, callTargetDisplayParts); } + var isVariadic; if (isTypeParameterList) { - prefixDisplayParts.push(ts.punctuationPart(25)); + isVariadic = false; + prefixDisplayParts.push(ts.punctuationPart(26)); var typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(27)); + suffixDisplayParts.push(ts.punctuationPart(28)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); }); ts.addRange(suffixDisplayParts, parameterParts); } else { + isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); }); ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(17)); + prefixDisplayParts.push(ts.punctuationPart(18)); var parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(18)); + suffixDisplayParts.push(ts.punctuationPart(19)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); }); ts.addRange(suffixDisplayParts, returnTypeParts); return { - isVariadic: candidateSignature.hasRestParameter, + isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(24), ts.spacePart()], + separatorDisplayParts: [ts.punctuationPart(25), ts.spacePart()], parameters: signatureHelpParameters, documentation: candidateSignature.getDocumentationComment() }; @@ -56008,7 +59736,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = symbol.getFlags(); if (flags & 32) - return ts.getDeclarationOfKind(symbol, 192) ? + return ts.getDeclarationOfKind(symbol, 197) ? ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; if (flags & 384) return ts.ScriptElementKind.enumElement; @@ -56039,7 +59767,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return ts.ScriptElementKind.localVariableElement; } - if (location.kind === 97 && ts.isExpression(location)) { + if (location.kind === 98 && ts.isExpression(location)) { return ts.ScriptElementKind.parameterElement; } if (flags & 3) { @@ -56099,7 +59827,7 @@ var ts; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 && ts.isExpression(location); + var isThisExpression = location.kind === 98 && ts.isExpression(location); var type; if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { @@ -56108,14 +59836,14 @@ var ts; var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 172) { + if (location.parent && location.parent.kind === 177) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } var callExpression = void 0; - if (location.kind === 174 || location.kind === 175) { + if (location.kind === 179 || location.kind === 180) { callExpression = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -56127,7 +59855,7 @@ var ts; if (!signature && candidateSignatures.length) { signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; + var useConstructSignatures = callExpression.kind === 180 || callExpression.expression.kind === 96; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -56142,7 +59870,7 @@ var ts; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -56157,13 +59885,13 @@ var ts; case ts.ScriptElementKind.letElement: case ts.ScriptElementKind.parameterElement: case ts.ScriptElementKind.localVariableElement: - displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.punctuationPart(55)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152) && type.symbol) { + if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -56175,21 +59903,21 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 121 && location.parent.kind === 148)) { + (location.kind === 122 && location.parent.kind === 150)) { var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration.kind === 150 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 148) { + if (functionDeclaration.kind === 150) { symbolKind = ts.ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 153 && !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -56198,11 +59926,11 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192)) { + if (ts.getDeclarationOfKind(symbol, 197)) { pushTypePart(ts.ScriptElementKind.localClassElement); } else { - displayParts.push(ts.keywordPart(73)); + displayParts.push(ts.keywordPart(74)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -56210,72 +59938,72 @@ var ts; } if ((symbolFlags & 64) && (semanticMeaning & 2)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107)); + displayParts.push(ts.keywordPart(108)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.keywordPart(136)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74)); + displayParts.push(ts.keywordPart(75)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(81)); + displayParts.push(ts.keywordPart(82)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69; - displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); + var declaration = ts.getDeclarationOfKind(symbol, 230); + var isNamespace = declaration && declaration.name && declaration.name.kind === 70; + displayParts.push(ts.keywordPart(isNamespace ? 128 : 127)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144) && (semanticMeaning & 2)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(19)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90)); - displayParts.push(ts.spacePart()); if (symbol.parent) { + addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 141); + var declaration = ts.getDeclarationOfKind(symbol, 143); ts.Debug.assert(declaration !== undefined); declaration = declaration.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152) { - displayParts.push(ts.keywordPart(92)); + if (declaration.kind === 154) { + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 151 && declaration.name) { + else if (declaration.kind !== 153 && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); } - else { - displayParts.push(ts.keywordPart(134)); + else if (declaration.kind === 228) { + addInPrefix(); + displayParts.push(ts.keywordPart(136)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -56286,11 +60014,11 @@ var ts; if (symbolFlags & 8) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 255) { + if (declaration.kind === 260) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); } @@ -56298,33 +60026,33 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228) { - displayParts.push(ts.keywordPart(82)); + if (symbol.declarations[0].kind === 233) { + displayParts.push(ts.keywordPart(83)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126)); + displayParts.push(ts.keywordPart(128)); } else { - displayParts.push(ts.keywordPart(89)); + displayParts.push(ts.keywordPart(90)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229) { + if (declaration.kind === 234) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.keywordPart(131)); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(19)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -56338,7 +60066,7 @@ var ts; if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97)); + displayParts.push(ts.keywordPart(98)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -56347,7 +60075,7 @@ var ts; symbolFlags & 3 || symbolKind === ts.ScriptElementKind.localVariableElement || isThisExpression) { - displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.punctuationPart(55)); displayParts.push(ts.spacePart()); if (type.symbol && type.symbol.flags & 262144) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -56377,10 +60105,10 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); if (documentation.length === 0 && symbol.flags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187) { + if (!declaration.parent || declaration.parent.kind !== 192) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -56401,6 +60129,11 @@ var ts; displayParts.push(ts.lineBreakPart()); } } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(91)); + displayParts.push(ts.spacePart()); + } function addFullSymbolName(symbol, enclosingDeclaration) { var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); ts.addRange(displayParts, fullSymbolDisplayParts); @@ -56423,9 +60156,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(19)); return; } } @@ -56433,12 +60166,12 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.operatorPart(35)); + displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.operatorPart(36)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.punctuationPart(19)); } documentation = signature.getDocumentationComment(); } @@ -56455,14 +60188,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 179) { + if (declaration.kind === 184) { return true; } - if (declaration.kind !== 218 && declaration.kind !== 220) { + if (declaration.kind !== 223 && declaration.kind !== 225) { return false; } - for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { - if (parent_23.kind === 256 || parent_23.kind === 226) { + for (var parent_20 = declaration.parent; !ts.isFunctionBlock(parent_20); parent_20 = parent_20.parent) { + if (parent_20.kind === 261 || parent_20.kind === 231) { return false; } } @@ -56503,8 +60236,8 @@ var ts; var outputText; var sourceMapText; var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); sourceMapText = text; @@ -56520,9 +60253,9 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -56546,7 +60279,7 @@ var ts; return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_2 = function (opt) { + var _loop_3 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -56562,7 +60295,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_2(opt); + _loop_3(opt); } return options; } @@ -56571,11 +60304,11 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(2, false, 0); - var jsxScanner = ts.createScanner(2, false, 1); + var standardScanner = ts.createScanner(5, false, 0); + var jsxScanner = ts.createScanner(5, false, 1); var scanner; function getFormattingScanner(sourceFile, startPos, endPos) { - ts.Debug.assert(scanner === undefined); + ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); scanner = sourceFile.languageVariant === 1 ? jsxScanner : standardScanner; scanner.setText(sourceFile.text); scanner.setTextPos(startPos); @@ -56600,7 +60333,7 @@ var ts; } }; function advance() { - ts.Debug.assert(scanner !== undefined); + ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { @@ -56640,11 +60373,11 @@ var ts; function shouldRescanGreaterThanToken(node) { if (node) { switch (node.kind) { - case 29: - case 64: + case 30: case 65: + case 66: + case 46: case 45: - case 44: return true; } } @@ -56653,27 +60386,27 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 246: - case 243: - case 245: - case 242: - return node.kind === 69; + case 250: + case 248: + case 249: + case 247: + return node.kind === 70; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 244; + return node && node.kind === 10; } function shouldRescanSlashToken(container) { - return container.kind === 10; + return container.kind === 11; } function shouldRescanTemplateToken(container) { - return container.kind === 13 || - container.kind === 14; + return container.kind === 14 || + container.kind === 15; } function startsWithSlashToken(t) { - return t === 39 || t === 61; + return t === 40 || t === 62; } function readTokenInfo(n) { ts.Debug.assert(scanner !== undefined); @@ -56704,7 +60437,7 @@ var ts; scanner.scan(); } var currentToken = scanner.getToken(); - if (expectedScanAction === 1 && currentToken === 27) { + if (expectedScanAction === 1 && currentToken === 28) { currentToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 1; @@ -56714,11 +60447,11 @@ var ts; ts.Debug.assert(n.kind === currentToken); lastScanAction = 2; } - else if (expectedScanAction === 3 && currentToken === 16) { + else if (expectedScanAction === 3 && currentToken === 17) { currentToken = scanner.reScanTemplateToken(); lastScanAction = 3; } - else if (expectedScanAction === 4 && currentToken === 69) { + else if (expectedScanAction === 4 && currentToken === 70) { currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } @@ -56852,8 +60585,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 15, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 16, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 16, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 17, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -56949,7 +60682,7 @@ var ts; function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i - 0] = arguments[_i]; + funcs[_i] = arguments[_i]; } this.customContextChecks = funcs; } @@ -56982,88 +60715,88 @@ var ts; function Rules() { this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1)); - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16, 80), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16, 104), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.FromTokens([18, 20, 24, 23])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17, 81), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17, 105), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.FromTokens([19, 21, 25, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69, 3, 73, 82, 89]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18, 3, 79, 100, 85, 80]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([70, 3, 74, 83, 90]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([19, 3, 80, 101, 86, 81]); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); + this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); + this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102, 98, 92, 78, 94, 101, 119]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108, 74]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(43, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(37, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(37, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([103, 99, 93, 79, 95, 102, 120]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([109, 75]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); + this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(88, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(104, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(95, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([19, 80, 81, 72]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([101, 86]), 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124, 133]), 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 129]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 73, 122, 77, 81, 82, 83, 123, 106, 89, 107, 125, 126, 110, 112, 111, 131, 113, 134, 136]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83, 106, 136])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.FromTokens([18, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115, 69, 82, 77, 73, 113, 112, 110, 111, 123, 131, 19, 37])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37, formatting.Shared.TokenRange.FromTokens([69, 17])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114, 37]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([127, 131]), 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116, 74, 123, 78, 82, 83, 84, 124, 107, 90, 108, 127, 128, 111, 113, 112, 133, 114, 136, 138]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84, 107, 138])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(35, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(23, 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.FromTokens([19, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(19, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 28), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.FromTokens([18, 20, 28, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116, 70, 83, 78, 74, 114, 113, 111, 112, 124, 133, 20, 38])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(88, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(38, formatting.Shared.TokenRange.FromTokens([70, 18])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(115, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 38]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(119, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(119, 88), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(70, formatting.Shared.TokenRange.FromTokens([12, 13])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 40), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(40, 28), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(57, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -57118,81 +60851,81 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(18, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(20, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13, 14]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13, 14]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14, 15])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14, 15])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_51 in o) { - if (o[name_51] === rule) { - return name_51; + for (var name_49 in o) { + if (o[name_49] === rule) { + return name_49; } } throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 206; + return context.contextNode.kind === 211; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 187: - case 188: - case 195: - case 238: - case 234: - case 154: - case 162: - case 163: + case 192: + case 193: + case 200: + case 243: + case 239: + case 156: + case 164: + case 165: return true; - case 169: + case 174: + case 228: + case 234: case 223: - case 229: - case 218: - case 142: - case 255: - case 145: case 144: - return context.currentTokenSpan.kind === 56 || context.nextTokenSpan.kind === 56; - case 207: - return context.currentTokenSpan.kind === 90 || context.nextTokenSpan.kind === 90; - case 208: - return context.currentTokenSpan.kind === 138 || context.nextTokenSpan.kind === 138; + case 260: + case 147: + case 146: + return context.currentTokenSpan.kind === 57 || context.nextTokenSpan.kind === 57; + case 212: + return context.currentTokenSpan.kind === 91 || context.nextTokenSpan.kind === 91; + case 213: + return context.currentTokenSpan.kind === 140 || context.nextTokenSpan.kind === 140; } return false; }; @@ -57200,7 +60933,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 188; + return context.contextNode.kind === 193; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); @@ -57225,120 +60958,120 @@ var ts; return true; } switch (node.kind) { - case 199: - case 227: - case 171: - case 226: + case 204: + case 232: + case 176: + case 231: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 220: - case 147: - case 146: + case 225: case 149: - case 150: - case 151: - case 179: case 148: - case 180: - case 222: + case 151: + case 152: + case 153: + case 184: + case 150: + case 185: + case 227: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 220 || context.contextNode.kind === 179; + return context.contextNode.kind === 225 || context.contextNode.kind === 184; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 221: - case 192: - case 222: - case 224: - case 159: - case 225: - case 236: - case 237: + case 226: + case 197: + case 227: + case 229: + case 161: case 230: - case 233: + case 241: + case 242: + case 235: + case 238: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 221: - case 225: - case 224: - case 199: - case 252: case 226: - case 213: + case 230: + case 229: + case 204: + case 256: + case 231: + case 218: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 203: - case 213: - case 206: - case 207: case 208: - case 205: - case 216: - case 204: + case 218: + case 211: case 212: - case 252: + case 213: + case 210: + case 221: + case 209: + case 217: + case 256: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 171; + return context.contextNode.kind === 176; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 174; + return context.contextNode.kind === 179; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 175; + return context.contextNode.kind === 180; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); }; Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 24; + return context.currentTokenSpan.kind !== 25; }; Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 20; + return context.nextTokenSpan.kind !== 21; }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 180; + return context.contextNode.kind === 185; }; Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; }; Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 241; + return context.contextNode.kind !== 246; }; Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 248; + return context.contextNode.kind === 252; }; Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246; + return context.nextTokenParent.kind === 250; }; Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246; + return context.contextNode.kind === 250; }; Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242; + return context.contextNode.kind === 247; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -57353,41 +61086,41 @@ var ts; while (ts.isPartOfExpression(node)) { node = node.parent; } - return node.kind === 143; + return node.kind === 145; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 219 && + return context.currentTokenParent.kind === 224 && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 225; + return context.contextNode.kind === 230; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 159; + return context.contextNode.kind === 161; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 25 && token.kind !== 27) { + if (token.kind !== 26 && token.kind !== 28) { return false; } switch (parent.kind) { - case 155: - case 177: - case 221: - case 192: - case 222: - case 220: + case 157: + case 182: + case 226: + case 197: + case 227: + case 225: + case 184: + case 185: + case 149: + case 148: + case 153: + case 154: case 179: case 180: - case 147: - case 146: - case 151: - case 152: - case 174: - case 175: - case 194: + case 199: return true; default: return false; @@ -57398,13 +61131,13 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 177; + return context.contextNode.kind === 182; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 183; + return context.currentTokenSpan.kind === 104 && context.currentTokenParent.kind === 188; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 190 && context.contextNode.expression !== undefined; + return context.contextNode.kind === 195 && context.contextNode.expression !== undefined; }; return Rules; }()); @@ -57426,7 +61159,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 138 + 1; + this.mapRowLength = 140 + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); var rulesBucketConstructionStateList = new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); @@ -57439,6 +61172,7 @@ var ts; }); }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + ts.Debug.assert(row <= 140 && column <= 140, "Must compute formatting context from tokens"); var rulesBucketIndex = (row * this.mapRowLength) + column; return rulesBucketIndex; }; @@ -57475,6 +61209,7 @@ var ts; formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; + var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; @@ -57482,8 +61217,7 @@ var ts; RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesPosition = formatting.RulesPosition; + })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); var RulesBucketConstructionState = (function () { function RulesBucketConstructionState() { this.rulesInsertionIndexBitmap = 0; @@ -57602,12 +61336,12 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0; token <= 138; token++) { + for (var token = 0; token <= 140; token++) { result.push(token); } return result; }; - TokenAllAccess.prototype.Contains = function (tokenValue) { + TokenAllAccess.prototype.Contains = function () { return true; }; TokenAllAccess.prototype.toString = function () { @@ -57646,17 +61380,17 @@ var ts; }()); TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(70, 138); - TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.Keywords = TokenRange.FromRange(71, 140); + TokenRange.BinaryOperators = TokenRange.FromRange(26, 69); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91, 92, 140, 117, 125]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([42, 43, 51, 50]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 70, 18, 20, 16, 98, 93]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([70, 18, 98, 93]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([70, 19, 21, 93]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([70, 18, 98, 93]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([70, 19, 21, 93]); TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); + TokenRange.TypeNames = TokenRange.FromTokens([70, 132, 134, 121, 135, 104, 118]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -57689,25 +61423,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -57717,7 +61451,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -57727,7 +61461,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -57737,7 +61471,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -57745,7 +61479,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -57753,13 +61487,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -57767,14 +61501,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -57812,11 +61546,11 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 23, sourceFile, options, rulesProvider, 3); + return formatOutermostParent(position, 24, sourceFile, options, rulesProvider, 3); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 16, sourceFile, options, rulesProvider, 4); + return formatOutermostParent(position, 17, sourceFile, options, rulesProvider, 4); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -57864,17 +61598,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 221: - case 222: - return ts.rangeContainsRange(parent.members, node); - case 225: - var body = parent.body; - return body && body.kind === 199 && ts.rangeContainsRange(body.statements, node); - case 256: - case 199: case 226: + case 227: + return ts.rangeContainsRange(parent.members, node); + case 230: + var body = parent.body; + return body && body.kind === 231 && ts.rangeContainsRange(body.statements, node); + case 261: + case 204: + case 231: return ts.rangeContainsRange(parent.statements, node); - case 252: + case 256: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -57918,7 +61652,7 @@ var ts; index++; } }; - function rangeHasNoErrors(r) { + function rangeHasNoErrors() { return false; } } @@ -57945,7 +61679,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -58005,12 +61739,12 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -58030,18 +61764,18 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 221: return 73; - case 222: return 107; - case 220: return 87; - case 224: return 224; - case 149: return 123; - case 150: return 131; - case 147: + case 226: return 74; + case 227: return 108; + case 225: return 88; + case 229: return 229; + case 151: return 124; + case 152: return 133; + case 149: if (node.asteriskToken) { - return 37; + return 38; } - case 145: - case 142: + case 147: + case 144: return node.name.kind; } } @@ -58049,9 +61783,9 @@ var ts; return { getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { - case 16: - case 20: - case 18: + case 17: + case 21: + case 19: return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; @@ -58063,15 +61797,15 @@ var ts; } } switch (kind) { - case 15: case 16: - case 19: - case 20: case 17: + case 20: + case 21: case 18: - case 80: - case 104: - case 55: + case 19: + case 81: + case 105: + case 56: return indentation; default: return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; @@ -58082,13 +61816,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -58151,17 +61885,17 @@ var ts; if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (ts.isToken(child)) { + if (ts.isToken(child) && child.kind !== 10) { var tokenInfo = formattingScanner.readTokenInfo(child); - ts.Debug.assert(tokenInfo.token.end === child.end); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 143 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 145 ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent.kind === 170 && inheritedIndentation === -1) { + if (isFirstListItem && parent.kind === 175 && inheritedIndentation === -1) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -58336,11 +62070,23 @@ var ts; else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); - if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } } } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } @@ -58448,7 +62194,7 @@ var ts; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2: @@ -58465,41 +62211,41 @@ var ts; } function getOpenTokenForList(node, list) { switch (node.kind) { + case 150: + case 225: + case 184: + case 149: case 148: - case 220: - case 179: - case 147: - case 146: - case 180: + case 185: if (node.typeParameters === list) { - return 25; + return 26; } else if (node.parameters === list) { - return 17; + return 18; } break; - case 174: - case 175: + case 179: + case 180: if (node.typeArguments === list) { - return 25; + return 26; } else if (node.arguments === list) { - return 17; + return 18; } break; - case 155: + case 157: if (node.typeArguments === list) { - return 25; + return 26; } } return 0; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 17: - return 18; - case 25: - return 27; + case 18: + return 19; + case 26: + return 28; } return 0; } @@ -58507,14 +62253,14 @@ var ts; var internedTabsIndentation; var internedSpacesIndentation; function getIndentationString(indentation, options) { - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -58529,13 +62275,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -58564,7 +62310,7 @@ var ts; if (position > sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +62322,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58588,7 +62334,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 && precedingToken.parent.kind !== 187) { + if (precedingToken.kind === 25 && precedingToken.parent.kind !== 192) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; @@ -58605,7 +62351,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +62361,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +62372,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +62410,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58690,7 +62436,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 256 || !parentAndChildShareLine); + (parent.kind === 261 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -58701,10 +62447,10 @@ var ts; if (!nextToken) { return false; } - if (nextToken.kind === 15) { + if (nextToken.kind === 16) { return true; } - else if (nextToken.kind === 16) { + else if (nextToken.kind === 17) { var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine; } @@ -58714,8 +62460,8 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 203 && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 80, sourceFile); + if (parent.kind === 208 && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 81, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -58726,23 +62472,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 155: + case 157: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 171: + case 176: return node.parent.properties; - case 170: + case 175: return node.parent.elements; - case 220: - case 179: - case 180: - case 147: - case 146: - case 151: - case 152: { + case 225: + case 184: + case 185: + case 149: + case 148: + case 153: + case 154: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -58753,8 +62499,8 @@ var ts; } break; } - case 175: - case 174: { + case 180: + case 179: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -58779,11 +62525,11 @@ var ts; } } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - if (node.kind === 18) { + if (node.kind === 19) { return -1; } - if (node.parent && (node.parent.kind === 174 || - node.parent.kind === 175) && + if (node.parent && (node.parent.kind === 179 || + node.parent.kind === 180) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -58801,10 +62547,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 174: - case 175: - case 172: - case 173: + case 179: + case 180: + case 177: + case 178: node = node.expression; break; default: @@ -58818,7 +62564,7 @@ var ts; var node = list[index]; var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 24) { + if (list[i].kind === 25) { continue; } var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; @@ -58842,7 +62588,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58858,48 +62604,48 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202: - case 221: - case 192: - case 222: - case 224: - case 223: - case 170: - case 199: + case 207: case 226: - case 171: - case 159: - case 161: + case 197: case 227: - case 250: - case 249: - case 178: - case 172: - case 174: + case 229: + case 228: case 175: - case 200: - case 218: - case 235: - case 211: - case 188: - case 168: - case 167: - case 243: - case 242: - case 248: - case 146: - case 151: - case 152: - case 142: - case 156: - case 157: - case 164: + case 204: + case 231: case 176: - case 184: - case 237: - case 233: + case 161: + case 163: + case 232: + case 254: + case 253: + case 183: + case 177: + case 179: + case 180: + case 205: + case 223: + case 240: + case 216: + case 193: + case 173: + case 172: + case 248: + case 247: + case 252: + case 148: + case 153: + case 154: + case 144: + case 158: + case 159: + case 166: + case 181: + case 189: + case 242: case 238: - case 234: + case 243: + case 239: return true; } return false; @@ -58907,27 +62653,27 @@ var ts; function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0; switch (parent.kind) { - case 204: - case 205: - case 207: + case 209: + case 210: + case 212: + case 213: + case 211: case 208: - case 206: - case 203: - case 220: - case 179: - case 147: - case 180: - case 148: + case 225: + case 184: case 149: + case 185: case 150: - return childKind !== 199; - case 236: - return childKind !== 237; - case 230: - return childKind !== 231 || - (child.namedBindings && child.namedBindings.kind !== 233); + case 151: + case 152: + return childKind !== 204; case 241: - return childKind !== 245; + return childKind !== 242; + case 235: + return childKind !== 236 || + (child.namedBindings && child.namedBindings.kind !== 238); + case 246: + return childKind !== 249; } return indentByDefault; } @@ -58940,11 +62686,689 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 122) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 98) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 179) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 207 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var ModuleSpecifierComparison; + (function (ModuleSpecifierComparison) { + ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; + })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); + var ImportCodeActionMap = (function () { + function ImportCodeActionMap() { + this.symbolIdToActionMap = ts.createMap(); + } + ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { + if (!newAction) { + return; + } + if (!this.symbolIdToActionMap[symbolId]) { + this.symbolIdToActionMap[symbolId] = [newAction]; + return; + } + if (newAction.kind === "CodeChange") { + this.symbolIdToActionMap[symbolId].push(newAction); + return; + } + var updatedNewImports = []; + for (var _i = 0, _a = this.symbolIdToActionMap[symbolId]; _i < _a.length; _i++) { + var existingAction = _a[_i]; + if (existingAction.kind === "CodeChange") { + updatedNewImports.push(existingAction); + continue; + } + switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { + case ModuleSpecifierComparison.Better: + if (newAction.kind === "NewImport") { + return; + } + case ModuleSpecifierComparison.Equal: + updatedNewImports.push(existingAction); + break; + case ModuleSpecifierComparison.Worse: + continue; + } + } + updatedNewImports.push(newAction); + this.symbolIdToActionMap[symbolId] = updatedNewImports; + }; + ImportCodeActionMap.prototype.addActions = function (symbolId, newActions) { + for (var _i = 0, newActions_1 = newActions; _i < newActions_1.length; _i++) { + var newAction = newActions_1[_i]; + this.addAction(symbolId, newAction); + } + }; + ImportCodeActionMap.prototype.getAllActions = function () { + var result = []; + for (var symbolId in this.symbolIdToActionMap) { + result = ts.concatenate(result, this.symbolIdToActionMap[symbolId]); + } + return result; + }; + ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { + if (moduleSpecifier1 === moduleSpecifier2) { + return ModuleSpecifierComparison.Equal; + } + if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { + return ModuleSpecifierComparison.Better; + } + if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { + return ModuleSpecifierComparison.Worse; + } + if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { + var regex = new RegExp(ts.directorySeparator, "g"); + var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; + var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; + return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Better + : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Equal + : ModuleSpecifierComparison.Worse; + } + return ModuleSpecifierComparison.Equal; + }; + return ImportCodeActionMap; + }()); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = ts.createMap(); + var cachedNewImportInsertPosition; + var allPotentialModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + allPotentialModules.push(otherSourceFile.symbol); + } + } + var currentTokenMeaning = ts.getMeaningFromLocation(token); + for (var _a = 0, allPotentialModules_1 = allPotentialModules; _a < allPotentialModules_1.length; _a++) { + var moduleSymbol = allPotentialModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + } + } + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + if (cachedImportDeclarations[moduleSymbolId]) { + return cachedImportDeclarations[moduleSymbolId]; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 235) { + return node; + } + if (node.kind === 234) { + return node; + } + node = node.parent; + } + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (declaration.kind === 235) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 237) { + namespaceImportDeclaration = declaration; + } + else { + namedImportDeclaration = declaration; + } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + } + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + if (namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var textChange = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], textChange.newText, textChange.span, sourceFile.fileName, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + } + else { + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 245) { + return declaration.moduleReference.expression.getText(); + } + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var newImportText = isDefault ? "default as " + name : name; + var importList = importClause.namedBindings; + if (!importList && importClause.name) { + var start = importClause.name.getEnd(); + return { + newText: ", { " + newImportText + " }", + span: { start: start, length: 0 } + }; + } + if (importList.elements.length === 0) { + var start = importList.getStart(); + return { + newText: "{ " + newImportText + " }", + span: { start: start, length: importList.getEnd() - start } + }; + } + var insertPoint = importList.elements[importList.elements.length - 1].getEnd(); + var startLine = ts.getLineOfLocalPosition(sourceFile, importList.getStart()); + var endLine = ts.getLineOfLocalPosition(sourceFile, importList.getEnd()); + var oneImportPerLine = endLine - startLine > importList.elements.length; + return { + newText: "," + (oneImportPerLine ? context.newLineCharacter : " ") + newImportText, + span: { start: insertPoint, length: 0 } + }; + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 235) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); + } + else { + namespacePrefix = declaration.name.getText(); + } + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], namespacePrefix + ".", { start: token.getStart(), length: 0 }, sourceFile.fileName, "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!cachedNewImportInsertPosition) { + var lastModuleSpecifierEnd = -1; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier_1 = _a[_i]; + var end = moduleSpecifier_1.getEnd(); + if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) { + lastModuleSpecifierEnd = end; + } + } + cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart(); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var importStatementText = isDefault + ? "import " + name + " from \"" + moduleSpecifierWithoutQuotes + "\"" + : "import { " + name + " } from \"" + moduleSpecifierWithoutQuotes + "\""; + var newText = cachedNewImportInsertPosition === sourceFile.getStart() + ? importStatementText + ";" + context.newLineCharacter + context.newLineCharacter + : "" + context.newLineCharacter + importStatementText + ";"; + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], newText, { start: cachedNewImportInsertPosition, length: 0 }, sourceFile.fileName, "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.path; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 261) { + return moduleSymbol.name; + } + } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { + return undefined; + } + var normalizedBaseUrl = ts.toPath(options.baseUrl, ts.getDirectoryPath(options.baseUrl), getCanonicalFileName); + var relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl); + if (!relativeName) { + return undefined; + } + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName) { + return key; + } + } + } + } + return relativeName; + } + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedRootDirs = ts.map(options.rootDirs, function (rootDir) { return ts.toPath(rootDir, undefined, getCanonicalFileName); }); + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + } + return undefined; + } + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } + } + } + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; + } + } + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = tryRemoveParentDirectoryName(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } + function tryRemoveParentDirectoryName(path, parentDirectory) { + var index = path.indexOf(parentDirectory); + if (index === 0) { + return ts.endsWith(parentDirectory, ts.directorySeparator) + ? path.substring(parentDirectory.length) + : path.substring(parentDirectory.length + 1); + } + return undefined; + } + } + } + function createCodeAction(description, diagnosticArgs, newText, span, fileName, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: [{ fileName: fileName, textChanges: [{ newText: newText, span: span }] }], + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_never_used.code + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start); + if (token.kind === 20) { + token = ts.getTokenAtPosition(sourceFile, start + 1); + } + switch (token.kind) { + case 70: + switch (token.parent.kind) { + case 223: + switch (token.parent.parent.parent.kind) { + case 211: + var forStatement = token.parent.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos); + } + else { + return removeSingleItem(forInitializer.declarations, token); + } + case 213: + var forOfStatement = token.parent.parent.parent; + if (forOfStatement.initializer.kind === 224) { + var forOfInitializer = forOfStatement.initializer; + return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos); + } + break; + case 212: + return undefined; + case 256: + var catchClause = token.parent.parent; + var parameter = catchClause.variableDeclaration.getChildren()[0]; + return createCodeFix("", parameter.pos, parameter.end - parameter.pos); + default: + var variableStatement = token.parent.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos); + } + else { + var declarations = variableStatement.declarationList.declarations; + return removeSingleItem(declarations, token); + } + } + case 143: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2); + } + else { + return removeSingleItem(typeParameters, token); + } + case 144: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else { + return removeSingleItem(functionDeclaration.parameters, token); + } + case 234: + var importEquals = findImportDeclaration(token); + return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos); + case 239: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = findImportDeclaration(token); + return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos); + } + else { + return removeSingleItem(namedImports.elements, token); + } + case 236: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = findImportDeclaration(importClause); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos); + } + case 237: + var namespaceImport = token.parent; + if (namespaceImport.name == token && !namespaceImport.parent.name) { + var importDecl = findImportDeclaration(namespaceImport); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + var start_4 = namespaceImport.parent.name.end; + return createCodeFix("", start_4, namespaceImport.parent.namedBindings.end - start_4); + } + } + break; + case 147: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + case 237: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + if (ts.isDeclarationName(token)) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos); + } + else { + return undefined; + } + function findImportDeclaration(token) { + var importDecl = token; + while (importDecl.kind != 235 && importDecl.parent) { + importDecl = importDecl.parent; + } + return importDecl; + } + function createCodeFix(newText, start, length) { + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_unused_identifiers), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ newText: newText, span: { start: start, length: length } }] + }] + }]; + } + function removeSingleItem(elements, token) { + if (elements[0] === token.parent) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1); + } + else { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1); + } + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { - var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + var node = kind >= 141 ? new NodeObject(kind, pos, end) : + kind === 70 ? new IdentifierObject(70, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -58955,7 +63379,6 @@ var ts; this.end = end; this.flags = 0; this.transformFlags = undefined; - this.excludeTransformFlags = undefined; this.parent = undefined; this.kind = kind; } @@ -59002,11 +63425,11 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(292, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -59021,11 +63444,11 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 139) { + if (this.kind >= 141) { ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; + var useJSDocScanner_1 = this.kind >= 278 && this.kind <= 291; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { @@ -59043,8 +63466,8 @@ var ts; children.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; - if (this.jsDocComments) { - for (var _i = 0, _a = this.jsDocComments; _i < _a.length; _i++) { + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; processNode(jsDocComment); } @@ -59079,7 +63502,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 139 ? child : child.getFirstToken(sourceFile); + return child.kind < 141 ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -59087,7 +63510,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 139 ? child : child.getLastToken(sourceFile); + return child.kind < 141 ? child : child.getLastToken(sourceFile); }; return NodeObject; }()); @@ -59125,19 +63548,19 @@ var ts; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + TokenOrIdentifierObject.prototype.getChildAt = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getLastToken = function () { return undefined; }; return TokenOrIdentifierObject; @@ -59158,7 +63581,7 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); } return this.documentationComment; }; @@ -59167,19 +63590,20 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69; + IdentifierObject.prototype.kind = 70; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -59213,7 +63637,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 | 65536) + return this.flags & 32768 && this.objectFlags & (1 | 2) ? this.checker.getBaseTypes(this) : undefined; }; @@ -59240,7 +63664,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; } return this.documentationComment; }; @@ -59249,7 +63673,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59263,6 +63687,19 @@ var ts; SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { return ts.getPositionOfLineAndCharacter(this, line, character); }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); @@ -59284,13 +63721,13 @@ var ts; } function getDeclarationName(declaration) { if (declaration.name) { - var result_6 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_6 !== undefined) { - return result_6; + var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_7 !== undefined) { + return result_7; } - if (declaration.name.kind === 140) { + if (declaration.name.kind === 142) { var expr = declaration.name.expression; - if (expr.kind === 172) { + if (expr.kind === 177) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -59300,7 +63737,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || node.kind === 8) { return node.text; @@ -59310,10 +63747,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 220: - case 179: - case 147: - case 146: + case 225: + case 184: + case 149: + case 148: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -59327,33 +63764,33 @@ var ts; else { declarations.push(functionDeclaration); } - ts.forEachChild(node, visit); } + ts.forEachChild(node, visit); break; - case 221: - case 192: - case 222: - case 223: - case 224: - case 225: + case 226: + case 197: + case 227: + case 228: case 229: - case 238: + case 230: case 234: - case 229: - case 231: - case 232: - case 149: - case 150: - case 159: + case 243: + case 239: + case 234: + case 236: + case 237: + case 151: + case 152: + case 161: addDeclaration(node); ts.forEachChild(node, visit); break; - case 142: + case 144: if (!ts.hasModifier(node, 92)) { break; } - case 218: - case 169: { + case 223: + case 174: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -59362,24 +63799,24 @@ var ts; if (decl.initializer) visit(decl.initializer); } - case 255: - case 145: - case 144: + case 260: + case 147: + case 146: addDeclaration(node); break; - case 236: + case 241: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 230: + case 235: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { + if (importClause.namedBindings.kind === 237) { addDeclaration(importClause.namedBindings); } else { @@ -59403,9 +63840,33 @@ var ts; getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } + getSignatureConstructor: function () { return SignatureObject; }, }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +63881,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59467,7 +63932,7 @@ var ts; }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (path, value) { + this.fileNameToEntry.forEachValue(function (_path, value) { if (value) { fileNames.push(value.hostFileName); } @@ -59497,7 +63962,7 @@ var ts; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5, version, true, scriptKind); } else if (this.currentFileVersion !== version) { var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); @@ -59583,7 +64048,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +64085,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59643,7 +64115,7 @@ var ts; useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: function (fileName, data, writeByteOrderMark) { }, + writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { return hostCache.getOrCreateEntry(fileName) !== undefined; @@ -59733,6 +64205,7 @@ var ts; return program; } function cleanupSemanticCache() { + program = undefined; } function dispose() { if (program) { @@ -59785,12 +64258,12 @@ var ts; var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { - case 69: - case 172: - case 139: - case 97: - case 165: - case 95: + case 70: + case 177: + case 141: + case 98: + case 167: + case 96: var type = typeChecker.getTypeAtLocation(node); if (type) { return { @@ -59878,12 +64351,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +64367,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59911,23 +64384,23 @@ var ts; function getSourceFile(fileName) { return getNonBoundSourceFile(fileName); } - function getNameOrDottedNameSpan(fileName, startPos, endPos) { + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, startPos); if (node === sourceFile) { return; } switch (node.kind) { - case 172: - case 139: + case 177: + case 141: case 9: - case 84: - case 99: - case 93: - case 95: - case 97: - case 165: - case 69: + case 85: + case 100: + case 94: + case 96: + case 98: + case 167: + case 70: break; default: return; @@ -59938,7 +64411,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 225 && + if (nodeForStartPos.parent.parent.kind === 230 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -59957,14 +64430,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60006,48 +64491,76 @@ var ts; return result; function getMatchingTokenKind(token) { switch (token.kind) { - case 15: return 16; - case 17: return 18; - case 19: return 20; - case 25: return 27; - case 16: return 15; - case 18: return 17; - case 20: return 19; - case 27: return 25; + case 16: return 17; + case 18: return 19; + case 20: return 21; + case 26: return 28; + case 17: return 16; + case 19: return 18; + case 21: return 20; + case 28: return 26; } return undefined; } } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar, + host: host, + cancellationToken: cancellationToken + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60056,7 +64569,7 @@ var ts; return false; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -60159,6 +64672,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +64682,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60188,13 +64703,13 @@ var ts; sourceFile.nameTable = nameTable; function walk(node) { switch (node.kind) { - case 69: + case 70: nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9: case 8: if (ts.isDeclarationName(node) || - node.parent.kind === 240 || + node.parent.kind === 245 || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node)) { nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; @@ -60202,10 +64717,10 @@ var ts; break; default: ts.forEachChild(node, walk); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - ts.forEachChild(jsDocComment, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); } } } @@ -60214,7 +64729,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 173 && + node.parent.kind === 178 && node.parent.argumentExpression === node; } function getDefaultLibFilePath(options) { @@ -60233,43 +64748,2751 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var TextStorage = (function () { + function TextStorage(host, fileName) { + this.host = host; + this.fileName = fileName; + this.svcVersion = 0; + this.textVersion = 0; } - return spaceCache[n]; + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + : "Text-" + this.textVersion; + }; + TextStorage.prototype.hasScriptVersionCache = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache = function (newText) { + this.switchToScriptVersionCache(newText); + }; + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.setText(newText); + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + }; + TextStorage.prototype.reload = function (text) { + if (this.svc) { + this.svc.reload(text); + } + else { + this.setText(text); + } + }; + TextStorage.prototype.reloadFromFile = function (tempFileName) { + if (this.svc || (tempFileName !== this.fileName)) { + this.reload(this.getFileText(tempFileName)); + } + else { + this.setText(undefined); + } + }; + TextStorage.prototype.getSnapshot = function () { + return this.svc + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + }; + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.svc) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.svc) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.svc) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + var index = this.svc.getSnapshot().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + TextStorage.prototype.getFileText = function (tempFileName) { + return this.host.readFile(tempFileName || this.fileName) || ""; + }; + TextStorage.prototype.ensureNoScriptVersionCache = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + }; + TextStorage.prototype.switchToScriptVersionCache = function (newText) { + if (!this.svc) { + this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svcVersion++; + this.text = undefined; + } + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + this.ensureNoScriptVersionCache(); + if (this.text === undefined) { + this.setText(this.getFileText()); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + this.ensureNoScriptVersionCache(); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + TextStorage.prototype.setText = function (newText) { + this.ensureNoScriptVersionCache(); + if (newText === undefined || this.text !== newText) { + this.text = newText; + this.lineMap = undefined; + this.textVersion++; + } + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.textStorage = new TextStorage(host, fileName); + if (hasMixedContent) { + this.textStorage.reload(""); + } + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); + } + ScriptInfo.prototype.isScriptOpen = function () { + return this.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.isOpen = true; + this.textStorage.useScriptVersionCache(newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + return this.containingProjects[0]; + }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.textStorage.getVersion(); + }; + ScriptInfo.prototype.reload = function (script) { + this.textStorage.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.textStorage.getSnapshot(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.textStorage.reloadFromFile(tempFileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.getLineInfo = function (line) { + return this.textStorage.getLineInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.textStorage.edit(start, end, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + return this.textStorage.lineToTextSpan(line); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + return this.textStorage.lineOffsetToPosition(line, offset); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + return this.textStorage.positionToLineOffset(position); + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var globalCache = _this.project.getTypeAcquisition().enable + ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation + : undefined; + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (!(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { + var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; + } + } + return primaryResult; + }; + if (this.host.realpath) { + this.realpath = function (path) { return _this.host.realpath(path); }; + } + } + LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { + this.filesWithChangedSetOfUnresolvedImports = []; + }; + LSHost.prototype.finishRecordingFilesWithChangedResolutions = function () { + var collected = this.filesWithChangedSetOfUnresolvedImports; + this.filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + }; + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult, getResultFileName, logChanges) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_50 = names_2[_i]; + var resolution = newResolutions[name_50]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_50]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_50] = resolution = loader(name_50, containingFile, compilerOptions, this); + } + if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + this.filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResult(oldResolution); + var newResult = getResult(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return getResultFileName(oldResult) === getResultFileName(newResult); + } + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + return getResultFileName(result) !== lastDeletedFileName; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }, function (r) { return r.resolvedFileName; }, false); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }, function (r) { return r.resolvedFileName; }, true); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + } + this.compilationSettings = opt; + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: ts.noop, + attach: ts.noop, + onProjectClosed: ts.noop, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typeAcquisitionChanged(opt1, opt2) { + return opt1.enable !== opt2.enable || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function unresolvedImportsChanged(imports1, imports2) { + if (imports1 === imports2) { + return false; } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + return !ts.arrayIsEqualTo(imports1, imports2); + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); + } + TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { + var typeAcquisition = project.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || + !entry || + typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || + compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) || + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typeAcquisition: typeAcquisition, + typings: result, + unresolvedImports: unresolvedImports, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } return result; + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typeAcquisition: typeAcquisition, + typings: server.toSortedReadonlyArray(newTypings), + unresolvedImports: unresolvedImports, + poisoned: false + }; + }; + TypingsCache.prototype.deleteTypingsForProject = function (projectName) { + delete this.perProjectCache[projectName]; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 230 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return this.project.projectService.host.createHash(text); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + } + AbstractBuilder.prototype.getFileInfos = function () { + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + }; + AbstractBuilder.prototype.clear = function () { + this.fileInfos_doNotAccessDirectly = undefined; + }; + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.getFileInfos().get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.getFileInfos().getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.getFileInfos().set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.getFileInfos().remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.clear = function () { + this.projectVersionForDependencyGraph = undefined; + _super.prototype.clear.call(this); + }; + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var ProjectKind; + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var UnresolvedImportsMap = (function () { + function UnresolvedImportsMap() { + this.perFileMap = ts.createFileMap(); + this.version = 0; + } + UnresolvedImportsMap.prototype.clear = function () { + this.perFileMap.clear(); + this.version = 0; + }; + UnresolvedImportsMap.prototype.getVersion = function () { + return this.version; + }; + UnresolvedImportsMap.prototype.remove = function (path) { + this.perFileMap.remove(path); + this.version++; + }; + UnresolvedImportsMap.prototype.get = function (path) { + return this.perFileMap.get(path); + }; + UnresolvedImportsMap.prototype.set = function (path, value) { + this.perFileMap.set(path, value); + this.version++; + }; + return UnresolvedImportsMap; + }()); + server.UnresolvedImportsMap = UnresolvedImportsMap; + var Project = (function () { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectName = projectName; + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); + this.languageServiceEnabled = true; + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + this.setInternalCompilerOptionsForEmittingJsFiles(); + this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + this.lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); + if (!languageServiceEnabled) { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getCachedUnresolvedImportsPerFile_TestOnly = function () { + return this.cachedUnresolvedImportsPerFile; + }; + Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { + if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { + this.compilerOptions.noEmitForJsFiles = true; + } + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + if (this.languageServiceEnabled) { + return; + } + this.languageServiceEnabled = true; + this.projectService.onUpdateLanguageServiceStateForProject(this, true); + }; + Project.prototype.disableLanguageService = function () { + if (!this.languageServiceEnabled) { + return; + } + this.languageService.cleanupSemanticCache(); + this.languageServiceEnabled = false; + this.projectService.onUpdateLanguageServiceStateForProject(this, false); + }; + Project.prototype.getProjectName = function () { + return this.projectName; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (this.languageServiceEnabled || f.isScriptOpen()) { + result.push(f.fileName); + } + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + if (!this.languageServiceEnabled) { + return this.rootFiles; + } + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries) { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var result = []; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(server.asNormalizedPath(f.fileName)); + } + return result; + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isScriptOpen() || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + this.cachedUnresolvedImportsPerFile.remove(info.path); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap()))[fileName] = fileName; + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result) { + var cached = this.cachedUnresolvedImportsPerFile.get(file.path); + if (cached) { + for (var _i = 0, cached_1 = cached; _i < cached_1.length; _i++) { + var f = cached_1[_i]; + result.push(f); + } + return; + } + var unresolvedImports; + if (file.resolvedModules) { + for (var name_51 in file.resolvedModules) { + if (!file.resolvedModules[name_51] && !ts.isExternalModuleNameRelative(name_51)) { + var trimmed = name_51.trim(); + var i = trimmed.indexOf("/"); + if (i !== -1 && trimmed.charCodeAt(0) === 64) { + i = trimmed.indexOf("/", i + 1); + } + if (i !== -1) { + trimmed = trimmed.substr(0, i); + } + (unresolvedImports || (unresolvedImports = [])).push(trimmed); + result.push(trimmed); + } + } + } + this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); + }; + Project.prototype.updateGraph = function () { + this.lsHost.startRecordingFilesWithChangedResolutions(); + var hasChanges = this.updateGraphWorker(); + var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { + var file = changedFiles_1[_i]; + this.cachedUnresolvedImportsPerFile.remove(file); + } + var unresolvedImports; + if (hasChanges || changedFiles.length) { + var result = []; + for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { + var sourceFile = _b[_a]; + this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + } + this.lastCachedUnresolvedImportsList = server.toSortedReadonlyArray(result); + } + unresolvedImports = this.lastCachedUnresolvedImportsList; + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (this.languageServiceEnabled) { + this.builder.onProjectUpdateGraph(); + } + else { + this.builder.clear(); + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + if (ts.changesAffectModuleResolution(this.compilerOptions, compilerOptions)) { + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = undefined; + } + this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename, tempFileName) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(tempFileName); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions(), + languageServiceDisabled: !this.languageServiceEnabled + }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + var updated = ts.getOwnKeys(updatedFileNames); + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed, updated: updated }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, compilerOptions) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; + _this.directoriesWatchedForTsconfig = []; + return _this; + } + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypeAcquisition = function () { + return { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); + return _this; + } + ConfiguredProject.prototype.getConfigFilePath = function () { + return this.getProjectName(); + }; + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.getConfigFilePath()); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + this.typeAcquisition = newTypeAcquisition; + }; + ConfiguredProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.getConfigFilePath()); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.getConfigFilePath()); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); + }; + ExternalProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition) { + newTypeAcquisition = { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypeAcquisition.enable === undefined) { + newTypeAcquisition.enable = allRootFilesAreJsOrDts(this); + } + if (!newTypeAcquisition.include) { + newTypeAcquisition.include = []; + } + if (!newTypeAcquisition.exclude) { + newTypeAcquisition.exclude = []; + } + } + this.typeAcquisition = newTypeAcquisition; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + server.ContextEvent = "context"; + server.ConfigFileDiagEvent = "configFileDiag"; + server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + for (var id in optionMap) { + ts.Debug.assert(typeof optionMap[id] === "number"); + } + map[option.name] = optionMap; + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMap({ + "none": ts.IndentStyle.None, + "block": ts.IndentStyle.Block, + "smart": ts.IndentStyle.Smart + }); + function convertFormatOptions(protocolOptions) { + if (typeof protocolOptions.indentStyle === "string") { + protocolOptions.indentStyle = indentStyle[protocolOptions.indentStyle.toLowerCase()]; + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + for (var id in compilerOptionConverters) { + var propertyValue = protocolOptions[id]; + if (typeof propertyValue === "string") { + var mappedValues = compilerOptionConverters[id]; + protocolOptions[id] = mappedValues[propertyValue.toLowerCase()]; + } + } + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return typeof scriptKindName === "string" + ? convertScriptKindName(scriptKindName) + : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1; + case "JSX": + return 2; + case "TS": + return 3; + case "TSX": + return 4; + default: + return 0; + } + } + server.convertScriptKindName = convertScriptKindName; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (fileName, extraFileExtensions) { + var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); + return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + ts.Debug.assert(!!host.createHash, "'ServerHost.createHash' is required for ProjectService"); + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host", + extraFileExtensions: [] + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; + ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: server.ProjectLanguageServiceStateEvent, + data: { project: project, languageServiceEnabled: languageServiceEnabled } + }); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case server.ActionSet: + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); + break; + case server.ActionInvalidate: + this.typingsCache.deleteTypingsForProject(response.projectName); + break; + } + project.updateGraph(); + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); + this.compilerOptionsForInferredProjects.allowNonTsExtensions = true; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(this.compilerOptionsForInferredProjects); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isScriptOpen())) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isScriptOpen()) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ + eventName: server.ContextEvent, + data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } + }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.getConfigFilePath(), 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project, fileName); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project, triggerFile) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + var configFileName = project.getConfigFilePath(); + this.logger.info("Config file changed: " + configFileName); + var configFileErrors = this.updateConfiguredProject(project); + this.reportConfigFileDiagnostics(configFileName, configFileErrors, configFileName); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.close(); + server.removeItemFromSet(this.openFiles, info); + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + for (var _i = 0, _a = this.configuredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.canonicalConfigFilePath === configFileName) { + return proj; + } + } + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typeAcquisition: parsedCommandLine.typeAcquisition, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typeAcquisition) { + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypeAcquisition(typeAcquisition); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isScriptOpen() && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypeAcquisition(newTypeAcquisition); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.getConfigFilePath())) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return configFileErrors; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + project.enableLanguageService(); + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); + } + return configFileErrors; + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + if (openedByClient || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (openedByClient) { + if (fileContent === undefined) { + fileContent = this.host.readFile(fileName) || ""; + } + } + else { + if (!hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + } + if (info) { + if (openedByClient && !info.isScriptOpen()) { + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + else if (fileContent !== undefined) { + info.reload(fileContent); + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(convertFormatOptions(args.formatOptions)); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); + this.logger.info("Format host information updated"); + } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.logger.info("Host file extension mappings updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var configFileName; + var configFileErrors; + var project = this.findContainingExternalProject(fileName); + if (!project) { + (_a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + } + } + if (project && !project.languageServiceEnabled) { + project.markAsDirty(); + } + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + var _a; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_4 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_4(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) { + var file = changedFiles_2[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProjects = function (projects) { + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + for (var externalProjectName in this.externalProjectToConfiguredProjectMap) { + projectsToClose[externalProjectName] = true; + } + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var externalProject = projects_4[_i]; + this.openExternalProject(externalProject, true); + delete projectsToClose[externalProject.projectFileName]; + } + for (var externalProjectName in projectsToClose) { + this.closeExternalProject(externalProjectName, true); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { + if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } + if (proj.typingOptions && !proj.typeAcquisition) { + var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); + proj.typeAcquisition = typeAcquisition; + } + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + if (this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + var compilerOptions = convertCompilerOptions(proj.options); + if (this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, proj.rootFiles, externalFilePropertyReader)) { + externalProject.disableLanguageService(); + } + else { + externalProject.enableLanguageService(); + } + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + } + if (!suppressRefreshOfInferredProjects) { + this.refreshInferredProjects(); + } + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +67511,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +67527,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,119 +67538,240 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments, false); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + _this.projectService.openExternalProjects(request.arguments.projects); + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { - var openArgs = request.arguments; - var scriptKind; - switch (openArgs.scriptKindName) { - case "TS": - scriptKind = 3; - break; - case "JS": - scriptKind = 1; - break; - case "TSX": - scriptKind = 4; - break; - case "JSX": - scriptKind = 2; - break; - } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName)); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function () { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,100 +67788,128 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(true); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, - _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _a[CommandNames.ReloadProjects] = function () { + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function () { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { - case "context": + case server.ContextEvent: var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; - case "configFileDiag": + case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + break; + case server.ProjectLanguageServiceStateEvent: + var eventName = "projectLanguageServiceState"; + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, eventName); + break; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60555,18 +67930,18 @@ var ts; seq: 0, type: "event", event: eventName, - body: info + body: info, }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg + success: !errorMsg, }; if (!errorMsg) { res.body = info; @@ -60576,17 +67951,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +67966,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +67976,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +67994,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +68005,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,195 +68021,277 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (isSemantic && shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, file: fileName, - isWriteAccess: isWriteAccess + isWriteAccess: isWriteAccess, }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)), + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +68312,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - 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(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +68367,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString, + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +68520,109 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + if (!project.languageServiceEnabled) { + return false; + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount, + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +68631,35 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file, tempFileName)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +68669,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end, + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,43 +68780,81 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, 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 fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { var info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isOpen) { + if (!info.isScriptOpen()) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else @@ -61283,10 +68866,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +68876,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +68894,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +68930,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +68947,7 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - 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); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - 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++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - 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) { - return this.getSourceFile(info); - } - } - }; - 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 = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - 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(); - }; - Project.prototype.isConfiguredProject = function () { - 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.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - 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; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - 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 parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.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 { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, 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, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - 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 errors; - } - 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 _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 _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); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; + var CharRangeSection; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62591,30 +68955,30 @@ var ts; CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; - })(server.CharRangeSection || (server.CharRangeSection = {})); - var CharRangeSection = server.CharRangeSection; + })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); var BaseLineIndexWalker = (function () { function BaseLineIndexWalker() { this.goSubtree = true; this.done = false; } - BaseLineIndexWalker.prototype.leaf = function (rangeStart, rangeLength, ll) { + BaseLineIndexWalker.prototype.leaf = function (_rangeStart, _rangeLength, _ll) { }; return BaseLineIndexWalker; }()); var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62692,14 +69056,14 @@ var ts; } return this.lineIndex; }; - EditWalker.prototype.post = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { + EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } this.stack.length--; return undefined; }; - EditWalker.prototype.pre = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { + EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { this.state = CharRangeSection.Start; @@ -62801,10 +69165,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +69187,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +69195,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +69227,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +69240,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -62921,7 +69288,7 @@ var ts; var starts = [-1]; var count = 1; var pos = 0; - this.index.every(function (ll, s, len) { + this.index.every(function (ll) { starts[count] = pos; count++; pos += ll.text.length; @@ -62944,8 +69311,9 @@ var ts; } }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { - var oldSnap = oldSnapshot; - return this.getTextChangeRangeSinceVersion(oldSnap.version); + if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { + return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + } }; return LineIndexSnapshot; }()); @@ -63011,7 +69379,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +69392,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63215,7 +69583,7 @@ var ts; if (!childInfo.child) { return { line: lineNumber, - offset: charOffset + offset: charOffset, }; } else if (childInfo.childIndex < this.children.length) { @@ -63404,12 +69772,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63431,16 +69793,56 @@ var ts; (function (ts) { var server; (function (server) { + var net = require("net"); + var childProcess = require("child_process"); + var os = require("os"); + function getGlobalTypingsCacheLocation() { + switch (process.platform) { + case "win32": { + var basePath = process.env.LOCALAPPDATA || + process.env.APPDATA || + (os.homedir && os.homedir()) || + process.env.USERPROFILE || + (process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) || + os.tmpdir(); + return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + } + case "darwin": + case "linux": + case "android": { + var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); + return ts.combinePaths(cacheLocation, "typescript"); + } + default: + ts.Debug.fail("unsupported platform '" + process.platform + "'"); + return; + } + } + function getNonWindowsCacheLocation(platformIsDarwin) { + if (process.env.XDG_CACHE_HOME) { + return process.env.XDG_CACHE_HOME; + } + var usersDir = platformIsDarwin ? "Users" : "home"; + var homePath = (os.homedir && os.homedir()) || + process.env.HOME || + ((process.env.LOGNAME || process.env.USER) && "/" + usersDir + "/" + (process.env.LOGNAME || process.env.USER)) || + os.tmpdir(); + var cacheFolder = platformIsDarwin + ? "Library/Caches" + : ".cache"; + return ts.combinePaths(ts.normalizeSlashes(homePath), cacheFolder); + } var readline = require("readline"); var fs = require("fs"); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, - terminal: false + terminal: false, }); var Logger = (function () { - function Logger(logFilename, level) { + function Logger(logFilename, traceToConsole, level) { this.logFilename = logFilename; + this.traceToConsole = traceToConsole; this.level = level; this.fd = -1; this.seq = 0; @@ -63455,11 +69857,14 @@ var ts; fs.close(this.fd); } }; + Logger.prototype.getLogFileName = function () { + return this.logFilename; + }; Logger.prototype.perftrc = function (s) { - this.msg(s, "Perf"); + this.msg(s, server.Msg.Perf); }; Logger.prototype.info = function (s) { - this.msg(s, "Info"); + this.msg(s, server.Msg.Info); }; Logger.prototype.startGroup = function () { this.inGroup = true; @@ -63471,19 +69876,19 @@ var ts; this.firstInGroup = true; }; Logger.prototype.loggingEnabled = function () { - return !!this.logFilename; + return !!this.logFilename || this.traceToConsole; }; - Logger.prototype.isVerbose = function () { - return this.loggingEnabled() && (this.level == "verbose"); + Logger.prototype.hasLevel = function (level) { + return this.loggingEnabled() && this.level >= level; }; Logger.prototype.msg = function (s, type) { - if (type === void 0) { type = "Err"; } + if (type === void 0) { type = server.Msg.Err; } if (this.fd < 0) { if (this.logFilename) { this.fd = fs.openSync(this.logFilename, "w"); } } - if (this.fd >= 0) { + if (this.fd >= 0 || this.traceToConsole) { s = s + "\n"; var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { @@ -63494,19 +69899,163 @@ var ts; this.seq++; this.firstInGroup = true; } - var buf = new Buffer(s); - fs.writeSync(this.fd, buf, 0, buf.length, null); + if (this.fd >= 0) { + var buf = new Buffer(s); + fs.writeSync(this.fd, buf, 0, buf.length, null); + } + if (this.traceToConsole) { + console.warn(s); + } } }; return Logger; }()); + var NodeTypingsInstaller = (function () { + function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, newLine) { + var _this = this; + this.telemetryEnabled = telemetryEnabled; + this.logger = logger; + this.globalTypingsCacheLocation = globalTypingsCacheLocation; + this.newLine = newLine; + this.installerPidReported = false; + this.throttledOperations = new server.ThrottledOperations(host); + if (eventPort) { + var s_1 = net.connect({ port: eventPort }, function () { + _this.socket = s_1; + _this.reportInstallerProcessId(); + }); + } + } + NodeTypingsInstaller.prototype.reportInstallerProcessId = function () { + if (this.installerPidReported) { + return; + } + if (this.socket && this.installer) { + this.sendEvent(0, "typingsInstallerPid", { pid: this.installer.pid }); + this.installerPidReported = true; + } + }; + NodeTypingsInstaller.prototype.sendEvent = function (seq, event, body) { + this.socket.write(server.formatMessage({ seq: seq, type: "event", event: event, body: body }, this.logger, Buffer.byteLength, this.newLine), "utf8"); + }; + NodeTypingsInstaller.prototype.setTelemetrySender = function (telemetrySender) { + this.eventSender = telemetrySender; + }; + NodeTypingsInstaller.prototype.attach = function (projectService) { + var _this = this; + this.projectService = projectService; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + this.logger.info("Binding..."); + } + var args = [server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + if (this.telemetryEnabled) { + args.push(server.Arguments.EnableTelemetry); + } + if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { + args.push(server.Arguments.LogFile, ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log")); + } + var execArgv = []; + { + for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { + var arg = _a[_i]; + var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); + if (match) { + var currentPort = match[3] !== undefined + ? +match[3] + : match[1] === "debug" ? 5858 : 9229; + execArgv.push("--" + match[1] + "=" + (currentPort + 1)); + break; + } + } + } + this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); + this.installer.on("message", function (m) { return _this.handleMessage(m); }); + this.reportInstallerProcessId(); + process.on("exit", function () { + _this.installer.kill(); + }); + }; + NodeTypingsInstaller.prototype.onProjectClosed = function (p) { + this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typeAcquisition, unresolvedImports) { + var _this = this; + var request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Scheduling throttled operation: " + JSON.stringify(request)); + } + } + this.throttledOperations.schedule(project.getProjectName(), 250, function () { + if (_this.logger.hasLevel(server.LogLevel.verbose)) { + _this.logger.info("Sending request: " + JSON.stringify(request)); + } + _this.installer.send(request); + }); + }; + NodeTypingsInstaller.prototype.handleMessage = function (response) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Received response: " + JSON.stringify(response)); + } + if (response.kind === server.EventBeginInstallTypes) { + if (!this.eventSender) { + return; + } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + var eventName = "beginInstallTypes"; + this.eventSender.event(body, eventName); + return; + } + if (response.kind === server.EventEndInstallTypes) { + if (!this.eventSender) { + return; + } + if (this.telemetryEnabled) { + var body_1 = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion + } + }; + var eventName_1 = "telemetry"; + this.eventSender.event(body_1, eventName_1); + } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + var eventName = "endInstallTypes"; + this.eventSender.event(body, eventName); + return; + } + this.projectService.updateTypingsForProject(response); + if (response.kind == server.ActionSet && this.socket) { + this.sendEvent(0, "setTypings", response); + } + }; + return NodeTypingsInstaller; + }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(host, logger) { - _super.call(this, host, Buffer.byteLength, process.hrtime, logger); + function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, disableAutomaticTypingAcquisition, globalTypingsCacheLocation, telemetryEnabled, logger) { + var _this; + var typingsInstaller = disableAutomaticTypingAcquisition + ? undefined + : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, host.newLine); + _this = _super.call(this, host, cancellationToken, useSingleInferredProject, typingsInstaller || server.nullTypingsInstaller, Buffer.byteLength, process.hrtime, logger, canUseEvents) || this; + if (telemetryEnabled && typingsInstaller) { + typingsInstaller.setTelemetrySender(_this); + } + return _this; } IOSession.prototype.exit = function () { - this.projectService.log("Exiting...", "Info"); + this.logger.info("Exiting..."); this.projectService.closeLog(); process.exit(0); }; @@ -63523,7 +70072,7 @@ var ts; return IOSession; }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { - var logEnv = {}; + var logEnv = { logToFile: true }; var args = logEnvStr.split(" "); for (var i = 0, len = args.length; i < (len - 1); i += 2) { var option = args[i]; @@ -63531,10 +70080,17 @@ var ts; if (option && value) { switch (option) { case "-file": - logEnv.file = value; + logEnv.file = ts.stripQuotes(value); break; case "-level": - logEnv.detailLevel = value; + var level = server.LogLevel[value]; + logEnv.detailLevel = typeof level === "number" ? level : server.LogLevel.normal; + break; + case "-traceToConsole": + logEnv.traceToConsole = value.toLowerCase() === "true"; + break; + case "-logToFile": + logEnv.logToFile = value.toLowerCase() === "true"; break; } } @@ -63543,21 +70099,25 @@ var ts; } function createLoggerFromEnv() { var fileName = undefined; - var detailLevel = "normal"; + var detailLevel = server.LogLevel.normal; + var traceToConsole = false; var logEnvStr = process.env["TSS_LOG"]; if (logEnvStr) { var logEnv = parseLoggingEnvironmentString(logEnvStr); - if (logEnv.file) { - fileName = logEnv.file; - } - else { - fileName = __dirname + "/.log" + process.pid.toString(); + if (logEnv.logToFile) { + if (logEnv.file) { + fileName = logEnv.file; + } + else { + fileName = __dirname + "/.log" + process.pid.toString(); + } } if (logEnv.detailLevel) { detailLevel = logEnv.detailLevel; } + traceToConsole = logEnv.traceToConsole; } - return new Logger(fileName, detailLevel); + return new Logger(fileName, traceToConsole, detailLevel); } function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } @@ -63629,13 +70189,13 @@ var ts; var logger = createLoggerFromEnv(); var pending = []; var canWrite = true; - function writeMessage(s) { + function writeMessage(buf) { if (!canWrite) { - pending.push(s); + pending.push(buf); } else { canWrite = false; - process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary); + process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); } } function setCanWriteFlagAndWriteMessageIfNecessary() { @@ -63645,7 +70205,7 @@ var ts; } } var sys = ts.sys; - sys.write = function (s) { return writeMessage(s); }; + sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); return { @@ -63654,14 +70214,46 @@ var ts; }; sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; - var ioSession = new IOSession(sys, logger); + sys.setImmediate = setImmediate; + sys.clearImmediate = clearImmediate; + if (typeof global !== "undefined" && global.gc) { + sys.gc = function () { return global.gc(); }; + } + var cancellationToken; + try { + var factory = require("./cancellationToken"); + cancellationToken = factory(sys.args); + } + catch (e) { + cancellationToken = { + isCancellationRequested: function () { return false; } + }; + } + ; + var eventPort; + { + var str = server.findArgument("--eventPort"); + var v = str && parseInt(str); + if (!isNaN(v)) { + eventPort = v; + } + } + var localeStr = server.findArgument("--locale"); + if (localeStr) { + ts.validateLocaleAndSetLanguage(localeStr, sys); + } + var useSingleInferredProject = server.hasArgument("--useSingleInferredProject"); + var disableAutomaticTypingAcquisition = server.hasArgument("--disableAutomaticTypingAcquisition"); + var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); + var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, disableAutomaticTypingAcquisition, getGlobalTypingsCacheLocation(), telemetryEnabled, logger); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); + process.noAsar = true; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63706,7 +70298,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -63739,6 +70331,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63795,7 +70393,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -63837,7 +70435,7 @@ var ts; } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, 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) { @@ -63911,7 +70509,7 @@ var ts; this.factory = factory; factory.registerShim(this); } - ShimBase.prototype.dispose = function (dummy) { + ShimBase.prototype.dispose = function (_dummy) { this.factory.unregisterShim(this); }; return ShimBase; @@ -63932,11 +70530,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -64115,6 +70714,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -64139,10 +70742,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -64164,10 +70768,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -64177,8 +70782,15 @@ var ts; return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (resolvedFileName && !compilerOptions.allowJs && ts.fileExtensionIs(resolvedFileName, ".js")) { + return { + resolvedFileName: undefined, + failedLookupLocations: [] + }; + } return { - resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations }; }); @@ -64238,7 +70850,7 @@ var ts; if (result.error) { return { options: {}, - typingOptions: {}, + typeAcquisition: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] @@ -64248,7 +70860,7 @@ var ts; var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { options: configFile.options, - typingOptions: configFile.typingOptions, + typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") @@ -64263,7 +70875,7 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typingOptions, info.compilerOptions); + return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -64338,4 +70950,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.1"; +var toolsVersion = "2.2"; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 7ed6595bc80..e01f4393032 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,4 +1,873 @@ -/// +/// +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceFull = "brace-full"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionsFull = "completions-full"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type DefinitionFull = "definition-full"; + type Implementation = "implementation"; + type ImplementationFull = "implementation-full"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type FormatFull = "format-full"; + type FormatonkeyFull = "formatonkey-full"; + type FormatRangeFull = "formatRange-full"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type NavBarFull = "navbar-full"; + type Navto = "navto"; + type NavtoFull = "navto-full"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type DocumentHighlightsFull = "documentHighlights-full"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type QuickinfoFull = "quickinfo-full"; + type References = "references"; + type ReferencesFull = "references-full"; + type Reload = "reload"; + type Rename = "rename"; + type RenameInfoFull = "rename-full"; + type RenameLocationsFull = "renameLocations-full"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type SignatureHelpFull = "signatureHelp-full"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type SynchronizeProjectList = "synchronizeProjectList"; + type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + type Cleanup = "cleanup"; + type OutliningSpans = "outliningSpans"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + type BreakpointStatement = "breakpointStatement"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetCodeFixesFull = "getCodeFixes-full"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + interface Message { + seq: number; + type: "request" | "response" | "event"; + } + interface Request extends Message { + command: string; + arguments?: any; + } + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + interface Event extends Message { + event: string; + body?: any; + } + interface Response extends Message { + request_seq: number; + success: boolean; + command: string; + message?: string; + body?: any; + } + interface FileRequestArgs { + file: string; + projectFileName?: string; + } + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + interface TodoCommentRequestArgs extends FileRequestArgs { + descriptors: TodoCommentDescriptor[]; + } + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + interface IndentationResponse extends Response { + body?: IndentationResult; + } + interface IndentationResult { + position: number; + indentation: number; + } + interface IndentationRequestArgs extends FileLocationRequestArgs { + options?: EditorSettings; + } + interface ProjectInfoRequestArgs extends FileRequestArgs { + needFileNameList: boolean; + } + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + interface CompilerOptionsDiagnosticsRequestArgs { + projectFileName: string; + } + interface ProjectInfo { + configFileName: string; + fileNames?: string[]; + languageServiceDisabled?: boolean; + } + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + interface FileLocationRequestArgs extends FileRequestArgs { + line: number; + offset: number; + position?: number; + } + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface CodeFixRequestArgs extends FileRequestArgs { + startLine: number; + startOffset: number; + startPosition?: number; + endLine: number; + endOffset: number; + endPosition?: number; + errorCodes?: number[]; + } + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + interface GetSupportedCodeFixesResponse extends Response { + body?: string[]; + } + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + start: number; + length: number; + } + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + filesToSearch: string[]; + } + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + interface Location { + line: number; + offset: number; + } + interface TextSpan { + start: Location; + end: Location; + } + interface FileSpan extends TextSpan { + file: string; + } + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + openingBrace: string; + } + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + interface HighlightSpan extends TextSpan { + kind: string; + } + interface DocumentHighlightsItem { + file: string; + highlightSpans: HighlightSpan[]; + } + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + lineText: string; + isWriteAccess: boolean; + isDefinition: boolean; + } + interface ReferencesResponseBody { + refs: ReferencesResponseItem[]; + symbolName: string; + symbolStartOffset: number; + symbolDisplayString: string; + } + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface RenameRequestArgs extends FileLocationRequestArgs { + findInComments?: boolean; + findInStrings?: boolean; + } + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage?: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + } + interface SpanGroup { + file: string; + locs: TextSpan[]; + } + interface RenameResponseBody { + info: RenameInfo; + locs: SpanGroup[]; + } + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + interface ExternalFile { + fileName: string; + scriptKind?: ScriptKindName | ts.ScriptKind; + hasMixedContent?: boolean; + content?: string; + } + interface ExternalProject { + projectFileName: string; + rootFiles: ExternalFile[]; + options: ExternalProjectCompilerOptions; + typingOptions?: TypeAcquisition; + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + compileOnSave?: boolean; + } + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + interface ProjectVersionInfo { + projectName: string; + isInferred: boolean; + version: number; + options: ts.CompilerOptions; + languageServiceDisabled: boolean; + } + interface ProjectChanges { + added: string[]; + removed: string[]; + updated: string[]; + } + interface ProjectFiles { + info?: ProjectVersionInfo; + files?: string[]; + changes?: ProjectChanges; + } + interface ProjectFilesWithDiagnostics extends ProjectFiles { + projectErrors: DiagnosticWithLinePosition[]; + } + interface ChangedOpenFile { + fileName: string; + changes: ts.TextChange[]; + } + interface ConfigureRequestArguments { + hostInfo?: string; + file?: string; + formatOptions?: FormatCodeSettings; + extraFileExtensions?: FileExtensionInfo[]; + } + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + interface ConfigureResponse extends Response { + } + interface OpenRequestArgs extends FileRequestArgs { + fileContent?: string; + scriptKindName?: ScriptKindName; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + type OpenExternalProjectArgs = ExternalProject; + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + interface OpenExternalProjectsArgs { + projects: ExternalProject[]; + } + interface OpenExternalProjectResponse extends Response { + } + interface OpenExternalProjectsResponse extends Response { + } + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + interface CloseExternalProjectRequestArgs { + projectFileName: string; + } + interface CloseExternalProjectResponse extends Response { + } + interface SynchronizeProjectListRequest extends Request { + arguments: SynchronizeProjectListRequestArgs; + } + interface SynchronizeProjectListRequestArgs { + knownProjects: protocol.ProjectVersionInfo[]; + } + interface ApplyChangedToOpenFilesRequest extends Request { + arguments: ApplyChangedToOpenFilesRequestArgs; + } + interface ApplyChangedToOpenFilesRequestArgs { + openFiles?: ExternalFile[]; + changedFiles?: ChangedOpenFile[]; + closedFiles?: string[]; + } + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + interface SetCompilerOptionsForInferredProjectsArgs { + options: ExternalProjectCompilerOptions; + } + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + interface CompileOnSaveAffectedFileListSingleProject { + projectFileName: string; + fileNames: string[]; + } + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + forced?: boolean; + } + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + interface QuickInfoResponseBody { + kind: string; + kindModifiers: string; + start: Location; + end: Location; + displayString: string; + documentation: string; + } + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + interface FormatRequestArgs extends FileLocationRequestArgs { + endLine: number; + endOffset: number; + endPosition?: number; + options?: FormatCodeSettings; + } + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + interface CodeEdit { + start: Location; + end: Location; + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + body?: CodeAction[]; + } + interface CodeAction { + description: string; + changes: FileCodeEdits[]; + } + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + key: string; + options?: FormatCodeSettings; + } + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + interface CompletionsRequestArgs extends FileLocationRequestArgs { + prefix?: string; + } + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + entryNames: string[]; + } + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + replacementSpan?: TextSpan; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface GeterrForProjectRequestArgs { + file: string; + delay: number; + } + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + interface GeterrRequestArgs { + files: string[]; + delay: number; + } + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + interface Diagnostic { + start: Location; + end: Location; + text: string; + code?: number; + } + interface DiagnosticEventBody { + file: string; + diagnostics: Diagnostic[]; + } + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + triggerFile: string; + configFile: string; + diagnostics: Diagnostic[]; + } + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + projectName: string; + languageServiceEnabled: boolean; + } + interface ReloadRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + interface ReloadResponse extends Response { + } + interface SavetoRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + interface NavtoRequestArgs extends FileRequestArgs { + searchValue: string; + maxResultCount?: number; + currentFileOnly?: boolean; + projectFileName?: string; + } + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + interface NavtoItem { + name: string; + kind: string; + matchKind?: string; + isCaseSensitive?: boolean; + kindModifiers?: string; + file: string; + start: Location; + end: Location; + containerName?: string; + containerKind?: string; + } + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + interface ChangeRequestArgs extends FormatRequestArgs { + insertString?: string; + } + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + interface BraceResponse extends Response { + body?: TextSpan[]; + } + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers?: string; + spans: TextSpan[]; + childItems?: NavigationBarItem[]; + indent: number; + } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + installedPackages: string; + installSuccess: boolean; + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + eventId: number; + packages: ReadonlyArray; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + namespace IndentStyle { + type None = "None"; + type Block = "Block"; + type Smart = "Smart"; + } + type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + types?: string[]; + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + namespace JsxEmit { + type None = "None"; + type Preserve = "Preserve"; + type React = "React"; + } + type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React; + namespace ModuleKind { + type None = "None"; + type CommonJS = "CommonJS"; + type AMD = "AMD"; + type UMD = "UMD"; + type System = "System"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; + namespace ModuleResolutionKind { + type Classic = "Classic"; + type Node = "Node"; + } + type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; + namespace NewLineKind { + type Crlf = "Crlf"; + type Lf = "Lf"; + } + type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; + namespace ScriptTarget { + type ES3 = "ES3"; + type ES5 = "ES5"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; +} declare namespace ts { interface MapLike { [index: string]: T; @@ -15,6 +884,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -32,315 +902,324 @@ declare namespace ts { ConflictMarkerTrivia = 7, NumericLiteral = 8, StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - AsteriskAsteriskToken = 38, - SlashToken = 39, - PercentToken = 40, - PlusPlusToken = 41, - MinusMinusToken = 42, - LessThanLessThanToken = 43, - GreaterThanGreaterThanToken = 44, - GreaterThanGreaterThanGreaterThanToken = 45, - AmpersandToken = 46, - BarToken = 47, - CaretToken = 48, - ExclamationToken = 49, - TildeToken = 50, - AmpersandAmpersandToken = 51, - BarBarToken = 52, - QuestionToken = 53, - ColonToken = 54, - AtToken = 55, - EqualsToken = 56, - PlusEqualsToken = 57, - MinusEqualsToken = 58, - AsteriskEqualsToken = 59, - AsteriskAsteriskEqualsToken = 60, - SlashEqualsToken = 61, - PercentEqualsToken = 62, - LessThanLessThanEqualsToken = 63, - GreaterThanGreaterThanEqualsToken = 64, - GreaterThanGreaterThanGreaterThanEqualsToken = 65, - AmpersandEqualsToken = 66, - BarEqualsToken = 67, - CaretEqualsToken = 68, - Identifier = 69, - BreakKeyword = 70, - CaseKeyword = 71, - CatchKeyword = 72, - ClassKeyword = 73, - ConstKeyword = 74, - ContinueKeyword = 75, - DebuggerKeyword = 76, - DefaultKeyword = 77, - DeleteKeyword = 78, - DoKeyword = 79, - ElseKeyword = 80, - EnumKeyword = 81, - ExportKeyword = 82, - ExtendsKeyword = 83, - FalseKeyword = 84, - FinallyKeyword = 85, - ForKeyword = 86, - FunctionKeyword = 87, - IfKeyword = 88, - ImportKeyword = 89, - InKeyword = 90, - InstanceOfKeyword = 91, - NewKeyword = 92, - NullKeyword = 93, - ReturnKeyword = 94, - SuperKeyword = 95, - SwitchKeyword = 96, - ThisKeyword = 97, - ThrowKeyword = 98, - TrueKeyword = 99, - TryKeyword = 100, - TypeOfKeyword = 101, - VarKeyword = 102, - VoidKeyword = 103, - WhileKeyword = 104, - WithKeyword = 105, - ImplementsKeyword = 106, - InterfaceKeyword = 107, - LetKeyword = 108, - PackageKeyword = 109, - PrivateKeyword = 110, - ProtectedKeyword = 111, - PublicKeyword = 112, - StaticKeyword = 113, - YieldKeyword = 114, - AbstractKeyword = 115, - AsKeyword = 116, - AnyKeyword = 117, - AsyncKeyword = 118, - AwaitKeyword = 119, - BooleanKeyword = 120, - ConstructorKeyword = 121, - DeclareKeyword = 122, - GetKeyword = 123, - IsKeyword = 124, - ModuleKeyword = 125, - NamespaceKeyword = 126, - NeverKeyword = 127, - ReadonlyKeyword = 128, - RequireKeyword = 129, - NumberKeyword = 130, - SetKeyword = 131, - StringKeyword = 132, - SymbolKeyword = 133, - TypeKeyword = 134, - UndefinedKeyword = 135, - FromKeyword = 136, - GlobalKeyword = 137, - OfKeyword = 138, - QualifiedName = 139, - ComputedPropertyName = 140, - TypeParameter = 141, - Parameter = 142, - Decorator = 143, - PropertySignature = 144, - PropertyDeclaration = 145, - MethodSignature = 146, - MethodDeclaration = 147, - Constructor = 148, - GetAccessor = 149, - SetAccessor = 150, - CallSignature = 151, - ConstructSignature = 152, - IndexSignature = 153, - TypePredicate = 154, - TypeReference = 155, - FunctionType = 156, - ConstructorType = 157, - TypeQuery = 158, - TypeLiteral = 159, - ArrayType = 160, - TupleType = 161, - UnionType = 162, - IntersectionType = 163, - ParenthesizedType = 164, - ThisType = 165, - LiteralType = 166, - ObjectBindingPattern = 167, - ArrayBindingPattern = 168, - BindingElement = 169, - ArrayLiteralExpression = 170, - ObjectLiteralExpression = 171, - PropertyAccessExpression = 172, - ElementAccessExpression = 173, - CallExpression = 174, - NewExpression = 175, - TaggedTemplateExpression = 176, - TypeAssertionExpression = 177, - ParenthesizedExpression = 178, - FunctionExpression = 179, - ArrowFunction = 180, - DeleteExpression = 181, - TypeOfExpression = 182, - VoidExpression = 183, - AwaitExpression = 184, - PrefixUnaryExpression = 185, - PostfixUnaryExpression = 186, - BinaryExpression = 187, - ConditionalExpression = 188, - TemplateExpression = 189, - YieldExpression = 190, - SpreadElementExpression = 191, - ClassExpression = 192, - OmittedExpression = 193, - ExpressionWithTypeArguments = 194, - AsExpression = 195, - NonNullExpression = 196, - TemplateSpan = 197, - SemicolonClassElement = 198, - Block = 199, - VariableStatement = 200, - EmptyStatement = 201, - ExpressionStatement = 202, - IfStatement = 203, - DoStatement = 204, - WhileStatement = 205, - ForStatement = 206, - ForInStatement = 207, - ForOfStatement = 208, - ContinueStatement = 209, - BreakStatement = 210, - ReturnStatement = 211, - WithStatement = 212, - SwitchStatement = 213, - LabeledStatement = 214, - ThrowStatement = 215, - TryStatement = 216, - DebuggerStatement = 217, - VariableDeclaration = 218, - VariableDeclarationList = 219, - FunctionDeclaration = 220, - ClassDeclaration = 221, - InterfaceDeclaration = 222, - TypeAliasDeclaration = 223, - EnumDeclaration = 224, - ModuleDeclaration = 225, - ModuleBlock = 226, - CaseBlock = 227, - NamespaceExportDeclaration = 228, - ImportEqualsDeclaration = 229, - ImportDeclaration = 230, - ImportClause = 231, - NamespaceImport = 232, - NamedImports = 233, - ImportSpecifier = 234, - ExportAssignment = 235, - ExportDeclaration = 236, - NamedExports = 237, - ExportSpecifier = 238, - MissingDeclaration = 239, - ExternalModuleReference = 240, - JsxElement = 241, - JsxSelfClosingElement = 242, - JsxOpeningElement = 243, - JsxText = 244, - JsxClosingElement = 245, - JsxAttribute = 246, - JsxSpreadAttribute = 247, - JsxExpression = 248, - CaseClause = 249, - DefaultClause = 250, - HeritageClause = 251, - CatchClause = 252, - PropertyAssignment = 253, - ShorthandPropertyAssignment = 254, - EnumMember = 255, - SourceFile = 256, - JSDocTypeExpression = 257, - JSDocAllType = 258, - JSDocUnknownType = 259, - JSDocArrayType = 260, - JSDocUnionType = 261, - JSDocTupleType = 262, - JSDocNullableType = 263, - JSDocNonNullableType = 264, - JSDocRecordType = 265, - JSDocRecordMember = 266, - JSDocTypeReference = 267, - JSDocOptionalType = 268, - JSDocFunctionType = 269, - JSDocVariadicType = 270, - JSDocConstructorType = 271, - JSDocThisType = 272, - JSDocComment = 273, - JSDocTag = 274, - JSDocParameterTag = 275, - JSDocReturnTag = 276, - JSDocTypeTag = 277, - JSDocTemplateTag = 278, - JSDocTypedefTag = 279, - JSDocPropertyTag = 280, - JSDocTypeLiteral = 281, - JSDocLiteralType = 282, - JSDocNullKeyword = 283, - JSDocUndefinedKeyword = 284, - JSDocNeverKeyword = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - Count = 289, - FirstAssignment = 56, - LastAssignment = 68, - FirstCompoundAssignment = 57, - LastCompoundAssignment = 68, - FirstReservedWord = 70, - LastReservedWord = 105, - FirstKeyword = 70, - LastKeyword = 138, - FirstFutureReservedWord = 106, - LastFutureReservedWord = 114, - FirstTypeNode = 154, - LastTypeNode = 166, - FirstPunctuation = 15, - LastPunctuation = 68, + JsxText = 10, + RegularExpressionLiteral = 11, + NoSubstitutionTemplateLiteral = 12, + TemplateHead = 13, + TemplateMiddle = 14, + TemplateTail = 15, + OpenBraceToken = 16, + CloseBraceToken = 17, + OpenParenToken = 18, + CloseParenToken = 19, + OpenBracketToken = 20, + CloseBracketToken = 21, + DotToken = 22, + DotDotDotToken = 23, + SemicolonToken = 24, + CommaToken = 25, + LessThanToken = 26, + LessThanSlashToken = 27, + GreaterThanToken = 28, + LessThanEqualsToken = 29, + GreaterThanEqualsToken = 30, + EqualsEqualsToken = 31, + ExclamationEqualsToken = 32, + EqualsEqualsEqualsToken = 33, + ExclamationEqualsEqualsToken = 34, + EqualsGreaterThanToken = 35, + PlusToken = 36, + MinusToken = 37, + AsteriskToken = 38, + AsteriskAsteriskToken = 39, + SlashToken = 40, + PercentToken = 41, + PlusPlusToken = 42, + MinusMinusToken = 43, + LessThanLessThanToken = 44, + GreaterThanGreaterThanToken = 45, + GreaterThanGreaterThanGreaterThanToken = 46, + AmpersandToken = 47, + BarToken = 48, + CaretToken = 49, + ExclamationToken = 50, + TildeToken = 51, + AmpersandAmpersandToken = 52, + BarBarToken = 53, + QuestionToken = 54, + ColonToken = 55, + AtToken = 56, + EqualsToken = 57, + PlusEqualsToken = 58, + MinusEqualsToken = 59, + AsteriskEqualsToken = 60, + AsteriskAsteriskEqualsToken = 61, + SlashEqualsToken = 62, + PercentEqualsToken = 63, + LessThanLessThanEqualsToken = 64, + GreaterThanGreaterThanEqualsToken = 65, + GreaterThanGreaterThanGreaterThanEqualsToken = 66, + AmpersandEqualsToken = 67, + BarEqualsToken = 68, + CaretEqualsToken = 69, + Identifier = 70, + BreakKeyword = 71, + CaseKeyword = 72, + CatchKeyword = 73, + ClassKeyword = 74, + ConstKeyword = 75, + ContinueKeyword = 76, + DebuggerKeyword = 77, + DefaultKeyword = 78, + DeleteKeyword = 79, + DoKeyword = 80, + ElseKeyword = 81, + EnumKeyword = 82, + ExportKeyword = 83, + ExtendsKeyword = 84, + FalseKeyword = 85, + FinallyKeyword = 86, + ForKeyword = 87, + FunctionKeyword = 88, + IfKeyword = 89, + ImportKeyword = 90, + InKeyword = 91, + InstanceOfKeyword = 92, + NewKeyword = 93, + NullKeyword = 94, + ReturnKeyword = 95, + SuperKeyword = 96, + SwitchKeyword = 97, + ThisKeyword = 98, + ThrowKeyword = 99, + TrueKeyword = 100, + TryKeyword = 101, + TypeOfKeyword = 102, + VarKeyword = 103, + VoidKeyword = 104, + WhileKeyword = 105, + WithKeyword = 106, + ImplementsKeyword = 107, + InterfaceKeyword = 108, + LetKeyword = 109, + PackageKeyword = 110, + PrivateKeyword = 111, + ProtectedKeyword = 112, + PublicKeyword = 113, + StaticKeyword = 114, + YieldKeyword = 115, + AbstractKeyword = 116, + AsKeyword = 117, + AnyKeyword = 118, + AsyncKeyword = 119, + AwaitKeyword = 120, + BooleanKeyword = 121, + ConstructorKeyword = 122, + DeclareKeyword = 123, + GetKeyword = 124, + IsKeyword = 125, + KeyOfKeyword = 126, + ModuleKeyword = 127, + NamespaceKeyword = 128, + NeverKeyword = 129, + ReadonlyKeyword = 130, + RequireKeyword = 131, + NumberKeyword = 132, + SetKeyword = 133, + StringKeyword = 134, + SymbolKeyword = 135, + TypeKeyword = 136, + UndefinedKeyword = 137, + FromKeyword = 138, + GlobalKeyword = 139, + OfKeyword = 140, + QualifiedName = 141, + ComputedPropertyName = 142, + TypeParameter = 143, + Parameter = 144, + Decorator = 145, + PropertySignature = 146, + PropertyDeclaration = 147, + MethodSignature = 148, + MethodDeclaration = 149, + Constructor = 150, + GetAccessor = 151, + SetAccessor = 152, + CallSignature = 153, + ConstructSignature = 154, + IndexSignature = 155, + TypePredicate = 156, + TypeReference = 157, + FunctionType = 158, + ConstructorType = 159, + TypeQuery = 160, + TypeLiteral = 161, + ArrayType = 162, + TupleType = 163, + UnionType = 164, + IntersectionType = 165, + ParenthesizedType = 166, + ThisType = 167, + TypeOperator = 168, + IndexedAccessType = 169, + MappedType = 170, + LiteralType = 171, + ObjectBindingPattern = 172, + ArrayBindingPattern = 173, + BindingElement = 174, + ArrayLiteralExpression = 175, + ObjectLiteralExpression = 176, + PropertyAccessExpression = 177, + ElementAccessExpression = 178, + CallExpression = 179, + NewExpression = 180, + TaggedTemplateExpression = 181, + TypeAssertionExpression = 182, + ParenthesizedExpression = 183, + FunctionExpression = 184, + ArrowFunction = 185, + DeleteExpression = 186, + TypeOfExpression = 187, + VoidExpression = 188, + AwaitExpression = 189, + PrefixUnaryExpression = 190, + PostfixUnaryExpression = 191, + BinaryExpression = 192, + ConditionalExpression = 193, + TemplateExpression = 194, + YieldExpression = 195, + SpreadElement = 196, + ClassExpression = 197, + OmittedExpression = 198, + ExpressionWithTypeArguments = 199, + AsExpression = 200, + NonNullExpression = 201, + TemplateSpan = 202, + SemicolonClassElement = 203, + Block = 204, + VariableStatement = 205, + EmptyStatement = 206, + ExpressionStatement = 207, + IfStatement = 208, + DoStatement = 209, + WhileStatement = 210, + ForStatement = 211, + ForInStatement = 212, + ForOfStatement = 213, + ContinueStatement = 214, + BreakStatement = 215, + ReturnStatement = 216, + WithStatement = 217, + SwitchStatement = 218, + LabeledStatement = 219, + ThrowStatement = 220, + TryStatement = 221, + DebuggerStatement = 222, + VariableDeclaration = 223, + VariableDeclarationList = 224, + FunctionDeclaration = 225, + ClassDeclaration = 226, + InterfaceDeclaration = 227, + TypeAliasDeclaration = 228, + EnumDeclaration = 229, + ModuleDeclaration = 230, + ModuleBlock = 231, + CaseBlock = 232, + NamespaceExportDeclaration = 233, + ImportEqualsDeclaration = 234, + ImportDeclaration = 235, + ImportClause = 236, + NamespaceImport = 237, + NamedImports = 238, + ImportSpecifier = 239, + ExportAssignment = 240, + ExportDeclaration = 241, + NamedExports = 242, + ExportSpecifier = 243, + MissingDeclaration = 244, + ExternalModuleReference = 245, + JsxElement = 246, + JsxSelfClosingElement = 247, + JsxOpeningElement = 248, + JsxClosingElement = 249, + JsxAttribute = 250, + JsxSpreadAttribute = 251, + JsxExpression = 252, + CaseClause = 253, + DefaultClause = 254, + HeritageClause = 255, + CatchClause = 256, + PropertyAssignment = 257, + ShorthandPropertyAssignment = 258, + SpreadAssignment = 259, + EnumMember = 260, + SourceFile = 261, + JSDocTypeExpression = 262, + JSDocAllType = 263, + JSDocUnknownType = 264, + JSDocArrayType = 265, + JSDocUnionType = 266, + JSDocTupleType = 267, + JSDocNullableType = 268, + JSDocNonNullableType = 269, + JSDocRecordType = 270, + JSDocRecordMember = 271, + JSDocTypeReference = 272, + JSDocOptionalType = 273, + JSDocFunctionType = 274, + JSDocVariadicType = 275, + JSDocConstructorType = 276, + JSDocThisType = 277, + JSDocComment = 278, + JSDocTag = 279, + JSDocAugmentsTag = 280, + JSDocParameterTag = 281, + JSDocReturnTag = 282, + JSDocTypeTag = 283, + JSDocTemplateTag = 284, + JSDocTypedefTag = 285, + JSDocPropertyTag = 286, + JSDocTypeLiteral = 287, + JSDocLiteralType = 288, + JSDocNullKeyword = 289, + JSDocUndefinedKeyword = 290, + JSDocNeverKeyword = 291, + SyntaxList = 292, + NotEmittedStatement = 293, + PartiallyEmittedExpression = 294, + MergeDeclarationMarker = 295, + EndOfDeclarationMarker = 296, + RawExpression = 297, + Count = 298, + FirstAssignment = 57, + LastAssignment = 69, + FirstCompoundAssignment = 58, + LastCompoundAssignment = 69, + FirstReservedWord = 71, + LastReservedWord = 106, + FirstKeyword = 71, + LastKeyword = 140, + FirstFutureReservedWord = 107, + LastFutureReservedWord = 115, + FirstTypeNode = 156, + LastTypeNode = 171, + FirstPunctuation = 16, + LastPunctuation = 69, FirstToken = 0, - LastToken = 138, + LastToken = 140, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 68, - FirstNode = 139, - FirstJSDocNode = 257, - LastJSDocNode = 282, - FirstJSDocTagNode = 273, - LastJSDocTagNode = 285, + LastLiteralToken = 12, + FirstTemplateToken = 12, + LastTemplateToken = 15, + FirstBinaryOperator = 26, + LastBinaryOperator = 69, + FirstNode = 141, + FirstJSDocNode = 262, + LastJSDocNode = 288, + FirstJSDocTagNode = 278, + LastJSDocTagNode = 291, } const enum NodeFlags { None = 0, @@ -354,27 +1233,21 @@ declare namespace ts { HasImplicitReturn = 128, HasExplicitReturn = 256, GlobalAugmentation = 512, - HasClassExtends = 1024, - HasDecorators = 2048, - HasParamDecorators = 4096, - HasAsyncFunctions = 8192, - HasJsxSpreadAttributes = 16384, - DisallowInContext = 32768, - YieldContext = 65536, - DecoratorContext = 131072, - AwaitContext = 262144, - ThisNodeHasError = 524288, - JavaScriptFile = 1048576, - ThisNodeOrAnySubNodesHasError = 2097152, - HasAggregatedChildData = 4194304, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, BlockScoped = 3, ReachabilityCheckFlags = 384, - EmitHelperFlags = 31744, - ReachabilityAndEmitFlags = 32128, - ContextFlags = 1540096, - TypeExcludesFlags = 327680, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 96256, + TypeExcludesFlags = 20480, } - type ModifiersArray = NodeArray; const enum ModifierFlags { None = 0, Export = 1, @@ -392,6 +1265,8 @@ declare namespace ts { AccessibilityModifier = 28, ParameterPropertyModifier = 92, NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, } const enum JsxFlags { None = 0, @@ -415,25 +1290,33 @@ declare namespace ts { parent?: Node; original?: Node; startsOnNewLine?: boolean; - jsDocComments?: JSDoc[]; + jsDoc?: JSDoc[]; + jsDocCache?: (JSDoc | JSDocTag)[]; symbol?: Symbol; locals?: SymbolTable; nextContainer?: Node; localSymbol?: Symbol; flowNode?: FlowNode; - transformId?: number; - emitFlags?: NodeEmitFlags; - sourceMapRange?: TextRange; - commentRange?: TextRange; + emitNode?: EmitNode; } interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; + transformFlags?: TransformFlags; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type ReadonlyToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; const enum GeneratedIdentifierKind { None = 0, Auto = 1, @@ -442,35 +1325,44 @@ declare namespace ts { Node = 4, } interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; autoGenerateKind?: GeneratedIdentifierKind; autoGenerateId?: number; + isInJSDocNamespace?: boolean; } interface TransientIdentifier extends Identifier { resolvedSymbol: Symbol; } + interface GeneratedIdentifier extends Identifier { + autoGenerateKind: GeneratedIdentifierKind.Auto | GeneratedIdentifierKind.Loop | GeneratedIdentifierKind.Unique | GeneratedIdentifierKind.Node; + } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } type EntityName = Identifier | QualifiedName; - type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -482,40 +1374,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -524,134 +1424,178 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } - type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } + interface SpreadAssignment extends ObjectLiteralElement { + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyLikeDeclaration extends Declaration { name: PropertyName; } - interface BindingPattern extends Node { - elements: NodeArray; - } - interface ObjectBindingPattern extends BindingPattern { + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } - type ArrayBindingElement = BindingElement | OmittedExpression; - interface ArrayBindingPattern extends BindingPattern { + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken; + type?: TypeNode; + } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; - textSourceNode?: Identifier | StringLiteral; + kind: SyntaxKind.StringLiteral; + textSourceNode?: Identifier | StringLiteral | NumericLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; expression: Expression; } interface UnaryExpression extends Expression { @@ -660,16 +1604,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; + operator: PostfixUnaryOperator; } interface LeftHandSideExpression extends IncrementExpression { _leftHandSideExpressionBrand: any; @@ -680,42 +1625,102 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -727,137 +1732,205 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; multiLine?: boolean; } - interface SpreadElementExpression extends Expression { + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; expression: Expression; } interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; multiLine?: boolean; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; + } + interface EndOfDeclarationMarker extends Statement { + kind: SyntaxKind.EndOfDeclarationMarker; + } + interface RawExpression extends PrimaryExpression { + kind: SyntaxKind.RawExpression; + text: string; + } + interface MergeDeclarationMarker extends Statement { + kind: SyntaxKind.MergeDeclarationMarker; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; multiLine?: boolean; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } + interface PrologueDirective extends ExpressionStatement { + expression: StringLiteral; + } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -866,68 +1939,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -939,9 +2029,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -950,85 +2042,112 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { - name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + kind: SyntaxKind.ModuleDeclaration; + name: Identifier | StringLiteral; + body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; + } + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: JSDocNamespaceDeclaration | Identifier; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1040,95 +2159,126 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { - name: Identifier | LiteralExpression; + kind: SyntaxKind.JSDocRecordMember; + name: Identifier | StringLiteral | NumericLiteral; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + typeExpression: JSDocTypeExpression; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; postParameterName?: Identifier; @@ -1144,8 +2294,9 @@ declare namespace ts { TrueCondition = 32, FalseCondition = 64, SwitchClause = 128, - Referenced = 256, - Shared = 512, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, Label = 12, Condition = 96, } @@ -1154,7 +2305,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1173,6 +2324,10 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + interface FlowArrayMutation extends FlowNode { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } type FlowType = Type | IncompleteType; interface IncompleteType { flags: TypeFlags; @@ -1183,8 +2338,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1205,15 +2361,16 @@ declare namespace ts { identifierCount: number; symbolCount: number; parseDiagnostics: Diagnostic[]; + additionalSyntacticDiagnostics?: Diagnostic[]; bindDiagnostics: Diagnostic[]; lineMap: number[]; classifiableNames?: Map; - resolvedModules: Map; + resolvedModules: Map; resolvedTypeReferenceDirectiveNames: Map; imports: LiteralExpression[]; moduleAugmentations: LiteralExpression[]; patternAmbientModules?: PatternAmbientModule[]; - externalHelpersModuleName?: Identifier; + ambientModuleNames: string[]; } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; @@ -1239,7 +2396,7 @@ declare namespace ts { interface Program extends ScriptReferenceHost { getRootFileNames(): string[]; getSourceFiles(): SourceFile[]; - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1248,6 +2405,7 @@ declare namespace ts { getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; getDiagnosticsProducingTypeChecker(): TypeChecker; + dropDiagnosticsProducingTypeChecker(): void; getClassifiableNames(): Map; getNodeCount(): number; getIdentifierCount(): number; @@ -1255,6 +2413,7 @@ declare namespace ts { getTypeCount(): number; getFileProcessingDiagnostics(): DiagnosticCollection; getResolvedTypeReferenceDirectives(): Map; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; structureIsReused?: boolean; } interface SourceMapSpan { @@ -1332,6 +2491,8 @@ declare namespace ts { getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; @@ -1359,6 +2520,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -1379,6 +2541,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } const enum SymbolFormatFlags { None = 0, @@ -1390,6 +2553,10 @@ declare namespace ts { NotAccessible = 1, CannotBeNamed = 2, } + const enum SyntheticSymbolKind { + UnionOrIntersection = 0, + Spread = 1, + } const enum TypePredicateKind { This = 0, Identifier = 1, @@ -1399,9 +2566,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1457,8 +2625,9 @@ declare namespace ts { getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile; getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; - isLiteralConstDeclaration(node: VariableDeclaration): boolean; - writeLiteralConstValue(node: VariableDeclaration, writer: SymbolWriter): void; + isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; + writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: SymbolWriter): void; + getJsxFactoryEntity(): EntityName; } const enum SymbolFlags { None = 0, @@ -1556,7 +2725,10 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; - hasCommonType?: boolean; + leftSpread?: Symbol; + rightSpread?: Symbol; + hasNonUniformType?: boolean; + isPartial?: boolean; isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; @@ -1603,6 +2775,7 @@ declare namespace ts { resolvedSignature?: Signature; resolvedSymbol?: Symbol; resolvedIndexInfo?: IndexInfo; + maybeTypePredicate?: boolean; enumMemberValue?: number; isVisible?: boolean; hasReportedStatementInAmbientContext?: boolean; @@ -1628,21 +2801,15 @@ declare namespace ts { Null = 4096, Never = 8192, TypeParameter = 16384, - Class = 32768, - Interface = 65536, - Reference = 131072, - Tuple = 262144, - Union = 524288, - Intersection = 1048576, - Anonymous = 2097152, - Instantiated = 4194304, - ObjectLiteral = 8388608, - FreshLiteral = 16777216, - ContainsWideningType = 33554432, - ContainsObjectLiteral = 67108864, - ContainsAnyFunctionType = 134217728, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, + Object = 32768, + Union = 65536, + Intersection = 131072, + Index = 262144, + IndexedAccess = 524288, + FreshLiteral = 1048576, + ContainsWideningType = 2097152, + ContainsObjectLiteral = 4194304, + ContainsAnyFunctionType = 8388608, Nullable = 6144, Literal = 480, StringOrNumberLiteral = 96, @@ -1650,18 +2817,18 @@ declare namespace ts { PossiblyFalsy = 7406, Intrinsic = 16015, Primitive = 8190, - StringLike = 34, + StringLike = 262178, NumberLike = 340, BooleanLike = 136, EnumLike = 272, - ObjectType = 2588672, - UnionOrIntersection = 1572864, - StructuredType = 4161536, - StructuredOrTypeParameter = 4177920, - Narrowable = 4178943, - NotUnionOrUnit = 2589191, - RequiresWidening = 100663296, - PropagatingFlags = 234881024, + UnionOrIntersection = 196608, + StructuredType = 229376, + StructuredOrTypeParameter = 507904, + TypeVariable = 540672, + Narrowable = 1033215, + NotUnionOrUnit = 33281, + RequiresWidening = 6291456, + PropagatingFlags = 14680064, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1686,7 +2853,21 @@ declare namespace ts { interface EnumLiteralType extends LiteralType { baseType: EnumType & UnionType; } + const enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ClassOrInterface = 3, + } interface ObjectType extends Type { + objectFlags: ObjectFlags; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1713,16 +2894,30 @@ declare namespace ts { interface UnionOrIntersectionType extends Type { types: Type[]; resolvedProperties: SymbolTable; - couldContainTypeParameters: boolean; + resolvedIndexType: IndexType; + couldContainTypeVariables: boolean; } interface UnionType extends UnionOrIntersectionType { } interface IntersectionType extends UnionOrIntersectionType { } + type StructuredType = ObjectType | UnionType | IntersectionType; interface AnonymousType extends ObjectType { target?: AnonymousType; mapper?: TypeMapper; } + interface MappedType extends ObjectType { + declaration: MappedTypeNode; + typeParameter?: TypeParameter; + constraintType?: Type; + templateType?: Type; + modifiersType?: Type; + mapper?: TypeMapper; + } + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } interface ResolvedType extends ObjectType, UnionOrIntersectionType { members: SymbolTable; properties: Symbol[]; @@ -1738,11 +2933,23 @@ declare namespace ts { iterableElementType?: Type; iteratorElementType?: Type; } - interface TypeParameter extends Type { + interface TypeVariable extends Type { + resolvedApparentType: Type; + resolvedIndexType: IndexType; + } + interface TypeParameter extends TypeVariable { constraint: Type; target?: TypeParameter; mapper?: TypeMapper; - resolvedApparentType: Type; + isThisType?: boolean; + } + interface IndexedAccessType extends TypeVariable { + objectType: Type; + indexType: Type; + constraint?: Type; + } + interface IndexType extends Type { + type: TypeVariable | UnionOrIntersectionType; } const enum SignatureKind { Call = 0, @@ -1763,6 +2970,7 @@ declare namespace ts { erasedSignatureCache?: Signature; isolatedSignatureType?: ObjectType; typePredicate?: TypePredicate; + instantiations?: Map; } const enum IndexKind { String = 0, @@ -1776,7 +2984,6 @@ declare namespace ts { interface TypeMapper { (t: TypeParameter): Type; mappedTypes?: Type[]; - targetTypes?: Type[]; instantiations?: Type[]; context?: InferenceContext; } @@ -1801,6 +3008,11 @@ declare namespace ts { PrototypeProperty = 3, ThisProperty = 4, } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -1830,16 +3042,14 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowNonTsExtensions?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; configFilePath?: string; @@ -1869,6 +3079,7 @@ declare namespace ts { moduleResolution?: ModuleResolutionKind; newLine?: NewLineKind; noEmit?: boolean; + noEmitForJsFiles?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; @@ -1884,14 +3095,15 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; pretty?: DiagnosticStyle; reactNamespace?: string; + jsxFactory?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1909,8 +3121,9 @@ declare namespace ts { watch?: boolean; [option: string]: CompilerOptionsValue | undefined; } - interface TypingOptions { + interface TypeAcquisition { enableAutoDiscovery?: boolean; + enable?: boolean; include?: string[]; exclude?: string[]; [option: string]: string[] | boolean | undefined; @@ -1920,8 +3133,9 @@ declare namespace ts { projectRootPath: string; safeListPath: string; packageNameToTypingLocation: Map; - typingOptions: TypingOptions; + typeAcquisition: TypeAcquisition; compilerOptions: CompilerOptions; + unresolvedImports: ReadonlyArray; } enum ModuleKind { None = 0, @@ -1929,7 +3143,6 @@ declare namespace ts { AMD = 2, UMD = 3, System = 4, - ES6 = 5, ES2015 = 5, } const enum JsxEmit { @@ -1955,9 +3168,11 @@ declare namespace ts { const enum ScriptTarget { ES3 = 0, ES5 = 1, - ES6 = 2, ES2015 = 2, - Latest = 2, + ES2016 = 3, + ES2017 = 4, + ESNext = 5, + Latest = 5, } const enum LanguageVariant { Standard = 0, @@ -1969,11 +3184,12 @@ declare namespace ts { } interface ParsedCommandLine { options: CompilerOptions; - typingOptions?: TypingOptions; + typeAcquisition?: TypeAcquisition; fileNames: string[]; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } const enum WatchDirectoryFlags { None = 0, @@ -2146,8 +3362,19 @@ declare namespace ts { resolvedFileName: string; isExternalLibraryImport?: boolean; } + interface ResolvedModuleFull extends ResolvedModule { + extension: Extension; + } + enum Extension { + Ts = 0, + Tsx = 1, + Dts = 2, + Js = 3, + Jsx = 4, + LastTypeScriptExtension = 2, + } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; + resolvedModule: ResolvedModuleFull | undefined; failedLookupLocations: string[]; } interface ResolvedTypeReferenceDirective { @@ -2178,82 +3405,153 @@ declare namespace ts { None = 0, TypeScript = 1, ContainsTypeScript = 2, - Jsx = 4, - ContainsJsx = 8, - ES7 = 16, - ContainsES7 = 32, - ES6 = 64, - ContainsES6 = 128, - DestructuringAssignment = 256, - Generator = 512, - ContainsGenerator = 1024, - ContainsDecorators = 2048, - ContainsPropertyInitializer = 4096, - ContainsLexicalThis = 8192, - ContainsCapturedLexicalThis = 16384, - ContainsLexicalThisInComputedPropertyName = 32768, - ContainsDefaultValueAssignments = 65536, - ContainsParameterPropertyAssignments = 131072, - ContainsSpreadElementExpression = 262144, - ContainsComputedPropertyName = 524288, - ContainsBlockScopedBinding = 1048576, - ContainsBindingPattern = 2097152, - ContainsYield = 4194304, - ContainsHoistedDeclarationOrCompletion = 8388608, + ContainsJsx = 4, + ContainsESNext = 8, + ContainsES2017 = 16, + ContainsES2016 = 32, + ES2015 = 64, + ContainsES2015 = 128, + Generator = 256, + ContainsGenerator = 512, + DestructuringAssignment = 1024, + ContainsDestructuringAssignment = 2048, + ContainsDecorators = 4096, + ContainsPropertyInitializer = 8192, + ContainsLexicalThis = 16384, + ContainsCapturedLexicalThis = 32768, + ContainsLexicalThisInComputedPropertyName = 65536, + ContainsDefaultValueAssignments = 131072, + ContainsParameterPropertyAssignments = 262144, + ContainsSpread = 524288, + ContainsObjectSpread = 1048576, + ContainsRest = 524288, + ContainsObjectRest = 1048576, + ContainsComputedPropertyName = 2097152, + ContainsBlockScopedBinding = 4194304, + ContainsBindingPattern = 8388608, + ContainsYield = 16777216, + ContainsHoistedDeclarationOrCompletion = 33554432, HasComputedFlags = 536870912, AssertTypeScript = 3, - AssertJsx = 12, - AssertES7 = 48, - AssertES6 = 192, - AssertGenerator = 1536, - NodeExcludes = 536871765, - ArrowFunctionExcludes = 550710101, - FunctionExcludes = 550726485, - ConstructorExcludes = 550593365, - MethodOrAccessorExcludes = 550593365, - ClassExcludes = 537590613, - ModuleExcludes = 546335573, + AssertJsx = 4, + AssertESNext = 8, + AssertES2017 = 16, + AssertES2016 = 32, + AssertES2015 = 192, + AssertGenerator = 768, + AssertDestructuringAssignment = 3072, + NodeExcludes = 536872257, + ArrowFunctionExcludes = 601249089, + FunctionExcludes = 601281857, + ConstructorExcludes = 601015617, + MethodOrAccessorExcludes = 601015617, + ClassExcludes = 539358529, + ModuleExcludes = 574674241, TypeExcludes = -3, - ObjectLiteralExcludes = 537430869, - ArrayLiteralOrCallOrNewExcludes = 537133909, - VariableDeclarationListExcludes = 538968917, - ParameterExcludes = 538968917, - TypeScriptClassSyntaxMask = 137216, - ES6FunctionSyntaxMask = 81920, + ObjectLiteralExcludes = 540087617, + ArrayLiteralOrCallOrNewExcludes = 537396545, + VariableDeclarationListExcludes = 546309441, + ParameterExcludes = 536872257, + CatchClauseExcludes = 537920833, + BindingPatternExcludes = 537396545, + TypeScriptClassSyntaxMask = 274432, + ES2015FunctionSyntaxMask = 163840, } - const enum NodeEmitFlags { - EmitEmitHelpers = 1, - EmitExportStar = 2, - EmitSuperHelper = 4, - EmitAdvancedSuperHelper = 8, - UMDDefine = 16, - SingleLine = 32, - AdviseOnEmitNode = 64, - NoSubstitution = 128, - CapturesThis = 256, - NoLeadingSourceMap = 512, - NoTrailingSourceMap = 1024, - NoSourceMap = 1536, - NoNestedSourceMaps = 2048, - NoTokenLeadingSourceMaps = 4096, - NoTokenTrailingSourceMaps = 8192, - NoTokenSourceMaps = 12288, - NoLeadingComments = 16384, - NoTrailingComments = 32768, - NoComments = 49152, - NoNestedComments = 65536, - ExportName = 131072, - LocalName = 262144, - Indented = 524288, - NoIndentation = 1048576, - AsyncFunctionBody = 2097152, - ReuseTempVariableScope = 4194304, - CustomPrologue = 8388608, + interface EmitNode { + annotatedNodes?: Node[]; + flags?: EmitFlags; + commentRange?: TextRange; + sourceMapRange?: TextRange; + tokenSourceMapRanges?: Map; + constantValue?: number; + externalHelpersModuleName?: Identifier; + helpers?: EmitHelper[]; } - interface LexicalEnvironment { + const enum EmitFlags { + SingleLine = 1, + AdviseOnEmitNode = 2, + NoSubstitution = 4, + CapturesThis = 8, + NoLeadingSourceMap = 16, + NoTrailingSourceMap = 32, + NoSourceMap = 48, + NoNestedSourceMaps = 64, + NoTokenLeadingSourceMaps = 128, + NoTokenTrailingSourceMaps = 256, + NoTokenSourceMaps = 384, + NoLeadingComments = 512, + NoTrailingComments = 1024, + NoComments = 1536, + NoNestedComments = 2048, + HelperName = 4096, + ExportName = 8192, + LocalName = 16384, + Indented = 32768, + NoIndentation = 65536, + AsyncFunctionBody = 131072, + ReuseTempVariableScope = 262144, + CustomPrologue = 524288, + NoHoisting = 1048576, + HasEndOfDeclarationMarker = 2097152, + } + interface EmitHelper { + readonly name: string; + readonly scoped: boolean; + readonly text: string; + readonly priority?: number; + } + const enum ExternalEmitHelpers { + Extends = 1, + Assign = 2, + Rest = 4, + Decorate = 8, + Metadata = 16, + Param = 32, + Awaiter = 64, + Generator = 128, + FirstEmitHelper = 1, + LastEmitHelper = 128, + } + const enum EmitContext { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + Unspecified = 3, + } + interface EmitHost extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; + getCommonSourceDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + isEmitBlocked(emitFileName: string): boolean; + writeFile: WriteFileCallback; + } + interface TransformationContext { + getCompilerOptions(): CompilerOptions; + getEmitResolver(): EmitResolver; + getEmitHost(): EmitHost; startLexicalEnvironment(): void; + suspendLexicalEnvironment(): void; + resumeLexicalEnvironment(): void; endLexicalEnvironment(): Statement[]; + hoistFunctionDeclaration(node: FunctionDeclaration): void; + hoistVariableDeclaration(node: Identifier): void; + requestEmitHelper(helper: EmitHelper): void; + readEmitHelpers(): EmitHelper[] | undefined; + enableSubstitution(kind: SyntaxKind): void; + isSubstitutionEnabled(node: Node): boolean; + onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node; + enableEmitNotification(kind: SyntaxKind): void; + isEmitNotificationEnabled(node: Node): boolean; + onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; } + interface TransformationResult { + transformed: SourceFile[]; + emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + } + type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; interface TextSpan { start: number; length: number; @@ -2285,12 +3583,18 @@ declare namespace ts.performance { function enable(): void; function disable(): void; } +declare namespace ts { + const version = "2.2.0"; +} declare namespace ts { const enum Ternary { False = 0, Maybe = 1, True = -1, } + const collator: { + compare(a: string, b: string): number; + }; function createMap(template?: MapLike): Map; function createFileMap(keyMapper?: (key: string) => string): FileMap; function toPath(fileName: string, basePath: string, getCanonicalFileName: (path: string) => string): Path; @@ -2300,6 +3604,7 @@ declare namespace ts { GreaterThan = 1, } function forEach(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; + function zipWith(arrayA: T[], arrayB: U[], callback: (a: T, b: U, index: number) => void): void; function every(array: T[], callback: (element: T, index: number) => boolean): boolean; function find(array: T[], predicate: (element: T, index: number) => boolean): T | undefined; function findMap(array: T[], callback: (element: T, index: number) => U | undefined): U; @@ -2312,22 +3617,30 @@ declare namespace ts { function removeWhere(array: T[], f: (x: T) => boolean): boolean; function filterMutate(array: T[], f: (x: T) => boolean): void; function map(array: T[], f: (x: T, i: number) => U): U[]; + function sameMap(array: T[], f: (x: T, i: number) => T): T[]; function flatten(array: (T | T[])[]): T[]; function flatMap(array: T[], mapfn: (x: T, i: number) => U | U[]): U[]; function span(array: T[], f: (x: T, i: number) => boolean): [T[], T[]]; function spanMap(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; function mapObject(object: MapLike, f: (key: string, x: T) => [string, U]): MapLike; + function some(array: T[], predicate?: (value: T) => boolean): boolean; function concatenate(array1: T[], array2: T[]): T[]; function deduplicate(array: T[], areEqual?: (a: T, b: T) => boolean): T[]; + function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean; + function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean; function compact(array: T[]): T[]; + function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer?: (x: T, y: T) => Comparison, offsetA?: number, offsetB?: number): T[] | undefined; function sum(array: any[], prop: string): number; - function addRange(to: T[], from: T[]): void; + function append(to: T[] | undefined, value: T | undefined): T[] | undefined; + function addRange(to: T[] | undefined, from: T[] | undefined): T[] | undefined; + function stableSort(array: T[], comparer?: (x: T, y: T) => Comparison): T[]; function rangeEquals(array1: T[], array2: T[], pos: number, end: number): boolean; function firstOrUndefined(array: T[]): T; + function lastOrUndefined(array: T[]): T; function singleOrUndefined(array: T[]): T; function singleOrMany(array: T[]): T | T[]; - function lastOrUndefined(array: T[]): T; - function binarySearch(array: number[], value: number): number; + function replaceElement(array: T[], index: number, value: T): T[]; + function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number, offset?: number): number; function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T; function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; @@ -2338,11 +3651,11 @@ declare namespace ts { function forEachProperty(map: Map, callback: (value: T, key: string) => U): U; function someProperties(map: Map, predicate?: (value: T, key: string) => boolean): boolean; function copyProperties(source: Map, target: MapLike): void; + function appendProperty(map: Map, key: string | number, value: T): Map; function assign, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3; function assign, T2>(t: T1, arg1: T2): T1 & T2; function assign>(t: T1, ...args: any[]): any; function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; - function reduceOwnProperties(map: MapLike, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer?: (left: T, right: T) => boolean): boolean; function arrayToMap(array: T[], makeKey: (value: T) => string): Map; function arrayToMap(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map; @@ -2350,15 +3663,20 @@ declare namespace ts { function cloneMap(map: Map): Map; function clone(object: T): T; function extend(first: T1, second: T2): T1 & T2; - function multiMapAdd(map: Map, key: string, value: V): V[]; + function multiMapAdd(map: Map, key: string | number, value: V): V[]; function multiMapRemove(map: Map, key: string, value: V): void; function isArray(value: any): value is any[]; + function noop(): void; + function notImplemented(): never; function memoize(callback: () => T): () => T; + function chain(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U; + function compose(...args: ((t: T) => T)[]): (t: T) => T; let localizedDiagnosticMessages: Map; function getLocaleSpecificMessage(message: DiagnosticMessage): string; - function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; - function formatMessage(dummy: any, message: DiagnosticMessage): string; - function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; + function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic; + function formatMessage(_dummy: any, message: DiagnosticMessage): string; + function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic; + function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic; function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain; function compareValues(a: T, b: T): Comparison; @@ -2375,7 +3693,13 @@ declare namespace ts { function getDirectoryPath(path: Path): Path; function getDirectoryPath(path: string): string; function isUrl(path: string): boolean; + function isExternalModuleNameRelative(moduleName: string): boolean; + function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; + function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; + function getEmitModuleResolutionKind(compilerOptions: CompilerOptions): ModuleResolutionKind; + function hasZeroOrOneAsteriskCharacter(str: string): boolean; function isRootedDiskPath(path: string): boolean; + function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNormalizedPathComponents(path: string, currentDirectory: string): string[]; function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string; function getNormalizedPathFromPathComponents(pathComponents: string[]): string; @@ -2388,9 +3712,11 @@ declare namespace ts { function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; function startsWith(str: string, prefix: string): boolean; function endsWith(str: string, suffix: string): boolean; + function hasExtension(fileName: string): 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; + function isImplicitGlob(lastPathComponent: string): boolean; interface FileSystemEntries { files: string[]; directories: string[]; @@ -2401,15 +3727,17 @@ declare namespace ts { excludePattern: string; basePaths: string[]; } - function getFileMatcherPatterns(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns; + function getFileMatcherPatterns(path: 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 supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; - function getSupportedExtensions(options?: CompilerOptions): string[]; - function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; + function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[]; + function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; + function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): boolean; const enum ExtensionPriority { TypeScriptFiles = 0, DeclarationAndJavaScriptFiles = 2, @@ -2423,13 +3751,12 @@ declare namespace ts { function removeFileExtension(path: string): string; function tryRemoveExtension(path: string, extension: string): string | undefined; function removeExtension(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; - getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; + getTokenConstructor(): new (kind: TKind, pos?: number, end?: number) => Token; + getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos?: number, end?: number) => Identifier; + getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; @@ -2442,15 +3769,25 @@ declare namespace ts { VeryAggressive = 3, } namespace Debug { + let currentAssertionLevel: AssertionLevel; function shouldAssert(level: AssertionLevel): boolean; function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void; function fail(message?: string): void; } - function getEnvironmentVariable(name: string, host?: CompilerHost): string; + function orderedRemoveItem(array: T[], item: T): boolean; function orderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItem(array: T[], item: T): void; function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string; + function matchPatternOrExact(patternStrings: string[], candidate: string): string | Pattern | undefined; + function patternText({prefix, suffix}: Pattern): string; + function matchedText(pattern: Pattern, candidate: string): string; + function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; + function tryParsePattern(pattern: string): Pattern | undefined; + function positionIsSynthesized(pos: number): boolean; + function extensionIsTypeScript(ext: Extension): boolean; + function extensionFromPath(path: string): Extension; + function tryGetExtensionFromPath(path: string): Extension | undefined; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2468,7 +3805,7 @@ declare namespace ts { readFile(path: string, encoding?: string): string; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; @@ -2485,6 +3822,8 @@ declare namespace ts { realpath?(path: string): string; getEnvironmentVariable(name: string): string; tryEnableSourceMapsForHost?(): void; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; } interface FileWatcher { close(): void; @@ -2493,10 +3832,10 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { - var Diagnostics: { + const Diagnostics: { Unterminated_string_literal: { code: number; category: DiagnosticCategory; @@ -2743,7 +4082,7 @@ declare namespace ts { key: string; message: string; }; - Type_0_is_not_a_valid_async_function_return_type: { + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: number; category: DiagnosticCategory; key: string; @@ -3403,12 +4742,6 @@ declare namespace ts { key: string; message: string; }; - Catch_clause_variable_name_must_be_an_identifier: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Catch_clause_variable_cannot_have_a_type_annotation: { code: number; category: DiagnosticCategory; @@ -3781,6 +5114,12 @@ declare namespace ts { key: string; message: string; }; + An_abstract_accessor_cannot_have_an_implementation: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Duplicate_identifier_0: { code: number; category: DiagnosticCategory; @@ -4039,6 +5378,12 @@ declare namespace ts { key: string; message: string; }; + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Type_0_does_not_satisfy_the_constraint_1: { code: number; category: DiagnosticCategory; @@ -4099,6 +5444,12 @@ declare namespace ts { key: string; message: string; }; + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: number; category: DiagnosticCategory; @@ -4111,7 +5462,7 @@ declare namespace ts { key: string; message: string; }; - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: number; category: DiagnosticCategory; key: string; @@ -4153,7 +5504,7 @@ declare namespace ts { key: string; message: string; }; - Invalid_left_hand_side_of_assignment_expression: { + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: number; category: DiagnosticCategory; key: string; @@ -4393,7 +5744,7 @@ declare namespace ts { key: string; message: string; }; - Invalid_left_hand_side_in_for_in_statement: { + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: number; category: DiagnosticCategory; key: string; @@ -4417,7 +5768,7 @@ declare namespace ts { key: string; message: string; }; - All_symbols_within_a_with_block_will_be_resolved_to_any: { + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: number; category: DiagnosticCategory; key: string; @@ -4621,18 +5972,6 @@ declare namespace ts { key: string; message: string; }; - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Cannot_redeclare_block_scoped_variable_0: { code: number; category: DiagnosticCategory; @@ -4699,7 +6038,7 @@ declare namespace ts { key: string; message: string; }; - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: number; category: DiagnosticCategory; key: string; @@ -4831,19 +6170,7 @@ declare namespace ts { key: string; message: string; }; - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - Invalid_left_hand_side_in_for_of_statement: { + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: number; category: DiagnosticCategory; key: string; @@ -5125,6 +6452,48 @@ declare namespace ts { key: string; message: string; }; + Type_0_cannot_be_used_to_index_type_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Type_0_has_no_matching_index_signature_for_type_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Type_0_cannot_be_used_as_an_index_type: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Cannot_assign_to_0_because_it_is_not_a_variable: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Index_signature_in_type_0_only_permits_reading: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; JSX_element_attributes_type_0_may_not_be_a_union_type: { code: number; category: DiagnosticCategory; @@ -5263,6 +6632,12 @@ declare namespace ts { key: string; message: string; }; + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: number; category: DiagnosticCategory; @@ -5383,7 +6758,7 @@ declare namespace ts { key: string; message: string; }; - Identifier_0_must_be_imported_from_a_module: { + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: number; category: DiagnosticCategory; key: string; @@ -5449,6 +6824,36 @@ declare namespace ts { key: string; message: string; }; + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Spread_types_may_only_be_created_from_object_types: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Rest_types_may_only_be_created_from_object_types: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5869,12 +7274,30 @@ declare namespace ts { key: string; message: string; }; + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: number; category: DiagnosticCategory; key: string; message: string; }; + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; The_current_host_does_not_support_the_0_option: { code: number; category: DiagnosticCategory; @@ -6043,6 +7466,12 @@ declare namespace ts { key: string; message: string; }; + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Concatenate_and_emit_output_to_single_file: { code: number; category: DiagnosticCategory; @@ -6115,7 +7544,7 @@ declare namespace ts { key: string; message: string; }; - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: number; category: DiagnosticCategory; key: string; @@ -6541,7 +7970,7 @@ declare namespace ts { key: string; message: string; }; - package_json_does_not_have_types_field: { + package_json_does_not_have_a_types_or_main_field: { code: number; category: DiagnosticCategory; key: string; @@ -6763,7 +8192,7 @@ declare namespace ts { key: string; message: string; }; - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: number; category: DiagnosticCategory; key: string; @@ -6781,6 +8210,48 @@ declare namespace ts { key: string; message: string; }; + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Module_0_was_resolved_to_1_but_jsx_is_not_set: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6829,7 +8300,13 @@ declare namespace ts { key: string; message: string; }; - Index_signature_of_object_type_implicitly_has_an_any_type: { + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: number; category: DiagnosticCategory; key: string; @@ -6925,6 +8402,12 @@ declare namespace ts { key: string; message: string; }; + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; You_cannot_rename_this_element: { code: number; category: DiagnosticCategory; @@ -7027,6 +8510,12 @@ declare namespace ts { key: string; message: string; }; + Language_service_is_disabled: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: number; category: DiagnosticCategory; @@ -7087,7 +8576,13 @@ declare namespace ts { key: string; message: string; }; - Unknown_typing_option_0: { + Unknown_type_acquisition_option_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: number; category: DiagnosticCategory; key: string; @@ -7099,7 +8594,91 @@ declare namespace ts { key: string; message: string; }; - The_path_in_an_extends_options_must_be_relative_or_rooted: { + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + The_files_list_in_config_file_0_is_empty: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Add_missing_super_call: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Make_super_call_the_first_statement_in_the_constructor: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Change_extends_to_implements: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Remove_unused_identifiers: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_reference: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_inherited_abstract_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Import_0_from_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Change_0_to_1: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Add_0_to_existing_import_declaration_from_1: { code: number; category: DiagnosticCategory; key: string; @@ -7174,13 +8753,15 @@ declare namespace ts { function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { + const compileOnSaveCommandLineOption: CommandLineOption; const optionDeclarations: CommandLineOption[]; - let typingOptionDeclarations: CommandLineOption[]; + let typeAcquisitionDeclarations: CommandLineOption[]; interface OptionNameMap { optionNameMap: Map; shortOptionNames: Map; } const defaultInitCompilerOptions: CompilerOptions; + function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition; function getOptionNameMap(): OptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): string | number; @@ -7190,23 +8771,147 @@ declare namespace ts { config?: any; error?: Diagnostic; }; - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; function generateTSConfig(options: CompilerOptions, fileNames: string[]): { compilerOptions: Map; }; - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; - function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; errors: Diagnostic[]; }; } +declare namespace ts.JsTyping { + interface TypingResolutionHost { + directoryExists: (path: string) => boolean; + fileExists: (fileName: string) => boolean; + readFile: (path: string, encoding?: string) => string; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; + } + const nodeCoreModuleList: ReadonlyArray; + function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typeAcquisition: TypeAcquisition, unresolvedImports: ReadonlyArray): { + cachedTypingPaths: string[]; + newTypingNames: string[]; + filesToWatch: string[]; + }; +} +declare namespace ts.server { + const ActionSet: ActionSet; + const ActionInvalidate: ActionInvalidate; + const EventBeginInstallTypes: EventBeginInstallTypes; + const EventEndInstallTypes: EventEndInstallTypes; + namespace Arguments { + const GlobalCacheLocation = "--globalTypingsCacheLocation"; + const LogFile = "--logFile"; + const EnableTelemetry = "--enableTelemetry"; + } + function hasArgument(argumentName: string): boolean; + function findArgument(argumentName: string): string; +} +declare namespace ts.server { + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3, + } + const emptyArray: ReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg.Types): void; + getLogFileName(): string; + } + namespace Msg { + type Err = "Err"; + const Err: Err; + type Info = "Info"; + const Info: Info; + type Perf = "Perf"; + const Perf: Perf; + type Types = Err | Info | Perf; + } + function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; + function mergeMaps(target: MapLike, source: MapLike): void; + function removeItemFromSet(items: T[], itemToRemove: T): void; + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + interface NormalizedPathMap { + get(path: NormalizedPath): T; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function createNormalizedPathMap(): NormalizedPathMap; + interface ProjectOptions { + configHasFilesProperty?: boolean; + files?: string[]; + wildcardDirectories?: Map; + compilerOptions?: CompilerOptions; + typeAcquisition?: TypeAcquisition; + compileOnSave?: boolean; + } + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + function toSortedReadonlyArray(arr: string[]): SortedReadonlyArray; + class ThrottledOperations { + private readonly host; + private pendingTimeouts; + constructor(host: ServerHost); + schedule(operationId: string, delay: number, cb: () => void): void; + private static run(self, operationId, cb); + } + class GcTimer { + private readonly host; + private readonly delay; + private readonly logger; + private timerId; + constructor(host: ServerHost, delay: number, logger: Logger); + scheduleCollect(): void; + private static run(self); + } +} +declare namespace ts { + function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; + function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean; + function moduleHasNonRelativeName(moduleName: string): boolean; + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function directoryProbablyExists(directoryName: string, host: { + directoryExists?: (directoryName: string) => boolean; + }): boolean; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function loadModuleFromGlobalCache(moduleName: string, projectName: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations; +} declare namespace ts { const externalHelpersModuleNameText = "tslib"; interface ReferencePathMatchResult { @@ -7219,24 +8924,14 @@ declare namespace ts { interface StringSymbolWriter extends SymbolWriter { string(): string; } - interface EmitHost extends ScriptReferenceHost { - getSourceFiles(): SourceFile[]; - isSourceFileFromExternalLibrary(file: SourceFile): boolean; - getCommonSourceDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - isEmitBlocked(emitFileName: string): boolean; - writeFile: WriteFileCallback; - } function getSingleLineStringWriter(): StringSymbolWriter; function releaseStringWriter(writer: StringSymbolWriter): void; function getFullWidth(node: Node): number; - function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean; function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean; - function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule; - function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void; + function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull; + function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void; function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void; - function moduleResolutionIsEqualTo(oldResolution: ResolvedModule, newResolution: ResolvedModule): boolean; + function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean; function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean; function hasChangesInResolutions(names: string[], newResolutions: T[], oldResolutions: Map, comparer: (oldResolution: T, newResolution: T) => boolean): boolean; function containsParseError(node: Node): boolean; @@ -7249,7 +8944,7 @@ declare namespace ts { function getEndLinePosition(line: number, sourceFile: SourceFile): number; function nodeIsMissing(node: Node): boolean; function nodeIsPresent(node: Node): boolean; - function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDocComment?: boolean): number; + function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDoc?: boolean): number; function isJSDocNode(node: Node): boolean; function isJSDocTag(node: Node): boolean; function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number; @@ -7262,16 +8957,20 @@ declare namespace ts { function unescapeIdentifier(identifier: string): string; function makeIdentifierFromModuleName(moduleName: string): string; function isBlockOrCatchScoped(declaration: Declaration): boolean; + function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration): boolean; function isAmbientModule(node: Node): boolean; function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean; function isBlockScopedContainerTopLevel(node: Node): boolean; function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; function isExternalModuleAugmentation(node: Node): boolean; + function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions): boolean; function isBlockScope(node: Node, parentNode: Node): boolean; function getEnclosingBlockScopeContainer(node: Node): Node; - function isCatchClauseVariableDeclaration(declaration: Declaration): boolean; function declarationNameToString(name: DeclarationName): string; - function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic; + function getTextOfPropertyName(name: PropertyName): string; + function entityNameToString(name: EntityNameOrEntityNameExpression): string; + function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic; + function createDiagnosticForNodeInSourceFile(sourceFile: SourceFile, node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic; function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic; function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan; function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan; @@ -7280,18 +8979,18 @@ declare namespace ts { function isConstEnumDeclaration(node: Node): boolean; function isConst(node: Node): boolean; function isLet(node: Node): boolean; - function isSuperCallExpression(n: Node): boolean; - function isPrologueDirective(node: Node): boolean; + function isSuperCall(n: Node): n is SuperCall; + function isPrologueDirective(node: Node): node is PrologueDirective; function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[]; function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[]; - function getJsDocComments(node: Node, sourceFileOfNode: SourceFile): CommentRange[]; - function getJsDocCommentsFromText(node: Node, text: string): CommentRange[]; + function getJSDocCommentRanges(node: Node, text: string): CommentRange[]; let fullTripleSlashReferencePathRegEx: RegExp; let fullTripleSlashReferenceTypeReferenceDirectiveRegEx: RegExp; let fullTripleSlashAMDReferencePathRegEx: RegExp; function isPartOfTypeNode(node: Node): boolean; function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T; function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void; + function getRestParameterElementType(node: TypeNode): TypeNode; function isVariableLike(node: Node): node is VariableLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; function isClassLike(node: Node): node is ClassLikeDeclaration; @@ -7301,6 +9000,7 @@ declare namespace ts { function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; function isFunctionBlock(node: Node): boolean; function isObjectLiteralMethod(node: Node): node is MethodDeclaration; + function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration; function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate; function isThisTypePredicate(predicate: TypePredicate): predicate is ThisTypePredicate; function getContainingFunction(node: Node): FunctionLikeDeclaration; @@ -7308,7 +9008,7 @@ declare namespace ts { function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; - function isSuperProperty(node: Node): node is (PropertyAccessExpression | ElementAccessExpression); + function isSuperProperty(node: Node): node is SuperProperty; function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; function isCallLikeExpression(node: Node): node is CallLikeExpression; function getInvokedExpression(node: CallLikeExpression): Expression; @@ -7318,7 +9018,6 @@ declare namespace ts { function childIsDecorated(node: Node): boolean; function isJSXTagName(node: Node): boolean; function isPartOfExpression(node: Node): boolean; - function isExternalModuleNameRelative(moduleName: string): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; function isExternalModuleImportEqualsDeclaration(node: Node): boolean; function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression; @@ -7330,19 +9029,26 @@ declare namespace ts { function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; - function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): NamespaceImport; + function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport; function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean; function hasQuestionToken(node: Node): boolean; function isJSDocConstructSignature(node: Node): boolean; - function getJSDocComments(node: Node, checkParentVariableStatement: boolean): string[]; - function getJSDocTypeTag(node: Node): JSDocTypeTag; + function getCommentsFromJSDoc(node: Node): string[]; + function getJSDocParameterTags(param: Node): JSDocParameterTag[]; + function getJSDocType(node: Node): JSDocType; + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag; function getJSDocReturnTag(node: Node): JSDocReturnTag; function getJSDocTemplateTag(node: Node): JSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag; function hasRestParameter(s: SignatureDeclaration): boolean; function hasDeclaredRestParameter(s: SignatureDeclaration): boolean; function isRestParameter(node: ParameterDeclaration): boolean; function isDeclaredRestParam(node: ParameterDeclaration): boolean; + const enum AssignmentKind { + None = 0, + Definite = 1, + Compound = 2, + } + function getAssignmentTargetKind(node: Node): AssignmentKind; function isAssignmentTarget(node: Node): boolean; function isNodeDescendantOf(node: Node, ancestor: Node): boolean; function isInAmbientContext(node: Node): boolean; @@ -7361,20 +9067,21 @@ declare namespace ts { function isKeyword(token: SyntaxKind): boolean; function isTrivia(token: SyntaxKind): boolean; function isAsyncFunctionLike(node: Node): boolean; - function isStringOrNumericLiteral(kind: SyntaxKind): boolean; + function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral; function hasDynamicName(declaration: Declaration): boolean; function isDynamicName(name: DeclarationName): boolean; function isWellKnownSymbolSyntactically(node: Expression): boolean; - function getPropertyNameForPropertyNameNode(name: DeclarationName): string; + function getPropertyNameForPropertyNameNode(name: DeclarationName | ParameterDeclaration): string; function getPropertyNameForKnownSymbolName(symbolName: string): string; function isESSymbolIdentifier(node: Node): boolean; + function isPushOrUnshiftIdentifier(node: Identifier): boolean; function isModifierKind(token: SyntaxKind): boolean; function isParameterDeclaration(node: VariableLikeDeclaration): boolean; function getRootDeclaration(node: Node): Node; function nodeStartsNewLexicalEnvironment(node: Node): boolean; function nodeIsSynthesized(node: TextRange): boolean; - function positionIsSynthesized(pos: number): boolean; function getOriginalNode(node: Node): Node; + function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; function isParseTreeNode(node: Node): boolean; function getParseTreeNode(node: Node): Node; function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; @@ -7387,7 +9094,7 @@ declare namespace ts { function getExpressionAssociativity(expression: Expression): Associativity; function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity; function getExpressionPrecedence(expression: Expression): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; - function getOperator(expression: Expression): SyntaxKind; + function getOperator(expression: Expression): SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.NumericLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.Identifier | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.LetKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.StaticKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AbstractKeyword | SyntaxKind.AsKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.GetKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.NumberKeyword | SyntaxKind.SetKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.TypeKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.FromKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.OfKeyword | SyntaxKind.QualifiedName | SyntaxKind.ComputedPropertyName | SyntaxKind.TypeParameter | SyntaxKind.Parameter | SyntaxKind.Decorator | SyntaxKind.PropertySignature | SyntaxKind.PropertyDeclaration | SyntaxKind.MethodSignature | SyntaxKind.MethodDeclaration | SyntaxKind.Constructor | SyntaxKind.GetAccessor | SyntaxKind.SetAccessor | SyntaxKind.CallSignature | SyntaxKind.ConstructSignature | SyntaxKind.IndexSignature | SyntaxKind.TypePredicate | SyntaxKind.TypeReference | SyntaxKind.FunctionType | SyntaxKind.ConstructorType | SyntaxKind.TypeQuery | SyntaxKind.TypeLiteral | SyntaxKind.ArrayType | SyntaxKind.TupleType | SyntaxKind.UnionType | SyntaxKind.IntersectionType | SyntaxKind.ParenthesizedType | SyntaxKind.ThisType | SyntaxKind.TypeOperator | SyntaxKind.IndexedAccessType | SyntaxKind.MappedType | SyntaxKind.LiteralType | SyntaxKind.ObjectBindingPattern | SyntaxKind.ArrayBindingPattern | SyntaxKind.BindingElement | SyntaxKind.ArrayLiteralExpression | SyntaxKind.ObjectLiteralExpression | SyntaxKind.PropertyAccessExpression | SyntaxKind.ElementAccessExpression | SyntaxKind.CallExpression | SyntaxKind.NewExpression | SyntaxKind.TaggedTemplateExpression | SyntaxKind.TypeAssertionExpression | SyntaxKind.ParenthesizedExpression | SyntaxKind.FunctionExpression | SyntaxKind.ArrowFunction | SyntaxKind.DeleteExpression | SyntaxKind.TypeOfExpression | SyntaxKind.VoidExpression | SyntaxKind.AwaitExpression | SyntaxKind.ConditionalExpression | SyntaxKind.TemplateExpression | SyntaxKind.YieldExpression | SyntaxKind.SpreadElement | SyntaxKind.ClassExpression | SyntaxKind.OmittedExpression | SyntaxKind.ExpressionWithTypeArguments | SyntaxKind.AsExpression | SyntaxKind.NonNullExpression | SyntaxKind.TemplateSpan | SyntaxKind.SemicolonClassElement | SyntaxKind.Block | SyntaxKind.VariableStatement | SyntaxKind.EmptyStatement | SyntaxKind.ExpressionStatement | SyntaxKind.IfStatement | SyntaxKind.DoStatement | SyntaxKind.WhileStatement | SyntaxKind.ForStatement | SyntaxKind.ForInStatement | SyntaxKind.ForOfStatement | SyntaxKind.ContinueStatement | SyntaxKind.BreakStatement | SyntaxKind.ReturnStatement | SyntaxKind.WithStatement | SyntaxKind.SwitchStatement | SyntaxKind.LabeledStatement | SyntaxKind.ThrowStatement | SyntaxKind.TryStatement | SyntaxKind.DebuggerStatement | SyntaxKind.VariableDeclaration | SyntaxKind.VariableDeclarationList | SyntaxKind.FunctionDeclaration | SyntaxKind.ClassDeclaration | SyntaxKind.InterfaceDeclaration | SyntaxKind.TypeAliasDeclaration | SyntaxKind.EnumDeclaration | SyntaxKind.ModuleDeclaration | SyntaxKind.ModuleBlock | SyntaxKind.CaseBlock | SyntaxKind.NamespaceExportDeclaration | SyntaxKind.ImportEqualsDeclaration | SyntaxKind.ImportDeclaration | SyntaxKind.ImportClause | SyntaxKind.NamespaceImport | SyntaxKind.NamedImports | SyntaxKind.ImportSpecifier | SyntaxKind.ExportAssignment | SyntaxKind.ExportDeclaration | SyntaxKind.NamedExports | SyntaxKind.ExportSpecifier | SyntaxKind.MissingDeclaration | SyntaxKind.ExternalModuleReference | SyntaxKind.JsxElement | SyntaxKind.JsxSelfClosingElement | SyntaxKind.JsxOpeningElement | SyntaxKind.JsxClosingElement | SyntaxKind.JsxAttribute | SyntaxKind.JsxSpreadAttribute | SyntaxKind.JsxExpression | SyntaxKind.CaseClause | SyntaxKind.DefaultClause | SyntaxKind.HeritageClause | SyntaxKind.CatchClause | SyntaxKind.PropertyAssignment | SyntaxKind.ShorthandPropertyAssignment | SyntaxKind.SpreadAssignment | SyntaxKind.EnumMember | SyntaxKind.SourceFile | SyntaxKind.JSDocTypeExpression | SyntaxKind.JSDocAllType | SyntaxKind.JSDocUnknownType | SyntaxKind.JSDocArrayType | SyntaxKind.JSDocUnionType | SyntaxKind.JSDocTupleType | SyntaxKind.JSDocNullableType | SyntaxKind.JSDocNonNullableType | SyntaxKind.JSDocRecordType | SyntaxKind.JSDocRecordMember | SyntaxKind.JSDocTypeReference | SyntaxKind.JSDocOptionalType | SyntaxKind.JSDocFunctionType | SyntaxKind.JSDocVariadicType | SyntaxKind.JSDocConstructorType | SyntaxKind.JSDocThisType | SyntaxKind.JSDocComment | SyntaxKind.JSDocTag | SyntaxKind.JSDocAugmentsTag | SyntaxKind.JSDocParameterTag | SyntaxKind.JSDocReturnTag | SyntaxKind.JSDocTypeTag | SyntaxKind.JSDocTemplateTag | SyntaxKind.JSDocTypedefTag | SyntaxKind.JSDocPropertyTag | SyntaxKind.JSDocTypeLiteral | SyntaxKind.JSDocLiteralType | SyntaxKind.JSDocNullKeyword | SyntaxKind.JSDocUndefinedKeyword | SyntaxKind.JSDocNeverKeyword | SyntaxKind.SyntaxList | SyntaxKind.NotEmittedStatement | SyntaxKind.PartiallyEmittedExpression | SyntaxKind.MergeDeclarationMarker | SyntaxKind.EndOfDeclarationMarker | SyntaxKind.RawExpression | SyntaxKind.Count; function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; function createDiagnosticCollection(): DiagnosticCollection; function escapeString(s: string): string; @@ -7413,26 +9120,29 @@ declare namespace ts { function getIndentSize(): number; function createTextWriter(newLine: String): EmitTextWriter; function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; - function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; + function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string; function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string; function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; - function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; - function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; interface EmitFileNames { jsFilePath: string; sourceMapFilePath: string; declarationFilePath: string; } function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): SourceFile[]; - function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void): void; - function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void; + function filterSourceFilesInDirectory(sourceFiles: SourceFile[], isSourceFileFromExternalLibrary: (file: SourceFile) => boolean): SourceFile[]; + function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, emitOnlyDtsFiles?: boolean): void; + function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean, emitOnlyDtsFiles: boolean) => void, targetSourceFile?: SourceFile, emitOnlyDtsFiles?: boolean): void; function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void; function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number; function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number): number; function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration; - function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode; + function getSetAccessorTypeAnnotationNode(accessor: SetAccessorDeclaration): TypeNode; + function getThisParameter(signature: SignatureDeclaration): ParameterDeclaration | undefined; + function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean; + function isThisIdentifier(node: Node | undefined): boolean; + function identifierIsThisKeyword(id: Identifier): boolean; interface AllAccessorDeclarations { firstAccessor: AccessorDeclaration; secondAccessor: AccessorDeclaration; @@ -7456,19 +9166,17 @@ declare namespace ts { function isLogicalOperator(token: SyntaxKind): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; function tryGetClassExtendingExpressionWithTypeArguments(node: Node): ClassLikeDeclaration | undefined; - function isDestructuringAssignment(node: Node): node is BinaryExpression; + function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression; + function isAssignmentExpression(node: Node, excludeCompoundAssignment?: false): node is AssignmentExpression; + function isDestructuringAssignment(node: Node): node is DestructuringAssignment; function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean; function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; function isEntityNameExpression(node: Expression): node is EntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; - function hasJavaScriptFileExtension(fileName: string): boolean; - function hasTypeScriptFileExtension(fileName: string): boolean; function tryExtractTypeScriptExtension(fileName: string): string | undefined; - const stringify: (value: any) => string; function convertToBase64(input: string): string; - function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNewLineCharacter(options: CompilerOptions): string; function isSimpleExpression(node: Expression): boolean; function formatSyntaxKind(kind: SyntaxKind): string; @@ -7489,12 +9197,7 @@ declare namespace ts { function rangeEndIsOnSameLineAsRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: SourceFile): boolean; function getStartPositionOfRange(range: TextRange, sourceFile: SourceFile): number; - function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver): { - externalImports: (ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration)[]; - exportSpecifiers: Map; - exportEquals: ExportAssignment; - hasExportStarsToExportValues: boolean; - }; + function isDeclarationNameOfEnumOrNamespace(node: Identifier): boolean; function getInitializedVariables(node: VariableDeclarationList): VariableDeclaration[]; function isMergedWithClass(node: Node): boolean; function isFirstDeclarationOfKind(node: Node, kind: SyntaxKind): boolean; @@ -7504,9 +9207,10 @@ declare namespace ts { function isTextualLiteralKind(kind: SyntaxKind): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; function isTemplateLiteralKind(kind: SyntaxKind): boolean; - function isTemplateLiteralFragment(node: Node): node is TemplateLiteralFragment; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; function isIdentifier(node: Node): node is Identifier; - function isGeneratedIdentifier(node: Node): boolean; + function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier; function isModifier(node: Node): node is Modifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; @@ -7521,16 +9225,25 @@ declare namespace ts { function isClassElement(node: Node): node is ClassElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; function isTypeNode(node: Node): node is TypeNode; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; function isBindingPattern(node: Node): node is BindingPattern; + function isAssignmentPattern(node: Node): node is AssignmentPattern; function isBindingElement(node: Node): node is BindingElement; function isArrayBindingElement(node: Node): node is ArrayBindingElement; + function isDeclarationBindingElement(bindingElement: BindingOrAssignmentElement): bindingElement is VariableDeclaration | ParameterDeclaration | BindingElement; + function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is BindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ArrayBindingOrAssignmentPattern; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; function isElementAccessExpression(node: Node): node is ElementAccessExpression; function isBinaryExpression(node: Node): node is BinaryExpression; function isConditionalExpression(node: Node): node is ConditionalExpression; function isCallExpression(node: Node): node is CallExpression; - function isTemplate(node: Node): node is Template; - function isSpreadElementExpression(node: Node): node is SpreadElementExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isSpreadExpression(node: Node): node is SpreadElement; function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; function isUnaryExpression(node: Node): node is UnaryExpression; @@ -7599,9 +9312,15 @@ declare namespace ts { let unchangedTextChangeRange: TextChangeRange; function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; - function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function isParameterPropertyDeclaration(node: Node): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + }, errors?: Diagnostic[]): void; } declare namespace ts { function updateNode(updated: T, original: T): T; @@ -7610,27 +9329,27 @@ declare namespace ts { function createSynthesizedNodeArray(elements?: T[]): NodeArray; function getSynthesizedClone(node: T): T; function getMutableClone(node: T): T; - function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral; + function createLiteral(textSource: StringLiteral | NumericLiteral | Identifier, location?: TextRange): StringLiteral; function createLiteral(value: string, location?: TextRange): StringLiteral; function createLiteral(value: number, location?: TextRange): NumericLiteral; + function createLiteral(value: boolean, location?: TextRange): BooleanLiteral; function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression; function createIdentifier(text: string, location?: TextRange): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, location?: TextRange): Identifier; function createLoopVariable(location?: TextRange): Identifier; function createUniqueName(text: string, location?: TextRange): Identifier; function getGeneratedNameForNode(node: Node, location?: TextRange): Identifier; - function createToken(token: SyntaxKind): Node; + function createToken(token: TKind): Token; function createSuper(): PrimaryExpression; function createThis(location?: TextRange): PrimaryExpression; function createNull(): PrimaryExpression; function createComputedPropertyName(expression: Expression, location?: TextRange): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - function createParameter(name: string | Identifier | BindingPattern, initializer?: Expression, location?: TextRange): ParameterDeclaration; - function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: Node, name: string | Identifier | BindingPattern, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; - function updateParameterDeclaration(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression): ParameterDeclaration; - function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; + function createParameter(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: BindingName, type: TypeNode, initializer: Expression): ParameterDeclaration; + function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, type: TypeNode, initializer: Expression): PropertyDeclaration; - function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; + function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): MethodDeclaration; function createConstructor(decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block, location?: TextRange, flags?: NodeFlags): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block): ConstructorDeclaration; @@ -7642,8 +9361,8 @@ declare namespace ts { function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[], location?: TextRange): ArrayBindingPattern; function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; - function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: Node, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; - function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression): BindingElement; + function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: DotDotDotToken, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; + function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken, propertyName: PropertyName, name: BindingName, initializer: Expression): BindingElement; function createArrayLiteral(elements?: Expression[], location?: TextRange, multiLine?: boolean): ArrayLiteralExpression; function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; function createObjectLiteral(properties?: ObjectLiteralElementLike[], location?: TextRange, multiLine?: boolean): ObjectLiteralExpression; @@ -7656,13 +9375,13 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): CallExpression; function createNew(expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[], location?: TextRange, flags?: NodeFlags): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): NewExpression; - function createTaggedTemplate(tag: Expression, template: Template, location?: TextRange): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: Template): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, template: TemplateLiteral, location?: TextRange): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createParen(expression: Expression, location?: TextRange): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; - function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: Node, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; + function createFunctionExpression(modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionExpression; + function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression, location?: TextRange): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): Expression; @@ -7672,27 +9391,28 @@ declare namespace ts { function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; function createAwait(expression: Expression, location?: TextRange): AwaitExpression; function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; - function createPrefix(operator: SyntaxKind, operand: Expression, location?: TextRange): PrefixUnaryExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression, location?: TextRange): PrefixUnaryExpression; function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; - function createPostfix(operand: Expression, operator: SyntaxKind, location?: TextRange): PostfixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator, location?: TextRange): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; - function createBinary(left: Expression, operator: SyntaxKind | Node, right: Expression, location?: TextRange): BinaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression, location?: TextRange): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; - function createConditional(condition: Expression, questionToken: Node, whenTrue: Expression, colonToken: Node, whenFalse: Expression, location?: TextRange): ConditionalExpression; + function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression, location?: TextRange): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; - function createTemplateExpression(head: TemplateLiteralFragment, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateLiteralFragment, templateSpans: TemplateSpan[]): TemplateExpression; - function createYield(asteriskToken: Node, expression: Expression, location?: TextRange): YieldExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createYield(asteriskToken: AsteriskToken, expression: Expression, location?: TextRange): YieldExpression; function updateYield(node: YieldExpression, expression: Expression): YieldExpression; - function createSpread(expression: Expression, location?: TextRange): SpreadElementExpression; - function updateSpread(node: SpreadElementExpression, expression: Expression): SpreadElementExpression; + function createSpread(expression: Expression, location?: TextRange): SpreadElement; + function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; function createClassExpression(modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassExpression; function updateClassExpression(node: ClassExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; function createOmittedExpression(location?: TextRange): OmittedExpression; function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression, location?: TextRange): ExpressionWithTypeArguments; function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function createTemplateSpan(expression: Expression, literal: TemplateLiteralFragment, location?: TextRange): TemplateSpan; - function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateLiteralFragment): TemplateSpan; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail, location?: TextRange): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function createBlock(statements: Statement[], location?: TextRange, multiLine?: boolean, flags?: NodeFlags): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[], declarationList: VariableDeclarationList | VariableDeclaration[], location?: TextRange, flags?: NodeFlags): VariableStatement; @@ -7715,9 +9435,9 @@ declare namespace ts { function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function createForOf(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForOfStatement; - function updateForOf(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createContinue(label?: Identifier, location?: TextRange): BreakStatement; - function updateContinue(node: ContinueStatement, label: Identifier): BreakStatement; + function updateForOf(node: ForOfStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: Identifier, location?: TextRange): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier): ContinueStatement; function createBreak(label?: Identifier, location?: TextRange): BreakStatement; function updateBreak(node: BreakStatement, label: Identifier): BreakStatement; function createReturn(expression?: Expression, location?: TextRange): ReturnStatement; @@ -7734,7 +9454,7 @@ declare namespace ts { function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause, finallyBlock: Block): TryStatement; function createCaseBlock(clauses: CaseOrDefaultClause[], location?: TextRange): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; - function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; + function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; @@ -7781,13 +9501,19 @@ declare namespace ts { function createPropertyAssignment(name: string | PropertyName, initializer: Expression, location?: TextRange): PropertyAssignment; function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer: Expression, location?: TextRange): ShorthandPropertyAssignment; + function createSpreadAssignment(expression: Expression, location?: TextRange): SpreadAssignment; function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression): ShorthandPropertyAssignment; + function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function updateSourceFileNode(node: SourceFile, statements: Statement[]): SourceFile; function createNotEmittedStatement(original: Node): NotEmittedStatement; + function createEndOfDeclarationMarker(original: Node): EndOfDeclarationMarker; + function createMergeDeclarationMarker(original: Node): MergeDeclarationMarker; function createPartiallyEmittedExpression(expression: Expression, original?: Node, location?: TextRange): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; + function createRawExpression(text: string): RawExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression, location?: TextRange): Expression; + function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression, location?: TextRange): DestructuringAssignment; function createAssignment(left: Expression, right: Expression, location?: TextRange): BinaryExpression; function createStrictEquality(left: Expression, right: Expression): BinaryExpression; function createStrictInequality(left: Expression, right: Expression): BinaryExpression; @@ -7798,26 +9524,21 @@ declare namespace ts { function createLogicalOr(left: Expression, right: Expression): BinaryExpression; function createLogicalNot(operand: Expression): PrefixUnaryExpression; function createVoidZero(): VoidExpression; + type TypeOfTag = "undefined" | "number" | "boolean" | "string" | "symbol" | "object" | "function"; + function createTypeCheck(value: Expression, tag: TypeOfTag): BinaryExpression; function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression; - function createRestParameter(name: string | Identifier): ParameterDeclaration; function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: Expression[], location?: TextRange): CallExpression; function createFunctionApply(func: Expression, thisArg: Expression, argumentsExpression: Expression, location?: TextRange): CallExpression; function createArraySlice(array: Expression, start?: number | Expression): CallExpression; function createArrayConcat(array: Expression, values: Expression[]): CallExpression; function createMathPow(left: Expression, right: Expression, location?: TextRange): CallExpression; - function createReactCreateElement(reactNamespace: string, tagName: Expression, props: Expression, children: Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression; + function createExpressionForJsxElement(jsxFactoryEntity: EntityName, reactNamespace: string, tagName: Expression, props: Expression, children: Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression; + function createExportDefault(expression: Expression): ExportAssignment; + function createExternalModuleExport(exportName: Identifier): ExportDeclaration; + function createLetStatement(name: Identifier, initializer: Expression, location?: TextRange): VariableStatement; function createLetDeclarationList(declarations: VariableDeclaration[], location?: TextRange): VariableDeclarationList; function createConstDeclarationList(declarations: VariableDeclaration[], location?: TextRange): VariableDeclarationList; - function createHelperName(externalHelpersModuleName: Identifier | undefined, name: string): Identifier | PropertyAccessExpression; - function createExtendsHelper(externalHelpersModuleName: Identifier | undefined, name: Identifier): CallExpression; - function createAssignHelper(externalHelpersModuleName: Identifier | undefined, attributesSegments: Expression[]): CallExpression; - function createParamHelper(externalHelpersModuleName: Identifier | undefined, expression: Expression, parameterOffset: number, location?: TextRange): CallExpression; - function createMetadataHelper(externalHelpersModuleName: Identifier | undefined, metadataKey: string, metadataValue: Expression): CallExpression; - function createDecorateHelper(externalHelpersModuleName: Identifier | undefined, decoratorExpressions: Expression[], target: Expression, memberName?: Expression, descriptor?: Expression, location?: TextRange): CallExpression; - function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block): CallExpression; - function createHasOwnProperty(target: LeftHandSideExpression, propertyName: Expression): CallExpression; - function createAdvancedAsyncSuperHelper(): VariableStatement; - function createSimpleAsyncSuperHelper(): VariableStatement; + function getHelperName(name: string): Identifier; interface CallBinding { target: LeftHandSideExpression; thisArg: Expression; @@ -7827,8 +9548,19 @@ declare namespace ts { function createExpressionFromEntityName(node: EntityName | Expression): Expression; function createExpressionForPropertyName(memberName: PropertyName): Expression; function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression; + function getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + function isLocalName(node: Identifier): boolean; + function getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + function isExportName(node: Identifier): boolean; + function getDeclarationName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + function getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression; + function getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression; + function convertToFunctionBody(node: ConciseBody, multiLine?: boolean): Block; function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; + function startsWithUseStrict(statements: Statement[]): boolean; + function ensureUseStrict(statements: NodeArray): NodeArray; function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression): Expression; + function parenthesizeForConditionalHead(condition: Expression): Expression; function parenthesizeForNew(expression: Expression): LeftHandSideExpression; function parenthesizeForAccess(expression: Expression): LeftHandSideExpression; function parenthesizePostfixOperand(operand: Expression): LeftHandSideExpression; @@ -7852,6 +9584,26 @@ declare namespace ts { function skipPartiallyEmittedExpressions(node: Node): Node; function startOnNewLine(node: T): T; function setOriginalNode(node: T, original: Node): T; + function disposeEmitNodes(sourceFile: SourceFile): void; + function getOrCreateEmitNode(node: Node): EmitNode; + function getEmitFlags(node: Node): EmitFlags; + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + function getSourceMapRange(node: Node): TextRange; + function setSourceMapRange(node: T, range: TextRange): T; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; + function getCommentRange(node: Node): TextRange; + function setCommentRange(node: T, range: TextRange): T; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; + function getExternalHelpersModuleName(node: SourceFile): Identifier; + function getOrCreateExternalHelpersModuleNameIfNeeded(node: SourceFile, compilerOptions: CompilerOptions): Identifier; + function addEmitHelper(node: T, helper: EmitHelper): T; + function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; + function removeEmitHelper(node: Node, helper: EmitHelper): boolean; + function getEmitHelpers(node: Node): EmitHelper[] | undefined; + function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; + function compareEmitHelpers(x: EmitHelper, y: EmitHelper): Comparison; function setTextRange(node: T, location: TextRange): T; function setNodeFlags(node: T, flags: NodeFlags): T; function setMultiLine(node: T, multiLine: boolean): T; @@ -7859,11 +9611,33 @@ declare namespace ts { function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier; function getExternalModuleNameLiteral(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions): StringLiteral; function tryGetModuleNameFromFile(file: SourceFile, host: EmitHost, options: CompilerOptions): StringLiteral; + function getInitializerOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Expression | undefined; + function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget; + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator; + function getPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): PropertyName; + function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): BindingOrAssignmentElement[]; + function convertToArrayAssignmentElement(element: BindingOrAssignmentElement): Expression; + function convertToObjectAssignmentElement(element: BindingOrAssignmentElement): ObjectLiteralElementLike; + function convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern; + function convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern): ObjectLiteralExpression; + function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern): ArrayLiteralExpression; + function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression; + interface ExternalModuleInfo { + externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; + externalHelpersImportDeclaration: ImportDeclaration | undefined; + exportSpecifiers: Map; + exportedBindings: Map; + exportedNames: Identifier[]; + exportEquals: ExportAssignment | undefined; + hasExportStarsToExportValues: boolean; + } + function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function parseIsolatedJSDocComment(content: string, start?: number, length?: number): { @@ -7884,6 +9658,7 @@ declare namespace ts { function getModuleInstanceState(node: Node): ModuleInstanceState; function bindSourceFile(file: SourceFile, options: CompilerOptions): void; function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags; + function getTransformFlagsSubtreeExclusions(kind: SyntaxKind): TransformFlags; } declare namespace ts { function getNodeId(node: Node): number; @@ -7892,43 +9667,65 @@ declare namespace ts { } declare namespace ts { type VisitResult = T | T[]; - function reduceEachChild(node: Node, f: (memo: T, node: Node) => T, initial: T): T; + function reduceEachChild(node: Node, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: Node[]) => T): T; function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray) => T): T; function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray) => T, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): T; function visitNodes(nodes: NodeArray, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, start?: number, count?: number): NodeArray; function visitNodes(nodes: NodeArray, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, start: number, count: number, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): NodeArray; - function visitEachChild(node: T, visitor: (node: Node) => VisitResult, context: LexicalEnvironment): T; + function visitLexicalEnvironment(statements: NodeArray, visitor: (node: Node) => VisitResult, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray; + function visitParameterList(nodes: NodeArray, visitor: (node: Node) => VisitResult, context: TransformationContext): NodeArray; + function visitFunctionBody(node: FunctionBody, visitor: (node: Node) => VisitResult, context: TransformationContext): FunctionBody; + function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult, context: TransformationContext): ConciseBody; + function visitEachChild(node: T, visitor: (node: Node) => VisitResult, context: TransformationContext): T; + function mergeLexicalEnvironment(statements: NodeArray, declarations: Statement[]): NodeArray; + function mergeLexicalEnvironment(statements: Statement[], declarations: Statement[]): Statement[]; function mergeFunctionBodyLexicalEnvironment(body: FunctionBody, declarations: Statement[]): FunctionBody; function mergeFunctionBodyLexicalEnvironment(body: ConciseBody, declarations: Statement[]): ConciseBody; function liftToBlock(nodes: Node[]): Statement; function aggregateTransformFlags(node: T): T; namespace Debug { - const failNotOptional: (message?: string) => void; + const failNotOptional: typeof noop; const failBadSyntaxKind: (node: Node, message?: string) => void; + const assertEachNode: (nodes: Node[], test: (node: Node) => boolean, message?: string) => void; const assertNode: (node: Node, test: (node: Node) => boolean, message?: string) => void; + const assertOptionalNode: (node: Node, test: (node: Node) => boolean, message?: string) => void; + const assertOptionalToken: (node: Node, kind: SyntaxKind, message?: string) => void; + const assertMissingNode: (node: Node, message?: string) => void; } } declare namespace ts { - function flattenDestructuringAssignment(context: TransformationContext, node: BinaryExpression, needsValue: boolean, recordTempVariable: (node: Identifier) => void, visitor?: (node: Node) => VisitResult): Expression; - function flattenParameterDestructuring(context: TransformationContext, node: ParameterDeclaration, value: Expression, visitor?: (node: Node) => VisitResult): VariableDeclaration[]; - function flattenVariableDestructuring(context: TransformationContext, node: VariableDeclaration, value?: Expression, visitor?: (node: Node) => VisitResult, recordTempVariable?: (node: Identifier) => void): VariableDeclaration[]; - function flattenVariableDestructuringToExpression(context: TransformationContext, node: VariableDeclaration, recordTempVariable: (name: Identifier) => void, nameSubstitution?: (name: Identifier) => Expression, visitor?: (node: Node) => VisitResult): Expression; + const enum FlattenLevel { + All = 0, + ObjectRest = 1, + } + function flattenDestructuringAssignment(node: VariableDeclaration | DestructuringAssignment, visitor: ((node: Node) => VisitResult) | undefined, context: TransformationContext, level: FlattenLevel, needsValue?: boolean, createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression; + function flattenDestructuringBinding(node: VariableDeclaration | ParameterDeclaration, visitor: (node: Node) => VisitResult, context: TransformationContext, level: FlattenLevel, rval?: Expression, hoistTempVariables?: boolean, skipInitializer?: boolean): VariableDeclaration[]; } declare namespace ts { function transformTypeScript(context: TransformationContext): (node: SourceFile) => SourceFile; } +declare namespace ts { + function transformESNext(context: TransformationContext): (node: SourceFile) => SourceFile; + function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]): CallExpression; +} declare namespace ts { function transformJsx(context: TransformationContext): (node: SourceFile) => SourceFile; } declare namespace ts { - function transformES7(context: TransformationContext): (node: SourceFile) => SourceFile; + function transformES2017(context: TransformationContext): (node: SourceFile) => SourceFile; } declare namespace ts { - function transformES6(context: TransformationContext): (node: SourceFile) => SourceFile; + function transformES2016(context: TransformationContext): (node: SourceFile) => SourceFile; +} +declare namespace ts { + function transformES2015(context: TransformationContext): (node: SourceFile) => SourceFile; } declare namespace ts { function transformGenerators(context: TransformationContext): (node: SourceFile) => SourceFile; } +declare namespace ts { + function transformES5(context: TransformationContext): (node: SourceFile) => SourceFile; +} declare namespace ts { function transformModule(context: TransformationContext): (node: SourceFile) => SourceFile; } @@ -7936,102 +9733,47 @@ declare namespace ts { function transformSystemModule(context: TransformationContext): (node: SourceFile) => SourceFile; } declare namespace ts { - function transformES6Module(context: TransformationContext): (node: SourceFile) => SourceFile; + function transformES2015Module(context: TransformationContext): (node: SourceFile) => SourceFile; } declare namespace ts { - interface TransformationResult { - getSourceFiles(): SourceFile[]; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - isSubstitutionEnabled(node: Node): boolean; - isEmitNotificationEnabled(node: Node): boolean; - onSubstituteNode(node: Node, isExpression: boolean): Node; - onEmitNode(node: Node, emitCallback: (node: Node) => void): void; - dispose(): void; - } - interface TransformationContext extends LexicalEnvironment { - getCompilerOptions(): CompilerOptions; - getEmitResolver(): EmitResolver; - getEmitHost(): EmitHost; - getNodeEmitFlags(node: Node): NodeEmitFlags; - setNodeEmitFlags(node: T, flags: NodeEmitFlags): T; - getSourceMapRange(node: Node): TextRange; - setSourceMapRange(node: T, range: TextRange): T; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; - getCommentRange(node: Node): TextRange; - setCommentRange(node: T, range: TextRange): T; - hoistFunctionDeclaration(node: FunctionDeclaration): void; - hoistVariableDeclaration(node: Identifier): void; - enableSubstitution(kind: SyntaxKind): void; - isSubstitutionEnabled(node: Node): boolean; - onSubstituteNode?: (node: Node, isExpression: boolean) => Node; - enableEmitNotification(kind: SyntaxKind): void; - isEmitNotificationEnabled(node: Node): boolean; - onEmitNode?: (node: Node, emit: (node: Node) => void) => void; - } - type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; function getTransformers(compilerOptions: CompilerOptions): Transformer[]; function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult; } declare namespace ts { function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[]; - function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean; + function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean): boolean; } declare namespace ts { interface SourceMapWriter { initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void; reset(): void; - getSourceMapData(): SourceMapData; setSourceFile(sourceFile: SourceFile): void; emitPos(pos: number): void; - emitStart(range: TextRange): void; - emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitEnd(range: TextRange): void; - emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitTokenStart(token: SyntaxKind, tokenStartPos: number): number; - emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - changeEmitSourcePos(): void; - stopOverridingSpan(): void; + emitNodeWithSourceMap(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitTokenWithSourceMap(node: Node, token: SyntaxKind, tokenStartPos: number, emitCallback: (token: SyntaxKind, tokenStartPos: number) => number): number; getText(): string; getSourceMappingURL(): string; + getSourceMapData(): SourceMapData; } function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter; - function getNullSourceMapWriter(): SourceMapWriter; } declare namespace ts { interface CommentWriter { reset(): void; setSourceFile(sourceFile: SourceFile): void; - emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void; + emitNodeWithComments(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; emitTrailingCommentsOfPosition(pos: number): void; } function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter; } declare namespace ts { - function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult; + function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult; } declare namespace ts { - const version = "2.1.0"; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string; - function hasZeroOrOneAsteriskCharacter(str: string): boolean; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; - function tryParsePattern(pattern: string): Pattern | undefined; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function directoryProbablyExists(directoryName: string, host: { - directoryExists?: (directoryName: string) => boolean; - }): boolean; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; interface FormatDiagnosticsHost { @@ -8041,8 +9783,8 @@ declare namespace ts { } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function getResolutionDiagnostic(options: CompilerOptions, {extension}: ResolvedModuleFull): DiagnosticMessage | undefined; } declare namespace ts { interface Node { @@ -8093,6 +9835,7 @@ declare namespace ts { nameTable: Map; getNamedDeclarations(): Map; getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; getLineStarts(): number[]; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; @@ -8135,6 +9878,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -8165,18 +9909,20 @@ declare namespace ts { findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; getNonBoundSourceFile(fileName: string): SourceFile; getSourceFile(fileName: string): SourceFile; @@ -8200,6 +9946,13 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -8213,6 +9966,14 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + description: string; + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; caretOffset: number; @@ -8257,6 +10018,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -8265,10 +10031,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -8284,7 +10053,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -8367,6 +10150,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; isNewIdentifierLocation: boolean; entries: CompletionEntry[]; @@ -8610,7 +10394,7 @@ declare namespace ts { declare namespace ts { function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean; function symbolPart(text: string, symbol: Symbol): SymbolDisplayPart; - function displayPart(text: string, kind: SymbolDisplayPartKind, symbol?: Symbol): SymbolDisplayPart; + function displayPart(text: string, kind: SymbolDisplayPartKind): SymbolDisplayPart; function spacePart(): SymbolDisplayPart; function keywordPart(kind: SyntaxKind): SymbolDisplayPart; function punctuationPart(kind: SyntaxKind): SymbolDisplayPart; @@ -8628,7 +10412,7 @@ declare namespace ts { function stripQuotes(name: string): string; function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; - function parseAndReEmitConfigJSONFile(content: string): { + function sanitizeConfigFile(configFileName: string, content: string): { configJsonObject: any; diagnostics: Diagnostic[]; }; @@ -8682,28 +10466,16 @@ declare namespace ts.GoToImplementation { function getImplementationAtPosition(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): ImplementationLocation[]; } declare namespace ts.JsDoc { - function getJsDocCommentsFromDeclarations(declarations: Declaration[], name: string, canUseParsedParamTagComments: boolean): SymbolDisplayPart[]; + function getJsDocCommentsFromDeclarations(declarations: Declaration[]): SymbolDisplayPart[]; function getAllJsDocCompletionEntries(): CompletionEntry[]; function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion; } -declare namespace ts.JsTyping { - interface TypingResolutionHost { - directoryExists: (path: string) => boolean; - fileExists: (fileName: string) => boolean; - readFile: (path: string, encoding?: string) => 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[]; - newTypingNames: string[]; - filesToWatch: string[]; - }; -} declare namespace ts.NavigateTo { - function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; + function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[]; } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; + function getNavigationTree(sourceFile: SourceFile): NavigationTree; } declare namespace ts.OutliningElementsCollector { function collectElements(sourceFile: SourceFile): OutliningSpan[]; @@ -9109,7 +10881,7 @@ declare namespace ts.formatting { } class TokenAllAccess implements ITokenAccess { GetTokens(): SyntaxKind[]; - Contains(tokenValue: SyntaxKind): boolean; + Contains(): boolean; toString(): string; } class TokenRange { @@ -9148,7 +10920,7 @@ declare namespace ts.formatting { getRuleName(rule: Rule): string; getRuleByName(name: string): Rule; getRulesMap(): RulesMap; - ensureUpToDate(options: ts.FormatCodeOptions): void; + ensureUpToDate(options: ts.FormatCodeSettings): void; private createActiveRules(options); } } @@ -9161,35 +10933,64 @@ declare namespace ts.formatting { token: TextRangeWithKind; trailingTrivia: TextRangeWithKind[]; } - function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function getIndentationString(indentation: number, options: FormatCodeOptions): string; + function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function getIndentationString(indentation: number, options: EditorSettings): string; } declare namespace ts.formatting { namespace SmartIndenter { - function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number; - function getBaseIndentation(options: EditorOptions): number; - function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number; + function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number; + function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number; + function getBaseIndentation(options: EditorSettings): number; function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean; - function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): { + function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): { column: number; character: number; }; - function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): number; + function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): number; function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean): boolean; function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean; } } +declare namespace ts { + interface CodeFix { + errorCodes: number[]; + getCodeActions(context: CodeFixContext): CodeAction[] | undefined; + } + interface CodeFixContext { + errorCode: number; + sourceFile: SourceFile; + span: TextSpan; + program: Program; + newLineCharacter: string; + host: LanguageServiceHost; + cancellationToken: CancellationToken; + } + namespace codefix { + function registerCodeFix(action: CodeFix): void; + function getSupportedErrorCodes(): string[]; + function getFixes(context: CodeFixContext): CodeAction[]; + } +} +declare namespace ts.codefix { +} +declare namespace ts.codefix { +} +declare namespace ts.codefix { +} declare namespace ts { const servicesVersion = "0.5"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; @@ -9198,101 +10999,585 @@ declare namespace ts { function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { - function generateSpaces(n: number): string; - function generateIndentString(n: number, editorOptions: EditorOptions): string; + class TextStorage { + private readonly host; + private readonly fileName; + private svc; + private svcVersion; + private text; + private lineMap; + private textVersion; + constructor(host: ServerHost, fileName: NormalizedPath); + getVersion(): string; + hasScriptVersionCache(): boolean; + useScriptVersionCache(newText?: string): void; + useText(newText?: string): void; + edit(start: number, end: number, newText: string): void; + reload(text: string): void; + reloadFromFile(tempFileName?: string): void; + getSnapshot(): IScriptSnapshot; + getLineInfo(line: number): ILineInfo; + lineToTextSpan(line: number): TextSpan; + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): ILineInfo; + private getFileText(tempFileName?); + private ensureNoScriptVersionCache(); + private switchToScriptVersionCache(newText?); + private getOrLoadText(); + private getLineMap(); + private setText(newText); + } + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + hasMixedContent: boolean; + readonly containingProjects: Project[]; + private formatCodeSettings; + readonly path: Path; + private fileWatcher; + private textStorage; + private isOpen; + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent?: boolean); + isScriptOpen(): boolean; + open(newText: string): void; + close(): void; + getSnapshot(): IScriptSnapshot; + getFormatCodeSettings(): FormatCodeSettings; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + registerFileUpdate(): void; + setFormatOptions(formatSettings: FormatCodeSettings): void; + setWatcher(watcher: FileWatcher): void; + stopWatcher(): void; + getLatestVersion(): string; + reload(script: string): void; + saveTo(fileName: string): void; + reloadFromFile(tempFileName?: NormalizedPath): void; + getLineInfo(line: number): ILineInfo; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + lineToTextSpan(line: number): TextSpan; + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): ILineInfo; + } +} +declare namespace ts.server { + class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost { + private readonly host; + private readonly project; + private readonly cancellationToken; + private compilationSettings; + private readonly resolvedModuleNames; + private readonly resolvedTypeReferenceDirectives; + private readonly getCanonicalFileName; + private filesWithChangedSetOfUnresolvedImports; + private readonly resolveModuleName; + readonly trace: (s: string) => void; + readonly realpath?: (path: string) => string; + constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); + startRecordingFilesWithChangedResolutions(): void; + finishRecordingFilesWithChangedResolutions(): Path[]; + private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult, getResultFileName, logChanges); + getProjectVersion(): string; + getCompilationSettings(): CompilerOptions; + useCaseSensitiveFileNames(): boolean; + getCancellationToken(): HostCancellationToken; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModuleFull[]; + getDefaultLibFileName(): string; + getScriptSnapshot(filename: string): ts.IScriptSnapshot; + getScriptFileNames(): string[]; + getTypeRootsVersion(): number; + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getCurrentDirectory(): string; + resolvePath(path: string): string; + fileExists(path: string): boolean; + readFile(fileName: string): string; + directoryExists(path: string): boolean; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + getDirectories(path: string): string[]; + notifyFileRemoved(info: ScriptInfo): void; + setCompilationSettings(opt: ts.CompilerOptions): void; + } +} +declare namespace ts.server { + interface ITypingsInstaller { + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string; + } + const nullTypingsInstaller: ITypingsInstaller; + class TypingsCache { + private readonly installer; + private readonly perProjectCache; + constructor(installer: ITypingsInstaller); + getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray, forceRefresh: boolean): SortedReadonlyArray; + updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]): void; + deleteTypingsForProject(projectName: string): void; + onProjectClosed(project: Project): void; + } +} +declare namespace ts.server { + function shouldEmitFile(scriptInfo: ScriptInfo): boolean; + class BuilderFileInfo { + readonly scriptInfo: ScriptInfo; + readonly project: Project; + private lastCheckedShapeSignature; + constructor(scriptInfo: ScriptInfo, project: Project); + isExternalModuleOrHasOnlyAmbientExternalModules(): boolean; + private containsOnlyAmbientModules(sourceFile); + private computeHash(text); + private getSourceFile(); + updateShapeSignature(): boolean; + } + interface Builder { + readonly project: Project; + getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; + onProjectUpdateGraph(): void; + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + clear(): void; + } + function createBuilder(project: Project): Builder; +} +declare namespace ts.server { + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2, + } + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { + projectErrors: Diagnostic[]; + } + class UnresolvedImportsMap { + readonly perFileMap: FileMap>; + private version; + clear(): void; + getVersion(): number; + remove(path: Path): void; + get(path: Path): ReadonlyArray; + set(path: Path, value: ReadonlyArray): void; + } + abstract class Project { + private readonly projectName; + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + private compilerOptions; + compileOnSaveEnabled: boolean; + private rootFiles; + private rootFilesMap; + private lsHost; + private program; + private cachedUnresolvedImportsPerFile; + private lastCachedUnresolvedImportsList; + private readonly languageService; + languageServiceEnabled: boolean; + builder: Builder; + private updatedFileNames; + private lastReportedFileNames; + private lastReportedVersion; + private projectStructureVersion; + private projectStateVersion; + private typingFiles; + protected projectErrors: Diagnostic[]; + typesVersion: number; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + getCachedUnresolvedImportsPerFile_TestOnly(): UnresolvedImportsMap; + constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + private setInternalCompilerOptionsForEmittingJsFiles(); + getProjectErrors(): Diagnostic[]; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + getProjectVersion(): string; + enableLanguageService(): void; + disableLanguageService(): void; + getProjectName(): string; + abstract getProjectRootPath(): string | undefined; + abstract getTypeAcquisition(): TypeAcquisition; + getSourceFile(path: Path): SourceFile; + updateTypes(): void; + close(): void; + getCompilerOptions(): CompilerOptions; + hasRoots(): boolean; + getRootFiles(): NormalizedPath[]; + getRootFilesLSHost(): string[]; + getRootScriptInfos(): ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; + getFileNames(excludeFilesFromExternalLibraries?: boolean): NormalizedPath[]; + getAllEmittableFiles(): string[]; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo): void; + removeFile(info: ScriptInfo, detachFromProject?: boolean): void; + registerFileUpdate(fileName: string): void; + markAsDirty(): void; + private extractUnresolvedImportsFromSourceFile(file, result); + updateGraph(): boolean; + private setTypings(typings); + private updateGraphWorker(); + getScriptInfoLSHost(fileName: string): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + filesToString(): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + reloadScript(filename: NormalizedPath, tempFileName?: NormalizedPath): boolean; + getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; + getReferencedFiles(path: Path): Path[]; + private removeRootFileIfNecessary(info); + } + class InferredProject extends Project { + private static newName; + directoriesWatchedForTsconfig: string[]; + constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions); + getProjectRootPath(): string; + close(): void; + getTypeAcquisition(): TypeAcquisition; + } + class ConfiguredProject extends Project { + private wildcardDirectories; + compileOnSaveEnabled: boolean; + private typeAcquisition; + private projectFileWatcher; + private directoryWatcher; + private directoriesWatchedForWildcards; + private typeRootsWatchers; + readonly canonicalConfigFilePath: NormalizedPath; + openRefCount: number; + constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); + getConfigFilePath(): string; + getProjectRootPath(): string; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; + getTypeAcquisition(): TypeAcquisition; + watchConfigFile(callback: (project: ConfiguredProject) => void): void; + watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; + watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; + watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void; + stopWatchingDirectory(): void; + close(): void; + addOpenRef(): void; + deleteOpenRef(): number; + getEffectiveTypeRoots(): string[]; + } + class ExternalProject extends Project { + compileOnSaveEnabled: boolean; + private readonly projectFilePath; + private typeAcquisition; + constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); + getProjectRootPath(): string; + getTypeAcquisition(): TypeAcquisition; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; + } +} +declare namespace ts.server { + const maxProgramSizeForNonTsFiles: number; + const ContextEvent = "context"; + const ConfigFileDiagEvent = "configFileDiag"; + const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + interface ContextEvent { + eventName: typeof ContextEvent; + data: { + project: Project; + fileName: NormalizedPath; + }; + } + interface ConfigFileDiagEvent { + eventName: typeof ConfigFileDiagEvent; + data: { + triggerFile: string; + configFileName: string; + diagnostics: Diagnostic[]; + }; + } + interface ProjectLanguageServiceStateEvent { + eventName: typeof ProjectLanguageServiceStateEvent; + data: { + project: Project; + languageServiceEnabled: boolean; + }; + } + type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent; + interface ProjectServiceEventHandler { + (event: ProjectServiceEvent): void; + } + function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; + function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; + function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind; + function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; + } + interface OpenConfiguredProjectResult { + configFileName?: NormalizedPath; + configFileErrors?: Diagnostic[]; + } + class ProjectService { + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly eventHandler; + readonly typingsCache: TypingsCache; + private readonly documentRegistry; + private readonly filenameToScriptInfo; + private readonly externalProjectToConfiguredProjectMap; + readonly externalProjects: ExternalProject[]; + readonly inferredProjects: InferredProject[]; + readonly configuredProjects: ConfiguredProject[]; + readonly openFiles: ScriptInfo[]; + private compilerOptionsForInferredProjects; + private compileOnSaveForInferredProjects; + private readonly directoryWatchers; + private readonly throttledOperations; + private readonly hostConfiguration; + private changedFiles; + readonly toCanonicalFileName: (f: string) => string; + lastDeletedFile: ScriptInfo; + constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler); + getChangedFiles_TestOnly(): ScriptInfo[]; + ensureInferredProjectsUpToDate_TestOnly(): void; + getCompilerOptionsForInferredProjects(): CompilerOptions; + onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean): void; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; + stopWatchingDirectory(directory: string): void; + findProject(projectName: string): Project; + getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; + private ensureInferredProjectsUpToDate(); + private findContainingExternalProject(fileName); + getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; + private updateProjectGraphs(projects); + private onSourceFileChanged(fileName); + private handleDeletedFile(info); + private onTypeRootFileChanged(project, fileName); + private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName); + private handleChangeInSourceFileForConfiguredProject(project, triggerFile); + private onConfigChangedForConfiguredProject(project); + private onConfigFileAddedForInferredProject(fileName); + private getCanonicalFileName(fileName); + private removeProject(project); + private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); + private closeOpenFile(info); + private openOrUpdateConfiguredProjectForFile(fileName); + private findConfigFile(searchPath); + private printProjects(); + private findConfiguredProjectByProjectName(configFileName); + private findExternalProjectByProjectName(projectFileName); + private convertConfigFileContentToProjectOptions(configFilename); + private exceededTotalSizeLimitForNonTsFiles(options, fileNames, propertyReader); + private createAndAddExternalProject(projectFileName, files, options, typeAcquisition); + private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile); + private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); + private watchConfigDirectoryForProject(project, options); + private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors); + private openConfigFile(configFileName, clientFileName?); + private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors); + private updateConfiguredProject(project); + createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; + getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfoForPath(fileName: Path): ScriptInfo; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + reloadProjects(): void; + refreshInferredProjects(): void; + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): OpenConfiguredProjectResult; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult; + closeClientFile(uncheckedFileName: string): void; + private collectChanges(lastKnownProjectVersions, currentProjects, result); + synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[]; + applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void; + private closeConfiguredProject(configFile); + closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; + openExternalProjects(projects: protocol.ExternalProject[]): void; + openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects?: boolean): void; + } +} +declare namespace ts.server { interface PendingErrorCheck { - fileName: string; + fileName: NormalizedPath; project: Project; } + interface EventSender { + event(payload: any, eventName: string): void; + } namespace CommandNames { - const Brace = "brace"; - const Change = "change"; - const Close = "close"; - const Completions = "completions"; - const CompletionDetails = "completionEntryDetails"; - const Configure = "configure"; - const Definition = "definition"; - const Exit = "exit"; - const Format = "format"; - const Formatonkey = "formatonkey"; - const Geterr = "geterr"; - const GeterrForProject = "geterrForProject"; - const Implementation = "implementation"; - const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - const NavBar = "navbar"; - const Navto = "navto"; - const Occurrences = "occurrences"; - const DocumentHighlights = "documentHighlights"; - const Open = "open"; - const Quickinfo = "quickinfo"; - const References = "references"; - const Reload = "reload"; - const Rename = "rename"; - const Saveto = "saveto"; - const SignatureHelp = "signatureHelp"; - const TypeDefinition = "typeDefinition"; - const ProjectInfo = "projectInfo"; - const ReloadProjects = "reloadProjects"; - const Unknown = "unknown"; + const Brace: protocol.CommandTypes.Brace; + const BraceFull: protocol.CommandTypes.BraceFull; + const BraceCompletion: protocol.CommandTypes.BraceCompletion; + const Change: protocol.CommandTypes.Change; + const Close: protocol.CommandTypes.Close; + const Completions: protocol.CommandTypes.Completions; + const CompletionsFull: protocol.CommandTypes.CompletionsFull; + const CompletionDetails: protocol.CommandTypes.CompletionDetails; + const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList; + const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile; + const Configure: protocol.CommandTypes.Configure; + const Definition: protocol.CommandTypes.Definition; + const DefinitionFull: protocol.CommandTypes.DefinitionFull; + const Exit: protocol.CommandTypes.Exit; + const Format: protocol.CommandTypes.Format; + const Formatonkey: protocol.CommandTypes.Formatonkey; + const FormatFull: protocol.CommandTypes.FormatFull; + const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull; + const FormatRangeFull: protocol.CommandTypes.FormatRangeFull; + const Geterr: protocol.CommandTypes.Geterr; + const GeterrForProject: protocol.CommandTypes.GeterrForProject; + const Implementation: protocol.CommandTypes.Implementation; + const ImplementationFull: protocol.CommandTypes.ImplementationFull; + const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync; + const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync; + const NavBar: protocol.CommandTypes.NavBar; + const NavBarFull: protocol.CommandTypes.NavBarFull; + const NavTree: protocol.CommandTypes.NavTree; + const NavTreeFull: protocol.CommandTypes.NavTreeFull; + const Navto: protocol.CommandTypes.Navto; + const NavtoFull: protocol.CommandTypes.NavtoFull; + const Occurrences: protocol.CommandTypes.Occurrences; + const DocumentHighlights: protocol.CommandTypes.DocumentHighlights; + const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull; + const Open: protocol.CommandTypes.Open; + const Quickinfo: protocol.CommandTypes.Quickinfo; + const QuickinfoFull: protocol.CommandTypes.QuickinfoFull; + const References: protocol.CommandTypes.References; + const ReferencesFull: protocol.CommandTypes.ReferencesFull; + const Reload: protocol.CommandTypes.Reload; + const Rename: protocol.CommandTypes.Rename; + const RenameInfoFull: protocol.CommandTypes.RenameInfoFull; + const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull; + const Saveto: protocol.CommandTypes.Saveto; + const SignatureHelp: protocol.CommandTypes.SignatureHelp; + const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull; + const TypeDefinition: protocol.CommandTypes.TypeDefinition; + const ProjectInfo: protocol.CommandTypes.ProjectInfo; + const ReloadProjects: protocol.CommandTypes.ReloadProjects; + const Unknown: protocol.CommandTypes.Unknown; + const OpenExternalProject: protocol.CommandTypes.OpenExternalProject; + const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects; + const CloseExternalProject: protocol.CommandTypes.CloseExternalProject; + const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList; + const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles; + const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull; + const Cleanup: protocol.CommandTypes.Cleanup; + const OutliningSpans: protocol.CommandTypes.OutliningSpans; + const TodoComments: protocol.CommandTypes.TodoComments; + const Indentation: protocol.CommandTypes.Indentation; + const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate; + const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull; + const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan; + const BreakpointStatement: protocol.CommandTypes.BreakpointStatement; + const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; + const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; + const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull; + const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; } - interface ServerHost extends ts.System { - setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout(timeoutId: any): void; - } - class Session { + function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + class Session implements EventSender { private host; + protected readonly typingsInstaller: ITypingsInstaller; private byteLength; private hrtime; - private logger; + protected logger: Logger; + protected readonly canUseEvents: boolean; + private readonly gcTimer; protected projectService: ProjectService; private errorTimer; private immediateId; private changeSeq; - constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger); - private handleEvent(event); + private eventHander; + constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean, eventHandler?: ProjectServiceEventHandler); + private defaultEventHandler(event); logError(err: Error, cmd: string): void; - private sendLineToClient(line); send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; event(info: any, eventName: string): void; - private response(info, cmdName, reqSeq?, errorMsg?); - output(body: any, commandName: string, requestSequence?: number, errorMessage?: string): void; + output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); - private reloadProjects(); private updateProjectStructure(seq, matchSeq, ms?); private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?); - private getDefinition(line, offset, fileName); - private getTypeDefinition(line, offset, fileName); - private getImplementation(line, offset, fileName); - private getOccurrences(line, offset, fileName); - private getDiagnosticsWorker(args, selector); + private cleanProjects(caption, projects); + private cleanup(); + private getEncodedSemanticClassifications(args); + private getProject(projectFileName); + private getCompilerOptionsDiagnostics(args); + private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); + private getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition); + private getDefinition(args, simplifiedResult); + private getTypeDefinition(args); + private getImplementation(args, simplifiedResult); + private getOccurrences(args); private getSyntacticDiagnosticsSync(args); private getSemanticDiagnosticsSync(args); - private getDocumentHighlights(line, offset, fileName, filesToSearch); - private getProjectInfo(fileName, needFileNameList); - private getRenameLocations(line, offset, fileName, findInComments, findInStrings); - private getReferences(line, offset, fileName); + private getDocumentHighlights(args, simplifiedResult); + private setCompilerOptionsForInferredProjects(args); + private getProjectInfo(args); + private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList); + private getRenameInfo(args); + private getProjects(args); + private getRenameLocations(args, simplifiedResult); + private getReferences(args, simplifiedResult); private openClientFile(fileName, fileContent?, scriptKind?); - private getQuickInfo(line, offset, fileName); - private getFormattingEditsForRange(line, offset, endLine, endOffset, fileName); - private getFormattingEditsAfterKeystroke(line, offset, key, fileName); - private getCompletions(line, offset, prefix, fileName); - private getCompletionEntryDetails(line, offset, entryNames, fileName); - private getSignatureHelpItems(line, offset, fileName); + private getPosition(args, scriptInfo); + private getFileAndProject(args, errorOnMissingProject?); + private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?); + private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject); + private getOutliningSpans(args); + private getTodoComments(args); + private getDocCommentTemplate(args); + private getIndentation(args); + private getBreakpointStatement(args); + private getNameOrDottedNameSpan(args); + private isValidBraceCompletion(args); + private getQuickInfoWorker(args, simplifiedResult); + private getFormattingEditsForRange(args); + private getFormattingEditsForRangeFull(args); + private getFormattingEditsForDocumentFull(args); + private getFormattingEditsAfterKeystrokeFull(args); + private getFormattingEditsAfterKeystroke(args); + private getCompletions(args, simplifiedResult); + private getCompletionEntryDetails(args); + private getCompileOnSaveAffectedFileList(args); + private emitFile(args); + private getSignatureHelpItems(args, simplifiedResult); private getDiagnostics(delay, fileNames); - private change(line, offset, endLine, endOffset, insertString, fileName); - private reload(fileName, tempFileName, reqSeq?); + private change(args); + private reload(args, reqSeq); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items, lineIndex); - private getNavigationBarItems(fileName); - private getNavigateToItems(searchValue, fileName, maxResultCount?, currentFileOnly?); - private getBraceMatching(line, offset, fileName); + private decorateNavigationBarItems(items, scriptInfo); + private getNavigationBarItems(args, simplifiedResult); + private decorateNavigationTree(tree, scriptInfo); + private decorateSpan(span, scriptInfo); + private getNavigationTree(args, simplifiedResult); + private getNavigateToItems(args, simplifiedResult); + private getSupportedCodeFixes(); + private getCodeFixes(args, simplifiedResult); + private mapCodeAction(codeAction, scriptInfo); + private convertTextChangeToCodeEdit(change, scriptInfo); + private getBraceMatching(args, simplifiedResult); getDiagnosticsForProject(delay: number, fileName: string): void; getCanonicalFileName(fileName: string): string; exit(): void; + private notRequired(); private requiredResponse(response); private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => { @@ -9307,227 +11592,6 @@ declare namespace ts.server { } } declare namespace ts.server { - interface Logger { - close(): void; - isVerbose(): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: string): void; - } - const maxProgramSizeForNonTsFiles: number; - class ScriptInfo { - private host; - fileName: string; - isOpen: boolean; - svc: ScriptVersionCache; - children: ScriptInfo[]; - defaultProject: Project; - fileWatcher: FileWatcher; - formatCodeOptions: FormatCodeOptions; - path: Path; - scriptKind: ScriptKind; - constructor(host: ServerHost, fileName: string, content: string, isOpen?: boolean); - setFormatOptions(formatOptions: protocol.FormatOptions): void; - close(): void; - addChild(childInfo: ScriptInfo): void; - snap(): LineIndexSnapshot; - getText(): string; - getLineInfo(line: number): ILineInfo; - editContent(start: number, end: number, newText: string): void; - getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange; - getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange; - } - class LSHost implements ts.LanguageServiceHost { - host: ServerHost; - project: Project; - ls: ts.LanguageService; - compilationSettings: ts.CompilerOptions; - filenameToScript: ts.FileMap; - roots: ScriptInfo[]; - private resolvedModuleNames; - private resolvedTypeReferenceDirectives; - private moduleResolutionHost; - private getCanonicalFileName; - constructor(host: ServerHost, project: Project); - private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; - getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): ts.IScriptSnapshot; - setCompilationSettings(opt: ts.CompilerOptions): void; - lineAffectsRefs(filename: string, line: number): boolean; - getCompilationSettings(): CompilerOptions; - getScriptFileNames(): string[]; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(filename: string): string; - getCurrentDirectory(): string; - getScriptIsOpen(filename: string): boolean; - removeReferencedFile(info: ScriptInfo): void; - getScriptInfo(filename: string): ScriptInfo; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - saveTo(filename: string, tmpfilename: string): void; - reloadScript(filename: string, tmpfilename: string, cb: () => any): void; - editScript(filename: string, start: number, end: number, newText: string): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile(path: string, encoding?: string): string; - lineToTextSpan(filename: string, line: number): ts.TextSpan; - lineOffsetToPosition(filename: string, line: number, offset: number): number; - positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; - getLineIndex(filename: string): LineIndex; - } - interface ProjectOptions { - files?: string[]; - wildcardDirectories?: ts.MapLike; - 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: Map; - updateGraphSeq: number; - openRefCount: number; - constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); - enableLanguageService(): void; - disableLanguageService(): void; - addOpenRef(): void; - deleteOpenRef(): number; - openReferencedFile(filename: string): ScriptInfo; - getRootFiles(): string[]; - getFileNames(): string[]; - getSourceFile(info: ScriptInfo): SourceFile; - getSourceFileFromName(filename: string, requireOpen?: boolean): SourceFile; - isRoot(info: ScriptInfo): boolean; - removeReferencedFile(info: ScriptInfo): void; - updateFileMap(): void; - finishGraph(): void; - updateGraph(): void; - isConfiguredProject(): string; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - filesToString(): string; - setProjectOptions(projectOptions: ProjectOptions): void; - } - interface ProjectOpenResult { - success?: boolean; - errorMsg?: string; - project?: Project; - } - function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; - type ProjectServiceEvent = { - eventName: "context"; - data: { - project: Project; - fileName: string; - }; - } | { - eventName: "configFileDiag"; - data: { - triggerFile?: string; - configFileName: string; - diagnostics: Diagnostic[]; - }; - }; - interface ProjectServiceEventHandler { - (event: ProjectServiceEvent): void; - } - interface HostConfiguration { - formatCodeOptions: ts.FormatCodeOptions; - hostInfo: string; - } - class ProjectService { - host: ServerHost; - psLogger: Logger; - eventHandler: ProjectServiceEventHandler; - filenameToScriptInfo: Map; - openFileRoots: ScriptInfo[]; - inferredProjects: Project[]; - configuredProjects: Project[]; - openFilesReferenced: ScriptInfo[]; - openFileRootsConfigured: ScriptInfo[]; - directoryWatchersForTsconfig: Map; - directoryWatchersRefCount: Map; - hostConfiguration: HostConfiguration; - timerForDetectingProjectFileListChanges: Map; - constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler); - addDefaultHostConfiguration(): void; - getFormatCodeOptions(file?: string): FormatCodeOptions; - watchedFileChanged(fileName: string): void; - directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void; - startTimerForDetectingProjectFileListChanges(project: Project): void; - handleProjectFileListChanges(project: Project): void; - reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string): void; - directoryWatchedForTsconfigChanged(fileName: string): void; - getCanonicalFileName(fileName: string): string; - watchedProjectConfigFileChanged(project: Project): void; - log(msg: string, type?: string): void; - setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments): void; - closeLog(): void; - createInferredProject(root: ScriptInfo): Project; - fileDeletedInFilesystem(info: ScriptInfo): void; - updateConfiguredProjectList(): void; - removeProject(project: Project): void; - setConfiguredProjectRoot(info: ScriptInfo): boolean; - addOpenFile(info: ScriptInfo): void; - closeOpenFile(info: ScriptInfo): void; - findReferencingProjects(info: ScriptInfo, excludedProject?: Project): Project[]; - reloadProjects(): void; - updateProjectStructure(): void; - getScriptInfo(filename: string): ScriptInfo; - openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; - findConfigFile(searchPath: string): string; - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - openOrUpdateConfiguredProjectForFile(fileName: string): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - closeClientFile(filename: string): void; - getProjectForFile(filename: string): Project; - printProjectsForFile(filename: string): void; - printProjects(): void; - configProjectIsActive(fileName: string): boolean; - findConfiguredProjectByConfigFile(configFileName: string): Project; - configFileToProjectOptions(configFilename: string): { - projectOptions?: ProjectOptions; - errors: Diagnostic[]; - }; - private exceedTotalNonTsFileSizeLimit(fileNames); - openConfigFile(configFilename: string, clientFileName?: string): { - project?: Project; - errors: Diagnostic[]; - }; - updateConfiguredProject(project: Project): Diagnostic[]; - createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; - } - class CompilerService { - project: Project; - host: LSHost; - languageService: ts.LanguageService; - classifier: ts.Classifier; - settings: ts.CompilerOptions; - documentRegistry: DocumentRegistry; - constructor(project: Project, opt?: ts.CompilerOptions); - setCompilerOptions(opt: ts.CompilerOptions): void; - isExternalModule(filename: string): boolean; - static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions; - } interface LineCollection { charCount(): number; lineCount(): number; @@ -9566,23 +11630,25 @@ declare namespace ts.server { changes: TextChange[]; versions: LineIndexSnapshot[]; minVersion: number; - private currentVersion; private host; + private currentVersion; static changeNumberThreshold: number; static changeLengthThreshold: number; static maxVersions: number; + private versionToIndex(version); + private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; latest(): LineIndexSnapshot; latestVersion(): number; - reloadFromFile(filename: string, cb?: () => any): void; + reloadFromFile(filename: string): void; reload(script: string): void; getSnapshot(): LineIndexSnapshot; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; static fromString(host: ServerHost, script: string): ScriptVersionCache; } class LineIndexSnapshot implements ts.IScriptSnapshot { - version: number; - cache: ScriptVersionCache; + readonly version: number; + readonly cache: ScriptVersionCache; index: LineIndex; changesSincePreviousVersion: TextChange[]; constructor(version: number, cache: ScriptVersionCache); @@ -9643,10 +11709,7 @@ declare namespace ts.server { } class LineLeaf implements LineCollection { text: string; - udata: any; constructor(text: string); - setUdata(data: any): void; - getUdata(): any; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; charCount(): number; @@ -9680,6 +11743,7 @@ declare namespace ts { getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; + getTypeRootsVersion?(): number; readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; readFile(path: string, encoding?: string): string; fileExists(path: string): boolean; @@ -9708,11 +11772,11 @@ declare namespace ts { unregisterShim(shim: Shim): void; } interface Shim { - dispose(dummy: any): void; + dispose(_dummy: any): void; } interface LanguageServiceShim extends Shim { languageService: LanguageService; - dispose(dummy: any): void; + dispose(_dummy: any): void; refresh(throwOnError: boolean): void; cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): string; @@ -9739,6 +11803,7 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; getNavigationBarItems(fileName: string): string; + getNavigationTree(fileName: string): string; getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; @@ -9767,7 +11832,7 @@ declare namespace ts { private files; private loggingEnabled; private tracingEnabled; - resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[]; + resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[]; resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; directoryExists: (directoryName: string) => boolean; constructor(shimHost: LanguageServiceShimHost); @@ -9775,6 +11840,7 @@ declare namespace ts { trace(s: string): void; error(s: string): void; getProjectVersion(): string; + getTypeRootsVersion(): number; useCaseSensitiveFileNames(): boolean; getCompilationSettings(): CompilerOptions; getScriptFileNames(): string[]; @@ -9824,4 +11890,4 @@ declare namespace ts { declare namespace TypeScript.Services { const TypeScriptServicesFactory: typeof ts.TypeScriptServicesFactory; } -declare const toolsVersion = "2.1"; +declare const toolsVersion = "2.2"; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index a8fa909efcc..842c5458a89 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -26,12 +26,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; @@ -44,41 +45,47 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); })(ts || (ts = {})); var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -129,8 +136,12 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + ts.version = "2.2.0"; +})(ts || (ts = {})); (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -150,13 +161,21 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, - clear: clear + getKeys: getKeys, + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -197,6 +216,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; function every(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -328,13 +354,32 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; function flatten(array) { var result; if (array) { @@ -435,10 +480,27 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } @@ -447,8 +509,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -461,6 +523,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; function compact(array) { var result; if (array) { @@ -479,26 +576,62 @@ var ts; return result || array; } ts.compact = compact; + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1: break inner; + case 0: continue outer; + case 1: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) + .map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -515,6 +648,12 @@ var ts; : undefined; } ts.firstOrUndefined = firstOrUndefined; + function lastOrUndefined(array) { + return array && array.length > 0 + ? array[array.length - 1] + : undefined; + } + ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -527,22 +666,28 @@ var ts; : array; } ts.singleOrMany = singleOrMany; - function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; } - ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { - var low = 0; + ts.replaceElement = replaceElement; + function binarySearch(array, value, comparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -641,6 +786,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -664,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -695,8 +840,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -765,6 +910,12 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function noop() { } + ts.noop = noop; + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -776,9 +927,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -803,11 +1004,11 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -830,6 +1031,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -870,7 +1082,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1012,10 +1224,53 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1187,6 +1442,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -1214,68 +1473,83 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -1285,7 +1559,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -1300,7 +1574,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -1342,25 +1616,30 @@ var ts; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } 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; - } + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); } - basePaths.push(includeBasePath); + }; + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -1385,15 +1664,34 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; - function isSupportedSourceFileName(fileName, compilerOptions) { + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -1452,10 +1750,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -1465,10 +1759,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -1480,7 +1774,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1786,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1806,17 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; + return false; } - ts.getEnvironmentVariable = getEnvironmentVariable; + ts.orderedRemoveItem = orderedRemoveItem; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1847,94 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,9 +2128,15 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -1855,6 +2229,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -1864,7 +2239,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -1872,7 +2247,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -1886,6 +2261,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1961,7 +2339,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -1972,7 +2352,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { return ChakraHost.readFile(path); }, writeFile: function (path, data, writeByteOrderMark) { @@ -1988,28 +2368,52 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2055,7 +2459,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -2165,7 +2569,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -2228,6 +2631,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -2271,6 +2675,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -2281,16 +2686,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -2330,11 +2736,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2368,8 +2774,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2381,7 +2785,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -2403,9 +2807,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -2452,6 +2854,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2475,6 +2884,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -2495,7 +2905,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -2506,6 +2916,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -2576,7 +2991,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -2605,6 +3023,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2617,7 +3036,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -2688,7 +3107,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -2725,9 +3144,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2736,7 +3162,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -2752,6 +3179,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2769,6 +3197,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -2779,141 +3208,157 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { - return token >= 69; + return token >= 70; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115, - "any": 117, - "as": 116, - "boolean": 120, - "break": 70, - "case": 71, - "catch": 72, - "class": 73, - "continue": 75, - "const": 74, - "constructor": 121, - "debugger": 76, - "declare": 122, - "default": 77, - "delete": 78, - "do": 79, - "else": 80, - "enum": 81, - "export": 82, - "extends": 83, - "false": 84, - "finally": 85, - "for": 86, - "from": 136, - "function": 87, - "get": 123, - "if": 88, - "implements": 106, - "import": 89, - "in": 90, - "instanceof": 91, - "interface": 107, - "is": 124, - "let": 108, - "module": 125, - "namespace": 126, - "never": 127, - "new": 92, - "null": 93, - "number": 130, - "package": 109, - "private": 110, - "protected": 111, - "public": 112, - "readonly": 128, - "require": 129, - "global": 137, - "return": 94, - "set": 131, - "static": 113, - "string": 132, - "super": 95, - "switch": 96, - "symbol": 133, - "this": 97, - "throw": 98, - "true": 99, - "try": 100, - "type": 134, - "typeof": 101, - "undefined": 135, - "var": 102, - "void": 103, - "while": 104, - "with": 105, - "yield": 114, - "async": 118, - "await": 119, - "of": 138, - "{": 15, - "}": 16, - "(": 17, - ")": 18, - "[": 19, - "]": 20, - ".": 21, - "...": 22, - ";": 23, - ",": 24, - "<": 25, - ">": 27, - "<=": 28, - ">=": 29, - "==": 30, - "!=": 31, - "===": 32, - "!==": 33, - "=>": 34, - "+": 35, - "-": 36, - "**": 38, - "*": 37, - "/": 39, - "%": 40, - "++": 41, - "--": 42, - "<<": 43, - ">": 44, - ">>>": 45, - "&": 46, - "|": 47, - "^": 48, - "!": 49, - "~": 50, - "&&": 51, - "||": 52, - "?": 53, - ":": 54, - "=": 56, - "+=": 57, - "-=": 58, - "*=": 59, - "**=": 60, - "/=": 61, - "%=": 62, - "<<=": 63, - ">>=": 64, - ">>>=": 65, - "&=": 66, - "|=": 67, - "^=": 68, - "@": 55 + "abstract": 116, + "any": 118, + "as": 117, + "boolean": 121, + "break": 71, + "case": 72, + "catch": 73, + "class": 74, + "continue": 76, + "const": 75, + "constructor": 122, + "debugger": 77, + "declare": 123, + "default": 78, + "delete": 79, + "do": 80, + "else": 81, + "enum": 82, + "export": 83, + "extends": 84, + "false": 85, + "finally": 86, + "for": 87, + "from": 138, + "function": 88, + "get": 124, + "if": 89, + "implements": 107, + "import": 90, + "in": 91, + "instanceof": 92, + "interface": 108, + "is": 125, + "keyof": 126, + "let": 109, + "module": 127, + "namespace": 128, + "never": 129, + "new": 93, + "null": 94, + "number": 132, + "package": 110, + "private": 111, + "protected": 112, + "public": 113, + "readonly": 130, + "require": 131, + "global": 139, + "return": 95, + "set": 133, + "static": 114, + "string": 134, + "super": 96, + "switch": 97, + "symbol": 135, + "this": 98, + "throw": 99, + "true": 100, + "try": 101, + "type": 136, + "typeof": 102, + "undefined": 137, + "var": 103, + "void": 104, + "while": 105, + "with": 106, + "yield": 115, + "async": 119, + "await": 120, + "of": 140, + "{": 16, + "}": 17, + "(": 18, + ")": 19, + "[": 20, + "]": 21, + ".": 22, + "...": 23, + ";": 24, + ",": 25, + "<": 26, + ">": 28, + "<=": 29, + ">=": 30, + "==": 31, + "!=": 32, + "===": 33, + "!==": 34, + "=>": 35, + "+": 36, + "-": 37, + "**": 39, + "*": 38, + "/": 40, + "%": 41, + "++": 42, + "--": 43, + "<<": 44, + ">": 45, + ">>>": 46, + "&": 47, + "|": 48, + "^": 49, + "!": 50, + "~": 51, + "&&": 52, + "||": 53, + "?": 54, + ":": 55, + "=": 57, + "+=": 58, + "-=": 59, + "*=": 60, + "**=": 61, + "/=": 62, + "%=": 63, + "<<=": 64, + ">>=": 65, + ">>>=": 66, + "&=": 67, + "|=": 68, + "^=": 69, + "@": 56, }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -3310,7 +3755,7 @@ var ts; return iterateCommentRanges(true, text, pos, true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -3376,8 +3821,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 || token > 105; }, - isReservedWord: function () { return token >= 70 && token <= 105; }, + isIdentifier: function () { return token === 70 || token > 106; }, + isReservedWord: function () { return token >= 71 && token <= 106; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -3396,7 +3841,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -3513,20 +3958,20 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } var currChar = text.charCodeAt(pos); if (currChar === 96) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 : 13; + resultingToken = startedWithBacktick ? 13 : 14; break; } if (currChar === 92) { @@ -3688,10 +4133,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69; + return token = 70; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -3763,12 +4208,12 @@ var ts; case 33: if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 33; + return pos += 3, token = 34; } - return pos += 2, token = 31; + return pos += 2, token = 32; } pos++; - return token = 49; + return token = 50; case 34: case 39: tokenValue = scanString(); @@ -3777,51 +4222,39 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 62; + return pos += 2, token = 63; } pos++; - return token = 40; + return token = 41; case 38: if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 51; + return pos += 2, token = 52; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + return pos += 2, token = 67; } pos++; - return token = 46; + return token = 47; case 40: pos++; - return token = 17; + return token = 18; case 41: pos++; - return token = 18; + return token = 19; case 42: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; + return pos += 2, token = 60; } if (text.charCodeAt(pos + 1) === 42) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 60; + return pos += 3, token = 61; } - return pos += 2, token = 38; + return pos += 2, token = 39; } pos++; - return token = 37; + return token = 38; case 43: if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 41; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 57; - } - pos++; - return token = 35; - case 44: - pos++; - return token = 24; - case 45: - if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; } if (text.charCodeAt(pos + 1) === 61) { @@ -3829,16 +4262,28 @@ var ts; } pos++; return token = 36; + case 44: + pos++; + return token = 25; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 43; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 59; + } + pos++; + return token = 37; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 22; + return pos += 3, token = 23; } pos++; - return token = 21; + return token = 22; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -3882,10 +4327,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; + return pos += 2, token = 62; } pos++; - return token = 39; + return token = 40; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -3934,10 +4379,10 @@ var ts; return token = 8; case 58: pos++; - return token = 54; + return token = 55; case 59: pos++; - return token = 23; + return token = 24; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3950,20 +4395,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 63; + return pos += 3, token = 64; } - return pos += 2, token = 43; + return pos += 2, token = 44; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 28; + return pos += 2, token = 29; } if (languageVariant === 1 && text.charCodeAt(pos + 1) === 47 && text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 26; + return pos += 2, token = 27; } pos++; - return token = 25; + return token = 26; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3976,15 +4421,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 32; + return pos += 3, token = 33; } - return pos += 2, token = 30; + return pos += 2, token = 31; } if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 34; + return pos += 2, token = 35; } pos++; - return token = 56; + return token = 57; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3996,43 +4441,43 @@ var ts; } } pos++; - return token = 27; + return token = 28; case 63: pos++; - return token = 53; + return token = 54; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 94: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 69; + } + pos++; + return token = 49; + case 123: + pos++; + return token = 16; + case 124: + if (text.charCodeAt(pos + 1) === 124) { + return pos += 2, token = 53; + } if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } pos++; return token = 48; - case 123: - pos++; - return token = 15; - case 124: - if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 52; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 67; - } - pos++; - return token = 47; case 125: pos++; - return token = 16; + return token = 17; case 126: pos++; - return token = 50; + return token = 51; case 64: pos++; - return token = 55; + return token = 56; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -4070,29 +4515,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27) { + if (token === 28) { if (text.charCodeAt(pos) === 62) { if (text.charCodeAt(pos + 1) === 62) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + return pos += 3, token = 66; } - return pos += 2, token = 45; + return pos += 2, token = 46; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + return pos += 2, token = 65; } pos++; - return token = 44; + return token = 45; } if (text.charCodeAt(pos) === 61) { pos++; - return token = 29; + return token = 30; } } return token; } function reScanSlashToken() { - if (token === 39 || token === 61) { + if (token === 40 || token === 62) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -4131,12 +4576,12 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10; + token = 11; } return token; } function reScanTemplateToken() { - ts.Debug.assert(token === 16, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -4153,14 +4598,14 @@ var ts; if (char === 60) { if (text.charCodeAt(pos + 1) === 47) { pos += 2; - return token = 26; + return token = 27; } pos++; - return token = 25; + return token = 26; } if (char === 123) { pos++; - return token = 15; + return token = 16; } while (pos < end) { pos++; @@ -4169,7 +4614,7 @@ var ts; break; } } - return token = 244; + return token = 10; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -4216,39 +4661,42 @@ var ts; return token = 5; case 64: pos++; - return token = 55; + return token = 56; case 10: case 13: pos++; return token = 4; case 42: pos++; - return token = 37; + return token = 38; case 123: pos++; - return token = 15; + return token = 16; case 125: pos++; - return token = 16; + return token = 17; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 61: pos++; - return token = 56; + return token = 57; case 44: pos++; - return token = 24; + return token = 25; + case 46: + pos++; + return token = 22; } - if (isIdentifierStart(ch, 2)) { + if (isIdentifierStart(ch, 5)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { pos++; } - return token = 69; + return token = 70; } else { return pos += 1, token = 0; @@ -4334,26 +4782,28 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -4368,7 +4818,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -4378,15 +4828,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -4395,27 +4845,32 @@ var ts; "react": 2 }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -4426,11 +4881,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -4439,12 +4894,12 @@ var ts; "lf": 1 }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -4453,7 +4908,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -4462,59 +4917,59 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -4537,30 +4992,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -4571,7 +5026,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -4586,22 +5041,25 @@ var ts; "es3": 0, "es5": 1, "es6": 2, - "es2015": 2 + "es2015": 2, + "es2016": 3, + "es2017": 4, + "esnext": 5, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -4618,10 +5076,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -4743,8 +5201,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4761,12 +5220,21 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -4789,9 +5257,21 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -4809,22 +5289,12 @@ var ts; } ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -4886,7 +5356,11 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -4962,10 +5436,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5059,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5069,14 +5545,15 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -5099,17 +5576,19 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); @@ -5142,6 +5621,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -5169,7 +5651,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -5178,33 +5660,49 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -5266,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5278,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -5334,14 +5832,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_6 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_6)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_6); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_6) ? 1 : 0; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -5362,6 +5859,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 : 0 + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 }; + } + return undefined; + } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); @@ -5395,6 +5905,967 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + JsTyping.nodeCoreModuleList = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console" + ]; + var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { + var inferredTypings = ts.createMap(); + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + if (unresolvedImports) { + for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { + var moduleId = unresolvedImports_1[_a]; + var typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } + } + } + for (var name_6 in packageNameToTypingLocation) { + if (name_6 in inferredTypings && !inferredTypings[name_6]) { + inferredTypings[name_6] = packageNameToTypingLocation[name_6]; + } + } + for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { + var excludeTypingName = exclude_1[_b]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + 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; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LogLevel; + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(LogLevel = server.LogLevel || (server.LogLevel = {})); + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(true), + compilerOptions: project.getCompilerOptions(), + typeAcquisition: typeAcquisition, + unresolvedImports: unresolvedImports, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + function toSortedReadonlyArray(arr) { + arr.sort(); + return arr; + } + server.toSortedReadonlyArray = toSortedReadonlyArray; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2: + case 0: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === 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, typeRoots); + } + } + else { + 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, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, false, state); + return path_1 && { path: path_1, extension: tsExtension }; + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0) || tryResolve(1); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; + } + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case 2: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocations.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocations.push(packageJsonPath); + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(2, moduleName, directory, failedLookupLocations, state, true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== 1) { + return loadModuleFromNodeModulesFolder(2, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0) || tryResolve(1); + return createResolvedModuleWithFailedLookupLocations(resolved, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === 0) { + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5423,13 +6894,14 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, - increaseIndent: function () { }, - decreaseIndent: function () { }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, clear: function () { return str_1 = ""; }, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; } return stringWriters.pop(); @@ -5444,22 +6916,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(array1, array2, equaler) { - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } @@ -5483,7 +6939,9 @@ var ts; } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function typeDirectiveIsEqualTo(oldResolution, newResolution) { @@ -5509,21 +6967,21 @@ var ts; ts.hasChangesInResolutions = hasChangesInResolutions; function containsParseError(node) { aggregateChildData(node); - return (node.flags & 2097152) !== 0; + return (node.flags & 131072) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 4194304)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 524288) !== 0) || + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.flags |= 2097152; + node.flags |= 131072; } - node.flags |= 4194304; + node.flags |= 262144; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 256) { + while (node && node.kind !== 261) { node = node.parent; } return node; @@ -5531,11 +6989,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: return true; } return false; @@ -5590,28 +7048,28 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function getTokenPosOfNode(node, sourceFile, includeJsDocComment) { + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; } if (isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); + if (node.kind === 292 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 262 && node.kind <= 288; } ts.isJSDocNode = isJSDocNode; function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; + return node.kind >= 278 && node.kind <= 291; } ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -5656,13 +7114,13 @@ var ts; switch (node.kind) { case 9: return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11: - return getQuotedEscapedLiteralText("`", node.text, "`"); case 12: - return getQuotedEscapedLiteralText("`", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "`"); case 13: - return getQuotedEscapedLiteralText("}", node.text, "${"); + return getQuotedEscapedLiteralText("`", node.text, "${"); case 14: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 15: return getQuotedEscapedLiteralText("}", node.text, "`"); case 8: return node.text; @@ -5700,11 +7158,16 @@ var ts; ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 223 && node.parent.kind === 256; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 225 && + return node && node.kind === 230 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; @@ -5713,11 +7176,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node.kind === 225 && (!node.body); + return node.kind === 230 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 256 || - node.kind === 225 || + return node.kind === 261 || + node.kind === 230 || isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -5730,32 +7193,36 @@ var ts; return false; } switch (node.parent.kind) { - case 256: + case 261: return ts.isExternalModule(node.parent); - case 226: + case 231: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { + case 261: + case 232: case 256: - case 227: - case 252: - case 225: - case 206: - case 207: - case 208: - case 148: - case 147: - case 149: + case 230: + case 211: + case 212: + case 213: case 150: - case 220: - case 179: - case 180: + case 149: + case 151: + case 152: + case 225: + case 184: + case 185: return true; - case 199: + case 204: return parentNode && !isFunctionLike(parentNode); } return false; @@ -5771,23 +7238,46 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 218 && - declaration.parent && - declaration.parent.kind === 252; - } - ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 70: + return name.text; + case 9: + case 8: + return name.text; + case 142: + if (isStringOrNumericLiteral(name.expression)) { + return name.expression.text; + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 70: + return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name); + case 141: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 177: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; function createDiagnosticForNode(node, message, arg0, arg1, arg2) { var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { var span = getErrorSpanForNode(sourceFile, node); return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } - ts.createDiagnosticForNode = createDiagnosticForNode; + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -5810,7 +7300,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 199) { + if (node.body && node.body.kind === 204) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -5822,29 +7312,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 256: + case 261: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 218: - case 169: - case 221: - case 192: - case 222: - case 225: - case 224: - case 255: - case 220: - case 179: - case 147: - case 149: - case 150: case 223: + case 174: + case 226: + case 197: + case 227: + case 230: + case 229: + case 260: + case 225: + case 184: + case 149: + case 151: + case 152: + case 228: errorNode = node.name; break; - case 180: + case 185: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -5865,7 +7355,7 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 224 && isConst(node); + return node.kind === 229 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -5877,12 +7367,13 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { - return n.kind === 174 && n.expression.kind === 95; + function isSuperCall(n) { + return n.kind === 179 && n.expression.kind === 96; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { - return node.kind === 202 && node.expression.kind === 9; + return node.kind === 207 + && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -5893,92 +7384,87 @@ var ts; return ts.getLeadingCommentRanges(text, node.pos); } ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJsDocComments(node, sourceFileOfNode) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - ts.getJsDocComments = getJsDocComments; - function getJsDocCommentsFromText(node, text) { - var commentRanges = (node.kind === 142 || - node.kind === 141 || - node.kind === 179 || - node.kind === 180) ? + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 144 || + node.kind === 143 || + node.kind === 184 || + node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { + return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 && text.charCodeAt(comment.pos + 2) === 42 && text.charCodeAt(comment.pos + 3) !== 47; - } + }); } - ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (154 <= node.kind && node.kind <= 166) { + if (156 <= node.kind && node.kind <= 171) { return true; } switch (node.kind) { - case 117: - case 130: + case 118: case 132: - case 120: - case 133: + case 134: + case 121: case 135: - case 127: + case 137: + case 129: return true; - case 103: - return node.parent.kind !== 183; - case 194: + case 104: + return node.parent.kind !== 188; + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 69: - if (node.parent.kind === 139 && node.parent.right === node) { + case 70: + if (node.parent.kind === 141 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 172 && node.parent.name === node) { + else if (node.parent.kind === 177 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 139 || node.kind === 172, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 139: - case 172: - case 97: + ts.Debug.assert(node.kind === 70 || node.kind === 141 || node.kind === 177, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 141: + case 177: + case 98: var parent_1 = node.parent; - if (parent_1.kind === 158) { + if (parent_1.kind === 160) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (156 <= parent_1.kind && parent_1.kind <= 171) { return true; } switch (parent_1.kind) { - case 194: + case 199: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 141: + case 143: return node === parent_1.constraint; - case 145: - case 144: - case 142: - case 218: - return node === parent_1.type; - case 220: - case 179: - case 180: - case 148: case 147: case 146: - case 149: - case 150: + case 144: + case 223: return node === parent_1.type; + case 225: + case 184: + case 185: + case 150: + case 149: + case 148: case 151: case 152: + return node === parent_1.type; case 153: + case 154: + case 155: return node === parent_1.type; - case 177: + case 182: return node === parent_1.type; - case 174: - case 175: + case 179: + case 180: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 176: + case 181: return false; } } @@ -5989,23 +7475,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 211: + case 216: return visitor(node); - case 227: - case 199: - case 203: + case 232: case 204: - case 205: - case 206: - case 207: case 208: + case 209: + case 210: + case 211: case 212: case 213: - case 249: - case 250: - case 214: - case 216: - case 252: + case 217: + case 218: + case 253: + case 254: + case 219: + case 221: + case 256: return ts.forEachChild(node, traverse); } } @@ -6015,23 +7501,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 190: + case 195: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 224: - case 222: - case 225: - case 223: - case 221: - case 192: + case 229: + case 227: + case 230: + case 228: + case 226: + case 197: return; default: if (isFunctionLike(node)) { var name_7 = node.name; - if (name_7 && name_7.kind === 140) { + if (name_7 && name_7.kind === 142) { traverse(name_7.expression); return; } @@ -6043,17 +7529,29 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { - case 169: - case 255: - case 142: - case 253: - case 145: + case 174: + case 260: case 144: - case 254: - case 218: + case 257: + case 147: + case 146: + case 258: + case 223: return true; } } @@ -6061,11 +7559,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 149 || node.kind === 150); + return node && (node.kind === 151 || node.kind === 152); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 221 || node.kind === 192); + return node && (node.kind === 226 || node.kind === 197); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6074,19 +7572,19 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 148: - case 179: - case 220: - case 180: - case 147: - case 146: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return true; } return false; @@ -6094,13 +7592,13 @@ var ts; ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 179: + case 151: + case 152: + case 225: + case 184: return true; } return false; @@ -6108,26 +7606,32 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: + case 211: + case 212: + case 213: + case 209: + case 210: return true; - case 214: + case 219: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 199 && isFunctionLike(node.parent); + return node && node.kind === 204 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 147 && node.parent.kind === 171; + return node && node.kind === 149 && node.parent.kind === 176; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 149 && + (node.parent.kind === 176 || + node.parent.kind === 197); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6161,39 +7665,39 @@ var ts; return undefined; } switch (node.kind) { - case 140: + case 142: if (isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 180: + case 185: if (!includeArrowFunctions) { continue; } - case 220: - case 179: case 225: - case 145: - case 144: + case 184: + case 230: case 147: case 146: - case 148: case 149: + case 148: case 150: case 151: case 152: case 153: - case 224: - case 256: + case 154: + case 155: + case 229: + case 261: return node; } } @@ -6206,25 +7710,25 @@ var ts; return node; } switch (node.kind) { - case 140: + case 142: node = node.parent; break; - case 220: - case 179: - case 180: + case 225: + case 184: + case 185: if (!stopOnFunctions) { continue; } - case 145: - case 144: case 147: case 146: - case 148: case 149: + case 148: case 150: + case 151: + case 152: return node; - case 143: - if (node.parent.kind === 142 && isClassElement(node.parent.parent)) { + case 145: + if (node.parent.kind === 144 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { @@ -6236,14 +7740,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 179 || func.kind === 180) { + if (func.kind === 184 || func.kind === 185) { var prev = func; var parent_2 = func.parent; - while (parent_2.kind === 178) { + while (parent_2.kind === 183) { prev = parent_2; parent_2 = parent_2.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { + if (parent_2.kind === 179 && parent_2.expression === prev) { return parent_2; } } @@ -6251,32 +7755,32 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 172 || kind === 173) - && node.expression.kind === 95; + return (kind === 177 || kind === 178) + && node.expression.kind === 96; } ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { - if (node) { - switch (node.kind) { - case 155: - return node.typeName; - case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); - return node.expression; - case 69: - case 139: - return node; - } + switch (node.kind) { + case 157: + case 272: + return node.typeName; + case 199: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 70: + case 141: + return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function isCallLikeExpression(node) { switch (node.kind) { - case 174: - case 175: - case 176: - case 143: + case 179: + case 180: + case 181: + case 145: return true; default: return false; @@ -6284,7 +7788,7 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { - if (node.kind === 176) { + if (node.kind === 181) { return node.tag; } return node.expression; @@ -6292,21 +7796,21 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 221: + case 226: return true; - case 145: - return node.parent.kind === 221; - case 149: - case 150: case 147: + return node.parent.kind === 226; + case 151: + case 152: + case 149: return node.body !== undefined - && node.parent.kind === 221; - case 142: + && node.parent.kind === 226; + case 144: return node.parent.body !== undefined - && (node.parent.kind === 148 - || node.parent.kind === 147 - || node.parent.kind === 150) - && node.parent.parent.kind === 221; + && (node.parent.kind === 150 + || node.parent.kind === 149 + || node.parent.kind === 152) + && node.parent.parent.kind === 226; } return false; } @@ -6322,19 +7826,19 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 221: + case 226: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 147: - case 150: + case 149: + case 152: return ts.forEach(node.parameters, nodeIsDecorated); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 243 || - parent.kind === 242 || - parent.kind === 245) { + if (parent.kind === 248 || + parent.kind === 247 || + parent.kind === 249) { return parent.tagName === node; } return false; @@ -6342,97 +7846,98 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 97: - case 95: - case 93: - case 99: - case 84: - case 10: - case 170: - case 171: - case 172: - case 173: - case 174: + case 98: + case 96: + case 94: + case 100: + case 85: + case 11: case 175: case 176: - case 195: case 177: - case 196: case 178: case 179: - case 192: case 180: - case 183: case 181: + case 200: case 182: + case 201: + case 183: + case 184: + case 197: case 185: + case 188: case 186: case 187: - case 188: - case 191: - case 189: - case 11: - case 193: - case 241: - case 242: case 190: - case 184: + case 191: + case 192: + case 193: + case 196: + case 194: + case 12: + case 198: + case 246: + case 247: + case 195: + case 189: return true; - case 139: - while (node.parent.kind === 139) { + case 141: + while (node.parent.kind === 141) { node = node.parent; } - return node.parent.kind === 158 || isJSXTagName(node); - case 69: - if (node.parent.kind === 158 || isJSXTagName(node)) { + return node.parent.kind === 160 || isJSXTagName(node); + case 70: + if (node.parent.kind === 160 || isJSXTagName(node)) { return true; } case 8: case 9: - case 97: + case 98: var parent_3 = node.parent; switch (parent_3.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 255: - case 253: - case 169: + case 147: + case 146: + case 260: + case 257: + case 174: return parent_3.initializer === node; - case 202: - case 203: - case 204: - case 205: - case 211: - case 212: - case 213: - case 249: - case 215: - case 213: - return parent_3.expression === node; - case 206: - var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || - forStatement.condition === node || - forStatement.incrementor === node; case 207: case 208: + case 209: + case 210: + case 216: + case 217: + case 218: + case 253: + case 220: + case 218: + return parent_3.expression === node; + case 211: + var forStatement = parent_3; + return (forStatement.initializer === node && forStatement.initializer.kind !== 224) || + forStatement.condition === node || + forStatement.incrementor === node; + case 212: + case 213: var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224) || forInStatement.expression === node; - case 177: - case 195: + case 182: + case 200: return node === parent_3.expression; - case 197: + case 202: return node === parent_3.expression; - case 140: + case 142: return node === parent_3.expression; - case 143: - case 248: - case 247: + case 145: + case 252: + case 251: + case 259: return true; - case 194: + case 199: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: if (isPartOfExpression(parent_3)) { @@ -6443,10 +7948,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6454,7 +7955,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind === 240; + return node.kind === 234 && node.moduleReference.kind === 245; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6463,7 +7964,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 && node.moduleReference.kind !== 240; + return node.kind === 234 && node.moduleReference.kind !== 245; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -6471,12 +7972,12 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 1048576); + return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression, checkArgumentIsStringLiteral) { - var isRequire = expression.kind === 174 && - expression.expression.kind === 69 && + var isRequire = expression.kind === 179 && + expression.expression.kind === 70 && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9); @@ -6487,9 +7988,9 @@ var ts; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; function isDeclarationOfFunctionExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + if (s.valueDeclaration && s.valueDeclaration.kind === 223) { var declaration = s.valueDeclaration; - return declaration.initializer && declaration.initializer.kind === 179; + return declaration.initializer && declaration.initializer.kind === 184; } return false; } @@ -6498,15 +7999,15 @@ var ts; if (!isInJavaScriptFile(expression)) { return 0; } - if (expression.kind !== 187) { + if (expression.kind !== 192) { return 0; } var expr = expression; - if (expr.operatorToken.kind !== 56 || expr.left.kind !== 172) { + if (expr.operatorToken.kind !== 57 || expr.left.kind !== 177) { return 0; } var lhs = expr.left; - if (lhs.expression.kind === 69) { + if (lhs.expression.kind === 70) { var lhsId = lhs.expression; if (lhsId.text === "exports") { return 1; @@ -6515,12 +8016,12 @@ var ts; return 2; } } - else if (lhs.expression.kind === 97) { + else if (lhs.expression.kind === 98) { return 4; } - else if (lhs.expression.kind === 172) { + else if (lhs.expression.kind === 177) { var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 69) { + if (innerPropertyAccess.expression.kind === 70) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { return 1; @@ -6534,35 +8035,35 @@ var ts; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 230) { + if (node.kind === 235) { return node.moduleSpecifier; } - if (node.kind === 229) { + if (node.kind === 234) { var reference = node.moduleReference; - if (reference.kind === 240) { + if (reference.kind === 245) { return reference.expression; } } - if (node.kind === 236) { + if (node.kind === 241) { return node.moduleSpecifier; } - if (node.kind === 225 && node.name.kind === 9) { + if (node.kind === 230 && node.name.kind === 9) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 230 + return node.kind === 235 && node.importClause && !!node.importClause.name; } @@ -6570,13 +8071,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 142: + case 144: + case 149: + case 148: + case 258: + case 257: case 147: case 146: - case 254: - case 253: - case 145: - case 144: return node.questionToken !== undefined; } } @@ -6584,157 +8085,123 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 269 && + return node.kind === 274 && node.parameters.length > 0 && - node.parameters[0].type.kind === 271; + node.parameters[0].type.kind === 276; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getJSDocTag(node, kind, checkParentVariableStatement) { - if (!node) { - return undefined; - } - var jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { - var tag = jsDocTags_1[_i]; - if (tag.kind === kind) { - return tag; - } - } + function getCommentsFromJSDoc(node) { + return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } - function append(previous, additional) { - if (additional) { - if (!previous) { - previous = []; - } - for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { - var x = additional_1[_i]; - previous.push(x); - } - } - return previous; - } - function getJSDocComments(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); - } - ts.getJSDocComments = getJSDocComments; - function getJSDocTags(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { + ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function getJSDocTags(node, kind) { + var docs = getJSDocs(node); + if (docs) { var result = []; for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { var doc = docs_1[_i]; - if (doc.tags) { - result.push.apply(result, doc.tags); + if (doc.kind === 281) { + if (doc.kind === kind) { + result.push(doc); + } + } + else { + result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; })); } } return result; - }, function (tags) { return tags; }); + } } - function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { - var result = undefined; - if (checkParentVariableStatement) { - var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === 200; + function getFirstJSDocTag(node, kind) { + return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + } + function getJSDocs(node) { + var cache = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + function getJSDocsWorker(node) { + var parent = node.parent; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 205; var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === 200; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + parent.parent.kind === 205; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } - if (node.kind === 225 && - node.parent && node.parent.kind === 225) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); - } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 192 && + parent.operatorToken.kind === 57 && + parent.parent.kind === 207; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + var isModuleDeclaration = node.kind === 230 && + parent && parent.kind === 230; + var isPropertyAssignmentExpression = parent && parent.kind === 257; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } - if (node.kind === 142) { - var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + if (node.kind === 144) { + cache = ts.concatenate(cache, getJSDocParameterTags(node)); } + if (isVariableLike(node) && node.initializer) { + cache = ts.concatenate(cache, node.initializer.jsDoc); + } + cache = ts.concatenate(cache, node.jsDoc); } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, false, getDocs, getTags)); - } - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); - } - else { - return getDocs(node.jsDocComments); - } - } - return result; } - function getJSDocParameterTag(param, checkParentVariableStatement) { + function getJSDocParameterTags(param) { + if (!isParameter(param)) { + return undefined; + } var func = param.parent; - var tags = getJSDocTags(func, checkParentVariableStatement); + var tags = getJSDocTags(func, 281); if (!param.name) { var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275; }); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281; }); if (paramTags && 0 <= i && i < paramTags.length) { return [paramTags[i]]; } } - else if (param.name.kind === 69) { + else if (param.name.kind === 70) { var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); - if (paramTags) { - return paramTags; - } + return ts.filter(tags, function (tag) { return tag.kind === 281 && tag.parameterName.text === name_8; }); } else { return undefined; } } - function getJSDocTypeTag(node) { - return getJSDocTag(node, 277, false); + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 283); + if (!tag && node.kind === 144) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; } - ts.getJSDocTypeTag = getJSDocTypeTag; + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 276, true); + return getFirstJSDocTag(node, 282); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 278, false); + return getFirstJSDocTag(node, 284); } ts.getJSDocTemplateTag = getJSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter) { - if (parameter.name && parameter.name.kind === 69) { - var parameterName = parameter.name.text; - var jsDocTags = getJSDocTags(parameter.parent, true); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { - var tag = jsDocTags_2[_i]; - if (tag.kind === 275) { - var parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } - } - } - return undefined; - } - ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -6744,14 +8211,11 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 1048576)) { - if (node.type && node.type.kind === 270) { + if (node && (node.flags & 65536)) { + if (node.type && node.type.kind === 275 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275; })) { return true; } - var paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 270; - } } return isDeclaredRestParam(node); } @@ -6760,27 +8224,44 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; - function isAssignmentTarget(node) { - while (node.parent.kind === 178) { - node = node.parent; - } + function getAssignmentTargetKind(node) { + var parent = node.parent; while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; - continue; + switch (parent.kind) { + case 192: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 57 ? 1 : 2 : + 0; + case 190: + case 191: + var unaryOperator = parent.operator; + return unaryOperator === 42 || unaryOperator === 43 ? 2 : 0; + case 212: + case 213: + return parent.initializer === node ? 1 : 0; + case 183: + case 175: + case 196: + node = parent; + break; + case 258: + if (parent.name !== node) { + return 0; + } + case 257: + node = parent.parent; + break; + default: + return 0; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; - continue; - } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + parent = node.parent; } } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } ts.isAssignmentTarget = isAssignmentTarget; function isNodeDescendantOf(node, ancestor) { while (node) { @@ -6793,7 +8274,7 @@ var ts; ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (hasModifier(node, 2) || (node.kind === 256 && node.isDeclarationFile)) { + if (hasModifier(node, 2) || (node.kind === 261 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6802,11 +8283,11 @@ var ts; } ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { - if (name.kind !== 69 && name.kind !== 9 && name.kind !== 8) { + if (name.kind !== 70 && name.kind !== 9 && name.kind !== 8) { return false; } var parent = name.parent; - if (parent.kind === 234 || parent.kind === 238) { + if (parent.kind === 239 || parent.kind === 243) { if (parent.propertyName) { return true; } @@ -6819,48 +8300,48 @@ var ts; ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 140 && + node.parent.kind === 142 && isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 145: - case 144: case 147: case 146: case 149: - case 150: - case 255: - case 253: - case 172: + case 148: + case 151: + case 152: + case 260: + case 257: + case 177: return parent.name === node; - case 139: + case 141: if (parent.right === node) { - while (parent.kind === 139) { + while (parent.kind === 141) { parent = parent.parent; } - return parent.kind === 158; + return parent.kind === 160; } return false; - case 169: - case 234: + case 174: + case 239: return parent.propertyName === node; - case 238: + case 243: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 229 || - node.kind === 228 || - node.kind === 231 && !!node.name || - node.kind === 232 || - node.kind === 234 || - node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + return node.kind === 234 || + node.kind === 233 || + node.kind === 236 && !!node.name || + node.kind === 237 || + node.kind === 239 || + node.kind === 243 || + node.kind === 240 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -6868,17 +8349,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 106); + var heritageClause = getHeritageClause(node.heritageClauses, 107); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83); + var heritageClause = getHeritageClause(node.heritageClauses, 84); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -6946,7 +8427,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 <= token && token <= 138; + return 71 <= token && token <= 140; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -6957,8 +8438,10 @@ var ts; return isFunctionLike(node) && hasModifier(node, 256) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; - function isStringOrNumericLiteral(kind) { - return kind === 9 || kind === 8; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { @@ -6966,8 +8449,8 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 140 && - !isStringOrNumericLiteral(name.expression.kind) && + return name.kind === 142 && + !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -6976,10 +8459,10 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { + if (name.kind === 70 || name.kind === 9 || name.kind === 8 || name.kind === 144) { return name.text; } - if (name.kind === 140) { + if (name.kind === 142) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -6997,22 +8480,26 @@ var ts; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function isESSymbolIdentifier(node) { - return node.kind === 69 && node.text === "Symbol"; + return node.kind === 70 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.text === "push" || node.text === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isModifierKind(token) { switch (token) { - case 115: - case 118: - case 74: - case 122: - case 77: - case 82: - case 112: - case 110: - case 111: - case 128: + case 116: + case 119: + case 75: + case 123: + case 78: + case 83: case 113: + case 111: + case 112: + case 130: + case 114: return true; } return false; @@ -7020,11 +8507,11 @@ var ts; ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 142; + return root.kind === 144; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 169) { + while (node.kind === 174) { node = node.parent.parent; } return node; @@ -7032,33 +8519,29 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 148 - || kind === 179 - || kind === 220 - || kind === 180 - || kind === 147 - || kind === 149 - || kind === 150 + return kind === 150 + || kind === 184 || kind === 225 - || kind === 256; + || kind === 185 + || kind === 149 + || kind === 151 + || kind === 152 + || kind === 230 + || kind === 261; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - function getOriginalNode(node) { + function getOriginalNode(node, nodeTest) { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; function isParseTreeNode(node) { @@ -7095,38 +8578,38 @@ var ts; ts.getOriginalNodeId = getOriginalNodeId; function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 175: + case 180: return hasArguments ? 0 : 1; - case 185: - case 182: - case 183: - case 181: - case 184: - case 188: case 190: - return 1; case 187: + case 188: + case 186: + case 189: + case 193: + case 195: + return 1; + case 192: switch (operator) { - case 38: - case 56: + case 39: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 1; } } @@ -7135,15 +8618,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 187) { + if (expression.kind === 192) { return expression.operatorToken.kind; } - else if (expression.kind === 185 || expression.kind === 186) { + else if (expression.kind === 190 || expression.kind === 191) { return expression.operator; } else { @@ -7153,106 +8636,107 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 97: - case 95: - case 69: - case 93: - case 99: - case 84: + case 98: + case 96: + case 70: + case 94: + case 100: + case 85: case 8: case 9: - case 170: - case 171: - case 179: - case 180: - case 192: - case 241: - case 242: - case 10: - case 11: - case 189: - case 178: - case 193: - return 19; - case 176: - case 172: - case 173: - return 18; case 175: - return hasArguments ? 18 : 17; - case 174: - return 17; - case 186: - return 16; - case 185: - case 182: - case 183: - case 181: + case 176: case 184: - return 15; + case 185: + case 197: + case 246: + case 247: + case 11: + case 12: + case 194: + case 183: + case 198: + case 297: + return 19; + case 181: + case 177: + case 178: + return 18; + case 180: + return hasArguments ? 18 : 17; + case 179: + return 17; + case 191: + return 16; + case 190: case 187: + case 188: + case 186: + case 189: + return 15; + case 192: switch (operatorKind) { - case 49: case 50: + case 51: return 15; - case 38: - case 37: case 39: + case 38: case 40: + case 41: return 14; - case 35: case 36: + case 37: return 13; - case 43: case 44: case 45: + case 46: return 12; - case 25: - case 28: - case 27: + case 26: case 29: - case 90: - case 91: - return 11; + case 28: case 30: - case 32: + case 91: + case 92: + return 11; case 31: case 33: + case 32: + case 34: return 10; - case 46: - return 9; - case 48: - return 8; case 47: + return 9; + case 49: + return 8; + case 48: return 7; - case 51: - return 6; case 52: + return 6; + case 53: return 5; - case 56: case 57: case 58: - case 60: case 59: case 61: + case 60: case 62: case 63: case 64: case 65: case 66: - case 68: case 67: + case 69: + case 68: return 3; - case 24: + case 25: return 0; default: return -1; } - case 188: + case 193: return 4; - case 190: + case 195: return 2; - case 191: + case 196: return 1; default: return -1; @@ -7487,48 +8971,46 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - var sourceFiles = host.getSourceFiles(); + var sourceFiles = getAllEmittableSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, isNonDeclarationFile); + var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); }); + } + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles(); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) { + return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); }); + } + ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory; function isNonDeclarationFile(sourceFile) { return !isDeclarationFile(sourceFile); } - function isBundleEmitNonExternalModule(sourceFile) { - return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function isBundleEmitNonExternalModule(sourceFile) { + return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + } + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { @@ -7552,10 +9034,10 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } - function onBundledEmit(host, sourceFiles) { + function onBundledEmit(sourceFiles) { if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -7568,16 +9050,16 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) { onSingleFileEmit(host, sourceFile); } } @@ -7595,18 +9077,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { - var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +9097,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7643,7 +9126,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 148 && nodeIsPresent(member.body)) { + if (member.kind === 150 && nodeIsPresent(member.body)) { return member; } }); @@ -7651,13 +9134,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 70 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 98; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7665,10 +9167,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 149) { + if (accessor.kind === 151) { getAccessor = accessor; } - else if (accessor.kind === 150) { + else if (accessor.kind === 152) { setAccessor = accessor; } else { @@ -7677,7 +9179,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 149 || member.kind === 150) + if ((member.kind === 151 || member.kind === 152) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -7688,10 +9190,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 149 && !getAccessor) { + if (member.kind === 151 && !getAccessor) { getAccessor = member; } - if (member.kind === 150 && !setAccessor) { + if (member.kind === 152 && !setAccessor) { setAccessor = member; } } @@ -7874,7 +9376,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4) { + if (node.flags & 4 || (node.kind === 70 && node.isInJSDocNamespace)) { flags |= 1; } node.modifierFlagsCache = flags | 536870912; @@ -7883,46 +9385,52 @@ var ts; ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { - case 113: return 32; - case 112: return 4; - case 111: return 16; - case 110: return 8; - case 115: return 128; - case 82: return 1; - case 122: return 2; - case 74: return 2048; - case 77: return 512; - case 118: return 256; - case 128: return 64; + case 114: return 32; + case 113: return 4; + case 112: return 16; + case 111: return 8; + case 116: return 128; + case 83: return 1; + case 123: return 2; + case 75: return 2048; + case 78: return 512; + case 119: return 256; + case 130: return 64; } return 0; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 52 - || token === 51 - || token === 49; + return token === 53 + || token === 52 + || token === 50; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 56 && token <= 68; + return token >= 57 && token <= 69; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 194 && - node.parent.token === 83 && + if (node.kind === 199 && + node.parent.token === 84 && isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 57 + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === 56) { - var kind = node.left.kind; - return kind === 171 - || kind === 170; - } + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 176 + || kind === 175; } return false; } @@ -7932,7 +9440,7 @@ var ts; } ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { + if (node.kind === 70) { return true; } else if (isPropertyAccessExpression(node)) { @@ -7947,21 +9455,21 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + return node.kind === 70 || + node.kind === 177 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 139 && node.parent.right === node) || - (node.parent.kind === 172 && node.parent.name === node); + return (node.parent.kind === 141 && node.parent.right === node) || + (node.parent.kind === 177 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 171) { + if (kind === 176) { return expression.properties.length === 0; } - if (kind === 170) { + if (kind === 175) { return expression.elements.length === 0; } return false; @@ -7971,14 +9479,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - 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 tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8012,39 +9512,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -8069,12 +9536,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8099,49 +9560,49 @@ var ts; var kind = node.kind; if (kind === 9 || kind === 8 - || kind === 10 || kind === 11 - || kind === 69 - || kind === 97 - || kind === 95 - || kind === 99 - || kind === 84 - || kind === 93) { + || kind === 12 + || kind === 70 + || kind === 98 + || kind === 96 + || kind === 100 + || kind === 85 + || kind === 94) { return true; } - else if (kind === 172) { + else if (kind === 177) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 173) { + else if (kind === 178) { return isSimpleExpressionWorker(node.expression, depth + 1) && isSimpleExpressionWorker(node.argumentExpression, depth + 1); } - else if (kind === 185 - || kind === 186) { + else if (kind === 190 + || kind === 191) { return isSimpleExpressionWorker(node.operand, depth + 1); } - else if (kind === 187) { - return node.operatorToken.kind !== 38 + else if (kind === 192) { + return node.operatorToken.kind !== 39 && isSimpleExpressionWorker(node.left, depth + 1) && isSimpleExpressionWorker(node.right, depth + 1); } - else if (kind === 188) { + else if (kind === 193) { return isSimpleExpressionWorker(node.condition, depth + 1) && isSimpleExpressionWorker(node.whenTrue, depth + 1) && isSimpleExpressionWorker(node.whenFalse, depth + 1); } - else if (kind === 183 - || kind === 182 - || kind === 181) { + else if (kind === 188 + || kind === 187 + || kind === 186) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 170) { + else if (kind === 175) { return node.elements.length === 0; } - else if (kind === 171) { + else if (kind === 176) { return node.properties.length === 0; } - else if (kind === 174) { + else if (kind === 179) { if (!isSimpleExpressionWorker(node.expression, depth + 1)) { return false; } @@ -8175,7 +9636,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,58 +9705,21 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; - function collectExternalModuleInfo(sourceFile, resolver) { - var externalImports = []; - var exportSpecifiers = ts.createMap(); - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 230: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - externalImports.push(node); - } - break; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { case 229: - if (node.moduleReference.kind === 240 && resolver.isReferencedAliasDeclaration(node)) { - externalImports.push(node); - } - break; - case 236: - if (node.moduleSpecifier) { - if (!node.exportClause) { - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); - } - } - break; - case 235: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; + case 230: + return parseNode === parseNode.parent.name; } } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + return false; } - ts.collectExternalModuleInfo = collectExternalModuleInfo; + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; function getInitializedVariables(node) { return ts.filter(node.declarations, isInitializedVariable); } @@ -8307,7 +9731,7 @@ var ts; if (node.symbol) { for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 && declaration !== node) { + if (declaration.kind === 226 && declaration !== node) { return true; } } @@ -8325,15 +9749,15 @@ var ts; } ts.isNodeArray = isNodeArray; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 11; + return node.kind === 12; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isLiteralKind(kind) { - return 8 <= kind && kind <= 11; + return 8 <= kind && kind <= 12; } ts.isLiteralKind = isLiteralKind; function isTextualLiteralKind(kind) { - return kind === 9 || kind === 11; + return kind === 9 || kind === 12; } ts.isTextualLiteralKind = isTextualLiteralKind; function isLiteralExpression(node) { @@ -8341,20 +9765,21 @@ var ts; } ts.isLiteralExpression = isLiteralExpression; function isTemplateLiteralKind(kind) { - return 11 <= kind && kind <= 14; + return 12 <= kind && kind <= 15; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 - || kind === 14; + function isTemplateHead(node) { + return node.kind === 13; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 14 + || kind === 15; } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { - return node.kind === 69; + return node.kind === 70; } ts.isIdentifier = isIdentifier; function isGeneratedIdentifier(node) { @@ -8366,183 +9791,240 @@ var ts; } ts.isModifier = isModifier; function isQualifiedName(node) { - return node.kind === 139; + return node.kind === 141; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 140; + return node.kind === 142; } ts.isComputedPropertyName = isComputedPropertyName; function isEntityName(node) { var kind = node.kind; - return kind === 139 - || kind === 69; + return kind === 141 + || kind === 70; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9 || kind === 8 - || kind === 140; + || kind === 142; } ts.isPropertyName = isPropertyName; function isModuleName(node) { var kind = node.kind; - return kind === 69 + return kind === 70 || kind === 9; } ts.isModuleName = isModuleName; function isBindingName(node) { var kind = node.kind; - return kind === 69 - || kind === 167 - || kind === 168; + return kind === 70 + || kind === 172 + || kind === 173; } ts.isBindingName = isBindingName; function isTypeParameter(node) { - return node.kind === 141; + return node.kind === 143; } ts.isTypeParameter = isTypeParameter; function isParameter(node) { - return node.kind === 142; + return node.kind === 144; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 143; + return node.kind === 145; } ts.isDecorator = isDecorator; function isMethodDeclaration(node) { - return node.kind === 147; + return node.kind === 149; } ts.isMethodDeclaration = isMethodDeclaration; function isClassElement(node) { var kind = node.kind; - return kind === 148 - || kind === 145 + return kind === 150 || kind === 147 || kind === 149 - || kind === 150 - || kind === 153 - || kind === 198; + || kind === 151 + || kind === 152 + || kind === 155 + || kind === 203; } ts.isClassElement = isClassElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 253 - || kind === 254 - || kind === 147 + return kind === 257 + || kind === 258 + || kind === 259 || kind === 149 - || kind === 150 - || kind === 239; + || kind === 151 + || kind === 152 + || kind === 244; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 154 && kind <= 166) - || kind === 117 - || kind === 130 - || kind === 120 + return (kind >= 156 && kind <= 171) + || kind === 118 || kind === 132 - || kind === 133 - || kind === 103 - || kind === 127 - || kind === 194; + || kind === 121 + || kind === 134 + || kind === 135 + || kind === 104 + || kind === 129 + || kind === 199; } function isTypeNode(node) { return isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; + function isArrayBindingPattern(node) { + return node.kind === 173; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isObjectBindingPattern(node) { + return node.kind === 172; + } + ts.isObjectBindingPattern = isObjectBindingPattern; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 168 - || kind === 167; + return kind === 173 + || kind === 172; } return false; } ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 175 + || kind === 176; + } + ts.isAssignmentPattern = isAssignmentPattern; function isBindingElement(node) { - return node.kind === 169; + return node.kind === 174; } ts.isBindingElement = isBindingElement; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 169 - || kind === 193; + return kind === 174 + || kind === 198; } ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 223: + case 144: + case 174: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 172: + case 176: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isArrayLiteralExpression(node) { + return node.kind === 175; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 176; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 172; + return node.kind === 177; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 173; + return node.kind === 178; } ts.isElementAccessExpression = isElementAccessExpression; function isBinaryExpression(node) { - return node.kind === 187; + return node.kind === 192; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 188; + return node.kind === 193; } ts.isConditionalExpression = isConditionalExpression; function isCallExpression(node) { - return node.kind === 174; + return node.kind === 179; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; - return kind === 189 - || kind === 11; + return kind === 194 + || kind === 12; } - ts.isTemplate = isTemplate; - function isSpreadElementExpression(node) { - return node.kind === 191; + ts.isTemplateLiteral = isTemplateLiteral; + function isSpreadExpression(node) { + return node.kind === 196; } - ts.isSpreadElementExpression = isSpreadElementExpression; + ts.isSpreadExpression = isSpreadExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 194; + return node.kind === 199; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isLeftHandSideExpressionKind(kind) { - return kind === 172 - || kind === 173 - || kind === 175 - || kind === 174 - || kind === 241 - || kind === 242 - || kind === 176 - || kind === 170 + return kind === 177 || kind === 178 - || kind === 171 - || kind === 192 + || kind === 180 || kind === 179 - || kind === 69 - || kind === 10 + || kind === 246 + || kind === 247 + || kind === 181 + || kind === 175 + || kind === 183 + || kind === 176 + || kind === 197 + || kind === 184 + || kind === 70 + || kind === 11 || kind === 8 || kind === 9 - || kind === 11 - || kind === 189 - || kind === 84 - || kind === 93 - || kind === 97 - || kind === 99 - || kind === 95 - || kind === 196; + || kind === 12 + || kind === 194 + || kind === 85 + || kind === 94 + || kind === 98 + || kind === 100 + || kind === 96 + || kind === 201 + || kind === 297; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isUnaryExpressionKind(kind) { - return kind === 185 + return kind === 190 + || kind === 191 || kind === 186 - || kind === 181 + || kind === 187 + || kind === 188 + || kind === 189 || kind === 182 - || kind === 183 - || kind === 184 - || kind === 177 || isLeftHandSideExpressionKind(kind); } function isUnaryExpression(node) { @@ -8550,13 +10032,14 @@ var ts; } ts.isUnaryExpression = isUnaryExpression; function isExpressionKind(kind) { - return kind === 188 - || kind === 190 - || kind === 180 - || kind === 187 - || kind === 191 + return kind === 193 || kind === 195 - || kind === 193 + || kind === 185 + || kind === 192 + || kind === 196 + || kind === 200 + || kind === 198 + || kind === 297 || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -8565,16 +10048,16 @@ var ts; ts.isExpression = isExpression; function isAssertionExpression(node) { var kind = node.kind; - return kind === 177 - || kind === 195; + return kind === 182 + || kind === 200; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 294; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 293; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -8583,15 +10066,15 @@ var ts; } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isOmittedExpression(node) { - return node.kind === 193; + return node.kind === 198; } ts.isOmittedExpression = isOmittedExpression; function isTemplateSpan(node) { - return node.kind === 197; + return node.kind === 202; } ts.isTemplateSpan = isTemplateSpan; function isBlock(node) { - return node.kind === 199; + return node.kind === 204; } ts.isBlock = isBlock; function isConciseBody(node) { @@ -8609,119 +10092,121 @@ var ts; } ts.isForInitializer = isForInitializer; function isVariableDeclaration(node) { - return node.kind === 218; + return node.kind === 223; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 219; + return node.kind === 224; } ts.isVariableDeclarationList = isVariableDeclarationList; function isCaseBlock(node) { - return node.kind === 227; + return node.kind === 232; } ts.isCaseBlock = isCaseBlock; function isModuleBody(node) { var kind = node.kind; - return kind === 226 - || kind === 225; + return kind === 231 + || kind === 230; } ts.isModuleBody = isModuleBody; function isImportEqualsDeclaration(node) { - return node.kind === 229; + return node.kind === 234; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportClause(node) { - return node.kind === 231; + return node.kind === 236; } ts.isImportClause = isImportClause; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 233 - || kind === 232; + return kind === 238 + || kind === 237; } ts.isNamedImportBindings = isNamedImportBindings; function isImportSpecifier(node) { - return node.kind === 234; + return node.kind === 239; } ts.isImportSpecifier = isImportSpecifier; function isNamedExports(node) { - return node.kind === 237; + return node.kind === 242; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 238; + return node.kind === 243; } ts.isExportSpecifier = isExportSpecifier; function isModuleOrEnumDeclaration(node) { - return node.kind === 225 || node.kind === 224; + return node.kind === 230 || node.kind === 229; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 180 - || kind === 169 - || kind === 221 - || kind === 192 - || kind === 148 - || kind === 224 - || kind === 255 - || kind === 238 - || kind === 220 - || kind === 179 - || kind === 149 - || kind === 231 + return kind === 185 + || kind === 174 + || kind === 226 + || kind === 197 + || kind === 150 || kind === 229 + || kind === 260 + || kind === 243 + || kind === 225 + || kind === 184 + || kind === 151 + || kind === 236 || kind === 234 - || kind === 222 + || kind === 239 + || kind === 227 + || kind === 149 + || kind === 148 + || kind === 230 + || kind === 233 + || kind === 237 + || kind === 144 + || kind === 257 || kind === 147 || kind === 146 - || kind === 225 + || kind === 152 + || kind === 258 || kind === 228 - || kind === 232 - || kind === 142 - || kind === 253 - || kind === 145 - || kind === 144 - || kind === 150 - || kind === 254 + || kind === 143 || kind === 223 - || kind === 141 - || kind === 218 - || kind === 279; + || kind === 285; } function isDeclarationStatementKind(kind) { - return kind === 220 - || kind === 239 - || kind === 221 - || kind === 222 - || kind === 223 - || kind === 224 - || kind === 225 - || kind === 230 + return kind === 225 + || kind === 244 + || kind === 226 + || kind === 227 + || kind === 228 || kind === 229 - || kind === 236 + || kind === 230 || kind === 235 - || kind === 228; + || kind === 234 + || kind === 241 + || kind === 240 + || kind === 233; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 210 - || kind === 209 - || kind === 217 - || kind === 204 - || kind === 202 - || kind === 201 - || kind === 207 - || kind === 208 - || kind === 206 - || kind === 203 + return kind === 215 || kind === 214 - || kind === 211 - || kind === 213 - || kind === 215 - || kind === 216 - || kind === 200 - || kind === 205 + || kind === 222 + || kind === 209 + || kind === 207 + || kind === 206 || kind === 212 - || kind === 287; + || kind === 213 + || kind === 211 + || kind === 208 + || kind === 219 + || kind === 216 + || kind === 218 + || kind === 220 + || kind === 221 + || kind === 205 + || kind === 210 + || kind === 217 + || kind === 293 + || kind === 296 + || kind === 295; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -8739,87 +10224,87 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 199; + || kind === 204; } ts.isStatement = isStatement; function isModuleReference(node) { var kind = node.kind; - return kind === 240 - || kind === 139 - || kind === 69; + return kind === 245 + || kind === 141 + || kind === 70; } ts.isModuleReference = isModuleReference; function isJsxOpeningElement(node) { - return node.kind === 243; + return node.kind === 248; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 245; + return node.kind === 249; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 97 - || kind === 69 - || kind === 172; + return kind === 98 + || kind === 70 + || kind === 177; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 241 - || kind === 248 - || kind === 242 - || kind === 244; + return kind === 246 + || kind === 252 + || kind === 247 + || kind === 10; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 246 - || kind === 247; + return kind === 250 + || kind === 251; } ts.isJsxAttributeLike = isJsxAttributeLike; function isJsxSpreadAttribute(node) { - return node.kind === 247; + return node.kind === 251; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxAttribute(node) { - return node.kind === 246; + return node.kind === 250; } ts.isJsxAttribute = isJsxAttribute; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 248; + || kind === 252; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 249 - || kind === 250; + return kind === 253 + || kind === 254; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isHeritageClause(node) { - return node.kind === 251; + return node.kind === 255; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 252; + return node.kind === 256; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 253; + return node.kind === 257; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 254; + return node.kind === 258; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 256; + return node.kind === 261; } ts.isSourceFile = isSourceFile; function isWatchSet(options) { @@ -8827,10 +10312,19 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { - return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case 5: + case 4: + return "lib.es2017.d.ts"; + case 3: + return "lib.es2016.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } } ts.getDefaultLibFileName = getDefaultLibFileName; function textSpanEnd(span) { @@ -8949,9 +10443,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 141) { + if (d && d.kind === 143) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 222) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227) { return current; } } @@ -8959,11 +10453,11 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 150 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 || ts.isBindingPattern(node))) { + while (node && (node.kind === 174 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -8971,14 +10465,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= ts.getModifierFlags(node); } return flags; @@ -8987,26 +10481,73 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 218) { + if (node.kind === 223) { node = node.parent; } - if (node && node.kind === 219) { + if (node && node.kind === 224) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 205) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; })(ts || (ts = {})); var ts; (function (ts) { var NodeConstructor; var SourceFileConstructor; function createNode(kind, location, flags) { - var ConstructorForKind = kind === 256 + var ConstructorForKind = kind === 261 ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); var node = location @@ -9062,7 +10603,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9087,14 +10628,14 @@ var ts; return node; } else if (typeof value === "boolean") { - return createNode(value ? 99 : 84, location, undefined); + return createNode(value ? 100 : 85, location, undefined); } else if (typeof value === "string") { var node = createNode(9, location, undefined); node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9104,7 +10645,7 @@ var ts; ts.createLiteral = createLiteral; var nextAutoGenerateId = 0; function createIdentifier(text, location) { - var node = createNode(69, location); + var node = createNode(70, location); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = ts.stringToToken(text); node.autoGenerateKind = 0; @@ -9113,7 +10654,7 @@ var ts; } ts.createIdentifier = createIdentifier; function createTempVariable(recordTempVariable, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 1; @@ -9126,7 +10667,7 @@ var ts; } ts.createTempVariable = createTempVariable; function createLoopVariable(location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = ""; name.originalKeywordKind = 0; name.autoGenerateKind = 2; @@ -9136,7 +10677,7 @@ var ts; } ts.createLoopVariable = createLoopVariable; function createUniqueName(text, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.text = text; name.originalKeywordKind = 0; name.autoGenerateKind = 3; @@ -9146,7 +10687,7 @@ var ts; } ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, location) { - var name = createNode(69, location); + var name = createNode(70, location); name.original = node; name.text = ""; name.originalKeywordKind = 0; @@ -9161,22 +10702,22 @@ var ts; } ts.createToken = createToken; function createSuper() { - var node = createNode(95); + var node = createNode(96); return node; } ts.createSuper = createSuper; function createThis(location) { - var node = createNode(97, location); + var node = createNode(98, location); return node; } ts.createThis = createThis; function createNull() { - var node = createNode(93); + var node = createNode(94); return node; } ts.createNull = createNull; function createComputedPropertyName(expression, location) { - var node = createNode(140, location); + var node = createNode(142, location); node.expression = expression; return node; } @@ -9188,12 +10729,8 @@ var ts; return node; } ts.updateComputedPropertyName = updateComputedPropertyName; - function createParameter(name, initializer, location) { - return createParameterDeclaration(undefined, undefined, undefined, name, undefined, undefined, initializer, location); - } - ts.createParameter = createParameter; - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { - var node = createNode(142, location, flags); + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(144, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.dotDotDotToken = dotDotDotToken; @@ -9203,16 +10740,16 @@ var ts; node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; return node; } - ts.createParameterDeclaration = createParameterDeclaration; - function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, node, node.flags), node); } return node; } - ts.updateParameterDeclaration = updateParameterDeclaration; + ts.updateParameter = updateParameter; function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { - var node = createNode(145, location); + var node = createNode(147, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9230,7 +10767,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(147, location, flags); + var node = createNode(149, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -9250,7 +10787,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body, location, flags) { - var node = createNode(148, location, flags); + var node = createNode(150, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = undefined; @@ -9268,7 +10805,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { - var node = createNode(149, location, flags); + var node = createNode(151, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9287,7 +10824,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { - var node = createNode(150, location, flags); + var node = createNode(152, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9305,7 +10842,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createObjectBindingPattern(elements, location) { - var node = createNode(167, location); + var node = createNode(172, location); node.elements = createNodeArray(elements); return node; } @@ -9318,7 +10855,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements, location) { - var node = createNode(168, location); + var node = createNode(173, location); node.elements = createNodeArray(elements); return node; } @@ -9331,7 +10868,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { - var node = createNode(169, location); + var node = createNode(174, location); node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; node.dotDotDotToken = dotDotDotToken; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -9339,15 +10876,15 @@ var ts; return node; } ts.createBindingElement = createBindingElement; - function updateBindingElement(node, propertyName, name, initializer) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, location, multiLine) { - var node = createNode(170, location); + var node = createNode(175, location); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) { node.multiLine = true; @@ -9363,7 +10900,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, location, multiLine) { - var node = createNode(171, location); + var node = createNode(176, location); node.properties = createNodeArray(properties); if (multiLine) { node.multiLine = true; @@ -9379,9 +10916,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name, location, flags) { - var node = createNode(172, location, flags); + var node = createNode(177, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 65536; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,14 +10926,14 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index, location) { - var node = createNode(173, location); + var node = createNode(178, location); node.expression = parenthesizeForAccess(expression); node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; return node; @@ -9410,7 +10947,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(174, location, flags); + var node = createNode(179, location, flags); node.expression = parenthesizeForAccess(expression); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -9427,7 +10964,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(175, location, flags); + var node = createNode(180, location, flags); node.expression = parenthesizeForNew(expression); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -9442,7 +10979,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template, location) { - var node = createNode(176, location); + var node = createNode(181, location); node.tag = parenthesizeForAccess(tag); node.template = template; return node; @@ -9456,7 +10993,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createParen(expression, location) { - var node = createNode(178, location); + var node = createNode(183, location); node.expression = expression; return node; } @@ -9468,9 +11005,9 @@ var ts; return node; } ts.updateParen = updateParen; - function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(179, location, flags); - node.modifiers = undefined; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(184, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -9480,20 +11017,20 @@ var ts; return node; } ts.createFunctionExpression = createFunctionExpression; - function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); + function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, node, node.flags), node); } return node; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { - var node = createNode(180, location, flags); + var node = createNode(185, location, flags); node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35); node.body = parenthesizeConciseBody(body); return node; } @@ -9506,7 +11043,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression, location) { - var node = createNode(181, location); + var node = createNode(186, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9519,7 +11056,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression, location) { - var node = createNode(182, location); + var node = createNode(187, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9532,7 +11069,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression, location) { - var node = createNode(183, location); + var node = createNode(188, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9545,7 +11082,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression, location) { - var node = createNode(184, location); + var node = createNode(189, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -9558,7 +11095,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand, location) { - var node = createNode(185, location); + var node = createNode(190, location); node.operator = operator; node.operand = parenthesizePrefixOperand(operand); return node; @@ -9572,7 +11109,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator, location) { - var node = createNode(186, location); + var node = createNode(191, location); node.operand = parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -9586,9 +11123,9 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; - var node = createNode(187, location); + var node = createNode(192, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); node.operatorToken = operatorToken; node.right = parenthesizeBinaryOperand(operatorKind, right, false, node.left); @@ -9602,13 +11139,21 @@ var ts; return node; } ts.updateBinary = updateBinary; - function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { - var node = createNode(188, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) { + var node = createNode(193, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + node.questionToken = createToken(54); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(55); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } ts.createConditional = createConditional; @@ -9620,7 +11165,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans, location) { - var node = createNode(189, location); + var node = createNode(194, location); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -9634,7 +11179,7 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createYield(asteriskToken, expression, location) { - var node = createNode(190, location); + var node = createNode(195, location); node.asteriskToken = asteriskToken; node.expression = expression; return node; @@ -9648,7 +11193,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression, location) { - var node = createNode(191, location); + var node = createNode(196, location); node.expression = parenthesizeExpressionForList(expression); return node; } @@ -9661,7 +11206,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(192, location); + var node = createNode(197, location); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -9679,12 +11224,12 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression(location) { - var node = createNode(193, location); + var node = createNode(198, location); return node; } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression, location) { - var node = createNode(194, location); + var node = createNode(199, location); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.expression = parenthesizeForAccess(expression); return node; @@ -9698,7 +11243,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createTemplateSpan(expression, literal, location) { - var node = createNode(197, location); + var node = createNode(202, location); node.expression = expression; node.literal = literal; return node; @@ -9712,7 +11257,7 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createBlock(statements, location, multiLine, flags) { - var block = createNode(199, location, flags); + var block = createNode(204, location, flags); block.statements = createNodeArray(statements); if (multiLine) { block.multiLine = true; @@ -9728,7 +11273,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList, location, flags) { - var node = createNode(200, location, flags); + var node = createNode(205, location, flags); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -9743,7 +11288,7 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createVariableDeclarationList(declarations, location, flags) { - var node = createNode(219, location, flags); + var node = createNode(224, location, flags); node.declarations = createNodeArray(declarations); return node; } @@ -9756,7 +11301,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createVariableDeclaration(name, type, initializer, location, flags) { - var node = createNode(218, location, flags); + var node = createNode(223, location, flags); node.name = typeof name === "string" ? createIdentifier(name) : name; node.type = type; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -9771,11 +11316,11 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement(location) { - return createNode(201, location); + return createNode(206, location); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression, location, flags) { - var node = createNode(202, location, flags); + var node = createNode(207, location, flags); node.expression = parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -9788,7 +11333,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement, location) { - var node = createNode(203, location); + var node = createNode(208, location); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -9803,7 +11348,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression, location) { - var node = createNode(204, location); + var node = createNode(209, location); node.statement = statement; node.expression = expression; return node; @@ -9817,7 +11362,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement, location) { - var node = createNode(205, location); + var node = createNode(210, location); node.expression = expression; node.statement = statement; return node; @@ -9831,7 +11376,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement, location) { - var node = createNode(206, location, undefined); + var node = createNode(211, location, undefined); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -9847,7 +11392,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement, location) { - var node = createNode(207, location); + var node = createNode(212, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -9862,7 +11407,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(initializer, expression, statement, location) { - var node = createNode(208, location); + var node = createNode(213, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -9877,7 +11422,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label, location) { - var node = createNode(209, location); + var node = createNode(214, location); if (label) { node.label = label; } @@ -9892,7 +11437,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label, location) { - var node = createNode(210, location); + var node = createNode(215, location); if (label) { node.label = label; } @@ -9907,7 +11452,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression, location) { - var node = createNode(211, location); + var node = createNode(216, location); node.expression = expression; return node; } @@ -9920,7 +11465,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement, location) { - var node = createNode(212, location); + var node = createNode(217, location); node.expression = expression; node.statement = statement; return node; @@ -9934,7 +11479,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock, location) { - var node = createNode(213, location); + var node = createNode(218, location); node.expression = parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -9948,7 +11493,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement, location) { - var node = createNode(214, location); + var node = createNode(219, location); node.label = typeof label === "string" ? createIdentifier(label) : label; node.statement = statement; return node; @@ -9962,7 +11507,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression, location) { - var node = createNode(215, location); + var node = createNode(220, location); node.expression = expression; return node; } @@ -9975,7 +11520,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock, location) { - var node = createNode(216, location); + var node = createNode(221, location); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -9990,7 +11535,7 @@ var ts; } ts.updateTry = updateTry; function createCaseBlock(clauses, location) { - var node = createNode(227, location); + var node = createNode(232, location); node.clauses = createNodeArray(clauses); return node; } @@ -10003,7 +11548,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(220, location, flags); + var node = createNode(225, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -10023,7 +11568,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(221, location); + var node = createNode(226, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -10041,7 +11586,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { - var node = createNode(230, location); + var node = createNode(235, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.importClause = importClause; @@ -10057,7 +11602,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings, location) { - var node = createNode(231, location); + var node = createNode(236, location); node.name = name; node.namedBindings = namedBindings; return node; @@ -10071,7 +11616,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name, location) { - var node = createNode(232, location); + var node = createNode(237, location); node.name = name; return node; } @@ -10084,7 +11629,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements, location) { - var node = createNode(233, location); + var node = createNode(238, location); node.elements = createNodeArray(elements); return node; } @@ -10097,7 +11642,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name, location) { - var node = createNode(234, location); + var node = createNode(239, location); node.propertyName = propertyName; node.name = name; return node; @@ -10111,7 +11656,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { - var node = createNode(235, location); + var node = createNode(240, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.isExportEquals = isExportEquals; @@ -10127,7 +11672,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { - var node = createNode(236, location); + var node = createNode(241, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.exportClause = exportClause; @@ -10143,7 +11688,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements, location) { - var node = createNode(237, location); + var node = createNode(242, location); node.elements = createNodeArray(elements); return node; } @@ -10156,7 +11701,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(name, propertyName, location) { - var node = createNode(238, location); + var node = createNode(243, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; return node; @@ -10170,7 +11715,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createJsxElement(openingElement, children, closingElement, location) { - var node = createNode(241, location); + var node = createNode(246, location); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -10185,7 +11730,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes, location) { - var node = createNode(242, location); + var node = createNode(247, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -10199,7 +11744,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes, location) { - var node = createNode(243, location); + var node = createNode(248, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -10213,7 +11758,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName, location) { - var node = createNode(245, location); + var node = createNode(249, location); node.tagName = tagName; return node; } @@ -10226,7 +11771,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxAttribute(name, initializer, location) { - var node = createNode(246, location); + var node = createNode(250, location); node.name = name; node.initializer = initializer; return node; @@ -10240,7 +11785,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxSpreadAttribute(expression, location) { - var node = createNode(247, location); + var node = createNode(251, location); node.expression = expression; return node; } @@ -10253,7 +11798,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(expression, location) { - var node = createNode(248, location); + var node = createNode(252, location); node.expression = expression; return node; } @@ -10266,7 +11811,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createHeritageClause(token, types, location) { - var node = createNode(251, location); + var node = createNode(255, location); node.token = token; node.types = createNodeArray(types); return node; @@ -10280,7 +11825,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements, location) { - var node = createNode(249, location); + var node = createNode(253, location); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -10294,7 +11839,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements, location) { - var node = createNode(250, location); + var node = createNode(254, location); node.statements = createNodeArray(statements); return node; } @@ -10307,7 +11852,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createCatchClause(variableDeclaration, block, location) { - var node = createNode(252, location); + var node = createNode(256, location); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -10321,7 +11866,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer, location) { - var node = createNode(253, location); + var node = createNode(257, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.questionToken = undefined; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -10336,12 +11881,18 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { - var node = createNode(254, location); + var node = createNode(258, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function createSpreadAssignment(expression, location) { + var node = createNode(259, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -10349,9 +11900,16 @@ var ts; return node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSpreadAssignment(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createNode(256, node, node.flags); + var updated = createNode(261, node, node.flags); updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; @@ -10405,21 +11963,33 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) - updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } return node; } ts.updateSourceFileNode = updateSourceFileNode; function createNotEmittedStatement(original) { - var node = createNode(287, original); + var node = createNode(293, original); node.original = original; return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + function createEndOfDeclarationMarker(original) { + var node = createNode(296); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + function createMergeDeclarationMarker(original) { + var node = createNode(295); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original, location) { - var node = createNode(288, location || original); + var node = createNode(294, location || original); node.expression = expression; node.original = original; return node; @@ -10432,69 +12002,77 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + function createRawExpression(text) { + var node = createNode(297); + node.text = text; + return node; + } + ts.createRawExpression = createRawExpression; function createComma(left, right) { - return createBinary(left, 24, right); + return createBinary(left, 25, right); } ts.createComma = createComma; function createLessThan(left, right, location) { - return createBinary(left, 25, right, location); + return createBinary(left, 26, right, location); } ts.createLessThan = createLessThan; function createAssignment(left, right, location) { - return createBinary(left, 56, right, location); + return createBinary(left, 57, right, location); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 32, right); + return createBinary(left, 33, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 33, right); + return createBinary(left, 34, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 35, right); + return createBinary(left, 36, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 36, right); + return createBinary(left, 37, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand, location) { - return createPostfix(operand, 41, location); + return createPostfix(operand, 42, location); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 51, right); + return createBinary(left, 52, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 52, right); + return createBinary(left, 53, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(49, operand); + return createPrefix(50, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { return createVoid(createLiteral(0)); } ts.createVoidZero = createVoidZero; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; function createMemberAccessForPropertyName(target, memberName, location) { if (ts.isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 64; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; - function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); - } - ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { return createCall(createPropertyAccess(func, "call"), undefined, [ thisArg @@ -10527,10 +12105,26 @@ var ts; function createReactNamespace(reactNamespace, parent) { var react = createIdentifier(reactNamespace || "React"); react.flags &= ~8; - react.parent = parent; + react.parent = ts.getParseTreeNode(parent); return react; } - function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = createSynthesizedNode(70); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { var argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -10550,9 +12144,21 @@ var ts; argumentsList.push(children[0]); } } - return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), undefined, argumentsList, location); + return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList, location); } - ts.createReactCreateElement = createReactCreateElement; + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExportDefault(expression) { + return createExportAssignment(undefined, undefined, false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(undefined, undefined, createNamedExports([createExportSpecifier(exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function createLetStatement(name, initializer, location) { + return createVariableStatement(undefined, createLetDeclarationList([createVariableDeclaration(name, undefined, initializer)]), location); + } + ts.createLetStatement = createLetStatement; function createLetDeclarationList(declarations, location) { return createVariableDeclarationList(declarations, location, 1); } @@ -10561,130 +12167,26 @@ var ts; return createVariableDeclarationList(declarations, location, 2); } ts.createConstDeclarationList = createConstDeclarationList; - function createHelperName(externalHelpersModuleName, name) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + function getHelperName(name) { + return setEmitFlags(createIdentifier(name), 4096 | 2); } - ts.createHelperName = createHelperName; - function createExtendsHelper(externalHelpersModuleName, name) { - return createCall(createHelperName(externalHelpersModuleName, "__extends"), undefined, [ - name, - createIdentifier("_super") - ]); - } - ts.createExtendsHelper = createExtendsHelper; - function createAssignHelper(externalHelpersModuleName, attributesSegments) { - return createCall(createHelperName(externalHelpersModuleName, "__assign"), undefined, attributesSegments); - } - ts.createAssignHelper = createAssignHelper; - function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { - return createCall(createHelperName(externalHelpersModuleName, "__param"), undefined, [ - createLiteral(parameterOffset), - expression - ], location); - } - ts.createParamHelper = createParamHelper; - function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { - return createCall(createHelperName(externalHelpersModuleName, "__metadata"), undefined, [ - createLiteral(metadataKey), - metadataValue - ]); - } - ts.createMetadataHelper = createMetadataHelper; - function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { - var argumentsArray = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, undefined, true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), undefined, argumentsArray, location); - } - ts.createDecorateHelper = createDecorateHelper; - function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; - return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ]); - } - ts.createAwaiterHelper = createAwaiterHelper; - function createHasOwnProperty(target, propertyName) { - return createCall(createPropertyAccess(target, "hasOwnProperty"), undefined, [propertyName]); - } - ts.createHasOwnProperty = createHasOwnProperty; - function createObjectCreate(prototype) { - return createCall(createPropertyAccess(createIdentifier("Object"), "create"), undefined, [prototype]); - } - function createGeti(target) { - return createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createElementAccess(target, createIdentifier("name"))); - } - function createSeti(target) { - return createArrowFunction(undefined, undefined, [ - createParameter("name"), - createParameter("value") - ], undefined, undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); - } - function createAdvancedAsyncSuperHelper() { - var createCache = createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("cache", undefined, createObjectCreate(createNull())) - ])); - var getter = createGetAccessor(undefined, undefined, "value", [], undefined, createBlock([ - createReturn(createCall(createIdentifier("geti"), undefined, [createIdentifier("name")])) - ])); - var setter = createSetAccessor(undefined, undefined, "value", [createParameter("v")], createBlock([ - createStatement(createCall(createIdentifier("seti"), undefined, [ - createIdentifier("name"), - createIdentifier("v") - ])) - ])); - var getOrCreateAccessorsForName = createReturn(createArrowFunction(undefined, undefined, [createParameter("name")], undefined, undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ - getter, - setter - ])))))); - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createCall(createParen(createFunctionExpression(undefined, undefined, undefined, [ - createParameter("geti"), - createParameter("seti") - ], undefined, createBlock([ - createCache, - getOrCreateAccessorsForName - ]))), undefined, [ - createGeti(createSuper()), - createSeti(createSuper()) - ])) - ])); - } - ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; - function createSimpleAsyncSuperHelper() { - return createVariableStatement(undefined, createConstDeclarationList([ - createVariableDeclaration("_super", undefined, createGeti(createSuper())) - ])); - } - ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + ts.getHelperName = getHelperName; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 69: + case 70: return cacheIdentifiers; - case 97: + case 98: case 8: case 9: return false; - case 170: + case 175: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 171: + case 176: return target.properties.length > 0; default: return true; @@ -10698,13 +12200,13 @@ var ts; thisArg = createThis(); target = callee; } - else if (callee.kind === 95) { + else if (callee.kind === 96) { thisArg = createThis(); target = languageVersion < 2 ? createIdentifier("_super", callee) : callee; } else { switch (callee.kind) { - case 172: { + case 177: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createPropertyAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.name, callee); @@ -10715,7 +12217,7 @@ var ts; } break; } - case 173: { + case 178: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); target = createElementAccess(createAssignment(thisArg, callee.expression, callee.expression), callee.argumentExpression, callee); @@ -10765,14 +12267,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 149: - case 150: + case 151: + case 152: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 253: + case 257: return createExpressionForPropertyAssignment(property, receiver); - case 254: + case 258: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 147: + case 149: return createExpressionForMethodDeclaration(property, receiver); } } @@ -10782,13 +12284,13 @@ var ts; if (property === firstAccessor) { var properties_1 = []; if (getAccessor) { - var getterFunction = createFunctionExpression(undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); + var getterFunction = createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body, getAccessor); setOriginalNode(getterFunction, getAccessor); var getter = createPropertyAssignment("get", getterFunction); properties_1.push(getter); } if (setAccessor) { - var setterFunction = createFunctionExpression(undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); + var setterFunction = createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body, setAccessor); setOriginalNode(setterFunction, setAccessor); var setter = createPropertyAssignment("set", setterFunction); properties_1.push(setter); @@ -10811,13 +12313,70 @@ var ts; return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), getSynthesizedClone(property.name), property), property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body, method), method), method), method)); } + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384); + } + ts.getLocalName = getLocalName; + function isLocalName(node) { + return (getEmitFlags(node) & 16384) !== 0; + } + ts.isLocalName = isLocalName; + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192); + } + ts.getExportName = getExportName; + function isExportName(node) { + return (getEmitFlags(node) & 8192) !== 0; + } + ts.isExportName = isExportName; + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { + var name_10 = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(name_10, emitFlags); + return name_10; + } + return getGeneratedNameForNode(node); + } + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), name); + var emitFlags; + if (!allowSourceMaps) + emitFlags |= 48; + if (!allowComments) + emitFlags |= 1536; + if (emitFlags) + setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : createBlock([createReturn(node, node)], node, multiLine); + } + ts.convertToFunctionBody = convertToFunctionBody; function isUseStrictPrologue(node) { return node.expression.text === "use strict"; } function addPrologueDirectives(target, source, ensureUseStrict, visitor) { - ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; var statementOffset = 0; var numStatements = source.length; @@ -10830,25 +12389,58 @@ var ts; target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (statement.emitFlags & 8388608) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (getEmitFlags(statement) & 524288) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + function ensureUseStrict(statements) { + var foundUseStrict = false; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))) + ].concat(statements), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 178) { + if (skipped.kind === 183) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -10857,15 +12449,15 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(187, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(187, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(192, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(192, binaryOperator); var emittedOperand = skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 190) { + && operand.kind === 195) { return false; } return true; @@ -10881,7 +12473,7 @@ var ts; if (operatorHasAssociativeProperty(binaryOperator)) { return false; } - if (binaryOperator === 35) { + if (binaryOperator === 36) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -10894,17 +12486,17 @@ var ts; } } function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 37 + return binaryOperator === 38 + || binaryOperator === 48 || binaryOperator === 47 - || binaryOperator === 46 - || binaryOperator === 48; + || binaryOperator === 49; } function getLiteralKindOfBinaryPlusOperand(node) { node = skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 187 && node.operatorToken.kind === 35) { + if (node.kind === 192 && node.operatorToken.kind === 36) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -10918,12 +12510,27 @@ var ts; } return 0; } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(193, 54); + var emittedCondition = skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + return createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + return e.kind === 192 && e.operatorToken.kind === 25 + ? createParen(e) + : e; + } function parenthesizeForNew(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { - case 174: + case 179: return createParen(expression); - case 175: + case 180: return emittedExpression.arguments ? expression : createParen(expression); @@ -10934,7 +12541,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 175 || emittedExpression.arguments) + && (emittedExpression.kind !== 180 || emittedExpression.arguments) && emittedExpression.kind !== 8) { return expression; } @@ -10972,7 +12579,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(187, 24); + var commaPrecedence = ts.getOperatorPrecedence(192, 25); return expressionPrecedence > commaPrecedence ? expression : createParen(expression, expression); @@ -10983,7 +12590,7 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 179 || kind === 180) { + if (kind === 184 || kind === 185) { var mutableCall = getMutableClone(emittedExpression); mutableCall.expression = createParen(callee, callee); return recreatePartiallyEmittedExpressions(expression, mutableCall); @@ -10991,7 +12598,7 @@ var ts; } else { var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 171 || leftmostExpressionKind === 179) { + if (leftmostExpressionKind === 176 || leftmostExpressionKind === 184) { return createParen(expression, expression); } } @@ -11009,21 +12616,21 @@ var ts; function getLeftmostExpression(node) { while (true) { switch (node.kind) { - case 186: + case 191: node = node.operand; continue; - case 187: + case 192: node = node.left; continue; - case 188: + case 193: node = node.condition; continue; - case 174: - case 173: - case 172: + case 179: + case 178: + case 177: node = node.expression; continue; - case 288: + case 294: node = node.expression; continue; } @@ -11032,7 +12639,7 @@ var ts; } function parenthesizeConciseBody(body) { var emittedBody = skipPartiallyEmittedExpressions(body); - if (emittedBody.kind === 171) { + if (emittedBody.kind === 176) { return createParen(body, body); } return body; @@ -11057,7 +12664,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 178) { + while (node.kind === 183) { node = node.expression; } return node; @@ -11071,7 +12678,7 @@ var ts; } ts.skipAssertions = skipAssertions; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 294) { node = node.expression; } return node; @@ -11085,17 +12692,214 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + if (!destEmitNode) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 261) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { + if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var helpers = getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + if (!helper.scoped) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!ts.contains(emitNode.helpers, helper)) { + emitNode.helpers = ts.append(emitNode.helpers, helper); + } + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!ts.contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0; + if (x.priority === y.priority) + return 0; + if (x.priority === undefined) + return 1; + if (y.priority === undefined) + return -1; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11125,10 +12929,10 @@ var ts; var name_11 = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } - if (node.kind === 230 && node.importClause) { + if (node.kind === 235 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 236 && node.moduleSpecifier) { + if (node.kind === 241 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; @@ -11166,6 +12970,291 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + return ts.isAssignmentExpression(bindingElement.initializer, true) + ? bindingElement.initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return bindingElement.right; + } + if (ts.isSpreadExpression(bindingElement)) { + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 257: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 258: + return bindingElement.name; + case 259: + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, true)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadExpression(bindingElement)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 144: + case 174: + return bindingElement.dotDotDotToken; + case 196: + case 259: + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 174: + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 257: + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 259: + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 172: + case 173: + case 175: + return name.elements; + case 176: + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 173: + case 175: + return convertToArrayAssignmentPattern(node); + case 172: + case 176: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportedBindings = ts.createMap(); + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration(undefined, undefined, createImportClause(undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 235: + externalImports.push(node); + break; + case 234: + if (node.moduleReference.kind === 245) { + externalImports.push(node); + } + break; + case 241: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports[specifier.name.text]) { + var name_12 = specifier.propertyName || specifier.name; + ts.multiMapAdd(exportSpecifiers, name_12.text, specifier); + var decl = resolver.getReferencedImportDeclaration(name_12) + || resolver.getReferencedValueDeclaration(name_12); + if (decl) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); + } + uniqueExports[specifier.name.text] = true; + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 240: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 205: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 225: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_13 = node.name; + if (!uniqueExports[name_13.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_13); + uniqueExports[name_13.text] = true; + exportedNames = ts.append(exportedNames, name_13); + } + } + } + break; + case 226: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name_14 = node.name; + if (!uniqueExports[name_14.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_14); + uniqueExports[name_14.text] = true; + exportedNames = ts.append(exportedNames, name_14); + } + } + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -11174,13 +13263,13 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 256) { + if (kind === 261) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { + else if (kind === 70) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } - else if (kind < 139) { + else if (kind < 141) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); } else { @@ -11216,26 +13305,28 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 139: + case 141: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 141: + case 143: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 254: + case 258: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 142: - case 145: + case 259: + return visitNode(cbNode, node.expression); case 144: - case 253: - case 218: - case 169: + case 147: + case 146: + case 257: + case 223: + case 174: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -11244,24 +13335,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 156: - case 157: - case 151: - case 152: + case 158: + case 159: case 153: + case 154: + case 155: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 179: - case 220: - case 180: + case 151: + case 152: + case 184: + case 225: + case 185: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -11272,308 +13363,320 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 155: + case 157: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 154: + case 156: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 158: - return visitNode(cbNode, node.exprName); - case 159: - return visitNodes(cbNodes, node.members); case 160: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 161: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 162: + return visitNode(cbNode, node.elementType); case 163: - return visitNodes(cbNodes, node.types); + return visitNodes(cbNodes, node.elementTypes); case 164: - return visitNode(cbNode, node.type); + case 165: + return visitNodes(cbNodes, node.types); case 166: - return visitNode(cbNode, node.literal); - case 167: case 168: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); + case 169: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); case 170: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); case 171: - return visitNodes(cbNodes, node.properties); + return visitNode(cbNode, node.literal); case 172: + case 173: + return visitNodes(cbNodes, node.elements); + case 175: + return visitNodes(cbNodes, node.elements); + case 176: + return visitNodes(cbNodes, node.properties); + case 177: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 173: + case 178: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 174: - case 175: + case 179: + case 180: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 176: + case 181: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 177: + case 182: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 178: - return visitNode(cbNode, node.expression); - case 181: - return visitNode(cbNode, node.expression); - case 182: - return visitNode(cbNode, node.expression); case 183: return visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.operand); + case 186: + return visitNode(cbNode, node.expression); + case 187: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); case 190: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 184: + case 189: return visitNode(cbNode, node.expression); - case 186: + case 191: return visitNode(cbNode, node.operand); - case 187: + case 192: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 195: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 196: + case 201: return visitNode(cbNode, node.expression); - case 188: + case 193: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 191: + case 196: return visitNode(cbNode, node.expression); - case 199: - case 226: + case 204: + case 231: return visitNodes(cbNodes, node.statements); - case 256: + case 261: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 200: + case 205: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 219: + case 224: return visitNodes(cbNodes, node.declarations); - case 202: + case 207: return visitNode(cbNode, node.expression); - case 203: + case 208: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 204: + case 209: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 205: + case 210: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206: + case 211: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 207: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 208: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 209: - case 210: - return visitNode(cbNode, node.label); - case 211: - return visitNode(cbNode, node.expression); case 212: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 213: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + case 215: + return visitNode(cbNode, node.label); + case 216: + return visitNode(cbNode, node.expression); + case 217: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 218: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 227: + case 232: return visitNodes(cbNodes, node.clauses); - case 249: + case 253: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 250: + case 254: return visitNodes(cbNodes, node.statements); - case 214: + case 219: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 215: + case 220: return visitNode(cbNode, node.expression); - case 216: + case 221: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 252: + case 256: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 143: + case 145: return visitNode(cbNode, node.expression); - case 221: - case 192: + case 226: + case 197: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 222: + case 227: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 223: + case 228: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 224: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 255: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 225: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); case 229: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNodes(cbNodes, node.members); + case 260: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 230: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 234: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 235: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 231: + case 236: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228: - return visitNode(cbNode, node.name); - case 232: - return visitNode(cbNode, node.name); case 233: + return visitNode(cbNode, node.name); case 237: + return visitNode(cbNode, node.name); + case 238: + case 242: return visitNodes(cbNodes, node.elements); - case 236: + case 241: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 234: - case 238: + case 239: + case 243: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 235: + case 240: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 197: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 140: - return visitNode(cbNode, node.expression); - case 251: - return visitNodes(cbNodes, node.types); case 194: + return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); + case 202: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 142: + return visitNode(cbNode, node.expression); + case 255: + return visitNodes(cbNodes, node.types); + case 199: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 240: + case 245: return visitNode(cbNode, node.expression); - case 239: + case 244: return visitNodes(cbNodes, node.decorators); - case 241: + case 246: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 242: - case 243: + case 247: + case 248: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 246: + case 250: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 247: + case 251: return visitNode(cbNode, node.expression); - case 248: + case 252: return visitNode(cbNode, node.expression); - case 245: + case 249: return visitNode(cbNode, node.tagName); - case 257: - return visitNode(cbNode, node.type); - case 261: - return visitNodes(cbNodes, node.types); case 262: - return visitNodes(cbNodes, node.types); - case 260: - return visitNode(cbNode, node.elementType); - case 264: - return visitNode(cbNode, node.type); - case 263: - return visitNode(cbNode, node.type); - case 265: - return visitNode(cbNode, node.literal); - case 267: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 268: - return visitNode(cbNode, node.type); - case 269: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 270: - return visitNode(cbNode, node.type); - case 271: - return visitNode(cbNode, node.type); - case 272: return visitNode(cbNode, node.type); case 266: + return visitNodes(cbNodes, node.types); + case 267: + return visitNodes(cbNodes, node.types); + case 265: + return visitNode(cbNode, node.elementType); + case 269: + return visitNode(cbNode, node.type); + case 268: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.literal); + case 272: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 273: + return visitNode(cbNode, node.type); + case 274: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 275: + return visitNode(cbNode, node.type); + case 276: + return visitNode(cbNode, node.type); + case 277: + return visitNode(cbNode, node.type); + case 271: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 273: + case 278: return visitNodes(cbNodes, node.tags); - case 275: + case 281: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 276: + case 282: return visitNode(cbNode, node.typeExpression); - case 277: + case 283: return visitNode(cbNode, node.typeExpression); - case 278: + case 280: + return visitNode(cbNode, node.typeExpression); + case 284: return visitNodes(cbNodes, node.typeParameters); - case 279: + case 285: return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.jsDocTypeLiteral); - case 281: + case 287: return visitNodes(cbNodes, node.jsDocPropertyTags); - case 280: + case 286: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 288: + case 294: return visitNode(cbNode, node.expression); - case 282: + case 288: return visitNode(cbNode, node.literal); } } @@ -11587,6 +13690,10 @@ var ts; return result; } ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } @@ -11609,8 +13716,8 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 32768 | 131072; + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -11626,18 +13733,27 @@ var ts; var parsingContext; var contextFlags; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; function getLanguageVariant(scriptKind) { return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; } - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); TokenConstructor = ts.objectAllocator.getTokenConstructor(); IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); @@ -11649,7 +13765,7 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 1048576 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -11684,7 +13800,7 @@ var ts; return sourceFile; } function addJSDocComment(node) { - var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; @@ -11692,10 +13808,10 @@ var ts; if (!jsDoc) { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } return node; @@ -11710,12 +13826,12 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -11724,7 +13840,7 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(261, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -11744,16 +13860,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 32768); + setContextFlag(val, 2048); } function setYieldContext(val) { - setContextFlag(val, 65536); + setContextFlag(val, 4096); } function setDecoratorContext(val) { - setContextFlag(val, 131072); + setContextFlag(val, 8192); } function setAwaitContext(val) { - setContextFlag(val, 262144); + setContextFlag(val, 16384); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -11776,40 +13892,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(32768, func); + return doOutsideOfContext(2048, func); } function disallowInAnd(func) { - return doInsideOfContext(32768, func); + return doInsideOfContext(2048, func); } function doInYieldContext(func) { - return doInsideOfContext(65536, func); + return doInsideOfContext(4096, func); } function doInDecoratorContext(func) { - return doInsideOfContext(131072, func); + return doInsideOfContext(8192, func); } function doInAwaitContext(func) { - return doInsideOfContext(262144, func); + return doInsideOfContext(16384, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(262144, func); + return doOutsideOfContext(16384, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(65536 | 262144, func); + return doInsideOfContext(4096 | 16384, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(65536); + return inContext(4096); } function inDisallowInContext() { - return inContext(32768); + return inContext(2048); } function inDecoratorContext() { - return inContext(131072); + return inContext(8192); } function inAwaitContext() { - return inContext(262144); + return inContext(16384); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -11880,16 +13996,16 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token() === 70) { return true; } - if (token() === 114 && inYieldContext()) { + if (token() === 115 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token() === 120 && inAwaitContext()) { return false; } - return token() > 105; + return token() > 106; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -11930,20 +14046,20 @@ var ts; return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token() === 24) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token() === 17 || token() === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token() === 24) { nextToken(); } return true; } else { - return parseExpected(23); + return parseExpected(24); } } function createNode(kind, pos) { @@ -11951,8 +14067,8 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : + return kind >= 141 ? new NodeConstructor(kind, pos, pos) : + kind === 70 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } function createNodeArray(elements, pos) { @@ -11971,7 +14087,7 @@ var ts; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 524288; + node.flags |= 32768; } return node; } @@ -11993,15 +14109,15 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(69); - if (token() !== 69) { + var node = createNode(70); + if (token() !== 70) { node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); } - return createMissingNode(69, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(70, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -12018,7 +14134,7 @@ var ts; if (token() === 9 || token() === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token() === 20) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -12033,10 +14149,10 @@ var ts; return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); } function parseComputedPropertyName() { - var node = createNode(140); - parseExpected(19); - node.expression = allowInAnd(parseExpression); + var node = createNode(142); parseExpected(20); + node.expression = allowInAnd(parseExpression); + parseExpected(21); return finishNode(node); } function parseContextualModifier(t) { @@ -12050,20 +14166,20 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { - return nextToken() === 81; + if (token() === 75) { + return nextToken() === 82; } - if (token() === 82) { + if (token() === 83) { nextToken(); - if (token() === 77) { + if (token() === 78) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token() !== 38 && token() !== 117 && token() !== 16 && canFollowModifier(); } - if (token() === 77) { + if (token() === 78) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token() === 114) { nextToken(); return canFollowModifier(); } @@ -12073,16 +14189,16 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token() === 20 + || token() === 16 + || token() === 38 + || token() === 23 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 74 || token() === 88 || + (token() === 119 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -12093,21 +14209,23 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token() === 24 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token() === 72 || token() === 78; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 24 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token() === 20 || token() === 38 || token() === 23 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token() === 20 || token() === 23 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token() === 16) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -12119,39 +14237,39 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); - case 17: + return token() === 25 || token() === 23 || isIdentifierOrPattern(); + case 18: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token() === 25 || token() === 23 || isStartOfExpression(); case 16: return isStartOfParameter(); - case 18: case 19: - return token() === 24 || isStartOfType(); case 20: - return isHeritageClause(); + return token() === 25 || isStartOfType(); case 21: + return isHeritageClause(); + case 22: return ts.tokenIsIdentifierOrKeyword(token()); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 16; case 14: return true; - case 22: case 23: - case 25: - return JSDocParser.isJSDocType(); case 24: + case 26: + return JSDocParser.isJSDocType(); + case 25: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); - if (nextToken() === 16) { + ts.Debug.assert(token() === 16); + if (nextToken() === 17) { var next = nextToken(); - return next === 24 || next === 15 || next === 83 || next === 106; + return next === 25 || next === 16 || next === 84 || next === 107; } return true; } @@ -12164,8 +14282,8 @@ var ts; return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token() === 107 || + token() === 84) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -12186,40 +14304,41 @@ var ts; case 6: case 12: case 9: - case 21: - return token() === 16; + case 22: + return token() === 17; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token() === 17 || token() === 72 || token() === 78; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token() === 16 || token() === 84 || token() === 107; case 8: return isVariableDeclaratorListTerminator(); - case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; - case 11: - return token() === 18 || token() === 23; - case 15: - case 19: - case 10: - return token() === 20; - case 16: - return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() === 28 || token() === 18 || token() === 16 || token() === 84 || token() === 107; + case 11: + return token() === 19 || token() === 24; + case 15: case 20: - return token() === 15 || token() === 16; + case 10: + return token() === 21; + case 16: + case 17: + return token() === 19 || token() === 21; + case 19: + return token() !== 25; + case 21: + return token() === 16 || token() === 17; case 13: - return token() === 27 || token() === 39; + return token() === 28 || token() === 40; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); - case 22: - return token() === 18 || token() === 54 || token() === 16; + return token() === 26 && lookAhead(nextTokenIsSlash); case 23: - return token() === 27 || token() === 16; - case 25: - return token() === 20 || token() === 16; + return token() === 19 || token() === 55 || token() === 17; case 24: - return token() === 16; + return token() === 28 || token() === 17; + case 26: + return token() === 21 || token() === 17; + case 25: + return token() === 17; } } function isVariableDeclaratorListTerminator() { @@ -12229,13 +14348,13 @@ var ts; if (isInOrOfKeyword(token())) { return true; } - if (token() === 34) { + if (token() === 35) { return true; } return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 26; kind++) { + for (var kind = 0; kind < 27; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -12286,7 +14405,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 1540096; + var nodeContextFlags = node.flags & 96256; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -12318,10 +14437,12 @@ var ts; return isReusableVariableDeclaration(node); case 16: return isReusableParameter(node); - case 20: case 17: - case 19: + return false; + case 21: case 18: + case 20: + case 19: case 11: case 12: case 7: @@ -12333,17 +14454,17 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 148: - case 153: - case 149: case 150: - case 145: - case 198: - return true; + case 155: + case 151: + case 152: case 147: + case 203: + return true; + case 149: var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 69 && - methodDeclaration.name.originalKeywordKind === 121; + var nameIsConstructor = methodDeclaration.name.kind === 70 && + methodDeclaration.name.originalKeywordKind === 122; return !nameIsConstructor; } } @@ -12352,8 +14473,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 249: - case 250: + case 253: + case 254: return true; } } @@ -12362,65 +14483,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 220: - case 200: - case 199: - case 203: - case 202: - case 215: - case 211: - case 213: - case 210: - case 209: - case 207: - case 208: - case 206: - case 205: - case 212: - case 201: - case 216: - case 214: - case 204: - case 217: - case 230: - case 229: - case 236: - case 235: case 225: + case 205: + case 204: + case 208: + case 207: + case 220: + case 216: + case 218: + case 215: + case 214: + case 212: + case 213: + case 211: + case 210: + case 217: + case 206: case 221: + case 219: + case 209: case 222: - case 224: - case 223: + case 235: + case 234: + case 241: + case 240: + case 230: + case 226: + case 227: + case 229: + case 228: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 255; + return node.kind === 260; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 152: + case 154: + case 148: + case 155: case 146: case 153: - case 144: - case 151: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 218) { + if (node.kind !== 223) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 142) { + if (node.kind !== 144) { return false; } var parameter = node; @@ -12440,6 +14561,7 @@ var ts; case 1: return ts.Diagnostics.Declaration_or_statement_expected; case 2: return ts.Diagnostics.case_or_default_expected; case 3: return ts.Diagnostics.Statement_expected; + case 17: case 4: return ts.Diagnostics.Property_or_signature_expected; case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6: return ts.Diagnostics.Enum_member_expected; @@ -12451,17 +14573,17 @@ var ts; case 12: return ts.Diagnostics.Property_assignment_expected; case 15: return ts.Diagnostics.Expression_or_comma_expected; case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 17: return ts.Diagnostics.Type_parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_argument_expected; - case 19: return ts.Diagnostics.Type_expected; - case 20: return ts.Diagnostics.Unexpected_token_expected; - case 21: return ts.Diagnostics.Identifier_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; - case 22: return ts.Diagnostics.Parameter_declaration_expected; - case 23: return ts.Diagnostics.Type_argument_expected; - case 25: return ts.Diagnostics.Type_expected; - case 24: return ts.Diagnostics.Property_assignment_expected; + case 23: return ts.Diagnostics.Parameter_declaration_expected; + case 24: return ts.Diagnostics.Type_argument_expected; + case 26: return ts.Diagnostics.Type_expected; + case 25: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -12474,15 +14596,15 @@ var ts; if (isListElement(kind, false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(24)) { + if (parseOptional(25)) { continue; } commaStart = -1; if (isListTerminator(kind)) { break; } - parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + parseExpected(25); + if (considerSemicolonAsDelimiter && token() === 24 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -12514,8 +14636,8 @@ var ts; } function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(21)) { - var node = createNode(139, entity.pos); + while (parseOptional(22)) { + var node = createNode(141, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -12526,33 +14648,33 @@ var ts; if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); + return createMissingNode(70, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(189); - template.head = parseTemplateLiteralFragment(); - ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); + var template = createNode(194); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 13, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 13); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 14); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(197); + var span = createNode(202); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token() === 17) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); + literal = parseExpectedToken(15, false, ts.Diagnostics._0_expected, ts.tokenToString(17)); } span.literal = literal; return finishNode(span); @@ -12560,8 +14682,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 14 || fragment.kind === 15, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -12585,35 +14714,35 @@ var ts; } function parseTypeReference() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - var node = createNode(155, typeName.pos); + var node = createNode(157, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (!scanner.hasPrecedingLineBreak() && token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(154, lhs.pos); + var node = createNode(156, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(165); + var node = createNode(167); nextToken(); return finishNode(node); } function parseTypeQuery() { - var node = createNode(158); - parseExpected(101); + var node = createNode(160); + parseExpected(102); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(141); + var node = createNode(143); node.name = parseIdentifier(); - if (parseOptional(83)) { + if (parseOptional(84)) { if (isStartOfType() || !isStartOfExpression()) { node.constraint = parseType(); } @@ -12624,34 +14753,34 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { - return parseBracketedList(17, parseTypeParameter, 25, 27); + if (token() === 26) { + return parseBracketedList(18, parseTypeParameter, 26, 28); } } function parseParameterType() { - if (parseOptional(54)) { + if (parseOptional(55)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token() === 23 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 || token() === 98; } function parseParameter() { - var node = createNode(142); - if (token() === 97) { + var node = createNode(144); + if (token() === 98) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(22); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { nextToken(); } - node.questionToken = parseOptionalToken(53); + node.questionToken = parseOptionalToken(54); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(true); return addJSDocComment(finishNode(node)); @@ -12663,7 +14792,7 @@ var ts; return parseInitializer(true); } function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 34; + var returnTokenRequired = returnToken === 35; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { @@ -12675,7 +14804,7 @@ var ts; } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(17)) { + if (parseExpected(18)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); @@ -12683,7 +14812,7 @@ var ts; var result = parseDelimitedList(16, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(18) && requireCompleteParameterList) { + if (!parseExpected(19) && requireCompleteParameterList) { return undefined; } return result; @@ -12691,29 +14820,29 @@ var ts; return requireCompleteParameterList ? undefined : createMissingList(); } function parseTypeMemberSemicolon() { - if (parseOptional(24)) { + if (parseOptional(25)) { return; } parseSemicolon(); } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 152) { - parseExpected(92); + if (kind === 154) { + parseExpected(93); } - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token() !== 19) { + if (token() !== 20) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token() === 23 || token() === 21) { return true; } if (ts.isModifierKind(token())) { @@ -12728,43 +14857,43 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token() === 55 || token() === 25) { return true; } - if (token() !== 53) { + if (token() !== 54) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token() === 55 || token() === 25 || token() === 21; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(153, fullStart); + var node = createNode(155, fullStart); node.decorators = decorators; node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 19, 20); + node.parameters = parseBracketedList(16, parseParameter, 20, 21); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { - var method = createNode(146, fullStart); + var questionToken = parseOptionalToken(54); + if (token() === 18 || token() === 26) { + var method = createNode(148, fullStart); method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; - fillSignature(54, false, false, false, method); + fillSignature(55, false, false, false, method); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(method)); } else { - var property = createNode(144, fullStart); + var property = createNode(146, fullStart); property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token() === 57) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -12773,14 +14902,14 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token() === 18 || token() === 26) { return true; } while (ts.isModifierKind(token())) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (isLiteralPropertyName()) { @@ -12788,21 +14917,21 @@ var ts; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || + return token() === 18 || + token() === 26 || token() === 54 || - token() === 24 || + token() === 55 || + token() === 25 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { - return parseSignatureMember(151); + if (token() === 18 || token() === 26) { + return parseSignatureMember(153); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(152); + if (token() === 93 && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(154); } var fullStart = getNodePos(); var modifiers = parseModifiers(); @@ -12813,50 +14942,77 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token() === 18 || token() === 26; } function parseTypeLiteral() { - var node = createNode(159); + var node = createNode(161); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(15)) { + if (parseExpected(16)) { members = parseList(4, parseTypeMember); - parseExpected(16); + parseExpected(17); } else { members = createMissingList(); } return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === 130) { + nextToken(); + } + return token() === 20 && nextTokenIsIdentifier() && nextToken() === 91; + } + function parseMappedTypeParameter() { + var node = createNode(143); + node.name = parseIdentifier(); + parseExpected(91); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(170); + parseExpected(16); + node.readonlyToken = parseOptionalToken(130); + parseExpected(20); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(21); + node.questionToken = parseOptionalToken(54); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(17); + return finishNode(node); + } function parseTupleType() { - var node = createNode(161); - node.elementTypes = parseBracketedList(19, parseType, 19, 20); + var node = createNode(163); + node.elementTypes = parseBracketedList(20, parseType, 20, 21); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(164); - parseExpected(17); - node.type = parseType(); + var node = createNode(166); parseExpected(18); + node.type = parseType(); + parseExpected(19); return finishNode(node); } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 157) { - parseExpected(92); + if (kind === 159) { + parseExpected(93); } - fillSignature(34, false, false, false, node); + fillSignature(35, false, false, false, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; + return token() === 22 ? undefined : node; } function parseLiteralTypeNode() { - var node = createNode(166); + var node = createNode(171); node.literal = parseSimpleUnaryExpression(); finishNode(node); return node; @@ -12866,41 +15022,41 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: + case 121: case 135: - case 127: + case 137: + case 129: var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseLiteralTypeNode(); - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 103: - case 93: + case 104: + case 94: return parseTokenNode(); - case 97: { + case 98: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 101: + case 102: return parseTypeQuery(); - case 15: - return parseTypeLiteral(); - case 19: + case 16: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 20: return parseTupleType(); - case 17: + case 18: return parseParenthesizedType(); default: return parseTypeReference(); @@ -12908,29 +15064,31 @@ var ts; } function isStartOfType() { switch (token()) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: + case 104: + case 137: + case 94: + case 98: + case 102: + case 129: + case 16: + case 20: + case 26: + case 48: + case 47: case 93: - case 97: - case 101: - case 127: - case 15: - case 19: - case 25: - case 92: case 9: case 8: - case 99: - case 84: + case 100: + case 85: return true; - case 36: + case 37: return lookAhead(nextTokenIsNumericLiteral); - case 17: + case 18: return lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); @@ -12938,19 +15096,43 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token() === 19 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(19)) { - parseExpected(20); - var node = createNode(160, type.pos); - node.elementType = type; - type = finishNode(node); + while (!scanner.hasPrecedingLineBreak() && parseOptional(20)) { + if (isStartOfType()) { + var node = createNode(169, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(21); + type = finishNode(node); + } + else { + var node = createNode(162, type.pos); + node.elementType = type; + parseExpected(21); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator) { + var node = createNode(168); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 126: + return parseTypeOperator(126); + } + return parseArrayTypeOrHigher(); + } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { var types = createNodeArray([type], type.pos); @@ -12965,26 +15147,26 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(163, parseArrayTypeOrHigher, 46); + return parseUnionOrIntersectionType(165, parseTypeOperatorOrHigher, 47); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); + return parseUnionOrIntersectionType(164, parseIntersectionTypeOrHigher, 48); } function isStartOfFunctionType() { - if (token() === 25) { + if (token() === 26) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 18 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token() === 98) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token() === 20 || token() === 16) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -12993,17 +15175,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token() === 19 || token() === 23) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token() === 55 || token() === 25 || + token() === 54 || token() === 57) { return true; } - if (token() === 18) { + if (token() === 19) { nextToken(); - if (token() === 34) { + if (token() === 35) { return true; } } @@ -13014,7 +15196,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(154, typePredicateVariable.pos); + var node = createNode(156, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -13025,46 +15207,46 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(327680, parseTypeWorker); + return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(156); + return parseFunctionOrConstructorType(158); } - if (token() === 92) { - return parseFunctionOrConstructorType(157); + if (token() === 93) { + return parseFunctionOrConstructorType(159); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(54) ? parseType() : undefined; + return parseOptional(55) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { switch (token()) { - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: case 8: case 9: - case 11: case 12: - case 17: - case 19: - case 15: - case 87: - case 73: - case 92: - case 39: - case 61: - case 69: + case 13: + case 18: + case 20: + case 16: + case 88: + case 74: + case 93: + case 40: + case 62: + case 70: return true; default: return isIdentifier(); @@ -13075,18 +15257,18 @@ var ts; return true; } switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 41: + case 79: + case 102: + case 104: case 42: - case 25: - case 119: - case 114: + case 43: + case 26: + case 120: + case 115: return true; default: if (isBinaryOperator()) { @@ -13096,10 +15278,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token() !== 16 && + token() !== 88 && + token() !== 74 && + token() !== 56 && isStartOfExpression(); } function parseExpression() { @@ -13109,7 +15291,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(24))) { + while ((operatorToken = parseOptionalToken(25))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -13118,12 +15300,12 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token() !== 57) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 16) || !isStartOfExpression()) { return undefined; } } - parseExpected(56); + parseExpected(57); return parseAssignmentExpressionOrHigher(); } function parseAssignmentExpressionOrHigher() { @@ -13135,7 +15317,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 70 && token() === 35) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -13144,7 +15326,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token() === 115) { if (inYieldContext()) { return true; } @@ -13157,11 +15339,11 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(190); + var node = createNode(195); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(37); + (token() === 38 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(38); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -13170,21 +15352,21 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 35, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(180, asyncModifier.pos); + node = createNode(185, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(180, identifier.pos); + node = createNode(185, identifier.pos); } - var parameter = createNode(142, identifier.pos); + var parameter = createNode(144, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -13201,78 +15383,78 @@ var ts; } var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 34 || lastToken === 15) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(35, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 35 || lastToken === 16) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return addJSDocComment(finishNode(arrowFunction)); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token() === 18 || token() === 26 || token() === 119) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token() === 35) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token() !== 18 && token() !== 26) { return 0; } } var first = token(); var second = nextToken(); - if (first === 17) { - if (second === 18) { + if (first === 18) { + if (second === 19) { var third = nextToken(); switch (third) { - case 34: - case 54: - case 15: + case 35: + case 55: + case 16: return 1; default: return 0; } } - if (second === 19 || second === 15) { + if (second === 20 || second === 16) { return 2; } - if (second === 22) { + if (second === 23) { return 1; } if (!isIdentifier()) { return 0; } - if (nextToken() === 54) { + if (nextToken() === 55) { return 1; } return 2; } else { - ts.Debug.assert(first === 25); + ts.Debug.assert(first === 26); if (!isIdentifier()) { return 0; } if (sourceFile.languageVariant === 1) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 83) { + if (third === 84) { var fourth = nextToken(); switch (fourth) { - case 56: - case 27: + case 57: + case 28: return false; default: return true; } } - else if (third === 24) { + else if (third === 25) { return true; } return false; @@ -13289,7 +15471,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token() === 119) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -13300,38 +15482,38 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token() === 119) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token() === 35) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 70 && token() === 35) { return 1; } } return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(180); + var node = createNode(185); node.modifiers = parseModifiersForArrowFunction(); var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(54, false, isAsync, !allowAmbiguity, node); + fillSignature(55, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token() !== 35 && token() !== 16) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token() === 16) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token() !== 24 && + token() !== 88 && + token() !== 74 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -13341,15 +15523,15 @@ var ts; : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); } function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(53); + var questionToken = parseOptionalToken(54); if (!questionToken) { return leftOperand; } - var node = createNode(188, leftOperand.pos); + var node = createNode(193, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(54, false, ts.Diagnostics._0_expected, ts.tokenToString(54)); + node.colonToken = parseExpectedToken(55, false, ts.Diagnostics._0_expected, ts.tokenToString(55)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -13358,22 +15540,22 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 || t === 138; + return t === 91 || t === 140; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token() === 39 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token() === 91 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token() === 117) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -13389,92 +15571,92 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token() === 91) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 52: + case 53: return 1; - case 51: + case 52: return 2; - case 47: - return 3; case 48: + return 3; + case 49: return 4; - case 46: + case 47: return 5; - case 30: case 31: case 32: case 33: + case 34: return 6; - case 25: - case 27: + case 26: case 28: case 29: + case 30: + case 92: case 91: - case 90: - case 116: + case 117: return 7; - case 43: case 44: case 45: + case 46: return 8; - case 35: case 36: - return 9; case 37: - case 39: - case 40: - return 10; + return 9; case 38: + case 40: + case 41: + return 10; + case 39: return 11; } return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(187, left.pos); + var node = createNode(192, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(195, left.pos); + var node = createNode(200, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(185); + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(181); + var node = createNode(186); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(182); + var node = createNode(187); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(183); + var node = createNode(188); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token() === 120) { if (inAwaitContext()) { return true; } @@ -13483,7 +15665,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(184); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13491,15 +15673,15 @@ var ts; function parseUnaryExpressionOrHigher() { if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token() === 39 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token() === 39) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 177) { + if (simpleUnaryExpression.kind === 182) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -13510,20 +15692,20 @@ var ts; } function parseSimpleUnaryExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: return parsePrefixUnaryExpression(); - case 78: + case 79: return parseDeleteExpression(); - case 101: + case 102: return parseTypeOfExpression(); - case 103: + case 104: return parseVoidExpression(); - case 25: + case 26: return parseTypeAssertion(); - case 119: + case 120: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -13533,16 +15715,16 @@ var ts; } function isUpdateExpression() { switch (token()) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 78: - case 101: - case 103: - case 119: + case 79: + case 102: + case 104: + case 120: return false; - case 25: + case 26: if (sourceFile.languageVariant !== 1) { return false; } @@ -13551,20 +15733,20 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { - var node = createNode(185); + if (token() === 42 || token() === 43) { + var node = createNode(190); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token() === 26 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(186, expression.pos); + if ((token() === 42 || token() === 43) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(191, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -13573,7 +15755,7 @@ var ts; return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token() === 96 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -13584,12 +15766,12 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token() === 18 || token() === 22 || token() === 20) { return expression; } - var node = createNode(172, expression.pos); + var node = createNode(177, expression.pos); node.expression = expression; - parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(22, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -13597,10 +15779,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 69) { + if (lhs.kind === 70) { return lhs.text === rhs.text; } - if (lhs.kind === 97) { + if (lhs.kind === 98) { return true; } return lhs.name.text === rhs.name.text && @@ -13609,8 +15791,8 @@ var ts; function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 243) { - var node = createNode(241, opening.pos); + if (opening.kind === 248) { + var node = createNode(246, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -13620,18 +15802,18 @@ var ts; result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 242); + ts.Debug.assert(opening.kind === 247); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token() === 26) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(187, result.pos); + var badNode = createNode(192, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(24, false, undefined); + badNode.operatorToken = createMissingNode(25, false, undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -13639,17 +15821,17 @@ var ts; return result; } function parseJsxText() { - var node = createNode(244, scanner.getStartPos()); + var node = createNode(10, scanner.getStartPos()); currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 244: + case 10: return parseJsxText(); - case 15: + case 16: return parseJsxExpression(false); - case 25: + case 26: return parseJsxElementOrSelfClosingElement(false); } ts.Debug.fail("Unknown JSX child kind " + token()); @@ -13660,7 +15842,7 @@ var ts; parsingContext |= 1 << 14; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + if (token() === 27) { break; } else if (token() === 1) { @@ -13675,24 +15857,24 @@ var ts; } function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(25); + parseExpected(26); var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { - node = createNode(243, fullStart); + if (token() === 28) { + node = createNode(248, fullStart); scanJsxText(); } else { - parseExpected(39); + parseExpected(40); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } - node = createNode(242, fullStart); + node = createNode(247, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -13700,10 +15882,10 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token() === 98 ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(21)) { - var propertyAccess = createNode(172, expression.pos); + while (parseOptional(22)) { + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13711,28 +15893,28 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(248); - parseExpected(15); - if (token() !== 16) { + var node = createNode(252); + parseExpected(16); + if (token() !== 17) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(16); + parseExpected(17); } else { - parseExpected(16, undefined, false); + parseExpected(17, undefined, false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token() === 16) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(246); + var node = createNode(250); node.name = parseIdentifierName(); - if (token() === 56) { + if (token() === 57) { switch (scanJsxAttributeValue()) { case 9: node.initializer = parseLiteralNode(); @@ -13745,69 +15927,69 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(247); - parseExpected(15); - parseExpected(22); - node.expression = parseExpression(); + var node = createNode(251); parseExpected(16); + parseExpected(23); + node.expression = parseExpression(); + parseExpected(17); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(245); - parseExpected(26); + var node = createNode(249); + parseExpected(27); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(27); + parseExpected(28); } else { - parseExpected(27, undefined, false); + parseExpected(28, undefined, false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(177); - parseExpected(25); + var node = createNode(182); + parseExpected(26); node.type = parseType(); - parseExpected(27); + parseExpected(28); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(21); + var dotToken = parseOptionalToken(22); if (dotToken) { - var propertyAccess = createNode(172, expression.pos); + var propertyAccess = createNode(177, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token() === 50 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(196, expression.pos); + var nonNullExpression = createNode(201, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } - if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(173, expression.pos); + if (!inDecoratorContext() && parseOptional(20)) { + var indexedAccess = createNode(178, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token() !== 21) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(20); + parseExpected(21); expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { - var tagExpression = createNode(176, expression.pos); + if (token() === 12 || token() === 13) { + var tagExpression = createNode(181, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token() === 12 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -13819,20 +16001,20 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token() === 26) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - var callExpr = createNode(174, expression.pos); + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 17) { - var callExpr = createNode(174, expression.pos); + else if (token() === 18) { + var callExpr = createNode(179, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -13842,17 +16024,17 @@ var ts; } } function parseArgumentList() { - parseExpected(17); - var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(18); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(19); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(25)) { + if (!parseOptional(26)) { return undefined; } - var typeArguments = parseDelimitedList(18, parseType); - if (!parseExpected(27)) { + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(28)) { return undefined; } return typeArguments && canFollowTypeArgumentsInExpression() @@ -13861,27 +16043,27 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 17: - case 21: case 18: - case 20: + case 22: + case 19: + case 21: + case 55: + case 24: case 54: - case 23: - case 53: - case 30: - case 32: case 31: case 33: - case 51: + case 32: + case 34: case 52: - case 48: - case 46: + case 53: + case 49: case 47: - case 16: + case 48: + case 17: case 1: return true; - case 24: - case 15: + case 25: + case 16: default: return false; } @@ -13890,103 +16072,109 @@ var ts; switch (token()) { case 8: case 9: - case 11: + case 12: return parseLiteralNode(); - case 97: - case 95: - case 93: - case 99: - case 84: + case 98: + case 96: + case 94: + case 100: + case 85: return parseTokenNode(); - case 17: + case 18: return parseParenthesizedExpression(); - case 19: + case 20: return parseArrayLiteralExpression(); - case 15: + case 16: return parseObjectLiteralExpression(); - case 118: + case 119: if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { break; } return parseFunctionExpression(); - case 73: + case 74: return parseClassExpression(); - case 87: + case 88: return parseFunctionExpression(); - case 92: + case 93: return parseNewExpression(); - case 39: - case 61: - if (reScanSlashToken() === 10) { + case 40: + case 62: + if (reScanSlashToken() === 11) { return parseLiteralNode(); } break; - case 12: + case 13: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(178); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(183); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); return finishNode(node); } function parseSpreadElement() { - var node = createNode(191); - parseExpected(22); + var node = createNode(196); + parseExpected(23); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token() === 23 ? parseSpreadElement() : + token() === 25 ? createNode(198) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(170); - parseExpected(19); + var node = createNode(175); + parseExpected(20); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(20); + parseExpected(21); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(123)) { - return parseAccessorDeclaration(149, fullStart, decorators, modifiers); + if (parseContextualModifier(124)) { + return parseAccessorDeclaration(151, fullStart, decorators, modifiers); } - else if (parseContextualModifier(131)) { - return parseAccessorDeclaration(150, fullStart, decorators, modifiers); + else if (parseContextualModifier(133)) { + return parseAccessorDeclaration(152, fullStart, decorators, modifiers); } return undefined; } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(23); + if (dotDotDotToken) { + var spreadElement = createNode(259, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } var decorators = parseDecorators(); var modifiers = parseModifiers(); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 || token() === 17 || token() === 57); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(254, fullStart); + var shorthandDeclaration = createNode(258, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(56); + var equalsToken = parseOptionalToken(57); if (equalsToken) { shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); @@ -13994,23 +16182,23 @@ var ts; return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(253, fullStart); + var propertyAssignment = createNode(257, fullStart); propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; - parseExpected(54); + parseExpected(55); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(171); - parseExpected(15); + var node = createNode(176); + parseExpected(16); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(16); + parseExpected(17); return finishNode(node); } function parseFunctionExpression() { @@ -14018,10 +16206,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(179); + var node = createNode(184); node.modifiers = parseModifiers(); - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); var isGenerator = !!node.asteriskToken; var isAsync = !!(ts.getModifierFlags(node) & 256); node.name = @@ -14029,7 +16217,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlock(isGenerator, isAsync, false); if (saveDecoratorContext) { setDecoratorContext(true); @@ -14040,23 +16228,23 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(175); - parseExpected(92); + var node = createNode(180); + parseExpected(93); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token() === 18) { node.arguments = parseArgumentList(); } return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(199); - if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(204); + if (parseExpected(16, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -14081,47 +16269,47 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(201); - parseExpected(23); + var node = createNode(206); + parseExpected(24); return finishNode(node); } function parseIfStatement() { - var node = createNode(203); - parseExpected(88); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(208); + parseExpected(89); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(80) ? parseStatement() : undefined; + node.elseStatement = parseOptional(81) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(204); - parseExpected(79); + var node = createNode(209); + parseExpected(80); node.statement = parseStatement(); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + parseExpected(105); parseExpected(18); - parseOptional(23); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + parseOptional(24); return finishNode(node); } function parseWhileStatement() { - var node = createNode(205); - parseExpected(104); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(210); + parseExpected(105); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(86); - parseExpected(17); + parseExpected(87); + parseExpected(18); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token() !== 24) { + if (token() === 103 || token() === 109 || token() === 75) { initializer = parseVariableDeclarationList(true); } else { @@ -14129,32 +16317,32 @@ var ts; } } var forOrForInOrForOfStatement; - if (parseOptional(90)) { - var forInStatement = createNode(207, pos); + if (parseOptional(91)) { + var forInStatement = createNode(212, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(138)) { - var forOfStatement = createNode(208, pos); + else if (parseOptional(140)) { + var forOfStatement = createNode(213, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(206, pos); + var forStatement = createNode(211, pos); forStatement.initializer = initializer; - parseExpected(23); - if (token() !== 23 && token() !== 18) { + parseExpected(24); + if (token() !== 24 && token() !== 19) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(23); - if (token() !== 18) { + parseExpected(24); + if (token() !== 19) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(18); + parseExpected(19); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -14162,7 +16350,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 210 ? 70 : 75); + parseExpected(kind === 215 ? 71 : 76); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14170,8 +16358,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(211); - parseExpected(94); + var node = createNode(216); + parseExpected(95); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -14179,90 +16367,90 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(212); - parseExpected(105); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(217); + parseExpected(106); parseExpected(18); + node.expression = allowInAnd(parseExpression); + parseExpected(19); node.statement = parseStatement(); return finishNode(node); } function parseCaseClause() { - var node = createNode(249); - parseExpected(71); + var node = createNode(253); + parseExpected(72); node.expression = allowInAnd(parseExpression); - parseExpected(54); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(250); - parseExpected(77); - parseExpected(54); + var node = createNode(254); + parseExpected(78); + parseExpected(55); node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 72 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(213); - parseExpected(96); - parseExpected(17); - node.expression = allowInAnd(parseExpression); + var node = createNode(218); + parseExpected(97); parseExpected(18); - var caseBlock = createNode(227, scanner.getStartPos()); - parseExpected(15); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + node.expression = allowInAnd(parseExpression); + parseExpected(19); + var caseBlock = createNode(232, scanner.getStartPos()); parseExpected(16); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(17); node.caseBlock = finishNode(caseBlock); return finishNode(node); } function parseThrowStatement() { - var node = createNode(215); - parseExpected(98); + var node = createNode(220); + parseExpected(99); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(216); - parseExpected(100); + var node = createNode(221); + parseExpected(101); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { - parseExpected(85); + node.catchClause = token() === 73 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 86) { + parseExpected(86); node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(252); - parseExpected(72); - if (parseExpected(17)) { + var result = createNode(256); + parseExpected(73); + if (parseExpected(18)) { result.variableDeclaration = parseVariableDeclaration(); } - parseExpected(18); + parseExpected(19); result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(217); - parseExpected(76); + var node = createNode(222); + parseExpected(77); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); - if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(214, fullStart); + if (expression.kind === 70 && parseOptional(55)) { + var labeledStatement = createNode(219, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(202, fullStart); + var expressionStatement = createNode(207, fullStart); expressionStatement.expression = expression; parseSemicolon(); return addJSDocComment(finishNode(expressionStatement)); @@ -14274,7 +16462,7 @@ var ts; } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token() === 88 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); @@ -14283,47 +16471,47 @@ var ts; function isDeclaration() { while (true) { switch (token()) { - case 102: - case 108: + case 103: + case 109: + case 75: + case 88: case 74: - case 87: - case 73: - case 81: + case 82: return true; - case 107: - case 134: + case 108: + case 136: return nextTokenIsIdentifierOnSameLine(); - case 125: - case 126: + case 127: + case 128: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 115: - case 118: - case 122: - case 110: + case 116: + case 119: + case 123: case 111: case 112: - case 128: + case 113: + case 130: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 137: + case 139: nextToken(); - return token() === 15 || token() === 69 || token() === 82; - case 89: + return token() === 16 || token() === 70 || token() === 83; + case 90: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); - case 82: + return token() === 9 || token() === 38 || + token() === 16 || ts.tokenIsIdentifierOrKeyword(token()); + case 83: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token() === 57 || token() === 38 || + token() === 16 || token() === 78 || + token() === 117) { return true; } continue; - case 113: + case 114: nextToken(); continue; default: @@ -14336,46 +16524,46 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 55: - case 23: - case 15: - case 102: - case 108: - case 87: - case 73: - case 81: + case 56: + case 24: + case 16: + case 103: + case 109: case 88: - case 79: - case 104: - case 86: - case 75: - case 70: - case 94: - case 105: - case 96: - case 98: - case 100: - case 76: - case 72: - case 85: - return true; case 74: case 82: case 89: - return isStartOfDeclaration(); - case 118: - case 122: - case 107: - case 125: - case 126: - case 134: - case 137: + case 80: + case 105: + case 87: + case 76: + case 71: + case 95: + case 106: + case 97: + case 99: + case 101: + case 77: + case 73: + case 86: return true; - case 112: - case 110: - case 111: - case 113: + case 75: + case 83: + case 90: + return isStartOfDeclaration(); + case 119: + case 123: + case 108: + case 127: case 128: + case 136: + case 139: + return true; + case 113: + case 111: + case 112: + case 114: + case 130: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -14383,73 +16571,73 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token() === 16 || token() === 20; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token()) { - case 23: + case 24: return parseEmptyStatement(); - case 15: + case 16: return parseBlock(false); - case 102: + case 103: return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 108: + case 109: if (isLetDeclaration()) { return parseVariableStatement(scanner.getStartPos(), undefined, undefined); } break; - case 87: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 73: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 88: - return parseIfStatement(); - case 79: - return parseDoStatement(); - case 104: - return parseWhileStatement(); - case 86: - return parseForOrForInOrForOfStatement(); - case 75: - return parseBreakOrContinueStatement(209); - case 70: - return parseBreakOrContinueStatement(210); - case 94: - return parseReturnStatement(); - case 105: - return parseWithStatement(); - case 96: - return parseSwitchStatement(); - case 98: - return parseThrowStatement(); - case 100: - case 72: - case 85: - return parseTryStatement(); - case 76: - return parseDebuggerStatement(); - case 55: - return parseDeclaration(); - case 118: - case 107: - case 134: - case 125: - case 126: - case 122: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 74: - case 81: - case 82: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); case 89: - case 110: + return parseIfStatement(); + case 80: + return parseDoStatement(); + case 105: + return parseWhileStatement(); + case 87: + return parseForOrForInOrForOfStatement(); + case 76: + return parseBreakOrContinueStatement(214); + case 71: + return parseBreakOrContinueStatement(215); + case 95: + return parseReturnStatement(); + case 106: + return parseWithStatement(); + case 97: + return parseSwitchStatement(); + case 99: + return parseThrowStatement(); + case 101: + case 73: + case 86: + return parseTryStatement(); + case 77: + return parseDebuggerStatement(); + case 56: + return parseDeclaration(); + case 119: + case 108: + case 136: + case 127: + case 128: + case 123: + case 75: + case 82: + case 83: + case 90: case 111: case 112: - case 115: case 113: - case 128: - case 137: + case 116: + case 114: + case 130: + case 139: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -14462,40 +16650,40 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token()) { - case 102: - case 108: - case 74: + case 103: + case 109: + case 75: return parseVariableStatement(fullStart, decorators, modifiers); - case 87: + case 88: return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 73: + case 74: return parseClassDeclaration(fullStart, decorators, modifiers); - case 107: + case 108: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 134: + case 136: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 81: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 137: - case 125: - case 126: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 89: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 139: + case 127: + case 128: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 90: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 83: nextToken(); switch (token()) { - case 77: - case 56: + case 78: + case 57: return parseExportAssignment(fullStart, decorators, modifiers); - case 116: + case 117: return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); } default: if (decorators || modifiers) { - var node = createMissingNode(239, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(244, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; node.modifiers = modifiers; @@ -14508,31 +16696,32 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token() !== 16 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { - return createNode(193); + if (token() === 25) { + return createNode(198); } - var node = createNode(169); - node.dotDotDotToken = parseOptionalToken(22); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(169); + var node = createNode(174); + node.dotDotDotToken = parseOptionalToken(23); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token() !== 55) { node.name = propertyName; } else { - parseExpected(54); + parseExpected(55); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -14540,33 +16729,33 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(167); - parseExpected(15); - node.elements = parseDelimitedList(9, parseObjectBindingElement); + var node = createNode(172); parseExpected(16); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(17); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(168); - parseExpected(19); - node.elements = parseDelimitedList(10, parseArrayBindingElement); + var node = createNode(173); parseExpected(20); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(21); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token() === 16 || token() === 20 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token() === 20) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token() === 16) { return parseObjectBindingPattern(); } return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(218); + var node = createNode(223); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { @@ -14575,21 +16764,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(219); + var node = createNode(224); switch (token()) { - case 102: + case 103: break; - case 108: + case 109: node.flags |= 1; break; - case 74: + case 75: node.flags |= 2; break; default: ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 140 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -14601,10 +16790,10 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 18; + return nextTokenIsIdentifier() && nextToken() === 19; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(200, fullStart); + var node = createNode(205, fullStart); node.decorators = decorators; node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(false); @@ -14612,29 +16801,29 @@ var ts; return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(220, fullStart); + var node = createNode(225, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(87); - node.asteriskToken = parseOptionalToken(37); + parseExpected(88); + node.asteriskToken = parseOptionalToken(38); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; var isAsync = ts.hasModifier(node, 256); - fillSignature(54, isGenerator, isAsync, false, node); + fillSignature(55, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(148, pos); + var node = createNode(150, pos); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(121); - fillSignature(54, false, false, false, node); + parseExpected(122); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(147, fullStart); + var method = createNode(149, fullStart); method.decorators = decorators; method.modifiers = modifiers; method.asteriskToken = asteriskToken; @@ -14642,12 +16831,12 @@ var ts; method.questionToken = questionToken; var isGenerator = !!asteriskToken; var isAsync = ts.hasModifier(method, 256); - fillSignature(54, isGenerator, isAsync, false, method); + fillSignature(55, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(145, fullStart); + var property = createNode(147, fullStart); property.decorators = decorators; property.modifiers = modifiers; property.name = name; @@ -14655,15 +16844,15 @@ var ts; property.type = parseTypeAnnotation(); property.initializer = ts.hasModifier(property, 32) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(65536 | 32768, parseNonParameterInitializer); + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); parseSemicolon(); return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(37); + var asteriskToken = parseOptionalToken(38); var name = parsePropertyName(); - var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + var questionToken = parseOptionalToken(54); + if (asteriskToken || token() === 18 || token() === 26) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -14678,17 +16867,17 @@ var ts; node.decorators = decorators; node.modifiers = modifiers; node.name = parsePropertyName(); - fillSignature(54, false, false, false, node); + fillSignature(55, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false); return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { - case 112: - case 110: - case 111: case 113: - case 128: + case 111: + case 112: + case 114: + case 130: return true; default: return false; @@ -14696,7 +16885,7 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token() === 56) { return true; } while (ts.isModifierKind(token())) { @@ -14706,26 +16895,26 @@ var ts; } nextToken(); } - if (token() === 37) { + if (token() === 38) { return true; } if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 19) { + if (token() === 20) { return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { + if (!ts.isKeyword(idToken) || idToken === 133 || idToken === 124) { return true; } switch (token()) { - case 17: - case 25: + case 18: + case 26: + case 55: + case 57: case 54: - case 56: - case 53: return true; default: return canParseSemicolon(); @@ -14737,10 +16926,10 @@ var ts; var decorators; while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(55)) { + if (!parseOptional(56)) { break; } - var decorator = createNode(143, decoratorStart); + var decorator = createNode(145, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); if (!decorators) { @@ -14760,7 +16949,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + if (token() === 75 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -14785,7 +16974,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 118) { + if (token() === 119) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -14796,8 +16985,8 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { - var result = createNode(198); + if (token() === 24) { + var result = createNode(203); nextToken(); return finishNode(result); } @@ -14808,7 +16997,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token() === 122) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -14817,33 +17006,33 @@ var ts; if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || - token() === 37 || - token() === 19) { + token() === 38 || + token() === 20) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_15 = createMissingNode(70, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_15, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 192); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 197); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 221); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(73); + parseExpected(74); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(true); - if (parseExpected(15)) { + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(16)) { node.members = parseClassMembers(); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -14856,17 +17045,17 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 107 && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause) { + function parseHeritageClauses() { if (isHeritageClause()) { - return parseList(20, parseHeritageClause); + return parseList(21, parseHeritageClause); } return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { - var node = createNode(251); + if (token() === 84 || token() === 107) { + var node = createNode(255); node.token = token(); nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -14875,57 +17064,57 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(194); + var node = createNode(199); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { - node.typeArguments = parseBracketedList(18, parseType, 25, 27); + if (token() === 26) { + node.typeArguments = parseBracketedList(19, parseType, 26, 28); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token() === 84 || token() === 107; } function parseClassMembers() { return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(222, fullStart); + var node = createNode(227, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(107); + parseExpected(108); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(223, fullStart); + var node = createNode(228, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(134); + parseExpected(136); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(56); + parseExpected(57); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { - var node = createNode(255, scanner.getStartPos()); + var node = createNode(260, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(224, fullStart); + var node = createNode(229, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(81); + parseExpected(82); node.name = parseIdentifier(); - if (parseExpected(15)) { + if (parseExpected(16)) { node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(16); + parseExpected(17); } else { node.members = createMissingList(); @@ -14933,10 +17122,10 @@ var ts; return addJSDocComment(finishNode(node)); } function parseModuleBlock() { - var node = createNode(226, scanner.getStartPos()); - if (parseExpected(15)) { + var node = createNode(231, scanner.getStartPos()); + if (parseExpected(16)) { node.statements = parseList(1, parseStatement); - parseExpected(16); + parseExpected(17); } else { node.statements = createMissingList(); @@ -14944,29 +17133,29 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); var namespaceFlag = flags & 16; node.decorators = decorators; node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(21) + node.body = parseOptional(22) ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(225, fullStart); + var node = createNode(230, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (token() === 137) { + if (token() === 139) { node.name = parseIdentifier(); node.flags |= 512; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token() === 16) { node.body = parseModuleBlock(); } else { @@ -14976,14 +17165,14 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = 0; - if (token() === 137) { + if (token() === 139) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } - else if (parseOptional(126)) { + else if (parseOptional(128)) { flags |= 16; } else { - parseExpected(125); + parseExpected(127); if (token() === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -14991,63 +17180,63 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token() === 131 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 17; + return nextToken() === 18; } function nextTokenIsSlash() { - return nextToken() === 39; + return nextToken() === 40; } function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228, fullStart); + var exportDeclaration = createNode(233, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; - parseExpected(116); - parseExpected(126); + parseExpected(117); + parseExpected(128); exportDeclaration.name = parseIdentifier(); - parseExpected(23); + parseSemicolon(); return finishNode(exportDeclaration); } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(89); + parseExpected(90); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { - var importEqualsDeclaration = createNode(229, fullStart); + if (token() !== 25 && token() !== 138) { + var importEqualsDeclaration = createNode(234, fullStart); importEqualsDeclaration.decorators = decorators; importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; - parseExpected(56); + parseExpected(57); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); return addJSDocComment(finishNode(importEqualsDeclaration)); } } - var importDeclaration = createNode(230, fullStart); + var importDeclaration = createNode(235, fullStart); importDeclaration.decorators = decorators; importDeclaration.modifiers = modifiers; if (identifier || - token() === 37 || - token() === 15) { + token() === 38 || + token() === 16) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(136); + parseExpected(138); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(231, fullStart); + var importClause = createNode(236, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || - parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + parseOptional(25)) { + importClause.namedBindings = token() === 38 ? parseNamespaceImport() : parseNamedImportsOrExports(238); } return finishNode(importClause); } @@ -15057,11 +17246,11 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(240); - parseExpected(129); - parseExpected(17); - node.expression = parseModuleSpecifier(); + var node = createNode(245); + parseExpected(131); parseExpected(18); + node.expression = parseModuleSpecifier(); + parseExpected(19); return finishNode(node); } function parseModuleSpecifier() { @@ -15075,22 +17264,22 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(232); - parseExpected(37); - parseExpected(116); + var namespaceImport = createNode(237); + parseExpected(38); + parseExpected(117); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 233 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(22, kind === 238 ? parseImportSpecifier : parseExportSpecifier, 16, 17); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(238); + return parseImportOrExportSpecifier(243); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(234); + return parseImportOrExportSpecifier(239); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -15098,9 +17287,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token() === 117) { node.propertyName = identifierName; - parseExpected(116); + parseExpected(117); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -15109,23 +17298,23 @@ var ts; else { node.name = identifierName; } - if (kind === 234 && checkIdentifierIsKeyword) { + if (kind === 239 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(236, fullStart); + var node = createNode(241, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(37)) { - parseExpected(136); + if (parseOptional(38)) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(136); + node.exportClause = parseNamedImportsOrExports(242); + if (token() === 138 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(138); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -15133,14 +17322,14 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(235, fullStart); + var node = createNode(240, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(56)) { + if (parseOptional(57)) { node.isExportEquals = true; } else { - parseExpected(77); + parseExpected(78); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -15212,10 +17401,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 229 && node.moduleReference.kind === 240 - || node.kind === 230 + || node.kind === 234 && node.moduleReference.kind === 245 || node.kind === 235 - || node.kind === 236 + || node.kind === 240 + || node.kind === 241 ? node : undefined; }); @@ -15224,24 +17413,24 @@ var ts; (function (JSDocParser) { function isJSDocType() { switch (token()) { - case 37: - case 53: - case 17: - case 19: - case 49: - case 15: - case 87: - case 22: - case 92: - case 97: + case 38: + case 54: + case 18: + case 20: + case 50: + case 16: + case 88: + case 23: + case 93: + case 98: return true; } return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); - sourceFile = createSourceFile("file.js", 2, 1); + initializeState(content, 5, undefined, 1); + sourceFile = createSourceFile("file.js", 5, 1); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15251,23 +17440,23 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression() { - var result = createNode(257, scanner.getTokenPos()); - parseExpected(15); - result.type = parseJSDocTopLevelType(); + var result = createNode(262, scanner.getTokenPos()); parseExpected(16); + result.type = parseJSDocTopLevelType(); + parseExpected(17); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { - var unionType = createNode(261, type.pos); + if (token() === 48) { + var unionType = createNode(266, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { - var optionalType = createNode(268, type.pos); + if (token() === 57) { + var optionalType = createNode(273, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -15277,21 +17466,21 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { - var arrayType = createNode(260, type.pos); + if (token() === 20) { + var arrayType = createNode(265, type.pos); arrayType.elementType = type; nextToken(); - parseExpected(20); + parseExpected(21); type = finishNode(arrayType); } - else if (token() === 53) { - var nullableType = createNode(263, type.pos); + else if (token() === 54) { + var nullableType = createNode(268, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { - var nonNullableType = createNode(264, type.pos); + else if (token() === 50) { + var nonNullableType = createNode(269, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -15304,94 +17493,94 @@ var ts; } function parseBasicTypeExpression() { switch (token()) { - case 37: + case 38: return parseJSDocAllType(); - case 53: + case 54: return parseJSDocUnknownOrNullableType(); - case 17: + case 18: return parseJSDocUnionType(); - case 19: + case 20: return parseJSDocTupleType(); - case 49: + case 50: return parseJSDocNonNullableType(); - case 15: + case 16: return parseJSDocRecordType(); - case 87: + case 88: return parseJSDocFunctionType(); - case 22: + case 23: return parseJSDocVariadicType(); - case 92: - return parseJSDocConstructorType(); - case 97: - return parseJSDocThisType(); - case 117: - case 132: - case 130: - case 120: - case 133: - case 103: case 93: + return parseJSDocConstructorType(); + case 98: + return parseJSDocThisType(); + case 118: + case 134: + case 132: + case 121: case 135: - case 127: + case 104: + case 94: + case 137: + case 129: return parseTokenNode(); case 9: case 8: - case 99: - case 84: + case 100: + case 85: return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(272); + var result = createNode(277); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(271); + var result = createNode(276); nextToken(); - parseExpected(54); + parseExpected(55); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(270); + var result = createNode(275); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(269); + var result = createNode(274); nextToken(); - parseExpected(17); - result.parameters = parseDelimitedList(22, parseJSDocParameter); - checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + result.parameters = parseDelimitedList(23, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(19); + if (token() === 55) { nextToken(); result.type = parseJSDocType(); } return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(142); + var parameter = createNode(144); parameter.type = parseJSDocType(); - if (parseOptional(56)) { - parameter.questionToken = createNode(56); + if (parseOptional(57)) { + parameter.questionToken = createNode(57); } return finishNode(parameter); } function parseJSDocTypeReference() { - var result = createNode(267); + var result = createNode(272); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); } else { - while (parseOptional(21)) { - if (token() === 25) { + while (parseOptional(22)) { + if (token() === 26) { result.typeArguments = parseTypeArguments(); break; } @@ -15404,10 +17593,10 @@ var ts; } function parseTypeArguments() { nextToken(); - var typeArguments = parseDelimitedList(23, parseJSDocType); + var typeArguments = parseDelimitedList(24, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); - parseExpected(27); + parseExpected(28); return typeArguments; } function checkForEmptyTypeArgumentList(typeArguments) { @@ -15418,28 +17607,28 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(139, left.pos); + var result = createNode(141, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(265); + var result = createNode(270); result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(264); + var result = createNode(269); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(262); + var result = createNode(267); nextToken(); - result.types = parseDelimitedList(25, parseJSDocType); + result.types = parseDelimitedList(26, parseJSDocType); checkForTrailingComma(result.types); - parseExpected(20); + parseExpected(21); return finishNode(result); } function checkForTrailingComma(list) { @@ -15449,51 +17638,51 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(261); + var result = createNode(266); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18); + parseExpected(19); return finishNode(result); } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(47)) { + while (parseOptional(48)) { types.push(parseJSDocType()); } types.end = scanner.getStartPos(); return types; } function parseJSDocAllType() { - var result = createNode(258); + var result = createNode(263); nextToken(); return finishNode(result); } function parseJSDocLiteralType() { - var result = createNode(282); + var result = createNode(288); result.literal = parseLiteralTypeNode(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { - var result = createNode(259, pos); + if (token() === 25 || + token() === 17 || + token() === 19 || + token() === 28 || + token() === 57 || + token() === 48) { + var result = createNode(264, pos); return finishNode(result); } else { - var result = createNode(263, pos); + var result = createNode(268, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2, undefined, 1); + initializeState(content, 5, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -15547,11 +17736,12 @@ var ts; } if (token() === 4) { state = 0; + indent = 0; nextJSDocToken(); } while (token() !== 1) { switch (token()) { - case 55: + case 56: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); @@ -15569,9 +17759,9 @@ var ts; state = 0; indent = 0; break; - case 37: + case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -15580,13 +17770,16 @@ var ts; indent += asterisk.length; } break; - case 69: + case 70: pushComment(scanner.getTokenText()); state = 2; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -15594,6 +17787,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -15626,7 +17820,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(273, start); + var result = createNode(278, start); result.tags = tags; result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -15637,8 +17831,8 @@ var ts; } } function parseTag(indent) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getTokenPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15649,6 +17843,9 @@ var ts; var tag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -15689,7 +17886,7 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 55 && token() !== 1) { + while (token() !== 56 && token() !== 1) { switch (token()) { case 4: if (state >= 1) { @@ -15698,7 +17895,7 @@ var ts; } indent = 0; break; - case 55: + case 56: break; case 5: if (state === 2) { @@ -15712,7 +17909,7 @@ var ts; indent += whitespace.length; } break; - case 37: + case 38: if (state === 0) { state = 1; indent += scanner.getTokenText().length; @@ -15723,7 +17920,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 55) { + if (token() === 56) { break; } nextJSDocToken(); @@ -15733,7 +17930,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(274, atToken.pos); + var result = createNode(279, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -15751,7 +17948,7 @@ var ts; function tryParseTypeExpression() { return tryParse(function () { skipWhitespace(); - if (token() !== 15) { + if (token() !== 16) { return undefined; } return parseJSDocTypeExpression(); @@ -15762,14 +17959,14 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (parseOptionalToken(19)) { + if (parseOptionalToken(20)) { name = parseJSDocIdentifierName(); skipWhitespace(); isBracketed = true; - if (parseOptionalToken(56)) { + if (parseOptionalToken(57)) { parseExpression(); } - parseExpected(20); + parseExpected(21); } else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); @@ -15788,7 +17985,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(275, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -15799,20 +17996,20 @@ var ts; return finishNode(result); } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 276; })) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(276, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 277; })) { + if (ts.forEach(tags, function (t) { return t.kind === 283; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(277, atToken.pos); + var result = createNode(283, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -15827,28 +18024,43 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(280, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.name = name; result.typeExpression = typeExpression; return finishNode(result); } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(279, atToken.pos); + var typedefTag = createNode(285, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (rightNode.kind !== 70) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); if (typeExpression) { - if (typeExpression.type.kind === 267) { + if (typeExpression.type.kind === 272) { var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + if (jsDocTypeReference.name.kind === 70) { + var name_16 = jsDocTypeReference.name; + if (name_16.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15862,7 +18074,7 @@ var ts; } return finishNode(typedefTag); function scanChildTags() { - var jsDocTypeLiteral = createNode(281, scanner.getStartPos()); + var jsDocTypeLiteral = createNode(287, scanner.getStartPos()); var resumePos = scanner.getStartPos(); var canParseTag = true; var seenAsterisk = false; @@ -15870,7 +18082,7 @@ var ts; while (token() !== 1 && !parentTagTerminated) { nextJSDocToken(); switch (token()) { - case 55: + case 56: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); if (!parentTagTerminated) { @@ -15884,13 +18096,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 37: + case 38: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 69: + case 70: canParseTag = false; case 1: break; @@ -15899,10 +18111,25 @@ var ts; scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(22)) { + var jsDocNamespaceNode = createNode(230, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return jsDocNamespaceNode; + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); - var atToken = createNode(55, scanner.getStartPos()); + ts.Debug.assert(token() === 56); + var atToken = createNode(56, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15919,32 +18146,35 @@ var ts; return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } var propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = []; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + return false; } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 278; })) { + if (ts.forEach(tags, function (t) { return t.kind === 284; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_17 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_17) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(143, name_17.pos); + typeParameter.name = name_17; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token() === 25) { nextJSDocToken(); skipWhitespace(); } @@ -15952,7 +18182,7 @@ var ts; break; } } - var result = createNode(278, atToken.pos); + var result = createNode(284, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -15973,7 +18203,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(69, pos); + var result = createNode(70, pos); result.text = content.substring(pos, end); finishNode(result, end); nextJSDocToken(); @@ -16032,8 +18262,8 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); } @@ -16044,8 +18274,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += 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); } } @@ -16054,7 +18284,7 @@ var ts; switch (node.kind) { case 9: case 8: - case 69: + case 70: return true; } return false; @@ -16117,8 +18347,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -16271,16 +18501,16 @@ var ts; var ts; (function (ts) { function getModuleInstanceState(node) { - if (node.kind === 222 || node.kind === 223) { + if (node.kind === 227 || node.kind === 228) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 230 || node.kind === 229) && !(ts.hasModifier(node, 1))) { + else if ((node.kind === 235 || node.kind === 234) && !(ts.hasModifier(node, 1))) { return 0; } - else if (node.kind === 226) { + else if (node.kind === 231) { var state_1 = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -16296,10 +18526,13 @@ var ts; }); return state_1; } - else if (node.kind === 225) { + else if (node.kind === 230) { var body = node.body; return body ? getModuleInstanceState(body) : 1; } + else if (node.kind === 70 && node.isInJSDocNamespace) { + return 0; + } else { return 1; } @@ -16344,7 +18577,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +18607,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16394,7 +18635,7 @@ var ts; if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 225)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230)) { symbol.valueDeclaration = node; } } @@ -16404,9 +18645,9 @@ var ts; if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 140) { + if (node.name.kind === 142) { var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -16415,21 +18656,21 @@ var ts; return node.name.text; } switch (node.kind) { - case 148: + case 150: return "__constructor"; - case 156: - case 151: - return "__call"; - case 157: - case 152: - return "__new"; + case 158: case 153: + return "__call"; + case 159: + case 154: + return "__new"; + case 155: return "__index"; - case 236: + case 241: return "__export"; - case 235: + case 240: return node.isExportEquals ? "export=" : "default"; - case 187: + case 192: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2: return "export="; @@ -16441,23 +18682,23 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 220: - case 221: + case 225: + case 226: return ts.hasModifier(node, 512) ? "default" : undefined; - case 269: + case 274: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 142: - ts.Debug.assert(node.parent.kind === 269); + case 144: + ts.Debug.assert(node.parent.kind === 274); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 279: + case 285: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 200) { + if (parentNode && parentNode.kind === 205) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { + if (nameIdentifier.kind === 70) { nameFromParentNode = nameIdentifier.text; } } @@ -16492,11 +18733,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 240 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16512,7 +18759,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 8388608) { - if (node.kind === 238 || (node.kind === 229 && hasExportModifier)) { + if (node.kind === 243 || (node.kind === 234 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -16520,7 +18767,11 @@ var ts; } } else { - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) { + var isJSDocTypedefInJSDocNamespace = node.kind === 285 && + node.name && + node.name.kind === 70 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793064 ? 2097152 : 0) | (symbolFlags & 1920 ? 4194304 : 0); @@ -16555,13 +18806,13 @@ var ts; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !!ts.getImmediatelyInvokedFunctionExpression(node); + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -16571,13 +18822,13 @@ var ts; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~32128; + node.flags &= ~1408; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { node.flags |= 128; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 256) { + if (node.kind === 261) { node.flags |= emitFlags; } if (isIIFE) { @@ -16612,6 +18863,7 @@ var ts; skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -16620,101 +18872,124 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - ts.forEach(node.jsDocComments, bind); + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + ts.forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - ts.forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { - case 205: + case 210: bindWhileStatement(node); break; - case 204: + case 209: bindDoStatement(node); break; - case 206: + case 211: bindForStatement(node); break; - case 207: - case 208: + case 212: + case 213: bindForInOrForOfStatement(node); break; - case 203: + case 208: bindIfStatement(node); break; - case 211: - case 215: + case 216: + case 220: bindReturnOrThrow(node); break; - case 210: - case 209: + case 215: + case 214: bindBreakOrContinueStatement(node); break; - case 216: + case 221: bindTryStatement(node); break; - case 213: + case 218: bindSwitchStatement(node); break; - case 227: + case 232: bindCaseBlock(node); break; - case 249: + case 253: bindCaseClause(node); break; - case 214: + case 219: bindLabeledStatement(node); break; - case 185: + case 190: bindPrefixUnaryExpressionFlow(node); break; - case 186: + case 191: bindPostfixUnaryExpressionFlow(node); break; - case 187: + case 192: bindBinaryExpressionFlow(node); break; - case 181: + case 186: bindDeleteExpressionFlow(node); break; - case 188: + case 193: bindConditionalExpressionFlow(node); break; - case 218: + case 223: bindVariableDeclarationFlow(node); break; - case 174: + case 179: bindCallExpressionFlow(node); break; default: - ts.forEachChild(node, bind); + bindEachChild(node); break; } } function isNarrowingExpression(expr) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return isNarrowableReference(expr); - case 174: + case 179: return hasNarrowableArgument(expr); - case 178: + case 183: return isNarrowingExpression(expr.expression); - case 187: + case 192: return isNarrowingBinaryExpression(expr); - case 185: - return expr.operator === 49 && isNarrowingExpression(expr.operand); + case 190: + return expr.operator === 50 && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); + return expr.kind === 70 || + expr.kind === 98 || + expr.kind === 177 && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -16725,41 +19000,41 @@ var ts; } } } - if (expr.expression.kind === 172 && + if (expr.expression.kind === 177 && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 187 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableReference(expr.left); - case 30: case 31: case 32: case 33: + case 34: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 91: + case 92: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 178: + case 183: return isNarrowableOperand(expr.expression); - case 187: + case 192: switch (expr.operatorToken.kind) { - case 56: + case 57: return isNarrowableOperand(expr.left); - case 24: + case 25: return isNarrowableOperand(expr.right); } } @@ -16778,7 +19053,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 256 ? 512 : 256; + flow.flags |= flow.flags & 512 ? 1024 : 512; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -16793,8 +19068,8 @@ var ts; if (!expression) { return flags & 32 ? antecedent : unreachableFlow; } - if (expression.kind === 99 && flags & 64 || - expression.kind === 84 && flags & 32) { + if (expression.kind === 100 && flags & 64 || + expression.kind === 85 && flags & 32) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -16828,6 +19103,14 @@ var ts; node: node }; } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } function finishFlowLabel(flow) { var antecedents = flow.antecedents; if (!antecedents) { @@ -16841,34 +19124,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 203: - case 205: - case 204: + case 208: + case 210: + case 209: return parent.expression === node; - case 206: - case 188: + case 211: + case 193: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 178) { + if (node.kind === 183) { node = node.expression; } - else if (node.kind === 185 && node.operator === 49) { + else if (node.kind === 190 && node.operator === 50) { node = node.operand; } else { - return node.kind === 187 && (node.operatorToken.kind === 51 || - node.operatorToken.kind === 52); + return node.kind === 192 && (node.operatorToken.kind === 52 || + node.operatorToken.kind === 53); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 178 || - node.parent.kind === 185 && - node.parent.operator === 49) { + while (node.parent.kind === 183 || + node.parent.kind === 190 && + node.parent.operator === 50) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -16909,8 +19192,11 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var preConditionLabel = createBranchLabel(); - var postDoLabel = createBranchLabel(); + var enclosingLabeledStatement = node.parent.kind === 219 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -16941,7 +19227,7 @@ var ts; bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 219) { + if (node.initializer.kind !== 224) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -16963,7 +19249,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 211) { + if (node.kind === 216) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -16982,8 +19268,8 @@ var ts; } return undefined; } - function bindbreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 210 ? breakTarget : continueTarget; + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 215 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -16995,28 +19281,41 @@ var ts; var activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node) { - var postFinallyLabel = createBranchLabel(); + var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); } - currentFlow = finishFlowLabel(postFinallyLabel); } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17027,7 +19326,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -17037,6 +19336,8 @@ var ts; currentFlow = finishFlowLabel(postSwitchLabel); } function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; var clauses = node.clauses; var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { @@ -17056,13 +19357,15 @@ var ts; errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { var saveCurrentFlow = currentFlow; currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - ts.forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name, breakTarget, continueTarget) { var activeLabel = { @@ -17088,11 +19391,13 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== 209) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node) { - if (node.kind === 187 && node.operatorToken.kind === 56) { + if (node.kind === 192 && node.operatorToken.kind === 57) { bindAssignmentTargetFlow(node.left); } else { @@ -17103,10 +19408,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 170) { + else if (node.kind === 175) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 191) { + if (e.kind === 196) { bindAssignmentTargetFlow(e.expression); } else { @@ -17114,21 +19419,24 @@ var ts; } } } - else if (node.kind === 171) { + else if (node.kind === 176) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 253) { + if (p.kind === 257) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 254) { + else if (p.kind === 258) { bindAssignmentTargetFlow(p.name); } + else if (p.kind === 259) { + bindAssignmentTargetFlow(p.expression); + } } } } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -17139,30 +19447,30 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 49) { + if (node.operator === 50) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - ts.forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.operator === 41 || node.operator === 42) { + bindEachChild(node); + if (node.operator === 42 || node.operator === 43) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 51 || operator === 52) { + if (operator === 52 || operator === 53) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -17173,15 +19481,21 @@ var ts; } } else { - ts.forEachChild(node, bind); - if (operator === 56 && !ts.isAssignmentTarget(node)) { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === 57 && node.left.kind === 178) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.expression.kind === 172) { + bindEachChild(node); + if (node.expression.kind === 177) { bindAssignmentTargetFlow(node.expression); } } @@ -17191,9 +19505,11 @@ var ts; var postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -17211,69 +19527,79 @@ var ts; } } function bindVariableDeclarationFlow(node) { - ts.forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === 207 || node.parent.parent.kind === 208) { + bindEachChild(node); + if (node.initializer || node.parent.parent.kind === 212 || node.parent.parent.kind === 213) { bindInitializedVariableFlow(node); } } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 178) { + while (expr.kind === 183) { expr = expr.expression; } - if (expr.kind === 179 || expr.kind === 180) { - ts.forEach(node.typeArguments, bind); - ts.forEach(node.arguments, bind); + if (expr.kind === 184 || expr.kind === 185) { + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - ts.forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === 177) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } function getContainerFlags(node) { switch (node.kind) { - case 192: - case 221: - case 224: - case 171: - case 159: - case 281: - case 265: + case 197: + case 226: + case 229: + case 176: + case 161: + case 287: + case 270: return 1; - case 222: + case 227: return 1 | 64; - case 269: - case 225: - case 223: + case 274: + case 230: + case 228: + case 170: return 1 | 32; - case 256: + case 261: return 1 | 4 | 32; - case 148: - case 220: - case 147: - case 146: case 149: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 150: + case 225: + case 148: case 151: case 152: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: return 1 | 4 | 32 | 8; - case 179: - case 180: + case 184: + case 185: return 1 | 4 | 32 | 8 | 16; - case 226: + case 231: return 4; - case 145: + case 147: return node.initializer ? 4 : 0; - case 252: - case 206: - case 207: - case 208: - case 227: + case 256: + case 211: + case 212: + case 213: + case 232: return 2; - case 199: + case 204: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -17289,36 +19615,37 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 225: + case 230: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 256: + case 261: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 192: - case 221: + case 197: + case 226: return declareClassMember(node, symbolFlags, symbolExcludes); - case 224: + case 229: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 159: - case 171: - case 222: - case 265: - case 281: + case 161: + case 176: + case 227: + case 270: + case 287: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 156: - case 157: + case 158: + case 159: + case 153: + case 154: + case 155: + case 149: + case 148: + case 150: case 151: case 152: - case 153: - case 147: - case 146: - case 148: - case 149: - case 150: - case 220: - case 179: - case 180: - case 269: - case 223: + case 225: + case 184: + case 185: + case 274: + case 228: + case 170: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -17333,11 +19660,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 256 ? node : node.body; - if (body && (body.kind === 256 || body.kind === 226)) { + var body = node.kind === 261 ? node : node.body; + if (body && (body.kind === 261 || body.kind === 231)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 236 || stat.kind === 235) { + if (stat.kind === 241 || stat.kind === 240) { return true; } } @@ -17413,11 +19740,11 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.name.kind !== 69) { + if (prop.kind === 259 || prop.name.kind !== 70) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 253 || prop.kind === 254 || prop.kind === 147 + var currentKind = prop.kind === 257 || prop.kind === 258 || prop.kind === 149 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -17439,10 +19766,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 225: + case 230: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 256: + case 261: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -17460,8 +19787,8 @@ var ts; } function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 106 && - node.originalKeywordKind <= 114 && + node.originalKeywordKind >= 107 && + node.originalKeywordKind <= 115 && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { if (!file.parseDiagnostics.length) { @@ -17489,17 +19816,17 @@ var ts; } } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 69) { + if (inStrictMode && node.expression.kind === 70) { var span_2 = ts.getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && + return node.kind === 70 && (node.text === "eval" || node.text === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69) { + if (name && name.kind === 70) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span_3 = ts.getErrorSpanForNode(file, name); @@ -17532,8 +19859,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 256 && - blockScopeContainer.kind !== 225 && + if (blockScopeContainer.kind !== 261 && + blockScopeContainer.kind !== 230 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -17552,7 +19879,7 @@ var ts; } function checkStrictModePrefixUnaryExpression(node) { if (inStrictMode) { - if (node.operator === 41 || node.operator === 42) { + if (node.operator === 42 || node.operator === 43) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -17576,7 +19903,7 @@ var ts; node.parent = parent; var saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 138) { + if (node.kind > 140) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -17595,8 +19922,8 @@ var ts; } function updateStrictModeStatementList(statements) { if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -17613,18 +19940,26 @@ var ts; } function bindWorker(node) { switch (node.kind) { - case 69: - case 97: - if (currentFlow && (ts.isExpression(node) || parent.kind === 254)) { + case 70: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 285) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 98: + if (currentFlow && (ts.isExpression(node) || parent.kind === 258)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 172: + case 177: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } break; - case 187: + case 192: if (ts.isInJavaScriptFile(node)) { var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { @@ -17647,120 +19982,137 @@ var ts; } } return checkStrictModeBinaryExpression(node); - case 252: + case 256: return checkStrictModeCatchClause(node); - case 181: + case 186: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 186: + case 191: return checkStrictModePostfixUnaryExpression(node); - case 185: + case 190: return checkStrictModePrefixUnaryExpression(node); - case 212: + case 217: return checkStrictModeWithStatement(node); - case 165: + case 167: seenThisKeyword = true; return; - case 154: + case 156: return checkTypePredicate(node); - case 141: + case 143: return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 142: - return bindParameter(node); - case 218: - case 169: - return bindVariableDeclarationOrBindingElement(node); - case 145: case 144: - case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); - case 280: - return bindJSDocProperty(node); - case 253: - case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 247: - emitFlags |= 16384; - return; - case 151: - case 152: - case 153: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); + return bindParameter(node); + case 223: + case 174: + return bindVariableDeclarationOrBindingElement(node); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 220: - return bindFunctionDeclaration(node); - case 148: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 271: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + case 286: + return bindJSDocProperty(node); + case 257: + case 258: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 260: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 259: + case 251: + var root = container; + var hasRest = false; + while (root.parent) { + if (root.kind === 176 && + root.parent.kind === 192 && + root.parent.operatorToken.kind === 57 && + root.parent.left === root) { + hasRest = true; + break; + } + root = root.parent; + } + return; + case 153: + case 154: + case 155: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 149: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 148: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 225: + return bindFunctionDeclaration(node); case 150: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 151: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 152: return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 156: - case 157: - case 269: - return bindFunctionOrConstructorType(node); + case 158: case 159: - case 281: - case 265: + case 274: + return bindFunctionOrConstructorType(node); + case 161: + case 170: + case 287: + case 270: return bindAnonymousDeclaration(node, 2048, "__type"); - case 171: + case 176: return bindObjectLiteralExpression(node); - case 179: - case 180: + case 184: + case 185: return bindFunctionExpression(node); - case 174: + case 179: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 192: - case 221: + case 197: + case 226: inStrictMode = true; return bindClassLikeDeclaration(node); - case 222: + case 227: return bindBlockScopedDeclaration(node, 64, 792968); - case 279: - case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 224: - return bindEnumDeclaration(node); - case 225: - return bindModuleDeclaration(node); - case 229: - case 232: - case 234: - case 238: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 285: + if (!node.fullName || node.fullName.kind === 70) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; case 228: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 229: + return bindEnumDeclaration(node); + case 230: + return bindModuleDeclaration(node); + case 234: + case 237: + case 239: + case 243: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 233: return bindNamespaceExportDeclaration(node); - case 231: - return bindImportClause(node); case 236: + return bindImportClause(node); + case 241: return bindExportDeclaration(node); - case 235: + case 240: return bindExportAssignment(node); - case 256: + case 261: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 199: + case 204: if (!ts.isFunctionLike(node.parent)) { return; } - case 226: + case 231: return updateStrictModeStatementList(node.statements); } } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 69) { + if (parameterName && parameterName.kind === 70) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 165) { + if (parameterName && parameterName.kind === 167) { seenThisKeyword = true; } bind(type); @@ -17779,27 +20131,27 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 240 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 256) { + if (node.parent.kind !== 261) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17823,7 +20175,9 @@ var ts; function setCommonJsModuleIndicator(node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } function bindExportsPropertyAssignment(node) { @@ -17836,11 +20190,11 @@ var ts; } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { + if (container.kind === 225 || container.kind === 184) { container.symbol.members = container.symbol.members || ts.createMap(); declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } - else if (container.kind === 148) { + else if (container.kind === 150) { var saveContainer = container; container = container.parent; var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); @@ -17872,15 +20226,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 1024; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; - } - } - if (node.kind === 221) { + if (node.kind === 226) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -17923,11 +20269,6 @@ var ts; } } function bindParameter(node) { - if (!ts.isDeclarationFile(file) && - !ts.isInAmbientContext(node) && - ts.nodeIsDecorated(node)) { - emitFlags |= (2048 | 4096); - } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); } @@ -17945,7 +20286,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } checkStrictModeFunctionName(node); @@ -17960,7 +20301,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; + emitFlags |= 1024; } } if (currentFlow) { @@ -17973,12 +20314,12 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048; + emitFlags |= 1024; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -17995,15 +20336,15 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 201) || - node.kind === 221 || - (node.kind === 225 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 224 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 206) || + node.kind === 226 || + (node.kind === 230 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 229 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 200 || + (node.kind !== 205 || ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -18017,52 +20358,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 174: - return computeCallExpression(node, subtreeFlags); - case 225: - return computeModuleDeclaration(node, subtreeFlags); - case 178: - return computeParenthesizedExpression(node, subtreeFlags); - case 187: - return computeBinaryExpression(node, subtreeFlags); - case 202: - return computeExpressionStatement(node, subtreeFlags); - case 142: - return computeParameter(node, subtreeFlags); - case 180: - return computeArrowFunction(node, subtreeFlags); case 179: - return computeFunctionExpression(node, subtreeFlags); - case 220: - return computeFunctionDeclaration(node, subtreeFlags); - case 218: - return computeVariableDeclaration(node, subtreeFlags); - case 219: - return computeVariableDeclarationList(node, subtreeFlags); - case 200: - return computeVariableStatement(node, subtreeFlags); - case 214: - return computeLabeledStatement(node, subtreeFlags); - case 221: - return computeClassDeclaration(node, subtreeFlags); + return computeCallExpression(node, subtreeFlags); + case 180: + return computeNewExpression(node, subtreeFlags); + case 230: + return computeModuleDeclaration(node, subtreeFlags); + case 183: + return computeParenthesizedExpression(node, subtreeFlags); case 192: + return computeBinaryExpression(node, subtreeFlags); + case 207: + return computeExpressionStatement(node, subtreeFlags); + case 144: + return computeParameter(node, subtreeFlags); + case 185: + return computeArrowFunction(node, subtreeFlags); + case 184: + return computeFunctionExpression(node, subtreeFlags); + case 225: + return computeFunctionDeclaration(node, subtreeFlags); + case 223: + return computeVariableDeclaration(node, subtreeFlags); + case 224: + return computeVariableDeclarationList(node, subtreeFlags); + case 205: + return computeVariableStatement(node, subtreeFlags); + case 219: + return computeLabeledStatement(node, subtreeFlags); + case 226: + return computeClassDeclaration(node, subtreeFlags); + case 197: return computeClassExpression(node, subtreeFlags); - case 251: + case 255: return computeHeritageClause(node, subtreeFlags); - case 194: + case 256: + return computeCatchClause(node, subtreeFlags); + case 199: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 148: - return computeConstructor(node, subtreeFlags); - case 145: - return computePropertyDeclaration(node, subtreeFlags); - case 147: - return computeMethod(node, subtreeFlags); - case 149: case 150: + return computeConstructor(node, subtreeFlags); + case 147: + return computePropertyDeclaration(node, subtreeFlags); + case 149: + return computeMethod(node, subtreeFlags); + case 151: + case 152: return computeAccessor(node, subtreeFlags); - case 229: + case 234: return computeImportEquals(node, subtreeFlags); - case 172: + case 177: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -18073,40 +20418,55 @@ var ts; var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (subtreeFlags & 262144 + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288 || isSuperOrSuperProperty(expression, expressionKind)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537133909; + return transformFlags & ~537396545; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 95: + case 96: return true; - case 172: - case 173: + case 177: + case 178: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 95; + return expressionKind === 96; } return false; } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 56 - && (leftKind === 171 - || leftKind === 170)) { - transformFlags |= 192 | 256; + if (operatorTokenKind === 57 && leftKind === 176) { + transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 38 - || operatorTokenKind === 60) { - transformFlags |= 48; + else if (operatorTokenKind === 57 && leftKind === 175) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 39 + || operatorTokenKind === 61) { + transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18114,36 +20474,38 @@ var ts; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken) { - transformFlags |= 3; - } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { - transformFlags |= 3 | 131072; + transformFlags |= 3 | 262144; } - if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { - transformFlags |= 192 | 65536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~536872257; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 195 - || expressionKind === 177) { + if (expressionKind === 200 + || expressionKind === 182) { transformFlags |= 3; } - if (expressionTransformFlags & 256) { - transformFlags |= 256; + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -18153,35 +20515,36 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 137216) - || (modifierFlags & 1)) { + if ((subtreeFlags & 274432) + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 137216) { + if (subtreeFlags & 274432 + || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + if (subtreeFlags & 65536) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537590613; + return transformFlags & ~539358529; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 83: + case 84: transformFlags |= 192; break; - case 106: + case 107: transformFlags |= 3; break; default: @@ -18189,7 +20552,15 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18197,127 +20568,155 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var body = node.body; - if (body === undefined) { + if (ts.hasModifier(node, 2270) + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - var typeParameters = node.typeParameters; - var asteriskToken = node.asteriskToken; - if (!body - || typeParameters - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body - || (modifierFlags & (256 | 128)) - || (subtreeFlags & 2048)) { + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { transformFlags |= 3; } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550593365; + return transformFlags & ~601015617; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer) { - transformFlags |= 4096; + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - var asteriskToken = node.asteriskToken; if (!body || (modifierFlags & 2)) { transformFlags = 3; } else { - transformFlags = subtreeFlags | 8388608; - if (modifierFlags & 1) { - transformFlags |= 3 | 192; - } - if (modifierFlags & 256) { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (modifierFlags & 256) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var asteriskToken = node.asteriskToken; - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 81920) { + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { - transformFlags |= 1536; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550726485; + return transformFlags & ~601281857; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 256) { + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { transformFlags |= 3; } - if (subtreeFlags & 8192) { - transformFlags |= 16384; + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~550710101; + return transformFlags & ~601249089; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (expressionKind === 95) { - transformFlags |= 8192; + if (expressionKind === 96) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - var nameKind = node.name.kind; - if (nameKind === 167 || nameKind === 168) { - transformFlags |= 192 | 2097152; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -18328,24 +20727,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (modifierFlags & 1) { - transformFlags |= 192 | 3; - } - if (declarationListTransformFlags & 2097152) { + if (declarationListTransformFlags & 8388608) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 1048576 + if (subtreeFlags & 4194304 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18353,15 +20749,15 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 256) { + if (node.expression.transformFlags & 1024) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536871765; + return transformFlags & ~536872257; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -18370,78 +20766,76 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546335573; + return transformFlags & ~574674241; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608; - if (subtreeFlags & 2097152) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 1048576; + transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~538968917; + return transformFlags & ~546309441; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536871765; + var excludeFlags = 536872257; switch (kind) { - case 112: - case 110: + case 119: + case 189: + transformFlags |= 16; + break; + case 113: case 111: - case 115: - case 122: - case 118: - case 74: - case 184: - case 224: - case 255: - case 177: - case 195: - case 196: - case 128: + case 112: + case 116: + case 123: + case 75: + case 229: + case 260: + case 182: + case 200: + case 201: + case 130: transformFlags |= 3; break; - case 241: - case 242: - case 243: - case 244: - case 245: case 246: case 247: case 248: - transformFlags |= 12; + case 10: + case 249: + case 250: + case 251: + case 252: + transformFlags |= 4; break; - case 82: - transformFlags |= 192 | 3; - break; - case 77: - case 11: + case 213: + transformFlags |= 8; case 12: case 13: case 14: - case 189: - case 176: - case 254: - case 208: + case 15: + case 194: + case 181: + case 258: + case 114: transformFlags |= 192; break; - case 190: - transformFlags |= 192 | 4194304; + case 195: + transformFlags |= 192 | 16777216; break; - case 117: - case 130: - case 127: + case 118: case 132: - case 120: - case 133: - case 103: - case 141: - case 144: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: case 146: - case 151: - case 152: + case 148: case 153: case 154: case 155: @@ -18454,73 +20848,154 @@ var ts; case 162: case 163: case 164: - case 222: - case 223: case 165: case 166: + case 227: + case 228: + case 167: + case 168: + case 169: + case 170: + case 171: transformFlags = 3; excludeFlags = -3; break; - case 140: - transformFlags |= 524288; - if (subtreeFlags & 8192) { - transformFlags |= 32768; + case 142: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; } break; - case 191: - transformFlags |= 262144; + case 196: + transformFlags |= 192 | 524288; break; - case 95: + case 259: + transformFlags |= 8 | 1048576; + break; + case 96: transformFlags |= 192; break; - case 97: - transformFlags |= 8192; + case 98: + transformFlags |= 16384; break; - case 167: - case 168: - transformFlags |= 192 | 2097152; + case 172: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; break; - case 143: - transformFlags |= 3 | 2048; + case 173: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; break; - case 171: - excludeFlags = 537430869; + case 174: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 145: + transformFlags |= 3 | 4096; + break; + case 176: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 175: + case 180: + excludeFlags = 537396545; if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; - } break; - case 170: - case 175: - excludeFlags = 537133909; - if (subtreeFlags & 262144) { - transformFlags |= 192; - } - break; - case 204: - case 205: - case 206: - case 207: - if (subtreeFlags & 1048576) { - transformFlags |= 192; - } - break; - case 256: - if (subtreeFlags & 16384) { - transformFlags |= 192; - } - break; - case 211: case 209: case 210: - transformFlags |= 8388608; + case 211: + case 212: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 261: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 216: + case 214: + case 215: + transformFlags |= 33554432; break; } node.transformFlags = transformFlags | 536870912; return transformFlags & ~excludeFlags; } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 156 && kind <= 171) { + return -3; + } + switch (kind) { + case 179: + case 180: + case 175: + return 537396545; + case 230: + return 574674241; + case 144: + return 536872257; + case 185: + return 601249089; + case 184: + case 225: + return 601281857; + case 224: + return 546309441; + case 226: + case 197: + return 539358529; + case 150: + return 601015617; + case 149: + case 151: + case 152: + return 601015617; + case 118: + case 132: + case 129: + case 134: + case 121: + case 135: + case 104: + case 143: + case 146: + case 148: + case 153: + case 154: + case 155: + case 227: + case 228: + return -3; + case 176: + return 540087617; + case 256: + return 537920833; + case 172: + case 173: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; })(ts || (ts = {})); var ts; (function (ts) { @@ -18547,6 +21022,8 @@ var ts; ts.getSymbolId = getSymbolId; function createTypeChecker(host, produceDiagnostics) { var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); @@ -18608,21 +21085,28 @@ var ts; getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + tryGetMemberInModuleExports: tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + } }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var stringLiteralTypes = ts.createMap(); var numericLiteralTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var trueType = createIntrinsicType(128, "true"); @@ -18633,10 +21117,13 @@ var ts; var neverType = createIntrinsicType(8192, "never"); var silentNeverType = createIntrinsicType(8192, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + emptyTypeLiteralSymbol.members = ts.createMap(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); @@ -18657,6 +21144,7 @@ var ts; var globalBooleanType; var globalRegExpType; var anyArrayType; + var autoArrayType; var anyReadonlyArrayType; var getGlobalTemplateStringsArrayType; var getGlobalESSymbolType; @@ -18723,6 +21211,8 @@ var ts; "undefined": undefinedType }); var jsxElementType; + var _jsxNamespace; + var _jsxFactoryEntity; var jsxTypes = ts.createMap(); var JsxNames = { JSX: "JSX", @@ -18743,6 +21233,21 @@ var ts; builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; + function getJsxNamespace() { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } function getEmitResolver(sourceFile, cancellationToken) { getDiagnostics(sourceFile, cancellationToken); return emitResolver; @@ -18823,12 +21328,10 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 225 && source.valueDeclaration.kind !== 225))) { + (target.valueDeclaration.kind === 230 && source.valueDeclaration.kind !== 230))) { target.valueDeclaration = source.valueDeclaration; } - ts.forEach(source.declarations, function (node) { - target.declarations.push(node); - }); + ts.addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = ts.createMap(); @@ -18879,7 +21382,7 @@ var ts; var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); if (!mainModule) { return; } @@ -18916,8 +21419,11 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } function isGlobalSourceFile(node) { - return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 261 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -18954,36 +21460,39 @@ var ts; (!compilerOptions.outFile && !compilerOptions.out)) { return true; } + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } var sourceFiles = host.getSourceFiles(); return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 218 || + return declaration.kind !== 223 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 200: - case 206: - case 208: + case 205: + case 211: + case 213: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } break; } switch (declaration.parent.parent.kind) { - case 207: - case 208: + case 212: + case 213: if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { return true; } } return false; } - function isUsedInFunctionOrNonStaticProperty(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage, container) { var current = usage; while (current) { if (current === container) { @@ -18993,7 +21502,7 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 145 && + current.parent.kind === 147 && (ts.getModifierFlags(current.parent) & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { @@ -19016,18 +21525,18 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 278) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 142 || - lastLocation.kind === 141 + lastLocation.kind === 144 || + lastLocation.kind === 143 : false; } if (meaning & 107455 && result.flags & 1) { useResult = - lastLocation.kind === 142 || + lastLocation.kind === 144 || (lastLocation === location.type && - result.valueDeclaration.kind === 142); + result.valueDeclaration.kind === 144); } } if (useResult) { @@ -19039,13 +21548,13 @@ var ts; } } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 225: + case 230: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 256 || ts.isAmbientModule(location)) { + if (location.kind === 261 || ts.isAmbientModule(location)) { if (result = moduleExports["default"]) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { @@ -19055,7 +21564,7 @@ var ts; } if (moduleExports[name] && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 238)) { + ts.getDeclarationOfKind(moduleExports[name], 243)) { break; } } @@ -19063,13 +21572,13 @@ var ts; break loop; } break; - case 224: + case 229: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 145: - case 144: + case 147: + case 146: if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -19079,9 +21588,9 @@ var ts; } } break; - case 221: - case 192: - case 222: + case 226: + case 197: + case 227: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -19089,7 +21598,7 @@ var ts; } break loop; } - if (location.kind === 192 && meaning & 32) { + if (location.kind === 197 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -19097,28 +21606,28 @@ var ts; } } break; - case 140: + case 142: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 222) { + if (ts.isClassLike(grandparent) || grandparent.kind === 227) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 147: - case 146: - case 148: case 149: + case 148: case 150: - case 220: - case 180: + case 151: + case 152: + case 225: + case 185: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 179: + case 184: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -19131,8 +21640,8 @@ var ts; } } break; - case 143: - if (location.parent && location.parent.kind === 142) { + case 145: + if (location.parent && location.parent.kind === 144) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -19154,6 +21663,7 @@ var ts; if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } @@ -19174,15 +21684,15 @@ var ts; } if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + if (decls && decls.length === 1 && decls[0].kind === 233) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 70 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -19220,16 +21730,26 @@ var ts; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 69: - case 172: + case 70: + case 177: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: + case 199: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); @@ -19244,7 +21764,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -19261,23 +21781,23 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 229) { + if (node.kind === 234) { return node; } - while (node && node.kind !== 230) { + while (node && node.kind !== 235) { node = node.parent; } return node; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 240) { + if (node.moduleReference.kind === 245) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -19335,28 +21855,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_18 = specifier.propertyName || specifier.name; + if (name_18.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_18.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_18.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_18.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_18.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_18, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_18)); } return symbol; } @@ -19378,19 +21898,19 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 229: - return getTargetOfImportEqualsDeclaration(node); - case 231: - return getTargetOfImportClause(node); - case 232: - return getTargetOfNamespaceImport(node); case 234: + return getTargetOfImportEqualsDeclaration(node); + case 236: + return getTargetOfImportClause(node); + case 237: + return getTargetOfNamespaceImport(node); + case 239: return getTargetOfImportSpecifier(node); - case 238: + case 243: return getTargetOfExportSpecifier(node); - case 235: + case 240: return getTargetOfExportAssignment(node); - case 228: + case 233: return getTargetOfNamespaceExportDeclaration(node); } } @@ -19434,10 +21954,10 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 235) { + if (node.kind === 240) { checkExpressionCached(node.expression); } - else if (node.kind === 238) { + else if (node.kind === 243) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -19445,15 +21965,15 @@ var ts; } } } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { - if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 70 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 69 || entityName.parent.kind === 139) { + if (entityName.kind === 70 || entityName.parent.kind === 141) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 229); + ts.Debug.assert(entityName.parent.kind === 234); return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } @@ -19465,16 +21985,16 @@ var ts; return undefined; } var symbol; - if (name.kind === 69) { + if (name.kind === 70) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } } - else if (name.kind === 139 || name.kind === 172) { - var left = name.kind === 139 ? name.left : name.expression; - var right = name.kind === 139 ? name.right : name.name; + else if (name.kind === 141 || name.kind === 177) { + var left = name.kind === 141 ? name.left : name.expression; + var right = name.kind === 141 ? name.right : name.name; var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -19499,27 +22019,28 @@ var ts; function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } if (moduleReferenceExpression.kind !== 9) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', 512); - if (symbol) { - return getMergedSymbol(symbol); - } + var ambientModule = tryFindAmbientModule(moduleName, true); + if (ambientModule) { + return ambientModule; } + var isRelative = ts.isExternalModuleNameRelative(moduleName); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return getMergedSymbol(sourceFile.symbol); @@ -19535,14 +22056,29 @@ var ts; return getMergedSymbol(pattern.symbol); } } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + } + return undefined; + } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -19564,6 +22100,12 @@ var ts; function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } function getExportsOfSymbol(symbol) { return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -19593,6 +22135,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -19656,7 +22199,7 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 148 && ts.nodeIsPresent(member.body)) { + if (member.kind === 150 && ts.nodeIsPresent(member.body)) { return member; } } @@ -19678,8 +22221,9 @@ var ts; type.intrinsicName = "boolean"; return type; } - function createObjectType(kind, symbol) { - var type = createType(kind); + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -19703,7 +22247,7 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; @@ -19715,7 +22259,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -19726,11 +22270,11 @@ var ts; } } switch (location_1.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 225: + case 230: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } @@ -19744,6 +22288,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -19757,26 +22311,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -19794,7 +22350,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -19808,10 +22364,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 145: case 147: case 149: - case 150: + case 151: + case 152: continue; default: return false; @@ -19833,7 +22389,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, }; } return hasAccessibleDeclarations; @@ -19854,7 +22410,7 @@ var ts; } return { accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 }; @@ -19867,7 +22423,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 261 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -19901,11 +22457,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 158 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 160 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning = 107455 | 1048576; } - else if (entityName.kind === 139 || entityName.kind === 172 || - entityName.parent.kind === 229) { + else if (entityName.kind === 141 || entityName.kind === 177 || + entityName.parent.kind === 234) { meaning = 1920; } else { @@ -19997,10 +22553,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 164) { + while (node.kind === 166) { node = node.parent; } - if (node.kind === 223) { + if (node.kind === 228) { return getSymbolOfNode(node); } } @@ -20008,7 +22564,7 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 226 && + node.parent.kind === 231 && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { @@ -20022,10 +22578,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 192: + case 197: return "(Anonymous class)"; - case 179: - case 180: + case 184: + case 185: return "(Anonymous function)"; } } @@ -20039,17 +22595,17 @@ var ts; var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 19); + writePunctuation(writer, 20); if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } else { - writePunctuation(writer, 21); + writePunctuation(writer, 22); writer.writeSymbol(symbolName, symbol); } } @@ -20077,9 +22633,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_5) { + walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,55 +22670,66 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { + else if (getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } else if (type.flags & 256) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); + writePunctuation(writer, 22); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { + else if (getObjectFlags(type) & 3 || type.flags & (16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 2097152) { + else if (getObjectFlags(type) & (16 | 32)) { writeAnonymousType(type, nextFlags); } else if (type.flags & 96) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & 262144) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 64); + } + else if (type.flags & 524288) { + writeType(type.objectType, 64); + writePunctuation(writer, 20); + writeType(type.indexType, 0); + writePunctuation(writer, 21); + } else { - writePunctuation(writer, 15); - writeSpace(writer); - writePunctuation(writer, 22); - writeSpace(writer); writePunctuation(writer, 16); + writeSpace(writer); + writePunctuation(writer, 23); + writeSpace(writer); + writePunctuation(writer, 17); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 24) { + if (delimiter !== 25) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 24 ? 0 : 64); + writeType(types[i], delimiter === 25 ? 0 : 64); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { @@ -20170,29 +22737,29 @@ var ts; buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); } if (pos < end) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); writeType(typeArguments[pos], 256); pos++; while (pos < end) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); writeType(typeArguments[pos], 0); pos++; } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & 1)) { writeType(typeArguments[0], 64); - writePunctuation(writer, 19); writePunctuation(writer, 20); + writePunctuation(writer, 21); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); + else if (type.target.objectFlags & 8) { writePunctuation(writer, 20); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 25); + writePunctuation(writer, 21); } else { var outerTypeParameters = type.target.outerTypeParameters; @@ -20201,13 +22768,13 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); - writePunctuation(writer, 21); + writeSymbolTypeReference(parent_6, typeArguments, start, i, flags); + writePunctuation(writer, 22); } } } @@ -20217,16 +22784,16 @@ var ts; } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 48); } else { - writeTypeList(type.types, 46); + writeTypeList(type.types, 47); } if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } } function writeAnonymousType(type, flags) { @@ -20244,7 +22811,7 @@ var ts; buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); } else { - writeKeyword(writer, 117); + writeKeyword(writer, 118); } } else { @@ -20265,7 +22832,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 256 || declaration.parent.kind === 226; + return declaration.parent.kind === 261 || declaration.parent.kind === 231; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -20274,37 +22841,37 @@ var ts; } } function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 101); + writeKeyword(writer, 102); writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); } function writeIndexSignature(info, keyword) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } - writePunctuation(writer, 19); + writePunctuation(writer, 20); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeKeyword(writer, keyword); - writePunctuation(writer, 20); - writePunctuation(writer, 54); + writePunctuation(writer, 21); + writePunctuation(writer, 55); writeSpace(writer); writeType(info.type, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 128); + writeKeyword(writer, 130); writeSpace(writer); } buildSymbolDisplay(prop, writer); if (prop.flags & 536870912) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { @@ -20319,56 +22886,68 @@ var ts; return false; } function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 15); writePunctuation(writer, 16); + writePunctuation(writer, 17); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { if (flags & 64) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); } - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { - writePunctuation(writer, 18); + writePunctuation(writer, 19); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 15); + writePunctuation(writer, 16); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 17); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } - writeIndexSignature(resolved.stringIndexInfo, 132); - writeIndexSignature(resolved.numberIndexInfo, 130); + writeIndexSignature(resolved.stringIndexInfo, 134); + writeIndexSignature(resolved.numberIndexInfo, 132); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -20378,22 +22957,45 @@ var ts; var signature = signatures_1[_f]; writePropertyWithModifiers(p); buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); writeType(t, 0); - writePunctuation(writer, 23); + writePunctuation(writer, 24); writer.writeLine(); } } - writer.decreaseIndent(); + } + function writeMappedType(type) { writePunctuation(writer, 16); - inObjectTypeLiteral = saveInObjectTypeLiteral; + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 130); + writeSpace(writer); + } + writePunctuation(writer, 20); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 91); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 21); + if (type.declaration.questionToken) { + writePunctuation(writer, 54); + } + writePunctuation(writer, 55); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 24); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 17); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { @@ -20407,7 +23009,7 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 83); + writeKeyword(writer, 84); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } @@ -20415,7 +23017,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (ts.isRestParameter(parameterNode)) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } if (ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -20424,36 +23026,36 @@ var ts; appendSymbolNameOnly(p, writer); } if (isOptionalParameter(parameterNode)) { - writePunctuation(writer, 53); + writePunctuation(writer, 54); } - writePunctuation(writer, 54); + writePunctuation(writer, 55); writeSpace(writer); buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 167) { - writePunctuation(writer, 15); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (bindingPattern.kind === 172) { writePunctuation(writer, 16); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 17); } - else if (bindingPattern.kind === 168) { - writePunctuation(writer, 19); + else if (bindingPattern.kind === 173) { + writePunctuation(writer, 20); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); } - writePunctuation(writer, 20); + writePunctuation(writer, 21); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 169); + ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); - writePunctuation(writer, 54); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 55); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -20461,75 +23063,75 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 22); + writePunctuation(writer, 23); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); + writePunctuation(writer, 26); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } action(list[i]); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25); - var flags_1 = 256; + writePunctuation(writer, 26); + var flags = 256; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); - flags_1 = 0; + flags = 0; } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags_1); + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 27); + writePunctuation(writer, 28); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 17); + writePunctuation(writer, 18); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 24); + writePunctuation(writer, 25); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 18); + writePunctuation(writer, 19); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 97); + writeKeyword(writer, 98); } writeSpace(writer); - writeKeyword(writer, 124); + writeKeyword(writer, 125); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); - writePunctuation(writer, 34); + writePunctuation(writer, 35); } else { - writePunctuation(writer, 54); + writePunctuation(writer, 55); } writeSpace(writer); if (signature.typePredicate) { @@ -20542,7 +23144,7 @@ var ts; } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { if (kind === 1) { - writeKeyword(writer, 92); + writeKeyword(writer, 93); writeSpace(writer); } if (signature.target && (flags & 32)) { @@ -20578,63 +23180,63 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 169: + case 174: return isDeclarationVisible(node.parent.parent); - case 218: + case 223: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } + case 230: + case 226: + case 227: + case 228: case 225: - case 221: - case 222: - case 223: - case 220: - case 224: case 229: + case 234: if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_7 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 234 && parent_7.kind !== 261 && ts.isInAmbientContext(parent_7))) { + return isGlobalSourceFile(parent_7); } - return isDeclarationVisible(parent_9); - case 145: - case 144: - case 149: - case 150: + return isDeclarationVisible(parent_7); case 147: case 146: + case 151: + case 152: + case 149: + case 148: if (ts.getModifierFlags(node) & (8 | 16)) { return false; } - case 148: - case 152: - case 151: + case 150: + case 154: case 153: - case 142: - case 226: - case 156: - case 157: - case 159: case 155: - case 160: + case 144: + case 231: + case 158: + case 159: case 161: + case 157: case 162: case 163: case 164: + case 165: + case 166: return isDeclarationVisible(node.parent); - case 231: - case 232: - case 234: + case 236: + case 237: + case 239: return false; - case 141: - case 256: - case 228: + case 143: + case 261: + case 233: return true; - case 235: + case 240: return false; default: return false; @@ -20643,10 +23245,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 235) { + if (node.parent && node.parent.kind === 240) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 238) { + else if (node.parent.kind === 243) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -20708,7 +23310,6 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -20725,12 +23326,12 @@ var ts; node = ts.getRootDeclaration(node); while (node) { switch (node.kind) { - case 218: - case 219: - case 234: - case 233: - case 232: - case 231: + case 223: + case 224: + case 239: + case 238: + case 237: + case 236: node = node.parent; break; default: @@ -20756,22 +23357,36 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } - function getTextOfPropertyName(name) { - switch (name.kind) { - case 69: - return name.text; - case 9: - case 8: - return name.text; - case 140: - if (ts.isStringOrNumericLiteral(name.expression.kind)) { - return name.expression.text; - } - } - return undefined; - } function isComputedNonLiteralName(name) { - return name.kind === 140 && !ts.isStringOrNumericLiteral(name.expression.kind); + return name.kind === 142 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createMap(); + var names = ts.createMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name_19 = properties_2[_i]; + names[ts.getTextOfPropertyName(name_19)] = true; + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = prop.name in names; + var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isMethod = prop.flags & 8192; + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -20786,26 +23401,45 @@ var ts; return parentType; } var type; - if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { - return anyType; + if (pattern.kind === 172) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = getTextOfPropertyName(name_16); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); - return unknownType; + else { + var name_20 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_20)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name_20); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_20)); + return unknownType; + } } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) @@ -20820,9 +23454,6 @@ var ts; return unknownType; } } - else { - type = createArrayType(elementType); - } } if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { type = getTypeWithFacts(type, 131072); @@ -20832,46 +23463,35 @@ var ts; type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); - } - } - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var typeTag = ts.getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - if (declaration.kind === 218 && - declaration.parent.kind === 219 && - declaration.parent.parent.kind === 200) { - var annotation = ts.getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === 142) { - var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } return undefined; } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 94 || expr.kind === 70 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 175 && expr.elements.length === 0; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.parent.parent.kind === 207) { - return stringType; + if (declaration.parent.parent.kind === 212) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; } - if (declaration.parent.parent.kind === 208) { + if (declaration.parent.parent.kind === 213) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -20880,10 +23500,20 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } - if (declaration.kind === 142) { + if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && + declaration.kind === 223 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 144) { var func = declaration.parent; - if (func.kind === 150 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149); + if (func.kind === 152 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -20896,8 +23526,7 @@ var ts; } var type = void 0; if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -20910,7 +23539,7 @@ var ts; var type = checkDeclarationInitializer(declaration); return addOptionality(type, declaration.questionToken && includeOptionality); } - if (declaration.kind === 254) { + if (declaration.kind === 258) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -20932,6 +23561,7 @@ var ts; } function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createMap(); + var stringIndexInfo; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -20939,19 +23569,23 @@ var ts; hasComputedProperties = true; return; } - var text = getTextOfPropertyName(name); + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.objectFlags |= 512; } return result; } @@ -20970,7 +23604,7 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 167 + return pattern.kind === 172 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -20980,7 +23614,7 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 253) { + if (declaration.kind === 257) { return type; } return getWidenedType(type); @@ -20995,7 +23629,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 142 ? root.parent : root; + var memberDeclaration = root.kind === 144 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -21005,28 +23639,28 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 252) { + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 235) { + if (declaration.kind === 240) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 1048576 && declaration.kind === 280 && declaration.typeExpression) { + if (declaration.flags & 65536 && declaration.kind === 286 && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } if (!pushTypeResolution(symbol, 0)) { return unknownType; } var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 1048576) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + if (declaration.kind === 192 || + declaration.kind === 177 && declaration.parent.kind === 192) { + if (declaration.flags & 65536) { + var jsdocType = ts.getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 ? checkExpressionCached(decl.right) : checkExpressionCached(decl.parent.right); }); type = getUnionType(declaredTypes, true); @@ -21035,16 +23669,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -21052,7 +23677,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 149) { + if (accessor.kind === 151) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -21072,9 +23697,9 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 149); - var setter = ts.getDeclarationOfKind(symbol, 150); - if (getter && getter.flags & 1048576) { + var getter = ts.getDeclarationOfKind(symbol, 151); + var setter = ts.getDeclarationOfKind(symbol, 152); + if (getter && getter.flags & 65536) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -21114,7 +23739,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 149); + var getter_1 = ts.getDeclarationOfKind(symbol, 151); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -21125,11 +23750,11 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(16, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; } @@ -21156,10 +23781,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -21182,7 +23824,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return getObjectFlags(type) & 4 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -21210,9 +23852,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 221 || node.kind === 192 || - node.kind === 220 || node.kind === 179 || - node.kind === 147 || node.kind === 180) { + if (node.kind === 226 || node.kind === 197 || + node.kind === 225 || node.kind === 184 || + node.kind === 149 || node.kind === 185) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -21221,15 +23863,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 222); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 222 || node.kind === 221 || - node.kind === 192 || node.kind === 223) { + if (node.kind === 227 || node.kind === 226 || + node.kind === 197 || node.kind === 228) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -21242,7 +23884,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -21254,7 +23896,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -21269,7 +23911,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -21286,7 +23928,7 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { + if (type.objectFlags & 8) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (32 | 64)) { @@ -21306,7 +23948,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 32768)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -21324,15 +23966,22 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getObjectFlags(getTargetType(baseType)) & 3)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } if (type.resolvedBaseTypes === emptyArray) { @@ -21355,12 +24004,12 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 227 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getObjectFlags(getTargetType(baseType)) & 3) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -21384,7 +24033,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222) { + if (declaration.kind === 227) { if (declaration.flags & 64) { return false; } @@ -21407,12 +24056,12 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1 : 2; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -21420,7 +24069,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21433,8 +24083,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); + var declaration = ts.getDeclarationOfKind(symbol, 285); var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -21445,14 +24094,15 @@ var ts; } } else { - declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + declaration = ts.getDeclarationOfKind(symbol, 228); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { + links.typeParameters = typeParameters; links.instantiations = ts.createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -21469,14 +24119,14 @@ var ts; return !ts.isInAmbientContext(member); } return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; + expr.kind === 70 && !!symbol.exports[expr.text]; } function enumHasLiteralMembers(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!isLiteralEnumMember(symbol, member)) { @@ -21504,7 +24154,7 @@ var ts; var memberTypes = ts.createMap(); for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224) { + if (declaration.kind === 229) { computeEnumMemberValues(declaration); for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; @@ -21519,7 +24169,7 @@ var ts; } enumType.memberTypes = memberTypes; if (memberTypeList.length > 1) { - enumType.flags |= 524288; + enumType.flags |= 65536; enumType.types = memberTypeList; unionTypes[getTypeListId(memberTypeList)] = enumType; } @@ -21531,7 +24181,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? + links.declaredType = enumType.flags & 65536 ? enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : enumType; } @@ -21542,7 +24192,7 @@ var ts; if (!links.declaredType) { var type = createType(16384); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 141).constraint) { + if (!ts.getDeclarationOfKind(symbol, 143).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -21591,20 +24241,20 @@ var ts; } function isIndependentType(node) { switch (node.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 166: + case 104: + case 137: + case 94: + case 129: + case 171: return true; - case 160: + case 162: return isIndependentType(node.elementType); - case 155: + case 157: return isIndependentTypeReference(node); } return false; @@ -21613,7 +24263,7 @@ var ts; return node.type && isIndependentType(node.type) || !node.type && !node.initializer; } function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 148 && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 150 && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -21629,12 +24279,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 145: - case 144: - return isIndependentVariableLikeDeclaration(declaration); case 147: case 146: + return isIndependentVariableLikeDeclaration(declaration); + case 149: case 148: + case 150: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -21677,7 +24327,7 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (getObjectFlags(type) & 4) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; @@ -21700,8 +24350,8 @@ var ts; else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -21721,7 +24371,7 @@ var ts; numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -21756,14 +24406,14 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -21848,7 +24498,7 @@ var ts; var constructSignatures = getUnionSignatures(type.types, 1); var stringIndexInfo = getUnionIndexInfo(type.types, 0); var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); @@ -21856,6 +24506,9 @@ var ts; function intersectIndexInfos(info1, info2) { return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { var callSignatures = emptyArray; var constructSignatures = emptyArray; @@ -21868,17 +24521,17 @@ var ts; stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { var members = symbol.members; @@ -21886,7 +24539,7 @@ var ts; var constructSignatures = getSignaturesOfSymbol(members["__new"]); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { var members = emptySymbols; @@ -21901,46 +24554,130 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 32768) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); } } } + function resolveMappedTypeMembers(type) { + var members = ts.createMap(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 168) { + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t) { + var iterationMapper = createUnaryTypeMapper(typeParameter, t); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = t.text; + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); + var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getErasedTemplateTypeFromMappedType(type) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32) { + var constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, 540672 | 262144); + } + return false; + } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { - resolveTypeReferenceMembers(type); + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } } - else if (type.flags & (32768 | 65536)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & 2097152) { - resolveAnonymousTypeMembers(type); - } - else if (type.flags & 524288) { + else if (type.flags & 65536) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 131072) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -21953,51 +24690,55 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 65536) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & 34) { - type = globalStringType; - } - else if (type.flags & 340) { - type = globalNumberType; - } - else if (type.flags & 136) { - type = globalBooleanType; - } - else if (type.flags & 512) { - type = getGlobalESSymbolType(); - } - return type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & 262178 ? globalStringType : + t.flags & 340 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22015,21 +24756,21 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { - return undefined; + else if (containingType.flags & 65536) { + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +24781,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,9 +24805,13 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -22082,13 +24825,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 196608) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -22098,7 +24841,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 229376) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -22129,7 +24872,7 @@ var ts; return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -22157,21 +24900,31 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 1048576) { - if (node.type && node.type.kind === 268) { + if (node.flags & 65536) { + if (node.type && node.type.kind === 273) { return true; } - var paramTag = ts.getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 268; + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 273; + } } } } } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } function isOptionalParameter(node) { if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -22186,7 +24939,7 @@ var ts; return false; } function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 69) { + if (node.parameterName.kind === 70) { var parameterName = node.parameterName; return { kind: 1, @@ -22225,7 +24978,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166) { + if (param.type && param.type.kind === 171) { hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { @@ -22237,10 +24990,10 @@ var ts; minArgumentCount = -1; } } - if ((declaration.kind === 149 || declaration.kind === 150) && + if ((declaration.kind === 151 || declaration.kind === 152) && !ts.hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 149 ? 150 : 149; + var otherKind = declaration.kind === 151 ? 152 : 151; var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); @@ -22252,24 +25005,21 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } - var classType = declaration.kind === 148 ? + var classType = declaration.kind === 150 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 154 ? + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 156 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType) { + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -22279,14 +25029,14 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 1048576) { + if (declaration.flags & 65536) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } } - if (declaration.kind === 149 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 150); + if (declaration.kind === 151 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 152); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -22300,20 +25050,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 269: + case 184: + case 185: + case 274: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -22374,13 +25124,18 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { return type.typeArguments[0]; } } return anyType; } function getSignatureInstantiation(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + function createSignatureInstantiation(signature, typeArguments) { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { @@ -22393,8 +25148,8 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var isConstructor = signature.declaration.kind === 150 || signature.declaration.kind === 154; + var type = createObjectType(16); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -22407,7 +25162,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 130 : 132; + var syntaxKind = kind === 1 ? 132 : 134; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -22434,11 +25189,11 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 141).constraint; + return ts.getDeclarationOfKind(type.symbol, 143).constraint; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22466,8 +25221,13 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } function getTypeListId(types) { var result = ""; @@ -22500,22 +25260,23 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(4, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; type.target = target; type.typeArguments = typeArguments; } return type; } function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -22531,7 +25292,7 @@ var ts; error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); return unknownType; } - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -22539,18 +25300,23 @@ var ts; } return type; } - function getTypeFromTypeAliasReference(node, symbol) { + function getTypeAliasInstantiation(symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); - var id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -22567,11 +25333,11 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 155: + case 157: return node.typeName; - case 267: + case 272: return node.name; - case 194: + case 199: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -22579,7 +25345,7 @@ var ts; } return undefined; } - function resolveTypeReferenceName(node, typeReferenceName) { + function resolveTypeReferenceName(typeReferenceName) { if (!typeReferenceName) { return unknownSymbol; } @@ -22595,7 +25361,7 @@ var ts; if (symbol.flags & 524288) { return getTypeFromTypeAliasReference(node, symbol); } - if (symbol.flags & 107455 && node.kind === 267) { + if (symbol.flags & 107455 && node.kind === 272) { return getTypeOfSymbol(symbol); } return getTypeFromNonGenericTypeReference(node, symbol); @@ -22605,13 +25371,13 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - if (node.kind === 267) { + if (node.kind === 272) { var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { - var typeNameOrExpression = node.kind === 155 + var typeNameOrExpression = node.kind === 157 ? node.typeName : ts.isEntityNameExpression(node.expression) ? node.expression @@ -22640,9 +25406,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 221: - case 222: - case 224: + case 226: + case 227: + case 229: return declaration; } } @@ -22651,7 +25417,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 32768)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -22714,7 +25480,7 @@ var ts; property.type = typeParameter; properties.push(property); } - var type = createObjectType(262144 | 131072); + var type = createObjectType(8 | 4); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -22722,7 +25488,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22740,7 +25507,7 @@ var ts; function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -22768,7 +25535,7 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 524288) { + if (flags & 65536) { addTypesToUnion(typeSet, type.types); } else if (flags & 1) { @@ -22779,7 +25546,7 @@ var ts; typeSet.containsUndefined = true; if (flags & 4096) typeSet.containsNull = true; - if (!(flags & 33554432)) + if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } else if (!(flags & 8192)) { @@ -22792,7 +25559,8 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -22821,7 +25589,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -22837,7 +25622,7 @@ var ts; var t = types[i]; var remove = t.flags & 32 && types.containsString || t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 16777216 && containsType(types, t.regularType); + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -22879,28 +25664,31 @@ var ts; var type = unionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); + type = unionTypes[id] = createType(65536 | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { + if (type.flags & 131072) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1) { typeSet.containsAny = true; } else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -22922,43 +25710,303 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + type = intersectionTypes[id] = createType(131072 | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(32, ts.unescapeIdentifier(prop.name)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); } return links.resolvedType; } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + var propName = indexType.flags & (32 | 64 | 256) ? + indexType.text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : + undefined; + if (propName) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 340 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + var indexNode = accessNode.kind === 178 ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 | 64)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + } + else if (indexType.flags & (2 | 4)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 178 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (ts.isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 228 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right, isFromObjectLiteral) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + left = filterType(left, function (t) { return !(t.flags & 6144); }); + if (left.flags & 8192) { + return right; + } + right = filterType(right, function (t) { return !(t.flags & 6144); }); + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right, isFromObjectLiteral); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t, isFromObjectLiteral); }); + } + var members = ts.createMap(); + var skippedPrivateMembers = ts.createMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isOwnProperty = !(rightProp.flags & 8192) || isFromObjectLiteral; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + var rightProp = members[leftProp.name]; + var rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } function createLiteralType(flags, text) { var type = createType(flags); type.text = text; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 16777216)) { + if (type.flags & 96 && !(type.flags & 1048576)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 16777216, type.text); + var freshType = createLiteralType(type.flags | 1048576, type.text); freshType.regularType = type; type.freshType = freshType; } @@ -22967,7 +26015,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 16777216 ? type.regularType : type; + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; } function getLiteralTypeForText(flags, text) { var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; @@ -22991,7 +26039,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); + var types = ts.map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -22999,9 +26047,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 222)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 227)) { if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 148 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 150 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -23015,85 +26063,88 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type) { - return getTypeFromTypeNode(type, undefined, undefined); - } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { - case 117: - case 258: - case 259: - return anyType; - case 132: - return stringType; - case 130: - return numberType; - case 120: - return booleanType; - case 133: - return esSymbolType; - case 103: - return voidType; - case 135: - return undefinedType; - case 93: - return nullType; - case 127: - return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; - case 165: - case 97: - return getTypeFromThisTypeNode(node); - case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); - case 155: - case 267: - return getTypeFromTypeReference(node); - case 154: - return booleanType; - case 194: - return getTypeFromTypeReference(node); - case 158: - return getTypeFromTypeQueryNode(node); - case 160: - case 260: - return getTypeFromArrayTypeNode(node); - case 161: - return getTypeFromTupleTypeNode(node); - case 162: - case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 164: + case 118: case 263: case 264: - case 271: - case 272: - case 268: - return getTypeFromTypeNode(node.type); - case 265: - return getTypeFromTypeNode(node.literal); - case 156: + return anyType; + case 134: + return stringType; + case 132: + return numberType; + case 121: + return booleanType; + case 135: + return esSymbolType; + case 104: + return voidType; + case 137: + return undefinedType; + case 94: + return nullType; + case 129: + return neverType; + case 289: + return nullType; + case 290: + return undefinedType; + case 291: + return neverType; + case 167: + case 98: + return getTypeFromThisTypeNode(node); + case 171: + return getTypeFromLiteralTypeNode(node); + case 288: + return getTypeFromLiteralTypeNode(node.literal); case 157: - case 159: - case 281: + case 272: + return getTypeFromTypeReference(node); + case 156: + return booleanType; + case 199: + return getTypeFromTypeReference(node); + case 160: + return getTypeFromTypeQueryNode(node); + case 162: + case 265: + return getTypeFromArrayTypeNode(node); + case 163: + return getTypeFromTupleTypeNode(node); + case 164: + case 266: + return getTypeFromUnionTypeNode(node); + case 165: + return getTypeFromIntersectionTypeNode(node); + case 166: + case 268: case 269: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); - case 69: - case 139: + case 276: + case 277: + case 273: + return getTypeFromTypeNode(node.type); + case 270: + return getTypeFromTypeNode(node.literal); + case 158: + case 159: + case 161: + case 287: + case 274: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 168: + return getTypeFromTypeOperatorNode(node); + case 169: + return getTypeFromIndexedAccessTypeNode(node); + case 170: + return getTypeFromMappedTypeNode(node); + case 70: + case 141: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 262: + case 267: return getTypeFromJSDocTupleType(node); - case 270: + case 275: return getTypeFromJSDocVariadicType(node); default: return unknownType; @@ -23110,6 +26161,16 @@ var ts; } return items; } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } function createUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -23132,7 +26193,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -23222,45 +26282,68 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - if (mapper.instantiations) { - var cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + var replacementMapper = createUnaryTypeMapper(typeVariable_1, t); + var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - var result = createObjectType(2097152 | 4194304, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } var mappedTypes = mapper.mappedTypes; var node = symbol.declarations[0].parent; while (node) { switch (node.kind) { - case 156: - case 157: - case 220: - case 147: - case 146: + case 158: + case 159: + case 225: + case 149: case 148: + case 150: + case 153: + case 154: + case 155: case 151: case 152: - case 153: - case 149: - case 150: - case 179: - case 180: - case 221: - case 192: - case 222: - case 223: + case 184: + case 185: + case 226: + case 197: + case 227: + case 228: var declaration = node; if (declaration.typeParameters) { for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { @@ -23270,86 +26353,122 @@ var ts; } } } - if (ts.isClassLike(node) || node.kind === 222) { + if (ts.isClassLike(node) || node.kind === 227) { var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; if (thisType && ts.contains(mappedTypes, thisType)) { return true; } } break; - case 225: - case 256: + case 230: + case 261: return false; } node = node.parent; } return false; } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 261 || parentKind === 231; + } + return false; + } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { - return mapper(type); + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & 2097152) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & 131072) { - return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } return type; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 179: - case 180: + case 184: + case 185: return isContextSensitiveFunctionLikeDeclaration(node); - case 171: + case 176: return ts.forEach(node.properties, isContextSensitive); - case 170: + case 175: return ts.forEach(node.elements, isContextSensitive); - case 188: + case 193: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 187: - return node.operatorToken.kind === 52 && + case 192: + return node.operatorToken.kind === 53 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 253: + case 257: return isContextSensitive(node.initializer); - case 147: - case 146: + case 149: + case 148: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 183: return isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - var areAllParametersUntyped = !ts.forEach(node.parameters, function (p) { return p.type; }); - var isNullaryArrow = node.kind === 180 && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !p.type; })) { + return true; + } + if (node.kind === 185) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(16, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -23528,7 +26647,7 @@ var ts; } if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { + (source.flags & 65536) !== (target.flags & 65536)) { return enumRelation[id] = false; } var targetEnumType = getTypeOfSymbol(target.symbol); @@ -23551,7 +26670,7 @@ var ts; return false; if (target.flags & 1 || source.flags & 8192) return true; - if (source.flags & 34 && target.flags & 2) + if (source.flags & 262178 && target.flags & 2) return true; if (source.flags & 340 && target.flags & 4) return true; @@ -23585,23 +26704,23 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 2588672 && target.flags & 2588672) { + if (source.flags & 32768 && target.flags & 32768) { var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { return related === 1; } } - if (source.flags & 4177920 || target.flags & 4177920) { + if (source.flags & 507904 || target.flags & 507904) { return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); } return false; @@ -23638,9 +26757,15 @@ var ts; targetType = typeToString(target, undefined, 128); } if (!message) { - message = relation === comparableRelation ? - ts.Diagnostics.Type_0_is_not_comparable_to_type_1 : - ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); } @@ -23654,12 +26779,29 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; - if (source.flags & 96 && source.flags & 16777216) { + if (source.flags & 96 && source.flags & 1048576) { source = source.regularType; } - if (target.flags & 96 && target.flags & 16777216) { + if (target.flags & 96 && target.flags & 1048576) { target = target.regularType; } if (source === target) @@ -23669,19 +26811,19 @@ var ts; } if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (source.flags & 8388608 && source.flags & 16777216) { + if (getObjectFlags(source) & 128 && source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 65536) { if (relation === comparableRelation) { result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); } @@ -23692,44 +26834,106 @@ var ts; return result; } } - else if (target.flags & 1048576) { - result = typeRelatedToEachType(source, target, reportErrors); - if (result) { + else if (target.flags & 65536) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { return result; } } - else { - if (source.flags & 1048576) { - if (result = someTypeRelatedToType(source, target, false)) { + else if (target.flags & 131072) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else if (source.flags & 131072) { + if (result = someTypeRelatedToType(source, target, false)) { + return result; + } + } + else if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + var constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & 262144) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 524288) { + if (source.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & 16384) { - var constraint = getConstraintOfTypeParameter(source); - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { + if (apparentSource.flags & (32768 | 131072) && target.flags & 32768) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; @@ -23738,10 +26942,10 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { + if (source.flags & 32768 && target.flags & 8190) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 2588672 && globalObjectType === source) { + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -23750,18 +26954,18 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 32768 && target.flags & 32768) { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { - if (result = eachTypeRelatedToSomeType(source, target, false)) { - if (result &= eachTypeRelatedToSomeType(target, source, false)) { + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -23769,7 +26973,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -23778,7 +26982,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 196608) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -23796,7 +27000,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23811,7 +27015,7 @@ var ts; } return false; } - function eachTypeRelatedToSomeType(source, target, reportErrors) { + function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { @@ -23826,7 +27030,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { + if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } var len = targetTypes.length; @@ -23853,7 +27057,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { + if (source.flags & 65536 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -23940,6 +27144,9 @@ var ts; if (expandingFlags === 3) { result = 1; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -23967,15 +27174,42 @@ var ts; } return result; } + function mappedTypeRelatedTo(source, target, reportErrors) { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + var result_2; + if (relation === identityRelation) { + var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken; + var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) { + return -1; + } + return 0; + } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -24027,7 +27261,7 @@ var ts; return 0; } result &= related; - if (sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -24039,7 +27273,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 32768 && target.flags & 32768)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -24211,7 +27445,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (getObjectFlags(type) & 16) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -24223,12 +27457,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (getObjectFlags(type) & (4 | 64) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (getObjectFlags(t) & (4 | 64) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -24386,10 +27620,10 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return getObjectFlags(type) & 4 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { @@ -24400,7 +27634,7 @@ var ts; } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -24408,19 +27642,19 @@ var ts; type.flags & 64 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 && type.flags & 16777216 ? stringType : - type.flags & 64 && type.flags & 16777216 ? numberType : + return type.flags & 32 && type.flags & 1048576 ? stringType : + type.flags & 64 && type.flags & 1048576 ? numberType : type.flags & 128 ? booleanType : type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type.flags & 65536 && !(type.flags & 16) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -24431,7 +27665,7 @@ var ts; return result; } function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 ? type.text === "" ? 32 : 0 : type.flags & 64 ? type.text === "0" ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : @@ -24442,7 +27676,7 @@ var ts; return type; } var types = [type]; - if (flags & 34) + if (flags & 262178) types.push(emptyStringType); if (flags & 340) types.push(zeroType); @@ -24492,7 +27726,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 8388608 && type.flags & 16777216)) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -24502,7 +27736,8 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; type.regularType = regularNew; return regularNew; } @@ -24519,25 +27754,25 @@ var ts; return type.flags & 6144 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { + if (type.flags & 6291456) { if (type.flags & 6144) { return anyType; } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 65536) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -24553,11 +27788,11 @@ var ts; } } } - if (type.flags & 8388608) { + if (getObjectFlags(type) & 128) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -24571,25 +27806,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 145: - case 144: + case 147: + case 146: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 142: + case 144: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 169: + case 174: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 220: - case 147: - case 146: + case 225: case 149: - case 150: - case 179: - case 180: + case 148: + case 151: + case 152: + case 184: + case 185: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -24602,7 +27837,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -24634,7 +27869,7 @@ var ts; signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length), }; } function createTypeInferencesObject() { @@ -24642,26 +27877,72 @@ var ts; primary: undefined, secondary: undefined, topLevel: true, - isFixed: false + isFixed: false, }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 1572864 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypes(context, originalSource, originalTarget) { - var typeParameters = context.signature.typeParameters; + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var typeVariableArray = [typeVariable]; + var typeInferences = createTypeInferencesObject(); + var typeInferencesArray = [typeInferences]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var members = createSymbolTable(properties); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + var inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, true); + } + } + function inferTypesWithContext(context, originalSource, originalTarget) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { var sourceStack; var targetStack; var depth = 0; @@ -24677,11 +27958,19 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { return; } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 16 && target.flags & 16) || + source.flags & 131072 && target.flags & 131072) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -24708,13 +27997,13 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 540672) { + if (source.flags & 8388608) { return; } - for (var i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - var inferences = context.inferences[i]; + for (var i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + var inferences = typeInferences[i]; if (!inferences.isFixed) { var candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : @@ -24722,7 +28011,7 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -24730,7 +28019,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -24738,27 +28027,27 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (target.flags & 196608) { var targetTypes = target.types; - var typeParameterCount = 0; - var typeParameter = void 0; + var typeVariableCount = 0; + var typeVariable = void 0; for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & 540672 && ts.contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 196608) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -24767,7 +28056,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 32768) { if (isInProcess(source, target)) { return; } @@ -24786,18 +28075,41 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var index = ts.indexOf(typeVariables, constraintType.type); + if (index >= 0 && !typeInferences[index].isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -24863,7 +28175,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -24871,7 +28183,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; @@ -24883,7 +28195,7 @@ var ts; var widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; @@ -24924,10 +28236,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 158: + case 160: return true; - case 69: - case 139: + case 70: + case 141: node = node.parent; continue; default: @@ -24937,14 +28249,14 @@ var ts; ts.Debug.fail("should not get here"); } function getFlowCacheKey(node) { - if (node.kind === 69) { + if (node.kind === 70) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - if (node.kind === 97) { + if (node.kind === 98) { return "0"; } - if (node.kind === 172) { + if (node.kind === 177) { var key = getFlowCacheKey(node.expression); return key && key + "." + node.name.text; } @@ -24952,31 +28264,31 @@ var ts; } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { - case 69: - case 97: + case 70: + case 98: return node; - case 172: + case 177: return getLeftmostIdentifierOrThis(node.expression); } return undefined; } function isMatchingReference(source, target) { switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && + case 70: + return target.kind === 70 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 223 || target.kind === 174) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && + case 98: + return target.kind === 98; + case 177: + return target.kind === 177 && source.name.text === target.name.text && isMatchingReference(source.expression, target.expression); } return false; } function containsMatchingReference(source, target) { - while (source.kind === 172) { + while (source.kind === 177) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -24985,33 +28297,26 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && + return target.kind === 177 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { + if (expr.kind === 70) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 172) { + if (expr.kind === 177) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.text); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25030,7 +28335,7 @@ var ts; } } } - if (callExpression.expression.kind === 172 && + if (callExpression.expression.kind === 177 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -25044,7 +28349,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 65536)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -25107,7 +28412,7 @@ var ts; type === falseType ? 3030404 : 1981828 : type === falseType ? 3145092 : 4193668; } - if (flags & 2588672) { + if (flags & 32768) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 : 8376288 : strictNullChecks ? 6166480 : 8378320; @@ -25125,7 +28430,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type); return getTypeFacts(constraint || emptyObjectType); } - if (flags & 1572864) { + if (flags & 196608) { return getTypeFactsOfTypes(type.types); } return 8388607; @@ -25135,13 +28440,13 @@ var ts; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { - var defaultType = checkExpression(defaultExpression); + var defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, 131072), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { - var text = getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || @@ -25152,19 +28457,19 @@ var ts; checkIteratedTypeOrElementType(type, undefined, false) || unknownType; } - function getTypeOfDestructuredSpreadElement(type) { + function getTypeOfDestructuredSpreadExpression(type) { return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 170 || node.parent.kind === 253 ? + return node.parent.kind === 175 || node.parent.kind === 257 ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node) { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node) { return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); @@ -25175,21 +28480,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 207: + case 212: return stringType; - case 208: + case 213: return checkRightHandSideOfForOf(parent.expression) || unknownType; - case 187: + case 192: return getAssignedTypeOfBinaryExpression(parent); - case 181: + case 186: return undefinedType; - case 170: + case 175: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 191: - return getAssignedTypeOfSpreadElement(parent); - case 253: + case 196: + return getAssignedTypeOfSpreadExpression(parent); + case 257: return getAssignedTypeOfPropertyAssignment(parent); - case 254: + case 258: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -25197,56 +28502,69 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 167 ? + var type = pattern.kind === 172 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { var links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 207) { + if (node.parent.parent.kind === 212) { return stringType; } - if (node.parent.parent.kind === 208) { + if (node.parent.parent.kind === 213) { return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 218 ? + return node.kind === 223 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? + return node.kind === 223 || node.kind === 174 ? getInitialType(node) : getAssignedType(node); } + function isEmptyArrayAssignment(node) { + return node.kind === 223 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 174 && node.parent.kind === 192 && + isEmptyArrayLiteral(node.parent.right); + } function getReferenceCandidate(node) { switch (node.kind) { - case 178: + case 183: return getReferenceCandidate(node.expression); - case 187: + case 192: switch (node.operatorToken.kind) { - case 56: + case 57: return getReferenceCandidate(node.left); - case 24: + case 25: return getReferenceCandidate(node.right); } } return node; } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 183 || + parent.kind === 192 && parent.operatorToken.kind === 57 && parent.left === node || + parent.kind === 192 && parent.operatorToken.kind === 25 && parent.right === node ? + getReferenceRoot(parent) : node; + } function getTypeOfSwitchClause(clause) { - if (clause.kind === 249) { - var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + if (clause.kind === 253) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -25260,13 +28578,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { + if (source.flags & 65536) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -25280,14 +28598,34 @@ var ts; } return containsType(target.types, source); } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } function filterType(type, f) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 65536 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25297,22 +28635,105 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 177 && (parent.name.text === "length" || + parent.parent.kind === 179 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 178 && + parent.expression === root && + parent.parent.kind === 192 && + parent.parent.operatorToken.kind === 57 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288).flags & 8192) { + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 201 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 512) { + if (flow.flags & 1024) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -25342,18 +28763,25 @@ var ts; getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && container !== flowContainer && reference.kind !== 177) { flow = container.flowNode; continue; } type = initialType; } else { - type = declaredType; + type = convertAutoToAny(declaredType); } - if (flow.flags & 512) { + if (flow.flags & 1024) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -25364,27 +28792,70 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; } return undefined; } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 179 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 179) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (!(type.flags & 8192)) { - var assumeTrue = (flow.flags & 32) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & 8192 && isIncomplete(flowType)) { - type = silentNeverType; - } + if (type.flags & 8192) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); @@ -25419,7 +28890,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); @@ -25431,8 +28902,8 @@ var ts; return cache[key]; } for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); } } var antecedentTypes = []; @@ -25463,15 +28934,15 @@ var ts; break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, true); } return cache[key] = result; } function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && + return expr.kind === 177 && + declaredType.flags & 65536 && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(declaredType, expr.name.text); } @@ -25495,19 +28966,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 56: + case 57: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 30: case 31: case 32: case 33: + case 34: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { + if (left_1.kind === 187 && right_1.kind === 9) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { + if (right_1.kind === 187 && left_1.kind === 9) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -25526,9 +28997,9 @@ var ts; return declaredType; } break; - case 91: + case 92: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 24: + case 25: return narrowType(type, expr.right, assumeTrue); } return type; @@ -25537,28 +29008,28 @@ var ts; if (type.flags & 1) { return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); + var valueType = getTypeOfExpression(value); if (valueType.flags & 6144) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 30 || operator === 31; + var doubleEquals = operator === 31 || operator === 32; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - value.kind === 93 ? + value.kind === 94 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 33281) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25574,10 +29045,10 @@ var ts; } return type; } - if (operator === 31 || operator === 33) { + if (operator === 32 || operator === 34) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { + if (assumeTrue && !(type.flags & 65536)) { var targetType = typeofTypesByName[literal.text]; if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; @@ -25596,7 +29067,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25611,7 +29083,7 @@ var ts; } return type; } - var rightType = checkExpression(expr.right); + var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -25628,10 +29100,10 @@ var ts; } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (getObjectFlags(rightType) & 2) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (getObjectFlags(rightType) & 16) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -25639,16 +29111,16 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type, candidate, assumeTrue) { + function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); if (!(assignableType.flags & 8192)) { return assignableType; } @@ -25660,7 +29132,7 @@ var ts; getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } var signature = getResolvedSignature(callExpression); @@ -25675,7 +29147,7 @@ var ts; var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -25683,12 +29155,12 @@ var ts; } } else { - var invokedExpression = skipParenthesizedNodes(callExpression.expression); - if (invokedExpression.kind === 173 || invokedExpression.kind === 172) { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 178 || invokedExpression.kind === 177) { var accessExpression = invokedExpression; - var possibleReference = skipParenthesizedNodes(accessExpression.expression); + var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -25699,18 +29171,18 @@ var ts; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 69: - case 97: - case 172: + case 70: + case 98: + case 177: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 174: + case 179: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 178: + case 183: return narrowType(type, expr.expression, assumeTrue); - case 187: + case 192: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 185: - if (expr.operator === 49) { + case 190: + if (expr.operator === 50) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -25719,12 +29191,12 @@ var ts; } } function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 69) { + if (location.kind === 70) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { - var type = checkExpression(location); + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -25732,19 +29204,13 @@ var ts; } return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression) { - while (expression.kind === 178) { - expression = expression.expression; - } - return expression; - } function getControlFlowContainer(node) { while (true) { node = node.parent; if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + node.kind === 231 || + node.kind === 261 || + node.kind === 147) { return node; } } @@ -25772,10 +29238,10 @@ var ts; } } function markParameterAssignments(node) { - if (node.kind === 69) { + if (node.kind === 70) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144) { symbol.isAssigned = true; } } @@ -25784,21 +29250,28 @@ var ts; ts.forEachChild(node, markParameterAssignments); } } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 180) { + if (container.kind === 185) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - if (node.flags & 262144) { + if (node.flags & 16384) { getNodeLinks(container).flags |= 8192; } + return getTypeOfSymbol(symbol); } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); @@ -25806,8 +29279,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); if (localOrExportSymbol.flags & 32) { var declaration_1 = localOrExportSymbol.valueDeclaration; - if (languageVersion === 2 - && declaration_1.kind === 221 + if (declaration_1.kind === 226 && ts.nodeIsDecorated(declaration_1)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -25819,11 +29291,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration_1.kind === 192) { + else if (declaration_1.kind === 197) { var container = ts.getThisContainer(node, false); while (container !== undefined) { if (container.parent === declaration_1) { - if (container.kind === 145 && ts.hasModifier(container, 32)) { + if (container.kind === 147 && ts.hasModifier(container, 32)) { getNodeLinks(declaration_1).flags |= 8388608; getNodeLinks(node).flags |= 16777216; } @@ -25838,26 +29310,47 @@ var ts; checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; + var isParameter = ts.getRootDeclaration(declaration).kind === 144; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === 184 || + flowContainer.kind === 185 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node, threshold) { var current = node; @@ -25872,7 +29365,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 252) { + symbol.valueDeclaration.parent.kind === 256) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -25890,8 +29383,8 @@ var ts; if (usedInFunction) { getNodeLinks(current).flags |= 65536; } - if (container.kind === 206 && - ts.getAncestor(symbol.valueDeclaration, 219).parent === container && + if (container.kind === 211 && + ts.getAncestor(symbol.valueDeclaration, 224).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152; } @@ -25903,16 +29396,16 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 178) { + while (current.parent.kind === 183) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 185 || current.parent.kind === 186)) { + else if ((current.parent.kind === 190 || current.parent.kind === 191)) { var expr = current.parent; - isAssigned = expr.operator === 41 || expr.operator === 42; + isAssigned = expr.operator === 42 || expr.operator === 43; } if (!isAssigned) { return false; @@ -25929,7 +29422,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 145 || container.kind === 148) { + if (container.kind === 147 || container.kind === 150) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -25938,7 +29431,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -25960,42 +29453,45 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 148) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + if (container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 180) { + if (container.kind === 185) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 225: + case 230: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 224: + case 229: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 148: + case 150: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 145: - case 144: + case 147: + case 146: if (ts.getModifierFlags(container) & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 140: + case 142: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -26003,8 +29499,8 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { - if (container.kind === 179 && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 184 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { var className = container.parent @@ -26016,7 +29512,7 @@ var ts; return getInferredClassType(classSymbol); } } - var thisType = getThisTypeOfDeclaration(container); + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -26038,28 +29534,28 @@ var ts; return anyType; } function getTypeForThisExpressionFromJSDoc(node) { - var typeTag = ts.getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 269) { - var jsDocFunctionType = typeTag.typeExpression.type; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 272) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 274) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 142) { + if (n.kind === 144) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 174 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 179 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 180) { + while (container && container.kind === 185) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -26068,16 +29564,16 @@ var ts; var nodeCheckFlag = 0; if (!canUseSuperExpression) { var current = node; - while (current && current !== container && current.kind !== 140) { + while (current && current !== container && current.kind !== 142) { current = current.parent; } - if (current && current.kind === 140) { + if (current && current.kind === 142) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 171)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -26085,6 +29581,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -26092,7 +29591,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 147 && ts.getModifierFlags(container) & 256) { + if (container.kind === 149 && ts.getModifierFlags(container) & 256) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -26103,7 +29602,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 171) { + if (container.parent.kind === 176) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -26121,7 +29620,7 @@ var ts; } return unknownType; } - if (container.kind === 148 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 150 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -26133,35 +29632,38 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 148; + return container.kind === 150; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 171) { + if (ts.isClassLike(container.parent) || container.parent.kind === 176) { if (ts.getModifierFlags(container) & 32) { - return container.kind === 147 || - container.kind === 146 || - container.kind === 149 || - container.kind === 150; + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152; } else { - return container.kind === 147 || + return container.kind === 149 || + container.kind === 148 || + container.kind === 151 || + container.kind === 152 || + container.kind === 147 || container.kind === 146 || - container.kind === 149 || - container.kind === 150 || - container.kind === 145 || - container.kind === 144 || - container.kind === 148; + container.kind === 150; } } } return false; } } - function getContextualThisParameter(func) { - if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { + function getContextualThisParameterType(func) { + if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } return undefined; @@ -26211,7 +29713,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 142) { + if (declaration.kind === 144) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -26222,11 +29724,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_21 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_21)) { + var text = ts.getTextOfPropertyName(name_21); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26263,7 +29765,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 142 && node.parent.initializer === node) { + if (node.parent.kind === 144 && node.parent.initializer === node) { return true; } node = node.parent; @@ -26272,8 +29774,8 @@ var ts; } function getContextualReturnType(functionDecl) { if (functionDecl.type || - functionDecl.kind === 148 || - functionDecl.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 150))) { + functionDecl.kind === 150 || + functionDecl.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); @@ -26292,7 +29794,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 176) { + if (template.parent.kind === 181) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -26300,22 +29802,22 @@ var ts; function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; - if (operator >= 56 && operator <= 68) { + if (operator >= 57 && operator <= 69) { if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { return undefined; } if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } - else if (operator === 52) { + else if (operator === 53) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } - else if (operator === 51 || operator === 24) { + else if (operator === 52 || operator === 25) { if (node === binaryExpression.right) { return getContextualType(binaryExpression); } @@ -26323,14 +29825,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 65536)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -26348,7 +29850,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -26356,7 +29858,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -26400,13 +29902,13 @@ var ts; var kind = attribute.kind; var jsxElement = attribute.parent; var attrsType = getJsxElementAttributesType(jsxElement); - if (attribute.kind === 246) { + if (attribute.kind === 250) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - else if (attribute.kind === 247) { + else if (attribute.kind === 251) { return attrsType; } ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); @@ -26424,56 +29926,70 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 218: - case 142: - case 145: + case 223: case 144: - case 169: - return getContextualTypeForInitializerExpression(node); - case 180: - case 211: - return getContextualTypeForReturnExpression(node); - case 190: - return getContextualTypeForYieldOperand(parent); + case 147: + case 146: case 174: - case 175: - return getContextualTypeForArgument(parent, node); - case 177: + return getContextualTypeForInitializerExpression(node); + case 185: + case 216: + return getContextualTypeForReturnExpression(node); case 195: + return getContextualTypeForYieldOperand(parent); + case 179: + case 180: + return getContextualTypeForArgument(parent, node); + case 182: + case 200: return getTypeFromTypeNode(parent.type); - case 187: + case 192: return getContextualTypeForBinaryOperand(node); - case 253: - case 254: + case 257: + case 258: return getContextualTypeForObjectLiteralElement(parent); - case 170: + case 175: return getContextualTypeForElementExpression(node); - case 188: + case 193: return getContextualTypeForConditionalOperand(node); - case 197: - ts.Debug.assert(parent.parent.kind === 189); + case 202: + ts.Debug.assert(parent.parent.kind === 194); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 178: + case 183: return getContextualType(parent); - case 248: + case 252: return getContextualType(parent); - case 246: - case 247: + case 250: + case 251: return getContextualTypeForJsxAttribute(parent); } return undefined; } - function getNonGenericSignature(type) { + function getNonGenericSignature(type, node) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 179 || node.kind === 180; + return node.kind === 184 || node.kind === 185; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -26486,19 +30002,19 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 524288)) { - return getNonGenericSignature(type); + if (!(type.flags & 65536)) { + return getNonGenericSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; - var signature = getNonGenericSignature(current); + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { signatureList = [signature]; @@ -26522,13 +30038,13 @@ var ts; function isInferentialContext(mapper) { return mapper && mapper.context; } - function checkSpreadElementExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node, contextualMapper) { + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 169 && !!node.initializer) || - (node.kind === 187 && node.operatorToken.kind === 56); + return (node.kind === 174 && !!node.initializer) || + (node.kind === 192 && node.operatorToken.kind === 57); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -26537,7 +30053,7 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 191) { + if (inDestructuringPattern && e.kind === 196) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -26549,7 +30065,7 @@ var ts; var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 191; + hasSpreadElement = hasSpreadElement || e.kind === 196; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -26560,7 +30076,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 168 || pattern.kind === 170)) { + if (pattern && (pattern.kind === 173 || pattern.kind === 175)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -26568,7 +30084,7 @@ var ts; elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 193) { + if (patternElement.kind !== 198) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -26585,7 +30101,7 @@ var ts; strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { - return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 142 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); @@ -26603,7 +30119,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 262178 | 512)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -26612,10 +30128,10 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(node, properties, kind) { + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(node.properties[i].name)) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -26627,35 +30143,38 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createMap(); var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 167 || contextualType.pattern.kind === 171); + (contextualType.pattern.kind === 172 || contextualType.pattern.kind === 176); var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var memberDecl = _a[_i]; + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; var member = memberDecl.symbol; - if (memberDecl.kind === 253 || - memberDecl.kind === 254 || + if (memberDecl.kind === 257 || + memberDecl.kind === 258 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 253) { + if (memberDecl.kind === 257) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 147) { + else if (memberDecl.kind === 149) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 254); + ts.Debug.assert(memberDecl.kind === 258); type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 253 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 254 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 257 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 258 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } @@ -26663,12 +30182,12 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -26681,8 +30200,29 @@ var ts; prop.target = member; member = prop; } + else if (memberDecl.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + propertiesArray = []; + propertiesTable = ts.createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, false); + offset = i + 1; + continue; + } else { - ts.Debug.assert(memberDecl.kind === 149 || memberDecl.kind === 150); + ts.Debug.assert(memberDecl.kind === 151 || memberDecl.kind === 152); checkAccessorDeclaration(memberDecl); } if (ts.hasDynamicName(memberDecl)) { @@ -26699,8 +30239,8 @@ var ts; propertiesArray.push(member); } if (contextualTypeHasPattern) { - for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { - var prop = _c[_b]; + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); @@ -26710,15 +30250,40 @@ var ts; } } } - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); - if (inDestructuringPattern) { - result.pattern = node; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), true); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - return result; + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); @@ -26735,13 +30300,13 @@ var ts; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 248: + case 252: checkJsxExpression(child); break; - case 241: + case 246: checkJsxElement(child); break; - case 242: + case 247: checkJsxSelfClosingElement(child); break; } @@ -26752,7 +30317,7 @@ var ts; return name.indexOf("-") < 0; } function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 172 || tagName.kind === 97) { + if (tagName.kind === 177 || tagName.kind === 98) { return false; } else { @@ -26768,7 +30333,7 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); + var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); if (attributeType) { correspondingPropType = attributeType; } @@ -26794,6 +30359,9 @@ var ts; return exprType; } function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + if (compilerOptions.jsx === 2) { + checkExternalEmitHelpers(node, 2); + } var type = checkExpression(node.expression); var props = getPropertiesOfType(type); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { @@ -26843,7 +30411,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 65536)); if (isTypeAny(valueType)) { return anyType; } @@ -26855,7 +30423,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -26882,9 +30450,9 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 65536) { var types = elemType.types; - return getUnionType(types.map(function (type) { + return getUnionType(ts.map(types, function (type) { return getResolvedJsxType(node, type, elemClassType); }), true); } @@ -26944,7 +30512,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 65536) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -27021,20 +30589,23 @@ var ts; checkGrammarJsxElement(node); checkJsxPreconditions(node); var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactNamespace = getJsxNamespace(); var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + reactSym.isReferenced = true; + if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = ts.createMap(); var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 246) { + if (node.attributes[i].kind === 250) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 247); + ts.Debug.assert(node.attributes[i].kind === 251); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -27060,7 +30631,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 145; + return s.valueDeclaration ? s.valueDeclaration.kind : 147; } function getDeclarationModifierFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; @@ -27071,11 +30642,11 @@ var ts; function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); - var errorNode = node.kind === 172 || node.kind === 218 ? + var errorNode = node.kind === 177 || node.kind === 223 ? node.name : node.right; - if (left.kind === 95) { - if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 147) { + if (left.kind === 96) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 149) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -27095,7 +30666,7 @@ var ts; } return true; } - if (left.kind === 95) { + if (left.kind === 96) { return true; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { @@ -27109,10 +30680,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -27138,6 +30709,33 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { + if (prop.flags & 16777216) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -27150,48 +30748,33 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & 32) { checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (node.kind !== 172 || ts.isAssignmentTarget(node) || + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } + if (node.kind !== 177 || assignmentKind === 1 || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 65536)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 524288 && !(containingType.flags & 8190)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + var flowType = getFlowTypeOfReference(node, propType, true, undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 172 + var left = node.kind === 177 ? node.expression : node.left; var type = checkExpression(left); @@ -27205,13 +30788,13 @@ var ts; } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 219) { + if (initializer.kind === 224) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 69) { + else if (initializer.kind === 70) { return getResolvedSymbol(initializer); } return undefined; @@ -27220,17 +30803,17 @@ var ts; return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); } function isForInVariableForNumericPropertyNames(expr) { - var e = skipParenthesizedNodes(expr); - if (e.kind === 69) { + var e = ts.skipParentheses(expr); + if (e.kind === 70) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 207 && + if (node.kind === 212 && child === node.statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression(node.expression))) { + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { return true; } child = node; @@ -27241,9 +30824,11 @@ var ts; return false; } function checkIndexedAccess(node) { - if (!node.argumentExpression) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 175 && node.parent.expression === node) { + if (node.parent.kind === 180 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -27253,71 +30838,17 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } + return unknownType; } - var objectType = getApparentType(checkNonNullExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - var isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== 9)) { - error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); - 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_18, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - var numberIndexInfo = getIndexInfoOfType(objectType, 1); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - var stringIndexInfo = getIndexInfoOfType(objectType, 0); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, 1) ? - ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - return anyType; - } - error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - return unknownType; - } - function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { - if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { - return indexArgumentExpression.text; - } - if (indexArgumentExpression.kind === 173 || indexArgumentExpression.kind === 172) { - var value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, false)) { - var rightHandSideName = indexArgumentExpression.name.text; - return ts.getPropertyNameForKnownSymbolName(rightHandSideName); - } - return undefined; + return getIndexedAccessType(objectType, indexType, node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { @@ -27350,10 +30881,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 176) { + if (node.kind === 181) { checkExpression(node.template); } - else if (node.kind !== 143) { + else if (node.kind !== 145) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -27375,19 +30906,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_8 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_8 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_8; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_8; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -27404,7 +30935,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 191) { + if (arg && arg.kind === 196) { return i; } } @@ -27417,11 +30948,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 176) { + if (node.kind === 181) { var tagExpression = node; argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 189) { + if (tagExpression.template.kind === 194) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -27429,11 +30960,11 @@ var ts; } else { var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 11); + ts.Debug.assert(templateLiteral.kind === 12); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 143) { + else if (node.kind === 145) { isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); @@ -27441,7 +30972,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 175); + ts.Debug.assert(callExpression.kind === 180); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -27464,7 +30995,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 32768) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -27476,7 +31007,7 @@ var ts; function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { var context = createInferenceContext(signature, true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -27495,19 +31026,19 @@ var ts; if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } if (excludeArgument) { @@ -27515,7 +31046,7 @@ var ts; if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -27547,7 +31078,7 @@ var ts; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 175) { + if (thisType && thisType !== voidType && node.kind !== 180) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -27560,9 +31091,9 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 193) { + if (arg === undefined || arg.kind !== 198) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } @@ -27575,28 +31106,28 @@ var ts; return true; } function getThisArgumentOfCall(node) { - if (node.kind === 174) { + if (node.kind === 179) { var callee = node.expression; - if (callee.kind === 172) { + if (callee.kind === 177) { return callee.expression; } - else if (callee.kind === 173) { + else if (callee.kind === 178) { return callee.expression; } } } function getEffectiveCallArguments(node) { var args; - if (node.kind === 176) { + if (node.kind === 181) { var template = node.template; args = [undefined]; - if (template.kind === 189) { + if (template.kind === 194) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 143) { + else if (node.kind === 145) { return undefined; } else { @@ -27605,21 +31136,21 @@ var ts; return args; } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 143) { + if (node.kind === 145) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return 1; - case 145: - return 2; case 147: + return 2; case 149: - case 150: + case 151: + case 152: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 142: + case 144: return 3; } } @@ -27628,48 +31159,48 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { node = node.parent; - if (node.kind === 148) { + if (node.kind === 150) { return anyType; } } - if (node.kind === 145 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 149 || - node.kind === 150) { + node.kind === 151 || + node.kind === 152) { var element = node; switch (element.name.kind) { - case 69: + case 70: case 8: case 9: return getLiteralTypeForText(32, element.name.text); - case 140: + case 142: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512)) { return nameType; @@ -27686,20 +31217,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 221) { + if (node.kind === 226) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 142) { + if (node.kind === 144) { return numberType; } - if (node.kind === 145) { + if (node.kind === 147) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 147 || - node.kind === 149 || - node.kind === 150) { + if (node.kind === 149 || + node.kind === 151 || + node.kind === 152) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -27719,27 +31250,27 @@ var ts; ts.Debug.fail("Decorators should not have a fourth synthetic argument."); return unknownType; } - function getEffectiveArgumentType(node, argIndex, arg) { - if (node.kind === 143) { + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 145) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return getGlobalTemplateStringsArrayType(); } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 143 || - (argIndex === 0 && node.kind === 176)) { + if (node.kind === 145 || + (argIndex === 0 && node.kind === 181)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 143) { + if (node.kind === 145) { return node.expression; } - else if (argIndex === 0 && node.kind === 176) { + else if (argIndex === 0 && node.kind === 181) { return node.template; } else { @@ -27747,12 +31278,12 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 176; - var isDecorator = node.kind === 143; + var isTaggedTemplate = node.kind === 181; + var isDecorator = node.kind === 145; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; - if (node.expression.kind !== 95) { + if (node.expression.kind !== 96) { ts.forEach(typeArguments, checkSourceElement); } } @@ -27778,7 +31309,7 @@ var ts; var candidateForTypeArgumentError; var resultOfFailedInference; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 174 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -27797,7 +31328,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -27818,7 +31349,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -27850,7 +31381,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -27893,7 +31424,7 @@ var ts; } } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); @@ -27939,7 +31470,7 @@ var ts; return true; } if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { + if (funcType.flags & 65536) { return false; } return isTypeAssignableTo(funcType, globalFunctionType); @@ -28009,12 +31540,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -28046,16 +31578,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 221: - case 192: + case 226: + case 197: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 142: + case 144: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 145: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 147: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 149: - case 150: + case 151: + case 152: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -28082,13 +31614,13 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 174: + case 179: return resolveCallExpression(node, candidatesOutArray); - case 175: + case 180: return resolveNewExpression(node, candidatesOutArray); - case 176: + case 181: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 143: + case 145: return resolveDecorator(node, candidatesOutArray); } ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); @@ -28117,17 +31649,17 @@ var ts; function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 95) { + if (node.expression.kind === 96) { return voidType; } - if (node.kind === 175) { + if (node.kind === 180) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 148 && - declaration.kind !== 152 && - declaration.kind !== 157 && + declaration.kind !== 150 && + declaration.kind !== 154 && + declaration.kind !== 159 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 69 ? + var funcSymbol = node.expression.kind === 70 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { @@ -28139,11 +31671,33 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, true)) { + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 8388608) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 225 + : resolvedRequire.flags & 3 + ? 223 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } function checkTaggedTemplateExpression(node) { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -28179,21 +31733,36 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } function assignBindingElementTypes(node) { @@ -28201,7 +31770,7 @@ var ts; for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 69) { + if (element.name.kind === 70) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } assignBindingElementTypes(element); @@ -28214,14 +31783,14 @@ var ts; if (!links.type) { links.type = instantiateType(contextualType, mapper); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 167 || - parameter.valueDeclaration.name.kind === 168)) { + (parameter.valueDeclaration.name.kind === 172 || + parameter.valueDeclaration.name.kind === 173)) { links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); } assignBindingElementTypes(parameter.valueDeclaration); } else if (isInferentialContext(mapper)) { - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } function getReturnTypeFromJSDocComment(func) { @@ -28242,7 +31811,7 @@ var ts; 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); + error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } return promiseType; @@ -28254,7 +31823,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 199) { + if (func.body.kind !== 204) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -28290,7 +31859,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28316,7 +31887,7 @@ var ts; if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(node.expression); + var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -28324,14 +31895,14 @@ var ts; if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 128)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + if (lastStatement && lastStatement.kind === 218 && isExhaustiveSwitchStatement(lastStatement)) { return false; } return true; @@ -28360,7 +31931,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 179 || func.kind === 180)) { + func.kind === 184 || func.kind === 185)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -28377,7 +31948,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; @@ -28404,9 +31975,9 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 179) { + if (!hasGrammarError && node.kind === 184) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -28440,14 +32011,14 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 149) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 147 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); if (!node.asteriskToken) { @@ -28457,7 +32028,7 @@ var ts; if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 199) { + if (node.body.kind === 204) { checkSourceElement(node.body); } else { @@ -28492,10 +32063,10 @@ var ts; function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 172 || expr.kind === 173) && - expr.expression.kind === 97) { + (expr.kind === 177 || expr.kind === 178) && + expr.expression.kind === 98) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 148)) + if (!(func && func.kind === 150)) return true; return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } @@ -28504,44 +32075,24 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 172 || expr.kind === 173) { - var node = skipParenthesizedNodes(expr.expression); - if (node.kind === 69) { + if (expr.kind === 177 || expr.kind === 178) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 70) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 8388608) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 232; + return declaration && declaration.kind === 237; } } } return false; } - function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { - var node = skipParenthesizedNodes(expr); - if (node.kind !== 69 && node.kind !== 172 && node.kind !== 173) { + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipParentheses(expr); + if (node.kind !== 70 && node.kind !== 177 && node.kind !== 178) { error(expr, invalidReferenceMessage); return false; } - var links = getNodeLinks(node); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - if (node.kind === 69 && !(symbol.flags & 3)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === 173) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } function checkDeleteExpression(node) { @@ -28558,7 +32109,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 262144)) { + if (!(node.flags & 16384)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -28573,27 +32124,27 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 36 && node.operand.kind === 8) { + if (node.operator === 37 && node.operand.kind === 8) { return getFreshTypeOfLiteralType(getLiteralTypeForText(64, "" + -node.operand.text)); } switch (node.operator) { - case 35: case 36: - case 50: + case 37: + case 51: if (maybeTypeOfKind(operandType, 512)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 49: + case 50: var facts = getTypeFacts(operandType) & (1048576 | 2097152); return facts === 1048576 ? falseType : facts === 2097152 ? trueType : booleanType; - case 41: case 42: + case 43: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -28606,7 +32157,7 @@ var ts; } var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -28614,10 +32165,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -28629,20 +32180,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { - var t = types_16[_a]; + for (var _a = 0, types_17 = types; _a < types_17.length; _a++) { + var t = types_17[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -28651,7 +32202,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -28672,39 +32223,39 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 | 512))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var p = properties_4[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { - if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 257 || property.kind === 258) { + var name_22 = property.name; + if (name_22.kind === 142) { + checkComputedPropertyName(name_22); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_22)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = ts.getTextOfPropertyName(name_22); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || getIndexTypeOfType(objectLiteralType, 0); if (type) { - if (property.kind === 254) { + if (property.kind === 258) { return checkDestructuringAssignment(property, type); } else { @@ -28712,9 +32263,22 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_22, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_22)); } } + else if (property.kind === 259) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, ts.Diagnostics.Property_assignment_expected); } @@ -28730,8 +32294,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 193) { - if (element.kind !== 191) { + if (element.kind !== 198) { + if (element.kind !== 196) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -28753,11 +32317,11 @@ var ts; } else { if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { var restExpression = element.expression; - if (restExpression.kind === 187 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 192 && restExpression.operatorToken.kind === 57) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -28770,7 +32334,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 254) { + if (exprOrAssignment.kind === 258) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && @@ -28784,21 +32348,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 187 && target.operatorToken.kind === 56) { + if (target.kind === 192 && target.operatorToken.kind === 57) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 171) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + if (target.kind === 176) { + return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 170) { + if (target.kind === 175) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + var error = target.parent.kind === 259 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); } return sourceType; @@ -28806,49 +32373,49 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 69: + case 70: case 9: - case 10: - case 176: - case 189: case 11: + case 181: + case 194: + case 12: case 8: - case 99: - case 84: - case 93: - case 135: - case 179: - case 192: - case 180: - case 170: - case 171: - case 182: - case 196: - case 242: - case 241: + case 100: + case 85: + case 94: + case 137: + case 184: + case 197: + case 185: + case 175: + case 176: + case 187: + case 201: + case 247: + case 246: return true; - case 188: + case 193: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 187: + case 192: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 185: - case 186: + case 190: + case 191: switch (node.operator) { - case 49: - case 35: - case 36: case 50: + case 36: + case 37: + case 51: return true; } return false; - case 183: - case 177: - case 195: + case 188: + case 182: + case 200: default: return false; } @@ -28868,34 +32435,34 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 171 || left.kind === 170)) { + if (operator === 57 && (left.kind === 176 || left.kind === 175)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); var rightType = checkExpression(right, contextualMapper); switch (operator) { - case 37: case 38: - case 59: - case 60: case 39: + case 60: case 61: case 40: case 62: - case 36: - case 58: - case 43: + case 41: case 63: + case 37: + case 59: case 44: case 64: case 45: case 65: - case 47: - case 67: - case 48: - case 68: case 46: case 66: + case 48: + case 68: + case 49: + case 69: + case 47: + case 67: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -28919,8 +32486,8 @@ var ts; } } return numberType; - case 35: - case 57: + case 36: + case 58: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -28935,7 +32502,7 @@ var ts; resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -28949,24 +32516,26 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 57) { + if (operator === 58) { checkAssignmentOperator(resultType); } return resultType; - case 25: - case 27: + case 26: case 28: case 29: + case 30: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } } return booleanType; - case 30: case 31: case 32: case 33: + case 34: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -28977,22 +32546,22 @@ var ts; reportOperatorError(); } return booleanType; - case 91: + case 92: return checkInstanceOfExpression(left, right, leftType, rightType); - case 90: + case 91: return checkInExpression(left, right, leftType, rightType); - case 51: + case 52: return getTypeFacts(leftType) & 1048576 ? includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; - case 52: + case 53: return getTypeFacts(leftType) & 2097152 ? getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : leftType; - case 56: + case 57: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 24: + case 25: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -29010,23 +32579,22 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { + case 48: + case 68: + return 53; + case 49: + case 69: + return 34; case 47: case 67: return 52; - case 48: - case 68: - return 33; - case 46: - case 66: - return 51; default: return undefined; } } function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 56 && operator <= 68) { - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - if (ok) { + if (produceDiagnostics && operator >= 57 && operator <= 69) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { checkTypeAssignableTo(valueType, leftType, left, undefined); } } @@ -29052,7 +32620,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.flags & 65536) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -29096,9 +32664,9 @@ var ts; return getFreshTypeOfLiteralType(getLiteralTypeForText(32, node.text)); case 8: return getFreshTypeOfLiteralType(getLiteralTypeForText(64, node.text)); - case 99: + case 100: return trueType; - case 84: + case 85: return falseType; } } @@ -29126,25 +32694,25 @@ var ts; return links.resolvedType; } function isTypeAssertion(node) { - node = skipParenthesizedNodes(node); - return node.kind === 177 || node.kind === 195; + node = ts.skipParentheses(node); + return node.kind === 182 || node.kind === 200; } function checkDeclarationInitializer(declaration) { var type = checkExpressionCached(declaration.initializer); return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, 480); + return maybeTypeOfKind(contextualType, (480 | 262144)); } return false; } @@ -29153,14 +32721,14 @@ var ts; return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -29181,9 +32749,19 @@ var ts; } return type; } + function getTypeOfExpression(node) { + if (node.kind === 179 && node.expression.kind !== 96) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return checkExpression(node); + } function checkExpression(node, contextualMapper) { var type; - if (node.kind === 139) { + if (node.kind === 141) { type = checkQualifiedName(node); } else { @@ -29191,9 +32769,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 172 && node.parent.expression === node) || - (node.parent.kind === 173 && node.parent.expression === node) || - ((node.kind === 69 || node.kind === 139) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 177 && node.parent.expression === node) || + (node.parent.kind === 178 && node.parent.expression === node) || + ((node.kind === 70 || node.kind === 141) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -29202,79 +32780,79 @@ var ts; } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { - case 69: + case 70: return checkIdentifier(node); - case 97: + case 98: return checkThisExpression(node); - case 95: + case 96: return checkSuperExpression(node); - case 93: + case 94: return nullWideningType; case 9: case 8: - case 99: - case 84: + case 100: + case 85: return checkLiteralExpression(node); - case 189: + case 194: return checkTemplateExpression(node); - case 11: + case 12: return stringType; - case 10: + case 11: return globalRegExpType; - case 170: - return checkArrayLiteral(node, contextualMapper); - case 171: - return checkObjectLiteral(node, contextualMapper); - case 172: - return checkPropertyAccessExpression(node); - case 173: - return checkIndexedAccess(node); - case 174: case 175: - return checkCallExpression(node); + return checkArrayLiteral(node, contextualMapper); case 176: - return checkTaggedTemplateExpression(node); + return checkObjectLiteral(node, contextualMapper); + case 177: + return checkPropertyAccessExpression(node); case 178: - return checkExpression(node.expression, contextualMapper); - case 192: - return checkClassExpression(node); + return checkIndexedAccess(node); case 179: case 180: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 182: - return checkTypeOfExpression(node); - case 177: - case 195: - return checkAssertion(node); - case 196: - return checkNonNullAssertion(node); + return checkCallExpression(node); case 181: - return checkDeleteExpression(node); + return checkTaggedTemplateExpression(node); case 183: - return checkVoidExpression(node); + return checkExpression(node.expression, contextualMapper); + case 197: + return checkClassExpression(node); case 184: - return checkAwaitExpression(node); case 185: - return checkPrefixUnaryExpression(node); - case 186: - return checkPostfixUnaryExpression(node); + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 187: - return checkBinaryExpression(node, contextualMapper); + return checkTypeOfExpression(node); + case 182: + case 200: + return checkAssertion(node); + case 201: + return checkNonNullAssertion(node); + case 186: + return checkDeleteExpression(node); case 188: - return checkConditionalExpression(node, contextualMapper); - case 191: - return checkSpreadElementExpression(node, contextualMapper); - case 193: - return undefinedWideningType; + return checkVoidExpression(node); + case 189: + return checkAwaitExpression(node); case 190: + return checkPrefixUnaryExpression(node); + case 191: + return checkPostfixUnaryExpression(node); + case 192: + return checkBinaryExpression(node, contextualMapper); + case 193: + return checkConditionalExpression(node, contextualMapper); + case 196: + return checkSpreadExpression(node, contextualMapper); + case 198: + return undefinedWideningType; + case 195: return checkYieldExpression(node); - case 248: + case 252: return checkJsxExpression(node); - case 241: + case 246: return checkJsxElement(node); - case 242: + case 247: return checkJsxSelfClosingElement(node); - case 243: + case 248: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -29295,7 +32873,7 @@ var ts; var func = ts.getContainingFunction(node); if (ts.getModifierFlags(node) & 92) { func = ts.getContainingFunction(node); - if (!(func.kind === 148 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 150 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -29306,7 +32884,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); } - if (func.kind === 148 || func.kind === 152 || func.kind === 157) { + if (func.kind === 150 || func.kind === 154 || func.kind === 159) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -29318,15 +32896,15 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 147 || - node.kind === 220 || - node.kind === 179; + return node.kind === 149 || + node.kind === 225 || + node.kind === 184; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 69 && + if (param.name.kind === 70 && param.name.text === parameter.text) { return i; } @@ -29361,9 +32939,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_23 = _a[_i].name; + if (ts.isBindingPattern(name_23) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_23, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29376,16 +32954,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 180: - case 151: - case 220: - case 179: - case 156: - case 147: - case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + case 185: + case 153: + case 225: + case 184: + case 158: + case 149: + case 148: + var parent_9 = node.parent; + if (node === parent_9.type) { + return parent_9; } } } @@ -29395,29 +32973,35 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_24 = element.name; + if (name_24.kind === 70 && + name_24.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_24.kind === 173 || + name_24.kind === 172) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_24, predicateVariableNode, predicateVariableName)) { return true; } } } } function checkSignatureDeclaration(node) { - if (node.kind === 153) { + if (node.kind === 155) { checkGrammarIndexSignature(node); } - else if (node.kind === 156 || node.kind === 220 || node.kind === 157 || - node.kind === 151 || node.kind === 148 || - node.kind === 152) { + else if (node.kind === 158 || node.kind === 225 || node.kind === 159 || + node.kind === 153 || node.kind === 150 || + node.kind === 154) { checkGrammarFunctionLikeDeclaration(node); } + if (ts.isAsyncFunctionLike(node) && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { @@ -29427,10 +33011,10 @@ var ts; checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 152: + case 154: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 151: + case 153: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -29461,7 +33045,7 @@ var ts; var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { @@ -29470,18 +33054,18 @@ var ts; } } else { - var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114; }); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 149: + case 151: addName(names, member.name, memberName, 1); break; - case 150: + case 152: addName(names, member.name, memberName, 2); break; - case 145: + case 147: addName(names, member.name, memberName, 3); break; } @@ -29507,12 +33091,12 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind == 144) { + if (member.kind == 146) { var memberName = void 0; switch (member.name.kind) { case 9: case 8: - case 69: + case 70: memberName = member.name.text; break; default: @@ -29529,7 +33113,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 222) { + if (node.kind === 227) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -29544,7 +33128,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 132: + case 134: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -29552,7 +33136,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 130: + case 132: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -29596,7 +33180,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29608,20 +33192,21 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function markThisReferencesAsErrors(n) { - if (n.kind === 97) { + if (n.kind === 98) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 179 && n.kind !== 220) { + else if (n.kind !== 184 && n.kind !== 225) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 145 && + return n.kind === 147 && !(ts.getModifierFlags(n) & 32) && !!n.initializer; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29633,9 +33218,9 @@ var ts; if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -29658,18 +33243,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 149) { + if (node.kind === 151) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 149 ? 150 : 149; + var otherKind = node.kind === 151 ? 152 : 151; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { @@ -29683,11 +33268,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { + if (node.kind === 151) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - if (node.parent.kind !== 171) { + if (node.parent.kind !== 176) { checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); } @@ -29717,7 +33302,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -29768,14 +33353,25 @@ var ts; function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node) { + getTypeFromIndexedAccessTypeNode(node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } function isPrivateWithinAmbient(node) { return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 222 && - n.parent.kind !== 221 && - n.parent.kind !== 192 && + if (n.parent.kind !== 227 && + n.parent.kind !== 226 && + n.parent.kind !== 197 && ts.isInAmbientContext(n)) { if (!(flags & 2)) { flags |= 1; @@ -29852,7 +33448,7 @@ var ts; if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 147 || node.kind === 146) && + var reportError = (node.kind === 149 || node.kind === 148) && (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); if (reportError) { var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -29885,11 +33481,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 222 || node.parent.kind === 159 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 227 || node.parent.kind === 161 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 220 || node.kind === 147 || node.kind === 146 || node.kind === 148) { + if (node.kind === 225 || node.kind === 149 || node.kind === 148 || node.kind === 150) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -30000,20 +33596,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 222: + case 227: return 2097152; - case 225: + case 230: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 221: - case 224: - return 2097152 | 1048576; + case 226: case 229: - var result_2 = 0; + return 2097152 | 1048576; + case 234: + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; default: return 1048576; } @@ -30036,7 +33632,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (getObjectFlags(promise) & 4) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -30054,7 +33650,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -30073,7 +33669,7 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 65536) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -30101,51 +33697,50 @@ var ts; } } } - function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - error(location, diagnostic, typeName); - return unknownType; - } function checkAsyncFunctionReturnType(node) { + var returnType = getTypeFromTypeNode(node.type); if (languageVersion >= 2) { - var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - return unknownType; + else { + markTypeNodeAsReferenced(node.type); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } } - var promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - return unknownType; - } - var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - var typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } - checkReturnTypeAnnotationAsExpression(node); - var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } - var promiseName = ts.getEntityNameFromTypeNode(node.type); - var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); - return unknownType; - } - return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } function checkDecorator(node) { var signature = getResolvedSignature(node); @@ -30157,22 +33752,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 221: + case 226: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 142: + case 144: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 145: + case 147: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 147: case 149: - case 150: + case 151: + case 152: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -30180,30 +33775,19 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } - function checkTypeNodeAsExpression(node) { - if (node && node.kind === 155) { - var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; - var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); - if (rootSymbol && rootSymbol.flags & 8388608) { - var aliasTarget = resolveAlias(rootSymbol); - if (aliasTarget.flags & 107455 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } + function markTypeNodeAsReferenced(node) { + var typeName = node && ts.getEntityNameFromTypeNode(node); + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 70 ? 793064 : 1920) | 8388608, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 8388608 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } - function checkTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkReturnTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkParameterTypeAnnotationsAsExpressions(node) { - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - checkTypeAnnotationAsExpression(parameter); - } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; } function checkDecorators(node) { if (!node.decorators) { @@ -30215,23 +33799,37 @@ var ts; if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 144) { + checkExternalEmitHelpers(firstDecorator, 32); + } if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 221: + case 226: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; - case 147: case 149: - case 150: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + case 151: + case 152: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markTypeNodeAsReferenced(node.type); break; - case 145: - case 142: - checkTypeAnnotationAsExpression(node); + case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + case 144: + markTypeNodeAsReferenced(node.type); break; } } @@ -30250,7 +33848,7 @@ var ts; checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (node.name && node.name.kind === 140) { + if (node.name && node.name.kind === 142) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { @@ -30292,43 +33890,43 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 256: - case 225: + case 261: + case 230: checkUnusedModuleMembers(node); break; - case 221: - case 192: + case 226: + case 197: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 222: + case 227: checkUnusedTypeParameters(node); break; - case 199: - case 227: - case 206: - case 207: - case 208: + case 204: + case 232: + case 211: + case 212: + case 213: checkUnusedLocalsAndParameters(node); break; - case 148: - case 179: - case 220: - case 180: - case 147: - case 149: case 150: + case 184: + case 225: + case 185: + case 149: + case 151: + case 152: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 146: - case 151: - case 152: + case 148: case 153: - case 156: - case 157: + case 154: + case 155: + case 158: + case 159: checkUnusedTypeParameters(node); break; } @@ -30337,46 +33935,66 @@ var ts; } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function (key) { + if (node.parent.kind !== 227 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + var _loop_2 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144) { + var parameter = ts.getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !ts.parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); } } }; for (var key in node.locals) { - _loop_1(key); + _loop_2(key); } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; } - function parameterNameStartsWithUnderscore(parameter) { - return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 223 && + (declaration.parent.parent.kind === 212 || + declaration.parent.parent.kind === 213)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 70 && node.text.charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 147 || member.kind === 145) { + if (member.kind === 149 || member.kind === 147) { if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } - else if (member.kind === 148) { + else if (member.kind === 150) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { @@ -30421,7 +34039,7 @@ var ts; } } function checkBlock(node) { - if (node.kind === 199) { + if (node.kind === 204) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -30443,19 +34061,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 145 || - node.kind === 144 || - node.kind === 147 || + if (node.kind === 147 || node.kind === 146 || node.kind === 149 || - node.kind === 150) { + node.kind === 148 || + node.kind === 151 || + node.kind === 152) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 142 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 144 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -30469,7 +34087,7 @@ var ts; var current = node; while (current) { if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 69; + var isDeclaration_1 = node.kind !== 70; if (isDeclaration_1) { error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -30490,7 +34108,7 @@ var ts; return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_2 = node.kind !== 69; + var isDeclaration_2 = node.kind !== 70; if (isDeclaration_2) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -30500,26 +34118,29 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 225 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 230 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 256 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192) { + if (parent.kind === 261 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -30527,7 +34148,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 218 && !node.initializer) { + if (node.kind === 223 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -30537,25 +34158,25 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219); - var container = varDeclList.parent.kind === 200 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224); + var container = varDeclList.parent.kind === 205 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 199 && ts.isFunctionLike(container.parent) || - container.kind === 226 || - container.kind === 225 || - container.kind === 256); + (container.kind === 204 && ts.isFunctionLike(container.parent) || + container.kind === 231 || + container.kind === 230 || + container.kind === 261); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_25 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_25, name_25); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 142) { + if (ts.getRootDeclaration(node).kind !== 144) { return; } var func = ts.getContainingFunction(node); @@ -30564,10 +34185,10 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 172) { + if (n.kind === 177) { return visit(n.expression); } - else if (n.kind === 69) { + else if (n.kind === 70) { var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; @@ -30578,7 +34199,7 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 142) { + if (symbol.valueDeclaration.kind === 144) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -30587,7 +34208,7 @@ var ts; if (ts.isFunctionLike(current.parent)) { return; } - if (current.parent.kind === 145 && + if (current.parent.kind === 147 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)) { return; @@ -30603,51 +34224,58 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 140) { + if (node.name.kind === 142) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 169) { - if (node.propertyName && node.propertyName.kind === 140) { + if (node.kind === 174) { + if (node.parent.kind === 172 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 142) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_10 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_10); + var name_26 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_26)); + markPropertyAsReferenced(property); + if (parent_10.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 142 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 144 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 207) { + if (node.initializer && node.parent.parent.kind !== 212) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -30659,9 +34287,9 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 145 && node.kind !== 144) { + if (node.kind !== 147 && node.kind !== 146) { checkExportsOnMergedDeclarations(node); - if (node.kind === 218 || node.kind === 169) { + if (node.kind === 223 || node.kind === 174) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -30671,8 +34299,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 142 && right.kind === 218) || - (left.kind === 218 && right.kind === 142)) { + if ((left.kind === 144 && right.kind === 223) || + (left.kind === 223 && right.kind === 144)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -30699,7 +34327,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 171) { + if (node.modifiers && node.parent.kind === 176) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -30718,7 +34346,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 201) { + if (node.thenStatement.kind === 206) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -30735,12 +34363,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 219) { + if (node.initializer && node.initializer.kind === 224) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -30758,18 +34386,18 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + if (node.initializer.kind === 224) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -30782,7 +34410,8 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 219) { + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 224) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -30792,18 +34421,17 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 170 || varExpr.kind === 171) { + if (varExpr.kind === 175 || varExpr.kind === 176) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -30856,7 +34484,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -30882,7 +34510,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -30917,7 +34545,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & 4) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -30926,10 +34554,14 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 65536) { + var arrayTypes = arrayOrStringType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 262178) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -30954,7 +34586,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 262178) { return stringType; } return getUnionType([arrayElementType, stringType], true); @@ -30965,7 +34597,7 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 149 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 150))); + return !!(node.kind === 151 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; @@ -30987,12 +34619,12 @@ var ts; if (func.asteriskToken) { return; } - if (func.kind === 150) { + if (func.kind === 152) { if (node.expression) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 148) { + else if (func.kind === 150) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -31010,27 +34642,33 @@ var ts; } } } - else if (func.kind !== 148 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 150 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 262144) { + if (node.flags & 16384) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 250 && !hasDuplicateDefaultClause) { + if (clause.kind === 254 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -31042,11 +34680,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 249) { + if (produceDiagnostics && clause.kind === 253) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { - checkTypeComparableTo(caseType, expressionType, caseClause.expression, undefined); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -31062,7 +34706,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 214 && current.label.text === node.label.text) { + if (current.kind === 219 && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -31088,22 +34732,20 @@ var ts; var catchClause = node.catchClause; if (catchClause) { if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== 69) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = catchClause.variableDeclaration.name.text; - var locals = catchClause.block.locals; - if (locals) { - var localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & 2) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + var blockLocals = catchClause.block.locals; + if (blockLocals) { + for (var caughtName in catchClause.locals) { + var blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -31125,7 +34767,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -31140,7 +34782,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -31156,13 +34798,13 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 140 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 142 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -31207,7 +34849,7 @@ var ts; var firstDecl; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 || declaration.kind === 222) { + if (declaration.kind === 226 || declaration.kind === 227) { if (!firstDecl) { firstDecl = declaration; } @@ -31253,6 +34895,9 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType_1 = baseTypes[0]; @@ -31270,7 +34915,9 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (baseType_1.symbol.valueDeclaration && + !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) && + baseType_1.symbol.valueDeclaration.kind === 226) { if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -31295,8 +34942,8 @@ var ts; if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = getObjectFlags(t) & 4 ? t.target : t; + if (getObjectFlags(declaredType) & 3) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -31318,7 +34965,7 @@ var ts; if (declaration && ts.getModifierFlags(declaration) & 8) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -31344,7 +34991,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 192) { + if (derivedClassDecl.kind === 197) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -31388,7 +35035,7 @@ var ts; } } function isAccessor(kind) { - return kind === 149 || kind === 150; + return kind === 151 || kind === 152; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -31426,8 +35073,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var prop = properties_5[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen[prop.name]; if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; @@ -31455,7 +35102,7 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(node, symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 222); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -31484,6 +35131,7 @@ var ts; function checkTypeAliasDeclaration(node) { checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } function computeEnumMemberValues(node) { @@ -31500,7 +35148,7 @@ var ts; error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - var text = getTextOfPropertyName(member.name); + var text = ts.getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -31550,18 +35198,18 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 185: + case 190: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; } switch (e.operator) { - case 35: return value_1; - case 36: return -value_1; - case 50: return ~value_1; + case 36: return value_1; + case 37: return -value_1; + case 51: return ~value_1; } return undefined; - case 187: + case 192: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -31571,37 +35219,37 @@ var ts; return undefined; } switch (e.operatorToken.kind) { - case 47: return left | right; - case 46: return left & right; - case 44: return left >> right; - case 45: return left >>> right; - case 43: return left << right; - case 48: return left ^ right; - case 37: return left * right; - case 39: return left / right; - case 35: return left + right; - case 36: return left - right; - case 40: return left % right; + case 48: return left | right; + case 47: return left & right; + case 45: return left >> right; + case 46: return left >>> right; + case 44: return left << right; + case 49: return left ^ right; + case 38: return left * right; + case 40: return left / right; + case 36: return left + right; + case 37: return left - right; + case 41: return left % right; } return undefined; case 8: return +e.text; - case 178: + case 183: return evalConstant(e.expression); - case 69: - case 173: - case 172: + case 70: + case 178: + case 177: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; var propertyName = void 0; - if (e.kind === 69) { + if (e.kind === 70) { enumType_1 = currentType; propertyName = e.text; } else { var expression = void 0; - if (e.kind === 173) { + if (e.kind === 178) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -31615,17 +35263,17 @@ var ts; } var current = expression; while (current) { - if (current.kind === 69) { + if (current.kind === 70) { break; } - else if (current.kind === 172) { + else if (current.kind === 177) { current = current.expression; } else { return undefined; } } - enumType_1 = checkExpression(expression); + enumType_1 = getTypeOfExpression(expression); if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384))) { return undefined; } @@ -31678,7 +35326,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 224) { + if (declaration.kind !== 229) { return false; } var enumDeclaration = declaration; @@ -31701,8 +35349,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 221 || - (declaration.kind === 220 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 226 || + (declaration.kind === 225 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -31741,9 +35389,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31759,7 +35409,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 221); + var mergedClass = ts.getDeclarationOfKind(symbol, 226); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -31802,36 +35452,36 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 200: + case 205: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 235: - case 236: + case 240: + case 241: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 229: - case 230: + case 234: + case 235: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 169: - case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + case 174: + case 223: + var name_27 = node.name; + if (ts.isBindingPattern(name_27)) { + for (var _b = 0, _c = name_27.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } - case 221: - case 224: - case 220: - case 222: + case 226: + case 229: case 225: - case 223: + case 227: + case 230: + case 228: if (isGlobalAugmentation) { return; } @@ -31847,17 +35497,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 69: + case 70: return node; - case 139: + case 141: do { node = node.left; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; - case 172: + case 177: do { node = node.expression; - } while (node.kind !== 69); + } while (node.kind !== 70); return node; } } @@ -31867,9 +35517,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { - error(moduleName, node.kind === 236 ? + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { + error(moduleName, node.kind === 241 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -31890,7 +35540,7 @@ var ts; (symbol.flags & 793064 ? 793064 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 238 ? + var message = node.kind === 243 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -31917,7 +35567,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { + if (importClause.namedBindings.kind === 237) { checkImportBinding(importClause.namedBindings); } else { @@ -31952,7 +35602,7 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { grammarErrorOnNode(node, ts.Diagnostics.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); } } @@ -31968,8 +35618,8 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 226 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 231 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -31982,9 +35632,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 261 || node.parent.kind === 231 || node.parent.kind === 230; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32003,15 +35655,15 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 256 ? node.parent : node.parent.parent; - if (container.kind === 225 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 261 ? node.parent : node.parent.parent; + if (container.kind === 230 && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { markExportAsReferenced(node); } else { @@ -32019,7 +35671,7 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES6) { + if (modulekind === ts.ModuleKind.ES2015) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { @@ -32046,12 +35698,12 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports = getExportsOfModule(moduleSymbol); - for (var id in exports) { + var exports_1 = getExportsOfModule(moduleSymbol); + for (var id in exports_1) { if (id === "__export") { continue; } - var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; if (flags & (1920 | 64 | 384)) { continue; } @@ -32071,7 +35723,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 225 && declaration.kind !== 149) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32081,118 +35734,123 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { + case 230: + case 226: + case 227: case 225: - case 221: - case 222: - case 220: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 141: + case 143: return checkTypeParameter(node); - case 142: - return checkParameter(node); - case 145: case 144: - return checkPropertyDeclaration(node); - case 156: - case 157: - case 151: - case 152: - return checkSignatureDeclaration(node); - case 153: - return checkSignatureDeclaration(node); + return checkParameter(node); case 147: case 146: - return checkMethodDeclaration(node); - case 148: - return checkConstructorDeclaration(node); - case 149: - case 150: - return checkAccessorDeclaration(node); - case 155: - return checkTypeReferenceNode(node); - case 154: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 158: - return checkTypeQuery(node); case 159: - return checkTypeLiteral(node); + case 153: + case 154: + return checkSignatureDeclaration(node); + case 155: + return checkSignatureDeclaration(node); + case 149: + case 148: + return checkMethodDeclaration(node); + case 150: + return checkConstructorDeclaration(node); + case 151: + case 152: + return checkAccessorDeclaration(node); + case 157: + return checkTypeReferenceNode(node); + case 156: + return checkTypePredicate(node); case 160: - return checkArrayType(node); + return checkTypeQuery(node); case 161: - return checkTupleType(node); + return checkTypeLiteral(node); case 162: + return checkArrayType(node); case 163: - return checkUnionOrIntersectionType(node); + return checkTupleType(node); case 164: + case 165: + return checkUnionOrIntersectionType(node); + case 166: + case 168: return checkSourceElement(node.type); - case 220: - return checkFunctionDeclaration(node); - case 199: - case 226: - return checkBlock(node); - case 200: - return checkVariableStatement(node); - case 202: - return checkExpressionStatement(node); - case 203: - return checkIfStatement(node); - case 204: - return checkDoStatement(node); - case 205: - return checkWhileStatement(node); - case 206: - return checkForStatement(node); - case 207: - return checkForInStatement(node); - case 208: - return checkForOfStatement(node); - case 209: - case 210: - return checkBreakOrContinueStatement(node); - case 211: - return checkReturnStatement(node); - case 212: - return checkWithStatement(node); - case 213: - return checkSwitchStatement(node); - case 214: - return checkLabeledStatement(node); - case 215: - return checkThrowStatement(node); - case 216: - return checkTryStatement(node); - case 218: - return checkVariableDeclaration(node); case 169: - return checkBindingElement(node); - case 221: - return checkClassDeclaration(node); - case 222: - return checkInterfaceDeclaration(node); - case 223: - return checkTypeAliasDeclaration(node); - case 224: - return checkEnumDeclaration(node); + return checkIndexedAccessType(node); + case 170: + return checkMappedType(node); case 225: - return checkModuleDeclaration(node); - case 230: - return checkImportDeclaration(node); - case 229: - return checkImportEqualsDeclaration(node); - case 236: - return checkExportDeclaration(node); - case 235: - return checkExportAssignment(node); - case 201: - checkGrammarStatementInAmbientContext(node); - return; + return checkFunctionDeclaration(node); + case 204: + case 231: + return checkBlock(node); + case 205: + return checkVariableStatement(node); + case 207: + return checkExpressionStatement(node); + case 208: + return checkIfStatement(node); + case 209: + return checkDoStatement(node); + case 210: + return checkWhileStatement(node); + case 211: + return checkForStatement(node); + case 212: + return checkForInStatement(node); + case 213: + return checkForOfStatement(node); + case 214: + case 215: + return checkBreakOrContinueStatement(node); + case 216: + return checkReturnStatement(node); case 217: + return checkWithStatement(node); + case 218: + return checkSwitchStatement(node); + case 219: + return checkLabeledStatement(node); + case 220: + return checkThrowStatement(node); + case 221: + return checkTryStatement(node); + case 223: + return checkVariableDeclaration(node); + case 174: + return checkBindingElement(node); + case 226: + return checkClassDeclaration(node); + case 227: + return checkInterfaceDeclaration(node); + case 228: + return checkTypeAliasDeclaration(node); + case 229: + return checkEnumDeclaration(node); + case 230: + return checkModuleDeclaration(node); + case 235: + return checkImportDeclaration(node); + case 234: + return checkImportEqualsDeclaration(node); + case 241: + return checkExportDeclaration(node); + case 240: + return checkExportAssignment(node); + case 206: checkGrammarStatementInAmbientContext(node); return; - case 239: + case 222: + checkGrammarStatementInAmbientContext(node); + return; + case 244: return checkMissingDeclaration(node); } } @@ -32205,17 +35863,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 179: - case 180: - case 147: - case 146: + case 184: + case 185: + case 149: + case 148: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 149: - case 150: + case 151: + case 152: checkAccessorDeferred(node); break; - case 192: + case 197: checkClassExpressionDeferred(node); break; } @@ -32269,8 +35927,19 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; } ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); @@ -32287,7 +35956,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 212 && node.parent.statement === node) { + if (node.parent.kind === 217 && node.parent.statement === node) { return true; } node = node.parent; @@ -32309,28 +35978,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 256: + case 261: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 225: + case 230: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 224: + case 229: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 192: + case 197: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 221: - case 222: + case 226: + case 227: if (!(memberFlags & 32)) { copySymbols(getSymbolOfNode(location).members, meaning & 793064); } break; - case 179: + case 184: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -32363,33 +36032,33 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 69 && + return name.kind === 70 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 141: - case 221: - case 222: - case 223: - case 224: + case 143: + case 226: + case 227: + case 228: + case 229: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 139) { + while (node.parent && node.parent.kind === 141) { node = node.parent; } - return node.parent && (node.parent.kind === 155 || node.parent.kind === 267); + return node.parent && (node.parent.kind === 157 || node.parent.kind === 272); } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 172) { + while (node.parent && node.parent.kind === 177) { node = node.parent; } - return node.parent && node.parent.kind === 194; + return node.parent && node.parent.kind === 199; } function forEachEnclosingClass(node, callback) { var result; @@ -32406,13 +36075,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 139) { + while (nodeOnRightSide.parent.kind === 141) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 229) { + if (nodeOnRightSide.parent.kind === 234) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 235) { + if (nodeOnRightSide.parent.kind === 240) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -32424,7 +36093,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 172) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: @@ -32436,20 +36105,20 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 240 && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); + if (entityName.kind !== 177 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 234); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 194) { + if (entityName.parent.kind === 199) { meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -32465,20 +36134,20 @@ var ts; if (ts.nodeIsMissing(entityName)) { return undefined; } - if (entityName.kind === 69) { + if (entityName.kind === 70) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } return resolveEntityName(entityName, 107455, false, true); } - else if (entityName.kind === 172) { + else if (entityName.kind === 177) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 139) { + else if (entityName.kind === 141) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -32487,19 +36156,19 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 157 || entityName.parent.kind === 272) ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 246) { + else if (entityName.parent.kind === 250) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 154) { + if (entityName.parent.kind === 156) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 256) { + if (node.kind === 261) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } if (isInsideWithStatementBody(node)) { @@ -32511,12 +36180,12 @@ var ts; else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 69) { + if (node.kind === 70) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 169 && - node.parent.parent.kind === 167 && + else if (node.parent.kind === 174 && + node.parent.parent.kind === 172 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -32526,11 +36195,11 @@ var ts; } } switch (node.kind) { - case 69: - case 172: - case 139: + case 70: + case 177: + case 141: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 97: + case 98: var container = ts.getThisContainer(node, false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -32538,27 +36207,30 @@ var ts; return sig.thisParameter; } } - case 95: - var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + case 96: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; - case 165: + case 167: return getTypeFromTypeNode(node).symbol; - case 121: + case 122: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 148) { + if (constructorDeclaration && constructorDeclaration.kind === 150) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 230 || node.parent.kind === 236) && + ((node.parent.kind === 235 || node.parent.kind === 241) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: - if (node.parent.kind === 173 && node.parent.argumentExpression === node) { - var objectType = checkExpression(node.parent.expression); + if (node.parent.kind === 178 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); if (objectType === unknownType) return undefined; var apparentType = getApparentType(objectType); @@ -32571,7 +36243,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 254) { + if (location && location.kind === 258) { return resolveEntityName(location.name, 107455 | 8388608); } return undefined; @@ -32589,7 +36261,7 @@ var ts; return getTypeFromTypeNode(node); } if (ts.isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; @@ -32621,20 +36293,20 @@ var ts; return unknownType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 171 || expr.kind === 170); - if (expr.parent.kind === 208) { + ts.Debug.assert(expr.kind === 176 || expr.kind === 175); + if (expr.parent.kind === 213) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 187) { - var iteratedType = checkExpression(expr.parent.right); + if (expr.parent.kind === 192) { + var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 253) { + if (expr.parent.kind === 257) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 170); + ts.Debug.assert(expr.parent.kind === 175); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); @@ -32643,11 +36315,11 @@ var ts; var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr) { + function getRegularTypeOfExpression(expr) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); @@ -32670,9 +36342,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_28 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_28); if (symbol) { symbols_3.push(symbol); } @@ -32680,6 +36352,10 @@ var ts; return symbols_3; } else if (symbol.flags & 67108864) { + if (symbol.leftSpread) { + var links = symbol; + return [links.leftSpread, links.rightSpread]; + } var target = void 0; var next = symbol; while (next = getSymbolLinks(next).target) { @@ -32721,7 +36397,7 @@ var ts; } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; - return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } function getReferencedExportContainer(node, prefixLocals) { node = ts.getParseTreeNode(node, ts.isIdentifier); @@ -32737,7 +36413,7 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 256) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 261) { var symbolFile = parentSymbol.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -32775,7 +36451,7 @@ var ts; else if (nodeLinks_1.flags & 131072) { var isDeclaredInLoop = nodeLinks_1.flags & 262144; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 199 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 204 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -32815,18 +36491,18 @@ var ts; return true; } switch (node.kind) { - case 229: - case 231: - case 232: case 234: - case 238: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 236: + case 237: + case 239: + case 243: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 241: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 235: + case 240: return node.expression - && node.expression.kind === 69 + && node.expression.kind === 70 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -32834,7 +36510,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 256 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 261 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -32885,7 +36561,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 255) { + if (node.kind === 260) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -32897,7 +36573,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); @@ -32929,7 +36605,7 @@ var ts; else if (isTypeOfKind(type, 340)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 262178)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { @@ -32960,7 +36636,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getTypeOfExpression(expr)); + var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { @@ -32979,9 +36655,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_11 = reference.parent; + if (ts.isDeclaration(parent_11) && reference === parent_11.name) { + location = getDeclarationContainer(parent_11); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33001,7 +36677,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 16777216); + return !!(type.flags & 96 && type.flags & 1048576); } return false; } @@ -33052,13 +36728,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) + var meaning = (node.kind === 177) || (node.kind === 70 && isInTypeQuery(node)) ? 107455 | 1048576 : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); @@ -33080,6 +36757,9 @@ var ts; if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + return undefined; + } } } return typeReferenceDirectives; @@ -33090,15 +36770,15 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_12 = getParentOfSymbol(current); + if (parent_12) { + current = parent_12; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 256 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 261 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -33117,7 +36797,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 256); + return ts.getDeclarationOfKind(moduleSymbol, 261); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -33125,8 +36805,6 @@ var ts; ts.bindSourceFile(file, compilerOptions); } var augmentations; - var requestedExternalEmitHelpers = 0; - var firstFileRequestingExternalHelpers; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { @@ -33146,15 +36824,6 @@ var ts; } } } - if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { - var fileRequestedExternalEmitHelpers = file.flags & 31744; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { @@ -33205,43 +36874,50 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); - if (helpersModule) { - var exports = helpersModule.exports; - if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { - verifyHelperSymbol(exports, "__extends", 107455); - } - if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { - verifyHelperSymbol(exports, "__assign", 107455); - } - if (requestedExternalEmitHelpers & 2048) { - verifyHelperSymbol(exports, "__decorate", 107455); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455); - } - } - if (requestedExternalEmitHelpers & 4096) { - verifyHelperSymbol(exports, "__param", 107455); - } - if (requestedExternalEmitHelpers & 8192) { - verifyHelperSymbol(exports, "__awaiter", 107455); - if (languageVersion < 2) { - verifyHelperSymbol(exports, "__generator", 107455); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 128; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name_29 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name_29), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_29); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols, name, meaning) { - var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); - if (!symbol) { - error(undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; } } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -33252,7 +36928,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -33264,14 +36940,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 147 && !ts.nodeIsPresent(node.body)) { + if (node.kind === 149 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 149 || node.kind === 150) { + else if (node.kind === 151 || node.kind === 152) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -33288,28 +36964,28 @@ var ts; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 128) { - if (node.kind === 144 || node.kind === 146) { + if (modifier.kind !== 130) { + if (node.kind === 146 || node.kind === 148) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 153) { + if (node.kind === 155) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 74: - if (node.kind !== 224 && node.parent.kind === 221) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + case 75: + if (node.kind !== 229 && node.parent.kind === 226) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75)); } break; + case 113: case 112: case 111: - case 110: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 111) { + if (modifier.kind === 112) { lastProtected = modifier; } - else if (modifier.kind === 110) { + else if (modifier.kind === 111) { lastPrivate = modifier; } if (flags & 28) { @@ -33324,11 +37000,11 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { - if (modifier.kind === 110) { + if (modifier.kind === 111) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -33337,7 +37013,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 113: + case 114: if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -33347,10 +37023,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 226 || node.parent.kind === 256) { + else if (node.parent.kind === 231 || node.parent.kind === 261) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -33359,17 +37035,17 @@ var ts; flags |= 32; lastStatic = modifier; break; - case 128: + case 130: if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 145 && node.kind !== 144 && node.kind !== 153 && node.kind !== 142) { + else if (node.kind !== 147 && node.kind !== 146 && node.kind !== 155 && node.kind !== 144) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; lastReadonly = modifier; break; - case 82: + case 83: if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -33382,45 +37058,45 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; - case 122: + case 123: if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 226) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; lastDeclare = modifier; break; - case 115: + case 116: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 221) { - if (node.kind !== 147 && - node.kind !== 145 && - node.kind !== 149 && - node.kind !== 150) { + if (node.kind !== 226) { + if (node.kind !== 149 && + node.kind !== 147 && + node.kind !== 151 && + node.kind !== 152) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 && ts.getModifierFlags(node.parent) & 128)) { + if (!(node.parent.kind === 226 && ts.getModifierFlags(node.parent) & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -33432,14 +37108,14 @@ var ts; } flags |= 128; break; - case 118: + case 119: if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 142) { + else if (node.kind === 144) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -33447,7 +37123,7 @@ var ts; break; } } - if (node.kind === 148) { + if (node.kind === 150) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -33462,13 +37138,13 @@ var ts; } return; } - else if ((node.kind === 230 || node.kind === 229) && flags & 2) { + else if ((node.kind === 235 || node.kind === 234) && flags & 2) { 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)) { + else if (node.kind === 144 && (flags & 92) && ts.isBindingPattern(node.name)) { 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) { + else if (node.kind === 144 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -33484,38 +37160,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 149: + case 151: + case 152: case 150: - case 148: - case 145: - case 144: case 147: case 146: - case 153: - case 225: + case 149: + case 148: + case 155: case 230: - case 229: - case 236: case 235: - case 179: - case 180: - case 142: + case 234: + case 241: + case 240: + case 184: + case 185: + case 144: return false; default: - if (node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 231 || node.parent.kind === 261) { return false; } switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: + case 225: + return nodeHasAnyModifiersExcept(node, 119); + case 226: + return nodeHasAnyModifiersExcept(node, 116); + case 227: + case 205: + case 228: return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); + case 229: + return nodeHasAnyModifiersExcept(node, 75); default: ts.Debug.fail(); return false; @@ -33527,10 +37203,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 147: - case 220: - case 179: - case 180: + case 149: + case 225: + case 184: + case 185: if (!node.asteriskToken) { return false; } @@ -33546,7 +37222,7 @@ var ts; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } - function checkGrammarTypeParameterList(node, typeParameters, file) { + function checkGrammarTypeParameterList(typeParameters, file) { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -33588,11 +37264,11 @@ var ts; } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 180) { + if (node.kind === 185) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -33627,7 +37303,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 132 && parameter.type.kind !== 130) { + if (parameter.type.kind !== 134 && parameter.type.kind !== 132) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -33652,9 +37328,9 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 193) { + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; + if (arg.kind === 198) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -33680,7 +37356,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -33693,7 +37369,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -33708,14 +37384,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83) { + if (heritageClause.token === 84) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106); + ts.Debug.assert(heritageClause.token === 107); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } checkGrammarHeritageClause(heritageClause); @@ -33724,19 +37400,19 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 140) { + if (node.kind !== 142) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 187 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 192 && computedPropertyName.expression.operatorToken.kind === 25) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 220 || - node.kind === 179 || - node.kind === 147); + ts.Debug.assert(node.kind === 225 || + node.kind === 184 || + node.kind === 149); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -33748,7 +37424,7 @@ var ts; } } } - function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + function checkGrammarForInvalidQuestionMark(questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -33761,43 +37437,45 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + if (prop.kind === 259) { + continue; } - if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { + var name_30 = prop.name; + if (name_30.kind === 142) { + checkGrammarComputedPropertyName(name_30); + } + if (prop.kind === 258 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 118 || prop.kind !== 147) { + if (mod.kind !== 119 || prop.kind !== 149) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } 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_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (prop.kind === 257 || prop.kind === 258) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_30.kind === 8) { + checkGrammarNumericLiteral(name_30); } currentKind = Property; } - else if (prop.kind === 147) { + else if (prop.kind === 149) { currentKind = Property; } - else if (prop.kind === 149) { + else if (prop.kind === 151) { currentKind = GetAccessor; } - else if (prop.kind === 150) { + else if (prop.kind === 152) { currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_30); if (effectiveName === undefined) { continue; } @@ -33807,18 +37485,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_30, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_30)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_30, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_30, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33827,19 +37505,19 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 247) { + if (attr.kind === 251) { continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_31 = jsxAttr.name; + if (!seen[name_31.text]) { + seen[name_31.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_31, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 248 && !initializer.expression) { + if (initializer && initializer.kind === 252 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -33848,7 +37526,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 219) { + if (forInOrOfStatement.initializer.kind === 224) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -33856,20 +37534,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 207 + var diagnostic = forInOrOfStatement.kind === 212 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -33889,15 +37567,18 @@ var ts; else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 149 ? + return grammarErrorOnNode(accessor.name, kind === 151 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 150) { + else if (kind === 152) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -33916,20 +37597,11 @@ var ts; } } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 151 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -33943,8 +37615,8 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 171) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (node.parent.kind === 176) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -33959,10 +37631,10 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -33973,9 +37645,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 214: + case 219: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 209 + var isMisplacedContinueLabel = node.kind === 214 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -33983,8 +37655,8 @@ var ts; return false; } break; - case 213: - if (node.kind === 210 && !node.label) { + case 218: + if (node.kind === 215 && !node.label) { return false; } break; @@ -33997,13 +37669,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 210 + var message = node.kind === 215 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -34013,9 +37685,9 @@ var ts; if (node.dotDotDotToken) { var elements = node.parent.elements; if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 168 || node.name.kind === 167) { + if (node.name.kind === 173 || node.name.kind === 172) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -34025,11 +37697,11 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 || expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && + expr.kind === 190 && expr.operator === 37 && expr.operand.kind === 8; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 207 && node.parent.parent.kind !== 208) { + if (node.parent.parent.kind !== 212 && node.parent.parent.kind !== 213) { if (ts.isInAmbientContext(node)) { if (node.initializer) { if (ts.isConst(node) && !node.type) { @@ -34060,8 +37732,8 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 69) { - if (name.originalKeywordKind === 108) { + if (name.kind === 70) { + if (name.originalKeywordKind === 109) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -34086,15 +37758,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 203: - case 204: - case 205: - case 212: - case 206: - case 207: case 208: + case 209: + case 210: + case 217: + case 211: + case 212: + case 213: return false; - case 214: + case 219: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -34149,7 +37821,7 @@ var ts; return true; } } - else if (node.parent.kind === 222) { + else if (node.parent.kind === 227) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -34157,7 +37829,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 159) { + else if (node.parent.kind === 161) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -34170,13 +37842,13 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 222 || - node.kind === 223 || - node.kind === 230 || - node.kind === 229 || - node.kind === 236 || - node.kind === 235 || + if (node.kind === 227 || node.kind === 228 || + node.kind === 235 || + node.kind === 234 || + node.kind === 241 || + node.kind === 240 || + node.kind === 233 || ts.getModifierFlags(node) & (2 | 1 | 512)) { return false; } @@ -34185,7 +37857,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 200) { + if (ts.isDeclaration(decl) || decl.kind === 205) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -34204,7 +37876,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 199 || node.parent.kind === 226 || node.parent.kind === 256) { + if (node.parent.kind === 204 || node.parent.kind === 231 || node.parent.kind === 261) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -34243,49 +37915,49 @@ var ts; (function (ts) { ; var nodeEdgeTraversalMap = ts.createMap((_a = {}, - _a[139] = [ + _a[141] = [ { name: "left", test: ts.isEntityName }, { name: "right", test: ts.isIdentifier } ], - _a[143] = [ + _a[145] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[177] = [ + _a[182] = [ { name: "type", test: ts.isTypeNode }, { name: "expression", test: ts.isUnaryExpression } ], - _a[195] = [ + _a[200] = [ { name: "expression", test: ts.isExpression }, { name: "type", test: ts.isTypeNode } ], - _a[196] = [ + _a[201] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[224] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isIdentifier }, - { name: "members", test: ts.isEnumMember } - ], - _a[225] = [ - { name: "decorators", test: ts.isDecorator }, - { name: "modifiers", test: ts.isModifier }, - { name: "name", test: ts.isModuleName }, - { name: "body", test: ts.isModuleBody } - ], - _a[226] = [ - { name: "statements", test: ts.isStatement } - ], _a[229] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isIdentifier }, + { name: "members", test: ts.isEnumMember } + ], + _a[230] = [ + { name: "decorators", test: ts.isDecorator }, + { name: "modifiers", test: ts.isModifier }, + { name: "name", test: ts.isModuleName }, + { name: "body", test: ts.isModuleBody } + ], + _a[231] = [ + { name: "statements", test: ts.isStatement } + ], + _a[234] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "moduleReference", test: ts.isModuleReference } ], - _a[240] = [ + _a[245] = [ { name: "expression", test: ts.isExpression, optional: true } ], - _a[255] = [ + _a[260] = [ { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], @@ -34293,330 +37965,338 @@ var ts; function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } - function reduceEachChild(node, f, initial) { + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } + function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return initial; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return initial; } var result = initial; switch (node.kind) { + case 203: + case 206: case 198: - case 201: - case 193: - case 217: - case 287: - break; - case 140: - result = reduceNode(node.expression, f, result); + case 222: + case 293: break; case 142: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; - case 143: - result = reduceNode(node.expression, f, result); + case 144: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 145: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 147: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 148: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 149: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 150: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; - case 167: - case 168: - result = ts.reduceLeft(node.elements, f, result); + case 151: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 169: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; - case 170: - result = ts.reduceLeft(node.elements, f, result); - break; - case 171: - result = ts.reduceLeft(node.properties, f, result); + case 152: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; case 172: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.name, f, result); - break; case 173: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.argumentExpression, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 174: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 175: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + result = reduceNodes(node.elements, cbNodes, result); break; case 176: - result = reduceNode(node.tag, f, result); - result = reduceNode(node.template, f, result); + result = reduceNodes(node.properties, cbNodes, result); break; - case 179: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); - break; - case 180: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 177: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; case 178: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); + break; + case 179: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; + case 180: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); + break; case 181: - case 182: - case 183: + result = reduceNode(node.tag, cbNode, result); + result = reduceNode(node.template, cbNode, result); + break; case 184: - case 190: - case 191: - case 196: - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; case 185: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 183: case 186: - result = reduceNode(node.operand, f, result); - break; case 187: - result = reduceNode(node.left, f, result); - result = reduceNode(node.right, f, result); - break; case 188: - result = reduceNode(node.condition, f, result); - result = reduceNode(node.whenTrue, f, result); - result = reduceNode(node.whenFalse, f, result); - break; case 189: - result = reduceNode(node.head, f, result); - result = ts.reduceLeft(node.templateSpans, f, result); + case 195: + case 196: + case 201: + result = reduceNode(node.expression, cbNode, result); + break; + case 190: + case 191: + result = reduceNode(node.operand, cbNode, result); break; case 192: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); + break; + case 193: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); break; case 194: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); break; case 197: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.literal, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 199: - result = ts.reduceLeft(node.statements, f, result); - break; - case 200: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.declarationList, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); break; case 202: - result = reduceNode(node.expression, f, result); - break; - case 203: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.thenStatement, f, result); - result = reduceNode(node.elseStatement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); break; case 204: - result = reduceNode(node.statement, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.statements, cbNodes, result); break; case 205: - case 212: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); - break; - case 206: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.condition, f, result); - result = reduceNode(node.incrementor, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); break; case 207: + result = reduceNode(node.expression, cbNode, result); + break; case 208: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); + break; + case 209: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + break; + case 210: + case 217: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 211: - case 215: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; + case 212: case 213: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.caseBlock, f, result); - break; - case 214: - result = reduceNode(node.label, f, result); - result = reduceNode(node.statement, f, result); + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 216: - result = reduceNode(node.tryBlock, f, result); - result = reduceNode(node.catchClause, f, result); - result = reduceNode(node.finallyBlock, f, result); + case 220: + result = reduceNode(node.expression, cbNode, result); break; case 218: - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); break; case 219: - result = ts.reduceLeft(node.declarations, f, result); - break; - case 220: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; case 221: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); break; - case 227: - result = ts.reduceLeft(node.clauses, f, result); + case 223: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 230: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.importClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 224: + result = reduceNodes(node.declarations, cbNodes, result); break; - case 231: - result = reduceNode(node.name, f, result); - result = reduceNode(node.namedBindings, f, result); + case 225: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); + break; + case 226: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; case 232: - result = reduceNode(node.name, f, result); - break; - case 233: - case 237: - result = ts.reduceLeft(node.elements, f, result); - break; - case 234: - case 238: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); + result = reduceNodes(node.clauses, cbNodes, result); break; case 235: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.expression, f, result); + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 236: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.exportClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); + break; + case 237: + result = reduceNode(node.name, cbNode, result); + break; + case 238: + case 242: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 239: + case 243: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + break; + case 240: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; case 241: - result = reduceNode(node.openingElement, f, result); - result = ts.reduceLeft(node.children, f, result); - result = reduceNode(node.closingElement, f, result); - break; - case 242: - case 243: - result = reduceNode(node.tagName, f, result); - result = ts.reduceLeft(node.attributes, f, result); - break; - case 245: - result = reduceNode(node.tagName, f, result); + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; case 246: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); break; case 247: - result = reduceNode(node.expression, f, result); - break; case 248: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.attributes, cbNodes, result); break; case 249: - result = reduceNode(node.expression, f, result); + result = reduceNode(node.tagName, cbNode, result); + break; case 250: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; case 251: - result = ts.reduceLeft(node.types, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 252: - result = reduceNode(node.variableDeclaration, f, result); - result = reduceNode(node.block, f, result); + result = reduceNode(node.expression, cbNode, result); break; case 253: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); - break; + result = reduceNode(node.expression, cbNode, result); case 254: - result = reduceNode(node.name, f, result); - result = reduceNode(node.objectAssignmentInitializer, f, result); + result = reduceNodes(node.statements, cbNodes, result); + break; + case 255: + result = reduceNodes(node.types, cbNodes, result); break; case 256: - result = ts.reduceLeft(node.statements, f, result); + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); break; - case 288: - result = reduceNode(node.expression, f, result); + case 257: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); + break; + case 258: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 259: + result = reduceNode(node.expression, cbNode, result); + break; + case 261: + result = reduceNodes(node.statements, cbNodes, result); + break; + case 294: + result = reduceNode(node.expression, cbNode, result); break; default: var edgeTraversalPath = nodeEdgeTraversalMap[kind]; @@ -34626,8 +38306,8 @@ var ts; var value = node[edge.name]; if (value !== undefined) { result = ts.isArray(value) - ? ts.reduceLeft(value, f, result) - : f(result, value); + ? reduceNodes(value, cbNodes, result) + : cbNode(result, value); } } } @@ -34637,9 +38317,10 @@ var ts; } ts.reduceEachChild = reduceEachChild; function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); var visited = visitor(node); if (visited === node) { return node; @@ -34682,6 +38363,7 @@ var ts; } for (var i = 0; i < count; i++) { var node = nodes[i + start]; + aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -34713,183 +38395,213 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.createNodeArray(ts.concatenate(statements, declarations), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + function visitParameterList(nodes, visitor, context) { + context.startLexicalEnvironment(); + var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; function visitEachChild(node, visitor, context) { if (node === undefined) { return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 138)) { + if ((kind > 0 && kind <= 140)) { return node; } - if ((kind >= 154 && kind <= 166)) { + if ((kind >= 156 && kind <= 171)) { return node; } switch (node.kind) { - case 198: - case 201: - case 193: - case 217: - return node; - case 140: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 142: - return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 145: - return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 147: - return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 148: - return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 149: - return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 150: - return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 167: - return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); - case 168: - return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); - case 169: - return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); - case 170: - return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); - case 171: - return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 172: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 173: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 174: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 175: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); - case 178: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 179: - return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); - case 180: - return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, true), context.endLexicalEnvironment())); - case 181: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 182: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 183: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 184: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 187: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); - case 185: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 186: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 188: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); - case 190: - return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192: - return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 194: - return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); - case 199: - return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 200: - return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 202: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 203: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); - case 204: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 205: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 206: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + case 198: + case 222: + return node; + case 142: + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + case 144: + return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 147: + return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 149: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 150: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 151: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 152: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 172: + return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); + case 173: + return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); + case 174: + return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 175: + return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); + case 176: + return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 177: + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + case 178: + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + case 179: + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 180: + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); + case 181: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 183: + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + case 184: + return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 185: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 186: + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + case 187: + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + case 188: + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + case 189: + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + case 192: + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); + case 190: + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 191: + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + case 193: + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + case 194: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 195: + return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); + case 196: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 197: + return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); + case 199: + return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + case 202: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); + case 204: + return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 205: + return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); case 207: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 208: - return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, true, liftToBlock)); case 209: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 210: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 211: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 212: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 213: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 214: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 215: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, true)); case 216: - return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, true)); + case 217: + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 218: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 219: - return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, false, liftToBlock)); case 220: - return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, true), context.endLexicalEnvironment())); + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); case 221: + return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, true), visitNode(node.finallyBlock, visitor, ts.isBlock, true)); + case 223: + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, true), visitNode(node.initializer, visitor, ts.isExpression, true)); + case 224: + return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); + case 225: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, true), visitFunctionBody(node.body, visitor, context)); + case 226: return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 227: - return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 230: - return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 231: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 232: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 233: - return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); - case 234: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 235: - return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 236: - return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true)); case 237: - return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 238: - return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); + case 239: + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); + case 240: + return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 241: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, true)); case 242: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); + return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); case 243: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 245: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, true), visitNode(node.name, visitor, ts.isIdentifier)); case 246: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 247: - return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 248: - return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); case 249: - return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 250: - return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 251: - return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); + return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); case 252: - return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 253: - return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); case 254: - return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); + case 255: + return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); case 256: - context.startLexicalEnvironment(); - return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); - case 288: + return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); + case 257: + return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); + case 258: + return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 259: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); + case 261: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); + case 294: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); default: var updated = void 0; @@ -34917,6 +38629,15 @@ var ts; } } ts.visitEachChild = visitEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.createNodeArray(ts.concatenate(statements, declarations), statements) + : ts.addRange(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function mergeFunctionBodyLexicalEnvironment(body, declarations) { if (body && declarations !== undefined && declarations.length > 0) { if (ts.isBlock(body)) { @@ -34947,85 +38668,61 @@ var ts; if (node === undefined) { return 0; } - else if (node.transformFlags & 536870912) { - return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + if (node.transformFlags & 536870912) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } - else { - var subtreeFlags = aggregateTransformFlagsForSubtree(node); - return ts.computeTransformFlagsForNode(node, subtreeFlags); + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0; } + var subtreeFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { if (ts.hasModifier(node, 2) || ts.isTypeNode(node)) { return 0; } - return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0); + return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } - function aggregateTransformFlagsForChildNode(transformFlags, child) { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 154 && kind <= 166) { - return -3; - } - switch (kind) { - case 174: - case 175: - case 170: - return 537133909; - case 225: - return 546335573; - case 142: - return 538968917; - case 180: - return 550710101; - case 179: - case 220: - return 550726485; - case 219: - return 538968917; - case 221: - case 192: - return 537590613; - case 148: - return 550593365; - case 147: - case 149: - case 150: - return 550593365; - case 117: - case 130: - case 127: - case 132: - case 120: - case 133: - case 103: - case 141: - case 144: - case 146: - case 151: - case 152: - case 153: - case 222: - case 223: - return -3; - case 171: - return 537430869; - default: - return 536871765; - } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } var Debug; (function (Debug) { Debug.failNotOptional = Debug.shouldAssert(1) ? function (message) { return Debug.assert(false, message || "Node not optional."); } - : function (message) { }; + : ts.noop; Debug.failBadSyntaxKind = Debug.shouldAssert(1) ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } - : function (node, message) { }; + : ts.noop; + Debug.assertEachNode = Debug.shouldAssert(1) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; Debug.assertNode = Debug.shouldAssert(1) ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } - : function (node, test, message) { }; + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + : ts.noop; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -35044,277 +38741,316 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { - if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { - var right = node.right; - if (ts.isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; - var value = node.right; - var expressions = []; - if (needsValue) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment, visitor); + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - else if (ts.nodeIsSynthesized(node)) { - location = value; + var expressions; + var flattenContext = { + context: context, + level: level, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (needsValue) { + value = ensureIdentifier(flattenContext, value, true, location); + } + else if (ts.nodeIsSynthesized(node)) { + location = value; + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); - if (needsValue) { + flattenBindingOrAssignmentElement(flattenContext, node, value, location, ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } expressions.push(value); } - var expression = ts.inlineExpressions(expressions); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location) { - var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { + ts.setEmitFlags(expression, 64); ts.aggregateTransformFlags(expression); - expressions.push(expression); + expressions = ts.append(expressions, expression); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location); + expression.original = original; + emitExpression(expression); } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; - function flattenParameterDestructuring(context, node, value, visitor) { + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + var pendingExpressions; + var pendingDeclarations = []; var declarations = []; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + var flattenContext = { + context: context, + level: level, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, undefined, undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_32 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_32, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2); + variable.original = original; + if (ts.isIdentifier(name_32)) { + ts.setEmitFlags(variable, 64); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } return declarations; - function emitAssignment(name, value, location) { - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); - ts.aggregateTransformFlags(declaration); - declarations.push(declaration); + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(undefined); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); } } - ts.flattenParameterDestructuring = flattenParameterDestructuring; - function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { - var declarations = []; - var pendingAssignments; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - return declarations; - function emitAssignment(name, value, location, original) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = ts.inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - var declaration = ts.createVariableDeclaration(name, undefined, value, location); - declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); - declarations.push(declaration); - ts.aggregateTransformFlags(declaration); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - if (recordTempVariable) { - var assignment = ts.createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, undefined); - } - return name; - } - } - ts.flattenVariableDestructuring = flattenVariableDestructuring; - function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { - var pendingAssignments = []; - flattenDestructuring(context, node, undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - var expression = ts.inlineExpressions(pendingAssignments); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location, original) { - var left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, undefined); - return name; - } - function emitPendingAssignment(name, value, location, original) { - var expression = ts.createAssignment(name, value, location); - expression.original = original; - context.setNodeEmitFlags(expression, 2048); - pendingAssignments.push(expression); - return expression; - } - } - ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; - function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { - if (value && visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); - } - if (ts.isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - function emitDestructuringAssignment(bindingTarget, value, location) { - var target; - if (ts.isShorthandPropertyAssignment(bindingTarget)) { - var initializer = visitor - ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) - : bindingTarget.objectAssignmentInitializer; - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - target = bindingTarget.name; - } - else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56) { - var initializer = visitor - ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) - : bindingTarget.right; - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - if (target.kind === 171) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === 170) { - emitArrayLiteralAssignment(target, value, location); - } - else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); - } - } - function emitObjectLiteralAssignment(target, value, location) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; - if (p.kind === 253 || p.kind === 254) { - var propName = p.name; - var target_1 = p.kind === 254 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, location) { - var elements = target.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var e = elements[i]; - if (e.kind !== 193) { - if (e.kind !== 191) { - emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); - } - } - } - } - function emitBindingElement(target, value) { - var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + ts.flattenDestructuringBinding = flattenDestructuringBinding; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { value = ts.createVoidZero(); } - var name = target.name; - if (ts.isBindingPattern(name)) { - var elements = name.elements; - var numElements = elements.length; - if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0, target, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (ts.isOmittedExpression(element)) { - continue; - } - else if (name.kind === 167) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - emitBindingElement(element, ts.createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, ts.createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - function createDefaultValueCheck(value, defaultValue, location) { - value = ensureIdentifier(value, true, location, emitTempVariableAssignment); - return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53), defaultValue, ts.createToken(54), value); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } - function createDestructuringPropertyAccess(expression, propertyName) { - if (ts.isComputedPropertyName(propertyName)) { - return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, false, propertyName, emitTempVariableAssignment)); - } - else if (ts.isLiteralExpression(propertyName)) { - var clone_2 = ts.getSynthesizedClone(propertyName); - clone_2.text = ts.unescapeIdentifier(clone_2.text); - return ts.createElementAccess(expression, clone_2); - } - else { - if (ts.isGeneratedIdentifier(propertyName)) { - var clone_3 = ts.getSynthesizedClone(propertyName); - clone_3.text = ts.unescapeIdentifier(clone_3.text); - return ts.createPropertyAccess(expression, clone_3); + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, element); + } + } + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 + && !(element.transformFlags & (524288 | 1048576)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); } else { - return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0)) { + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1) { + if (element.transformFlags & 1048576) { + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } } } - function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteral(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + return ts.createElementAccess(value, argumentExpression); + } + else { + var name_33 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + return ts.createPropertyAccess(value, name_33); + } + } + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); + var temp = ts.createTempVariable(undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.createAssignment(temp, value, location)); } - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, undefined); + } + return temp; } } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(undefined, undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]); + } })(ts || (ts = {})); var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,34 +39059,61 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(177); + context.enableSubstitution(178); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; - var currentSourceFileExternalHelpersModuleName; + var currentScopeFirstDeclarationsOfName; var enabledSubstitutions; var classAliases; var applicableSubstitutions; - var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { - return ts.visitNode(node, visitor, ts.isSourceFile); + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 261: + case 232: + case 231: + case 204: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 226: + case 225: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); + break; + } + } function visitor(node) { return saveStateAndInvoke(node, visitorWorker); } function visitorWorker(node) { - if (node.kind === 256) { - return visitSourceFile(node); - } - else if (node.transformFlags & 1) { + if (node.transformFlags & 1) { return visitTypeScript(node); } else if (node.transformFlags & 2) { @@ -35358,15 +39121,32 @@ var ts; } return node; } + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 240: + return visitExportAssignment(node); + case 241: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } function namespaceElementVisitor(node) { return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 236 || - node.kind === 230 || - node.kind === 231 || - (node.kind === 229 && - node.moduleReference.kind === 240)) { + if (node.kind === 241 || + node.kind === 235 || + node.kind === 236 || + (node.kind === 234 && + node.moduleReference.kind === 245)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -35382,145 +39162,129 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 148: - return undefined; - case 145: - case 153: - case 149: case 150: + return undefined; case 147: + case 155: + case 151: + case 152: + case 149: return visitorWorker(node); - case 198: + case 203: return node; default: ts.Debug.failBadSyntaxKind(node); return undefined; } } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270) { + return undefined; + } + else if (currentNamespace && node.kind === 83) { + return undefined; + } + return node; + } function visitTypeScript(node) { if (ts.hasModifier(node, 2) && ts.isStatement(node)) { return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 82: - case 77: + case 83: + case 78: return currentNamespace ? undefined : node; - case 112: - case 110: + case 113: case 111: - case 115: - case 118: - case 74: - case 122: - case 128: - case 160: - case 161: - case 159: - case 154: - case 141: - case 117: - case 120: - case 132: + case 112: + case 116: + case 75: + case 123: case 130: - case 127: - case 103: - case 133: - case 157: - case 156: - case 158: - case 155: case 162: case 163: + case 161: + case 156: + case 143: + case 118: + case 121: + case 134: + case 132: + case 129: + case 104: + case 135: + case 159: + case 158: + case 160: + case 157: case 164: case 165: case 166: - case 153: - case 143: - case 223: + case 167: + case 168: + case 169: + case 170: + case 171: + case 155: case 145: - case 148: - return undefined; - case 222: - return ts.createNotEmittedStatement(node); - case 221: - return visitClassDeclaration(node); - case 192: - return visitClassExpression(node); - case 251: - return visitHeritageClause(node); - case 194: - return visitExpressionWithTypeArguments(node); + case 228: case 147: - return visitMethodDeclaration(node); - case 149: - return visitGetAccessor(node); + return undefined; case 150: + return visitConstructor(node); + case 227: + return ts.createNotEmittedStatement(node); + case 226: + return visitClassDeclaration(node); + case 197: + return visitClassExpression(node); + case 255: + return visitHeritageClause(node); + case 199: + return visitExpressionWithTypeArguments(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessor(node); + case 152: return visitSetAccessor(node); - case 220: - return visitFunctionDeclaration(node); - case 179: - return visitFunctionExpression(node); - case 180: - return visitArrowFunction(node); - case 142: - return visitParameter(node); - case 178: - return visitParenthesizedExpression(node); - case 177: - case 195: - return visitAssertionExpression(node); - case 196: - return visitNonNullExpression(node); - case 224: - return visitEnumDeclaration(node); - case 184: - return visitAwaitExpression(node); - case 200: - return visitVariableStatement(node); case 225: - return visitModuleDeclaration(node); + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 183: + return visitParenthesizedExpression(node); + case 182: + case 200: + return visitAssertionExpression(node); + case 179: + return visitCallExpression(node); + case 180: + return visitNewExpression(node); + case 201: + return visitNonNullExpression(node); case 229: + return visitEnumDeclaration(node); + case 205: + return visitVariableStatement(node); + case 223: + return visitVariableDeclaration(node); + case 230: + return visitModuleDeclaration(node); + case 234: return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function onBeforeVisitNode(node) { - switch (node.kind) { - case 256: - case 227: - case 226: - case 199: - currentScope = node; - break; - } - } function visitSourceFile(node) { - currentSourceFile = node; - if (node.flags & 31744 - && compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); - var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); - var externalHelpersModuleImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~8; - statements.push(externalHelpersModuleImport); - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = ts.visitEachChild(node, visitor, context); - } - setNodeEmitFlags(node, 1 | node.emitFlags); - return node; + var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { if (node.decorators && node.decorators.length > 0) { @@ -35539,71 +39303,64 @@ var ts; var staticProperties = getInitializedProperties(node, true); var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var classAlias; var name = node.name; if (!name && staticProperties.length > 0) { name = ts.getGeneratedNameForNode(node); } - var statements = []; - if (!isDecoratedClass) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); - ts.setOriginalNode(classDeclaration, node); - if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); - } - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + var classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var statements = [classStatement]; if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, true)); + addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); if (isNamespaceExport(node)) { addExportMemberAssignment(statements, node); } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(ts.createExportAssignment(undefined, undefined, false, getLocalName(node))); + statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } - return statements; + if (statements.length > 1) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + } + return ts.singleOrMany(statements); } - function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + var emitFlags = ts.getEmitFlags(node); + if (hasStaticProperties) { + emitFlags |= 32; + } + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; + } + function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { var location = ts.moveRangePastDecorators(node); - var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), location), node); - if (!name) { - name = ts.getGeneratedNameForNode(node); - } - var classAlias; - if (resolver.getNodeCheckFlags(node) & 8388608) { - enableSubstitutionForClassAliases(); - classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - } - var declaredName = getDeclarationName(node, true); - var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) - ]), location); - setCommentRange(transformedClassExpression, node); - statements.push(ts.setOriginalNode(transformedClassExpression, node)); - if (classAlias) { - statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(declaredName, undefined, classAlias) - ]), location), node)); - } - return classAlias; + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, false, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, hasExtendsClause); + var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members, location); + ts.setOriginalNode(classExpression, node); + var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location); + ts.setOriginalNode(statement, node); + ts.setCommentRange(statement, node); + return statement; } function visitClassExpression(node) { var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, heritageClauses !== undefined); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84; })); var classExpression = ts.setOriginalNode(ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members, node), node); if (staticProperties.length > 0) { var expressions = []; @@ -35612,9 +39369,9 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); - ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } @@ -35631,24 +39388,23 @@ var ts; } function transformConstructor(node, hasExtendsClause) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 131072; + var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + var body = transformConstructorBody(node, constructor, hasExtendsClause); return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(undefined, undefined, parameters, body, constructor || node), constructor)); } function transformConstructorParameters(constructor) { - return constructor - ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) - : []; + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } - function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + function transformConstructorBody(node, constructor, hasExtendsClause) { var statements = []; var indexOfFirstStatement = 0; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); var propertyAssignments = getParametersWithPropertyAssignments(constructor); @@ -35658,12 +39414,12 @@ var ts; statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); - addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } ts.addRange(statements, endLexicalEnvironment()); - return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined), true); + return ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : undefined, true); } function addPrologueDirectivesAndInitialSuperCall(ctor, result) { if (ctor.body) { @@ -35673,7 +39429,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 207 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +39448,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 1536 | 48); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 1536); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35707,32 +39463,32 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 145 + return member.kind === 147 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } - function addInitializedPropertyStatements(statements, node, properties, receiver) { - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; - var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } - function generateInitializedPropertyExpressions(node, properties, receiver) { + function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { - var property = properties_8[_i]; - var expression = transformInitializedProperty(node, property, receiver); + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; } - function transformInitializedProperty(node, property, receiver) { + function transformInitializedProperty(property, receiver) { var propertyName = visitPropertyNameOfClassElement(property); var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); @@ -35780,12 +39536,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 149: - case 150: + case 151: + case 152: return getAllDecoratorsOfAccessors(node, member); - case 147: + case 149: return getAllDecoratorsOfMethod(member); - case 145: + case 147: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -35796,10 +39552,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -35824,14 +39581,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -35856,44 +39613,40 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 145 + ? member.kind === 147 ? ts.createVoidZero() : ts.createNull() : undefined; - var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536); return helper; } - function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { - var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } } - function generateConstructorDecorationExpression(node, decoratedClassAlias) { + function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - if (decoratedClassAlias) { - var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); - var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } - else { - var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); - return result; - } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, false, true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; } function transformDecorator(decorator) { return ts.visitNode(decorator.expression, visitor, ts.isExpression); @@ -35904,97 +39657,90 @@ var ts; expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, decorator.expression); + ts.setEmitFlags(helper, 1536); expressions.push(helper); } } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, undefined, true))); } } } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 147 - || kind === 149 - || kind === 150 - || kind === 145; + return kind === 149 + || kind === 151 + || kind === 152 + || kind === 147; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 147; + return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 221 - || kind === 192 - || kind === 147 - || kind === 149 - || kind === 150; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { - case 145: - case 142: - case 149: - return serializeTypeNode(node.type); - case 150: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 221: - case 192: case 147: + case 144: + case 151: + return serializeTypeNode(node.type); + case 152: + return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 226: + case 197: + case 149: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 160) { - return node.elementType; - } - else if (node && node.kind === 155) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -36002,7 +39748,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -36010,7 +39756,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -36019,6 +39765,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -36033,49 +39788,75 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 103: + case 104: return ts.createVoidZero(); - case 164: - return serializeTypeNode(node.type); - case 156: - case 157: - return ts.createIdentifier("Function"); - case 160: - case 161: - return ts.createIdentifier("Array"); - case 154: - case 120: - return ts.createIdentifier("Boolean"); - case 132: - return ts.createIdentifier("String"); case 166: + return serializeTypeNode(node.type); + case 158: + case 159: + return ts.createIdentifier("Function"); + case 162: + case 163: + return ts.createIdentifier("Array"); + case 156: + case 121: + return ts.createIdentifier("Boolean"); + case 134: + return ts.createIdentifier("String"); + case 171: switch (node.literal.kind) { case 9: return ts.createIdentifier("String"); case 8: return ts.createIdentifier("Number"); - case 99: - case 84: + case 100: + case 85: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 130: + case 132: return ts.createIdentifier("Number"); - case 133: + case 135: return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 155: + case 157: return serializeTypeReferenceNode(node); - case 158: - case 159: - case 162: - case 163: - case 117: case 165: + case 164: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 70) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } + case 160: + case 168: + case 169: + case 170: + case 161: + case 118: + case 167: break; default: ts.Debug.failBadSyntaxKind(node); @@ -36088,7 +39869,7 @@ var ts; case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: return serializeEntityNameAsExpression(node.typeName, false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: @@ -36116,22 +39897,22 @@ var ts; } function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + case 70: + var name_34 = ts.getMutableClone(node); + name_34.flags &= ~8; + name_34.original = undefined; + name_34.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_34), ts.createLiteral("undefined")), name_34); } - return name_29; - case 139: + return name_34; + case 141: return serializeQualifiedNameAsExpression(node, useFallback); } } function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 69) { + if (node.left.kind === 70) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { @@ -36144,7 +39925,7 @@ var ts; return ts.createPropertyAccess(left, node.right); } function getGlobalSymbolNameWithFallback() { - return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53), ts.createIdentifier("Symbol"), ts.createToken(54), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; @@ -36154,7 +39935,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeIdentifier(name.text)); } else { return ts.getSynthesizedClone(name); @@ -36176,9 +39957,9 @@ var ts; } } function visitHeritageClause(node) { - if (node.token === 83) { + if (node.token === 84) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.createHeritageClause(83, types, node); + return ts.createHeritageClause(84, types, node); } return undefined; } @@ -36189,15 +39970,22 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.visitEachChild(node, visitor, context); + } function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(method, node); - return method; + var updated = ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); @@ -36206,135 +39994,56 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateGetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateSetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var func = ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); + var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isNamespaceExport(node)) { - var statements = [func]; + var statements = [updated]; addExportMemberAssignment(statements, node); return statements; } - return func; + return updated; } function visitFunctionExpression(node) { if (ts.nodeIsMissing(node.body)) { return ts.createOmittedExpression(); } - var func = ts.createFunctionExpression(node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - ts.setOriginalNode(func, node); - return func; + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitArrowFunction(node) { - var func = ts.createArrowFunction(undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.equalsGreaterThanToken, transformConciseBody(node), node); - ts.setOriginalNode(func, node); - return func; - } - function transformFunctionBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformFunctionBodyWorker(node.body); - } - function transformFunctionBodyWorker(body, start) { - if (start === void 0) { start = 0; } - var savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); - var visited = ts.updateBlock(body, statements); - var declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - function transformConciseBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformConciseBodyWorker(node.body, false); - } - function transformConciseBodyWorker(body, forceBlockFunctionBody) { - if (ts.isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - var visited = ts.visitNode(body, visitor, ts.isConciseBody); - var declarations = endLexicalEnvironment(); - var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !ts.isBlock(merged)) { - return ts.createBlock([ - ts.createReturn(merged) - ]); - } - else { - return merged; - } - } - } - function getPromiseConstructor(type) { - var typeName = ts.getEntityNameFromTypeNode(type); - if (typeName && ts.isEntityName(typeName)) { - var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - return undefined; - } - function transformAsyncFunctionBody(node) { - var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(node.type) : undefined; - var isArrowFunction = node.kind === 180; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; - if (!isArrowFunction) { - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); - var block = ts.createBlock(statements, node.body, true); - if (languageVersion >= 2) { - if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); - } - else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); - } - } - return block; - } - else { - return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, true)); - } + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); + var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32); return parameter; } function visitVariableStatement(node) { @@ -36352,14 +40061,14 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + return ts.flattenDestructuringAssignment(node, visitor, context, 0, false, createNamespaceExportExpression); } else { return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), node); } } - function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2); @@ -36377,42 +40086,43 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return ts.createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } function shouldEmitEnumDeclaration(node) { return !ts.isConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); - } - function addVarForEnumExportedFromNamespace(statements, node) { - var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); - statements.push(statement); - } function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { return undefined; } var statements = []; - var emitFlags = 64; - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); - ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); - statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); + moduleArg = ts.createAssignment(localName, moduleArg); } + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg]), node); + ts.setOriginalNode(enumStatement, node); + ts.setEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -36447,35 +40157,56 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); + function hasNamespaceQualifiedExportName(node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.System); } - function isES6ExportedDeclaration(node) { - return isExternalModuleExport(node) - && moduleKind === ts.ModuleKind.ES6; + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } } - function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_35 = node.symbol && node.symbol.name; + if (name_35) { + return currentScopeFirstDeclarationsOfName[name_35] === node; + } + } + return false; } function addVarForEnumOrModuleDeclaration(statements, node) { - var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) - ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) - : undefined, [ - ts.createVariableDeclaration(getDeclarationName(node, false, true)) + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + ts.createVariableDeclaration(ts.getLocalName(node, false, true)) ]); ts.setOriginalNode(statement, node); - if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + if (node.kind === 229) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 1024 | 2097152); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 | 2097152); + statements.push(mergeMarker); + return false; } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); - statements.push(statement); } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -36484,38 +40215,42 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name), "TypeScript module should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; - var emitFlags = 64; - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + var emitFlags = 2; + if (addVarForEnumOrModuleDeclaration(statements, node)) { if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384; + emitFlags |= 512; } } var parameterName = getNamespaceParameterName(node); var containerName = getNamespaceContainerName(node); - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) + : ts.getLocalName(node, false, true); var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); - if (ts.hasModifier(node, 1) && !isES6ExportedDeclaration(node)) { - var localName = getLocalName(node); + if (hasNamespaceQualifiedExportName(node)) { + var localName = ts.getLocalName(node, false, true); moduleArg = ts.createAssignment(localName, moduleArg); } - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 226) { + if (body.kind === 231) { ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); statementsLocation = body.statements; blockLocation = body; @@ -36536,18 +40271,69 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); - if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + if (body.kind !== 231) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body.kind === 230) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + function visitImportDeclaration(node) { + if (!node.importClause) { + return node; + } + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, true); + return importClause + ? ts.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier) + : undefined; + } + function visitImportClause(node) { + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, true); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + function visitNamedImportBindings(node) { + if (node.kind === 237) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + function visitImportSpecifier(node) { + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + function visitExportAssignment(node) { + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + function visitExportDeclaration(node) { + if (!node.exportClause) { + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + return undefined; + } + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, true); + return exportClause + ? ts.updateExportDeclaration(node, undefined, undefined, exportClause, node.moduleSpecifier) + : undefined; + } + function visitNamedExports(node) { + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + function visitExportSpecifier(node) { + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } function shouldEmitImportEqualsDeclaration(node) { return resolver.isReferencedAliasDeclaration(node) || (!ts.isExternalModule(currentSourceFile) @@ -36555,16 +40341,18 @@ var ts; } function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { - return ts.visitEachChild(node, visitor, context); + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 1536 | 2048); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { - return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(node.name, undefined, moduleReference) + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ]), node), node); } else { @@ -36589,148 +40377,87 @@ var ts; return ts.createStatement(expression, undefined); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, false, true), exportValue), location); + return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, false, true), exportValue), location); } - function createExternalModuleExport(exportName) { - return ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([ - ts.createExportSpecifier(exportName) - ])); - } - function getNamespaceMemberName(name, allowComments, allowSourceMaps) { - var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), name); - var emitFlags; - if (!allowComments) { - emitFlags |= 49152; - } - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return getNamespaceMemberName(name, false, true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, false, true); } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { return ts.getGeneratedNameForNode(node); } - function getLocalName(node, noSourceMaps, allowComments) { - return getDeclarationName(node, allowComments, !noSourceMaps, 262144); - } - function getExportName(node, noSourceMaps, allowComments) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - return getDeclarationName(node, allowComments, !noSourceMaps, 131072); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); - } - return name_30; - } - else { - return ts.getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 8388608) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } function getClassPrototype(node) { - return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { return ts.hasModifier(member, 32) - ? getDeclarationName(node) + ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8) === 0) { enabledSubstitutions |= 8; - context.enableSubstitution(69); - } - } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 4) === 0) { - enabledSubstitutions |= 4; - context.enableSubstitution(174); - context.enableSubstitution(172); - context.enableSubstitution(173); - context.enableEmitNotification(221); - context.enableEmitNotification(147); - context.enableEmitNotification(149); - context.enableEmitNotification(150); - context.enableEmitNotification(148); + context.enableSubstitution(70); } } function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(69); + context.enableSubstitution(70); classAliases = ts.createMap(); } } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(69); - context.enableSubstitution(254); - context.enableEmitNotification(225); + context.enableSubstitution(70); + context.enableSubstitution(258); + context.enableEmitNotification(230); } } - function isSuperContainer(node) { - var kind = node.kind; - return kind === 221 - || kind === 148 - || kind === 147 - || kind === 149 - || kind === 150; - } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 225; + return ts.getOriginalNode(node).kind === 230; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 224; + return ts.getOriginalNode(node).kind === 229; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; - var savedCurrentSuperContainer = currentSuperContainer; - if (enabledSubstitutions & 4 && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2; } if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,32 +40467,26 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_36 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_36); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_36, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_36, exportedName, node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: - return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); } return node; } @@ -36781,10 +40502,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); - return clone_4; + var clone_2 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -36792,11 +40513,11 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container) { - var substitute = (applicableSubstitutions & 2 && container.kind === 225) || - (applicableSubstitutions & 8 && container.kind === 224); + if (container && container.kind !== 261) { + var substitute = (applicableSubstitutions & 2 && container.kind === 230) || + (applicableSubstitutions & 8 && container.kind === 229); if (substitute) { return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, node); } @@ -36804,100 +40525,354 @@ var ts; } return undefined; } - function substituteCallExpression(node) { - var expression = node.expression; - if (ts.isSuperProperty(expression)) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - var argumentExpression = ts.isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ - ts.createThis() - ].concat(node.arguments)); - } - } - return node; - } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); - } - } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; } + ts.setConstantValue(node, constantValue); + return substitute; } return node; } - function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { - if (flags & 4096) { - return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; } - else { - return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); - } - } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; } } ts.transformTypeScript = transformTypeScript; + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.createCall(ts.getHelperName("__param"), undefined, [ + ts.createLiteral(parameterOffset), + expression + ], location); + } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); + } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + context.requestEmitHelper(decorateHelper); + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, undefined, true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray, location); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, true); + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8) === 0) { + return node; + } + switch (node.kind) { + case 176: + return visitObjectLiteralExpression(node); + case 192: + return visitBinaryExpression(node, noDestructuringValue); + case 223: + return visitVariableDeclaration(node); + case 213: + return visitForOfStatement(node); + case 211: + return visitForStatement(node); + case 188: + return visitVoidExpression(node); + case 150: + return visitConstructorDeclaration(node); + case 149: + return visitMethodDeclaration(node); + case 151: + return visitGetAccessorDeclaration(node); + case 152: + return visitSetAccessorDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + case 144: + return visitParameter(node); + case 207: + return visitExpressionStatement(node); + case 183: + return visitParenthesizedExpression(node, noDestructuringValue); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; + if (e.kind === 259) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === 257) { + var p = e; + chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); + } + else { + chunkObject.push(e); + } + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 1048576) { + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 176) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); + } + else if (node.operatorToken.kind === 25) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + return ts.flattenDestructuringBinding(node, visitor, context, 1); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitForOfStatement(node) { + var leadingStatements; + var temp; + var initializer = ts.skipParentheses(node.initializer); + if (initializer.transformFlags & 1048576) { + if (ts.isVariableDeclarationList(initializer)) { + temp = ts.createTempVariable(undefined); + var firstDeclaration = ts.firstOrUndefined(initializer.declarations); + var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(initializer, declarations), initializer); + leadingStatements = ts.append(leadingStatements, statement); + } + } + else if (ts.isAssignmentPattern(initializer)) { + temp = ts.createTempVariable(undefined); + var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, node.initializer)), visitor, context, 1); + leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, node.initializer)); + } + } + if (temp) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var block = ts.isBlock(statement) + ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements)) + : ts.createBlock(ts.append(leadingStatements, statement), statement, true); + return ts.updateForOf(node, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, undefined, undefined, node.initializer) + ], node.initializer, 1), expression, block); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParameter(node) { + if (node.transformFlags & 1048576) { + return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + return ts.updateConstructor(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitGetAccessorDeclaration(node) { + return ts.updateGetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitSetAccessorDeclaration(node) { + return ts.updateSetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var leadingStatements; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 1048576) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 524288); + leadingStatements = ts.append(leadingStatements, statement); + } + } + } + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + var trailingStatements = endLexicalEnvironment(); + if (ts.some(leadingStatements) || ts.some(trailingStatements)) { + var block = ts.convertToFunctionBody(body, true); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); + } + return body; + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + }; + function createAssignHelper(context, attributesSegments) { + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; })(ts || (ts = {})); var ts; (function (ts) { - var entities = createEntitiesMap(); function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; - return node; + return visited; } function visitor(node) { if (node.transformFlags & 4) { return visitorWorker(node); } - else if (node.transformFlags & 8) { - return ts.visitEachChild(node, visitor, context); - } else { return node; } } function visitorWorker(node) { switch (node.kind) { - case 241: + case 246: return visitJsxElement(node, false); - case 242: + case 247: return visitJsxSelfClosingElement(node, false); - case 248: + case 252: return visitJsxExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.visitEachChild(node, visitor, context); } } function transformJsxChildToExpression(node) { switch (node.kind) { - case 244: + case 10: return visitJsxText(node); - case 248: + case 252: return visitJsxExpression(node); - case 241: + case 246: return visitJsxElement(node, true); - case 242: + case 247: return visitJsxSelfClosingElement(node, true); default: ts.Debug.failBadSyntaxKind(node); @@ -36924,10 +40899,12 @@ var ts; if (ts.isJsxSpreadAttribute(attrs[0])) { segments.unshift(ts.createObjectLiteral()); } - objectProperties = ts.singleOrUndefined(segments) - || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } } - var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -36949,7 +40926,7 @@ var ts; var decoded = tryDecodeEntities(node.text); return decoded ? ts.createLiteral(decoded, node) : node; } - else if (node.kind === 248) { + else if (node.kind === 252) { return visitJsxExpression(node); } else { @@ -37014,16 +40991,16 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 241) { + if (node.kind === 246) { return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_37 = node.tagName; + if (ts.isIdentifier(name_37) && ts.isIntrinsicJsxName(name_37.text)) { + return ts.createLiteral(name_37.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_37); } } } @@ -37041,330 +41018,585 @@ var ts; } } ts.transformJsx = transformJsx; - function createEntitiesMap() { - return ts.createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + var entities = ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); })(ts || (ts = {})); var ts; (function (ts) { - function transformES7(context) { + function transformES2017(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var currentSourceFile; + var enabledSubstitutions; + var currentSuperContainer; + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16) === 0) { + return node; + } + switch (node.kind) { + case 119: + return undefined; + case 189: + return visitAwaitExpression(node); + case 149: + return visitMethodDeclaration(node); + case 225: + return visitFunctionDeclaration(node); + case 184: + return visitFunctionExpression(node); + case 185: + return visitArrowFunction(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression), node), node); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 185; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(statements, node.body, true); + if (languageVersion >= 2) { + if (resolver.getNodeCheckFlags(node) & 4096) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, asyncSuperHelper); + } + } + return block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements)); + } + return expression; + } + } + function transformFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); + var declarations = endLexicalEnvironment(); + return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1) === 0) { + enabledSubstitutions |= 1; + context.enableSubstitution(179); + context.enableSubstitution(177); + context.enableSubstitution(178); + context.enableEmitNotification(226); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(150); + } + } + function substituteExpression(node) { + switch (node.kind) { + case 177: + return substitutePropertyAccessExpression(node); + case 178: + return substituteElementAccessExpression(node); + case 179: + if (enabledSubstitutions & 1) { + return substituteCallExpression(node); + } + break; + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (enabledSubstitutions & 1 && node.expression.kind === 96) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 226 + || kind === 150 + || kind === 149 + || kind === 151 + || kind === 152; + } + function onEmitNode(emitContext, node, emitCallback) { + if (enabledSubstitutions & 1 && isSuperContainer(node)) { + var savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 | 4096); + } + } + ts.transformES2017 = transformES2017; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(38), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: "\n const _super = name => super[name];" + }; + var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);" + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if (node.transformFlags & 16) { - return visitorWorker(node); - } - else if (node.transformFlags & 32) { - return ts.visitEachChild(node, visitor, context); - } - else { + if ((node.transformFlags & 32) === 0) { return node; } - } - function visitorWorker(node) { switch (node.kind) { - case 187: + case 192: return visitBinaryExpression(node); default: - ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } function visitBinaryExpression(node) { - var left = ts.visitNode(node.left, visitor, ts.isExpression); - var right = ts.visitNode(node.right, visitor, ts.isExpression); - if (node.operatorToken.kind === 60) { - var target = void 0; - var value = void 0; - if (ts.isElementAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); - value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); - } - else if (ts.isPropertyAccessExpression(left)) { - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); - value = ts.createPropertyAccess(expressionTemp, left.name, left); - } - else { - target = left; - value = left; - } - return ts.createAssignment(target, ts.createMathPow(value, right, node), node); - } - else if (node.operatorToken.kind === 38) { - return ts.createMathPow(left, right, node); - } - else { - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + switch (node.operatorToken.kind) { + case 61: + return visitExponentiationAssignmentExpression(node); + case 39: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); } } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, left.argumentExpression), left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, left); + } + else if (ts.isPropertyAccessExpression(left)) { + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, left.expression), left.name, left); + value = ts.createPropertyAccess(expressionTemp, left.name, left); + } + else { + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, node), node); + } + function visitExponentiationExpression(node) { + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, node); + } } - ts.transformES7 = transformES7; + ts.transformES2016 = transformES2016; })(ts || (ts = {})); var ts; (function (ts) { - function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37380,13 +41612,21 @@ var ts; var enclosingFunction; var enclosingNonArrowFunction; var enclosingNonAsyncFunctionBody; + var isInConstructorWithCapturedSuper; var convertedLoopState; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; - return ts.visitNode(node, visitor, ts.isSourceFile); + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + return visited; } function visitor(node) { return saveStateAndInvoke(node, dispatcher); @@ -37406,11 +41646,14 @@ var ts; var savedCurrentParent = currentParent; var savedCurrentNode = currentNode; var savedConvertedLoopState = convertedLoopState; + var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; if (ts.nodeStartsNewLexicalEnvironment(node)) { + isInConstructorWithCapturedSuper = false; convertedLoopState = undefined; } onBeforeVisitNode(node); var visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; convertedLoopState = savedConvertedLoopState; enclosingFunction = savedEnclosingFunction; enclosingNonArrowFunction = savedEnclosingNonArrowFunction; @@ -37422,16 +41665,57 @@ var ts; currentNode = savedCurrentNode; return visited; } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 185) { + enclosingNonArrowFunction = currentNode; + if (!(ts.getEmitFlags(currentNode) & 131072)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + switch (currentNode.kind) { + case 205: + enclosingVariableStatement = currentNode; + break; + case 224: + case 223: + case 174: + case 172: + case 173: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return isInConstructorWithCapturedSuper && node.kind === 216 && !node.expression; + } function shouldCheckNode(node) { return (node.transformFlags & 64) !== 0 || - node.kind === 214 || + node.kind === 219 || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); } function visitorWorker(node) { - if (shouldCheckNode(node)) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { return visitJavaScript(node); } - else if (node.transformFlags & 128) { + else if (node.transformFlags & 128 || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) { return ts.visitEachChild(node, visitor, context); } else { @@ -37450,18 +41734,19 @@ var ts; } function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 211: + case 216: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; return visitReturnStatement(node); - case 200: + case 205: return visitVariableStatement(node); - case 213: + case 218: return visitSwitchStatement(node); - case 210: - case 209: + case 215: + case 214: return visitBreakOrContinueStatement(node); - case 97: + case 98: return visitThisKeyword(node); - case 69: + case 70: return visitIdentifier(node); default: return ts.visitEachChild(node, visitor, context); @@ -37469,111 +41754,90 @@ var ts; } function visitJavaScript(node) { switch (node.kind) { - case 82: - return node; - case 221: + case 114: + return undefined; + case 226: return visitClassDeclaration(node); - case 192: + case 197: return visitClassExpression(node); - case 142: + case 144: return visitParameter(node); - case 220: + case 225: return visitFunctionDeclaration(node); - case 180: + case 185: return visitArrowFunction(node); - case 179: + case 184: return visitFunctionExpression(node); - case 218: + case 223: return visitVariableDeclaration(node); - case 69: + case 70: return visitIdentifier(node); - case 219: + case 224: return visitVariableDeclarationList(node); - case 214: + case 219: return visitLabeledStatement(node); - case 204: + case 209: return visitDoStatement(node); - case 205: + case 210: return visitWhileStatement(node); - case 206: + case 211: return visitForStatement(node); - case 207: + case 212: return visitForInStatement(node); - case 208: + case 213: return visitForOfStatement(node); - case 202: + case 207: return visitExpressionStatement(node); - case 171: + case 176: return visitObjectLiteralExpression(node); - case 254: + case 256: + return visitCatchClause(node); + case 258: return visitShorthandPropertyAssignment(node); - case 170: - return visitArrayLiteralExpression(node); - case 174: - return visitCallExpression(node); case 175: + return visitArrayLiteralExpression(node); + case 179: + return visitCallExpression(node); + case 180: return visitNewExpression(node); - case 178: + case 183: return visitParenthesizedExpression(node, true); - case 187: + case 192: return visitBinaryExpression(node, true); - case 11: case 12: case 13: case 14: + case 15: return visitTemplateLiteral(node); - case 176: + case 181: return visitTaggedTemplateExpression(node); - case 189: + case 194: return visitTemplateExpression(node); - case 190: + case 195: return visitYieldExpression(node); - case 95: - return visitSuperKeyword(node); - case 190: + case 196: + return visitSpreadElement(node); + case 96: + return visitSuperKeyword(); + case 195: return ts.visitEachChild(node, visitor, context); - case 147: + case 149: return visitMethodDeclaration(node); - case 256: - return visitSourceFileNode(node); - case 200: + case 205: return visitVariableStatement(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function onBeforeVisitNode(node) { - if (currentNode) { - if (ts.isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - if (ts.isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== 180) { - enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - switch (currentNode.kind) { - case 200: - enclosingVariableStatement = currentNode; - break; - case 219: - case 218: - case 169: - case 167: - case 168: - break; - default: - enclosingVariableStatement = undefined; - } - } - currentParent = currentNode; - currentNode = node; + function visitSourceFile(node) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); } function visitSwitchStatement(node) { ts.Debug.assert(convertedLoopState !== undefined); @@ -37594,7 +41858,7 @@ var ts; } function visitThisKeyword(node) { ts.Debug.assert(convertedLoopState !== undefined); - if (enclosingFunction && enclosingFunction.kind === 180) { + if (enclosingFunction && enclosingFunction.kind === 185) { convertedLoopState.containsLexicalThis = true; return node; } @@ -37614,13 +41878,13 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 210 ? 2 : 4; + var jump = node.kind === 215 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 210) { + if (node.kind === 215) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -37630,7 +41894,7 @@ var ts; } } else { - if (node.kind === 210) { + if (node.kind === 215) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -37649,10 +41913,10 @@ var ts; expr = copyExpr; } else { - expr = ts.createBinary(expr, 24, copyExpr); + expr = ts.createBinary(expr, 25, copyExpr); } } - returnExpression = ts.createBinary(expr, 24, returnExpression); + returnExpression = ts.createBinary(expr, 25, returnExpression); } return ts.createReturn(returnExpression); } @@ -37660,26 +41924,26 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitClassDeclaration(node) { - var modifierFlags = ts.getModifierFlags(node); - var isExported = modifierFlags & 1; - var isDefault = modifierFlags & 512; - var modifiers = isExported && !isDefault - ? ts.filter(node.modifiers, isExportModifier) - : undefined; - var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(getDeclarationName(node, true), undefined, transformClassLikeDeclarationToExpression(node)) - ]), node); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, true), undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([variable]), node); ts.setOriginalNode(statement, node); ts.startOnNewLine(statement); - if (isExported && isDefault) { - var statements = [statement]; - statements.push(ts.createExportAssignment(undefined, undefined, false, getDeclarationName(node, false))); - return statements; + statements.push(statement); + if (ts.hasModifier(node, 1)) { + var exportStatement = ts.hasModifier(node, 512) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); } - return statement; - } - function isExportModifier(node) { - return node.kind === 82; + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 2097152) === 0) { + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 2097152); + } + return ts.singleOrMany(statements); } function visitClassExpression(node) { return transformClassLikeDeclarationToExpression(node); @@ -37689,16 +41953,16 @@ var ts; enableSubstitutionsForBlockScopedBindings(); } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); + if (ts.getEmitFlags(node) & 32768) { + ts.setEmitFlags(classFunction, 32768); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 1536); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 1536); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37709,83 +41973,161 @@ var ts; addExtendsHelperIfNeeded(statements, node, extendsClauseElement); addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16); - var localName = getLocalName(node); + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 17); + var localName = ts.getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 1536); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 1536); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), extendsClauseElement)); + statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { - if (constructor && !hasSynthesizedSuper) { - return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); - } - return []; + return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; - startLexicalEnvironment(); + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 0; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { + isInConstructorWithCapturedSuper = superCaptureStatus === 1; + return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); + }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 1536); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 216) { + return true; } + else if (statement.kind === 208) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 204) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 207 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (16384 | 32768))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 192 + || superCallExpression.left.kind !== 179) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); + statements.push(returnStatement); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { return undefined; } else if (ts.isBindingPattern(node.name)) { - return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), undefined, node), node); + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, ts.getGeneratedNameForNode(node), undefined, undefined, undefined, node), node); } else if (node.initializer) { - return ts.setOriginalNode(ts.createParameter(node.name, undefined, node), node); + return ts.setOriginalNode(ts.createParameter(undefined, undefined, undefined, node.name, undefined, undefined, undefined, node), node); } else { return node; } } function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536) !== 0; + return (node.transformFlags & 131072) !== 0; } function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { @@ -37793,38 +42135,38 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) - ], parameter), 32 | 1024 | 12288), undefined, parameter); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer)), parameter)) + ], parameter), 1 | 32 | 384), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 384 | 32 | 524288); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 69 && !inConstructorWithSynthesizedSuper; + return node && node.dotDotDotToken && node.name.kind === 70 && !inConstructorWithSynthesizedSuper; } function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { var parameter = ts.lastOrUndefined(node.parameters); @@ -37832,51 +42174,56 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 48); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ]), parameter), 8388608)); + ]), parameter), 524288)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ - ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 524288); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + if (node.transformFlags & 32768 && node.kind !== 185) { + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 198: + case 203: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 147: + case 149: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); break; - case 149: - case 150: + case 151: + case 152: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); } break; - case 148: + case 150: break; default: ts.Debug.failBadSyntaxKind(node); @@ -37888,43 +42235,46 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); - var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); - var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); + var memberFunction = transformFunctionLikeToExpression(member, member, undefined); + ts.setEmitFlags(memberFunction, 1536); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 48); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 1536 | 32); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 1536 | 16); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37939,25 +42289,30 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 8192) { + if (node.transformFlags & 16384) { enableSubstitutionsForCapturedThis(); } - var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8); return func; } function visitFunctionExpression(node) { - return transformFunctionLikeToExpression(node, node, node.name); + return ts.updateFunctionExpression(node, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); } function visitFunctionDeclaration(node) { - return ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, node.asteriskToken, node.name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node), node); + return ts.updateFunctionDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.transformFlags & 64 + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); } function transformFunctionLikeToExpression(node, location, name) { var savedContainingNonArrowFunction = enclosingNonArrowFunction; - if (node.kind !== 180) { + if (node.kind !== 185) { enclosingNonArrowFunction = node; } - var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); + var expression = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, saveStateAndInvoke(node, transformFunctionBody), location), node); enclosingNonArrowFunction = savedContainingNonArrowFunction; return expression; } @@ -37969,7 +42324,7 @@ var ts; var statements = []; var body = node.body; var statementOffset; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (ts.isBlock(body)) { statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); } @@ -37987,7 +42342,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 180); + ts.Debug.assert(node.kind === 185); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -38000,48 +42355,49 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 384 | 32 | 1024); statements.push(returnStatement); closeBraceLocation = body; } - var lexicalEnvironment = endLexicalEnvironment(); + var lexicalEnvironment = context.endLexicalEnvironment(); ts.addRange(statements, lexicalEnvironment); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 1); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 17, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; } function visitExpressionStatement(node) { switch (node.expression.kind) { - case 178: + case 183: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 187: + case 192: return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); } return ts.visitEachChild(node, visitor, context); } function visitParenthesizedExpression(node, needsDestructuringValue) { - if (needsDestructuringValue) { + if (!needsDestructuringValue) { switch (node.expression.kind) { - case 178: - return ts.createParen(visitParenthesizedExpression(node.expression, true), node); - case 187: - return ts.createParen(visitBinaryExpression(node.expression, true), node); + case 183: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); + case 192: + return ts.updateParen(node, visitBinaryExpression(node.expression, false)); } } return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node, needsDestructuringValue) { - ts.Debug.assert(ts.isDestructuringAssignment(node)); - return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0, needsDestructuringValue); + } } function visitVariableStatement(node) { if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3) == 0) { @@ -38052,16 +42408,16 @@ var ts; if (decl.initializer) { var assignment = void 0; if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 57, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } } if (assignments) { - return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24, acc); }), node); + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25, acc); }), node); } else { return undefined; @@ -38078,13 +42434,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 8388608 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38098,8 +42454,8 @@ var ts; && ts.isBlock(enclosingBlockScopeContainer) && ts.isIterationStatement(enclosingBlockScopeContainerParent, false)); var emitExplicitInitializer = !emittedAsTopLevel - && enclosingBlockScopeContainer.kind !== 207 - && enclosingBlockScopeContainer.kind !== 208 + && enclosingBlockScopeContainer.kind !== 212 + && enclosingBlockScopeContainer.kind !== 213 && (!resolver.isDeclarationWithCollidingName(node) || (isDeclaredInLoop && !isCapturedInFunction @@ -38112,17 +42468,17 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_5 = ts.getMutableClone(node); - clone_5.initializer = ts.createVoidZero(); - return clone_5; + var clone_3 = ts.getMutableClone(node); + clone_3.initializer = ts.createVoidZero(); + return clone_3; } return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { if (ts.isBindingPattern(node.name)) { - var recordTempVariablesInLine = !enclosingVariableStatement - || !ts.hasModifier(enclosingVariableStatement, 1); - return ts.flattenVariableDestructuring(context, node, undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + var hoistTempVariables = enclosingVariableStatement + && ts.hasModifier(enclosingVariableStatement, 1); + return ts.flattenDestructuringBinding(node, visitor, context, 0, undefined, hoistTempVariables); } return ts.visitEachChild(node, visitor, context); } @@ -38165,33 +42521,34 @@ var ts; var initializer = node.initializer; var statements = []; var counter = ts.createLoopVariable(); - var rhsReference = expression.kind === 69 + var rhsReference = expression.kind === 70 ? ts.createUniqueName(expression.text) : ts.createTempVariable(undefined); + var elementAccess = ts.createElementAccess(rhsReference, counter); if (ts.isVariableDeclarationList(initializer)) { if (initializer.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, elementAccess); var declarationList = ts.createVariableDeclarationList(declarations, initializer); ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, ts.createElementAccess(rhsReference, counter)) - ], ts.moveRangePos(initializer, -1)), ts.moveRangeEnd(initializer, -1))); + ], ts.moveRangePos(initializer, -1)), initializer), ts.moveRangeEnd(initializer, -1))); } } else { - var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); + var assignment = ts.createAssignment(initializer, elementAccess); if (ts.isDestructuringAssignment(assignment)) { - statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, false, hoistVariableDeclaration, visitor))); + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0))); } else { assignment.end = initializer.end; @@ -38214,14 +42571,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 48 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.setEmitFlags(body, 48 | 384); + var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) - ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ], node.expression), 1048576), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); + ts.setEmitFlags(forStatement, 256); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38230,8 +42587,8 @@ var ts; var numInitialProperties = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if (property.transformFlags & 4194304 - || property.name.kind === 140) { + if (property.transformFlags & 16777216 + || property.name.kind === 142) { numInitialProperties = i; break; } @@ -38239,7 +42596,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 32768)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38257,7 +42614,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 69) { + if (node.kind === 70) { state.hoistedLocalVariables.push(node); } else { @@ -38286,11 +42643,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 206: - case 207: - case 208: + case 211: + case 212: + case 213: var initializer = node.initializer; - if (initializer && initializer.kind === 219) { + if (initializer && initializer.kind === 224) { loopInitializer = initializer; } break; @@ -38316,30 +42673,35 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { - var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_3); - loopBody = ts.createBlock(statements_3, undefined, true); + if (loopOutParameters.length || lexicalEnvironment) { + var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); + loopBody = ts.createBlock(statements_4, undefined, true); } if (!ts.isBlock(loopBody)) { loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 - && (node.statement.transformFlags & 4194304) !== 0; + && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072) !== 0 + && (node.statement.transformFlags & 16777216) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { - loopBodyFlags |= 256; + loopBodyFlags |= 8; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 2097152; + loopBodyFlags |= 131072; } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ])); + var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, isAsyncBlockContainingAwait ? ts.createToken(38) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ]), 1048576)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; if (currentState.argumentsName) { @@ -38366,8 +42728,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +42738,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38397,7 +42759,7 @@ var ts; loop.transformFlags = 0; ts.aggregateTransformFlags(loop); } - statements.push(currentParent.kind === 214 + statements.push(currentParent.kind === 219 ? ts.createLabel(currentParent.label, loop) : loop); return statements; @@ -38405,7 +42767,7 @@ var ts; function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 56, source); + return ts.createBinary(target, 57, source); } function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { @@ -38420,7 +42782,7 @@ var ts; !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37), call) : call; + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38), call) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); copyOutParameters(state.loopOutParameters, 0, statements); @@ -38439,10 +42801,10 @@ var ts; else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 33, ts.createLiteral("object")), returnStatement)); } if (state.nonLocalJumps & 2) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 32, ts.createLiteral("break")), ts.createBreak())); + statements.push(ts.createIf(ts.createBinary(loopResultName, 33, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; @@ -38496,7 +42858,7 @@ var ts; } } else { - loopParameters.push(ts.createParameter(name)); + loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { var outParamName = ts.createUniqueName("out_" + name.text); loopOutParameters.push({ originalName: name, outParamName: outParamName }); @@ -38509,21 +42871,21 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 149: - case 150: + case 151: + case 152: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); } break; - case 253: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + case 257: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 254: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + case 258: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 147: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + case 149: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); break; default: ts.Debug.failBadSyntaxKind(node); @@ -38531,31 +42893,44 @@ var ts; } } } - function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), property); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } - function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), property); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } - function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined), method); if (startsOnNewLine) { expression.startsOnNewLine = true; } return expression; } + function visitCatchClause(node) { + ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name)); + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0, temp); + var list = ts.createVariableDeclarationList(vars, node.variableDeclaration, node.variableDeclaration.flags); + var destructure = ts.createVariableStatement(undefined, list); + return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 512 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,44 +42943,66 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + if (node.expression.kind === 96) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall; + if (node.transformFlags & 524288) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 96) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { - ts.Debug.assert((node.transformFlags & 262144) !== 0); + ts.Debug.assert((node.transformFlags & 524288) !== 0); var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { var numElements = elements.length; - var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); })); if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 + return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 ? ts.createArraySlice(segments[0]) : segments[0]; } return ts.createArrayConcat(segments.shift(), segments); } - function partitionSpreadElement(node) { - return ts.isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; + function partitionSpread(node) { + return ts.isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; } - function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.map(chunk, visitExpressionOfSpreadElement); + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); } - function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, undefined, hasTrailingComma), visitor, ts.isExpression), undefined, multiLine); } - function visitExpressionOfSpreadElement(node) { + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + function visitExpressionOfSpread(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } function visitTemplateLiteral(node) { @@ -38640,7 +43037,7 @@ var ts; } function getRawLiteral(node) { var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - var isLast = node.kind === 11 || node.kind === 14; + var isLast = node.kind === 12 || node.kind === 15; text = text.substring(1, text.length - (isLast ? 1 : 2)); text = text.replace(/\r\n?/g, "\n"); return ts.createLiteral(text, node); @@ -38674,56 +43071,44 @@ var ts; } } } - function visitSuperKeyword(node) { + function visitSuperKeyword() { return enclosingNonAsyncFunctionBody && ts.isClassElement(enclosingNonAsyncFunctionBody) && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32) - && currentParent.kind !== 174 + && currentParent.kind !== 179 ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") : ts.createIdentifier("_super"); } - function visitSourceFileNode(node) { - var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; - var statements = []; - startLexicalEnvironment(); - ts.addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); - ts.addRange(statements, endLexicalEnvironment()); - var clone = ts.getMutableClone(node); - clone.statements = ts.createNodeArray(statements, node.statements); - return clone; - } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; - context.enableSubstitution(69); + context.enableSubstitution(70); } } function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(97); - context.enableEmitNotification(148); - context.enableEmitNotification(147); - context.enableEmitNotification(149); + context.enableSubstitution(98); context.enableEmitNotification(150); - context.enableEmitNotification(180); - context.enableEmitNotification(179); - context.enableEmitNotification(220); + context.enableEmitNotification(149); + context.enableEmitNotification(151); + context.enableEmitNotification(152); + context.enableEmitNotification(185); + context.enableEmitNotification(184); + context.enableEmitNotification(225); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38743,10 +43128,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 169: - case 221: - case 224: - case 218: + case 174: + case 226: + case 229: + case 223: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -38754,9 +43139,9 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - case 97: + case 98: return substituteThisKeyword(node); } return node; @@ -38773,64 +43158,56 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 8) { return ts.createIdentifier("_this", node); } return node; } - function getLocalName(node, allowComments, allowSourceMaps) { - return getDeclarationName(node, allowComments, allowSourceMaps, 262144); - } - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536; - } - if (!allowComments) { - emitFlags |= 49152; - } - if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); - } - return name_35; - } - return ts.getGeneratedNameForNode(node); - } function getClassMemberPrefix(node, member) { - var expression = getLocalName(node); + var expression = ts.getLocalName(node); return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { return false; } - var parameter = ts.singleOrUndefined(constructor.parameters); - if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + if (ts.some(constructor.parameters)) { return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 96) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196) { return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression === parameter.name; + return ts.isIdentifier(expression) && expression.text === "arguments"; } } - ts.transformES6 = transformES6; + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), undefined, [ + name, + ts.createIdentifier("_super") + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -38842,7 +43219,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,12 +43253,15 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { - if (node.transformFlags & 1024) { - currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); - currentSourceFile = undefined; + if (ts.isDeclarationFile(node) + || (node.transformFlags & 512) === 0) { + return node; } - return node; + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } function visitor(node) { var transformFlags = node.transformFlags; @@ -38891,10 +43271,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 512) { + else if (transformFlags & 256) { return visitGenerator(node); } - else if (transformFlags & 1024) { + else if (transformFlags & 512) { return ts.visitEachChild(node, visitor, context); } else { @@ -38903,13 +43283,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 204: + case 209: return visitDoStatement(node); - case 205: + case 210: return visitWhileStatement(node); - case 213: + case 218: return visitSwitchStatement(node); - case 214: + case 219: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -38917,30 +43297,30 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); - case 149: - case 150: + case 151: + case 152: return visitAccessorDeclaration(node); - case 200: + case 205: return visitVariableStatement(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 210: - return visitBreakStatement(node); - case 209: - return visitContinueStatement(node); case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 215: + return visitBreakStatement(node); + case 214: + return visitContinueStatement(node); + case 216: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 | 8388608)) { + else if (node.transformFlags & (512 | 33554432)) { return ts.visitEachChild(node, visitor, context); } else { @@ -38950,21 +43330,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 187: + case 192: return visitBinaryExpression(node); - case 188: + case 193: return visitConditionalExpression(node); - case 190: + case 195: return visitYieldExpression(node); - case 170: - return visitArrayLiteralExpression(node); - case 171: - return visitObjectLiteralExpression(node); - case 173: - return visitElementAccessExpression(node); - case 174: - return visitCallExpression(node); case 175: + return visitArrayLiteralExpression(node); + case 176: + return visitObjectLiteralExpression(node); + case 178: + return visitElementAccessExpression(node); + case 179: + return visitCallExpression(node); + case 180: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -38972,9 +43352,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 220: + case 225: return visitFunctionDeclaration(node); - case 179: + case 184: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -38982,8 +43362,8 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -39003,8 +43383,8 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { - node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); + if (node.asteriskToken && ts.getEmitFlags(node) & 131072) { + node = ts.setOriginalNode(ts.createFunctionExpression(undefined, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -39034,6 +43414,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +43427,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39053,7 +43435,7 @@ var ts; operationArguments = undefined; operationLocations = undefined; state = ts.createTempVariable(undefined); - startLexicalEnvironment(); + resumeLexicalEnvironment(); var statementOffset = ts.addPrologueDirectives(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); @@ -39064,6 +43446,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39074,12 +43457,12 @@ var ts; return ts.createBlock(statements, body, body.multiLine); } function visitVariableStatement(node) { - if (node.transformFlags & 4194304) { + if (node.transformFlags & 16777216) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 524288) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39104,23 +43487,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 57 - && kind <= 68; + return kind >= 58 + && kind <= 69; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 57: return 35; case 58: return 36; case 59: return 37; case 60: return 38; case 61: return 39; case 62: return 40; - case 63: return 43; + case 63: return 41; case 64: return 44; case 65: return 45; case 66: return 46; case 67: return 47; case 68: return 48; + case 69: return 49; } } function visitRightAssociativeBinaryExpression(node) { @@ -39128,10 +43511,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 172: + case 177: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 173: + case 178: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -39140,7 +43523,7 @@ var ts; } var operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return ts.createBinary(target, 56, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + return ts.createBinary(target, 57, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); } else { return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); @@ -39153,13 +43536,13 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 24) { + else if (node.operatorToken.kind === 25) { return visitCommaExpression(node); } - var clone_6 = ts.getMutableClone(node); - clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_6; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -39167,7 +43550,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); - if (node.operatorToken.kind === 51) { + if (node.operatorToken.kind === 52) { emitBreakWhenFalse(resultLabel, resultLocal, node.left); } else { @@ -39183,7 +43566,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 25) { visit(node.left); visit(node.right); } @@ -39224,26 +43607,30 @@ var ts; return createGeneratorResume(); } function visitArrayLiteralExpression(node) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, undefined, undefined, node.multiLine); } - function visitElements(elements, multiLine) { + function visitElements(elements, leadingElement, location, multiLine) { var numInitialElements = countInitialNodesWithoutYield(elements); var temp = declareLocal(); var hasAssignedTemp = false; if (numInitialElements > 0) { - emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; hasAssignedTemp = true; } var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine); function reduceElement(expressions, element) { if (containsYield(element) && expressions.length > 0) { emitAssignment(temp, hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions)); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, undefined, multiLine)); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } expressions.push(ts.visitNode(element, visitor, ts.isExpression)); @@ -39277,24 +43664,24 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_7 = ts.getMutableClone(node); - clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_7; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, false), node), node); + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, false)), undefined, [], node), node); + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, ts.createVoidZero())), undefined, [], node), node); } return ts.visitEachChild(node, visitor, context); } @@ -39323,35 +43710,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 199: - return transformAndEmitBlock(node); - case 202: - return transformAndEmitExpressionStatement(node); - case 203: - return transformAndEmitIfStatement(node); case 204: - return transformAndEmitDoStatement(node); - case 205: - return transformAndEmitWhileStatement(node); - case 206: - return transformAndEmitForStatement(node); + return transformAndEmitBlock(node); case 207: - return transformAndEmitForInStatement(node); + return transformAndEmitExpressionStatement(node); + case 208: + return transformAndEmitIfStatement(node); case 209: - return transformAndEmitContinueStatement(node); + return transformAndEmitDoStatement(node); case 210: - return transformAndEmitBreakStatement(node); + return transformAndEmitWhileStatement(node); case 211: - return transformAndEmitReturnStatement(node); + return transformAndEmitForStatement(node); case 212: - return transformAndEmitWithStatement(node); - case 213: - return transformAndEmitSwitchStatement(node); + return transformAndEmitForInStatement(node); case 214: - return transformAndEmitLabeledStatement(node); + return transformAndEmitContinueStatement(node); case 215: - return transformAndEmitThrowStatement(node); + return transformAndEmitBreakStatement(node); case 216: + return transformAndEmitReturnStatement(node); + case 217: + return transformAndEmitWithStatement(node); + case 218: + return transformAndEmitSwitchStatement(node); + case 219: + return transformAndEmitLabeledStatement(node); + case 220: + return transformAndEmitThrowStatement(node); + case 221: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement, true)); @@ -39635,7 +44022,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 250 && defaultClauseIndex === -1) { + if (clause.kind === 254 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -39645,7 +44032,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 249) { + if (clause.kind === 253) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -39736,7 +44123,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 4194304) !== 0; + return node && (node.transformFlags & 16777216) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -39747,9 +44134,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,12 +44153,12 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); - return clone_8; + var name_39 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_39) { + var clone_6 = ts.getMutableClone(name_39); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -39877,7 +44264,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = ts.createMap(); - context.enableSubstitution(69); + context.enableSubstitution(70); } renamedCatchVariables[text] = true; renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -40067,7 +44454,7 @@ var ts; if (labelExpressions === undefined) { labelExpressions = []; } - var expression = ts.createSynthesizedNode(8); + var expression = ts.createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -40076,7 +44463,7 @@ var ts; } return expression; } - return ts.createNode(193); + return ts.createOmittedExpression(); } function createInstruction(instruction) { var literal = ts.createLiteral(instruction); @@ -40162,10 +44549,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ - ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) - ]); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 262144)); } function buildStatements() { if (operations) { @@ -40428,9 +44812,64 @@ var ts; } } ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]); + } + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; var _a; })(ts || (ts = {})); var ts; +(function (ts) { + function transformES5(context) { + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(177); + context.enableSubstitution(257); + return transformSourceFile; + function transformSourceFile(node) { + return node; + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.createElementAccess(node.expression, literalName, node); + } + return node; + } + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + if (token >= 71 && token <= 106) { + return ts.createLiteral(name, name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +var ts; (function (ts) { function transformModule(context) { var transformModuleDelegates = ts.createMap((_a = {}, @@ -40439,7 +44878,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40449,47 +44888,43 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableSubstitution(254); - context.enableEmitNotification(256); + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableSubstitution(258); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var bindingNameExportSpecifiersMap; - var bindingNameExportSpecifiersForFileMap = ts.createMap(); - var hasExportStarsToExportValues; + var currentModuleInfo; + var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; - var updated = transformModule_1(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; } - return node; - var _a; + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + return ts.aggregateTransformFlags(updated); } function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); addExportEqualsIfNeeded(statements, false); - var updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(updated, exportStarHelper); } return updated; } @@ -40499,83 +44934,111 @@ var ts; return transformAsynchronousModule(node, define, moduleName, true); } function transformUMDModule(node) { - var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + var define = ts.createRawExpression(umdHelper); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return updateSourceFile(node, [ + return ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter("require"), - ts.createParameter("exports") + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) - ]); + ], node.statements)); + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + var aliasedModuleNames = []; + var unaliasedModuleNames = []; + var importAliasNames = []; + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + ts.setEmitFlags(importAliasName, 4); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(undefined, undefined, undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(body, exportStarHelper); } return body; } function addExportEqualsIfNeeded(statements, emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (currentModuleInfo.exportEquals) { if (emitAsReturn) { - var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + var statement = ts.createReturn(currentModuleInfo.exportEquals.expression, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); statements.push(statement); } else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression), currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); statements.push(statement); } } } - function visitor(node) { + function sourceElementVisitor(node) { switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return visitExportDeclaration(node); + case 240: return visitExportAssignment(node); - case 200: + case 205: return visitVariableStatement(node); - case 220: + case 225: return visitFunctionDeclaration(node); - case 221: + case 226: return visitClassDeclaration(node); - case 202: - return visitExpressionStatement(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); default: return node; } } function visitImportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var statements = []; + var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { - statements.push(ts.createStatement(createRequireCall(node), node)); + return ts.createStatement(createRequireCall(node), node); } else { var variables = []; @@ -40588,43 +45051,60 @@ var ts; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } } - statements.push(ts.createVariableStatement(undefined, ts.createConstDeclarationList(variables), node)); + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, undefined, languageVersion >= 2 ? 2 : 0), node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node), node) - ]))); + ], undefined, languageVersion >= 2 ? 2 : 0))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); } - addExportImportAssignments(statements, node); return ts.singleOrMany(statements); } - function visitImportEqualsDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); } - setNodeEmitFlags(node.name, 128); - var statements = []; + return ts.createCall(ts.createIdentifier("require"), undefined, args); + } + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), node)); + statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)), node)); } else { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) ], undefined, languageVersion >= 2 ? 2 : 0), node)); } } else { if (ts.hasModifier(node, 1)) { - statements.push(ts.createStatement(createExportAssignment(node.name, node.name), node)); + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)), node)); } } - addExportImportAssignments(statements, node); - return statements; + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); } function visitExportDeclaration(node) { - if (!ts.contains(externalImports, node)) { + if (!node.moduleSpecifier) { return undefined; } var generatedName = ts.getGeneratedNameForNode(node); @@ -40637,14 +45117,12 @@ var ts; } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), specifier)); - } + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue), specifier)); } return ts.singleOrMany(statements); } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + else { return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) @@ -40653,207 +45131,262 @@ var ts; } } function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - var statements = []; - addExportDefault(statements, node.expression, node); - return statements; - } + if (node.isExportEquals) { + return undefined; } - return undefined; - } - function addExportDefault(statements, expression, location) { - tryAddExportDefaultCompat(statements); - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); - } - function tryAddExportDefaultCompat(statements) { - var original = ts.getOriginalNode(currentSourceFile); - ts.Debug.assert(original.kind === 256); - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === 0) { - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); - } - else { - statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) - ]) - ]))); - } - } - } - function addExportImportAssignments(statements, node) { - if (ts.isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); } else { - var names = ts.reduceEachChild(node, collectExportMembers, []); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); - } - } - } - function collectExportMembers(names, node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); - } - } - return ts.reduceEachChild(node, collectExportMembers, names); - } - function addExportMemberAssignments(statements, name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), specifier.name))); - } - } - } - function addExportMemberAssignment(statements, node) { - if (ts.hasModifier(node, 512)) { - addExportDefault(statements, getDeclarationName(node), node); - } - else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); - } - } - function visitVariableStatement(node) { - var originalKind = ts.getOriginalNode(node).kind; - if (originalKind === 225 || - originalKind === 224 || - originalKind === 221) { - if (!ts.hasModifier(node, 1)) { - return node; - } - return ts.setOriginalNode(ts.createVariableStatement(undefined, node.declarationList), node); - } - var resultStatements = []; - if (ts.hasModifier(node, 1)) { - var variables = ts.getInitializedVariables(node.declarationList); - if (variables.length > 0) { - var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - return resultStatements; - } - function addExportMemberAssignmentsForBindingName(resultStatements, name) { - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - var sourceFileId = ts.getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - function transformInitializedVariable(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); - } - else { - return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); } + return ts.singleOrMany(statements); } function visitFunctionDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); + var statements; if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name, undefined, node.parameters, undefined, node.body, node), node)); - addExportMemberAssignment(statements, node); + statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body, node), node)); } else { - statements.push(node); + statements = ts.append(statements, node); } - if (node.name) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return ts.singleOrMany(statements); } function visitClassDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); + var statements; if (ts.hasModifier(node, 1)) { - statements.push(ts.setOriginalNode(ts.createClassDeclaration(undefined, undefined, name, undefined, node.heritageClauses, node.members, node), node)); - addExportMemberAssignment(statements, node); + statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members, node), node)); } else { - statements.push(node); + statements = ts.append(statements, node); } - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return ts.singleOrMany(statements); } - function visitExpressionStatement(node) { - var original = ts.getOriginalNode(node); - var origKind = original.kind; - if (origKind === 224 || origKind === 225) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === 221) { - var classDecl = original; - if (classDecl.name) { - var statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1)) { + var modifiers = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + } + else { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name, node.name), node.initializer); + } + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } return node; } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { - var statements = [node]; - if (ts.hasModifier(original, 1) && - original.kind === 224 && - ts.isFirstDeclarationOfKind(original, 224)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } } - addExportMemberAssignments(statements, original.name); return statements; } - function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { - var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); - statements.push(transformedStatement); + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; } - function onEmitNode(node, emit) { - if (node.kind === 256) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - bindingNameExportSpecifiersMap = undefined; + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, exportSpecifier.name); + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, location, allowComments) { + if (exportName.text === "default") { + var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 0) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + function createExportStatement(name, value, location, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value, location) { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location); + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = ts.createMap(); + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40875,870 +45408,169 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 69: + case 70: return substituteExpressionIdentifier(node); - case 187: + case 192: return substituteBinaryExpression(node); - case 186: - case 185: + case 191: + case 190: return substituteUnaryExpression(node); } return node; } function substituteExpressionIdentifier(node) { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 261) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name_40 = importDeclaration.propertyName || importDeclaration.name; + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); + } + } + } + return node; } function substituteBinaryExpression(node) { - var left = node.left; - if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, node); } - return nestedExportAssignment; + return expression; } } return node; } function substituteUnaryExpression(node) { - var operator = node.operator; - var operand = node.operand; - if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); - var transformedUnaryExpression = void 0; - if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 ? 58 : 59), ts.createLiteral(1), node) + : node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); } - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; + return expression; } } return node; } - function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); - if ((emitFlags & 262144) === 0) { - var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); - if (container) { - if (container.kind === 256) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), node); - } + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; } } - return undefined; - } - function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (ts.isImportClause(declaration)) { - if (languageVersion >= 1) { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), node); - } - else { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), node); - } - } - else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); - } - else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); - } - } - } - } - return undefined; - } - function getModuleMemberName(name) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), name, name); - } - function createRequireCall(importNode) { - var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var args = []; - if (ts.isDefined(moduleName)) { - args.push(moduleName); - } - return ts.createCall(ts.createIdentifier("require"), undefined, args); - } - function createExportStatement(name, value, location) { - var statement = ts.createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - return statement; - } - function createExportAssignment(name, value) { - return ts.createAssignment(name.originalKeywordKind === 77 && languageVersion === 0 - ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) - : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); - } - function collectAsynchronousDependencies(node, includeNonAmdDependencies) { - var aliasedModuleNames = []; - var unaliasedModuleNames = []; - var importAliasNames = []; - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - } - } - for (var _b = 0, externalImports_1 = externalImports; _b < externalImports_1.length; _b++) { - var importNode = externalImports_1[_b]; - var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function updateSourceFile(node, statements) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - return updated; } var _a; } ts.transformModule = transformModule; + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })"; })(ts || (ts = {})); var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(69); - context.enableSubstitution(187); - context.enableSubstitution(185); - context.enableSubstitution(186); - context.enableEmitNotification(256); - var exportFunctionForFileMap = []; + context.enableSubstitution(70); + context.enableSubstitution(192); + context.enableSubstitution(190); + context.enableSubstitution(191); + context.enableEmitNotification(261); + var moduleInfoMap = ts.createMap(); + var deferredExports = ts.createMap(); + var exportFunctionsMap = ts.createMap(); + var noSubstitutionMap = ts.createMap(); var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var exportFunctionForFile; - var contextObjectForFile; - var exportedLocalNames; - var exportedFunctionDeclarations; + var moduleInfo; + var exportFunction; + var contextObject; + var hoistedStatements; var enclosingBlockScopedContainer; - var currentParent; - var currentNode; + var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; - var updated = transformSystemModuleWorker(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - return node; - } - function transformSystemModuleWorker(node) { - ts.Debug.assert(!exportFunctionForFile); - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - exportFunctionForFile = ts.createUniqueName("exports"); - contextObjectForFile = ts.createUniqueName("context"); - exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; - var dependencyGroups = collectDependencyGroups(externalImports); - var statements = []; - addSystemModuleBody(statements, node, dependencyGroups); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); - var body = ts.createFunctionExpression(undefined, undefined, undefined, [ - ts.createParameter(exportFunctionForFile), - ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName - ? [moduleName, dependencies, body] - : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); - var _a; - } - function addSystemModuleBody(statements, node, dependencyGroups) { - startLexicalEnvironment(); - var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, visitSourceElement); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) - ]))); - var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); - ts.addRange(statements, endLexicalEnvironment()); - ts.addRange(statements, exportedFunctionDeclarations); - var exportStarFunction = addExportStarIfNeeded(statements); - statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ - ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) - ]), true))); - } - function addExportStarIfNeeded(statements) { - if (!hasExportStarsToExportValues) { - return; - } - if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { - var hasExportDeclarationWithExportClause = false; - for (var _i = 0, externalImports_2 = externalImports; _i < externalImports_2.length; _i++) { - var externalImport = externalImports_2[_i]; - if (externalImport.kind === 236 && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - return addExportStarFunction(statements, undefined); - } - } - var exportedNames = []; - if (exportedLocalNames) { - for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { - var exportedLocalName = exportedLocalNames_1[_a]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); - } - } - for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { - var externalImport = externalImports_3[_b]; - if (externalImport.kind !== 236) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - continue; - } - for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { - var element = _d[_c]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); - } - } - var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) - ]))); - return addExportStarFunction(statements, exportedNamesStorageRef); - } - function generateSetters(exportStarFunction, dependencyGroups) { - var setters = []; - for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group = dependencyGroups_1[_i]; - var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); - var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); - var statements = []; - for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { - var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); - switch (entry.kind) { - case 230: - if (!entry.importClause) { - break; - } - case 229: - ts.Debug.assert(importVariableName !== undefined); - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); - break; - case 236: - ts.Debug.assert(importVariableName !== undefined); - if (entry.exportClause) { - var properties = []; - for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { - var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); - } - statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); - } - else { - statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); - } - break; - } - } - setters.push(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, ts.createBlock(statements, undefined, true))); - } - return ts.createArrayLiteral(setters, undefined, true); - } - function visitSourceElement(node) { - switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 236: - return visitExportDeclaration(node); - case 235: - return visitExportAssignment(node); - default: - return visitNestedNode(node); - } - } - function visitNestedNode(node) { - var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; - } - var result = visitNestedNodeWorker(node); - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return result; - } - function visitNestedNodeWorker(node) { - switch (node.kind) { - case 200: - return visitVariableStatement(node); - case 220: - return visitFunctionDeclaration(node); - case 221: - return visitClassDeclaration(node); - case 206: - return visitForStatement(node); - case 207: - return visitForInStatement(node); - case 208: - return visitForOfStatement(node); - case 204: - return visitDoStatement(node); - case 205: - return visitWhileStatement(node); - case 214: - return visitLabeledStatement(node); - case 212: - return visitWithStatement(node); - case 213: - return visitSwitchStatement(node); - case 227: - return visitCaseBlock(node); - case 249: - return visitCaseClause(node); - case 250: - return visitDefaultClause(node); - case 216: - return visitTryStatement(node); - case 252: - return visitCatchClause(node); - case 199: - return visitBlock(node); - case 202: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (node.importClause && ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitImportEqualsDeclaration(node) { - if (ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitExportDeclaration(node) { - if (!node.moduleSpecifier) { - var statements = []; - ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - return undefined; - } - function visitExportSpecifier(specifier) { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement(specifier.name, specifier.propertyName || specifier.name); - } - return undefined; - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement(ts.createLiteral("default"), node.expression); - } - } - return undefined; - } - function visitVariableStatement(node) { - var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3) == 0) || - enclosingBlockScopedContainer.kind === 256; - if (!shouldHoist) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { return node; } - var isExported = ts.hasModifier(node, 1); - var expressions = []; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports"); + contextObject = ts.createUniqueName("context"); + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, exportFunction), + ts.createParameter(undefined, undefined, undefined, contextObject) + ], undefined, moduleBodyBlock); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ], node.statements)), 1024); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } - if (expressions.length) { - return ts.createStatement(ts.inlineExpressions(expressions), node); - } - return undefined; - } - function transformVariable(node, isExported) { - hoistBindingElement(node, isExported); - if (!node.initializer) { - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - return ts.createAssignment(name, node.initializer); - } - else { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); - recordExportedFunctionDeclaration(node); - if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); - } - ts.setOriginalNode(newNode, node); - node = newNode; - } - hoistFunctionDeclaration(node); - return undefined; - } - function visitExpressionStatement(node) { - var originalNode = ts.getOriginalNode(node); - if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); - if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); - } - return [ - node, - createExportStatement(name_41, name_41) - ]; - } - return node; - } - function visitClassDeclaration(node) { - var name = getDeclarationName(node); - hoistVariableDeclaration(name); - var statements = []; - statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, node.heritageClauses, node.members, node)), node)); - if (ts.hasModifier(node, 1)) { - if (!ts.hasModifier(node, 512)) { - recordExportName(name); - } - statements.push(createDeclarationExport(node)); - } - return statements; - } - function shouldHoistLoopInitializer(node) { - return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3) === 0; - } - function visitForStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var expressions = []; - for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, false); - if (visited) { - expressions.push(visited); - } - } - ; - return ts.createFor(expressions.length - ? ts.inlineExpressions(expressions) - : ts.createSynthesizedNode(193), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), node); - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function transformForBinding(node) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, false); - var name = firstDeclaration.name; - return ts.isIdentifier(name) - ? name - : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); - } - function visitForInStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitForOfStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - function visitDoStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWhileStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitLabeledStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitWithStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - function visitSwitchStatement(node) { - var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); - if (caseBlock !== node.caseBlock) { - var updated = ts.getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; - } - function visitCaseBlock(node) { - var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); - if (clauses !== node.clauses) { - var updated = ts.getMutableClone(node); - updated.clauses = clauses; - return updated; - } - return node; - } - function visitCaseClause(node) { - var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); - if (statements !== node.statements) { - var updated = ts.getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; - } - function visitDefaultClause(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitTryStatement(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function visitCatchClause(node) { - var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); - if (block !== node.block) { - var updated = ts.getMutableClone(node); - updated.block = block; - return updated; - } - return node; - } - function visitBlock(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - function onEmitNode(node, emit) { - if (node.kind === 256) { - exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - exportFunctionForFile = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69: - return substituteExpressionIdentifier(node); - case 187: - return substituteBinaryExpression(node); - case 185: - case 186: - return substituteUnaryExpression(node); - } - return node; - } - function substituteExpressionIdentifier(node) { - var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - var importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; - } - } - return node; - } - function substituteBinaryExpression(node) { - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); - } - return node; - } - function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); - var left = node.left; - switch (left.kind) { - case 69: - var exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); - } - break; - case 171: - case 170: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - return node; - } - function isExportedBinding(name) { - var container = resolver.getReferencedExportContainer(name); - return container && container.kind === 256; - } - function hasExportedReferenceInDestructuringPattern(node) { - switch (node.kind) { - case 69: - return isExportedBinding(node); - case 171: - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var property = _a[_i]; - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - break; - case 170: - for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - break; - } - return false; - } - function hasExportedReferenceInObjectDestructuringElement(node) { - if (ts.isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (ts.isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - function hasExportedReferenceInArrayDestructuringElement(node) { - if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - function hasExportedReferenceInDestructuringElement(node) { - if (ts.isBinaryExpression(node)) { - var left = node.left; - return node.operatorToken.kind === 56 - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (ts.isIdentifier(node)) { - return isExportedBinding(node); - } - else if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - function isDestructuringPattern(node) { - var kind = node.kind; - return kind === 69 - || kind === 171 - || kind === 170; - } - function substituteDestructuring(node) { - return ts.flattenDestructuringAssignment(context, node, true, hoistVariableDeclaration); - } - function substituteUnaryExpression(node) { - var operand = node.operand; - var operator = node.operator; - var substitute = ts.isIdentifier(operand) && - (node.kind === 186 || - (node.kind === 185 && (operator === 41 || operator === 42))); - if (substitute) { - var exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); - var call = createExportExpression(operand, expr); - if (node.kind === 185) { - return call; - } - else { - return operator === 41 - ? ts.createSubtract(call, ts.createLiteral(1)) - : ts.createAdd(call, ts.createLiteral(1)); - } - } - } - return node; - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function addExportStarFunction(statements, localNames) { - var exportStarFunction = ts.createUniqueName("exportStar"); - var m = ts.createIdentifier("m"); - var n = ts.createIdentifier("n"); - var exports = ts.createIdentifier("exports"); - var condition = ts.createStrictInequality(n, ts.createLiteral("default")); - if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); - } - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(m)], undefined, ts.createBlock([ - ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) - ])), - ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, undefined) - ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) - ])), - ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) - ], undefined, true))); - return exportStarFunction; - } - function createExportExpression(name, value) { - var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; - return ts.createCall(exportFunctionForFile, undefined, [exportName, value]); - } - function createExportStatement(name, value) { - return ts.createStatement(createExportExpression(name, value)); - } - function createDeclarationExport(node) { - var declarationName = getDeclarationName(node); - var exportName = ts.hasModifier(node, 512) ? ts.createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - function createImportBinding(importDeclaration) { - var importAlias; - var name; - if (ts.isImportClause(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); - name = ts.createIdentifier("default"); - } - else if (ts.isImportSpecifier(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - if (name.originalKeywordKind && languageVersion === 0) { - return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); - } - else { - return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); } function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); @@ -41750,7 +45582,6 @@ var ts; if (ts.hasProperty(groupIndices, text)) { var groupIndex = groupIndices[text]; dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; } else { groupIndices[text] = dependencyGroups.length; @@ -41762,171 +45593,808 @@ var ts; } return dependencyGroups; } - function getNameOfDependencyGroup(dependencyGroup) { - return dependencyGroup.name; + function createSystemModuleBody(node, dependencyGroups) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true); + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + ts.addRange(statements, hoistedStatements); + ts.addRange(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, undefined, true))) + ]), true))); + return ts.createBlock(statements, undefined, true); } - function recordExportName(name) { - if (!exportedLocalNames) { - exportedLocalNames = []; - } - exportedLocalNames.push(name); - } - function recordExportedFunctionDeclaration(node) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; - } - exportedFunctionDeclarations.push(createDeclarationExport(node)); - } - function hoistBindingElement(node, isExported) { - if (ts.isOmittedExpression(node)) { + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { return; } - var name = node.name; - if (ts.isIdentifier(name)) { - hoistVariableDeclaration(ts.getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); + if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) { + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 241 && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + var exportStarFunction_1 = createExportStarFunction(undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; } } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.text === "default") { + continue; + } + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true))); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 241) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + continue; + } + for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, undefined, true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), undefined, [n]))); + } + return ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(undefined, undefined, undefined, m)], undefined, ts.createBlock([ + ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1) + ])), + ts.createStatement(ts.createCall(exportFunction, undefined, [exports])) + ], undefined, true)); + } + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 235: + if (!entry.importClause) { + break; + } + case 234: + ts.Debug.assert(importVariableName !== undefined); + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 241: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, undefined, true)]))); + } + else { + statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, ts.createBlock(statements, undefined, true))); + } + return ts.createArrayLiteral(setters, undefined, true); + } + function sourceElementVisitor(node) { + switch (node.kind) { + case 235: + return visitImportDeclaration(node); + case 234: + return visitImportEqualsDeclaration(node); + case 241: + return undefined; + case 240: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); } } - function hoistExportedBindingElement(node) { - hoistBindingElement(node, true); + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); } - function hoistNonExportedBindingElement(node) { - hoistBindingElement(node, false); + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); } - function updateSourceFile(node, statements, nodeEmitFlags) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); - return updated; + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, true); + } + } + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + function visitClassDeclaration(node) { + var statements; + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement), node)), node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), node)); + } + if (isMarkedDeclaration) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, false); + } + return ts.singleOrMany(statements); + } + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + function shouldHoistVariableDeclarationList(node) { + return (ts.getEmitFlags(node) & 1048576) === 0 + && (enclosingBlockScopedContainer.kind === 261 + || (ts.getOriginalNode(node).flags & 3) === 0); + } + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + } + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, true); + } + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, false); + } + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location))) + : preventSubstitution(ts.createAssignment(name, value, location)); + } + function visitMergeDeclarationMarker(node) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152) !== 0; + } + function visitEndOfDeclarationMarker(node) { + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = decl.name.text; + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1)) { + var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = exportName.text; + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + function createExportStatement(name, value, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536); + } + return statement; + } + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + return ts.createCall(exportFunction, undefined, [exportName, value]); + } + function nestedElementVisitor(node) { + switch (node.kind) { + case 205: + return visitVariableStatement(node); + case 225: + return visitFunctionDeclaration(node); + case 226: + return visitClassDeclaration(node); + case 211: + return visitForStatement(node); + case 212: + return visitForInStatement(node); + case 213: + return visitForOfStatement(node); + case 209: + return visitDoStatement(node); + case 210: + return visitWhileStatement(node); + case 219: + return visitLabeledStatement(node); + case 217: + return visitWithStatement(node); + case 218: + return visitSwitchStatement(node); + case 232: + return visitCaseBlock(node); + case 253: + return visitCaseClause(node); + case 254: + return visitDefaultClause(node); + case 221: + return visitTryStatement(node); + case 256: + return visitCatchClause(node); + case 204: + return visitBlock(node); + case 295: + return visitMergeDeclarationMarker(node); + case 296: + return visitEndOfDeclarationMarker(node); + default: + return destructuringVisitor(node); + } + } + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + } + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, false, ts.liftToBlock)); + } + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function destructuringVisitor(node) { + if (node.transformFlags & 1024 + && node.kind === 192) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & 2048) { + return ts.visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + } + return ts.visitEachChild(node, destructuringVisitor, context); + } + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 261; + } + else { + return false; + } + } + function modifierVisitor(node) { + switch (node.kind) { + case 83: + case 78: + return undefined; + } + return node; + } + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === 1) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 70: + return substituteExpressionIdentifier(node); + case 192: + return substituteBinaryExpression(node); + case 190: + case 191: + return substituteUnaryExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), node); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + var expression = node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + function substituteUnaryExpression(node) { + if ((node.operator === 42 || node.operator === 43) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 + ? ts.createPrefix(node.operator, node.operand, node) + : node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 191) { + expression = node.operator === 42 + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; + } + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, false); + if (exportContainer && exportContainer.kind === 261) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); + } + } + return exportedNames; + } + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = ts.createMap(); + noSubstitution[ts.getNodeId(node)] = true; + return node; + } + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; } } ts.transformSystemModule = transformSystemModule; })(ts || (ts = {})); var ts; (function (ts) { - function transformES6Module(context) { + function transformES2015Module(context) { var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(261); + context.enableSubstitution(70); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return ts.visitEachChild(node, visitor, context); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements); + ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); + } } return node; } function visitor(node) { switch (node.kind) { - case 230: - return visitImportDeclaration(node); - case 229: - return visitImportEqualsDeclaration(node); - case 231: - return visitImportClause(node); - case 233: - case 232: - return visitNamedBindings(node); case 234: - return visitImportSpecifier(node); - case 235: + return undefined; + case 240: return visitExportAssignment(node); - case 236: - return visitExportDeclaration(node); - case 237: - return visitNamedExports(node); - case 238: - return visitExportSpecifier(node); } return node; } function visitExportAssignment(node) { - if (node.isExportEquals) { - return undefined; - } - var original = ts.getOriginalNode(node); - return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + return node.isExportEquals ? undefined : node; } - function visitExportDeclaration(node) { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + function onEmitNode(emitContext, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; + else { + previousOnEmitNode(emitContext, node, emitCallback); } - var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, true); - if (node.exportClause === newExportClause) { - return node; + } + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isIdentifier(node) && emitContext === 1) { + return substituteExpressionIdentifier(node); } - return newExportClause - ? ts.createExportDeclaration(undefined, undefined, newExportClause, node.moduleSpecifier) - : undefined; + return node; } - function visitNamedExports(node) { - var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? ts.createNamedExports(newExports) : undefined; - } - function visitExportSpecifier(node) { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - function visitImportEqualsDeclaration(node) { - return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - function visitImportDeclaration(node) { - if (node.importClause) { - var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return ts.createImportDeclaration(undefined, undefined, newImportClause, node.moduleSpecifier); + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); } } return node; } - function visitImportClause(node) { - var newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? ts.createImportClause(newDefaultImport, newNamedBindings) - : node; - } - function visitNamedBindings(node) { - if (node.kind === 232) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === node.elements) { - return node; - } - return ts.createNamedImports(newNamedImportElements); - } - } - function visitImportSpecifier(node) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } } - ts.transformES6Module = transformES6Module; + ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); var ts; (function (ts) { var moduleTransformerMap = ts.createMap((_a = {}, - _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.ES2015] = ts.transformES2015Module, _a[ts.ModuleKind.System] = ts.transformSystemModule, _a[ts.ModuleKind.AMD] = ts.transformModule, _a[ts.ModuleKind.CommonJS] = ts.transformModule, @@ -41939,79 +46407,65 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var transformers = []; transformers.push(ts.transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); if (jsx === 2) { transformers.push(ts.transformJsx); } - transformers.push(ts.transformES7); + if (languageVersion < 5) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3) { + transformers.push(ts.transformES2016); + } if (languageVersion < 2) { - transformers.push(ts.transformES6); + transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + if (languageVersion < 1) { + transformers.push(ts.transformES5); + } return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); + var enabledSyntaxKindFeatures = new Array(298); + var lexicalEnvironmentDisabled = false; + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; - var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; - var hoistedVariableDeclarations; - var hoistedFunctionDeclarations; - var lexicalEnvironmentDisabled; + var lexicalEnvironmentSuspended = false; + var emitHelpers; var context = { getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, - startLexicalEnvironment: startLexicalEnvironment, - endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + onSubstituteNode: function (_emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,112 +46477,86 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 4) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 2) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); var decl = ts.createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } function hoistFunctionDeclaration(func) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } function startLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + function suspendLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + function resumeLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } function endLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = hoistedFunctionDeclarations.slice(); + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); } - if (hoistedVariableDeclarations) { - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + if (lexicalEnvironmentVariableDeclarations) { + var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -42138,60 +46566,27 @@ var ts; } } lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + function requestEmitHelper(helper) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +46597,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42224,7 +46619,7 @@ var ts; var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; var noDeclare; var moduleElementDeclarationEmitInfo = []; @@ -42242,7 +46637,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42268,7 +46663,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 230); + ts.Debug.assert(aliasEmitInfo.node.kind === 235); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -42299,7 +46694,7 @@ var ts; reportedDeclarationError: reportedDeclarationError, moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput + referencesOutput: referencesOutput, }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); @@ -42324,6 +46719,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -42339,10 +46735,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 218) { + if (declaration.kind === 223) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 233 || declaration.kind === 234 || declaration.kind === 231) { + else if (declaration.kind === 238 || declaration.kind === 239 || declaration.kind === 236) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -42353,7 +46749,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 230) { + if (moduleElementEmitInfo.node.kind === 235) { moduleElementEmitInfo.isVisible = true; } else { @@ -42361,12 +46757,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 225) { + if (nodeToCheck.kind === 230) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -42427,7 +46823,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,20 +46835,20 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } function emitLines(nodes) { - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -42467,7 +46863,7 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); } @@ -42478,67 +46874,73 @@ var ts; } function emitType(type) { switch (type.kind) { - case 117: + case 118: + case 134: case 132: - case 130: - case 120: - case 133: - case 103: + case 121: case 135: - case 93: - case 127: - case 165: - case 166: + case 104: + case 137: + case 94: + case 129: + case 167: + case 171: return writeTextOfNode(currentText, type); - case 194: + case 199: return emitExpressionWithTypeArguments(type); - case 155: - return emitTypeReference(type); - case 158: - return emitTypeQuery(type); - case 160: - return emitArrayType(type); - case 161: - return emitTupleType(type); - case 162: - return emitUnionType(type); - case 163: - return emitIntersectionType(type); - case 164: - return emitParenType(type); - case 156: case 157: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 160: + return emitTypeQuery(type); + case 162: + return emitArrayType(type); + case 163: + return emitTupleType(type); + case 164: + return emitUnionType(type); + case 165: + return emitIntersectionType(type); + case 166: + return emitParenType(type); + case 168: + return emitTypeOperator(type); + case 169: + return emitIndexedAccessType(type); + case 170: + return emitMappedType(type); + case 158: case 159: + return emitSignatureDeclarationWithJsDocComments(type); + case 161: return emitTypeLiteral(type); - case 69: + case 70: return emitEntityName(type); - case 139: + case 141: return emitEntityName(type); - case 154: + case 156: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 69) { + if (entityName.kind === 70) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 139 ? entityName.left : entityName.expression; - var right = entityName.kind === 139 ? entityName.right : entityName.name; + var left = entityName.kind === 141 ? entityName.left : entityName.expression; + var right = entityName.kind === 141 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 229 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 234 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); + ts.Debug.assert(node.expression.kind === 70 || node.expression.kind === 177); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -42584,6 +46986,42 @@ var ts; emitType(type.type); write(")"); } + function emitTypeOperator(type) { + write(ts.tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + function emitIndexedAccessType(node) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + function emitMappedType(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } function emitTypeLiteral(type) { write("{"); if (type.members.length) { @@ -42612,14 +47050,14 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_41 = baseName + "_" + count; + if (!(name_41 in currentIdentifiers)) { + return name_41; } } } function emitExportAssignment(node) { - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -42632,7 +47070,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -42640,11 +47078,11 @@ var ts; } write(";"); writeLine(); - if (node.expression.kind === 69) { + if (node.expression.kind === 70) { var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic) { + function getDefaultExportAccessibilityDiagnostic() { return { diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -42658,10 +47096,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 229 || - (node.parent.kind === 256 && isCurrentFileExternalModule)) { + else if (node.kind === 234 || + (node.parent.kind === 261 && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 256) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -42670,7 +47108,7 @@ var ts; }); } else { - if (node.kind === 230) { + if (node.kind === 235) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -42688,30 +47126,30 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 220: - return writeFunctionDeclaration(node); - case 200: - return writeVariableStatement(node); - case 222: - return writeInterfaceDeclaration(node); - case 221: - return writeClassDeclaration(node); - case 223: - return writeTypeAliasDeclaration(node); - case 224: - return writeEnumDeclaration(node); case 225: - return writeModuleDeclaration(node); + return writeFunctionDeclaration(node); + case 205: + return writeVariableStatement(node); + case 227: + return writeInterfaceDeclaration(node); + case 226: + return writeClassDeclaration(node); + case 228: + return writeTypeAliasDeclaration(node); case 229: - return writeImportEqualsDeclaration(node); + return writeEnumDeclaration(node); case 230: + return writeModuleDeclaration(node); + case 234: + return writeImportEqualsDeclaration(node); + case 235: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 256) { + if (node.parent.kind === 261) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { write("export "); @@ -42719,7 +47157,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 222 && !noDeclare) { + else if (node.kind !== 227 && !noDeclare) { write("declare "); } } @@ -42759,7 +47197,7 @@ var ts; write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult) { + function getImportEntityNameVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -42769,7 +47207,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 232) { + if (namedBindings.kind === 237) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -42792,7 +47230,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 232) { + if (node.importClause.namedBindings.kind === 237) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -42809,13 +47247,13 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 225; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230; var moduleSpecifier; - if (parent.kind === 229) { + if (parent.kind === 234) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 225) { + else if (parent.kind === 230) { moduleSpecifier = parent.name; } else { @@ -42883,7 +47321,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 226) { + while (node.body && node.body.kind !== 231) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -42917,7 +47355,7 @@ var ts; write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + function getTypeAliasDeclarationVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -42953,7 +47391,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 149 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -42963,51 +47401,54 @@ var ts; writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - (node.parent.parent && node.parent.parent.kind === 159)) { - ts.Debug.assert(node.parent.kind === 147 || - node.parent.kind === 146 || - node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.kind === 151 || - node.parent.kind === 152); + if (node.parent.kind === 158 || + node.parent.kind === 159 || + (node.parent.parent && node.parent.parent.kind === 161)) { + ts.Debug.assert(node.parent.kind === 149 || + node.parent.kind === 148 || + node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.kind === 153 || + node.parent.kind === 154); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { + function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 221: + case 226: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 222: + case 227: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 152: + case 154: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151: + case 153: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 220: + case 225: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case 228: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; default: ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -43033,16 +47474,16 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 93) { + else if (!isImplementsList && node.expression.kind === 94) { write("null"); } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult) { + function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 221) { + if (node.parent.parent.kind === 226) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -43101,7 +47542,10 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); + var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, false); + } write(" {"); writeLine(); increaseIndent(); @@ -43122,17 +47566,17 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 218 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 223 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 147 || node.kind === 146 || + (node.kind === 144 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { + if ((node.kind === 147 || node.kind === 146) && node.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -43145,14 +47589,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 218) { + if (node.kind === 223) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 145 || node.kind === 144) { + else if (node.kind === 147 || node.kind === 146) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43160,7 +47604,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43186,7 +47630,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193) { + if (element.kind !== 198) { elements.push(element); } } @@ -43252,7 +47696,7 @@ var ts; accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 149 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 151 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -43265,7 +47709,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 149 + return accessor.kind === 151 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -43274,7 +47718,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 150) { + if (accessorWithTypeAnnotation.kind === 152) { if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -43320,17 +47764,17 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 220) { + if (node.kind === 225) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 147 || node.kind === 148) { + else if (node.kind === 149 || node.kind === 150) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 220) { + if (node.kind === 225) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 148) { + else if (node.kind === 150) { write("constructor"); } else { @@ -43350,15 +47794,15 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 153) { + if (node.kind === 155) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 || node.kind === 157) { + if (node.kind === 154 || node.kind === 159) { write("new "); } - else if (node.kind === 156) { + else if (node.kind === 158) { var currentOutput = writer.getText(); if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; @@ -43369,20 +47813,20 @@ var ts; write("("); } emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 153) { + if (node.kind === 155) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 156 || node.kind === 157; - if (isFunctionTypeOrConstructorType || node.parent.kind === 159) { + var isFunctionTypeOrConstructorType = node.kind === 158 || node.kind === 159; + if (isFunctionTypeOrConstructorType || node.parent.kind === 161) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 148 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 150 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -43396,23 +47840,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 152: + case 154: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151: + case 153: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 153: + case 155: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 147: - case 146: + case 149: + case 148: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43420,7 +47864,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 221) { + else if (node.parent.kind === 226) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43433,7 +47877,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 220: + case 225: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -43465,9 +47909,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 156 || - node.parent.kind === 157 || - node.parent.parent.kind === 159) { + if (node.parent.kind === 158 || + node.parent.kind === 159 || + node.parent.parent.kind === 161) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8)) { @@ -43483,22 +47927,26 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 148: + case 150: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 152: + case 154: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151: + case 153: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 147: - case 146: + case 155: + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 149: + case 148: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -43506,7 +47954,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221) { + else if (node.parent.parent.kind === 226) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43518,7 +47966,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 220: + case 225: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -43529,12 +47977,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 167) { + if (bindingPattern.kind === 172) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 168) { + else if (bindingPattern.kind === 173) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -43545,10 +47993,10 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 193) { + if (bindingElement.kind === 198) { write(" "); } - else if (bindingElement.kind === 169) { + else if (bindingElement.kind === 174) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -43558,7 +48006,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 69); + ts.Debug.assert(bindingElement.name.kind === 70); if (bindingElement.dotDotDotToken) { write("..."); } @@ -43570,57 +48018,57 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 220: case 225: - case 229: - case 222: - case 221: - case 223: - case 224: - return emitModuleElement(node, isModuleElementVisible(node)); - case 200: - return emitModuleElement(node, isVariableStatementVisible(node)); case 230: + case 234: + case 227: + case 226: + case 228: + case 229: + return emitModuleElement(node, isModuleElementVisible(node)); + case 205: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 235: return emitModuleElement(node, !node.importClause); - case 236: + case 241: return emitExportDeclaration(node); + case 150: + case 149: case 148: + return writeFunctionDeclaration(node); + case 154: + case 153: + case 155: + return emitSignatureDeclarationWithJsDocComments(node); + case 151: + case 152: + return emitAccessorDeclaration(node); case 147: case 146: - return writeFunctionDeclaration(node); - case 152: - case 151: - case 153: - return emitSignatureDeclarationWithJsDocComments(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 145: - case 144: return emitPropertyDeclaration(node); - case 255: + case 260: return emitEnumMemberDeclaration(node); - case 235: + case 240: return emitExportAssignment(node); - case 256: + case 261: return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); referencesOutput += "/// " + newLine; } return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) { if (isBundledEmit && !addBundledFileReference) { return; } @@ -43630,8 +48078,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +48105,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +48112,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, - getSourceMappingURL: getSourceMappingURL + getSourceMappingURL: getSourceMappingURL, }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +48183,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +48193,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +48223,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +48248,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 293 + && (emitFlags & 16) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 64) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 293 + && (emitFlags & 32) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 128) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,18 +48325,24 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, sources: sourceMapData.sourceMapSources, names: sourceMapData.sourceMapNames, mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent + sourcesContent: sourceMapData.sourceMapSourcesContent, }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +48352,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44069,31 +48400,33 @@ var ts; setSourceFile: setSourceFile, emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 32768) !== 0; + var isEmittedNode = node.kind !== 293; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -44105,18 +48438,20 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 219) { + if (node.kind === 224) { declarationListContainerEnd = end; } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitNodeWithComment"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,17 +48473,19 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; - var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44158,6 +48495,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -44177,7 +48517,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -44195,7 +48535,7 @@ var ts; function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -44218,7 +48558,7 @@ var ts; ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } } - function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -44256,16 +48596,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,20 +48641,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (_) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; - var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; - var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; - var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; - var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; - var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; - var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; - var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; - var superHelper = "\nconst _super = name => super[name];"; - var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -44332,11 +48653,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44346,21 +48667,20 @@ var ts; var currentSourceFile; var currentText; var currentFileIdentifiers; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; + var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +48689,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44392,11 +48716,12 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = ts.createMap(); + bundledHelpers = isBundledEmit ? ts.createMap() : undefined; isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; - emitEmitHelpers(sourceFile); + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; + emitHelpers(sourceFile, true); } } ts.forEach(sourceFiles, printSourceFile); @@ -44406,23 +48731,18 @@ var ts; write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); } if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); } if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); comments.reset(); writer.reset(); tempFlags = 0; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } function printSourceFile(node) { @@ -44431,360 +48751,369 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 261: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 70: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { - case 12: case 13: case 14: + case 15: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 74: - case 77: - case 82: - case 103: - case 110: + case 75: + case 78: + case 83: + case 104: case 111: case 112: case 113: - case 115: + case 114: + case 116: case 117: case 118: + case 119: case 120: + case 121: case 122: - case 130: + case 123: + case 124: + case 125: + case 127: case 128: + case 129: + case 130: + case 131: case 132: case 133: + case 134: + case 135: + case 136: case 137: - return writeTokenNode(node); + case 138: case 139: - return emitQualifiedName(node); case 140: - return emitComputedPropertyName(node); - case 141: - return emitTypeParameter(node); - case 142: - return emitParameter(node); - case 143: - return emitDecorator(node); - case 144: - return emitPropertySignature(node); - case 145: - return emitPropertyDeclaration(node); - case 146: - return emitMethodSignature(node); - case 147: - return emitMethodDeclaration(node); - case 148: - return emitConstructor(node); - case 149: - case 150: - return emitAccessorDeclaration(node); - case 151: - return emitCallSignature(node); - case 152: - return emitConstructSignature(node); - case 153: - return emitIndexSignature(node); - case 154: - return emitTypePredicate(node); - case 155: - return emitTypeReference(node); - case 156: - return emitFunctionType(node); - case 157: - return emitConstructorType(node); - case 158: - return emitTypeQuery(node); - case 159: - return emitTypeLiteral(node); - case 160: - return emitArrayType(node); - case 161: - return emitTupleType(node); - case 162: - return emitUnionType(node); - case 163: - return emitIntersectionType(node); - case 164: - return emitParenthesizedType(node); - case 194: - return emitExpressionWithTypeArguments(node); - case 165: - return emitThisType(node); - case 166: - return emitLiteralType(node); - case 167: - return emitObjectBindingPattern(node); - case 168: - return emitArrayBindingPattern(node); - case 169: - return emitBindingElement(node); - case 197: - return emitTemplateSpan(node); - case 198: - return emitSemicolonClassElement(node); - case 199: - return emitBlock(node); - case 200: - return emitVariableStatement(node); - case 201: - return emitEmptyStatement(node); - case 202: - return emitExpressionStatement(node); - case 203: - return emitIfStatement(node); - case 204: - return emitDoStatement(node); - case 205: - return emitWhileStatement(node); - case 206: - return emitForStatement(node); - case 207: - return emitForInStatement(node); - case 208: - return emitForOfStatement(node); - case 209: - return emitContinueStatement(node); - case 210: - return emitBreakStatement(node); - case 211: - return emitReturnStatement(node); - case 212: - return emitWithStatement(node); - case 213: - return emitSwitchStatement(node); - case 214: - return emitLabeledStatement(node); - case 215: - return emitThrowStatement(node); - case 216: - return emitTryStatement(node); - case 217: - return emitDebuggerStatement(node); - case 218: - return emitVariableDeclaration(node); - case 219: - return emitVariableDeclarationList(node); - case 220: - return emitFunctionDeclaration(node); - case 221: - return emitClassDeclaration(node); - case 222: - return emitInterfaceDeclaration(node); - case 223: - return emitTypeAliasDeclaration(node); - case 224: - return emitEnumDeclaration(node); - case 225: - return emitModuleDeclaration(node); - case 226: - return emitModuleBlock(node); - case 227: - return emitCaseBlock(node); - case 229: - return emitImportEqualsDeclaration(node); - case 230: - return emitImportDeclaration(node); - case 231: - return emitImportClause(node); - case 232: - return emitNamespaceImport(node); - case 233: - return emitNamedImports(node); - case 234: - return emitImportSpecifier(node); - case 235: - return emitExportAssignment(node); - case 236: - return emitExportDeclaration(node); - case 237: - return emitNamedExports(node); - case 238: - return emitExportSpecifier(node); - case 239: + writeTokenText(kind); return; + case 141: + return emitQualifiedName(node); + case 142: + return emitComputedPropertyName(node); + case 143: + return emitTypeParameter(node); + case 144: + return emitParameter(node); + case 145: + return emitDecorator(node); + case 146: + return emitPropertySignature(node); + case 147: + return emitPropertyDeclaration(node); + case 148: + return emitMethodSignature(node); + case 149: + return emitMethodDeclaration(node); + case 150: + return emitConstructor(node); + case 151: + case 152: + return emitAccessorDeclaration(node); + case 153: + return emitCallSignature(node); + case 154: + return emitConstructSignature(node); + case 155: + return emitIndexSignature(node); + case 156: + return emitTypePredicate(node); + case 157: + return emitTypeReference(node); + case 158: + return emitFunctionType(node); + case 159: + return emitConstructorType(node); + case 160: + return emitTypeQuery(node); + case 161: + return emitTypeLiteral(node); + case 162: + return emitArrayType(node); + case 163: + return emitTupleType(node); + case 164: + return emitUnionType(node); + case 165: + return emitIntersectionType(node); + case 166: + return emitParenthesizedType(node); + case 199: + return emitExpressionWithTypeArguments(node); + case 167: + return emitThisType(); + case 168: + return emitTypeOperator(node); + case 169: + return emitIndexedAccessType(node); + case 170: + return emitMappedType(node); + case 171: + return emitLiteralType(node); + case 172: + return emitObjectBindingPattern(node); + case 173: + return emitArrayBindingPattern(node); + case 174: + return emitBindingElement(node); + case 202: + return emitTemplateSpan(node); + case 203: + return emitSemicolonClassElement(); + case 204: + return emitBlock(node); + case 205: + return emitVariableStatement(node); + case 206: + return emitEmptyStatement(); + case 207: + return emitExpressionStatement(node); + case 208: + return emitIfStatement(node); + case 209: + return emitDoStatement(node); + case 210: + return emitWhileStatement(node); + case 211: + return emitForStatement(node); + case 212: + return emitForInStatement(node); + case 213: + return emitForOfStatement(node); + case 214: + return emitContinueStatement(node); + case 215: + return emitBreakStatement(node); + case 216: + return emitReturnStatement(node); + case 217: + return emitWithStatement(node); + case 218: + return emitSwitchStatement(node); + case 219: + return emitLabeledStatement(node); + case 220: + return emitThrowStatement(node); + case 221: + return emitTryStatement(node); + case 222: + return emitDebuggerStatement(node); + case 223: + return emitVariableDeclaration(node); + case 224: + return emitVariableDeclarationList(node); + case 225: + return emitFunctionDeclaration(node); + case 226: + return emitClassDeclaration(node); + case 227: + return emitInterfaceDeclaration(node); + case 228: + return emitTypeAliasDeclaration(node); + case 229: + return emitEnumDeclaration(node); + case 230: + return emitModuleDeclaration(node); + case 231: + return emitModuleBlock(node); + case 232: + return emitCaseBlock(node); + case 234: + return emitImportEqualsDeclaration(node); + case 235: + return emitImportDeclaration(node); + case 236: + return emitImportClause(node); + case 237: + return emitNamespaceImport(node); + case 238: + return emitNamedImports(node); + case 239: + return emitImportSpecifier(node); case 240: - return emitExternalModuleReference(node); - case 244: - return emitJsxText(node); + return emitExportAssignment(node); + case 241: + return emitExportDeclaration(node); + case 242: + return emitNamedExports(node); case 243: - return emitJsxOpeningElement(node); + return emitExportSpecifier(node); + case 244: + return; case 245: - return emitJsxClosingElement(node); - case 246: - return emitJsxAttribute(node); - case 247: - return emitJsxSpreadAttribute(node); + return emitExternalModuleReference(node); + case 10: + return emitJsxText(node); case 248: - return emitJsxExpression(node); + return emitJsxOpeningElement(node); case 249: - return emitCaseClause(node); + return emitJsxClosingElement(node); case 250: - return emitDefaultClause(node); + return emitJsxAttribute(node); case 251: - return emitHeritageClause(node); + return emitJsxSpreadAttribute(node); case 252: - return emitCatchClause(node); + return emitJsxExpression(node); case 253: - return emitPropertyAssignment(node); + return emitCaseClause(node); case 254: - return emitShorthandPropertyAssignment(node); + return emitDefaultClause(node); case 255: - return emitEnumMember(node); + return emitHeritageClause(node); case 256: - return emitSourceFile(node); + return emitCatchClause(node); + case 257: + return emitPropertyAssignment(node); + case 258: + return emitShorthandPropertyAssignment(node); + case 259: + return emitSpreadAssignment(node); + case 260: + return emitEnumMember(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: return emitNumericLiteral(node); case 9: - case 10: case 11: + case 12: return emitLiteral(node); - case 69: + case 70: return emitIdentifier(node); - case 84: - case 93: - case 95: - case 99: - case 97: - return writeTokenNode(node); - case 170: - return emitArrayLiteralExpression(node); - case 171: - return emitObjectLiteralExpression(node); - case 172: - return emitPropertyAccessExpression(node); - case 173: - return emitElementAccessExpression(node); - case 174: - return emitCallExpression(node); - case 175: - return emitNewExpression(node); - case 176: - return emitTaggedTemplateExpression(node); - case 177: - return emitTypeAssertionExpression(node); - case 178: - return emitParenthesizedExpression(node); - case 179: - return emitFunctionExpression(node); - case 180: - return emitArrowFunction(node); - case 181: - return emitDeleteExpression(node); - case 182: - return emitTypeOfExpression(node); - case 183: - return emitVoidExpression(node); - case 184: - return emitAwaitExpression(node); - case 185: - return emitPrefixUnaryExpression(node); - case 186: - return emitPostfixUnaryExpression(node); - case 187: - return emitBinaryExpression(node); - case 188: - return emitConditionalExpression(node); - case 189: - return emitTemplateExpression(node); - case 190: - return emitYieldExpression(node); - case 191: - return emitSpreadElementExpression(node); - case 192: - return emitClassExpression(node); - case 193: + case 85: + case 94: + case 96: + case 100: + case 98: + writeTokenText(kind); return; + case 175: + return emitArrayLiteralExpression(node); + case 176: + return emitObjectLiteralExpression(node); + case 177: + return emitPropertyAccessExpression(node); + case 178: + return emitElementAccessExpression(node); + case 179: + return emitCallExpression(node); + case 180: + return emitNewExpression(node); + case 181: + return emitTaggedTemplateExpression(node); + case 182: + return emitTypeAssertionExpression(node); + case 183: + return emitParenthesizedExpression(node); + case 184: + return emitFunctionExpression(node); + case 185: + return emitArrowFunction(node); + case 186: + return emitDeleteExpression(node); + case 187: + return emitTypeOfExpression(node); + case 188: + return emitVoidExpression(node); + case 189: + return emitAwaitExpression(node); + case 190: + return emitPrefixUnaryExpression(node); + case 191: + return emitPostfixUnaryExpression(node); + case 192: + return emitBinaryExpression(node); + case 193: + return emitConditionalExpression(node); + case 194: + return emitTemplateExpression(node); case 195: - return emitAsExpression(node); + return emitYieldExpression(node); case 196: + return emitSpreadExpression(node); + case 197: + return emitClassExpression(node); + case 198: + return; + case 200: + return emitAsExpression(node); + case 201: return emitNonNullExpression(node); - case 241: + case 246: return emitJsxElement(node); - case 242: + case 247: return emitJsxSelfClosingElement(node); - case 288: + case 294: return emitPartiallyEmittedExpression(node); + case 297: + return writeLines(node.text); } } function emitNumericLiteral(node) { @@ -44804,12 +49133,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, false)); - } + write(getTextOfNode(node, false)); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -44817,7 +49141,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -44887,7 +49211,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 149 ? "get " : "set "); + write(node.kind === 151 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -44915,7 +49239,7 @@ var ts; emitWithPrefix(": ", node.type); write(";"); } - function emitSemicolonClassElement(node) { + function emitSemicolonClassElement() { write(";"); } function emitTypePredicate(node) { @@ -44969,9 +49293,42 @@ var ts; emit(node.type); write(")"); } - function emitThisType(node) { + function emitThisType() { write("this"); } + function emitTypeOperator(node) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + function emitMappedType(node) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } function emitLiteralType(node) { emitExpression(node.literal); } @@ -45019,7 +49376,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +49389,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 65536)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = { kind: 22, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45055,17 +49409,16 @@ var ts; function needsDotDotForPropertyAccess(expression) { if (expression.kind === 8) { var text = getLiteralTextOfNode(expression); - return text.indexOf(ts.tokenToString(21)) < 0; + return text.indexOf(ts.tokenToString(22)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45073,11 +49426,13 @@ var ts; } function emitCallExpression(node) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { @@ -45137,16 +49492,16 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 185 - && ((node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) - || (node.operator === 36 && (operand.operator === 36 || operand.operator === 42))); + return operand.kind === 190 + && ((node.operator === 36 && (operand.operator === 36 || operand.operator === 42)) + || (node.operator === 37 && (operand.operator === 37 || operand.operator === 43))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 24; + var isCommaOperator = node.operatorToken.kind !== 25; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); @@ -45181,7 +49536,7 @@ var ts; write(node.asteriskToken ? "yield*" : "yield"); emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node) { + function emitSpreadExpression(node) { write("..."); emitExpression(node.expression); } @@ -45207,20 +49562,20 @@ var ts; emitExpression(node.expression); emit(node.literal); } - function emitBlock(node, format) { + function emitBlock(node) { if (isSingleLineEmptyBlock(node)) { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); write(" "); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } else { - writeToken(15, node.pos, node); + writeToken(16, node.pos, node); emitBlockStatements(node); - writeToken(16, node.statements.end, node); + writeToken(17, node.statements.end, node); } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 1) { emitList(node, node.statements, 384); } else { @@ -45232,7 +49587,7 @@ var ts; emit(node.declarationList); write(";"); } - function emitEmptyStatement(node) { + function emitEmptyStatement() { write(";"); } function emitExpressionStatement(node) { @@ -45240,16 +49595,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(88, node.pos, node); + var openParenPos = writeToken(89, node.pos, node); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitExpression(node.expression); - writeToken(18, node.expression.end, node); + writeToken(19, node.expression.end, node); emitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { writeLine(); - writeToken(80, node.thenStatement.end, node); - if (node.elseStatement.kind === 203) { + writeToken(81, node.thenStatement.end, node); + if (node.elseStatement.kind === 208) { write(" "); emit(node.elseStatement); } @@ -45278,9 +49633,9 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos, node); + writeToken(18, openParenPos, node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -45290,28 +49645,28 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(86, node.pos); + var openParenPos = writeToken(87, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 219) { + if (node.kind === 224) { emit(node); } else { @@ -45320,17 +49675,17 @@ var ts; } } function emitContinueStatement(node) { - writeToken(75, node.pos); + writeToken(76, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(70, node.pos); + writeToken(71, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitReturnStatement(node) { - writeToken(94, node.pos, node); + writeToken(95, node.pos, node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -45341,11 +49696,11 @@ var ts; emitEmbeddedStatement(node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(96, node.pos); + var openParenPos = writeToken(97, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emitExpression(node.expression); - writeToken(18, node.expression.end); + writeToken(19, node.expression.end); write(" "); emit(node.caseBlock); } @@ -45370,11 +49725,12 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(76, node.pos); + writeToken(77, node.pos); write(";"); } function emitVariableDeclaration(node) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } function emitVariableDeclarationList(node) { @@ -45395,19 +49751,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 262144) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { var savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } if (indentedFlag) { @@ -45430,8 +49786,8 @@ var ts; emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (ts.getEmitFlags(body) & 1) { return true; } if (body.multiLine) { @@ -45454,14 +49810,14 @@ var ts; } return true; } - function emitBlockFunctionBody(parentNode, body) { + function emitBlockFunctionBody(body) { write(" {"); increaseIndent(); - emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); decreaseIndent(); - writeToken(16, body.statements.end, body); + writeToken(17, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -45486,7 +49842,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 32768; if (indentedFlag) { increaseIndent(); } @@ -45539,7 +49895,7 @@ var ts; write(node.flags & 16 ? "namespace " : "module "); emit(node.name); var body = node.body; - while (body.kind === 225) { + while (body.kind === 230) { write("."); emit(body.name); body = body.body; @@ -45548,7 +49904,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45562,9 +49918,9 @@ var ts; } } function emitCaseBlock(node) { - writeToken(15, node.pos); + writeToken(16, node.pos); emitList(node, node.clauses, 65); - writeToken(16, node.clauses.end); + writeToken(17, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -45575,7 +49931,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -45695,7 +50051,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 69) { + if (node.kind === 70) { emitExpression(node); } else { @@ -45733,11 +50089,11 @@ var ts; } function emitCatchClause(node) { writeLine(); - var openParenPos = writeToken(72, node.pos); + var openParenPos = writeToken(73, node.pos); write(" "); - writeToken(17, openParenPos); + writeToken(18, openParenPos); emit(node.variableDeclaration); - writeToken(18, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + writeToken(19, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); write(" "); emit(node.block); } @@ -45745,8 +50101,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 512) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45758,6 +50114,12 @@ var ts; emitExpression(node.objectAssignmentInitializer); } } + function emitSpreadAssignment(node) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } function emitEnumMember(node) { emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); @@ -45793,64 +50155,31 @@ var ts; } return statements.length; } - function emitHelpers(node) { - var emitFlags = node.emitFlags; + function emitHelpers(node, isBundle) { + var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile; + var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit; var helpersEmitted = false; - if (emitFlags & 1) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - if (emitFlags & 2) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - if (emitFlags & 4) { - writeLines(superHelper); - helpersEmitted = true; - } - if (emitFlags & 8) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - return helpersEmitted; - } - function emitEmitHelpers(node) { - if (compilerOptions.noEmitHelpers) { - return false; - } - if (compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } - var helpersEmitted = false; - if ((languageVersion < 2) && (!extendsEmitted && node.flags & 1024)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } - if (compilerOptions.jsx !== 1 && !assignEmitted && (node.flags & 16384)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 2048) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + if (shouldSkip) + continue; + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + continue; + } + writeLines(helper.text); + helpersEmitted = true; } - decorateEmitted = true; - helpersEmitted = true; - } - if (!paramEmitted && node.flags & 4096) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - if (!awaiterEmitted && node.flags & 8192) { - writeLines(awaiterHelper); - if (languageVersion < 2) { - writeLines(generatorHelper); - } - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { writeLine(); @@ -45858,9 +50187,10 @@ var ts; return helpersEmitted; } function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); + var lines = text.split(/\r\n?|\n/g); + var indentation = guessIndentation(lines); for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + var line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -45869,6 +50199,21 @@ var ts; } } } + function guessIndentation(lines) { + var indentation; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var line = lines_1[_a]; + for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!ts.isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { @@ -45900,31 +50245,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +50344,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +50386,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46193,7 +50498,7 @@ var ts; && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 178 && ts.nodeIsSynthesized(node)) { + while (node.kind === 183 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -46225,17 +50530,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +50555,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_42 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_42)) { tempFlags |= flags; - return name_43; + return name_42; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_43 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_43)) { + return name_43; } } } @@ -46305,19 +50605,19 @@ var ts; } function generateNameForNode(node) { switch (node.kind) { - case 69: + case 70: return makeUniqueName(getTextOfNode(node)); - case 225: - case 224: - return generateNameForModuleOrEnum(node); case 230: - case 236: - return generateNameForImportOrExportDeclaration(node); - case 220: - case 221: + case 229: + return generateNameForModuleOrEnum(node); case 235: + case 241: + return generateNameForImportOrExportDeclaration(node); + case 225: + case 226: + case 240: return generateNameForExportDefault(); - case 192: + case 197: return generateNameForClassExpression(); default: return makeTempVariableName(0); @@ -46390,7 +50690,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.0"; var emptyArray = []; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -46445,581 +50744,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === 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, typeRoots); - } - } - else { - 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, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +50845,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); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47180,42 +50904,15 @@ var ts; } var resolutions = []; var cache = ts.createMap(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_44 = names_1[_i]; + var result = name_44 in cache + ? cache[name_44] + : cache[name_44] = loader(name_44, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47225,7 +50922,7 @@ var ts; var classifiableNames; var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; var modulesWithElidedImports = ts.createMap(); var sourceFilesFoundSearchingNodeModules = ts.createMap(); @@ -47238,10 +50935,17 @@ var ts; var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,16 +50953,17 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); 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 = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -47299,19 +51004,22 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { commonSourceDirectory += ts.directorySeparator; @@ -47330,25 +51038,85 @@ var ts; } return classifiableNames; } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var unknownModuleNames; + var result; + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + var isKnownToResolveToAmbientModule = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + result = new Array(moduleNames.length); + unknownModuleNames = moduleNames.slice(0, i); + } + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + unknownModuleNames.push(moduleName); + } + } + if (!unknownModuleNames) { + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState) { + return false; + } + var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + return false; + } + var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return false; } var oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + if (ts.changesAffectModuleResolution(oldOptions, options)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -47389,40 +51157,44 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { return false; } - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { newSourceFile = oldSourceFile; } newSourceFiles.push(newSourceFile); } + var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { - var modifiedFile = modifiedSourceFiles_1[_b]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { + var modifiedFile = modifiedSourceFiles_2[_d]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -47438,24 +51210,30 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked + isEmitBlocked: isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file) { + return sourceFilesFoundSearchingNodeModules[file.path]; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +51254,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47515,7 +51293,13 @@ var ts; return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } } - function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSyntacticDiagnosticsForFile(sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } function runWithCancellationToken(func) { @@ -47535,183 +51319,170 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; + var parent = sourceFile; walk(sourceFile); return diagnostics; function walk(node) { - if (!node) { - return false; + switch (parent.kind) { + case 144: + case 147: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + case 149: + case 148: + case 150: + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + case 223: + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } } switch (node.kind) { - case 229: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 235: + case 234: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 240: if (node.isExportEquals) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; } break; - case 221: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 251: + case 255: var heritageClause = node; - if (heritageClause.token === 106) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; + if (heritageClause.token === 107) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; } break; - case 222: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 225: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 223: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 147: - case 146: - case 148: + case 227: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 230: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 228: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 229: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 182: + var typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 226: case 149: + case 148: case 150: - case 179: - case 220: - case 180: - case 220: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; + case 151: + case 152: + case 184: + case 225: + case 185: + case 225: + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + case 205: + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 205); } break; - case 200: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 218: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 174: - case 175: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 142: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 145: - var propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + case 147: + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _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 (modifier.kind !== 114) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } - } - if (checkTypeAnnotation(node.type)) { - return true; + return; } break; - case 224: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 177: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 143: - if (!options.experimentalDecorators) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + case 144: + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112: - case 110: - case 111: - case 128: - case 122: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - case 113: - case 82: - case 74: - case 77: - case 115: + break; + case 179: + case 180: + case 199: + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 75: + if (isConstValid) { + continue; + } + case 113: + case 111: + case 112: + case 130: + case 123: + case 116: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + case 114: + case 83: + case 78: } } - return false; + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); - var writeFile = function () { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { @@ -47728,11 +51499,8 @@ var ts; ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName) { - return ts.getBaseFileName(fileName).indexOf(".") >= 0; - } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, true); + processSourceFile(ts.normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -47749,14 +51517,18 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; + var ambientModules; if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - var externalHelpersModuleReference = ts.createNode(9); + var externalHelpersModuleReference = ts.createSynthesizedNode(9); externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + var importDecl = ts.createSynthesizedNode(235); + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { @@ -47768,12 +51540,13 @@ var ts; } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 230: - case 229: - case 236: + case 235: + case 234: + case 241: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -47785,13 +51558,16 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 225: + case 230: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || ts.isDeclarationFile(file))) { var moduleName = node.name; if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + (ambientModules || (ambientModules = [])).push(moduleName.text); + } var body = node.body; if (body) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { @@ -47812,15 +51588,15 @@ var ts; } } } - function processSourceFile(fileName, isDefaultLib, isReference, refFile, refPos, refEnd) { + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { var diagnosticArgument; var diagnostic; - if (hasExtension(fileName)) { + if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -47830,13 +51606,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -47860,7 +51636,7 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, path, isDefaultLib, isReference, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { if (filesByName.contains(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { @@ -47869,16 +51645,16 @@ var ts; if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } } return file_1; @@ -47905,12 +51681,11 @@ var ts; } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - var basePath = ts.getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); } @@ -47920,10 +51695,10 @@ var ts; } return file; } - function processReferencedFiles(file, basePath, isDefaultLib) { + function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -47945,18 +51720,20 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } else { if (previousResolution) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } } saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); } } } @@ -47982,28 +51759,35 @@ var ts; function getCanonicalFileName(fileName) { return host.getCanonicalFileName(fileName); } - function processImportedModules(file, basePath) { + function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = ts.createMap(); - var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); + var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; - var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48013,12 +51797,11 @@ var ts; else { file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +51812,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +51856,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +51867,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +51906,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48164,13 +51950,21 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); - ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); @@ -48179,10 +51973,15 @@ var ts; if (emitFileName) { var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + var chain_1; + if (!options.configFilePath) { + chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } if (emitFilesSeen.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -48190,12 +51989,33 @@ var ts; } } } - function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); } } ts.createProgram = createProgram; + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ts.Extension.Ts: + case ts.Extension.Dts: + return undefined; + case ts.Extension.Tsx: + return needJsx(); + case ts.Extension.Jsx: + return needJsx() || needAllowJs(); + case ts.Extension.Js: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; })(ts || (ts = {})); var ts; (function (ts) { @@ -48206,12 +52026,14 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + StringScriptSnapshot.prototype.getChangeRange = function () { return undefined; }; return StringScriptSnapshot; @@ -48234,12 +52056,13 @@ var ts; HighlightSpanKind.reference = "reference"; HighlightSpanKind.writtenReference = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; (function (IndentStyle) { IndentStyle[IndentStyle["None"] = 0] = "None"; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -48263,8 +52086,8 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -48275,8 +52098,7 @@ var ts; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { ScriptElementKind.unknown = ""; @@ -48355,37 +52177,37 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.scanner = ts.createScanner(2, true); + ts.scanner = ts.createScanner(5, true); ts.emptyArray = []; function getMeaningFromDeclaration(node) { switch (node.kind) { - case 142: - case 218: - case 169: - case 145: case 144: - case 253: - case 254: - case 255: + case 223: + case 174: case 147: case 146: - case 148: + case 257: + case 258: + case 260: case 149: + case 148: case 150: - case 220: - case 179: - case 180: - case 252: - return 1; - case 141: - case 222: - case 223: - case 159: - return 2; - case 221: - case 224: - return 1 | 2; + case 151: + case 152: case 225: + case 184: + case 185: + case 256: + return 1; + case 143: + case 227: + case 228: + case 161: + return 2; + case 226: + case 229: + return 1 | 2; + case 230: if (ts.isAmbientModule(node)) { return 4 | 1; } @@ -48395,21 +52217,21 @@ var ts; else { return 4; } - case 233: + case 238: + case 239: case 234: - case 229: - case 230: case 235: - case 236: + case 240: + case 241: return 1 | 2 | 4; - case 256: + case 261: return 4 | 1; } return 1 | 2 | 4; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.parent.kind === 235) { + if (node.parent.kind === 240) { return 1 | 2 | 4; } else if (isInRightSideOfImport(node)) { @@ -48430,16 +52252,16 @@ var ts; } ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69); - if (node.parent.kind === 139 && + ts.Debug.assert(node.kind === 70); + if (node.parent.kind === 141 && node.parent.right === node && - node.parent.parent.kind === 229) { + node.parent.parent.kind === 234) { return 1 | 2 | 4; } return 4; } function isInRightSideOfImport(node) { - while (node.parent.kind === 139) { + while (node.parent.kind === 141) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -48450,27 +52272,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 139) { - while (root.parent && root.parent.kind === 139) { + if (root.parent.kind === 141) { + while (root.parent && root.parent.kind === 141) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 155 && !isLastClause; + return root.parent.kind === 157 && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 172) { - while (root.parent && root.parent.kind === 172) { + if (root.parent.kind === 177) { + while (root.parent && root.parent.kind === 177) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 194 && root.parent.parent.kind === 251) { + if (!isLastClause && root.parent.kind === 199 && root.parent.parent.kind === 255) { var decl = root.parent.parent.parent; - return (decl.kind === 221 && root.parent.parent.token === 106) || - (decl.kind === 222 && root.parent.parent.token === 83); + return (decl.kind === 226 && root.parent.parent.token === 107) || + (decl.kind === 227 && root.parent.parent.token === 84); } return false; } @@ -48478,17 +52300,17 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 155 || - (node.parent.kind === 194 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 && !ts.isPartOfExpression(node)) || - node.kind === 165; + return node.parent.kind === 157 || + (node.parent.kind === 199 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 98 && !ts.isPartOfExpression(node)) || + node.kind === 167; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 174); + return isCallOrNewExpressionTarget(node, 179); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 175); + return isCallOrNewExpressionTarget(node, 180); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -48501,7 +52323,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 214 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 219 && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -48510,14 +52332,14 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 69 && - (node.parent.kind === 210 || node.parent.kind === 209) && + return node.kind === 70 && + (node.parent.kind === 215 || node.parent.kind === 214) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 69 && - node.parent.kind === 214 && + return node.kind === 70 && + node.parent.kind === 219 && node.parent.label === node; } function isLabelName(node) { @@ -48525,38 +52347,38 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 && node.parent.right === node; + return node.parent.kind === 141 && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 && node.parent.name === node; + return node && node.parent && node.parent.kind === 177 && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 && node.parent.name === node; + return node.parent.kind === 230 && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 69 && + return node.kind === 70 && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 || node.kind === 8) { switch (node.parent.kind) { - case 145: - case 144: - case 253: - case 255: case 147: case 146: + case 257: + case 260: case 149: - case 150: - case 225: + case 148: + case 151: + case 152: + case 230: return node.parent.name === node; - case 173: + case 178: return node.parent.argumentExpression === node; - case 140: + case 142: return true; } } @@ -48600,17 +52422,17 @@ var ts; return undefined; } switch (node.kind) { - case 256: - case 147: - case 146: - case 220: - case 179: + case 261: case 149: - case 150: - case 221: - case 222: - case 224: + case 148: case 225: + case 184: + case 151: + case 152: + case 226: + case 227: + case 229: + case 230: return node; } } @@ -48618,46 +52440,46 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 256: + case 261: return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; - case 225: + case 230: return ts.ScriptElementKind.moduleElement; - case 221: - case 192: + case 226: + case 197: return ts.ScriptElementKind.classElement; - case 222: return ts.ScriptElementKind.interfaceElement; - case 223: return ts.ScriptElementKind.typeElement; - case 224: return ts.ScriptElementKind.enumElement; - case 218: + case 227: return ts.ScriptElementKind.interfaceElement; + case 228: return ts.ScriptElementKind.typeElement; + case 229: return ts.ScriptElementKind.enumElement; + case 223: return getKindOfVariableDeclaration(node); - case 169: + case 174: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: return ts.ScriptElementKind.functionElement; - case 149: return ts.ScriptElementKind.memberGetAccessorElement; - case 150: return ts.ScriptElementKind.memberSetAccessorElement; + case 151: return ts.ScriptElementKind.memberGetAccessorElement; + case 152: return ts.ScriptElementKind.memberSetAccessorElement; + case 149: + case 148: + return ts.ScriptElementKind.memberFunctionElement; case 147: case 146: - return ts.ScriptElementKind.memberFunctionElement; - case 145: - case 144: return ts.ScriptElementKind.memberVariableElement; - case 153: return ts.ScriptElementKind.indexSignatureElement; - case 152: return ts.ScriptElementKind.constructSignatureElement; - case 151: return ts.ScriptElementKind.callSignatureElement; - case 148: return ts.ScriptElementKind.constructorImplementationElement; - case 141: return ts.ScriptElementKind.typeParameterElement; - case 255: return ts.ScriptElementKind.enumMemberElement; - case 142: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; - case 229: + case 155: return ts.ScriptElementKind.indexSignatureElement; + case 154: return ts.ScriptElementKind.constructSignatureElement; + case 153: return ts.ScriptElementKind.callSignatureElement; + case 150: return ts.ScriptElementKind.constructorImplementationElement; + case 143: return ts.ScriptElementKind.typeParameterElement; + case 260: return ts.ScriptElementKind.enumMemberElement; + case 144: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; case 234: - case 231: - case 238: - case 232: + case 239: + case 236: + case 243: + case 237: return ts.ScriptElementKind.alias; - case 279: + case 285: return ts.ScriptElementKind.typeElement; default: return ts.ScriptElementKind.unknown; @@ -48672,7 +52494,7 @@ var ts; } ts.getNodeKind = getNodeKind; function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 ? node.parent : node; + var searchNode = node.parent.kind === 171 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); if (type && type.flags & 32) { return type; @@ -48682,10 +52504,10 @@ var ts; ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; function isThis(node) { switch (node.kind) { - case 97: + case 98: return true; - case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + case 70: + return ts.identifierIsThisKeyword(node) && node.parent.kind === 144; default: return false; } @@ -48729,107 +52551,107 @@ var ts; return false; } switch (n.kind) { - case 221: - case 222: - case 224: - case 171: - case 167: - case 159: - case 199: case 226: case 227: - case 233: - case 237: - return nodeEndsWith(n, 16, sourceFile); - case 252: + case 229: + case 176: + case 172: + case 161: + case 204: + case 231: + case 232: + case 238: + case 242: + return nodeEndsWith(n, 17, sourceFile); + case 256: return isCompletedNode(n.block, sourceFile); - case 175: + case 180: if (!n.arguments) { return true; } - case 174: - case 178: - case 164: - return nodeEndsWith(n, 18, sourceFile); - case 156: - case 157: - return isCompletedNode(n.type, sourceFile); - case 148: - case 149: - case 150: - case 220: case 179: - case 147: - case 146: - case 152: + case 183: + case 166: + return nodeEndsWith(n, 19, sourceFile); + case 158: + case 159: + return isCompletedNode(n.type, sourceFile); + case 150: case 151: - case 180: + case 152: + case 225: + case 184: + case 149: + case 148: + case 154: + case 153: + case 185: if (n.body) { return isCompletedNode(n.body, sourceFile); } if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 18, sourceFile); - case 225: + return hasChildOfKind(n, 19, sourceFile); + case 230: return n.body && isCompletedNode(n.body, sourceFile); - case 203: + case 208: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 202: + case 207: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23); - case 170: - case 168: + hasChildOfKind(n, 24); + case 175: case 173: - case 140: - case 161: - return nodeEndsWith(n, 20, sourceFile); - case 153: + case 178: + case 142: + case 163: + return nodeEndsWith(n, 21, sourceFile); + case 155: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 20, sourceFile); - case 249: - case 250: + return hasChildOfKind(n, 21, sourceFile); + case 253: + case 254: return false; - case 206: - case 207: - case 208: - case 205: + case 211: + case 212: + case 213: + case 210: return isCompletedNode(n.statement, sourceFile); - case 204: - var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); + case 209: + var hasWhileKeyword = findChildOfKind(n, 105, sourceFile); if (hasWhileKeyword) { - return nodeEndsWith(n, 18, sourceFile); + return nodeEndsWith(n, 19, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 158: + case 160: return isCompletedNode(n.exprName, sourceFile); - case 182: - case 181: - case 183: - case 190: - case 191: + case 187: + case 186: + case 188: + case 195: + case 196: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176: + case 181: return isCompletedNode(n.template, sourceFile); - case 189: + case 194: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 197: + case 202: return ts.nodeIsPresent(n.literal); - case 236: - case 230: + case 241: + case 235: return ts.nodeIsPresent(n.moduleSpecifier); - case 185: + case 190: return isCompletedNode(n.operand, sourceFile); - case 187: + case 192: return isCompletedNode(n.right, sourceFile); - case 188: + case 193: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -48843,7 +52665,7 @@ var ts; if (last.kind === expectedLastToken) { return true; } - else if (last.kind === 23 && children.length !== 1) { + else if (last.kind === 24 && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -48872,7 +52694,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 292 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -48980,7 +52802,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 244) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -48988,16 +52810,16 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 244) { + if (isToken(n)) { return n; } var children = n.getChildren(); for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 244)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 244 && start === child.end); + (child.kind === 10 && start === child.end); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -49007,7 +52829,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 256); + ts.Debug.assert(startNode !== undefined || n.kind === 261); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -49046,19 +52868,19 @@ var ts; if (!token) { return false; } - if (token.kind === 244) { + if (token.kind === 10) { return true; } - if (token.kind === 25 && token.parent.kind === 244) { + if (token.kind === 26 && token.parent.kind === 10) { return true; } - if (token.kind === 25 && token.parent.kind === 248) { + if (token.kind === 26 && token.parent.kind === 252) { return true; } - if (token && token.kind === 16 && token.parent.kind === 248) { + if (token && token.kind === 17 && token.parent.kind === 252) { return true; } - if (token.kind === 25 && token.parent.kind === 245) { + if (token.kind === 26 && token.parent.kind === 249) { return true; } return false; @@ -49097,9 +52919,9 @@ var ts; var node = ts.getTokenAtPosition(sourceFile, position); if (isToken(node)) { switch (node.kind) { - case 102: - case 108: - case 74: + case 103: + case 109: + case 75: node = node.parent === undefined ? undefined : node.parent.parent; break; default: @@ -49108,11 +52930,11 @@ var ts; } } if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - if (jsDocComment.tags) { - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (jsDoc.tags) { + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; if (tag.pos <= position && position <= tag.end) { return tag; @@ -49149,21 +52971,21 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 || node.kind === 174) { + if (node.kind === 157 || node.kind === 179) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 221 || node.kind === 222) { + if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 227) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 && n.kind <= 138; + return n.kind >= 0 && n.kind <= 140; } ts.isToken = isToken; function isWord(kind) { - return kind === 69 || ts.isKeyword(kind); + return kind === 70 || ts.isKeyword(kind); } ts.isWord = isWord; function isPropertyName(kind) { @@ -49175,7 +52997,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 - || kind === 10 + || kind === 11 || ts.isTemplateLiteralKind(kind)) { return true; } @@ -49183,7 +53005,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 15 <= kind && kind <= 68; + return 16 <= kind && kind <= 69; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position) { @@ -49193,9 +53015,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 112: - case 110: + case 113: case 111: + case 112: return true; } return false; @@ -49218,18 +53040,18 @@ var ts; } ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 || - node.kind === 171) { - if (node.parent.kind === 187 && + if (node.kind === 175 || + node.kind === 176) { + if (node.parent.kind === 192 && node.parent.left === node && - node.parent.operatorToken.kind === 56) { + node.parent.operatorToken.kind === 57) { return true; } - if (node.parent.kind === 208 && + if (node.parent.kind === 213 && node.parent.initializer === node) { return true; } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 257 ? node.parent.parent : node.parent)) { return true; } } @@ -49258,10 +53080,9 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 144; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -49278,13 +53099,14 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; function writeIndent() { if (lineStart) { @@ -49314,7 +53136,7 @@ var ts; } } function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); + return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol) { var flags = symbol.flags; if (flags & 3) { @@ -49363,7 +53185,7 @@ var ts; } } ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { + function displayPart(text, kind) { return { text: text, kind: ts.SymbolDisplayPartKind[kind] @@ -49435,8 +53257,8 @@ var ts; if (isImportOrExportSpecifierName(location)) { return location.getText(); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140) { + else if (ts.isStringOrNumericLiteral(location) && + location.parent.kind === 142) { return location.text; } var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); @@ -49446,7 +53268,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 234 || location.parent.kind === 238) && + (location.parent.kind === 239 || location.parent.kind === 243) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -49481,7 +53303,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +53314,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -49548,176 +53373,176 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 200: + case 205: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 218: - case 145: - case 144: - return spanInVariableDeclaration(node); - case 142: - return spanInParameterDeclaration(node); - case 220: + case 223: case 147: case 146: + return spanInVariableDeclaration(node); + case 144: + return spanInParameterDeclaration(node); + case 225: case 149: - case 150: case 148: - case 179: - case 180: + case 151: + case 152: + case 150: + case 184: + case 185: return spanInFunctionDeclaration(node); - case 199: + case 204: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 226: + case 231: return spanInBlock(node); - case 252: + case 256: return spanInBlock(node.block); - case 202: - return textSpan(node.expression); - case 211: - return textSpan(node.getChildAt(0), node.expression); - case 205: - return textSpanEndingAtNextToken(node, node.expression); - case 204: - return spanInNode(node.statement); - case 217: - return textSpan(node.getChildAt(0)); - case 203: - return textSpanEndingAtNextToken(node, node.expression); - case 214: - return spanInNode(node.statement); - case 210: - case 209: - return textSpan(node.getChildAt(0), node.label); - case 206: - return spanInForStatement(node); case 207: - return textSpanEndingAtNextToken(node, node.expression); - case 208: - return spanInInitializerOfForLike(node); - case 213: - return textSpanEndingAtNextToken(node, node.expression); - case 249: - case 250: - return spanInNode(node.statements[0]); + return textSpan(node.expression); case 216: - return spanInBlock(node.tryBlock); + return textSpan(node.getChildAt(0), node.expression); + case 210: + return textSpanEndingAtNextToken(node, node.expression); + case 209: + return spanInNode(node.statement); + case 222: + return textSpan(node.getChildAt(0)); + case 208: + return textSpanEndingAtNextToken(node, node.expression); + case 219: + return spanInNode(node.statement); case 215: + case 214: + return textSpan(node.getChildAt(0), node.label); + case 211: + return spanInForStatement(node); + case 212: + return textSpanEndingAtNextToken(node, node.expression); + case 213: + return spanInInitializerOfForLike(node); + case 218: + return textSpanEndingAtNextToken(node, node.expression); + case 253: + case 254: + return spanInNode(node.statements[0]); + case 221: + return spanInBlock(node.tryBlock); + case 220: return textSpan(node, node.expression); - case 235: + case 240: return textSpan(node, node.expression); - case 229: + case 234: return textSpan(node, node.moduleReference); + case 235: + return textSpan(node, node.moduleSpecifier); + case 241: + return textSpan(node, node.moduleSpecifier); case 230: - return textSpan(node, node.moduleSpecifier); - case 236: - return textSpan(node, node.moduleSpecifier); - case 225: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 221: - case 224: - case 255: - case 169: + case 226: + case 229: + case 260: + case 174: return textSpan(node); - case 212: + case 217: return spanInNode(node.statement); - case 143: + case 145: return spanInNodeArray(node.parent.decorators); - case 167: - case 168: + case 172: + case 173: return spanInBindingPattern(node); - case 222: - case 223: + case 227: + case 228: return undefined; - case 23: + case 24: case 1: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 24: - return spanInPreviousNode(node); - case 15: - return spanInOpenBraceToken(node); - case 16: - return spanInCloseBraceToken(node); - case 20: - return spanInCloseBracketToken(node); - case 17: - return spanInOpenParenToken(node); - case 18: - return spanInCloseParenToken(node); - case 54: - return spanInColonToken(node); - case 27: case 25: + return spanInPreviousNode(node); + case 16: + return spanInOpenBraceToken(node); + case 17: + return spanInCloseBraceToken(node); + case 21: + return spanInCloseBracketToken(node); + case 18: + return spanInOpenParenToken(node); + case 19: + return spanInCloseParenToken(node); + case 55: + return spanInColonToken(node); + case 28: + case 26: return spanInGreaterThanOrLessThanToken(node); - case 104: + case 105: return spanInWhileKeyword(node); - case 80: - case 72: - case 85: + case 81: + case 73: + case 86: return spanInNextNode(node); - case 138: + case 140: return spanInOfKeyword(node); default: if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } - if ((node.kind === 69 || - node.kind == 191 || - node.kind === 253 || - node.kind === 254) && + if ((node.kind === 70 || + node.kind == 196 || + node.kind === 257 || + node.kind === 258) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 187) { + if (node.kind === 192) { var binaryExpression = node; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); } - if (binaryExpression.operatorToken.kind === 56 && + if (binaryExpression.operatorToken.kind === 57 && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { return textSpan(node); } - if (binaryExpression.operatorToken.kind === 24) { + if (binaryExpression.operatorToken.kind === 25) { return spanInNode(binaryExpression.left); } } if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { - case 204: + case 209: return spanInPreviousNode(node); - case 143: + case 145: return spanInNode(node.parent); - case 206: - case 208: + case 211: + case 213: return textSpan(node); - case 187: - if (node.parent.operatorToken.kind === 24) { + case 192: + if (node.parent.operatorToken.kind === 25) { return textSpan(node); } break; - case 180: + case 185: if (node.parent.body === node) { return textSpan(node); } break; } } - if (node.parent.kind === 253 && + if (node.parent.kind === 257 && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 177 && node.parent.type === node) { + if (node.parent.kind === 182 && node.parent.type === node) { return spanInNextNode(node.parent.type); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } - if ((node.parent.kind === 218 || - node.parent.kind === 142)) { + if ((node.parent.kind === 223 || + node.parent.kind === 144)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -49725,7 +53550,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 187) { + if (node.parent.kind === 192) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -49746,7 +53571,7 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 207) { + if (variableDeclaration.parent.parent.kind === 212) { return spanInNode(variableDeclaration.parent.parent); } if (ts.isBindingPattern(variableDeclaration.name)) { @@ -49754,7 +53579,7 @@ var ts; } if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1) || - variableDeclaration.parent.parent.kind === 208) { + variableDeclaration.parent.parent.kind === 213) { return textSpanFromVariableDeclaration(variableDeclaration); } var declarations = variableDeclaration.parent.declarations; @@ -49786,7 +53611,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1) || - (functionDeclaration.parent.kind === 221 && functionDeclaration.kind !== 148); + (functionDeclaration.parent.kind === 226 && functionDeclaration.kind !== 150); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -49806,22 +53631,22 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 225: + case 230: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 205: - case 203: - case 207: - return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 206: + case 210: case 208: + case 212: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + case 211: + case 213: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 219) { + if (forLikeStatement.initializer.kind === 224) { var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -49843,62 +53668,62 @@ var ts; } } function spanInBindingPattern(bindingPattern) { - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 193 ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 198 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - if (bindingPattern.parent.kind === 169) { + if (bindingPattern.parent.kind === 174) { return textSpan(bindingPattern.parent); } return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 168 && node.kind !== 167); - var elements = node.kind === 170 ? + ts.Debug.assert(node.kind !== 173 && node.kind !== 172); + var elements = node.kind === 175 ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 193 ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 198 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - return textSpan(node.parent.kind === 187 ? node.parent : node); + return textSpan(node.parent.kind === 192 ? node.parent : node); } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 224: + case 229: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 221: + case 226: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 227: + case 232: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 226: + case 231: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 224: - case 221: + case 229: + case 226: return textSpan(node); - case 199: + case 204: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 252: + case 256: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 227: + case 232: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 167: + case 172: var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -49911,7 +53736,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 168: + case 173: var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -49923,33 +53748,33 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 204 || - node.parent.kind === 174 || - node.parent.kind === 175) { + if (node.parent.kind === 209 || + node.parent.kind === 179 || + node.parent.kind === 180) { return spanInPreviousNode(node); } - if (node.parent.kind === 178) { + if (node.parent.kind === 183) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 179: - case 220: - case 180: - case 147: - case 146: + case 184: + case 225: + case 185: case 149: - case 150: case 148: - case 205: - case 204: - case 206: - case 208: - case 174: - case 175: - case 178: + case 151: + case 152: + case 150: + case 210: + case 209: + case 211: + case 213: + case 179: + case 180: + case 183: return spanInPreviousNode(node); default: return spanInNode(node.parent); @@ -49957,26 +53782,26 @@ var ts; } function spanInColonToken(node) { if (ts.isFunctionLike(node.parent) || - node.parent.kind === 253 || - node.parent.kind === 142) { + node.parent.kind === 257 || + node.parent.kind === 144) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 177) { + if (node.parent.kind === 182) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 204) { + if (node.parent.kind === 209) { return textSpanEndingAtNextToken(node, node.parent.expression); } return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 208) { + if (node.parent.kind === 213) { return spanInNextNode(node); } return spanInNode(node.parent); @@ -49989,27 +53814,27 @@ var ts; var ts; (function (ts) { function createClassifier() { - var scanner = ts.createScanner(2, false); + var scanner = ts.createScanner(5, false); var noRegexTable = []; - noRegexTable[69] = true; + noRegexTable[70] = true; noRegexTable[9] = true; noRegexTable[8] = true; - noRegexTable[10] = true; - noRegexTable[97] = true; - noRegexTable[41] = true; + noRegexTable[11] = true; + noRegexTable[98] = true; noRegexTable[42] = true; - noRegexTable[18] = true; - noRegexTable[20] = true; - noRegexTable[16] = true; - noRegexTable[99] = true; - noRegexTable[84] = true; + noRegexTable[43] = true; + noRegexTable[19] = true; + noRegexTable[21] = true; + noRegexTable[17] = true; + noRegexTable[100] = true; + noRegexTable[85] = true; var templateStack = []; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 || - keyword2 === 131 || - keyword2 === 121 || - keyword2 === 113) { + if (keyword2 === 124 || + keyword2 === 133 || + keyword2 === 122 || + keyword2 === 114) { return true; } return false; @@ -50092,7 +53917,7 @@ var ts; text = "}\n" + text; offset = 2; case 6: - templateStack.push(12); + templateStack.push(13); break; } scanner.setText(text); @@ -50104,55 +53929,55 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 39 || token === 61) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10) { - token = 10; + if ((token === 40 || token === 62) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 11) { + token = 11; } } - else if (lastNonTriviaToken === 21 && isKeyword(token)) { - token = 69; + else if (lastNonTriviaToken === 22 && isKeyword(token)) { + token = 70; } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 69; + token = 70; } - else if (lastNonTriviaToken === 69 && - token === 25) { + else if (lastNonTriviaToken === 70 && + token === 26) { angleBracketStack++; } - else if (token === 27 && angleBracketStack > 0) { + else if (token === 28 && angleBracketStack > 0) { angleBracketStack--; } - else if (token === 117 || + else if (token === 118 || + token === 134 || token === 132 || - token === 130 || - token === 120 || - token === 133) { + token === 121 || + token === 135) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - token = 69; + token = 70; } } - else if (token === 12) { + else if (token === 13) { templateStack.push(token); } - else if (token === 15) { + else if (token === 16) { if (templateStack.length > 0) { templateStack.push(token); } } - else if (token === 16) { + else if (token === 17) { if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12) { + if (lastTemplateStackToken === 13) { token = scanner.reScanTemplateToken(); - if (token === 14) { + if (token === 15) { templateStack.pop(); } else { - ts.Debug.assert(token === 13, "Should have been a template middle. Was " + token); + ts.Debug.assert(token === 14, "Should have been a template middle. Was " + token); } } else { - ts.Debug.assert(lastTemplateStackToken === 15, "Should have been an open brace. Was: " + token); + ts.Debug.assert(lastTemplateStackToken === 16, "Should have been an open brace. Was: " + token); templateStack.pop(); } } @@ -50190,10 +54015,10 @@ var ts; } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { - if (token === 14) { + if (token === 15) { result.endOfLineState = 5; } - else if (token === 11) { + else if (token === 12) { result.endOfLineState = 4; } else { @@ -50201,7 +54026,7 @@ var ts; } } } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12) { + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 13) { result.endOfLineState = 6; } } @@ -50225,43 +54050,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 37: - case 39: + case 38: case 40: - case 35: + case 41: case 36: - case 43: + case 37: case 44: case 45: - case 25: - case 27: + case 46: + case 26: case 28: case 29: - case 91: - case 90: - case 116: case 30: + case 92: + case 91: + case 117: case 31: case 32: case 33: - case 46: - case 48: + case 34: case 47: - case 51: + case 49: + case 48: case 52: - case 67: - case 66: + case 53: case 68: - case 63: + case 67: + case 69: case 64: case 65: - case 57: + case 66: case 58: case 59: - case 61: + case 60: case 62: - case 56: - case 24: + case 63: + case 57: + case 25: return true; default: return false; @@ -50269,19 +54094,19 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 35: case 36: + case 37: + case 51: case 50: - case 49: - case 41: case 42: + case 43: return true; default: return false; } } function isKeyword(token) { - return token >= 70 && token <= 138; + return token >= 71 && token <= 140; } function classFromKind(token) { if (isKeyword(token)) { @@ -50290,7 +54115,7 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5; } - else if (token >= 15 && token <= 68) { + else if (token >= 16 && token <= 69) { return 10; } switch (token) { @@ -50298,7 +54123,7 @@ var ts; return 4; case 9: return 6; - case 10: + case 11: return 7; case 7: case 3: @@ -50307,7 +54132,7 @@ var ts; case 5: case 4: return 8; - case 69: + case 70: default: if (ts.isTemplateLiteralKind(token)) { return 6; @@ -50327,10 +54152,10 @@ var ts; ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { switch (kind) { + case 230: + case 226: + case 227: case 225: - case 221: - case 222: - case 220: cancellationToken.throwIfCancellationRequested(); } } @@ -50374,7 +54199,7 @@ var ts; return undefined; function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 && + return declaration.kind === 230 && ts.getModuleInstanceState(declaration) === 1; }); } @@ -50383,7 +54208,7 @@ var ts; if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { var kind = node.kind; checkForClassificationCancellation(cancellationToken, kind); - if (kind === 69 && !ts.nodeIsMissing(node)) { + if (kind === 70 && !ts.nodeIsMissing(node)) { var identifier = node; if (classifiableNames[identifier.text]) { var symbol = typeChecker.getSymbolAtLocation(node); @@ -50446,8 +54271,8 @@ var ts; function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { var spanStart = span.start; var spanLength = span.length; - var triviaScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2, false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 }; @@ -50515,16 +54340,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 275: + case 281: processJSDocParameterTag(tag); break; - case 278: + case 284: processJSDocTemplateTag(tag); break; - case 277: + case 283: processElement(tag.typeExpression); break; - case 276: + case 282: processElement(tag.typeExpression); break; } @@ -50589,10 +54414,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 10 && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 244 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 10 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -50605,22 +54430,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 243: + case 248: if (token.parent.tagName === token) { return 19; } break; - case 245: + case 249: if (token.parent.tagName === token) { return 20; } break; - case 242: + case 247: if (token.parent.tagName === token) { return 21; } break; - case 246: + case 250: if (token.parent.name === token) { return 22; } @@ -50632,25 +54457,25 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3; } - if (tokenKind === 25 || tokenKind === 27) { + if (tokenKind === 26 || tokenKind === 28) { if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return 10; } } if (ts.isPunctuation(tokenKind)) { if (token) { - if (tokenKind === 56) { - if (token.parent.kind === 218 || - token.parent.kind === 145 || - token.parent.kind === 142 || - token.parent.kind === 246) { + if (tokenKind === 57) { + if (token.parent.kind === 223 || + token.parent.kind === 147 || + token.parent.kind === 144 || + token.parent.kind === 250) { return 5; } } - if (token.parent.kind === 187 || - token.parent.kind === 185 || - token.parent.kind === 186 || - token.parent.kind === 188) { + if (token.parent.kind === 192 || + token.parent.kind === 190 || + token.parent.kind === 191 || + token.parent.kind === 193) { return 5; } } @@ -50660,49 +54485,48 @@ var ts; return 4; } else if (tokenKind === 9) { - return token.parent.kind === 246 ? 24 : 6; + return token.parent.kind === 250 ? 24 : 6; } - else if (tokenKind === 10) { + else if (tokenKind === 11) { return 6; } else if (ts.isTemplateLiteralKind(tokenKind)) { return 6; } - else if (tokenKind === 244) { + else if (tokenKind === 10) { return 23; } - else if (tokenKind === 69) { + else if (tokenKind === 70) { if (token) { switch (token.parent.kind) { - case 221: + case 226: if (token.parent.name === token) { return 11; } return; - case 141: + case 143: if (token.parent.name === token) { return 15; } return; - case 222: + case 227: if (token.parent.name === token) { return 13; } return; - case 224: + case 229: if (token.parent.name === token) { return 12; } return; - case 225: + case 230: if (token.parent.name === token) { return 14; } return; - case 142: + case 144: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,25 +54567,25 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 245) { + location.parent && location.parent.kind === 249) { var tagName = location.parent.parent.openingElement.tagName; entries.push({ name: tagName.text, kind: undefined, kindModifiers: undefined, - sortText: "0" + sortText: "0", }); } else { @@ -50773,17 +54597,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_45 in nameTable) { + if (nameTable[name_45] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_45]) { + uniqueNames[name_45] = name_45; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_45), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50806,7 +54630,7 @@ var ts; name: displayName, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - sortText: "0" + sortText: "0", }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { @@ -50833,19 +54657,21 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 257 && + node.parent.parent.kind === 176 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { return getStringLiteralCompletionEntriesFromElementAccess(node.parent); } - else if (node.parent.kind === 230 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + else if (node.parent.kind === 235 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { return getStringLiteralCompletionEntriesFromModuleNames(node); } else { var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); } return getStringLiteralCompletionEntriesFromContextualType(node); } @@ -50856,11 +54682,11 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { var candidates = []; var entries = []; typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); @@ -50872,7 +54698,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +54708,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +54719,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50902,7 +54728,7 @@ var ts; if (!type) { return; } - if (type.flags & 524288) { + if (type.flags & 65536) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { @@ -50934,6 +54760,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +54791,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +54955,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +54968,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51167,7 +54996,7 @@ var ts; if (typeRoots) { for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); + getCompletionEntriesFromDirectories(host, root, span, result); } } } @@ -51175,12 +55004,12 @@ var ts; for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { var packageJson = _d[_c]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + getCompletionEntriesFromDirectories(host, typesDir, span, result); } } return result; } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + function getCompletionEntriesFromDirectories(host, directory, span, result) { if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { @@ -51200,11 +55029,11 @@ var ts; if (currentConfigPath) { paths.push(currentConfigPath); currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_16 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_16) { + var parent_13 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_13) { break; } - currentDir = parent_16; + currentDir = parent_13; } else { break; @@ -51281,10 +55110,10 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location_3 = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -51310,8 +55139,8 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location_4 = completionData.location; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_4) === entryName ? s : undefined; }); } return undefined; } @@ -51336,9 +55165,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 277: - case 275: - case 276: + case 283: + case 281: + case 282: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -51347,7 +55176,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51373,13 +55202,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21) { - if (parent_17.kind === 172) { + var parent_14 = contextToken.parent, kind = contextToken.kind; + if (kind === 22) { + if (parent_14.kind === 177) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_17.kind === 139) { + else if (parent_14.kind === 141) { node = contextToken.parent.left; isRightOfDot = true; } @@ -51388,17 +55217,18 @@ var ts; } } else if (sourceFile.languageVariant === 1) { - if (kind === 25) { + if (kind === 26) { isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 && contextToken.parent.kind === 245) { + else if (kind === 40 && contextToken.parent.kind === 249) { isStartingCloseTag = true; location = contextToken; } } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51431,11 +55261,12 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 139 || node.kind === 172) { + if (node.kind === 70 || node.kind === 141 || node.kind === 177) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { symbol = typeChecker.getAliasedSymbol(symbol); @@ -51460,7 +55291,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 524288) { + if (isJavaScriptFile && type.flags & 65536) { var unionType = type; for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { var elementType = _c[_b]; @@ -51481,7 +55312,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { + if ((jsxContainer.kind === 247) || (jsxContainer.kind === 248)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); @@ -51500,6 +55331,13 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + if (scopeNode) { + isGlobalCompletion = + scopeNode.kind === 261 || + scopeNode.kind === 194 || + scopeNode.kind === 252 || + ts.isStatement(scopeNode); + } var symbolMeanings = 793064 | 107455 | 1920 | 8388608; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; @@ -51521,15 +55359,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 244) { + if (contextToken.kind === 10) { return true; } - if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 243) { + if (contextToken.kind === 28 && contextToken.parent) { + if (contextToken.parent.kind === 248) { return true; } - if (contextToken.parent.kind === 245 || contextToken.parent.kind === 242) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241; + if (contextToken.parent.kind === 249 || contextToken.parent.kind === 247) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 246; } } return false; @@ -51538,41 +55376,41 @@ var ts; if (previousToken) { var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { - case 24: - return containingNodeKind === 174 - || containingNodeKind === 148 + case 25: + return containingNodeKind === 179 + || containingNodeKind === 150 + || containingNodeKind === 180 || containingNodeKind === 175 - || containingNodeKind === 170 - || containingNodeKind === 187 - || containingNodeKind === 156; - case 17: - return containingNodeKind === 174 - || containingNodeKind === 148 - || containingNodeKind === 175 - || containingNodeKind === 178 - || containingNodeKind === 164; - case 19: - return containingNodeKind === 170 - || containingNodeKind === 153 - || containingNodeKind === 140; - case 125: - case 126: + || containingNodeKind === 192 + || containingNodeKind === 158; + case 18: + return containingNodeKind === 179 + || containingNodeKind === 150 + || containingNodeKind === 180 + || containingNodeKind === 183 + || containingNodeKind === 166; + case 20: + return containingNodeKind === 175 + || containingNodeKind === 155 + || containingNodeKind === 142; + case 127: + case 128: return true; - case 21: - return containingNodeKind === 225; - case 15: - return containingNodeKind === 221; - case 56: - return containingNodeKind === 218 - || containingNodeKind === 187; - case 12: - return containingNodeKind === 189; + case 22: + return containingNodeKind === 230; + case 16: + return containingNodeKind === 226; + case 57: + return containingNodeKind === 223 + || containingNodeKind === 192; case 13: - return containingNodeKind === 197; - case 112: - case 110: + return containingNodeKind === 194; + case 14: + return containingNodeKind === 202; + case 113: case 111: - return containingNodeKind === 145; + case 112: + return containingNodeKind === 147; } switch (previousToken.getText()) { case "public": @@ -51585,7 +55423,7 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 - || contextToken.kind === 10 + || contextToken.kind === 11 || ts.isTemplateLiteralKind(contextToken.kind)) { var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); @@ -51594,7 +55432,7 @@ var ts; } if (position === end) { return !!contextToken.isUnterminated - || contextToken.kind === 10; + || contextToken.kind === 11; } } return false; @@ -51603,22 +55441,22 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 171) { + if (objectLikeContainer.kind === 176) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 167) { + else if (objectLikeContainer.kind === 172) { isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142) { + if (!canGetType && rootDeclaration.kind === 144) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 147 || rootDeclaration.parent.kind === 150) { + else if (rootDeclaration.parent.kind === 149 || rootDeclaration.parent.kind === 152) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -51644,9 +55482,9 @@ var ts; return true; } function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 ? - 230 : - 236; + var declarationKind = namedImportsOrExports.kind === 238 ? + 235 : + 241; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -51665,11 +55503,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15: - case 24: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 || parent_18.kind === 167)) { - return parent_18; + case 16: + case 25: + var parent_15 = contextToken.parent; + if (parent_15 && (parent_15.kind === 176 || parent_15.kind === 172)) { + return parent_15; } break; } @@ -51679,11 +55517,11 @@ var ts; function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15: - case 24: + case 16: + case 25: switch (contextToken.parent.kind) { - case 233: - case 237: + case 238: + case 242: return contextToken.parent; } } @@ -51692,34 +55530,34 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_19 = contextToken.parent; + var parent_16 = contextToken.parent; switch (contextToken.kind) { - case 26: - case 39: - case 69: - case 246: - case 247: - if (parent_19 && (parent_19.kind === 242 || parent_19.kind === 243)) { - return parent_19; + case 27: + case 40: + case 70: + case 250: + case 251: + if (parent_16 && (parent_16.kind === 247 || parent_16.kind === 248)) { + return parent_16; } - else if (parent_19.kind === 246) { - return parent_19.parent; + else if (parent_16.kind === 250) { + return parent_16.parent; } break; case 9: - if (parent_19 && ((parent_19.kind === 246) || (parent_19.kind === 247))) { - return parent_19.parent; + if (parent_16 && ((parent_16.kind === 250) || (parent_16.kind === 251))) { + return parent_16.parent; } break; - case 16: - if (parent_19 && - parent_19.kind === 248 && - parent_19.parent && - (parent_19.parent.kind === 246)) { - return parent_19.parent.parent; + case 17: + if (parent_16 && + parent_16.kind === 252 && + parent_16.parent && + (parent_16.parent.kind === 250)) { + return parent_16.parent.parent; } - if (parent_19 && parent_19.kind === 247) { - return parent_19.parent; + if (parent_16 && parent_16.kind === 251) { + return parent_16.parent; } break; } @@ -51728,16 +55566,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 179: - case 180: - case 220: - case 147: - case 146: + case 184: + case 185: + case 225: case 149: - case 150: + case 148: case 151: case 152: case 153: + case 154: + case 155: return true; } return false; @@ -51745,67 +55583,67 @@ var ts; function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { - case 24: - return containingNodeKind === 218 || - containingNodeKind === 219 || - containingNodeKind === 200 || - containingNodeKind === 224 || - isFunction(containingNodeKind) || - containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 168 || - containingNodeKind === 223; - case 21: - return containingNodeKind === 168; - case 54: - return containingNodeKind === 169; - case 19: - return containingNodeKind === 168; - case 17: - return containingNodeKind === 252 || - isFunction(containingNodeKind); - case 15: - return containingNodeKind === 224 || - containingNodeKind === 222 || - containingNodeKind === 159; - case 23: - return containingNodeKind === 144 && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 || - contextToken.parent.parent.kind === 159); case 25: - return containingNodeKind === 221 || - containingNodeKind === 192 || - containingNodeKind === 222 || - containingNodeKind === 223 || - isFunction(containingNodeKind); - case 113: - return containingNodeKind === 145; + return containingNodeKind === 223 || + containingNodeKind === 224 || + containingNodeKind === 205 || + containingNodeKind === 229 || + isFunction(containingNodeKind) || + containingNodeKind === 226 || + containingNodeKind === 197 || + containingNodeKind === 227 || + containingNodeKind === 173 || + containingNodeKind === 228; case 22: - return containingNodeKind === 142 || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168); - case 112: - case 110: - case 111: - return containingNodeKind === 142; - case 116: - return containingNodeKind === 234 || - containingNodeKind === 238 || - containingNodeKind === 232; - case 73: - case 81: - case 107: - case 87: - case 102: - case 123: - case 131: - case 89: - case 108: - case 74: + return containingNodeKind === 173; + case 55: + return containingNodeKind === 174; + case 20: + return containingNodeKind === 173; + case 18: + return containingNodeKind === 256 || + isFunction(containingNodeKind); + case 16: + return containingNodeKind === 229 || + containingNodeKind === 227 || + containingNodeKind === 161; + case 24: + return containingNodeKind === 146 && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 227 || + contextToken.parent.parent.kind === 161); + case 26: + return containingNodeKind === 226 || + containingNodeKind === 197 || + containingNodeKind === 227 || + containingNodeKind === 228 || + isFunction(containingNodeKind); case 114: - case 134: + return containingNodeKind === 147; + case 23: + return containingNodeKind === 144 || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 173); + case 113: + case 111: + case 112: + return containingNodeKind === 144; + case 117: + return containingNodeKind === 239 || + containingNodeKind === 243 || + containingNodeKind === 237; + case 74: + case 82: + case 108: + case 88: + case 103: + case 124: + case 133: + case 90: + case 109: + case 75: + case 115: + case 136: return true; } switch (contextToken.getText()) { @@ -51842,8 +55680,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_46 = element.propertyName || element.name; + existingImportsOrExports[name_46.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51857,18 +55695,20 @@ var ts; var existingMemberNames = ts.createMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 253 && - m.kind !== 254 && - m.kind !== 169 && - m.kind !== 147) { + if (m.kind !== 257 && + m.kind !== 258 && + m.kind !== 174 && + m.kind !== 149 && + m.kind !== 151 && + m.kind !== 152) { continue; } if (m.getStart() <= position && position <= m.getEnd()) { continue; } var existingName = void 0; - if (m.kind === 169 && m.propertyName) { - if (m.propertyName.kind === 69) { + if (m.kind === 174 && m.propertyName) { + if (m.propertyName.kind === 70) { existingName = m.propertyName.text; } } @@ -51886,7 +55726,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 246) { + if (attr.kind === 250) { seenNames[attr.name.text] = true; } } @@ -51919,7 +55759,7 @@ var ts; return name; } var keywordCompletions = []; - for (var i = 70; i <= 138; i++) { + for (var i = 71; i <= 140; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ts.ScriptElementKind.keyword, @@ -51927,7 +55767,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104)) { + if (pushKeywordIf(keywords, loopTokens[i], 105)) { break; } } @@ -52330,7 +56170,7 @@ var ts; var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70, 75); + pushKeywordIf(keywords, statement.getFirstToken(), 71, 76); } }); return ts.map(keywords, getHighlightSpanForNode); @@ -52339,13 +56179,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 206: - case 207: - case 208: - case 204: - case 205: - return getLoopBreakContinueOccurrences(owner); + case 211: + case 212: case 213: + case 209: + case 210: + return getLoopBreakContinueOccurrences(owner); + case 218: return getSwitchCaseDefaultOccurrences(owner); } } @@ -52353,13 +56193,13 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 97); ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71, 77); + pushKeywordIf(keywords, clause.getFirstToken(), 72, 78); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70); + pushKeywordIf(keywords, statement.getFirstToken(), 71); } }); }); @@ -52367,13 +56207,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 101); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 86); } return ts.map(keywords, getHighlightSpanForNode); } @@ -52384,50 +56224,50 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99); }); if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95); }); } return ts.map(keywords, getHighlightSpanForNode); } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 199))) { + if (!(func && hasKind(func.body, 204))) { return undefined; } var keywords = []; ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95); }); ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99); }); return ts.map(keywords, getHighlightSpanForNode); } function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 203) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 208) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88); + pushKeywordIf(keywords, children[0], 89); for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80)) { + if (pushKeywordIf(keywords, children[i], 81)) { break; } } - if (!hasKind(ifStatement.elseStatement, 203)) { + if (!hasKind(ifStatement.elseStatement, 208)) { break; } ifStatement = ifStatement.elseStatement; } var result = []; for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 && i < keywords.length - 1) { + if (keywords[i].kind === 81 && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; var shouldCombindElseAndIf = true; @@ -52455,7 +56295,7 @@ var ts; } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 219; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -52580,9 +56420,9 @@ var ts; if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { break; } - case 69: - case 97: - case 121: + case 70: + case 98: + case 122: case 9: return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, false); } @@ -52603,7 +56443,7 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } - if (node.kind === 95) { + if (node.kind === 96) { return getReferencesForSuperKeyword(node); } } @@ -52628,9 +56468,9 @@ var ts; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var internedName = getInternedName(symbol, node); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = ts.getNameTable(sourceFile); if (nameTable[internedName] !== undefined) { @@ -52659,16 +56499,16 @@ var ts; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { if (symbol.flags & 8388608) { - var defaultImport = ts.getDeclarationOfKind(symbol, 231); + var defaultImport = ts.getDeclarationOfKind(symbol, 236); if (defaultImport) { return typeChecker.getAliasedSymbol(symbol); } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 || - declaration.kind === 238) ? declaration : undefined; }); + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 239 || + declaration.kind === 243) ? declaration : undefined; }); if (importOrExportSpecifier && (!importOrExportSpecifier.propertyName || importOrExportSpecifier.propertyName === location)) { - return importOrExportSpecifier.kind === 234 ? + return importOrExportSpecifier.kind === 239 ? typeChecker.getAliasedSymbol(symbol) : typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); } @@ -52683,20 +56523,20 @@ var ts; typeChecker.getPropertySymbolOfDestructuringAssignment(location); } function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var bindingElement = ts.getDeclarationOfKind(symbol, 174); return bindingElement && - bindingElement.parent.kind === 167 && + bindingElement.parent.kind === 172 && !bindingElement.propertyName; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169); + var bindingElement = ts.getDeclarationOfKind(symbol, 174); var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } return undefined; } - function getInternedName(symbol, location, declarations) { + function getInternedName(symbol, location) { if (ts.isImportOrExportSpecifierName(location)) { return location.getText(); } @@ -52706,13 +56546,13 @@ var ts; } function getSymbolScope(symbol) { var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 || valueDeclaration.kind === 192)) { + if (valueDeclaration && (valueDeclaration.kind === 184 || valueDeclaration.kind === 197)) { return valueDeclaration; } if (symbol.flags & (4 | 8192)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221); + return ts.getAncestor(privateDeclaration, 226); } } if (symbol.flags & 8388608) { @@ -52736,7 +56576,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (container.kind === 256 && !ts.isExternalModule(container)) { + if (container.kind === 261 && !ts.isExternalModule(container)) { return undefined; } scope = container; @@ -52758,8 +56598,8 @@ var ts; if (position > end) break; var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5))) { positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); @@ -52796,7 +56636,7 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { if (node) { switch (node.kind) { - case 69: + case 70: return node.getWidth() === searchSymbolName.length; case 9: if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || @@ -52846,14 +56686,14 @@ var ts; if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 121, parents, inheritsFromCache); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, searchLocation.kind === 122, parents, inheritsFromCache); if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } else if (!(referenceSymbol.flags & 67108864) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } - else if (searchLocation.kind === 121) { + else if (searchLocation.kind === 122) { findAdditionalConstructorReferences(referenceSymbol, referenceLocation); } } @@ -52869,7 +56709,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== searchSymbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 1572864) { + else if (localParentType.flags & 196608) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -52903,17 +56743,17 @@ var ts; var result = []; for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148); + ts.Debug.assert(decl.kind === 150); var ctrKeyword = decl.getChildAt(0); - ts.Debug.assert(ctrKeyword.kind === 121); + ts.Debug.assert(ctrKeyword.kind === 122); result.push(ctrKeyword); } ts.forEachProperty(classSymbol.exports, function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 147) { + if (decl && decl.kind === 149) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97, function (thisKeyword) { + forEachDescendantOfKind(body, 98, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { result.push(thisKeyword); } @@ -52932,10 +56772,10 @@ var ts; var result = []; for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148); + ts.Debug.assert(decl.kind === 150); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 95, function (node) { + forEachDescendantOfKind(body, 96, function (node) { if (ts.isCallExpressionTarget(node)) { result.push(node); } @@ -52972,8 +56812,8 @@ var ts; if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { result.push(getReferenceEntryFromNode(refNode.parent)); } - else if (refNode.kind === 69) { - if (refNode.parent.kind === 254) { + else if (refNode.kind === 70) { + if (refNode.parent.kind === 258) { getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); } var containingClass = getContainingClassIfInHeritageClause(refNode); @@ -52983,24 +56823,24 @@ var ts; } var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference) { - var parent_21 = containingTypeReference.parent; - if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { - maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + var parent_18 = containingTypeReference.parent; + if (ts.isVariableLike(parent_18) && parent_18.type === containingTypeReference && parent_18.initializer && isImplementationExpression(parent_18.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_18.initializer)); } - else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { - if (parent_21.body.kind === 199) { - ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + else if (ts.isFunctionLike(parent_18) && parent_18.type === containingTypeReference && parent_18.body) { + if (parent_18.body.kind === 204) { + ts.forEachReturnStatement(parent_18.body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); } }); } - else if (isImplementationExpression(parent_21.body)) { - maybeAdd(getReferenceEntryFromNode(parent_21.body)); + else if (isImplementationExpression(parent_18.body)) { + maybeAdd(getReferenceEntryFromNode(parent_18.body)); } } - else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { - maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + else if (ts.isAssertionExpression(parent_18) && isImplementationExpression(parent_18.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_18.expression)); } } } @@ -53017,7 +56857,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 1572864) { + if (componentType.getFlags() & 196608) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -53035,26 +56875,26 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 194 - && node.parent.kind === 251 + if (node.kind === 199 + && node.parent.kind === 255 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 69 || node.kind === 172) { + else if (node.kind === 70 || node.kind === 177) { return getContainingClassIfInHeritageClause(node.parent); } } return undefined; } function isImplementationExpression(node) { - if (node.kind === 178) { + if (node.kind === 183) { return isImplementationExpression(node.expression); } - return node.kind === 180 || - node.kind === 179 || - node.kind === 171 || - node.kind === 192 || - node.kind === 170; + return node.kind === 185 || + node.kind === 184 || + node.kind === 176 || + node.kind === 197 || + node.kind === 175; } function explicitlyInheritsFrom(child, parent, cachedResults) { var parentIsInterface = parent.getFlags() & 64; @@ -53083,7 +56923,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 222) { + else if (declaration.kind === 227) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -53110,13 +56950,13 @@ var ts; } var staticFlag = 32; switch (searchSpaceNode.kind) { - case 145: - case 144: case 147: case 146: - case 148: case 149: + case 148: case 150: + case 151: + case 152: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; @@ -53129,7 +56969,7 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95) { + if (!node || node.kind !== 96) { return; } var container = ts.getSuperContainer(node, false); @@ -53144,32 +56984,32 @@ var ts; var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); var staticFlag = 32; switch (searchSpaceNode.kind) { - case 147: - case 146: + case 149: + case 148: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } - case 145: - case 144: - case 148: - case 149: + case 147: + case 146: case 150: + case 151: + case 152: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; - case 256: + case 261: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 220: - case 179: + case 225: + case 184: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 256) { + if (searchSpaceNode.kind === 261) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -53203,26 +57043,26 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 179: - case 220: + case 184: + case 225: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 147: - case 146: + case 149: + case 148: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 192: - case 221: + case 197: + case 226: if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 256: - if (container.kind === 256 && !ts.isExternalModule(container)) { + case 261: + if (container.kind === 261 && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -53236,8 +57076,8 @@ var ts; return undefined; } var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var sourceFile = sourceFiles_9[_i]; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); } @@ -53271,7 +57111,7 @@ var ts; function populateSearchSymbolSet(symbol, location) { var result = [symbol]; var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254) { + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 258) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); if (propertySymbol) { result.push(propertySymbol); @@ -53290,7 +57130,7 @@ var ts; result.push(shorthandValueSymbol); } } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 && + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 144 && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); } @@ -53321,7 +57161,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 222) { + else if (declaration.kind === 227) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -53376,17 +57216,17 @@ var ts; return undefined; } } - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, ts.createMap()); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, ts.createMap()); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140) { + if (node.name.kind === 142) { var nameExpression = node.name.expression; - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } return undefined; @@ -53398,20 +57238,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_4 = []; + var result_5 = []; var symbol_2 = contextualType.getProperty(name); if (symbol_2) { - result_4.push(symbol_2); + result_5.push(symbol_2); } - if (contextualType.flags & 524288) { + if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); } - return result_4; + return result_5; } return undefined; } @@ -53453,7 +57293,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 218) { + else if (node.kind === 223) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2); } @@ -53463,18 +57303,18 @@ var ts; } else { switch (node.kind) { - case 221: - case 192: - case 224: - case 225: + case 226: + case 197: + case 229: + case 230: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 200) { - ts.Debug.assert(node.parent.kind === 219); + if (node.parent && node.parent.parent && node.parent.parent.kind === 205) { + ts.Debug.assert(node.parent.kind === 224); return node.parent.parent; } } @@ -53507,17 +57347,17 @@ var ts; } FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; function isWriteAccess(node) { - if (node.kind === 69 && ts.isDeclarationName(node)) { + if (node.kind === 70 && ts.isDeclarationName(node)) { return true; } var parent = node.parent; if (parent) { - if (parent.kind === 186 || parent.kind === 185) { + if (parent.kind === 191 || parent.kind === 190) { return true; } - else if (parent.kind === 187 && parent.left === node) { + else if (parent.kind === 192 && parent.left === node) { var operator = parent.operatorToken.kind; - return 56 <= operator && operator <= 68; + return 57 <= operator && operator <= 69; } } return false; @@ -53534,21 +57374,21 @@ var ts; switch (node.kind) { case 9: case 8: - if (node.parent.kind === 140) { + if (node.parent.kind === 142) { return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; } - case 69: + case 70: return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; } return undefined; } function isObjectLiteralPropertyDeclaration(node) { switch (node.kind) { - case 253: - case 254: - case 147: + case 257: + case 258: case 149: - case 150: + case 151: + case 152: return true; } return false; @@ -53605,13 +57445,13 @@ var ts; } if (symbol.flags & 8388608) { var declaration = symbol.declarations[0]; - if (node.kind === 69 && + if (node.kind === 70 && (node.parent === declaration || - (declaration.kind === 234 && declaration.parent && declaration.parent.kind === 233))) { + (declaration.kind === 239 && declaration.parent && declaration.parent.kind === 238))) { symbol = typeChecker.getAliasedSymbol(symbol); } } - if (node.parent.kind === 254) { + if (node.parent.kind === 258) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -53638,14 +57478,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 && !(type.flags & 16)) { - var result_5 = []; + if (type.flags & 65536 && !(type.flags & 16)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_5, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_5; + return result_6; } if (!type.symbol) { return undefined; @@ -53665,7 +57505,7 @@ var ts; } return result; function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isNewExpressionTarget(location) || location.kind === 121) { + if (ts.isNewExpressionTarget(location) || location.kind === 122) { if (symbol.flags & 32) { for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; @@ -53688,8 +57528,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148) || - (!selectConstructors && (d.kind === 220 || d.kind === 147 || d.kind === 146))) { + if ((selectConstructors && d.kind === 150) || + (!selectConstructors && (d.kind === 225 || d.kind === 149 || d.kind === 148))) { declarations.push(d); if (d.body) definition = d; @@ -53765,12 +57605,12 @@ var ts; var GoToImplementation; (function (GoToImplementation) { function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { - if (node.parent.kind === 254) { + if (node.parent.kind === 258) { var result = []; ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); return result.length > 0 ? result : undefined; } - else if (node.kind === 95 || ts.isSuperProperty(node.parent)) { + else if (node.kind === 96 || ts.isSuperProperty(node.parent)) { var symbol = typeChecker.getSymbolAtLocation(node); return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; } @@ -53815,6 +57655,7 @@ var ts; "lends", "link", "memberOf", + "method", "name", "namespace", "param", @@ -53834,10 +57675,10 @@ var ts; "version" ]; var jsDocCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getJSDocComments(declaration, true); + var comments = ts.getCommentsFromJSDoc(declaration); if (!comments) { return; } @@ -53873,7 +57714,7 @@ var ts; name: tagName, kind: ts.ScriptElementKind.keyword, kindModifiers: "", - sortText: "0" + sortText: "0", }; })); } @@ -53890,16 +57731,16 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 220: - case 147: - case 148: - case 221: - case 200: - break findOwner; - case 256: - return undefined; case 225: - if (commentOwner.parent.kind === 225) { + case 149: + case 150: + case 226: + case 205: + break findOwner; + case 261: + return undefined; + case 230: + if (commentOwner.parent.kind === 230) { return undefined; } break findOwner; @@ -53912,13 +57753,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; - var paramName = currentName.kind === 69 ? + var paramName = currentName.kind === 70 ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } var preamble = "/**" + newLine + indentationStr + " * "; @@ -53933,7 +57780,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 200) { + if (commentOwner.kind === 205) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -53943,17 +57790,17 @@ var ts; return ts.emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178) { + while (rightHandSide.kind === 183) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 179: - case 180: + case 184: + case 185: return rightHandSide.parameters; - case 192: + case 197: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 150) { return member.parameters; } } @@ -53964,160 +57811,22 @@ var ts; })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); })(ts || (ts = {})); var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_48 in packageNameToTypingLocation) { - if (name_48 in inferredTypings && !inferredTypings[name_48]) { - inferredTypings[name_48] = packageNameToTypingLocation[name_48]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - 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; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var baseSensitivity = { sensitivity: "base" }; ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_49 in nameToDeclarations) { - var declarations = nameToDeclarations[name_49]; + for (var name_47 in nameToDeclarations) { + var declarations = nameToDeclarations[name_47]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_49); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_47); if (!matches) { continue; } @@ -54128,21 +57837,21 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_49); + matches = patternMatcher.getMatches(containers, name_47); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_47, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } }); rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; - if (decl.kind === 231 || decl.kind === 234 || decl.kind === 229) { + if (decl.kind === 236 || decl.kind === 239 || decl.kind === 234) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; @@ -54169,7 +57878,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || node.kind === 8) { return node.text; @@ -54183,7 +57892,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 140) { + else if (declaration.name.kind === 142) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -54200,7 +57909,7 @@ var ts; } return true; } - if (expression.kind === 172) { + if (expression.kind === 177) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -54211,7 +57920,7 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 140) { + if (declaration.name.kind === 142) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -54239,8 +57948,8 @@ var ts; } function compareNavigateToItems(i1, i2) { return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -54272,6 +57981,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; var curSourceFile; function nodeText(node) { return node.getText(curSourceFile); @@ -54336,7 +58052,7 @@ var ts; return; } switch (node.kind) { - case 148: + case 150: var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { @@ -54346,28 +58062,28 @@ var ts; } } break; - case 147: case 149: - case 150: - case 146: + case 151: + case 152: + case 148: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 145: - case 144: + case 147: + case 146: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 231: + case 236: var importClause = node; if (importClause.name) { addLeafNode(importClause); } var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 232) { + if (namedBindings.kind === 237) { addLeafNode(namedBindings); } else { @@ -54378,12 +58094,12 @@ var ts; } } break; - case 169: - case 218: + case 174: + case 223: var decl = node; - var name_50 = decl.name; - if (ts.isBindingPattern(name_50)) { - addChildrenRecursively(name_50); + var name_48 = decl.name; + if (ts.isBindingPattern(name_48)) { + addChildrenRecursively(name_48); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -54392,12 +58108,12 @@ var ts; addNodeWithRecursiveChild(decl, decl.initializer); } break; - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: addNodeWithRecursiveChild(node, node.body); break; - case 224: + case 229: startNode(node); for (var _d = 0, _e = node.members; _d < _e.length; _d++) { var member = _e[_d]; @@ -54407,9 +58123,9 @@ var ts; } endNode(); break; - case 221: - case 192: - case 222: + case 226: + case 197: + case 227: startNode(node); for (var _f = 0, _g = node.members; _f < _g.length; _f++) { var member = _g[_f]; @@ -54417,21 +58133,21 @@ var ts; } endNode(); break; - case 225: + case 230: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 238: - case 229: + case 243: + case 234: + case 155: case 153: - case 151: - case 152: - case 223: + case 154: + case 228: addLeafNode(node); break; default: - ts.forEach(node.jsDocComments, function (jsDocComment) { - ts.forEach(jsDocComment.tags, function (tag) { - if (tag.kind === 279) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 285) { addLeafNode(tag); } }); @@ -54479,12 +58195,12 @@ var ts; } }); function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + return a.kind === b.kind && (a.kind !== 230 || areSameModule(a, b)); function areSameModule(a, b) { if (a.body.kind !== b.body.kind) { return false; } - if (a.body.kind !== 225) { + if (a.body.kind !== 230) { return true; } return areSameModule(a.body, b.body); @@ -54517,9 +58233,8 @@ var ts; 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) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.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 === "'") { @@ -54528,7 +58243,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -54536,7 +58251,7 @@ var ts; return a.length - b.length; }; function tryGetName(node) { - if (node.kind === 225) { + if (node.kind === 230) { return getModuleName(node); } var decl = node; @@ -54544,18 +58259,18 @@ var ts; return ts.getPropertyNameForPropertyNameNode(decl.name); } switch (node.kind) { - case 179: - case 180: - case 192: + case 184: + case 185: + case 197: return getFunctionOrClassName(node); - case 279: + case 285: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 225) { + if (node.kind === 230) { return getModuleName(node); } var name = node.name; @@ -54566,29 +58281,29 @@ var ts; } } switch (node.kind) { - case 256: + case 261: 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: + case 185: + case 225: + case 184: + case 226: + case 197: if (ts.getModifierFlags(node) & 512) { return "default"; } return getFunctionOrClassName(node); - case 148: + case 150: return "constructor"; - case 152: + case 154: return "new()"; - case 151: - return "()"; case 153: + return "()"; + case 155: return "[]"; - case 279: + case 285: return getJSDocTypedefTagName(node); default: return ""; @@ -54600,10 +58315,10 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { + if (parentNode && parentNode.kind === 205) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { + if (nameIdentifier.kind === 70) { return nameIdentifier.text; } } @@ -54628,24 +58343,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 221: - case 192: - case 224: - case 222: - case 225: - case 256: - case 223: - case 279: + case 226: + case 197: + case 229: + case 227: + case 230: + case 261: + case 228: + case 285: return true; - case 148: - case 147: - case 149: case 150: - case 218: + case 149: + case 151: + case 152: + case 223: return hasSomeImportantChild(item); - case 180: - case 220: - case 179: + case 185: + case 225: + case 184: return isTopLevelFunctionDeclaration(item); default: return false; @@ -54655,10 +58370,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 226: - case 256: - case 147: - case 148: + case 231: + case 261: + case 149: + case 150: return true; default: return hasSomeImportantChild(item); @@ -54667,12 +58382,21 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 218 && childKind !== 169; + return childKind !== 223 && childKind !== 174; }); } } } var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -54696,16 +58420,16 @@ var ts; grayed: false }; } - 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)); - } + } + 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 spans; } + return spans; } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { @@ -54713,20 +58437,20 @@ var ts; } var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 230) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } return result.join("."); } function getInteriorModule(decl) { - return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 230 ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 140; + return !member.name || member.name.kind === 142; } function getNodeSpan(node) { - return node.kind === 256 + return node.kind === 261 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); } @@ -54734,14 +58458,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 218) { + else if (node.parent.kind === 223) { 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 === 192 && + node.parent.operatorToken.kind === 57) { + return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 253 && node.parent.name) { + else if (node.parent.kind === 257 && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512) { @@ -54752,8 +58476,9 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 179 || node.kind === 180 || node.kind === 192; + return node.kind === 184 || node.kind === 185 || node.kind === 197; } + var whiteSpaceRegex = /\s+/g; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -54824,7 +58549,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180; + return ts.isFunctionBlock(node) && node.parent.kind !== 185; } var depth = 0; var maxDepth = 20; @@ -54836,30 +58561,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 199: + case 204: if (!ts.isFunctionBlock(n)) { - var parent_22 = n.parent; - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_22.kind === 204 || - parent_22.kind === 207 || - parent_22.kind === 208 || - parent_22.kind === 206 || - parent_22.kind === 203 || - parent_22.kind === 205 || - parent_22.kind === 212 || - parent_22.kind === 252) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + var parent_19 = n.parent; + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); + if (parent_19.kind === 209 || + parent_19.kind === 212 || + parent_19.kind === 213 || + parent_19.kind === 211 || + parent_19.kind === 208 || + parent_19.kind === 210 || + parent_19.kind === 217 || + parent_19.kind === 256) { + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_22.kind === 216) { - var tryStatement = parent_22; + if (parent_19.kind === 221) { + var tryStatement = parent_19; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85, sourceFile); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86, sourceFile); if (finallyKeyword) { addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); break; @@ -54875,25 +58600,25 @@ var ts; }); break; } - case 226: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + case 231: { + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 221: - case 222: - case 224: - case 171: - case 227: { - var openBrace = ts.findChildOfKind(n, 15, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16, sourceFile); + case 226: + case 227: + case 229: + case 176: + case 232: { + var openBrace = ts.findChildOfKind(n, 16, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 170: - var openBracket = ts.findChildOfKind(n, 19, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20, sourceFile); + case 175: + var openBracket = ts.findChildOfKind(n, 20, sourceFile); + var closeBracket = ts.findChildOfKind(n, 21, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); break; } @@ -54909,13 +58634,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var PatternMatchKind; (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; - })(ts.PatternMatchKind || (ts.PatternMatchKind = {})); - var PatternMatchKind = ts.PatternMatchKind; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { return { kind: kind, @@ -55136,7 +58861,7 @@ var ts; if (ch >= 65 && ch <= 90) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 2)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { return false; } var str = String.fromCharCode(ch); @@ -55146,7 +58871,7 @@ var ts; if (ch >= 97 && ch <= 122) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 2)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { return false; } var str = String.fromCharCode(ch); @@ -55329,10 +59054,10 @@ var ts; var externalModule = false; function nextToken() { var token = ts.scanner.scan(); - if (token === 15) { + if (token === 16) { braceNesting++; } - else if (token === 16) { + else if (token === 17) { braceNesting--; } return token; @@ -55380,9 +59105,9 @@ var ts; } function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 122) { + if (token === 123) { token = nextToken(); - if (token === 125) { + if (token === 127) { token = nextToken(); if (token === 9) { recordAmbientExternalModule(); @@ -55394,42 +59119,42 @@ var ts; } function tryConsumeImport() { var token = ts.scanner.getToken(); - if (token === 89) { + if (token === 90) { token = nextToken(); if (token === 9) { recordModuleName(); return true; } else { - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); return true; } } - else if (token === 56) { + else if (token === 57) { if (tryConsumeRequireCall(true)) { return true; } } - else if (token === 24) { + else if (token === 25) { token = nextToken(); } else { return true; } } - if (token === 15) { + if (token === 16) { token = nextToken(); - while (token !== 16 && token !== 1) { + while (token !== 17 && token !== 1) { token = nextToken(); } - if (token === 16) { + if (token === 17) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55437,13 +59162,13 @@ var ts; } } } - else if (token === 37) { + else if (token === 38) { token = nextToken(); - if (token === 116) { + if (token === 117) { token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55459,17 +59184,17 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 82) { + if (token === 83) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 15) { + if (token === 16) { token = nextToken(); - while (token !== 16 && token !== 1) { + while (token !== 17 && token !== 1) { token = nextToken(); } - if (token === 16) { + if (token === 17) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55477,20 +59202,20 @@ var ts; } } } - else if (token === 37) { + else if (token === 38) { token = nextToken(); - if (token === 136) { + if (token === 138) { token = nextToken(); if (token === 9) { recordModuleName(); } } } - else if (token === 89) { + else if (token === 90) { token = nextToken(); - if (token === 69 || ts.isKeyword(token)) { + if (token === 70 || ts.isKeyword(token)) { token = nextToken(); - if (token === 56) { + if (token === 57) { if (tryConsumeRequireCall(true)) { return true; } @@ -55503,9 +59228,9 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 129) { + if (token === 131) { token = nextToken(); - if (token === 17) { + if (token === 18) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -55517,27 +59242,27 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 69 && ts.scanner.getTokenValue() === "define") { + if (token === 70 && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 17) { + if (token !== 18) { return true; } token = nextToken(); if (token === 9) { token = nextToken(); - if (token === 24) { + if (token === 25) { token = nextToken(); } else { return true; } } - if (token !== 19) { + if (token !== 20) { return true; } token = nextToken(); var i = 0; - while (token !== 20 && token !== 1) { + while (token !== 21 && token !== 1) { if (token === 9) { recordModuleName(); i++; @@ -55609,7 +59334,7 @@ var ts; var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); var node = ts.getTouchingWord(sourceFile, position, true); if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || ts.isThis(node)) { @@ -55722,14 +59447,14 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 174) { + if (argumentInfo.invocation.kind !== 179) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; - var name = expression.kind === 69 + var name = expression.kind === 70 ? expression - : expression.kind === 172 + : expression.kind === 177 ? expression.name : undefined; if (!name || !name.text) { @@ -55758,10 +59483,10 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 174 || node.parent.kind === 175) { + if (node.parent.kind === 179 || node.parent.kind === 180) { var callExpression = node.parent; - if (node.kind === 25 || - node.kind === 17) { + if (node.kind === 26 || + node.kind === 18) { var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; ts.Debug.assert(list !== undefined); @@ -55790,24 +59515,24 @@ var ts; } return undefined; } - else if (node.kind === 11 && node.parent.kind === 176) { + else if (node.kind === 12 && node.parent.kind === 181) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0, sourceFile); } } - else if (node.kind === 12 && node.parent.parent.kind === 176) { + else if (node.kind === 13 && node.parent.parent.kind === 181) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189); + ts.Debug.assert(templateExpression.kind === 194); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 197 && node.parent.parent.parent.kind === 176) { + else if (node.parent.kind === 202 && node.parent.parent.parent.kind === 181) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189); - if (node.kind === 14 && !ts.isInsideTemplateLiteral(node, position)) { + ts.Debug.assert(templateExpression.kind === 194); + if (node.kind === 15 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); @@ -55824,7 +59549,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 24) { + if (child.kind !== 25) { argumentIndex++; } } @@ -55832,8 +59557,8 @@ var ts; } function getArgumentCount(argumentsList) { var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 24; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 24) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 25; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 25) { argumentCount++; } return argumentCount; @@ -55849,7 +59574,7 @@ var ts; return spanIndex + 1; } function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { - var argumentCount = tagExpression.template.kind === 11 + var argumentCount = tagExpression.template.kind === 12 ? 1 : tagExpression.template.templateSpans.length + 1; ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); @@ -55870,7 +59595,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 189) { + if (template.kind === 194) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -55879,7 +59604,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 256; n = n.parent) { + for (var n = node; n.kind !== 261; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -55929,35 +59654,38 @@ var ts; if (callTargetDisplayParts) { ts.addRange(prefixDisplayParts, callTargetDisplayParts); } + var isVariadic; if (isTypeParameterList) { - prefixDisplayParts.push(ts.punctuationPart(25)); + isVariadic = false; + prefixDisplayParts.push(ts.punctuationPart(26)); var typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(27)); + suffixDisplayParts.push(ts.punctuationPart(28)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); }); ts.addRange(suffixDisplayParts, parameterParts); } else { + isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); }); ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(17)); + prefixDisplayParts.push(ts.punctuationPart(18)); var parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(18)); + suffixDisplayParts.push(ts.punctuationPart(19)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); }); ts.addRange(suffixDisplayParts, returnTypeParts); return { - isVariadic: candidateSignature.hasRestParameter, + isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(24), ts.spacePart()], + separatorDisplayParts: [ts.punctuationPart(25), ts.spacePart()], parameters: signatureHelpParameters, documentation: candidateSignature.getDocumentationComment() }; @@ -56008,7 +59736,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = symbol.getFlags(); if (flags & 32) - return ts.getDeclarationOfKind(symbol, 192) ? + return ts.getDeclarationOfKind(symbol, 197) ? ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; if (flags & 384) return ts.ScriptElementKind.enumElement; @@ -56039,7 +59767,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return ts.ScriptElementKind.localVariableElement; } - if (location.kind === 97 && ts.isExpression(location)) { + if (location.kind === 98 && ts.isExpression(location)) { return ts.ScriptElementKind.parameterElement; } if (flags & 3) { @@ -56099,7 +59827,7 @@ var ts; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 && ts.isExpression(location); + var isThisExpression = location.kind === 98 && ts.isExpression(location); var type; if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { @@ -56108,14 +59836,14 @@ var ts; var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 172) { + if (location.parent && location.parent.kind === 177) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } var callExpression = void 0; - if (location.kind === 174 || location.kind === 175) { + if (location.kind === 179 || location.kind === 180) { callExpression = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -56127,7 +59855,7 @@ var ts; if (!signature && candidateSignatures.length) { signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 175 || callExpression.expression.kind === 95; + var useConstructSignatures = callExpression.kind === 180 || callExpression.expression.kind === 96; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -56142,7 +59870,7 @@ var ts; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -56157,13 +59885,13 @@ var ts; case ts.ScriptElementKind.letElement: case ts.ScriptElementKind.parameterElement: case ts.ScriptElementKind.localVariableElement: - displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.punctuationPart(55)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152) && type.symbol) { + if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -56175,21 +59903,21 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 121 && location.parent.kind === 148)) { + (location.kind === 122 && location.parent.kind === 150)) { var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration.kind === 150 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 148) { + if (functionDeclaration.kind === 150) { symbolKind = ts.ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 153 && !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -56198,11 +59926,11 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192)) { + if (ts.getDeclarationOfKind(symbol, 197)) { pushTypePart(ts.ScriptElementKind.localClassElement); } else { - displayParts.push(ts.keywordPart(73)); + displayParts.push(ts.keywordPart(74)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -56210,72 +59938,72 @@ var ts; } if ((symbolFlags & 64) && (semanticMeaning & 2)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107)); + displayParts.push(ts.keywordPart(108)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134)); + displayParts.push(ts.keywordPart(136)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74)); + displayParts.push(ts.keywordPart(75)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(81)); + displayParts.push(ts.keywordPart(82)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69; - displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); + var declaration = ts.getDeclarationOfKind(symbol, 230); + var isNamespace = declaration && declaration.name && declaration.name.kind === 70; + displayParts.push(ts.keywordPart(isNamespace ? 128 : 127)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144) && (semanticMeaning & 2)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(19)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90)); - displayParts.push(ts.spacePart()); if (symbol.parent) { + addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var declaration = ts.getDeclarationOfKind(symbol, 141); + var declaration = ts.getDeclarationOfKind(symbol, 143); ts.Debug.assert(declaration !== undefined); declaration = declaration.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152) { - displayParts.push(ts.keywordPart(92)); + if (declaration.kind === 154) { + displayParts.push(ts.keywordPart(93)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 151 && declaration.name) { + else if (declaration.kind !== 153 && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); } - else { - displayParts.push(ts.keywordPart(134)); + else if (declaration.kind === 228) { + addInPrefix(); + displayParts.push(ts.keywordPart(136)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -56286,11 +60014,11 @@ var ts; if (symbolFlags & 8) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 255) { + if (declaration.kind === 260) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); } @@ -56298,33 +60026,33 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228) { - displayParts.push(ts.keywordPart(82)); + if (symbol.declarations[0].kind === 233) { + displayParts.push(ts.keywordPart(83)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126)); + displayParts.push(ts.keywordPart(128)); } else { - displayParts.push(ts.keywordPart(89)); + displayParts.push(ts.keywordPart(90)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229) { + if (declaration.kind === 234) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.keywordPart(131)); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(19)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56)); + displayParts.push(ts.operatorPart(57)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -56338,7 +60066,7 @@ var ts; if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97)); + displayParts.push(ts.keywordPart(98)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -56347,7 +60075,7 @@ var ts; symbolFlags & 3 || symbolKind === ts.ScriptElementKind.localVariableElement || isThisExpression) { - displayParts.push(ts.punctuationPart(54)); + displayParts.push(ts.punctuationPart(55)); displayParts.push(ts.spacePart()); if (type.symbol && type.symbol.flags & 262144) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -56377,10 +60105,10 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); if (documentation.length === 0 && symbol.flags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187) { + if (!declaration.parent || declaration.parent.kind !== 192) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -56401,6 +60129,11 @@ var ts; displayParts.push(ts.lineBreakPart()); } } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(91)); + displayParts.push(ts.spacePart()); + } function addFullSymbolName(symbol, enclosingDeclaration) { var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); ts.addRange(displayParts, fullSymbolDisplayParts); @@ -56423,9 +60156,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.textOrKeywordPart(symbolKind)); displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(19)); return; } } @@ -56433,12 +60166,12 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17)); - displayParts.push(ts.operatorPart(35)); + displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.operatorPart(36)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18)); + displayParts.push(ts.punctuationPart(19)); } documentation = signature.getDocumentationComment(); } @@ -56455,14 +60188,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 179) { + if (declaration.kind === 184) { return true; } - if (declaration.kind !== 218 && declaration.kind !== 220) { + if (declaration.kind !== 223 && declaration.kind !== 225) { return false; } - for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { - if (parent_23.kind === 256 || parent_23.kind === 226) { + for (var parent_20 = declaration.parent; !ts.isFunctionBlock(parent_20); parent_20 = parent_20.parent) { + if (parent_20.kind === 261 || parent_20.kind === 231) { return false; } } @@ -56503,8 +60236,8 @@ var ts; var outputText; var sourceMapText; var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); sourceMapText = text; @@ -56520,9 +60253,9 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -56546,7 +60279,7 @@ var ts; return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_2 = function (opt) { + var _loop_3 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -56562,7 +60295,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_2(opt); + _loop_3(opt); } return options; } @@ -56571,11 +60304,11 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(2, false, 0); - var jsxScanner = ts.createScanner(2, false, 1); + var standardScanner = ts.createScanner(5, false, 0); + var jsxScanner = ts.createScanner(5, false, 1); var scanner; function getFormattingScanner(sourceFile, startPos, endPos) { - ts.Debug.assert(scanner === undefined); + ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); scanner = sourceFile.languageVariant === 1 ? jsxScanner : standardScanner; scanner.setText(sourceFile.text); scanner.setTextPos(startPos); @@ -56600,7 +60333,7 @@ var ts; } }; function advance() { - ts.Debug.assert(scanner !== undefined); + ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { @@ -56640,11 +60373,11 @@ var ts; function shouldRescanGreaterThanToken(node) { if (node) { switch (node.kind) { - case 29: - case 64: + case 30: case 65: + case 66: + case 46: case 45: - case 44: return true; } } @@ -56653,27 +60386,27 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 246: - case 243: - case 245: - case 242: - return node.kind === 69; + case 250: + case 248: + case 249: + case 247: + return node.kind === 70; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 244; + return node && node.kind === 10; } function shouldRescanSlashToken(container) { - return container.kind === 10; + return container.kind === 11; } function shouldRescanTemplateToken(container) { - return container.kind === 13 || - container.kind === 14; + return container.kind === 14 || + container.kind === 15; } function startsWithSlashToken(t) { - return t === 39 || t === 61; + return t === 40 || t === 62; } function readTokenInfo(n) { ts.Debug.assert(scanner !== undefined); @@ -56704,7 +60437,7 @@ var ts; scanner.scan(); } var currentToken = scanner.getToken(); - if (expectedScanAction === 1 && currentToken === 27) { + if (expectedScanAction === 1 && currentToken === 28) { currentToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 1; @@ -56714,11 +60447,11 @@ var ts; ts.Debug.assert(n.kind === currentToken); lastScanAction = 2; } - else if (expectedScanAction === 3 && currentToken === 16) { + else if (expectedScanAction === 3 && currentToken === 17) { currentToken = scanner.reScanTemplateToken(); lastScanAction = 3; } - else if (expectedScanAction === 4 && currentToken === 69) { + else if (expectedScanAction === 4 && currentToken === 70) { currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } @@ -56852,8 +60585,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 15, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 16, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 16, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 17, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -56949,7 +60682,7 @@ var ts; function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i - 0] = arguments[_i]; + funcs[_i] = arguments[_i]; } this.customContextChecks = funcs; } @@ -56982,88 +60715,88 @@ var ts; function Rules() { this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1)); - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16, 80), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16, 104), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.FromTokens([18, 20, 24, 23])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17, 81), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17, 105), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.FromTokens([19, 21, 25, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69, 3, 73, 82, 89]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18, 3, 79, 100, 85, 80]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([70, 3, 74, 83, 90]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([19, 3, 80, 101, 86, 81]); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); + this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); + this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102, 98, 92, 78, 94, 101, 119]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108, 74]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(43, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(37, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(37, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([103, 99, 93, 79, 95, 102, 120]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([109, 75]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); + this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(88, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(104, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(95, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([19, 80, 81, 72]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([101, 86]), 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124, 133]), 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 129]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 73, 122, 77, 81, 82, 83, 123, 106, 89, 107, 125, 126, 110, 112, 111, 131, 113, 134, 136]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83, 106, 136])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.FromTokens([18, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115, 69, 82, 77, 73, 113, 112, 110, 111, 123, 131, 19, 37])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37, formatting.Shared.TokenRange.FromTokens([69, 17])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114, 37]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([127, 131]), 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116, 74, 123, 78, 82, 83, 84, 124, 107, 90, 108, 127, 128, 111, 113, 112, 133, 114, 136, 138]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84, 107, 138])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(35, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(23, 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.FromTokens([19, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(19, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 28), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.FromTokens([18, 20, 28, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116, 70, 83, 78, 74, 114, 113, 111, 112, 124, 133, 20, 38])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(88, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(38, formatting.Shared.TokenRange.FromTokens([70, 18])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(115, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 38]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(119, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(119, 88), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(70, formatting.Shared.TokenRange.FromTokens([12, 13])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 70), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 40), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(40, 28), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(57, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -57118,81 +60851,81 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(18, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(20, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13, 14]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13, 14]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14, 15])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14, 15])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_51 in o) { - if (o[name_51] === rule) { - return name_51; + for (var name_49 in o) { + if (o[name_49] === rule) { + return name_49; } } throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 206; + return context.contextNode.kind === 211; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 187: - case 188: - case 195: - case 238: - case 234: - case 154: - case 162: - case 163: + case 192: + case 193: + case 200: + case 243: + case 239: + case 156: + case 164: + case 165: return true; - case 169: + case 174: + case 228: + case 234: case 223: - case 229: - case 218: - case 142: - case 255: - case 145: case 144: - return context.currentTokenSpan.kind === 56 || context.nextTokenSpan.kind === 56; - case 207: - return context.currentTokenSpan.kind === 90 || context.nextTokenSpan.kind === 90; - case 208: - return context.currentTokenSpan.kind === 138 || context.nextTokenSpan.kind === 138; + case 260: + case 147: + case 146: + return context.currentTokenSpan.kind === 57 || context.nextTokenSpan.kind === 57; + case 212: + return context.currentTokenSpan.kind === 91 || context.nextTokenSpan.kind === 91; + case 213: + return context.currentTokenSpan.kind === 140 || context.nextTokenSpan.kind === 140; } return false; }; @@ -57200,7 +60933,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 188; + return context.contextNode.kind === 193; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); @@ -57225,120 +60958,120 @@ var ts; return true; } switch (node.kind) { - case 199: - case 227: - case 171: - case 226: + case 204: + case 232: + case 176: + case 231: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 220: - case 147: - case 146: + case 225: case 149: - case 150: - case 151: - case 179: case 148: - case 180: - case 222: + case 151: + case 152: + case 153: + case 184: + case 150: + case 185: + case 227: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 220 || context.contextNode.kind === 179; + return context.contextNode.kind === 225 || context.contextNode.kind === 184; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 221: - case 192: - case 222: - case 224: - case 159: - case 225: - case 236: - case 237: + case 226: + case 197: + case 227: + case 229: + case 161: case 230: - case 233: + case 241: + case 242: + case 235: + case 238: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 221: - case 225: - case 224: - case 199: - case 252: case 226: - case 213: + case 230: + case 229: + case 204: + case 256: + case 231: + case 218: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 203: - case 213: - case 206: - case 207: case 208: - case 205: - case 216: - case 204: + case 218: + case 211: case 212: - case 252: + case 213: + case 210: + case 221: + case 209: + case 217: + case 256: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 171; + return context.contextNode.kind === 176; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 174; + return context.contextNode.kind === 179; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 175; + return context.contextNode.kind === 180; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); }; Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 24; + return context.currentTokenSpan.kind !== 25; }; Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 20; + return context.nextTokenSpan.kind !== 21; }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 180; + return context.contextNode.kind === 185; }; Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; }; Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 241; + return context.contextNode.kind !== 246; }; Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 248; + return context.contextNode.kind === 252; }; Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246; + return context.nextTokenParent.kind === 250; }; Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246; + return context.contextNode.kind === 250; }; Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242; + return context.contextNode.kind === 247; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -57353,41 +61086,41 @@ var ts; while (ts.isPartOfExpression(node)) { node = node.parent; } - return node.kind === 143; + return node.kind === 145; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 219 && + return context.currentTokenParent.kind === 224 && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 225; + return context.contextNode.kind === 230; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 159; + return context.contextNode.kind === 161; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 25 && token.kind !== 27) { + if (token.kind !== 26 && token.kind !== 28) { return false; } switch (parent.kind) { - case 155: - case 177: - case 221: - case 192: - case 222: - case 220: + case 157: + case 182: + case 226: + case 197: + case 227: + case 225: + case 184: + case 185: + case 149: + case 148: + case 153: + case 154: case 179: case 180: - case 147: - case 146: - case 151: - case 152: - case 174: - case 175: - case 194: + case 199: return true; default: return false; @@ -57398,13 +61131,13 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 177; + return context.contextNode.kind === 182; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 183; + return context.currentTokenSpan.kind === 104 && context.currentTokenParent.kind === 188; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 190 && context.contextNode.expression !== undefined; + return context.contextNode.kind === 195 && context.contextNode.expression !== undefined; }; return Rules; }()); @@ -57426,7 +61159,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 138 + 1; + this.mapRowLength = 140 + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); var rulesBucketConstructionStateList = new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); @@ -57439,6 +61172,7 @@ var ts; }); }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + ts.Debug.assert(row <= 140 && column <= 140, "Must compute formatting context from tokens"); var rulesBucketIndex = (row * this.mapRowLength) + column; return rulesBucketIndex; }; @@ -57475,6 +61209,7 @@ var ts; formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; + var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; @@ -57482,8 +61217,7 @@ var ts; RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesPosition = formatting.RulesPosition; + })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); var RulesBucketConstructionState = (function () { function RulesBucketConstructionState() { this.rulesInsertionIndexBitmap = 0; @@ -57602,12 +61336,12 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0; token <= 138; token++) { + for (var token = 0; token <= 140; token++) { result.push(token); } return result; }; - TokenAllAccess.prototype.Contains = function (tokenValue) { + TokenAllAccess.prototype.Contains = function () { return true; }; TokenAllAccess.prototype.toString = function () { @@ -57646,17 +61380,17 @@ var ts; }()); TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(70, 138); - TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 138, 116, 124]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); + TokenRange.Keywords = TokenRange.FromRange(71, 140); + TokenRange.BinaryOperators = TokenRange.FromRange(26, 69); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91, 92, 140, 117, 125]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([42, 43, 51, 50]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 70, 18, 20, 16, 98, 93]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([70, 18, 98, 93]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([70, 19, 21, 93]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([70, 18, 98, 93]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([70, 19, 21, 93]); TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([69, 130, 132, 120, 133, 103, 117]); + TokenRange.TypeNames = TokenRange.FromTokens([70, 132, 134, 121, 135, 104, 118]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -57689,25 +61423,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -57717,7 +61451,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -57727,7 +61461,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -57737,7 +61471,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -57745,7 +61479,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -57753,13 +61487,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -57767,14 +61501,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -57812,11 +61546,11 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 23, sourceFile, options, rulesProvider, 3); + return formatOutermostParent(position, 24, sourceFile, options, rulesProvider, 3); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 16, sourceFile, options, rulesProvider, 4); + return formatOutermostParent(position, 17, sourceFile, options, rulesProvider, 4); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -57864,17 +61598,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 221: - case 222: - return ts.rangeContainsRange(parent.members, node); - case 225: - var body = parent.body; - return body && body.kind === 199 && ts.rangeContainsRange(body.statements, node); - case 256: - case 199: case 226: + case 227: + return ts.rangeContainsRange(parent.members, node); + case 230: + var body = parent.body; + return body && body.kind === 231 && ts.rangeContainsRange(body.statements, node); + case 261: + case 204: + case 231: return ts.rangeContainsRange(parent.statements, node); - case 252: + case 256: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -57918,7 +61652,7 @@ var ts; index++; } }; - function rangeHasNoErrors(r) { + function rangeHasNoErrors() { return false; } } @@ -57945,7 +61679,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -58005,12 +61739,12 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -58030,18 +61764,18 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 221: return 73; - case 222: return 107; - case 220: return 87; - case 224: return 224; - case 149: return 123; - case 150: return 131; - case 147: + case 226: return 74; + case 227: return 108; + case 225: return 88; + case 229: return 229; + case 151: return 124; + case 152: return 133; + case 149: if (node.asteriskToken) { - return 37; + return 38; } - case 145: - case 142: + case 147: + case 144: return node.name.kind; } } @@ -58049,9 +61783,9 @@ var ts; return { getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { - case 16: - case 20: - case 18: + case 17: + case 21: + case 19: return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; @@ -58063,15 +61797,15 @@ var ts; } } switch (kind) { - case 15: case 16: - case 19: - case 20: case 17: + case 20: + case 21: case 18: - case 80: - case 104: - case 55: + case 19: + case 81: + case 105: + case 56: return indentation; default: return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; @@ -58082,13 +61816,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -58151,17 +61885,17 @@ var ts; if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (ts.isToken(child)) { + if (ts.isToken(child) && child.kind !== 10) { var tokenInfo = formattingScanner.readTokenInfo(child); - ts.Debug.assert(tokenInfo.token.end === child.end); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 143 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 145 ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent.kind === 170 && inheritedIndentation === -1) { + if (isFirstListItem && parent.kind === 175 && inheritedIndentation === -1) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -58336,11 +62070,23 @@ var ts; else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); - if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } } } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } @@ -58448,7 +62194,7 @@ var ts; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2: @@ -58465,41 +62211,41 @@ var ts; } function getOpenTokenForList(node, list) { switch (node.kind) { + case 150: + case 225: + case 184: + case 149: case 148: - case 220: - case 179: - case 147: - case 146: - case 180: + case 185: if (node.typeParameters === list) { - return 25; + return 26; } else if (node.parameters === list) { - return 17; + return 18; } break; - case 174: - case 175: + case 179: + case 180: if (node.typeArguments === list) { - return 25; + return 26; } else if (node.arguments === list) { - return 17; + return 18; } break; - case 155: + case 157: if (node.typeArguments === list) { - return 25; + return 26; } } return 0; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 17: - return 18; - case 25: - return 27; + case 18: + return 19; + case 26: + return 28; } return 0; } @@ -58507,14 +62253,14 @@ var ts; var internedTabsIndentation; var internedSpacesIndentation; function getIndentationString(indentation, options) { - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -58529,13 +62275,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -58564,7 +62310,7 @@ var ts; if (position > sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +62322,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58588,7 +62334,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 && precedingToken.parent.kind !== 187) { + if (precedingToken.kind === 25 && precedingToken.parent.kind !== 192) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; @@ -58605,7 +62351,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +62361,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +62372,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +62410,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58690,7 +62436,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 256 || !parentAndChildShareLine); + (parent.kind === 261 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -58701,10 +62447,10 @@ var ts; if (!nextToken) { return false; } - if (nextToken.kind === 15) { + if (nextToken.kind === 16) { return true; } - else if (nextToken.kind === 16) { + else if (nextToken.kind === 17) { var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine; } @@ -58714,8 +62460,8 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 203 && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 80, sourceFile); + if (parent.kind === 208 && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 81, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -58726,23 +62472,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 155: + case 157: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 171: + case 176: return node.parent.properties; - case 170: + case 175: return node.parent.elements; - case 220: - case 179: - case 180: - case 147: - case 146: - case 151: - case 152: { + case 225: + case 184: + case 185: + case 149: + case 148: + case 153: + case 154: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -58753,8 +62499,8 @@ var ts; } break; } - case 175: - case 174: { + case 180: + case 179: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -58779,11 +62525,11 @@ var ts; } } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - if (node.kind === 18) { + if (node.kind === 19) { return -1; } - if (node.parent && (node.parent.kind === 174 || - node.parent.kind === 175) && + if (node.parent && (node.parent.kind === 179 || + node.parent.kind === 180) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -58801,10 +62547,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 174: - case 175: - case 172: - case 173: + case 179: + case 180: + case 177: + case 178: node = node.expression; break; default: @@ -58818,7 +62564,7 @@ var ts; var node = list[index]; var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 24) { + if (list[i].kind === 25) { continue; } var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; @@ -58842,7 +62588,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58858,48 +62604,48 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202: - case 221: - case 192: - case 222: - case 224: - case 223: - case 170: - case 199: + case 207: case 226: - case 171: - case 159: - case 161: + case 197: case 227: - case 250: - case 249: - case 178: - case 172: - case 174: + case 229: + case 228: case 175: - case 200: - case 218: - case 235: - case 211: - case 188: - case 168: - case 167: - case 243: - case 242: - case 248: - case 146: - case 151: - case 152: - case 142: - case 156: - case 157: - case 164: + case 204: + case 231: case 176: - case 184: - case 237: - case 233: + case 161: + case 163: + case 232: + case 254: + case 253: + case 183: + case 177: + case 179: + case 180: + case 205: + case 223: + case 240: + case 216: + case 193: + case 173: + case 172: + case 248: + case 247: + case 252: + case 148: + case 153: + case 154: + case 144: + case 158: + case 159: + case 166: + case 181: + case 189: + case 242: case 238: - case 234: + case 243: + case 239: return true; } return false; @@ -58907,27 +62653,27 @@ var ts; function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0; switch (parent.kind) { - case 204: - case 205: - case 207: + case 209: + case 210: + case 212: + case 213: + case 211: case 208: - case 206: - case 203: - case 220: - case 179: - case 147: - case 180: - case 148: + case 225: + case 184: case 149: + case 185: case 150: - return childKind !== 199; - case 236: - return childKind !== 237; - case 230: - return childKind !== 231 || - (child.namedBindings && child.namedBindings.kind !== 233); + case 151: + case 152: + return childKind !== 204; case 241: - return childKind !== 245; + return childKind !== 242; + case 235: + return childKind !== 236 || + (child.namedBindings && child.namedBindings.kind !== 238); + case 246: + return childKind !== 249; } return indentByDefault; } @@ -58940,11 +62686,689 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 122) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 98) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 179) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 207 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var ModuleSpecifierComparison; + (function (ModuleSpecifierComparison) { + ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; + })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); + var ImportCodeActionMap = (function () { + function ImportCodeActionMap() { + this.symbolIdToActionMap = ts.createMap(); + } + ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { + if (!newAction) { + return; + } + if (!this.symbolIdToActionMap[symbolId]) { + this.symbolIdToActionMap[symbolId] = [newAction]; + return; + } + if (newAction.kind === "CodeChange") { + this.symbolIdToActionMap[symbolId].push(newAction); + return; + } + var updatedNewImports = []; + for (var _i = 0, _a = this.symbolIdToActionMap[symbolId]; _i < _a.length; _i++) { + var existingAction = _a[_i]; + if (existingAction.kind === "CodeChange") { + updatedNewImports.push(existingAction); + continue; + } + switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { + case ModuleSpecifierComparison.Better: + if (newAction.kind === "NewImport") { + return; + } + case ModuleSpecifierComparison.Equal: + updatedNewImports.push(existingAction); + break; + case ModuleSpecifierComparison.Worse: + continue; + } + } + updatedNewImports.push(newAction); + this.symbolIdToActionMap[symbolId] = updatedNewImports; + }; + ImportCodeActionMap.prototype.addActions = function (symbolId, newActions) { + for (var _i = 0, newActions_1 = newActions; _i < newActions_1.length; _i++) { + var newAction = newActions_1[_i]; + this.addAction(symbolId, newAction); + } + }; + ImportCodeActionMap.prototype.getAllActions = function () { + var result = []; + for (var symbolId in this.symbolIdToActionMap) { + result = ts.concatenate(result, this.symbolIdToActionMap[symbolId]); + } + return result; + }; + ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { + if (moduleSpecifier1 === moduleSpecifier2) { + return ModuleSpecifierComparison.Equal; + } + if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { + return ModuleSpecifierComparison.Better; + } + if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { + return ModuleSpecifierComparison.Worse; + } + if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { + var regex = new RegExp(ts.directorySeparator, "g"); + var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; + var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; + return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Better + : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Equal + : ModuleSpecifierComparison.Worse; + } + return ModuleSpecifierComparison.Equal; + }; + return ImportCodeActionMap; + }()); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + var cachedImportDeclarations = ts.createMap(); + var cachedNewImportInsertPosition; + var allPotentialModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + allPotentialModules.push(otherSourceFile.symbol); + } + } + var currentTokenMeaning = ts.getMeaningFromLocation(token); + for (var _a = 0, allPotentialModules_1 = allPotentialModules; _a < allPotentialModules_1.length; _a++) { + var moduleSymbol = allPotentialModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + } + } + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + if (cachedImportDeclarations[moduleSymbolId]) { + return cachedImportDeclarations[moduleSymbolId]; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 235) { + return node; + } + if (node.kind === 234) { + return node; + } + node = node.parent; + } + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (declaration.kind === 235) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 237) { + namespaceImportDeclaration = declaration; + } + else { + namedImportDeclaration = declaration; + } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + } + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + if (namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + var textChange = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], textChange.newText, textChange.span, sourceFile.fileName, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + } + else { + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 245) { + return declaration.moduleReference.expression.getText(); + } + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var newImportText = isDefault ? "default as " + name : name; + var importList = importClause.namedBindings; + if (!importList && importClause.name) { + var start = importClause.name.getEnd(); + return { + newText: ", { " + newImportText + " }", + span: { start: start, length: 0 } + }; + } + if (importList.elements.length === 0) { + var start = importList.getStart(); + return { + newText: "{ " + newImportText + " }", + span: { start: start, length: importList.getEnd() - start } + }; + } + var insertPoint = importList.elements[importList.elements.length - 1].getEnd(); + var startLine = ts.getLineOfLocalPosition(sourceFile, importList.getStart()); + var endLine = ts.getLineOfLocalPosition(sourceFile, importList.getEnd()); + var oneImportPerLine = endLine - startLine > importList.elements.length; + return { + newText: "," + (oneImportPerLine ? context.newLineCharacter : " ") + newImportText, + span: { start: insertPoint, length: 0 } + }; + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 235) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); + } + else { + namespacePrefix = declaration.name.getText(); + } + namespacePrefix = ts.stripQuotes(namespacePrefix); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], namespacePrefix + ".", { start: token.getStart(), length: 0 }, sourceFile.fileName, "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!cachedNewImportInsertPosition) { + var lastModuleSpecifierEnd = -1; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier_1 = _a[_i]; + var end = moduleSpecifier_1.getEnd(); + if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) { + lastModuleSpecifierEnd = end; + } + } + cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart(); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var importStatementText = isDefault + ? "import " + name + " from \"" + moduleSpecifierWithoutQuotes + "\"" + : "import { " + name + " } from \"" + moduleSpecifierWithoutQuotes + "\""; + var newText = cachedNewImportInsertPosition === sourceFile.getStart() + ? importStatementText + ";" + context.newLineCharacter + context.newLineCharacter + : "" + context.newLineCharacter + importStatementText + ";"; + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], newText, { start: cachedNewImportInsertPosition, length: 0 }, sourceFile.fileName, "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.path; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 261) { + return moduleSymbol.name; + } + } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { + return undefined; + } + var normalizedBaseUrl = ts.toPath(options.baseUrl, ts.getDirectoryPath(options.baseUrl), getCanonicalFileName); + var relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl); + if (!relativeName) { + return undefined; + } + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName) { + return key; + } + } + } + } + return relativeName; + } + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedRootDirs = ts.map(options.rootDirs, function (rootDir) { return ts.toPath(rootDir, undefined, getCanonicalFileName); }); + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + } + return undefined; + } + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } + } + } + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; + } + } + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = tryRemoveParentDirectoryName(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } + function tryRemoveParentDirectoryName(path, parentDirectory) { + var index = path.indexOf(parentDirectory); + if (index === 0) { + return ts.endsWith(parentDirectory, ts.directorySeparator) + ? path.substring(parentDirectory.length) + : path.substring(parentDirectory.length + 1); + } + return undefined; + } + } + } + function createCodeAction(description, diagnosticArgs, newText, span, fileName, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: [{ fileName: fileName, textChanges: [{ newText: newText, span: span }] }], + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_never_used.code + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start); + if (token.kind === 20) { + token = ts.getTokenAtPosition(sourceFile, start + 1); + } + switch (token.kind) { + case 70: + switch (token.parent.kind) { + case 223: + switch (token.parent.parent.parent.kind) { + case 211: + var forStatement = token.parent.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos); + } + else { + return removeSingleItem(forInitializer.declarations, token); + } + case 213: + var forOfStatement = token.parent.parent.parent; + if (forOfStatement.initializer.kind === 224) { + var forOfInitializer = forOfStatement.initializer; + return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos); + } + break; + case 212: + return undefined; + case 256: + var catchClause = token.parent.parent; + var parameter = catchClause.variableDeclaration.getChildren()[0]; + return createCodeFix("", parameter.pos, parameter.end - parameter.pos); + default: + var variableStatement = token.parent.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos); + } + else { + var declarations = variableStatement.declarationList.declarations; + return removeSingleItem(declarations, token); + } + } + case 143: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2); + } + else { + return removeSingleItem(typeParameters, token); + } + case 144: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else { + return removeSingleItem(functionDeclaration.parameters, token); + } + case 234: + var importEquals = findImportDeclaration(token); + return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos); + case 239: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + var importSpec = findImportDeclaration(token); + return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos); + } + else { + return removeSingleItem(namedImports.elements, token); + } + case 236: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = findImportDeclaration(importClause); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos); + } + case 237: + var namespaceImport = token.parent; + if (namespaceImport.name == token && !namespaceImport.parent.name) { + var importDecl = findImportDeclaration(namespaceImport); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + var start_4 = namespaceImport.parent.name.end; + return createCodeFix("", start_4, namespaceImport.parent.namedBindings.end - start_4); + } + } + break; + case 147: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + case 237: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + if (ts.isDeclarationName(token)) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos); + } + else { + return undefined; + } + function findImportDeclaration(token) { + var importDecl = token; + while (importDecl.kind != 235 && importDecl.parent) { + importDecl = importDecl.parent; + } + return importDecl; + } + function createCodeFix(newText, start, length) { + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_unused_identifiers), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ newText: newText, span: { start: start, length: length } }] + }] + }]; + } + function removeSingleItem(elements, token) { + if (elements[0] === token.parent) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1); + } + else { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1); + } + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { - var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + var node = kind >= 141 ? new NodeObject(kind, pos, end) : + kind === 70 ? new IdentifierObject(70, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -58955,7 +63379,6 @@ var ts; this.end = end; this.flags = 0; this.transformFlags = undefined; - this.excludeTransformFlags = undefined; this.parent = undefined; this.kind = kind; } @@ -59002,11 +63425,11 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(292, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -59021,11 +63444,11 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 139) { + if (this.kind >= 141) { ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; + var useJSDocScanner_1 = this.kind >= 278 && this.kind <= 291; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { @@ -59043,8 +63466,8 @@ var ts; children.push(_this.createSyntaxList(nodes)); pos_3 = nodes.end; }; - if (this.jsDocComments) { - for (var _i = 0, _a = this.jsDocComments; _i < _a.length; _i++) { + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; processNode(jsDocComment); } @@ -59079,7 +63502,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 139 ? child : child.getFirstToken(sourceFile); + return child.kind < 141 ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -59087,7 +63510,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 139 ? child : child.getLastToken(sourceFile); + return child.kind < 141 ? child : child.getLastToken(sourceFile); }; return NodeObject; }()); @@ -59125,19 +63548,19 @@ var ts; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + TokenOrIdentifierObject.prototype.getChildAt = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getLastToken = function () { return undefined; }; return TokenOrIdentifierObject; @@ -59158,7 +63581,7 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); } return this.documentationComment; }; @@ -59167,19 +63590,20 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69; + IdentifierObject.prototype.kind = 70; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -59213,7 +63637,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 | 65536) + return this.flags & 32768 && this.objectFlags & (1 | 2) ? this.checker.getBaseTypes(this) : undefined; }; @@ -59240,7 +63664,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], undefined, false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; } return this.documentationComment; }; @@ -59249,7 +63673,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59263,6 +63687,19 @@ var ts; SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { return ts.getPositionOfLineAndCharacter(this, line, character); }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); @@ -59284,13 +63721,13 @@ var ts; } function getDeclarationName(declaration) { if (declaration.name) { - var result_6 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_6 !== undefined) { - return result_6; + var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_7 !== undefined) { + return result_7; } - if (declaration.name.kind === 140) { + if (declaration.name.kind === 142) { var expr = declaration.name.expression; - if (expr.kind === 172) { + if (expr.kind === 177) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -59300,7 +63737,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 || + if (node.kind === 70 || node.kind === 9 || node.kind === 8) { return node.text; @@ -59310,10 +63747,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 220: - case 179: - case 147: - case 146: + case 225: + case 184: + case 149: + case 148: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -59327,33 +63764,33 @@ var ts; else { declarations.push(functionDeclaration); } - ts.forEachChild(node, visit); } + ts.forEachChild(node, visit); break; - case 221: - case 192: - case 222: - case 223: - case 224: - case 225: + case 226: + case 197: + case 227: + case 228: case 229: - case 238: + case 230: case 234: - case 229: - case 231: - case 232: - case 149: - case 150: - case 159: + case 243: + case 239: + case 234: + case 236: + case 237: + case 151: + case 152: + case 161: addDeclaration(node); ts.forEachChild(node, visit); break; - case 142: + case 144: if (!ts.hasModifier(node, 92)) { break; } - case 218: - case 169: { + case 223: + case 174: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -59362,24 +63799,24 @@ var ts; if (decl.initializer) visit(decl.initializer); } - case 255: - case 145: - case 144: + case 260: + case 147: + case 146: addDeclaration(node); break; - case 236: + case 241: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 230: + case 235: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { + if (importClause.namedBindings.kind === 237) { addDeclaration(importClause.namedBindings); } else { @@ -59403,9 +63840,33 @@ var ts; getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } + getSignatureConstructor: function () { return SignatureObject; }, }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +63881,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59467,7 +63932,7 @@ var ts; }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (path, value) { + this.fileNameToEntry.forEachValue(function (_path, value) { if (value) { fileNames.push(value.hostFileName); } @@ -59497,7 +63962,7 @@ var ts; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5, version, true, scriptKind); } else if (this.currentFileVersion !== version) { var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); @@ -59583,7 +64048,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +64085,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59643,7 +64115,7 @@ var ts; useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: function (fileName, data, writeByteOrderMark) { }, + writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { return hostCache.getOrCreateEntry(fileName) !== undefined; @@ -59733,6 +64205,7 @@ var ts; return program; } function cleanupSemanticCache() { + program = undefined; } function dispose() { if (program) { @@ -59785,12 +64258,12 @@ var ts; var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { - case 69: - case 172: - case 139: - case 97: - case 165: - case 95: + case 70: + case 177: + case 141: + case 98: + case 167: + case 96: var type = typeChecker.getTypeAtLocation(node); if (type) { return { @@ -59878,12 +64351,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +64367,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59911,23 +64384,23 @@ var ts; function getSourceFile(fileName) { return getNonBoundSourceFile(fileName); } - function getNameOrDottedNameSpan(fileName, startPos, endPos) { + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, startPos); if (node === sourceFile) { return; } switch (node.kind) { - case 172: - case 139: + case 177: + case 141: case 9: - case 84: - case 99: - case 93: - case 95: - case 97: - case 165: - case 69: + case 85: + case 100: + case 94: + case 96: + case 98: + case 167: + case 70: break; default: return; @@ -59938,7 +64411,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 225 && + if (nodeForStartPos.parent.parent.kind === 230 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -59957,14 +64430,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60006,48 +64491,76 @@ var ts; return result; function getMatchingTokenKind(token) { switch (token.kind) { - case 15: return 16; - case 17: return 18; - case 19: return 20; - case 25: return 27; - case 16: return 15; - case 18: return 17; - case 20: return 19; - case 27: return 25; + case 16: return 17; + case 18: return 19; + case 20: return 21; + case 26: return 28; + case 17: return 16; + case 19: return 18; + case 21: return 20; + case 28: return 26; } return undefined; } } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar, + host: host, + cancellationToken: cancellationToken + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60056,7 +64569,7 @@ var ts; return false; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -60159,6 +64672,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +64682,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60188,13 +64703,13 @@ var ts; sourceFile.nameTable = nameTable; function walk(node) { switch (node.kind) { - case 69: + case 70: nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9: case 8: if (ts.isDeclarationName(node) || - node.parent.kind === 240 || + node.parent.kind === 245 || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node)) { nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; @@ -60202,10 +64717,10 @@ var ts; break; default: ts.forEachChild(node, walk); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - ts.forEachChild(jsDocComment, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); } } } @@ -60214,7 +64729,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 173 && + node.parent.kind === 178 && node.parent.argumentExpression === node; } function getDefaultLibFilePath(options) { @@ -60233,43 +64748,2751 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var TextStorage = (function () { + function TextStorage(host, fileName) { + this.host = host; + this.fileName = fileName; + this.svcVersion = 0; + this.textVersion = 0; } - return spaceCache[n]; + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + : "Text-" + this.textVersion; + }; + TextStorage.prototype.hasScriptVersionCache = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache = function (newText) { + this.switchToScriptVersionCache(newText); + }; + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.setText(newText); + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + }; + TextStorage.prototype.reload = function (text) { + if (this.svc) { + this.svc.reload(text); + } + else { + this.setText(text); + } + }; + TextStorage.prototype.reloadFromFile = function (tempFileName) { + if (this.svc || (tempFileName !== this.fileName)) { + this.reload(this.getFileText(tempFileName)); + } + else { + this.setText(undefined); + } + }; + TextStorage.prototype.getSnapshot = function () { + return this.svc + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + }; + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.svc) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.svc) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.svc) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + var index = this.svc.getSnapshot().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + TextStorage.prototype.getFileText = function (tempFileName) { + return this.host.readFile(tempFileName || this.fileName) || ""; + }; + TextStorage.prototype.ensureNoScriptVersionCache = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + }; + TextStorage.prototype.switchToScriptVersionCache = function (newText) { + if (!this.svc) { + this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svcVersion++; + this.text = undefined; + } + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + this.ensureNoScriptVersionCache(); + if (this.text === undefined) { + this.setText(this.getFileText()); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + this.ensureNoScriptVersionCache(); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + TextStorage.prototype.setText = function (newText) { + this.ensureNoScriptVersionCache(); + if (newText === undefined || this.text !== newText) { + this.text = newText; + this.lineMap = undefined; + this.textVersion++; + } + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.textStorage = new TextStorage(host, fileName); + if (hasMixedContent) { + this.textStorage.reload(""); + } + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); + } + ScriptInfo.prototype.isScriptOpen = function () { + return this.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.isOpen = true; + this.textStorage.useScriptVersionCache(newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + return this.containingProjects[0]; + }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.textStorage.getVersion(); + }; + ScriptInfo.prototype.reload = function (script) { + this.textStorage.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.textStorage.getSnapshot(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.textStorage.reloadFromFile(tempFileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.getLineInfo = function (line) { + return this.textStorage.getLineInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.textStorage.edit(start, end, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + return this.textStorage.lineToTextSpan(line); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + return this.textStorage.lineOffsetToPosition(line, offset); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + return this.textStorage.positionToLineOffset(position); + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var globalCache = _this.project.getTypeAcquisition().enable + ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation + : undefined; + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (!(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { + var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; + } + } + return primaryResult; + }; + if (this.host.realpath) { + this.realpath = function (path) { return _this.host.realpath(path); }; + } + } + LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { + this.filesWithChangedSetOfUnresolvedImports = []; + }; + LSHost.prototype.finishRecordingFilesWithChangedResolutions = function () { + var collected = this.filesWithChangedSetOfUnresolvedImports; + this.filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + }; + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult, getResultFileName, logChanges) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_50 = names_2[_i]; + var resolution = newResolutions[name_50]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_50]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_50] = resolution = loader(name_50, containingFile, compilerOptions, this); + } + if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + this.filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + var oldResult = getResult(oldResolution); + var newResult = getResult(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return getResultFileName(oldResult) === getResultFileName(newResult); + } + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + return getResultFileName(result) !== lastDeletedFileName; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }, function (r) { return r.resolvedFileName; }, false); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }, function (r) { return r.resolvedFileName; }, true); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + } + this.compilationSettings = opt; + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: ts.noop, + attach: ts.noop, + onProjectClosed: ts.noop, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typeAcquisitionChanged(opt1, opt2) { + return opt1.enable !== opt2.enable || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function unresolvedImportsChanged(imports1, imports2) { + if (imports1 === imports2) { + return false; } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + return !ts.arrayIsEqualTo(imports1, imports2); + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); + } + TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { + var typeAcquisition = project.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || + !entry || + typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || + compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) || + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typeAcquisition: typeAcquisition, + typings: result, + unresolvedImports: unresolvedImports, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } return result; + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typeAcquisition: typeAcquisition, + typings: server.toSortedReadonlyArray(newTypings), + unresolvedImports: unresolvedImports, + poisoned: false + }; + }; + TypingsCache.prototype.deleteTypingsForProject = function (projectName) { + delete this.perProjectCache[projectName]; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 230 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return this.project.projectService.host.createHash(text); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + } + AbstractBuilder.prototype.getFileInfos = function () { + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + }; + AbstractBuilder.prototype.clear = function () { + this.fileInfos_doNotAccessDirectly = undefined; + }; + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.getFileInfos().get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.getFileInfos().getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.getFileInfos().set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.getFileInfos().remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.clear = function () { + this.projectVersionForDependencyGraph = undefined; + _super.prototype.clear.call(this); + }; + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var ProjectKind; + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var UnresolvedImportsMap = (function () { + function UnresolvedImportsMap() { + this.perFileMap = ts.createFileMap(); + this.version = 0; + } + UnresolvedImportsMap.prototype.clear = function () { + this.perFileMap.clear(); + this.version = 0; + }; + UnresolvedImportsMap.prototype.getVersion = function () { + return this.version; + }; + UnresolvedImportsMap.prototype.remove = function (path) { + this.perFileMap.remove(path); + this.version++; + }; + UnresolvedImportsMap.prototype.get = function (path) { + return this.perFileMap.get(path); + }; + UnresolvedImportsMap.prototype.set = function (path, value) { + this.perFileMap.set(path, value); + this.version++; + }; + return UnresolvedImportsMap; + }()); + server.UnresolvedImportsMap = UnresolvedImportsMap; + var Project = (function () { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectName = projectName; + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); + this.languageServiceEnabled = true; + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + this.setInternalCompilerOptionsForEmittingJsFiles(); + this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + this.lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); + if (!languageServiceEnabled) { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getCachedUnresolvedImportsPerFile_TestOnly = function () { + return this.cachedUnresolvedImportsPerFile; + }; + Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { + if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { + this.compilerOptions.noEmitForJsFiles = true; + } + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + if (this.languageServiceEnabled) { + return; + } + this.languageServiceEnabled = true; + this.projectService.onUpdateLanguageServiceStateForProject(this, true); + }; + Project.prototype.disableLanguageService = function () { + if (!this.languageServiceEnabled) { + return; + } + this.languageService.cleanupSemanticCache(); + this.languageServiceEnabled = false; + this.projectService.onUpdateLanguageServiceStateForProject(this, false); + }; + Project.prototype.getProjectName = function () { + return this.projectName; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (this.languageServiceEnabled || f.isScriptOpen()) { + result.push(f.fileName); + } + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + if (!this.languageServiceEnabled) { + return this.rootFiles; + } + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries) { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var result = []; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(server.asNormalizedPath(f.fileName)); + } + return result; + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isScriptOpen() || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + this.cachedUnresolvedImportsPerFile.remove(info.path); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap()))[fileName] = fileName; + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result) { + var cached = this.cachedUnresolvedImportsPerFile.get(file.path); + if (cached) { + for (var _i = 0, cached_1 = cached; _i < cached_1.length; _i++) { + var f = cached_1[_i]; + result.push(f); + } + return; + } + var unresolvedImports; + if (file.resolvedModules) { + for (var name_51 in file.resolvedModules) { + if (!file.resolvedModules[name_51] && !ts.isExternalModuleNameRelative(name_51)) { + var trimmed = name_51.trim(); + var i = trimmed.indexOf("/"); + if (i !== -1 && trimmed.charCodeAt(0) === 64) { + i = trimmed.indexOf("/", i + 1); + } + if (i !== -1) { + trimmed = trimmed.substr(0, i); + } + (unresolvedImports || (unresolvedImports = [])).push(trimmed); + result.push(trimmed); + } + } + } + this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); + }; + Project.prototype.updateGraph = function () { + this.lsHost.startRecordingFilesWithChangedResolutions(); + var hasChanges = this.updateGraphWorker(); + var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { + var file = changedFiles_1[_i]; + this.cachedUnresolvedImportsPerFile.remove(file); + } + var unresolvedImports; + if (hasChanges || changedFiles.length) { + var result = []; + for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { + var sourceFile = _b[_a]; + this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + } + this.lastCachedUnresolvedImportsList = server.toSortedReadonlyArray(result); + } + unresolvedImports = this.lastCachedUnresolvedImportsList; + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (this.languageServiceEnabled) { + this.builder.onProjectUpdateGraph(); + } + else { + this.builder.clear(); + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + if (ts.changesAffectModuleResolution(this.compilerOptions, compilerOptions)) { + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = undefined; + } + this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename, tempFileName) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(tempFileName); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions(), + languageServiceDisabled: !this.languageServiceEnabled + }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + var updated = ts.getOwnKeys(updatedFileNames); + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed, updated: updated }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, compilerOptions) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; + _this.directoriesWatchedForTsconfig = []; + return _this; + } + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypeAcquisition = function () { + return { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); + return _this; + } + ConfiguredProject.prototype.getConfigFilePath = function () { + return this.getProjectName(); + }; + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.getConfigFilePath()); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + this.typeAcquisition = newTypeAcquisition; + }; + ConfiguredProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.getConfigFilePath()); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.getConfigFilePath()); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); + }; + ExternalProject.prototype.getTypeAcquisition = function () { + return this.typeAcquisition; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition) { + newTypeAcquisition = { + enable: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypeAcquisition.enable === undefined) { + newTypeAcquisition.enable = allRootFilesAreJsOrDts(this); + } + if (!newTypeAcquisition.include) { + newTypeAcquisition.include = []; + } + if (!newTypeAcquisition.exclude) { + newTypeAcquisition.exclude = []; + } + } + this.typeAcquisition = newTypeAcquisition; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + server.ContextEvent = "context"; + server.ConfigFileDiagEvent = "configFileDiag"; + server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + for (var id in optionMap) { + ts.Debug.assert(typeof optionMap[id] === "number"); + } + map[option.name] = optionMap; + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMap({ + "none": ts.IndentStyle.None, + "block": ts.IndentStyle.Block, + "smart": ts.IndentStyle.Smart + }); + function convertFormatOptions(protocolOptions) { + if (typeof protocolOptions.indentStyle === "string") { + protocolOptions.indentStyle = indentStyle[protocolOptions.indentStyle.toLowerCase()]; + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + for (var id in compilerOptionConverters) { + var propertyValue = protocolOptions[id]; + if (typeof propertyValue === "string") { + var mappedValues = compilerOptionConverters[id]; + protocolOptions[id] = mappedValues[propertyValue.toLowerCase()]; + } + } + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return typeof scriptKindName === "string" + ? convertScriptKindName(scriptKindName) + : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1; + case "JSX": + return 2; + case "TS": + return 3; + case "TSX": + return 4; + default: + return 0; + } + } + server.convertScriptKindName = convertScriptKindName; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (fileName, extraFileExtensions) { + var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); + return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + ts.Debug.assert(!!host.createHash, "'ServerHost.createHash' is required for ProjectService"); + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host", + extraFileExtensions: [] + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; + ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: server.ProjectLanguageServiceStateEvent, + data: { project: project, languageServiceEnabled: languageServiceEnabled } + }); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case server.ActionSet: + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); + break; + case server.ActionInvalidate: + this.typingsCache.deleteTypingsForProject(response.projectName); + break; + } + project.updateGraph(); + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); + this.compilerOptionsForInferredProjects.allowNonTsExtensions = true; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(this.compilerOptionsForInferredProjects); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isScriptOpen())) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isScriptOpen()) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ + eventName: server.ContextEvent, + data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } + }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.getConfigFilePath(), 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project, fileName); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project, triggerFile) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + var configFileName = project.getConfigFilePath(); + this.logger.info("Config file changed: " + configFileName); + var configFileErrors = this.updateConfiguredProject(project); + this.reportConfigFileDiagnostics(configFileName, configFileErrors, configFileName); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.close(); + server.removeItemFromSet(this.openFiles, info); + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + for (var _i = 0, _a = this.configuredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.canonicalConfigFilePath === configFileName) { + return proj; + } + } + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typeAcquisition: parsedCommandLine.typeAcquisition, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typeAcquisition) { + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypeAcquisition(typeAcquisition); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isScriptOpen() && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypeAcquisition(newTypeAcquisition); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.getConfigFilePath())) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return configFileErrors; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + project.enableLanguageService(); + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); + } + return configFileErrors; + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + if (openedByClient || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (openedByClient) { + if (fileContent === undefined) { + fileContent = this.host.readFile(fileName) || ""; + } + } + else { + if (!hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + } + if (info) { + if (openedByClient && !info.isScriptOpen()) { + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + else if (fileContent !== undefined) { + info.reload(fileContent); + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(convertFormatOptions(args.formatOptions)); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); + this.logger.info("Format host information updated"); + } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.logger.info("Host file extension mappings updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var configFileName; + var configFileErrors; + var project = this.findContainingExternalProject(fileName); + if (!project) { + (_a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + } + } + if (project && !project.languageServiceEnabled) { + project.markAsDirty(); + } + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + var _a; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_4 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_4(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) { + var file = changedFiles_2[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProjects = function (projects) { + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + for (var externalProjectName in this.externalProjectToConfiguredProjectMap) { + projectsToClose[externalProjectName] = true; + } + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var externalProject = projects_4[_i]; + this.openExternalProject(externalProject, true); + delete projectsToClose[externalProject.projectFileName]; + } + for (var externalProjectName in projectsToClose) { + this.closeExternalProject(externalProjectName, true); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { + if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } + if (proj.typingOptions && !proj.typeAcquisition) { + var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); + proj.typeAcquisition = typeAcquisition; + } + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + if (this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + var compilerOptions = convertCompilerOptions(proj.options); + if (this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, proj.rootFiles, externalFilePropertyReader)) { + externalProject.disableLanguageService(); + } + else { + externalProject.enableLanguageService(); + } + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + } + if (!suppressRefreshOfInferredProjects) { + this.refreshInferredProjects(); + } + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +67511,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +67527,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,119 +67538,240 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments, false); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + _this.projectService.openExternalProjects(request.arguments.projects); + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { - var openArgs = request.arguments; - var scriptKind; - switch (openArgs.scriptKindName) { - case "TS": - scriptKind = 3; - break; - case "JS": - scriptKind = 1; - break; - case "TSX": - scriptKind = 4; - break; - case "JSX": - scriptKind = 2; - break; - } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName)); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function () { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,100 +67788,128 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(true); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, - _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _a[CommandNames.ReloadProjects] = function () { + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function () { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { - case "context": + case server.ContextEvent: var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; - case "configFileDiag": + case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + break; + case server.ProjectLanguageServiceStateEvent: + var eventName = "projectLanguageServiceState"; + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, eventName); + break; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60555,18 +67930,18 @@ var ts; seq: 0, type: "event", event: eventName, - body: info + body: info, }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg + success: !errorMsg, }; if (!errorMsg) { res.body = info; @@ -60576,17 +67951,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +67966,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +67976,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +67994,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +68005,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,195 +68021,277 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (isSemantic && shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, file: fileName, - isWriteAccess: isWriteAccess + isWriteAccess: isWriteAccess, }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)), + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +68312,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - 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(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +68367,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString, + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +68520,109 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + if (!project.languageServiceEnabled) { + return false; + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount, + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +68631,35 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file, tempFileName)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +68669,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end, + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,43 +68780,81 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, 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 fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { var info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isOpen) { + if (!info.isScriptOpen()) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else @@ -61283,10 +68866,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +68876,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +68894,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +68930,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +68947,7 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - 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); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - 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++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - 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) { - return this.getSourceFile(info); - } - } - }; - 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 = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - 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(); - }; - Project.prototype.isConfiguredProject = function () { - 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.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - 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; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - 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 parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.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 { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, 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, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - 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 errors; - } - 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 _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 _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); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; + var CharRangeSection; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62591,30 +68955,30 @@ var ts; CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; - })(server.CharRangeSection || (server.CharRangeSection = {})); - var CharRangeSection = server.CharRangeSection; + })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); var BaseLineIndexWalker = (function () { function BaseLineIndexWalker() { this.goSubtree = true; this.done = false; } - BaseLineIndexWalker.prototype.leaf = function (rangeStart, rangeLength, ll) { + BaseLineIndexWalker.prototype.leaf = function (_rangeStart, _rangeLength, _ll) { }; return BaseLineIndexWalker; }()); var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62692,14 +69056,14 @@ var ts; } return this.lineIndex; }; - EditWalker.prototype.post = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { + EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } this.stack.length--; return undefined; }; - EditWalker.prototype.pre = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { + EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { this.state = CharRangeSection.Start; @@ -62801,10 +69165,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +69187,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +69195,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +69227,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +69240,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -62921,7 +69288,7 @@ var ts; var starts = [-1]; var count = 1; var pos = 0; - this.index.every(function (ll, s, len) { + this.index.every(function (ll) { starts[count] = pos; count++; pos += ll.text.length; @@ -62944,8 +69311,9 @@ var ts; } }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { - var oldSnap = oldSnapshot; - return this.getTextChangeRangeSinceVersion(oldSnap.version); + if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { + return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + } }; return LineIndexSnapshot; }()); @@ -63011,7 +69379,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +69392,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63215,7 +69583,7 @@ var ts; if (!childInfo.child) { return { line: lineNumber, - offset: charOffset + offset: charOffset, }; } else if (childInfo.childIndex < this.children.length) { @@ -63404,12 +69772,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63427,7 +69789,7 @@ var ts; server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63472,7 +69834,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -63505,6 +69867,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63561,7 +69929,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -63603,7 +69971,7 @@ var ts; } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, 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) { @@ -63677,7 +70045,7 @@ var ts; this.factory = factory; factory.registerShim(this); } - ShimBase.prototype.dispose = function (dummy) { + ShimBase.prototype.dispose = function (_dummy) { this.factory.unregisterShim(this); }; return ShimBase; @@ -63698,11 +70066,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -63881,6 +70250,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -63905,10 +70278,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -63930,10 +70304,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -63943,8 +70318,15 @@ var ts; return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (resolvedFileName && !compilerOptions.allowJs && ts.fileExtensionIs(resolvedFileName, ".js")) { + return { + resolvedFileName: undefined, + failedLookupLocations: [] + }; + } return { - resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations }; }); @@ -64004,7 +70386,7 @@ var ts; if (result.error) { return { options: {}, - typingOptions: {}, + typeAcquisition: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] @@ -64014,7 +70396,7 @@ var ts; var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { options: configFile.options, - typingOptions: configFile.typingOptions, + typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") @@ -64029,7 +70411,7 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typingOptions, info.compilerOptions); + return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -64104,4 +70486,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.1"; +var toolsVersion = "2.2"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 9116a629d6d..c5cee20bdde 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + declare namespace ts { interface MapLike { [index: string]: T; @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -46,315 +47,324 @@ declare namespace ts { ConflictMarkerTrivia = 7, NumericLiteral = 8, StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - AsteriskAsteriskToken = 38, - SlashToken = 39, - PercentToken = 40, - PlusPlusToken = 41, - MinusMinusToken = 42, - LessThanLessThanToken = 43, - GreaterThanGreaterThanToken = 44, - GreaterThanGreaterThanGreaterThanToken = 45, - AmpersandToken = 46, - BarToken = 47, - CaretToken = 48, - ExclamationToken = 49, - TildeToken = 50, - AmpersandAmpersandToken = 51, - BarBarToken = 52, - QuestionToken = 53, - ColonToken = 54, - AtToken = 55, - EqualsToken = 56, - PlusEqualsToken = 57, - MinusEqualsToken = 58, - AsteriskEqualsToken = 59, - AsteriskAsteriskEqualsToken = 60, - SlashEqualsToken = 61, - PercentEqualsToken = 62, - LessThanLessThanEqualsToken = 63, - GreaterThanGreaterThanEqualsToken = 64, - GreaterThanGreaterThanGreaterThanEqualsToken = 65, - AmpersandEqualsToken = 66, - BarEqualsToken = 67, - CaretEqualsToken = 68, - Identifier = 69, - BreakKeyword = 70, - CaseKeyword = 71, - CatchKeyword = 72, - ClassKeyword = 73, - ConstKeyword = 74, - ContinueKeyword = 75, - DebuggerKeyword = 76, - DefaultKeyword = 77, - DeleteKeyword = 78, - DoKeyword = 79, - ElseKeyword = 80, - EnumKeyword = 81, - ExportKeyword = 82, - ExtendsKeyword = 83, - FalseKeyword = 84, - FinallyKeyword = 85, - ForKeyword = 86, - FunctionKeyword = 87, - IfKeyword = 88, - ImportKeyword = 89, - InKeyword = 90, - InstanceOfKeyword = 91, - NewKeyword = 92, - NullKeyword = 93, - ReturnKeyword = 94, - SuperKeyword = 95, - SwitchKeyword = 96, - ThisKeyword = 97, - ThrowKeyword = 98, - TrueKeyword = 99, - TryKeyword = 100, - TypeOfKeyword = 101, - VarKeyword = 102, - VoidKeyword = 103, - WhileKeyword = 104, - WithKeyword = 105, - ImplementsKeyword = 106, - InterfaceKeyword = 107, - LetKeyword = 108, - PackageKeyword = 109, - PrivateKeyword = 110, - ProtectedKeyword = 111, - PublicKeyword = 112, - StaticKeyword = 113, - YieldKeyword = 114, - AbstractKeyword = 115, - AsKeyword = 116, - AnyKeyword = 117, - AsyncKeyword = 118, - AwaitKeyword = 119, - BooleanKeyword = 120, - ConstructorKeyword = 121, - DeclareKeyword = 122, - GetKeyword = 123, - IsKeyword = 124, - ModuleKeyword = 125, - NamespaceKeyword = 126, - NeverKeyword = 127, - ReadonlyKeyword = 128, - RequireKeyword = 129, - NumberKeyword = 130, - SetKeyword = 131, - StringKeyword = 132, - SymbolKeyword = 133, - TypeKeyword = 134, - UndefinedKeyword = 135, - FromKeyword = 136, - GlobalKeyword = 137, - OfKeyword = 138, - QualifiedName = 139, - ComputedPropertyName = 140, - TypeParameter = 141, - Parameter = 142, - Decorator = 143, - PropertySignature = 144, - PropertyDeclaration = 145, - MethodSignature = 146, - MethodDeclaration = 147, - Constructor = 148, - GetAccessor = 149, - SetAccessor = 150, - CallSignature = 151, - ConstructSignature = 152, - IndexSignature = 153, - TypePredicate = 154, - TypeReference = 155, - FunctionType = 156, - ConstructorType = 157, - TypeQuery = 158, - TypeLiteral = 159, - ArrayType = 160, - TupleType = 161, - UnionType = 162, - IntersectionType = 163, - ParenthesizedType = 164, - ThisType = 165, - LiteralType = 166, - ObjectBindingPattern = 167, - ArrayBindingPattern = 168, - BindingElement = 169, - ArrayLiteralExpression = 170, - ObjectLiteralExpression = 171, - PropertyAccessExpression = 172, - ElementAccessExpression = 173, - CallExpression = 174, - NewExpression = 175, - TaggedTemplateExpression = 176, - TypeAssertionExpression = 177, - ParenthesizedExpression = 178, - FunctionExpression = 179, - ArrowFunction = 180, - DeleteExpression = 181, - TypeOfExpression = 182, - VoidExpression = 183, - AwaitExpression = 184, - PrefixUnaryExpression = 185, - PostfixUnaryExpression = 186, - BinaryExpression = 187, - ConditionalExpression = 188, - TemplateExpression = 189, - YieldExpression = 190, - SpreadElementExpression = 191, - ClassExpression = 192, - OmittedExpression = 193, - ExpressionWithTypeArguments = 194, - AsExpression = 195, - NonNullExpression = 196, - TemplateSpan = 197, - SemicolonClassElement = 198, - Block = 199, - VariableStatement = 200, - EmptyStatement = 201, - ExpressionStatement = 202, - IfStatement = 203, - DoStatement = 204, - WhileStatement = 205, - ForStatement = 206, - ForInStatement = 207, - ForOfStatement = 208, - ContinueStatement = 209, - BreakStatement = 210, - ReturnStatement = 211, - WithStatement = 212, - SwitchStatement = 213, - LabeledStatement = 214, - ThrowStatement = 215, - TryStatement = 216, - DebuggerStatement = 217, - VariableDeclaration = 218, - VariableDeclarationList = 219, - FunctionDeclaration = 220, - ClassDeclaration = 221, - InterfaceDeclaration = 222, - TypeAliasDeclaration = 223, - EnumDeclaration = 224, - ModuleDeclaration = 225, - ModuleBlock = 226, - CaseBlock = 227, - NamespaceExportDeclaration = 228, - ImportEqualsDeclaration = 229, - ImportDeclaration = 230, - ImportClause = 231, - NamespaceImport = 232, - NamedImports = 233, - ImportSpecifier = 234, - ExportAssignment = 235, - ExportDeclaration = 236, - NamedExports = 237, - ExportSpecifier = 238, - MissingDeclaration = 239, - ExternalModuleReference = 240, - JsxElement = 241, - JsxSelfClosingElement = 242, - JsxOpeningElement = 243, - JsxText = 244, - JsxClosingElement = 245, - JsxAttribute = 246, - JsxSpreadAttribute = 247, - JsxExpression = 248, - CaseClause = 249, - DefaultClause = 250, - HeritageClause = 251, - CatchClause = 252, - PropertyAssignment = 253, - ShorthandPropertyAssignment = 254, - EnumMember = 255, - SourceFile = 256, - JSDocTypeExpression = 257, - JSDocAllType = 258, - JSDocUnknownType = 259, - JSDocArrayType = 260, - JSDocUnionType = 261, - JSDocTupleType = 262, - JSDocNullableType = 263, - JSDocNonNullableType = 264, - JSDocRecordType = 265, - JSDocRecordMember = 266, - JSDocTypeReference = 267, - JSDocOptionalType = 268, - JSDocFunctionType = 269, - JSDocVariadicType = 270, - JSDocConstructorType = 271, - JSDocThisType = 272, - JSDocComment = 273, - JSDocTag = 274, - JSDocParameterTag = 275, - JSDocReturnTag = 276, - JSDocTypeTag = 277, - JSDocTemplateTag = 278, - JSDocTypedefTag = 279, - JSDocPropertyTag = 280, - JSDocTypeLiteral = 281, - JSDocLiteralType = 282, - JSDocNullKeyword = 283, - JSDocUndefinedKeyword = 284, - JSDocNeverKeyword = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - Count = 289, - FirstAssignment = 56, - LastAssignment = 68, - FirstCompoundAssignment = 57, - LastCompoundAssignment = 68, - FirstReservedWord = 70, - LastReservedWord = 105, - FirstKeyword = 70, - LastKeyword = 138, - FirstFutureReservedWord = 106, - LastFutureReservedWord = 114, - FirstTypeNode = 154, - LastTypeNode = 166, - FirstPunctuation = 15, - LastPunctuation = 68, + JsxText = 10, + RegularExpressionLiteral = 11, + NoSubstitutionTemplateLiteral = 12, + TemplateHead = 13, + TemplateMiddle = 14, + TemplateTail = 15, + OpenBraceToken = 16, + CloseBraceToken = 17, + OpenParenToken = 18, + CloseParenToken = 19, + OpenBracketToken = 20, + CloseBracketToken = 21, + DotToken = 22, + DotDotDotToken = 23, + SemicolonToken = 24, + CommaToken = 25, + LessThanToken = 26, + LessThanSlashToken = 27, + GreaterThanToken = 28, + LessThanEqualsToken = 29, + GreaterThanEqualsToken = 30, + EqualsEqualsToken = 31, + ExclamationEqualsToken = 32, + EqualsEqualsEqualsToken = 33, + ExclamationEqualsEqualsToken = 34, + EqualsGreaterThanToken = 35, + PlusToken = 36, + MinusToken = 37, + AsteriskToken = 38, + AsteriskAsteriskToken = 39, + SlashToken = 40, + PercentToken = 41, + PlusPlusToken = 42, + MinusMinusToken = 43, + LessThanLessThanToken = 44, + GreaterThanGreaterThanToken = 45, + GreaterThanGreaterThanGreaterThanToken = 46, + AmpersandToken = 47, + BarToken = 48, + CaretToken = 49, + ExclamationToken = 50, + TildeToken = 51, + AmpersandAmpersandToken = 52, + BarBarToken = 53, + QuestionToken = 54, + ColonToken = 55, + AtToken = 56, + EqualsToken = 57, + PlusEqualsToken = 58, + MinusEqualsToken = 59, + AsteriskEqualsToken = 60, + AsteriskAsteriskEqualsToken = 61, + SlashEqualsToken = 62, + PercentEqualsToken = 63, + LessThanLessThanEqualsToken = 64, + GreaterThanGreaterThanEqualsToken = 65, + GreaterThanGreaterThanGreaterThanEqualsToken = 66, + AmpersandEqualsToken = 67, + BarEqualsToken = 68, + CaretEqualsToken = 69, + Identifier = 70, + BreakKeyword = 71, + CaseKeyword = 72, + CatchKeyword = 73, + ClassKeyword = 74, + ConstKeyword = 75, + ContinueKeyword = 76, + DebuggerKeyword = 77, + DefaultKeyword = 78, + DeleteKeyword = 79, + DoKeyword = 80, + ElseKeyword = 81, + EnumKeyword = 82, + ExportKeyword = 83, + ExtendsKeyword = 84, + FalseKeyword = 85, + FinallyKeyword = 86, + ForKeyword = 87, + FunctionKeyword = 88, + IfKeyword = 89, + ImportKeyword = 90, + InKeyword = 91, + InstanceOfKeyword = 92, + NewKeyword = 93, + NullKeyword = 94, + ReturnKeyword = 95, + SuperKeyword = 96, + SwitchKeyword = 97, + ThisKeyword = 98, + ThrowKeyword = 99, + TrueKeyword = 100, + TryKeyword = 101, + TypeOfKeyword = 102, + VarKeyword = 103, + VoidKeyword = 104, + WhileKeyword = 105, + WithKeyword = 106, + ImplementsKeyword = 107, + InterfaceKeyword = 108, + LetKeyword = 109, + PackageKeyword = 110, + PrivateKeyword = 111, + ProtectedKeyword = 112, + PublicKeyword = 113, + StaticKeyword = 114, + YieldKeyword = 115, + AbstractKeyword = 116, + AsKeyword = 117, + AnyKeyword = 118, + AsyncKeyword = 119, + AwaitKeyword = 120, + BooleanKeyword = 121, + ConstructorKeyword = 122, + DeclareKeyword = 123, + GetKeyword = 124, + IsKeyword = 125, + KeyOfKeyword = 126, + ModuleKeyword = 127, + NamespaceKeyword = 128, + NeverKeyword = 129, + ReadonlyKeyword = 130, + RequireKeyword = 131, + NumberKeyword = 132, + SetKeyword = 133, + StringKeyword = 134, + SymbolKeyword = 135, + TypeKeyword = 136, + UndefinedKeyword = 137, + FromKeyword = 138, + GlobalKeyword = 139, + OfKeyword = 140, + QualifiedName = 141, + ComputedPropertyName = 142, + TypeParameter = 143, + Parameter = 144, + Decorator = 145, + PropertySignature = 146, + PropertyDeclaration = 147, + MethodSignature = 148, + MethodDeclaration = 149, + Constructor = 150, + GetAccessor = 151, + SetAccessor = 152, + CallSignature = 153, + ConstructSignature = 154, + IndexSignature = 155, + TypePredicate = 156, + TypeReference = 157, + FunctionType = 158, + ConstructorType = 159, + TypeQuery = 160, + TypeLiteral = 161, + ArrayType = 162, + TupleType = 163, + UnionType = 164, + IntersectionType = 165, + ParenthesizedType = 166, + ThisType = 167, + TypeOperator = 168, + IndexedAccessType = 169, + MappedType = 170, + LiteralType = 171, + ObjectBindingPattern = 172, + ArrayBindingPattern = 173, + BindingElement = 174, + ArrayLiteralExpression = 175, + ObjectLiteralExpression = 176, + PropertyAccessExpression = 177, + ElementAccessExpression = 178, + CallExpression = 179, + NewExpression = 180, + TaggedTemplateExpression = 181, + TypeAssertionExpression = 182, + ParenthesizedExpression = 183, + FunctionExpression = 184, + ArrowFunction = 185, + DeleteExpression = 186, + TypeOfExpression = 187, + VoidExpression = 188, + AwaitExpression = 189, + PrefixUnaryExpression = 190, + PostfixUnaryExpression = 191, + BinaryExpression = 192, + ConditionalExpression = 193, + TemplateExpression = 194, + YieldExpression = 195, + SpreadElement = 196, + ClassExpression = 197, + OmittedExpression = 198, + ExpressionWithTypeArguments = 199, + AsExpression = 200, + NonNullExpression = 201, + TemplateSpan = 202, + SemicolonClassElement = 203, + Block = 204, + VariableStatement = 205, + EmptyStatement = 206, + ExpressionStatement = 207, + IfStatement = 208, + DoStatement = 209, + WhileStatement = 210, + ForStatement = 211, + ForInStatement = 212, + ForOfStatement = 213, + ContinueStatement = 214, + BreakStatement = 215, + ReturnStatement = 216, + WithStatement = 217, + SwitchStatement = 218, + LabeledStatement = 219, + ThrowStatement = 220, + TryStatement = 221, + DebuggerStatement = 222, + VariableDeclaration = 223, + VariableDeclarationList = 224, + FunctionDeclaration = 225, + ClassDeclaration = 226, + InterfaceDeclaration = 227, + TypeAliasDeclaration = 228, + EnumDeclaration = 229, + ModuleDeclaration = 230, + ModuleBlock = 231, + CaseBlock = 232, + NamespaceExportDeclaration = 233, + ImportEqualsDeclaration = 234, + ImportDeclaration = 235, + ImportClause = 236, + NamespaceImport = 237, + NamedImports = 238, + ImportSpecifier = 239, + ExportAssignment = 240, + ExportDeclaration = 241, + NamedExports = 242, + ExportSpecifier = 243, + MissingDeclaration = 244, + ExternalModuleReference = 245, + JsxElement = 246, + JsxSelfClosingElement = 247, + JsxOpeningElement = 248, + JsxClosingElement = 249, + JsxAttribute = 250, + JsxSpreadAttribute = 251, + JsxExpression = 252, + CaseClause = 253, + DefaultClause = 254, + HeritageClause = 255, + CatchClause = 256, + PropertyAssignment = 257, + ShorthandPropertyAssignment = 258, + SpreadAssignment = 259, + EnumMember = 260, + SourceFile = 261, + JSDocTypeExpression = 262, + JSDocAllType = 263, + JSDocUnknownType = 264, + JSDocArrayType = 265, + JSDocUnionType = 266, + JSDocTupleType = 267, + JSDocNullableType = 268, + JSDocNonNullableType = 269, + JSDocRecordType = 270, + JSDocRecordMember = 271, + JSDocTypeReference = 272, + JSDocOptionalType = 273, + JSDocFunctionType = 274, + JSDocVariadicType = 275, + JSDocConstructorType = 276, + JSDocThisType = 277, + JSDocComment = 278, + JSDocTag = 279, + JSDocAugmentsTag = 280, + JSDocParameterTag = 281, + JSDocReturnTag = 282, + JSDocTypeTag = 283, + JSDocTemplateTag = 284, + JSDocTypedefTag = 285, + JSDocPropertyTag = 286, + JSDocTypeLiteral = 287, + JSDocLiteralType = 288, + JSDocNullKeyword = 289, + JSDocUndefinedKeyword = 290, + JSDocNeverKeyword = 291, + SyntaxList = 292, + NotEmittedStatement = 293, + PartiallyEmittedExpression = 294, + MergeDeclarationMarker = 295, + EndOfDeclarationMarker = 296, + RawExpression = 297, + Count = 298, + FirstAssignment = 57, + LastAssignment = 69, + FirstCompoundAssignment = 58, + LastCompoundAssignment = 69, + FirstReservedWord = 71, + LastReservedWord = 106, + FirstKeyword = 71, + LastKeyword = 140, + FirstFutureReservedWord = 107, + LastFutureReservedWord = 115, + FirstTypeNode = 156, + LastTypeNode = 171, + FirstPunctuation = 16, + LastPunctuation = 69, FirstToken = 0, - LastToken = 138, + LastToken = 140, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 68, - FirstNode = 139, - FirstJSDocNode = 257, - LastJSDocNode = 282, - FirstJSDocTagNode = 273, - LastJSDocTagNode = 285, + LastLiteralToken = 12, + FirstTemplateToken = 12, + LastTemplateToken = 15, + FirstBinaryOperator = 26, + LastBinaryOperator = 69, + FirstNode = 141, + FirstJSDocNode = 262, + LastJSDocNode = 288, + FirstJSDocTagNode = 278, + LastJSDocTagNode = 291, } enum NodeFlags { None = 0, @@ -368,27 +378,21 @@ declare namespace ts { HasImplicitReturn = 128, HasExplicitReturn = 256, GlobalAugmentation = 512, - HasClassExtends = 1024, - HasDecorators = 2048, - HasParamDecorators = 4096, - HasAsyncFunctions = 8192, - HasJsxSpreadAttributes = 16384, - DisallowInContext = 32768, - YieldContext = 65536, - DecoratorContext = 131072, - AwaitContext = 262144, - ThisNodeHasError = 524288, - JavaScriptFile = 1048576, - ThisNodeOrAnySubNodesHasError = 2097152, - HasAggregatedChildData = 4194304, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, BlockScoped = 3, ReachabilityCheckFlags = 384, - EmitHelperFlags = 31744, - ReachabilityAndEmitFlags = 32128, - ContextFlags = 1540096, - TypeExcludesFlags = 327680, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 96256, + TypeExcludesFlags = 20480, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -406,6 +410,8 @@ declare namespace ts { AccessibilityModifier = 28, ParameterPropertyModifier = 92, NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, } enum JsxFlags { None = 0, @@ -425,39 +431,54 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type ReadonlyToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; + isInJSDocNamespace?: boolean; } interface TransientIdentifier extends Identifier { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } type EntityName = Identifier | QualifiedName; - type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +490,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -511,40 +540,45 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } - type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } + interface SpreadAssignment extends ObjectLiteralElement { + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyLikeDeclaration extends Declaration { name: PropertyName; } - interface BindingPattern extends Node { - elements: NodeArray; - } - interface ObjectBindingPattern extends BindingPattern { + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } - type ArrayBindingElement = BindingElement | OmittedExpression; - interface ArrayBindingPattern extends BindingPattern { + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -555,95 +589,133 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken; + type?: TypeNode; + } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,16 +723,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; + operator: PostfixUnaryOperator; } interface LeftHandSideExpression extends IncrementExpression { _leftHandSideExpressionBrand: any; @@ -671,42 +744,102 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +850,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } - interface SpreadElementExpression extends Expression { + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; expression: Expression; } /** @@ -752,104 +902,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1045,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1135,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1148,112 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { - name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + kind: SyntaxKind.ModuleDeclaration; + name: Identifier | StringLiteral; + body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; + } + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: JSDocNamespaceDeclaration | Identifier; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1265,126 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { - name: Identifier | LiteralExpression; + kind: SyntaxKind.JSDocRecordMember; + name: Identifier | StringLiteral | NumericLiteral; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + typeExpression: JSDocTypeExpression; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1139,8 +1403,9 @@ declare namespace ts { TrueCondition = 32, FalseCondition = 64, SwitchClause = 128, - Referenced = 256, - Shared = 512, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, Label = 12, Condition = 96, } @@ -1149,7 +1414,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1168,6 +1433,10 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + interface FlowArrayMutation extends FlowNode { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } type FlowType = Type | IncompleteType; interface IncompleteType { flags: TypeFlags; @@ -1178,8 +1447,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1515,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1332,6 +1602,7 @@ declare namespace ts { getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1352,6 +1623,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -1372,6 +1644,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1660,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1487,29 +1761,24 @@ declare namespace ts { Null = 4096, Never = 8192, TypeParameter = 16384, - Class = 32768, - Interface = 65536, - Reference = 131072, - Tuple = 262144, - Union = 524288, - Intersection = 1048576, - Anonymous = 2097152, - Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, + Object = 32768, + Union = 65536, + Intersection = 131072, + Index = 262144, + IndexedAccess = 524288, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, - StringLike = 34, + StringLike = 262178, NumberLike = 340, BooleanLike = 136, EnumLike = 272, - ObjectType = 2588672, - UnionOrIntersection = 1572864, - StructuredType = 4161536, - StructuredOrTypeParameter = 4177920, - Narrowable = 4178943, - NotUnionOrUnit = 2589191, + UnionOrIntersection = 196608, + StructuredType = 229376, + StructuredOrTypeParameter = 507904, + TypeVariable = 540672, + Narrowable = 1033215, + NotUnionOrUnit = 33281, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1530,7 +1799,21 @@ declare namespace ts { interface EnumLiteralType extends LiteralType { baseType: EnumType & UnionType; } + enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ClassOrInterface = 3, + } interface ObjectType extends Type { + objectFlags: ObjectFlags; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1558,9 +1841,24 @@ declare namespace ts { } interface IntersectionType extends UnionOrIntersectionType { } - interface TypeParameter extends Type { + type StructuredType = ObjectType | UnionType | IntersectionType; + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } + interface TypeVariable extends Type { + } + interface TypeParameter extends TypeVariable { constraint: Type; } + interface IndexedAccessType extends TypeVariable { + objectType: Type; + indexType: Type; + constraint?: Type; + } + interface IndexType extends Type { + type: TypeVariable | UnionOrIntersectionType; + } enum SignatureKind { Call = 0, Construct = 1, @@ -1579,6 +1877,11 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -1614,15 +1917,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1961,14 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; + jsxFactory?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1677,12 +1979,13 @@ declare namespace ts { target?: ScriptTarget; traceResolution?: boolean; types?: string[]; - /** Paths used to used to compute primary types search locations */ + /** Paths used to compute primary types search locations */ typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - interface TypingOptions { + interface TypeAcquisition { enableAutoDiscovery?: boolean; + enable?: boolean; include?: string[]; exclude?: string[]; [option: string]: string[] | boolean | undefined; @@ -1692,8 +1995,9 @@ declare namespace ts { projectRootPath: string; safeListPath: string; packageNameToTypingLocation: Map; - typingOptions: TypingOptions; + typeAcquisition: TypeAcquisition; compilerOptions: CompilerOptions; + unresolvedImports: ReadonlyArray; } enum ModuleKind { None = 0, @@ -1701,7 +2005,6 @@ declare namespace ts { AMD = 2, UMD = 3, System = 4, - ES6 = 5, ES2015 = 5, } enum JsxEmit { @@ -1727,21 +2030,25 @@ declare namespace ts { enum ScriptTarget { ES3 = 0, ES5 = 1, - ES6 = 2, ES2015 = 2, - Latest = 2, + ES2016 = 3, + ES2017 = 4, + ESNext = 5, + Latest = 5, } enum LanguageVariant { Standard = 0, JSX = 1, } + /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { options: CompilerOptions; - typingOptions?: TypingOptions; + typeAcquisition?: TypeAcquisition; fileNames: string[]; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1760,12 +2067,45 @@ declare namespace ts { getCurrentDirectory?(): string; getDirectories?(path: string): string[]; } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ interface ResolvedModule { + /** Path of the file the module was resolved to. */ resolvedFileName: string; + /** + * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module: + * - be a .d.ts file + * - use top level imports\exports + * - don't use tripleslash references + */ isExternalLibraryImport?: boolean; } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + */ + interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + } + enum Extension { + Ts = 0, + Tsx = 1, + Dts = 2, + Js = 3, + Jsx = 4, + LastTypeScriptExtension = 2, + } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; + resolvedModule: ResolvedModuleFull | undefined; failedLookupLocations: string[]; } interface ResolvedTypeReferenceDirective { @@ -1807,6 +2147,10 @@ declare namespace ts { _children: Node[]; } } +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.2.0"; +} declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -1823,7 +2167,11 @@ declare namespace ts { readFile(path: string, encoding?: string): string; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; @@ -1838,6 +2186,8 @@ declare namespace ts { getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; } interface FileWatcher { close(): void; @@ -1846,7 +2196,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1932,22 +2282,30 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; - function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function isParameterPropertyDeclaration(node: Node): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + }, errors?: Diagnostic[]): void; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1957,19 +2315,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,9 +2325,26 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -1995,7 +2358,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2006,13 +2369,14 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; - function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; errors: Diagnostic[]; }; } @@ -2061,6 +2425,7 @@ declare namespace ts { } interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; getLineStarts(): number[]; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; @@ -2118,6 +2483,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2521,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2546,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2562,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2594,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2649,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2662,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2684,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2791,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +3116,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; @@ -2700,5 +3131,5 @@ declare namespace ts { */ function getDefaultLibFilePath(options: CompilerOptions): string; } - + export = ts; \ No newline at end of file diff --git a/lib/typescript.js b/lib/typescript.js index 14fbdce59a8..7f41e5d07f5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -22,6 +22,7 @@ var ts; (function (ts) { // token > SyntaxKind.Identifer => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; @@ -37,346 +38,355 @@ var ts; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 10] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 11] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 11] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 12] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 12] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 13] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 14] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 13] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 14] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 15] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 15] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 16] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 17] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 18] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 19] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 20] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 21] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 22] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 23] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 24] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 25] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 26] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 27] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 28] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 29] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 30] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 31] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 32] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 33] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 34] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 35] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 36] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 37] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 38] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 39] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 40] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 41] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 42] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 43] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 44] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 45] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 46] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 47] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 48] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 49] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 50] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 51] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 52] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 53] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 54] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 55] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 16] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 17] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 18] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 19] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 20] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 21] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 22] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 23] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 24] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 25] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 26] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 27] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 28] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 29] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 30] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 31] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 32] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 33] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 34] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 35] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 36] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 37] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 38] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 39] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 40] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 41] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 42] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 43] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 44] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 45] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 47] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 48] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 49] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 50] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 51] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 52] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 53] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 54] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 55] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 56] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 56] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 57] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 58] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 59] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 60] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 61] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 62] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 63] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 64] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 65] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 66] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 67] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 68] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 57] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 58] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 59] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 60] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 61] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 62] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 63] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 64] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 65] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 67] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 68] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 69] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 69] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 70] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 70] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 71] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 72] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 73] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 74] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 75] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 76] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 77] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 78] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 79] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 80] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 81] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 82] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 83] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 84] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 85] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 86] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 87] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 88] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 89] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 90] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 91] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 92] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 93] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 94] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 95] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 96] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 97] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 98] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 99] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 100] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 101] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 102] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 103] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 104] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 105] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 71] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 72] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 73] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 74] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 75] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 76] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 77] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 78] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 79] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 80] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 81] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 82] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 83] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 84] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 85] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 86] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 87] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 88] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 89] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 90] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 91] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 92] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 93] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 94] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 95] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 96] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 97] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 98] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 99] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 100] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 101] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 102] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 103] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 104] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 105] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 106] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 106] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 107] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 108] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 109] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 110] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 111] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 112] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 113] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 114] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 107] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 108] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 109] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 110] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 111] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 112] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 113] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 114] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 115] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 115] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 116] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 117] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 118] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 119] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 120] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 121] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 122] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 123] = "GetKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 124] = "IsKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 125] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 126] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 127] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 128] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 129] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 130] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 131] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 132] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 133] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 134] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 135] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 136] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 137] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 138] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 116] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 117] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 118] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 119] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 120] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 121] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 122] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 123] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 124] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 125] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 126] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 127] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 128] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 129] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 130] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 131] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 132] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 133] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 134] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 135] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 136] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 137] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 138] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 139] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 140] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 139] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 140] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 141] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 142] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 141] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 142] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 143] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 143] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 144] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 145] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 144] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 145] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 146] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 147] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 148] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 149] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 150] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 151] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 152] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 153] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 146] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 147] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 148] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 149] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 150] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 151] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 152] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 153] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 154] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 155] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 154] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 155] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 156] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 157] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 158] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 159] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 160] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 161] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 162] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 156] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 157] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 158] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 159] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 160] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 161] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 162] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 163] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 164] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 165] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 166] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 167] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 168] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 169] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 170] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 171] = "LiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 169] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 172] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 173] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 174] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 170] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 171] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 172] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 173] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 174] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 175] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 176] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 177] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 178] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 179] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 180] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 181] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 182] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 183] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 184] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 185] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 186] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 187] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 188] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 189] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 190] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 191] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 192] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 193] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 194] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 195] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 196] = "NonNullExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 175] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 176] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 177] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 178] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 179] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 180] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 181] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 182] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 183] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 184] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 185] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 186] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 187] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 188] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 189] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 190] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 191] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 192] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 193] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 194] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 195] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 196] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 197] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 198] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 199] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 200] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 201] = "NonNullExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 197] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 198] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 202] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 203] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 199] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 200] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 201] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 202] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 203] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 204] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 205] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 206] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 207] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 208] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 209] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 210] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 211] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 212] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 213] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 214] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 215] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 216] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 217] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 218] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 219] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 220] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 221] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 222] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 223] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 224] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 225] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 226] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 227] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 228] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 229] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 230] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 231] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 232] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 233] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 234] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 235] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 236] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 237] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 238] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 239] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 204] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 205] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 206] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 207] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 208] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 209] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 210] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 211] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 212] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 213] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 214] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 215] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 216] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 217] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 218] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 219] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 220] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 221] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 222] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 223] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 224] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 225] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 226] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 227] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 228] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 229] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 230] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 231] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 232] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 233] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 234] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 235] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 236] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 237] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 238] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 239] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 240] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 241] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 242] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 243] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 244] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 240] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 241] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 242] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 243] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 244] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 245] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 246] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 247] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 248] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 246] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 247] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 248] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 249] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 250] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 251] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 252] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 249] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 250] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 251] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 252] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 253] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 254] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 255] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 256] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 253] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 254] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 257] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 258] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 259] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 255] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 260] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 256] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 261] = "SourceFile"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 257] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 262] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 258] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 263] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 259] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 260] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 261] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 262] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 263] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 264] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 265] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 266] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 267] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 268] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 269] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 270] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 271] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 272] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 273] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 274] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 275] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 276] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 277] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 278] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; - SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; - SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; - SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 264] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 265] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 266] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 267] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 268] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 269] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 270] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 271] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 272] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 273] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 274] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 275] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 276] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 277] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 278] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 279] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 280] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 281] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 282] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 283] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 284] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 285] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 286] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 287] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 288] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 289] = "JSDocNullKeyword"; + SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 290] = "JSDocUndefinedKeyword"; + SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 291] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 292] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 293] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 294] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 295] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 296] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["RawExpression"] = 297] = "RawExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 289] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 298] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 57] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 68] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 138] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 154] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 166] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 57] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 69] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 58] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 69] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 71] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 106] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 71] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 140] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 107] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 115] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 156] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 171] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 16] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 69] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 138] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 140] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 11] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 11] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; - })(ts.SyntaxKind || (ts.SyntaxKind = {})); - var SyntaxKind = ts.SyntaxKind; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 12] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 12] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 15] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 26] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 69] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 141] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 262] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 288] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 278] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 291] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; NodeFlags[NodeFlags["Let"] = 1] = "Let"; @@ -389,29 +399,24 @@ var ts; NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasClassExtends"] = 1024] = "HasClassExtends"; - NodeFlags[NodeFlags["HasDecorators"] = 2048] = "HasDecorators"; - NodeFlags[NodeFlags["HasParamDecorators"] = 4096] = "HasParamDecorators"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 8192] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["HasJsxSpreadAttributes"] = 16384] = "HasJsxSpreadAttributes"; - NodeFlags[NodeFlags["DisallowInContext"] = 32768] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 65536] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 131072] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 262144] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 524288] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 1048576] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 2097152] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 4194304] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["EmitHelperFlags"] = 31744] = "EmitHelperFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 32128] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 1540096] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; // Exclude these flags when parsing a Type - NodeFlags[NodeFlags["TypeExcludesFlags"] = 327680] = "TypeExcludesFlags"; - })(ts.NodeFlags || (ts.NodeFlags = {})); - var NodeFlags = ts.NodeFlags; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; (function (ModifierFlags) { ModifierFlags[ModifierFlags["None"] = 0] = "None"; ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; @@ -430,8 +435,10 @@ var ts; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - })(ts.ModifierFlags || (ts.ModifierFlags = {})); - var ModifierFlags = ts.ModifierFlags; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; /** An element from a named property of the JSX.IntrinsicElements interface */ @@ -439,24 +446,24 @@ var ts; /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(ts.JsxFlags || (ts.JsxFlags = {})); - var JsxFlags = ts.JsxFlags; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); /* @internal */ + var RelationComparisonResult; (function (RelationComparisonResult) { RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var RelationComparisonResult = ts.RelationComparisonResult; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ + var GeneratedIdentifierKind; (function (GeneratedIdentifierKind) { GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var GeneratedIdentifierKind = ts.GeneratedIdentifierKind; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; FlowFlags[FlowFlags["Start"] = 2] = "Start"; @@ -466,12 +473,12 @@ var ts; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(ts.FlowFlags || (ts.FlowFlags = {})); - var FlowFlags = ts.FlowFlags; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } @@ -479,6 +486,7 @@ var ts; }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; (function (ExitStatus) { // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, // when -version or -help was provided, or this was a normal compilation, no diagnostics @@ -488,8 +496,8 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; @@ -502,8 +510,9 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var TypeFormatFlags = ts.TypeFormatFlags; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol @@ -515,23 +524,29 @@ var ts; // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - })(ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolFormatFlags = ts.SymbolFormatFlags; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ + var SymbolAccessibility; (function (SymbolAccessibility) { SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SymbolAccessibility = ts.SymbolAccessibility; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; (function (TypePredicateKind) { TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); - var TypePredicateKind = ts.TypePredicateKind; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; // should be emitted using a safe fallback. @@ -549,8 +564,8 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; // with call signatures. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; (function (SymbolFlags) { SymbolFlags[SymbolFlags["None"] = 0] = "None"; SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; @@ -625,9 +640,9 @@ var ts; // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; - })(ts.SymbolFlags || (ts.SymbolFlags = {})); - var SymbolFlags = ts.SymbolFlags; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; @@ -649,8 +664,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var NodeCheckFlags = ts.NodeCheckFlags; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; (function (TypeFlags) { TypeFlags[TypeFlags["Any"] = 1] = "Any"; TypeFlags[TypeFlags["String"] = 2] = "String"; @@ -667,26 +682,19 @@ var ts; TypeFlags[TypeFlags["Null"] = 4096] = "Null"; TypeFlags[TypeFlags["Never"] = 8192] = "Never"; TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 32768] = "Class"; - TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 524288] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; /* @internal */ - TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 16777216] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; - /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -698,35 +706,49 @@ var ts; TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 507904] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 1033215] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33281] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; - })(ts.TypeFlags || (ts.TypeFlags = {})); - var TypeFlags = ts.TypeFlags; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(ts.SignatureKind || (ts.SignatureKind = {})); - var SignatureKind = ts.SignatureKind; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; - })(ts.IndexKind || (ts.IndexKind = {})); - var IndexKind = ts.IndexKind; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); /* @internal */ + var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; /// exports.name = expr @@ -737,73 +759,74 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); - var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; (function (JsxEmit) { JsxEmit[JsxEmit["None"] = 0] = "None"; JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; JsxEmit[JsxEmit["React"] = 2] = "React"; - })(ts.JsxEmit || (ts.JsxEmit = {})); - var JsxEmit = ts.JsxEmit; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; (function (NewLineKind) { NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(ts.NewLineKind || (ts.NewLineKind = {})); - var NewLineKind = ts.NewLineKind; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; (function (ScriptKind) { ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; ScriptKind[ScriptKind["JS"] = 1] = "JS"; ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - })(ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptKind = ts.ScriptKind; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES6"] = 2] = "ES6"; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["Latest"] = 2] = "Latest"; - })(ts.ScriptTarget || (ts.ScriptTarget = {})); - var ScriptTarget = ts.ScriptTarget; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; (function (LanguageVariant) { LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(ts.LanguageVariant || (ts.LanguageVariant = {})); - var LanguageVariant = ts.LanguageVariant; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); /* @internal */ + var DiagnosticStyle; (function (DiagnosticStyle) { DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; - })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); - var DiagnosticStyle = ts.DiagnosticStyle; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; (function (WatchDirectoryFlags) { WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var WatchDirectoryFlags = ts.WatchDirectoryFlags; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); /* @internal */ + var CharacterCodes; (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; @@ -930,99 +953,140 @@ var ts; CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(ts.CharacterCodes || (ts.CharacterCodes = {})); - var CharacterCodes = ts.CharacterCodes; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ + var TransformFlags; (function (TransformFlags) { TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["Jsx"] = 4] = "Jsx"; - TransformFlags[TransformFlags["ContainsJsx"] = 8] = "ContainsJsx"; - TransformFlags[TransformFlags["ES7"] = 16] = "ES7"; - TransformFlags[TransformFlags["ContainsES7"] = 32] = "ContainsES7"; - TransformFlags[TransformFlags["ES6"] = 64] = "ES6"; - TransformFlags[TransformFlags["ContainsES6"] = 128] = "ContainsES6"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 256] = "DestructuringAssignment"; - TransformFlags[TransformFlags["Generator"] = 512] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 2048] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 4096] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 131072] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpreadElementExpression"] = 262144] = "ContainsSpreadElementExpression"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 12] = "AssertJsx"; - TransformFlags[TransformFlags["AssertES7"] = 48] = "AssertES7"; - TransformFlags[TransformFlags["AssertES6"] = 192] = "AssertES6"; - TransformFlags[TransformFlags["AssertGenerator"] = 1536] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536871765] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 550710101] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 550726485] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 550593365] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 550593365] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 537590613] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546335573] = "ModuleExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 537430869] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537133909] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 538968917] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 538968917] = "ParameterExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 137216] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES6FunctionSyntaxMask"] = 81920] = "ES6FunctionSyntaxMask"; - })(ts.TransformFlags || (ts.TransformFlags = {})); - var TransformFlags = ts.TransformFlags; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 128] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + /* @internal */ + var EmitContext; + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(EmitContext = ts.EmitContext || (ts.EmitContext = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,13 +1096,12 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -1121,8 +1184,12 @@ var ts; })(ts || (ts = {})); /// /// -/* @internal */ var ts; +(function (ts) { + /** The version of the TypeScript compiler release */ + ts.version = "2.2.0"; +})(ts || (ts = {})); +/* @internal */ (function (ts) { /** * Ternary values are defined such that @@ -1133,13 +1200,15 @@ var ts; * x | y is Maybe if either x or y is Maybe, but neither x or y is True. * x | y is True if either x or y is True. */ + var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; Ternary[Ternary["Maybe"] = 1] = "Maybe"; Ternary[Ternary["True"] = -1] = "True"; - })(ts.Ternary || (ts.Ternary = {})); - var Ternary = ts.Ternary; + })(Ternary = ts.Ternary || (ts.Ternary = {})); var createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); // tslint:disable-line:no-null-keyword // Using 'delete' on an object causes V8 to put the object in dictionary mode. @@ -1164,13 +1233,21 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, - clear: clear + getKeys: getKeys, + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1200,12 +1277,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(ts.Comparison || (ts.Comparison = {})); - var Comparison = ts.Comparison; + })(Comparison = ts.Comparison || (ts.Comparison = {})); /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -1223,6 +1300,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1364,13 +1448,33 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + // Maps from T to T and avoids allocation if all elements map to themselves + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; /** * Flattens an array containing a mix of array or non-array elements. * @@ -1493,20 +1597,38 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -1519,6 +1641,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; /** * Compacts an array, removing any falsey elements. */ @@ -1540,26 +1697,86 @@ var ts; return result || array; } ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: break inner; + case 0 /* EqualTo */: continue outer; + case 1 /* GreaterThan */: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + /** + * Appends a value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param value The value to append to the array. If `value` is `undefined`, nothing is + * appended. + */ + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Appends a range of value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) // create array of indices + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) // sort indices by value then position + .map(function (i) { return array[i]; }); // get sorted array + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -1570,26 +1787,17 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ function firstOrUndefined(array) { return array && array.length > 0 ? array[0] : undefined; } ts.firstOrUndefined = firstOrUndefined; - function singleOrUndefined(array) { - return array && array.length === 1 - ? array[0] - : undefined; - } - ts.singleOrUndefined = singleOrUndefined; - function singleOrMany(array) { - return array && array.length === 1 - ? array[0] - : array; - } - ts.singleOrMany = singleOrMany; /** - * Returns the last element of an array if non-empty, undefined otherwise. + * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { return array && array.length > 0 @@ -1597,6 +1805,31 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + /** + * Returns the only element of an array if it contains only one element; otheriwse, returns the + * array. + */ + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; /** * Performs a binary search, finding the index at which 'value' occurs in 'array'. * If no such index is found, returns the 2's-complement of first index at which @@ -1604,16 +1837,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { - var low = 0; + function binarySearch(array, value, comparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1756,6 +1995,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -1789,25 +2037,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -1836,8 +2065,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -1918,6 +2147,14 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + /** Does nothing. */ + function noop() { } + ts.noop = noop; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -1929,9 +2166,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -1956,12 +2243,12 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; /* internal */ - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -1984,6 +2271,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -2024,7 +2322,8 @@ var ts; if (b === undefined) return 1 /* GreaterThan */; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { + // accent means a ≠ b, a ≠ á, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -2096,7 +2395,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2430,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2484,57 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2384,6 +2737,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -2424,73 +2781,93 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - // The * and ? wildcards should not match directories or files that start with . if they - // appear first in a component. Dotted directories and files can be included explicitly - // like so: **/.*/.* - if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -2500,7 +2877,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -2515,7 +2892,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -2564,29 +2941,35 @@ var ts; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); // Append the literal and canonical candidate base paths. - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; // 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); + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -2621,15 +3004,34 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; - function isSupportedSourceFileName(fileName, compilerOptions) { + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -2643,14 +3045,14 @@ var ts; * aligned to the offset of the highest priority extension in the * allSupportedExtensions array. */ + var ExtensionPriority; (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; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -2709,10 +3111,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -2722,10 +3120,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -2737,7 +3135,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2748,18 +3145,18 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; (function (AssertionLevel) { AssertionLevel[AssertionLevel["None"] = 0] = "None"; AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(ts.AssertionLevel || (ts.AssertionLevel = {})); - var AssertionLevel = ts.AssertionLevel; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,31 +3174,19 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. for (var i = index; i < array.length - 1; i++) { @@ -2836,6 +3221,119 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); /// var ts; @@ -3040,10 +3538,18 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -3149,6 +3655,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3158,7 +3665,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -3166,7 +3673,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -3182,6 +3689,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3261,7 +3771,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -3272,7 +3784,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { // encoding is automatically handled by the implementation in ChakraHost return ChakraHost.readFile(path); }, @@ -3290,30 +3802,55 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3362,7 +3899,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -3472,7 +4009,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -3535,6 +4071,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -3578,6 +4115,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -3588,16 +4126,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -3637,11 +4176,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3675,8 +4214,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -3688,7 +4225,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -3710,9 +4247,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -3759,6 +4294,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3782,6 +4324,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -3802,7 +4345,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -3813,6 +4356,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -3883,7 +4431,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -3912,6 +4463,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3924,7 +4476,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -3995,7 +4547,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -4032,9 +4584,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4043,7 +4602,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -4059,6 +4619,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4076,6 +4637,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -4086,9 +4648,24 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); /// @@ -4097,133 +4674,134 @@ var ts; (function (ts) { /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 69 /* Identifier */; + return token >= 70 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115 /* AbstractKeyword */, - "any": 117 /* AnyKeyword */, - "as": 116 /* AsKeyword */, - "boolean": 120 /* BooleanKeyword */, - "break": 70 /* BreakKeyword */, - "case": 71 /* CaseKeyword */, - "catch": 72 /* CatchKeyword */, - "class": 73 /* ClassKeyword */, - "continue": 75 /* ContinueKeyword */, - "const": 74 /* ConstKeyword */, - "constructor": 121 /* ConstructorKeyword */, - "debugger": 76 /* DebuggerKeyword */, - "declare": 122 /* DeclareKeyword */, - "default": 77 /* DefaultKeyword */, - "delete": 78 /* DeleteKeyword */, - "do": 79 /* DoKeyword */, - "else": 80 /* ElseKeyword */, - "enum": 81 /* EnumKeyword */, - "export": 82 /* ExportKeyword */, - "extends": 83 /* ExtendsKeyword */, - "false": 84 /* FalseKeyword */, - "finally": 85 /* FinallyKeyword */, - "for": 86 /* ForKeyword */, - "from": 136 /* FromKeyword */, - "function": 87 /* FunctionKeyword */, - "get": 123 /* GetKeyword */, - "if": 88 /* IfKeyword */, - "implements": 106 /* ImplementsKeyword */, - "import": 89 /* ImportKeyword */, - "in": 90 /* InKeyword */, - "instanceof": 91 /* InstanceOfKeyword */, - "interface": 107 /* InterfaceKeyword */, - "is": 124 /* IsKeyword */, - "let": 108 /* LetKeyword */, - "module": 125 /* ModuleKeyword */, - "namespace": 126 /* NamespaceKeyword */, - "never": 127 /* NeverKeyword */, - "new": 92 /* NewKeyword */, - "null": 93 /* NullKeyword */, - "number": 130 /* NumberKeyword */, - "package": 109 /* PackageKeyword */, - "private": 110 /* PrivateKeyword */, - "protected": 111 /* ProtectedKeyword */, - "public": 112 /* PublicKeyword */, - "readonly": 128 /* ReadonlyKeyword */, - "require": 129 /* RequireKeyword */, - "global": 137 /* GlobalKeyword */, - "return": 94 /* ReturnKeyword */, - "set": 131 /* SetKeyword */, - "static": 113 /* StaticKeyword */, - "string": 132 /* StringKeyword */, - "super": 95 /* SuperKeyword */, - "switch": 96 /* SwitchKeyword */, - "symbol": 133 /* SymbolKeyword */, - "this": 97 /* ThisKeyword */, - "throw": 98 /* ThrowKeyword */, - "true": 99 /* TrueKeyword */, - "try": 100 /* TryKeyword */, - "type": 134 /* TypeKeyword */, - "typeof": 101 /* TypeOfKeyword */, - "undefined": 135 /* UndefinedKeyword */, - "var": 102 /* VarKeyword */, - "void": 103 /* VoidKeyword */, - "while": 104 /* WhileKeyword */, - "with": 105 /* WithKeyword */, - "yield": 114 /* YieldKeyword */, - "async": 118 /* AsyncKeyword */, - "await": 119 /* AwaitKeyword */, - "of": 138 /* OfKeyword */, - "{": 15 /* OpenBraceToken */, - "}": 16 /* CloseBraceToken */, - "(": 17 /* OpenParenToken */, - ")": 18 /* CloseParenToken */, - "[": 19 /* OpenBracketToken */, - "]": 20 /* CloseBracketToken */, - ".": 21 /* DotToken */, - "...": 22 /* DotDotDotToken */, - ";": 23 /* SemicolonToken */, - ",": 24 /* CommaToken */, - "<": 25 /* LessThanToken */, - ">": 27 /* GreaterThanToken */, - "<=": 28 /* LessThanEqualsToken */, - ">=": 29 /* GreaterThanEqualsToken */, - "==": 30 /* EqualsEqualsToken */, - "!=": 31 /* ExclamationEqualsToken */, - "===": 32 /* EqualsEqualsEqualsToken */, - "!==": 33 /* ExclamationEqualsEqualsToken */, - "=>": 34 /* EqualsGreaterThanToken */, - "+": 35 /* PlusToken */, - "-": 36 /* MinusToken */, - "**": 38 /* AsteriskAsteriskToken */, - "*": 37 /* AsteriskToken */, - "/": 39 /* SlashToken */, - "%": 40 /* PercentToken */, - "++": 41 /* PlusPlusToken */, - "--": 42 /* MinusMinusToken */, - "<<": 43 /* LessThanLessThanToken */, - ">": 44 /* GreaterThanGreaterThanToken */, - ">>>": 45 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 46 /* AmpersandToken */, - "|": 47 /* BarToken */, - "^": 48 /* CaretToken */, - "!": 49 /* ExclamationToken */, - "~": 50 /* TildeToken */, - "&&": 51 /* AmpersandAmpersandToken */, - "||": 52 /* BarBarToken */, - "?": 53 /* QuestionToken */, - ":": 54 /* ColonToken */, - "=": 56 /* EqualsToken */, - "+=": 57 /* PlusEqualsToken */, - "-=": 58 /* MinusEqualsToken */, - "*=": 59 /* AsteriskEqualsToken */, - "**=": 60 /* AsteriskAsteriskEqualsToken */, - "/=": 61 /* SlashEqualsToken */, - "%=": 62 /* PercentEqualsToken */, - "<<=": 63 /* LessThanLessThanEqualsToken */, - ">>=": 64 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 66 /* AmpersandEqualsToken */, - "|=": 67 /* BarEqualsToken */, - "^=": 68 /* CaretEqualsToken */, - "@": 55 /* AtToken */ + "abstract": 116 /* AbstractKeyword */, + "any": 118 /* AnyKeyword */, + "as": 117 /* AsKeyword */, + "boolean": 121 /* BooleanKeyword */, + "break": 71 /* BreakKeyword */, + "case": 72 /* CaseKeyword */, + "catch": 73 /* CatchKeyword */, + "class": 74 /* ClassKeyword */, + "continue": 76 /* ContinueKeyword */, + "const": 75 /* ConstKeyword */, + "constructor": 122 /* ConstructorKeyword */, + "debugger": 77 /* DebuggerKeyword */, + "declare": 123 /* DeclareKeyword */, + "default": 78 /* DefaultKeyword */, + "delete": 79 /* DeleteKeyword */, + "do": 80 /* DoKeyword */, + "else": 81 /* ElseKeyword */, + "enum": 82 /* EnumKeyword */, + "export": 83 /* ExportKeyword */, + "extends": 84 /* ExtendsKeyword */, + "false": 85 /* FalseKeyword */, + "finally": 86 /* FinallyKeyword */, + "for": 87 /* ForKeyword */, + "from": 138 /* FromKeyword */, + "function": 88 /* FunctionKeyword */, + "get": 124 /* GetKeyword */, + "if": 89 /* IfKeyword */, + "implements": 107 /* ImplementsKeyword */, + "import": 90 /* ImportKeyword */, + "in": 91 /* InKeyword */, + "instanceof": 92 /* InstanceOfKeyword */, + "interface": 108 /* InterfaceKeyword */, + "is": 125 /* IsKeyword */, + "keyof": 126 /* KeyOfKeyword */, + "let": 109 /* LetKeyword */, + "module": 127 /* ModuleKeyword */, + "namespace": 128 /* NamespaceKeyword */, + "never": 129 /* NeverKeyword */, + "new": 93 /* NewKeyword */, + "null": 94 /* NullKeyword */, + "number": 132 /* NumberKeyword */, + "package": 110 /* PackageKeyword */, + "private": 111 /* PrivateKeyword */, + "protected": 112 /* ProtectedKeyword */, + "public": 113 /* PublicKeyword */, + "readonly": 130 /* ReadonlyKeyword */, + "require": 131 /* RequireKeyword */, + "global": 139 /* GlobalKeyword */, + "return": 95 /* ReturnKeyword */, + "set": 133 /* SetKeyword */, + "static": 114 /* StaticKeyword */, + "string": 134 /* StringKeyword */, + "super": 96 /* SuperKeyword */, + "switch": 97 /* SwitchKeyword */, + "symbol": 135 /* SymbolKeyword */, + "this": 98 /* ThisKeyword */, + "throw": 99 /* ThrowKeyword */, + "true": 100 /* TrueKeyword */, + "try": 101 /* TryKeyword */, + "type": 136 /* TypeKeyword */, + "typeof": 102 /* TypeOfKeyword */, + "undefined": 137 /* UndefinedKeyword */, + "var": 103 /* VarKeyword */, + "void": 104 /* VoidKeyword */, + "while": 105 /* WhileKeyword */, + "with": 106 /* WithKeyword */, + "yield": 115 /* YieldKeyword */, + "async": 119 /* AsyncKeyword */, + "await": 120 /* AwaitKeyword */, + "of": 140 /* OfKeyword */, + "{": 16 /* OpenBraceToken */, + "}": 17 /* CloseBraceToken */, + "(": 18 /* OpenParenToken */, + ")": 19 /* CloseParenToken */, + "[": 20 /* OpenBracketToken */, + "]": 21 /* CloseBracketToken */, + ".": 22 /* DotToken */, + "...": 23 /* DotDotDotToken */, + ";": 24 /* SemicolonToken */, + ",": 25 /* CommaToken */, + "<": 26 /* LessThanToken */, + ">": 28 /* GreaterThanToken */, + "<=": 29 /* LessThanEqualsToken */, + ">=": 30 /* GreaterThanEqualsToken */, + "==": 31 /* EqualsEqualsToken */, + "!=": 32 /* ExclamationEqualsToken */, + "===": 33 /* EqualsEqualsEqualsToken */, + "!==": 34 /* ExclamationEqualsEqualsToken */, + "=>": 35 /* EqualsGreaterThanToken */, + "+": 36 /* PlusToken */, + "-": 37 /* MinusToken */, + "**": 39 /* AsteriskAsteriskToken */, + "*": 38 /* AsteriskToken */, + "/": 40 /* SlashToken */, + "%": 41 /* PercentToken */, + "++": 42 /* PlusPlusToken */, + "--": 43 /* MinusMinusToken */, + "<<": 44 /* LessThanLessThanToken */, + ">": 45 /* GreaterThanGreaterThanToken */, + ">>>": 46 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 47 /* AmpersandToken */, + "|": 48 /* BarToken */, + "^": 49 /* CaretToken */, + "!": 50 /* ExclamationToken */, + "~": 51 /* TildeToken */, + "&&": 52 /* AmpersandAmpersandToken */, + "||": 53 /* BarBarToken */, + "?": 54 /* QuestionToken */, + ":": 55 /* ColonToken */, + "=": 57 /* EqualsToken */, + "+=": 58 /* PlusEqualsToken */, + "-=": 59 /* MinusEqualsToken */, + "*=": 60 /* AsteriskEqualsToken */, + "**=": 61 /* AsteriskAsteriskEqualsToken */, + "/=": 62 /* SlashEqualsToken */, + "%=": 63 /* PercentEqualsToken */, + "<<=": 64 /* LessThanLessThanEqualsToken */, + ">>=": 65 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 67 /* AmpersandEqualsToken */, + "|=": 68 /* BarEqualsToken */, + "^=": 69 /* CaretEqualsToken */, + "@": 56 /* AtToken */, }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers @@ -4727,7 +5305,7 @@ var ts; return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -4800,8 +5378,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 /* Identifier */ || token > 105 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 70 /* FirstReservedWord */ && token <= 105 /* LastReservedWord */; }, + isIdentifier: function () { return token === 70 /* Identifier */ || token > 106 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -4820,7 +5398,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -4949,7 +5527,7 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + resultingToken = startedWithBacktick ? 12 /* NoSubstitutionTemplateLiteral */ : 15 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -4957,14 +5535,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + resultingToken = startedWithBacktick ? 12 /* NoSubstitutionTemplateLiteral */ : 15 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 13 /* TemplateHead */ : 14 /* TemplateMiddle */; break; } // Escape character @@ -5142,10 +5720,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69 /* Identifier */; + return token = 70 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -5222,12 +5800,12 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 33 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 34 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 31 /* ExclamationEqualsToken */; + return pos += 2, token = 32 /* ExclamationEqualsToken */; } pos++; - return token = 49 /* ExclamationToken */; + return token = 50 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -5236,68 +5814,68 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 62 /* PercentEqualsToken */; + return pos += 2, token = 63 /* PercentEqualsToken */; } pos++; - return token = 40 /* PercentToken */; + return token = 41 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 51 /* AmpersandAmpersandToken */; + return pos += 2, token = 52 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* AmpersandEqualsToken */; + return pos += 2, token = 67 /* AmpersandEqualsToken */; } pos++; - return token = 46 /* AmpersandToken */; + return token = 47 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 17 /* OpenParenToken */; + return token = 18 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 18 /* CloseParenToken */; + return token = 19 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* AsteriskEqualsToken */; + return pos += 2, token = 60 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 60 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 61 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 38 /* AsteriskAsteriskToken */; + return pos += 2, token = 39 /* AsteriskAsteriskToken */; } pos++; - return token = 37 /* AsteriskToken */; + return token = 38 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 41 /* PlusPlusToken */; + return pos += 2, token = 42 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 57 /* PlusEqualsToken */; + return pos += 2, token = 58 /* PlusEqualsToken */; } pos++; - return token = 35 /* PlusToken */; + return token = 36 /* PlusToken */; case 44 /* comma */: pos++; - return token = 24 /* CommaToken */; + return token = 25 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 42 /* MinusMinusToken */; + return pos += 2, token = 43 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 58 /* MinusEqualsToken */; + return pos += 2, token = 59 /* MinusEqualsToken */; } pos++; - return token = 36 /* MinusToken */; + return token = 37 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 22 /* DotDotDotToken */; + return pos += 3, token = 23 /* DotDotDotToken */; } pos++; - return token = 21 /* DotToken */; + return token = 22 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -5343,10 +5921,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* SlashEqualsToken */; + return pos += 2, token = 62 /* SlashEqualsToken */; } pos++; - return token = 39 /* SlashToken */; + return token = 40 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -5399,10 +5977,10 @@ var ts; return token = 8 /* NumericLiteral */; case 58 /* colon */: pos++; - return token = 54 /* ColonToken */; + return token = 55 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 23 /* SemicolonToken */; + return token = 24 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5415,20 +5993,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 63 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 64 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 43 /* LessThanLessThanToken */; + return pos += 2, token = 44 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 28 /* LessThanEqualsToken */; + return pos += 2, token = 29 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 26 /* LessThanSlashToken */; + return pos += 2, token = 27 /* LessThanSlashToken */; } pos++; - return token = 25 /* LessThanToken */; + return token = 26 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5441,15 +6019,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 32 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 33 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 30 /* EqualsEqualsToken */; + return pos += 2, token = 31 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 34 /* EqualsGreaterThanToken */; + return pos += 2, token = 35 /* EqualsGreaterThanToken */; } pos++; - return token = 56 /* EqualsToken */; + return token = 57 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5461,43 +6039,43 @@ var ts; } } pos++; - return token = 27 /* GreaterThanToken */; + return token = 28 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 53 /* QuestionToken */; + return token = 54 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 19 /* OpenBracketToken */; + return token = 20 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 20 /* CloseBracketToken */; + return token = 21 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* CaretEqualsToken */; + return pos += 2, token = 69 /* CaretEqualsToken */; } pos++; - return token = 48 /* CaretToken */; + return token = 49 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 52 /* BarBarToken */; + return pos += 2, token = 53 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 67 /* BarEqualsToken */; + return pos += 2, token = 68 /* BarEqualsToken */; } pos++; - return token = 47 /* BarToken */; + return token = 48 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 16 /* CloseBraceToken */; + return token = 17 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 50 /* TildeToken */; + return token = 51 /* TildeToken */; case 64 /* at */: pos++; - return token = 55 /* AtToken */; + return token = 56 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -5535,29 +6113,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27 /* GreaterThanToken */) { + if (token === 28 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 45 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 46 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 65 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 44 /* GreaterThanGreaterThanToken */; + return token = 45 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 29 /* GreaterThanEqualsToken */; + return token = 30 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) { + if (token === 40 /* SlashToken */ || token === 62 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -5602,7 +6180,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10 /* RegularExpressionLiteral */; + token = 11 /* RegularExpressionLiteral */; } return token; } @@ -5610,7 +6188,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 16 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -5627,14 +6205,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 26 /* LessThanSlashToken */; + return token = 27 /* LessThanSlashToken */; } pos++; - return token = 25 /* LessThanToken */; + return token = 26 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; } while (pos < end) { pos++; @@ -5643,7 +6221,7 @@ var ts; break; } } - return token = 244 /* JsxText */; + return token = 10 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -5693,39 +6271,42 @@ var ts; return token = 5 /* WhitespaceTrivia */; case 64 /* at */: pos++; - return token = 55 /* AtToken */; + return token = 56 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: pos++; - return token = 37 /* AsteriskToken */; + return token = 38 /* AsteriskToken */; case 123 /* openBrace */: pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; case 125 /* closeBrace */: pos++; - return token = 16 /* CloseBraceToken */; + return token = 17 /* CloseBraceToken */; case 91 /* openBracket */: pos++; - return token = 19 /* OpenBracketToken */; + return token = 20 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 20 /* CloseBracketToken */; + return token = 21 /* CloseBracketToken */; case 61 /* equals */: pos++; - return token = 56 /* EqualsToken */; + return token = 57 /* EqualsToken */; case 44 /* comma */: pos++; - return token = 24 /* CommaToken */; + return token = 25 /* CommaToken */; + case 46 /* dot */: + pos++; + return token = 22 /* DotToken */; } - if (isIdentifierStart(ch, 2 /* Latest */)) { + if (isIdentifierStart(ch, 5 /* Latest */)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2 /* Latest */) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5 /* Latest */) && pos < end) { pos++; } - return token = 69 /* Identifier */; + return token = 70 /* Identifier */; } else { return pos += 1, token = 0 /* Unknown */; @@ -5843,15 +6424,16 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str_1 += " "; }, - increaseIndent: function () { }, - decreaseIndent: function () { }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, clear: function () { return str_1 = ""; }, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; } return stringWriters.pop(); @@ -5866,22 +6448,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(array1, array2, equaler) { - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } @@ -5906,7 +6472,9 @@ var ts; ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; /* @internal */ function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; /* @internal */ @@ -5935,28 +6503,28 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.flags & 2097152 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 4194304 /* HasAggregatedChildData */)) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - var thisNodeOrAnySubNodesHasError = ((node.flags & 524288 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.flags |= 2097152 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propagated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.flags |= 4194304 /* HasAggregatedChildData */; + node.flags |= 262144 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 256 /* SourceFile */) { + while (node && node.kind !== 261 /* SourceFile */) { node = node.parent; } return node; @@ -5964,11 +6532,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 199 /* Block */: - case 227 /* CaseBlock */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: return true; } return false; @@ -6043,7 +6611,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function getTokenPosOfNode(node, sourceFile, includeJsDocComment) { + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { @@ -6052,25 +6620,25 @@ var ts; if (isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); + if (node.kind === 292 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; + return node.kind >= 262 /* FirstJSDocNode */ && node.kind <= 288 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; function isJSDocTag(node) { - return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + return node.kind >= 278 /* FirstJSDocTagNode */ && node.kind <= 291 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -6104,14 +6672,14 @@ var ts; function getLiteralText(node, sourceFile, languageVersion) { // Any template literal or string literal with an extended escape // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < 2 /* ES6 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + if (languageVersion < 2 /* ES2015 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { return getQuotedEscapedLiteralText('"', node.text, '"'); } // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); - if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { + if (languageVersion < 2 /* ES2015 */ && isBinaryOrOctalIntegerLiteral(node, text)) { return node.text; } return text; @@ -6121,13 +6689,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12 /* TemplateHead */: + case 13 /* TemplateHead */: return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13 /* TemplateMiddle */: + case 14 /* TemplateMiddle */: return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14 /* TemplateTail */: + case 15 /* TemplateTail */: return getQuotedEscapedLiteralText("}", node.text, "`"); case 8 /* NumericLiteral */: return node.text; @@ -6169,25 +6737,31 @@ var ts; ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 223 /* VariableDeclaration */ && node.parent.kind === 256 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 225 /* ModuleDeclaration */ && + return node && node.kind === 230 /* ModuleDeclaration */ && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + /** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; 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); + return node.kind === 230 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 256 /* SourceFile */ || - node.kind === 225 /* ModuleDeclaration */ || + return node.kind === 261 /* SourceFile */ || + node.kind === 230 /* ModuleDeclaration */ || isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -6203,32 +6777,36 @@ var ts; return false; } switch (node.parent.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: return ts.isExternalModule(node.parent); - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 252 /* CatchClause */: - case 225 /* ModuleDeclaration */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 261 /* SourceFile */: + case 232 /* CaseBlock */: + case 256 /* CatchClause */: + case 230 /* ModuleDeclaration */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return true; - case 199 /* Block */: + case 204 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return parentNode && !isFunctionLike(parentNode); @@ -6248,13 +6826,6 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 218 /* VariableDeclaration */ && - declaration.parent && - declaration.parent.kind === 252 /* CatchClause */; - } - ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. @@ -6262,12 +6833,42 @@ var ts; return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 70 /* Identifier */: + return name.text; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + case 142 /* ComputedPropertyName */: + if (isStringOrNumericLiteral(name.expression)) { + return name.expression.text; + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 70 /* Identifier */: + return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name); + case 141 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 177 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; function createDiagnosticForNode(node, message, arg0, arg1, arg2) { var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { var span = getErrorSpanForNode(sourceFile, node); return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } - ts.createDiagnosticForNode = createDiagnosticForNode; + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -6290,7 +6891,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 199 /* Block */) { + if (node.body && node.body.kind === 204 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -6304,7 +6905,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -6313,23 +6914,23 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 223 /* TypeAliasDeclaration */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 228 /* TypeAliasDeclaration */: errorNode = node.name; break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -6352,7 +6953,7 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 224 /* EnumDeclaration */ && isConst(node); + return node.kind === 229 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -6364,12 +6965,13 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { - return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + function isSuperCall(n) { + return n.kind === 179 /* CallExpression */ && n.expression.kind === 96 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { - return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 207 /* ExpressionStatement */ + && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -6380,63 +6982,58 @@ var ts; return ts.getLeadingCommentRanges(text, node.pos); } ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJsDocComments(node, sourceFileOfNode) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - ts.getJsDocComments = getJsDocComments; - function getJsDocCommentsFromText(node, text) { - var commentRanges = (node.kind === 142 /* Parameter */ || - node.kind === 141 /* TypeParameter */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 180 /* ArrowFunction */) ? + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 144 /* Parameter */ || + node.kind === 143 /* TypeParameter */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 185 /* ArrowFunction */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { - // True if the comment starts with '/**' but not if it is '/**/' + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */; - } + }); } - ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (154 /* FirstTypeNode */ <= node.kind && node.kind <= 166 /* LastTypeNode */) { + if (156 /* FirstTypeNode */ <= node.kind && node.kind <= 171 /* LastTypeNode */) { return true; } switch (node.kind) { - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: return true; - case 103 /* VoidKeyword */: - return node.parent.kind !== 183 /* VoidExpression */; - case 194 /* ExpressionWithTypeArguments */: + case 104 /* VoidKeyword */: + return node.parent.kind !== 188 /* VoidExpression */; + case 199 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 69 /* Identifier */: + case 70 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 139 /* QualifiedName */: - case 172 /* PropertyAccessExpression */: - case 97 /* ThisKeyword */: + ts.Debug.assert(node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 141 /* QualifiedName */: + case 177 /* PropertyAccessExpression */: + case 98 /* ThisKeyword */: var parent_1 = node.parent; - if (parent_1.kind === 158 /* TypeQuery */) { + if (parent_1.kind === 160 /* TypeQuery */) { return false; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -6445,38 +7042,38 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (154 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 166 /* LastTypeNode */) { + if (156 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 171 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return node === parent_1.constraint; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 144 /* Parameter */: + case 223 /* VariableDeclaration */: return node === parent_1.type; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return node === parent_1.type; - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return node === parent_1.type; - case 177 /* TypeAssertionExpression */: + case 182 /* TypeAssertionExpression */: return node === parent_1.type; - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -6490,23 +7087,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitor(node); - case 227 /* CaseBlock */: - case 199 /* Block */: - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 212 /* WithStatement */: - case 213 /* SwitchStatement */: - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - case 214 /* LabeledStatement */: - case 216 /* TryStatement */: - case 252 /* CatchClause */: + case 232 /* CaseBlock */: + case 204 /* Block */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 217 /* WithStatement */: + case 218 /* SwitchStatement */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: + case 219 /* LabeledStatement */: + case 221 /* TryStatement */: + case 256 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -6516,18 +7113,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -6535,7 +7132,7 @@ var ts; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 140 /* ComputedPropertyName */) { + if (name_5 && name_5.kind === 142 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(name_5.expression); @@ -6551,17 +7148,35 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 162 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 157 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { - case 169 /* BindingElement */: - case 255 /* EnumMember */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 254 /* ShorthandPropertyAssignment */: - case 218 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 260 /* EnumMember */: + case 144 /* Parameter */: + case 257 /* PropertyAssignment */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 258 /* ShorthandPropertyAssignment */: + case 223 /* VariableDeclaration */: return true; } } @@ -6569,11 +7184,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 149 /* GetAccessor */ || node.kind === 150 /* SetAccessor */); + return node && (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 221 /* ClassDeclaration */ || node.kind === 192 /* ClassExpression */); + return node && (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6582,19 +7197,19 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return true; } return false; @@ -6602,13 +7217,13 @@ var ts; ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return true; } return false; @@ -6616,26 +7231,32 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: return true; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 199 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 204 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; + return node && node.kind === 149 /* MethodDeclaration */ && node.parent.kind === 176 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 149 /* MethodDeclaration */ && + (node.parent.kind === 176 /* ObjectLiteralExpression */ || + node.parent.kind === 197 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6669,7 +7290,7 @@ var ts; return undefined; } switch (node.kind) { - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -6684,9 +7305,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 142 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -6697,37 +7318,37 @@ var ts; node = node.parent; } break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 225 /* ModuleDeclaration */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 224 /* EnumDeclaration */: - case 256 /* SourceFile */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 230 /* ModuleDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 229 /* EnumDeclaration */: + case 261 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6737,26 +7358,26 @@ var ts; return node; } switch (node.kind) { - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: node = node.parent; break; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!stopOnFunctions) { continue; } - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return node; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 142 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -6772,14 +7393,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */) { + if (func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */) { var prev = func; var parent_2 = func.parent; - while (parent_2.kind === 178 /* ParenthesizedExpression */) { + while (parent_2.kind === 183 /* ParenthesizedExpression */) { prev = parent_2; parent_2 = parent_2.parent; } - if (parent_2.kind === 174 /* CallExpression */ && parent_2.expression === prev) { + if (parent_2.kind === 179 /* CallExpression */ && parent_2.expression === prev) { return parent_2; } } @@ -6790,32 +7411,32 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 172 /* PropertyAccessExpression */ || kind === 173 /* ElementAccessExpression */) - && node.expression.kind === 95 /* SuperKeyword */; + return (kind === 177 /* PropertyAccessExpression */ || kind === 178 /* ElementAccessExpression */) + && node.expression.kind === 96 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { - if (node) { - switch (node.kind) { - case 155 /* TypeReference */: - return node.typeName; - case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(isEntityNameExpression(node.expression)); - return node.expression; - case 69 /* Identifier */: - case 139 /* QualifiedName */: - return node; - } + switch (node.kind) { + case 157 /* TypeReference */: + case 272 /* JSDocTypeReference */: + return node.typeName; + case 199 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 70 /* Identifier */: + case 141 /* QualifiedName */: + return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function isCallLikeExpression(node) { switch (node.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 176 /* TaggedTemplateExpression */: - case 143 /* Decorator */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 181 /* TaggedTemplateExpression */: + case 145 /* Decorator */: return true; default: return false; @@ -6823,7 +7444,7 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -6832,25 +7453,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: // classes are valid targets return true; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 221 /* ClassDeclaration */; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: + return node.parent.kind === 226 /* ClassDeclaration */; + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && node.parent.kind === 221 /* ClassDeclaration */; - case 142 /* Parameter */: + && node.parent.kind === 226 /* ClassDeclaration */; + case 144 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return node.parent.body !== undefined - && (node.parent.kind === 148 /* Constructor */ - || node.parent.kind === 147 /* MethodDeclaration */ - || node.parent.kind === 150 /* SetAccessor */) - && node.parent.parent.kind === 221 /* ClassDeclaration */; + && (node.parent.kind === 150 /* Constructor */ + || node.parent.kind === 149 /* MethodDeclaration */ + || node.parent.kind === 152 /* SetAccessor */) + && node.parent.parent.kind === 226 /* ClassDeclaration */; } return false; } @@ -6866,19 +7487,19 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 147 /* MethodDeclaration */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 152 /* SetAccessor */: return ts.forEach(node.parameters, nodeIsDecorated); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 243 /* JsxOpeningElement */ || - parent.kind === 242 /* JsxSelfClosingElement */ || - parent.kind === 245 /* JsxClosingElement */) { + if (parent.kind === 248 /* JsxOpeningElement */ || + parent.kind === 247 /* JsxSelfClosingElement */ || + parent.kind === 249 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -6886,98 +7507,99 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - case 10 /* RegularExpressionLiteral */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 176 /* TaggedTemplateExpression */: - case 195 /* AsExpression */: - case 177 /* TypeAssertionExpression */: - case 196 /* NonNullExpression */: - case 178 /* ParenthesizedExpression */: - case 179 /* FunctionExpression */: - case 192 /* ClassExpression */: - case 180 /* ArrowFunction */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 182 /* TypeOfExpression */: - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - case 187 /* BinaryExpression */: - case 188 /* ConditionalExpression */: - case 191 /* SpreadElementExpression */: - case 189 /* TemplateExpression */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 193 /* OmittedExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 190 /* YieldExpression */: - case 184 /* AwaitExpression */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: + case 11 /* RegularExpressionLiteral */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 181 /* TaggedTemplateExpression */: + case 200 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 201 /* NonNullExpression */: + case 183 /* ParenthesizedExpression */: + case 184 /* FunctionExpression */: + case 197 /* ClassExpression */: + case 185 /* ArrowFunction */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 187 /* TypeOfExpression */: + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + case 192 /* BinaryExpression */: + case 193 /* ConditionalExpression */: + case 196 /* SpreadElement */: + case 194 /* TemplateExpression */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 198 /* OmittedExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 195 /* YieldExpression */: + case 189 /* AwaitExpression */: return true; - case 139 /* QualifiedName */: - while (node.parent.kind === 139 /* QualifiedName */) { + case 141 /* QualifiedName */: + while (node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 158 /* TypeQuery */ || isJSXTagName(node); - case 69 /* Identifier */: - if (node.parent.kind === 158 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node); + case 70 /* Identifier */: + if (node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node)) { return true; } // fall through case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: var parent_3 = node.parent; switch (parent_3.kind) { - case 218 /* VariableDeclaration */: - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 255 /* EnumMember */: - case 253 /* PropertyAssignment */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 260 /* EnumMember */: + case 257 /* PropertyAssignment */: + case 174 /* BindingElement */: return parent_3.initializer === node; - case 202 /* ExpressionStatement */: - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 211 /* ReturnStatement */: - case 212 /* WithStatement */: - case 213 /* SwitchStatement */: - case 249 /* CaseClause */: - case 215 /* ThrowStatement */: - case 213 /* SwitchStatement */: + case 207 /* ExpressionStatement */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 216 /* ReturnStatement */: + case 217 /* WithStatement */: + case 218 /* SwitchStatement */: + case 253 /* CaseClause */: + case 220 /* ThrowStatement */: + case 218 /* SwitchStatement */: return parent_3.expression === node; - case 206 /* ForStatement */: + case 211 /* ForStatement */: var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 219 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 224 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224 /* VariableDeclarationList */) || forInStatement.expression === node; - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return node === parent_3.expression; - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return node === parent_3.expression; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return node === parent_3.expression; - case 143 /* Decorator */: - case 248 /* JsxExpression */: - case 247 /* JsxSpreadAttribute */: + case 145 /* Decorator */: + case 252 /* JsxExpression */: + case 251 /* JsxSpreadAttribute */: + case 259 /* SpreadAssignment */: return true; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: if (isPartOfExpression(parent_3)) { @@ -6988,12 +7610,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7001,7 +7617,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */; + return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -7010,7 +7626,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 240 /* ExternalModuleReference */; + return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 245 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -7018,7 +7634,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 1048576 /* JavaScriptFile */); + return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; /** @@ -7028,8 +7644,8 @@ var ts; */ function isRequireCall(expression, checkArgumentIsStringLiteral) { // of the form 'require("name")' - var isRequire = expression.kind === 174 /* CallExpression */ && - expression.expression.kind === 69 /* Identifier */ && + var isRequire = expression.kind === 179 /* CallExpression */ && + expression.expression.kind === 70 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); @@ -7044,9 +7660,9 @@ var ts; * 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 */) { + if (s.valueDeclaration && s.valueDeclaration.kind === 223 /* VariableDeclaration */) { var declaration = s.valueDeclaration; - return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + return declaration.initializer && declaration.initializer.kind === 184 /* FunctionExpression */; } return false; } @@ -7057,15 +7673,15 @@ var ts; if (!isInJavaScriptFile(expression)) { return 0 /* None */; } - if (expression.kind !== 187 /* BinaryExpression */) { + if (expression.kind !== 192 /* BinaryExpression */) { return 0 /* None */; } var expr = expression; - if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 172 /* PropertyAccessExpression */) { + if (expr.operatorToken.kind !== 57 /* EqualsToken */ || expr.left.kind !== 177 /* PropertyAccessExpression */) { return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 69 /* Identifier */) { + if (lhs.expression.kind === 70 /* Identifier */) { var lhsId = lhs.expression; if (lhsId.text === "exports") { // exports.name = expr @@ -7076,13 +7692,13 @@ var ts; return 2 /* ModuleExports */; } } - else if (lhs.expression.kind === 97 /* ThisKeyword */) { + else if (lhs.expression.kind === 98 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 172 /* PropertyAccessExpression */) { + else if (lhs.expression.kind === 177 /* PropertyAccessExpression */) { // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 69 /* Identifier */) { + if (innerPropertyAccess.expression.kind === 70 /* Identifier */) { // module.exports.name = expr var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { @@ -7097,35 +7713,35 @@ var ts; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 230 /* ImportDeclaration */) { + if (node.kind === 235 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 240 /* ExternalModuleReference */) { + if (reference.kind === 245 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 236 /* ExportDeclaration */) { + if (node.kind === 241 /* ExportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 225 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (node.kind === 230 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237 /* NamespaceImport */) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 230 /* ImportDeclaration */ + return node.kind === 235 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } @@ -7133,13 +7749,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 142 /* Parameter */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 254 /* ShorthandPropertyAssignment */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 144 /* Parameter */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 258 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -7147,132 +7763,103 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 269 /* JSDocFunctionType */ && + return node.kind === 274 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 271 /* JSDocConstructorType */; + node.parameters[0].type.kind === 276 /* JSDocConstructorType */; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getJSDocTag(node, kind, checkParentVariableStatement) { - if (!node) { - return undefined; - } - var jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { - var tag = jsDocTags_1[_i]; - if (tag.kind === kind) { - return tag; - } - } + function getCommentsFromJSDoc(node) { + return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } - function append(previous, additional) { - if (additional) { - if (!previous) { - previous = []; - } - for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { - var x = additional_1[_i]; - previous.push(x); - } - } - return previous; - } - function getJSDocComments(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); - } - ts.getJSDocComments = getJSDocComments; - function getJSDocTags(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { + ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function getJSDocTags(node, kind) { + var docs = getJSDocs(node); + if (docs) { var result = []; for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { var doc = docs_1[_i]; - if (doc.tags) { - result.push.apply(result, doc.tags); + if (doc.kind === 281 /* JSDocParameterTag */) { + if (doc.kind === kind) { + result.push(doc); + } + } + else { + result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; })); } } return result; - }, function (tags) { return tags; }); + } } - function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { - // TODO: Get rid of getJsDocComments and friends (note the lowercase 's' in Js) - // TODO: A lot of this work should be cached, maybe. I guess it's only used in services right now... - var result = undefined; - // prepend documentation from parent sources - if (checkParentVariableStatement) { + function getFirstJSDocTag(node, kind) { + return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + } + function getJSDocs(node) { + var cache = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + function getJSDocsWorker(node) { + var parent = node.parent; // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** // * @param {number} name // * @returns {number} // */ // var x = function(name) { return name.length; } - var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === 200 /* VariableStatement */; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 205 /* VariableStatement */; var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === 200 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + parent.parent.kind === 205 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); - } - if (node.kind === 225 /* ModuleDeclaration */ && - node.parent && node.parent.kind === 225 /* ModuleDeclaration */) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } // Also recognize when the node is the RHS of an assignment expression - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 /* BinaryExpression */ && - parent_4.operatorToken.kind === 56 /* EqualsToken */ && - parent_4.parent.kind === 202 /* ExpressionStatement */; + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 192 /* BinaryExpression */ && + parent.operatorToken.kind === 57 /* EqualsToken */ && + parent.parent.kind === 207 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253 /* PropertyAssignment */; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + var isModuleDeclaration = node.kind === 230 /* ModuleDeclaration */ && + parent && parent.kind === 230 /* ModuleDeclaration */; + var isPropertyAssignmentExpression = parent && parent.kind === 257 /* PropertyAssignment */; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } // Pull parameter comments from declaring function as well - if (node.kind === 142 /* Parameter */) { - var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + if (node.kind === 144 /* Parameter */) { + cache = ts.concatenate(cache, getJSDocParameterTags(node)); } - } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, /*checkParentVariableStatement*/ false, getDocs, getTags)); - } - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); - } - else { - return getDocs(node.jsDocComments); + if (isVariableLike(node) && node.initializer) { + cache = ts.concatenate(cache, node.initializer.jsDoc); } + cache = ts.concatenate(cache, node.jsDoc); } - return result; } - function getJSDocParameterTag(param, checkParentVariableStatement) { + function getJSDocParameterTags(param) { + if (!isParameter(param)) { + return undefined; + } var func = param.parent; - var tags = getJSDocTags(func, checkParentVariableStatement); + var tags = getJSDocTags(func, 281 /* JSDocParameterTag */); if (!param.name) { // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */; }); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */; }); if (paramTags && 0 <= i && i < paramTags.length) { return [paramTags[i]]; } } - else if (param.name.kind === 69 /* Identifier */) { + else if (param.name.kind === 70 /* Identifier */) { var name_6 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); - if (paramTags) { - return paramTags; - } + return ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); } else { // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines @@ -7280,40 +7867,30 @@ var ts; return undefined; } } - function getJSDocTypeTag(node) { - return getJSDocTag(node, 277 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 283 /* JSDocTypeTag */); + if (!tag && node.kind === 144 /* Parameter */) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; } - ts.getJSDocTypeTag = getJSDocTypeTag; + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 280 /* JSDocAugmentsTag */); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 276 /* JSDocReturnTag */, /*checkParentVariableStatement*/ true); + return getFirstJSDocTag(node, 282 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 278 /* JSDocTemplateTag */, /*checkParentVariableStatement*/ false); + return getFirstJSDocTag(node, 284 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter) { - if (parameter.name && parameter.name.kind === 69 /* Identifier */) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - var parameterName = parameter.name.text; - var jsDocTags = getJSDocTags(parameter.parent, /*checkParentVariableStatement*/ true); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { - var tag = jsDocTags_2[_i]; - if (tag.kind === 275 /* JSDocParameterTag */) { - var parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } - } - } - return undefined; - } - ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -7323,14 +7900,11 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 1048576 /* JavaScriptFile */)) { - if (node.type && node.type.kind === 270 /* JSDocVariadicType */) { + if (node && (node.flags & 65536 /* JavaScriptFile */)) { + if (node.type && node.type.kind === 275 /* JSDocVariadicType */ || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275 /* JSDocVariadicType */; })) { return true; } - var paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 270 /* JSDocVariadicType */; - } } return isDeclaredRestParam(node); } @@ -7339,29 +7913,53 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 192 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 57 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 42 /* PlusPlusToken */ || unaryOperator === 43 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 183 /* ParenthesizedExpression */: + case 175 /* ArrayLiteralExpression */: + case 196 /* SpreadElement */: + node = parent; + break; + case 258 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + // Fall through + case 257 /* PropertyAssignment */: + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { - while (node.parent.kind === 178 /* ParenthesizedExpression */) { - node = node.parent; - } - while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 /* ArrayLiteralExpression */ || parent_5.kind === 191 /* SpreadElementExpression */) { - node = parent_5; - continue; - } - if (parent_5.kind === 253 /* PropertyAssignment */ || parent_5.kind === 254 /* ShorthandPropertyAssignment */) { - node = parent_5.parent; - continue; - } - return parent_5.kind === 187 /* BinaryExpression */ && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && - parent_5.initializer === node; - } + return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; function isNodeDescendantOf(node, ancestor) { @@ -7375,7 +7973,7 @@ var ts; ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (hasModifier(node, 2 /* Ambient */) || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { + if (hasModifier(node, 2 /* Ambient */) || (node.kind === 261 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -7385,11 +7983,11 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { + if (name.kind !== 70 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { return false; } var parent = name.parent; - if (parent.kind === 234 /* ImportSpecifier */ || parent.kind === 238 /* ExportSpecifier */) { + if (parent.kind === 239 /* ImportSpecifier */ || parent.kind === 243 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -7402,7 +8000,7 @@ var ts; ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 140 /* ComputedPropertyName */ && + node.parent.kind === 142 /* ComputedPropertyName */ && isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -7410,31 +8008,31 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 255 /* EnumMember */: - case 253 /* PropertyAssignment */: - case 172 /* PropertyAccessExpression */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 260 /* EnumMember */: + case 257 /* PropertyAssignment */: + case 177 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 139 /* QualifiedName */) { + while (parent.kind === 141 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 158 /* TypeQuery */; + return parent.kind === 160 /* TypeQuery */; } return false; - case 169 /* BindingElement */: - case 234 /* ImportSpecifier */: + case 174 /* BindingElement */: + case 239 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -7450,13 +8048,13 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 228 /* NamespaceExportDeclaration */ || - node.kind === 231 /* ImportClause */ && !!node.name || - node.kind === 232 /* NamespaceImport */ || - node.kind === 234 /* ImportSpecifier */ || - node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 234 /* ImportEqualsDeclaration */ || + node.kind === 233 /* NamespaceExportDeclaration */ || + node.kind === 236 /* ImportClause */ && !!node.name || + node.kind === 237 /* NamespaceImport */ || + node.kind === 239 /* ImportSpecifier */ || + node.kind === 243 /* ExportSpecifier */ || + node.kind === 240 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7464,17 +8062,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 106 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 107 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -7542,7 +8140,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 /* FirstKeyword */ <= token && token <= 138 /* LastKeyword */; + return 71 /* FirstKeyword */ <= token && token <= 140 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -7553,8 +8151,10 @@ var ts; return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; - function isStringOrNumericLiteral(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; /** @@ -7569,8 +8169,8 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 140 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression.kind) && + return name.kind === 142 /* ComputedPropertyName */ && + !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -7584,10 +8184,10 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 142 /* Parameter */) { + if (name.kind === 70 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 144 /* Parameter */) { return name.text; } - if (name.kind === 140 /* ComputedPropertyName */) { + if (name.kind === 142 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -7608,22 +8208,26 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 69 /* Identifier */ && node.text === "Symbol"; + return node.kind === 70 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.text === "push" || node.text === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isModifierKind(token) { switch (token) { - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 122 /* DeclareKeyword */: - case 77 /* DefaultKeyword */: - case 82 /* ExportKeyword */: - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 128 /* ReadonlyKeyword */: - case 113 /* StaticKeyword */: + case 116 /* AbstractKeyword */: + case 119 /* AsyncKeyword */: + case 75 /* ConstKeyword */: + case 123 /* DeclareKeyword */: + case 78 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 130 /* ReadonlyKeyword */: + case 114 /* StaticKeyword */: return true; } return false; @@ -7631,11 +8235,11 @@ var ts; ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 142 /* Parameter */; + return root.kind === 144 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 169 /* BindingElement */) { + while (node.kind === 174 /* BindingElement */) { node = node.parent.parent; } return node; @@ -7643,35 +8247,29 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 148 /* Constructor */ - || kind === 179 /* FunctionExpression */ - || kind === 220 /* FunctionDeclaration */ - || kind === 180 /* ArrowFunction */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 225 /* ModuleDeclaration */ - || kind === 256 /* SourceFile */; + return kind === 150 /* Constructor */ + || kind === 184 /* FunctionExpression */ + || kind === 225 /* FunctionDeclaration */ + || kind === 185 /* ArrowFunction */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 230 /* ModuleDeclaration */ + || kind === 261 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - function getOriginalNode(node) { + function getOriginalNode(node, nodeTest) { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; /** @@ -7711,45 +8309,45 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; Associativity[Associativity["Right"] = 1] = "Right"; - })(ts.Associativity || (ts.Associativity = {})); - var Associativity = ts.Associativity; + })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 175 /* NewExpression */: + case 180 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 185 /* PrefixUnaryExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 184 /* AwaitExpression */: - case 188 /* ConditionalExpression */: - case 190 /* YieldExpression */: + case 190 /* PrefixUnaryExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 189 /* AwaitExpression */: + case 193 /* ConditionalExpression */: + case 195 /* YieldExpression */: return 1 /* Right */; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (operator) { - case 38 /* AsteriskAsteriskToken */: - case 56 /* EqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 67 /* BarEqualsToken */: + case 39 /* AsteriskAsteriskToken */: + case 57 /* EqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 68 /* BarEqualsToken */: return 1 /* Right */; } } @@ -7758,15 +8356,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 187 /* BinaryExpression */) { + if (expression.kind === 192 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 185 /* PrefixUnaryExpression */ || expression.kind === 186 /* PostfixUnaryExpression */) { + else if (expression.kind === 190 /* PrefixUnaryExpression */ || expression.kind === 191 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -7776,106 +8374,107 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 69 /* Identifier */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 70 /* Identifier */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 189 /* TemplateExpression */: - case 178 /* ParenthesizedExpression */: - case 193 /* OmittedExpression */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 197 /* ClassExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 11 /* RegularExpressionLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 194 /* TemplateExpression */: + case 183 /* ParenthesizedExpression */: + case 198 /* OmittedExpression */: + case 297 /* RawExpression */: return 19; - case 176 /* TaggedTemplateExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 181 /* TaggedTemplateExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: return 18; - case 175 /* NewExpression */: + case 180 /* NewExpression */: return hasArguments ? 18 : 17; - case 174 /* CallExpression */: + case 179 /* CallExpression */: return 17; - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return 16; - case 185 /* PrefixUnaryExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 184 /* AwaitExpression */: + case 190 /* PrefixUnaryExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 189 /* AwaitExpression */: return 15; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (operatorKind) { - case 49 /* ExclamationToken */: - case 50 /* TildeToken */: + case 50 /* ExclamationToken */: + case 51 /* TildeToken */: return 15; - case 38 /* AsteriskAsteriskToken */: - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: + case 39 /* AsteriskAsteriskToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: return 14; - case 35 /* PlusToken */: - case 36 /* MinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: return 13; - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 25 /* LessThanToken */: - case 28 /* LessThanEqualsToken */: - case 27 /* GreaterThanToken */: - case 29 /* GreaterThanEqualsToken */: - case 90 /* InKeyword */: - case 91 /* InstanceOfKeyword */: + case 26 /* LessThanToken */: + case 29 /* LessThanEqualsToken */: + case 28 /* GreaterThanToken */: + case 30 /* GreaterThanEqualsToken */: + case 91 /* InKeyword */: + case 92 /* InstanceOfKeyword */: return 11; - case 30 /* EqualsEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return 10; - case 46 /* AmpersandToken */: + case 47 /* AmpersandToken */: return 9; - case 48 /* CaretToken */: + case 49 /* CaretToken */: return 8; - case 47 /* BarToken */: + case 48 /* BarToken */: return 7; - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return 6; - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return 5; - case 56 /* EqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 67 /* BarEqualsToken */: + case 57 /* EqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 68 /* BarEqualsToken */: return 3; - case 24 /* CommaToken */: + case 25 /* CommaToken */: return 0; default: return -1; } - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return 4; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return 2; - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return 1; default: return -1; @@ -8125,24 +8724,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,23 +8742,38 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - var sourceFiles = host.getSourceFiles(); + var sourceFiles = getAllEmittableSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, isNonDeclarationFile); + var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); }); + } + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles(); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. */ + function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) { + return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); }); + } + ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory; function isNonDeclarationFile(sourceFile) { return !isDeclarationFile(sourceFile); } + /** + * Whether a file should be emitted in a non-`--outFile` case. + * Don't emit if source file is a declaration file, or was located under node_modules + */ + function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + } function isBundleEmitNonExternalModule(sourceFile) { - return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } /** * Iterates over each source file to emit. The source files are expected to have been @@ -8184,11 +8786,11 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { @@ -8217,10 +8819,10 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } - function onBundledEmit(host, sourceFiles) { + function onBundledEmit(sourceFiles) { if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -8242,18 +8844,17 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { onBundledEmit(host); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - // Don't emit if source file is a declaration file, or was located under node_modules - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) { onSingleFileEmit(host, sourceFile); } } @@ -8275,20 +8876,21 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with // --module or --target es6 specified. Files included by searching under node_modules are also not emitted. - var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8898,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8325,21 +8927,41 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 148 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 150 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 70 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 98 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8347,10 +8969,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 149 /* GetAccessor */) { + if (accessor.kind === 151 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 150 /* SetAccessor */) { + else if (accessor.kind === 152 /* SetAccessor */) { setAccessor = accessor; } else { @@ -8359,7 +8981,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) + if ((member.kind === 151 /* GetAccessor */ || member.kind === 152 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -8370,10 +8992,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 149 /* GetAccessor */ && !getAccessor) { + if (member.kind === 151 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 150 /* SetAccessor */ && !setAccessor) { + if (member.kind === 152 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -8600,7 +9222,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; @@ -8609,47 +9231,53 @@ var ts; ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 32 /* Static */; - case 112 /* PublicKeyword */: return 4 /* Public */; - case 111 /* ProtectedKeyword */: return 16 /* Protected */; - case 110 /* PrivateKeyword */: return 8 /* Private */; - case 115 /* AbstractKeyword */: return 128 /* Abstract */; - case 82 /* ExportKeyword */: return 1 /* Export */; - case 122 /* DeclareKeyword */: return 2 /* Ambient */; - case 74 /* ConstKeyword */: return 2048 /* Const */; - case 77 /* DefaultKeyword */: return 512 /* Default */; - case 118 /* AsyncKeyword */: return 256 /* Async */; - case 128 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 114 /* StaticKeyword */: return 32 /* Static */; + case 113 /* PublicKeyword */: return 4 /* Public */; + case 112 /* ProtectedKeyword */: return 16 /* Protected */; + case 111 /* PrivateKeyword */: return 8 /* Private */; + case 116 /* AbstractKeyword */: return 128 /* Abstract */; + case 83 /* ExportKeyword */: return 1 /* Export */; + case 123 /* DeclareKeyword */: return 2 /* Ambient */; + case 75 /* ConstKeyword */: return 2048 /* Const */; + case 78 /* DefaultKeyword */: return 512 /* Default */; + case 119 /* AsyncKeyword */: return 256 /* Async */; + case 130 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 52 /* BarBarToken */ - || token === 51 /* AmpersandAmpersandToken */ - || token === 49 /* ExclamationToken */; + return token === 53 /* BarBarToken */ + || token === 52 /* AmpersandAmpersandToken */ + || token === 50 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; + return token >= 57 /* FirstAssignment */ && token <= 69 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 194 /* ExpressionWithTypeArguments */ && - node.parent.token === 83 /* ExtendsKeyword */ && + if (node.kind === 199 /* ExpressionWithTypeArguments */ && + node.parent.token === 84 /* ExtendsKeyword */ && isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 57 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === 56 /* EqualsToken */) { - var kind = node.left.kind; - return kind === 171 /* ObjectLiteralExpression */ - || kind === 170 /* ArrayLiteralExpression */; - } + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 176 /* ObjectLiteralExpression */ + || kind === 175 /* ArrayLiteralExpression */; } return false; } @@ -8661,7 +9289,7 @@ var ts; } ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { return true; } else if (isPropertyAccessExpression(node)) { @@ -8676,21 +9304,21 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isEntityNameExpression(node) { - return node.kind === 69 /* Identifier */ || - node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 70 /* Identifier */ || + node.kind === 177 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 171 /* ObjectLiteralExpression */) { + if (kind === 176 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 170 /* ArrayLiteralExpression */) { + if (kind === 175 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -8700,14 +9328,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - 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; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8747,47 +9367,6 @@ var ts; } return output; } - /** - * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph - * as the fallback implementation does not check for circular references by default. - */ - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - /** - * Serialize an object graph into a JSON string. - */ - function stringifyFallback(value) { - // JSON.stringify returns `undefined` here, instead of the string "undefined". - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -8820,12 +9399,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8856,49 +9429,49 @@ var ts; var kind = node.kind; if (kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 10 /* RegularExpressionLiteral */ - || kind === 11 /* NoSubstitutionTemplateLiteral */ - || kind === 69 /* Identifier */ - || kind === 97 /* ThisKeyword */ - || kind === 95 /* SuperKeyword */ - || kind === 99 /* TrueKeyword */ - || kind === 84 /* FalseKeyword */ - || kind === 93 /* NullKeyword */) { + || kind === 11 /* RegularExpressionLiteral */ + || kind === 12 /* NoSubstitutionTemplateLiteral */ + || kind === 70 /* Identifier */ + || kind === 98 /* ThisKeyword */ + || kind === 96 /* SuperKeyword */ + || kind === 100 /* TrueKeyword */ + || kind === 85 /* FalseKeyword */ + || kind === 94 /* NullKeyword */) { return true; } - else if (kind === 172 /* PropertyAccessExpression */) { + else if (kind === 177 /* PropertyAccessExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 173 /* ElementAccessExpression */) { + else if (kind === 178 /* ElementAccessExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1) && isSimpleExpressionWorker(node.argumentExpression, depth + 1); } - else if (kind === 185 /* PrefixUnaryExpression */ - || kind === 186 /* PostfixUnaryExpression */) { + else if (kind === 190 /* PrefixUnaryExpression */ + || kind === 191 /* PostfixUnaryExpression */) { return isSimpleExpressionWorker(node.operand, depth + 1); } - else if (kind === 187 /* BinaryExpression */) { - return node.operatorToken.kind !== 38 /* AsteriskAsteriskToken */ + else if (kind === 192 /* BinaryExpression */) { + return node.operatorToken.kind !== 39 /* AsteriskAsteriskToken */ && isSimpleExpressionWorker(node.left, depth + 1) && isSimpleExpressionWorker(node.right, depth + 1); } - else if (kind === 188 /* ConditionalExpression */) { + else if (kind === 193 /* ConditionalExpression */) { return isSimpleExpressionWorker(node.condition, depth + 1) && isSimpleExpressionWorker(node.whenTrue, depth + 1) && isSimpleExpressionWorker(node.whenFalse, depth + 1); } - else if (kind === 183 /* VoidExpression */ - || kind === 182 /* TypeOfExpression */ - || kind === 181 /* DeleteExpression */) { + else if (kind === 188 /* VoidExpression */ + || kind === 187 /* TypeOfExpression */ + || kind === 186 /* DeleteExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 170 /* ArrayLiteralExpression */) { + else if (kind === 175 /* ArrayLiteralExpression */) { return node.elements.length === 0; } - else if (kind === 171 /* ObjectLiteralExpression */) { + else if (kind === 176 /* ObjectLiteralExpression */) { return node.properties.length === 0; } - else if (kind === 174 /* CallExpression */) { + else if (kind === 179 /* CallExpression */) { if (!isSimpleExpressionWorker(node.expression, depth + 1)) { return false; } @@ -8938,7 +9511,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,67 +9627,25 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; - function collectExternalModuleInfo(sourceFile, resolver) { - var externalImports = []; - var exportSpecifiers = ts.createMap(); - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 230 /* ImportDeclaration */: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - case 229 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - case 236 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_8 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); - } - } - break; - case 235 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; } } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + return false; } - ts.collectExternalModuleInfo = collectExternalModuleInfo; + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; function getInitializedVariables(node) { return ts.filter(node.declarations, isInitializedVariable); } @@ -9129,7 +9660,7 @@ var ts; if (node.symbol) { for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 /* ClassDeclaration */ && declaration !== node) { + if (declaration.kind === 226 /* ClassDeclaration */ && declaration !== node) { return true; } } @@ -9159,15 +9690,15 @@ var ts; ts.isNodeArray = isNodeArray; // Literals function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 11 /* NoSubstitutionTemplateLiteral */; + return node.kind === 12 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 12 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; + return kind === 9 /* StringLiteral */ || kind === 12 /* NoSubstitutionTemplateLiteral */; } ts.isTextualLiteralKind = isTextualLiteralKind; function isLiteralExpression(node) { @@ -9176,21 +9707,22 @@ var ts; ts.isLiteralExpression = isLiteralExpression; // Pseudo-literals function isTemplateLiteralKind(kind) { - return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; + return 12 /* FirstTemplateToken */ <= kind && kind <= 15 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ - || kind === 14 /* TemplateTail */; + function isTemplateHead(node) { + return node.kind === 13 /* TemplateHead */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 14 /* TemplateMiddle */ + || kind === 15 /* TemplateTail */; } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { - return node.kind === 69 /* Identifier */; + return node.kind === 70 /* Identifier */; } ts.isIdentifier = isIdentifier; function isGeneratedIdentifier(node) { @@ -9205,90 +9737,91 @@ var ts; ts.isModifier = isModifier; // Names function isQualifiedName(node) { - return node.kind === 139 /* QualifiedName */; + return node.kind === 141 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 140 /* ComputedPropertyName */; + return node.kind === 142 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; function isEntityName(node) { var kind = node.kind; - return kind === 139 /* QualifiedName */ - || kind === 69 /* Identifier */; + return kind === 141 /* QualifiedName */ + || kind === 70 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ + return kind === 70 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 140 /* ComputedPropertyName */; + || kind === 142 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isModuleName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ + return kind === 70 /* Identifier */ || kind === 9 /* StringLiteral */; } ts.isModuleName = isModuleName; function isBindingName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ - || kind === 167 /* ObjectBindingPattern */ - || kind === 168 /* ArrayBindingPattern */; + return kind === 70 /* Identifier */ + || kind === 172 /* ObjectBindingPattern */ + || kind === 173 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Signature elements function isTypeParameter(node) { - return node.kind === 141 /* TypeParameter */; + return node.kind === 143 /* TypeParameter */; } ts.isTypeParameter = isTypeParameter; function isParameter(node) { - return node.kind === 142 /* Parameter */; + return node.kind === 144 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 143 /* Decorator */; + return node.kind === 145 /* Decorator */; } ts.isDecorator = isDecorator; // Type members function isMethodDeclaration(node) { - return node.kind === 147 /* MethodDeclaration */; + return node.kind === 149 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isClassElement(node) { var kind = node.kind; - return kind === 148 /* Constructor */ - || kind === 145 /* PropertyDeclaration */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 153 /* IndexSignature */ - || kind === 198 /* SemicolonClassElement */; + return kind === 150 /* Constructor */ + || kind === 147 /* PropertyDeclaration */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 155 /* IndexSignature */ + || kind === 203 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 253 /* PropertyAssignment */ - || kind === 254 /* ShorthandPropertyAssignment */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 239 /* MissingDeclaration */; + return kind === 257 /* PropertyAssignment */ + || kind === 258 /* ShorthandPropertyAssignment */ + || kind === 259 /* SpreadAssignment */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 244 /* MissingDeclaration */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) - || kind === 117 /* AnyKeyword */ - || kind === 130 /* NumberKeyword */ - || kind === 120 /* BooleanKeyword */ - || kind === 132 /* StringKeyword */ - || kind === 133 /* SymbolKeyword */ - || kind === 103 /* VoidKeyword */ - || kind === 127 /* NeverKeyword */ - || kind === 194 /* ExpressionWithTypeArguments */; + return (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */) + || kind === 118 /* AnyKeyword */ + || kind === 132 /* NumberKeyword */ + || kind === 121 /* BooleanKeyword */ + || kind === 134 /* StringKeyword */ + || kind === 135 /* SymbolKeyword */ + || kind === 104 /* VoidKeyword */ + || kind === 129 /* NeverKeyword */ + || kind === 199 /* ExpressionWithTypeArguments */; } /** * Node test that determines whether a node is a valid type node. @@ -9300,98 +9833,166 @@ var ts; } ts.isTypeNode = isTypeNode; // Binding patterns + function isArrayBindingPattern(node) { + return node.kind === 173 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isObjectBindingPattern(node) { + return node.kind === 172 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 168 /* ArrayBindingPattern */ - || kind === 167 /* ObjectBindingPattern */; + return kind === 173 /* ArrayBindingPattern */ + || kind === 172 /* ObjectBindingPattern */; } return false; } ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 175 /* ArrayLiteralExpression */ + || kind === 176 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; function isBindingElement(node) { - return node.kind === 169 /* BindingElement */; + return node.kind === 174 /* BindingElement */; } ts.isBindingElement = isBindingElement; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 169 /* BindingElement */ - || kind === 193 /* OmittedExpression */; + return kind === 174 /* BindingElement */ + || kind === 198 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 174 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 172 /* ObjectBindingPattern */: + case 176 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; // Expression + function isArrayLiteralExpression(node) { + return node.kind === 175 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 176 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 172 /* PropertyAccessExpression */; + return node.kind === 177 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 173 /* ElementAccessExpression */; + return node.kind === 178 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isBinaryExpression(node) { - return node.kind === 187 /* BinaryExpression */; + return node.kind === 192 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 188 /* ConditionalExpression */; + return node.kind === 193 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isCallExpression(node) { - return node.kind === 174 /* CallExpression */; + return node.kind === 179 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; - return kind === 189 /* TemplateExpression */ - || kind === 11 /* NoSubstitutionTemplateLiteral */; + return kind === 194 /* TemplateExpression */ + || kind === 12 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; - function isSpreadElementExpression(node) { - return node.kind === 191 /* SpreadElementExpression */; + ts.isTemplateLiteral = isTemplateLiteral; + function isSpreadExpression(node) { + return node.kind === 196 /* SpreadElement */; } - ts.isSpreadElementExpression = isSpreadElementExpression; + ts.isSpreadExpression = isSpreadExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 194 /* ExpressionWithTypeArguments */; + return node.kind === 199 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isLeftHandSideExpressionKind(kind) { - return kind === 172 /* PropertyAccessExpression */ - || kind === 173 /* ElementAccessExpression */ - || kind === 175 /* NewExpression */ - || kind === 174 /* CallExpression */ - || kind === 241 /* JsxElement */ - || kind === 242 /* JsxSelfClosingElement */ - || kind === 176 /* TaggedTemplateExpression */ - || kind === 170 /* ArrayLiteralExpression */ - || kind === 178 /* ParenthesizedExpression */ - || kind === 171 /* ObjectLiteralExpression */ - || kind === 192 /* ClassExpression */ - || kind === 179 /* FunctionExpression */ - || kind === 69 /* Identifier */ - || kind === 10 /* RegularExpressionLiteral */ + return kind === 177 /* PropertyAccessExpression */ + || kind === 178 /* ElementAccessExpression */ + || kind === 180 /* NewExpression */ + || kind === 179 /* CallExpression */ + || kind === 246 /* JsxElement */ + || kind === 247 /* JsxSelfClosingElement */ + || kind === 181 /* TaggedTemplateExpression */ + || kind === 175 /* ArrayLiteralExpression */ + || kind === 183 /* ParenthesizedExpression */ + || kind === 176 /* ObjectLiteralExpression */ + || kind === 197 /* ClassExpression */ + || kind === 184 /* FunctionExpression */ + || kind === 70 /* Identifier */ + || kind === 11 /* RegularExpressionLiteral */ || kind === 8 /* NumericLiteral */ || kind === 9 /* StringLiteral */ - || kind === 11 /* NoSubstitutionTemplateLiteral */ - || kind === 189 /* TemplateExpression */ - || kind === 84 /* FalseKeyword */ - || kind === 93 /* NullKeyword */ - || kind === 97 /* ThisKeyword */ - || kind === 99 /* TrueKeyword */ - || kind === 95 /* SuperKeyword */ - || kind === 196 /* NonNullExpression */; + || kind === 12 /* NoSubstitutionTemplateLiteral */ + || kind === 194 /* TemplateExpression */ + || kind === 85 /* FalseKeyword */ + || kind === 94 /* NullKeyword */ + || kind === 98 /* ThisKeyword */ + || kind === 100 /* TrueKeyword */ + || kind === 96 /* SuperKeyword */ + || kind === 201 /* NonNullExpression */ + || kind === 297 /* RawExpression */; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isUnaryExpressionKind(kind) { - return kind === 185 /* PrefixUnaryExpression */ - || kind === 186 /* PostfixUnaryExpression */ - || kind === 181 /* DeleteExpression */ - || kind === 182 /* TypeOfExpression */ - || kind === 183 /* VoidExpression */ - || kind === 184 /* AwaitExpression */ - || kind === 177 /* TypeAssertionExpression */ + return kind === 190 /* PrefixUnaryExpression */ + || kind === 191 /* PostfixUnaryExpression */ + || kind === 186 /* DeleteExpression */ + || kind === 187 /* TypeOfExpression */ + || kind === 188 /* VoidExpression */ + || kind === 189 /* AwaitExpression */ + || kind === 182 /* TypeAssertionExpression */ || isLeftHandSideExpressionKind(kind); } function isUnaryExpression(node) { @@ -9399,13 +10000,14 @@ var ts; } ts.isUnaryExpression = isUnaryExpression; function isExpressionKind(kind) { - return kind === 188 /* ConditionalExpression */ - || kind === 190 /* YieldExpression */ - || kind === 180 /* ArrowFunction */ - || kind === 187 /* BinaryExpression */ - || kind === 191 /* SpreadElementExpression */ - || kind === 195 /* AsExpression */ - || kind === 193 /* OmittedExpression */ + return kind === 193 /* ConditionalExpression */ + || kind === 195 /* YieldExpression */ + || kind === 185 /* ArrowFunction */ + || kind === 192 /* BinaryExpression */ + || kind === 196 /* SpreadElement */ + || kind === 200 /* AsExpression */ + || kind === 198 /* OmittedExpression */ + || kind === 297 /* RawExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -9414,16 +10016,16 @@ var ts; ts.isExpression = isExpression; function isAssertionExpression(node) { var kind = node.kind; - return kind === 177 /* TypeAssertionExpression */ - || kind === 195 /* AsExpression */; + return kind === 182 /* TypeAssertionExpression */ + || kind === 200 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288 /* PartiallyEmittedExpression */; + return node.kind === 294 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287 /* NotEmittedStatement */; + return node.kind === 293 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -9432,17 +10034,17 @@ var ts; } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isOmittedExpression(node) { - return node.kind === 193 /* OmittedExpression */; + return node.kind === 198 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; // Misc function isTemplateSpan(node) { - return node.kind === 197 /* TemplateSpan */; + return node.kind === 202 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; // Element function isBlock(node) { - return node.kind === 199 /* Block */; + return node.kind === 204 /* Block */; } ts.isBlock = isBlock; function isConciseBody(node) { @@ -9460,119 +10062,121 @@ var ts; } ts.isForInitializer = isForInitializer; function isVariableDeclaration(node) { - return node.kind === 218 /* VariableDeclaration */; + return node.kind === 223 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 219 /* VariableDeclarationList */; + return node.kind === 224 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isCaseBlock(node) { - return node.kind === 227 /* CaseBlock */; + return node.kind === 232 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isModuleBody(node) { var kind = node.kind; - return kind === 226 /* ModuleBlock */ - || kind === 225 /* ModuleDeclaration */; + return kind === 231 /* ModuleBlock */ + || kind === 230 /* ModuleDeclaration */; } ts.isModuleBody = isModuleBody; function isImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */; + return node.kind === 234 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportClause(node) { - return node.kind === 231 /* ImportClause */; + return node.kind === 236 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 233 /* NamedImports */ - || kind === 232 /* NamespaceImport */; + return kind === 238 /* NamedImports */ + || kind === 237 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; function isImportSpecifier(node) { - return node.kind === 234 /* ImportSpecifier */; + return node.kind === 239 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isNamedExports(node) { - return node.kind === 237 /* NamedExports */; + return node.kind === 242 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 238 /* ExportSpecifier */; + return node.kind === 243 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isModuleOrEnumDeclaration(node) { - return node.kind === 225 /* ModuleDeclaration */ || node.kind === 224 /* EnumDeclaration */; + return node.kind === 230 /* ModuleDeclaration */ || node.kind === 229 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 180 /* ArrowFunction */ - || kind === 169 /* BindingElement */ - || kind === 221 /* ClassDeclaration */ - || kind === 192 /* ClassExpression */ - || kind === 148 /* Constructor */ - || kind === 224 /* EnumDeclaration */ - || kind === 255 /* EnumMember */ - || kind === 238 /* ExportSpecifier */ - || kind === 220 /* FunctionDeclaration */ - || kind === 179 /* FunctionExpression */ - || kind === 149 /* GetAccessor */ - || kind === 231 /* ImportClause */ - || kind === 229 /* ImportEqualsDeclaration */ - || kind === 234 /* ImportSpecifier */ - || kind === 222 /* InterfaceDeclaration */ - || kind === 147 /* MethodDeclaration */ - || kind === 146 /* MethodSignature */ - || kind === 225 /* ModuleDeclaration */ - || kind === 228 /* NamespaceExportDeclaration */ - || kind === 232 /* NamespaceImport */ - || kind === 142 /* Parameter */ - || kind === 253 /* PropertyAssignment */ - || kind === 145 /* PropertyDeclaration */ - || kind === 144 /* PropertySignature */ - || kind === 150 /* SetAccessor */ - || kind === 254 /* ShorthandPropertyAssignment */ - || kind === 223 /* TypeAliasDeclaration */ - || kind === 141 /* TypeParameter */ - || kind === 218 /* VariableDeclaration */ - || kind === 279 /* JSDocTypedefTag */; + return kind === 185 /* ArrowFunction */ + || kind === 174 /* BindingElement */ + || kind === 226 /* ClassDeclaration */ + || kind === 197 /* ClassExpression */ + || kind === 150 /* Constructor */ + || kind === 229 /* EnumDeclaration */ + || kind === 260 /* EnumMember */ + || kind === 243 /* ExportSpecifier */ + || kind === 225 /* FunctionDeclaration */ + || kind === 184 /* FunctionExpression */ + || kind === 151 /* GetAccessor */ + || kind === 236 /* ImportClause */ + || kind === 234 /* ImportEqualsDeclaration */ + || kind === 239 /* ImportSpecifier */ + || kind === 227 /* InterfaceDeclaration */ + || kind === 149 /* MethodDeclaration */ + || kind === 148 /* MethodSignature */ + || kind === 230 /* ModuleDeclaration */ + || kind === 233 /* NamespaceExportDeclaration */ + || kind === 237 /* NamespaceImport */ + || kind === 144 /* Parameter */ + || kind === 257 /* PropertyAssignment */ + || kind === 147 /* PropertyDeclaration */ + || kind === 146 /* PropertySignature */ + || kind === 152 /* SetAccessor */ + || kind === 258 /* ShorthandPropertyAssignment */ + || kind === 228 /* TypeAliasDeclaration */ + || kind === 143 /* TypeParameter */ + || kind === 223 /* VariableDeclaration */ + || kind === 285 /* JSDocTypedefTag */; } function isDeclarationStatementKind(kind) { - return kind === 220 /* FunctionDeclaration */ - || kind === 239 /* MissingDeclaration */ - || kind === 221 /* ClassDeclaration */ - || kind === 222 /* InterfaceDeclaration */ - || kind === 223 /* TypeAliasDeclaration */ - || kind === 224 /* EnumDeclaration */ - || kind === 225 /* ModuleDeclaration */ - || kind === 230 /* ImportDeclaration */ - || kind === 229 /* ImportEqualsDeclaration */ - || kind === 236 /* ExportDeclaration */ - || kind === 235 /* ExportAssignment */ - || kind === 228 /* NamespaceExportDeclaration */; + return kind === 225 /* FunctionDeclaration */ + || kind === 244 /* MissingDeclaration */ + || kind === 226 /* ClassDeclaration */ + || kind === 227 /* InterfaceDeclaration */ + || kind === 228 /* TypeAliasDeclaration */ + || kind === 229 /* EnumDeclaration */ + || kind === 230 /* ModuleDeclaration */ + || kind === 235 /* ImportDeclaration */ + || kind === 234 /* ImportEqualsDeclaration */ + || kind === 241 /* ExportDeclaration */ + || kind === 240 /* ExportAssignment */ + || kind === 233 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 210 /* BreakStatement */ - || kind === 209 /* ContinueStatement */ - || kind === 217 /* DebuggerStatement */ - || kind === 204 /* DoStatement */ - || kind === 202 /* ExpressionStatement */ - || kind === 201 /* EmptyStatement */ - || kind === 207 /* ForInStatement */ - || kind === 208 /* ForOfStatement */ - || kind === 206 /* ForStatement */ - || kind === 203 /* IfStatement */ - || kind === 214 /* LabeledStatement */ - || kind === 211 /* ReturnStatement */ - || kind === 213 /* SwitchStatement */ - || kind === 215 /* ThrowStatement */ - || kind === 216 /* TryStatement */ - || kind === 200 /* VariableStatement */ - || kind === 205 /* WhileStatement */ - || kind === 212 /* WithStatement */ - || kind === 287 /* NotEmittedStatement */; + return kind === 215 /* BreakStatement */ + || kind === 214 /* ContinueStatement */ + || kind === 222 /* DebuggerStatement */ + || kind === 209 /* DoStatement */ + || kind === 207 /* ExpressionStatement */ + || kind === 206 /* EmptyStatement */ + || kind === 212 /* ForInStatement */ + || kind === 213 /* ForOfStatement */ + || kind === 211 /* ForStatement */ + || kind === 208 /* IfStatement */ + || kind === 219 /* LabeledStatement */ + || kind === 216 /* ReturnStatement */ + || kind === 218 /* SwitchStatement */ + || kind === 220 /* ThrowStatement */ + || kind === 221 /* TryStatement */ + || kind === 205 /* VariableStatement */ + || kind === 210 /* WhileStatement */ + || kind === 217 /* WithStatement */ + || kind === 293 /* NotEmittedStatement */ + || kind === 296 /* EndOfDeclarationMarker */ + || kind === 295 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -9593,93 +10197,93 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 199 /* Block */; + || kind === 204 /* Block */; } ts.isStatement = isStatement; // Module references function isModuleReference(node) { var kind = node.kind; - return kind === 240 /* ExternalModuleReference */ - || kind === 139 /* QualifiedName */ - || kind === 69 /* Identifier */; + return kind === 245 /* ExternalModuleReference */ + || kind === 141 /* QualifiedName */ + || kind === 70 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX function isJsxOpeningElement(node) { - return node.kind === 243 /* JsxOpeningElement */; + return node.kind === 248 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 245 /* JsxClosingElement */; + return node.kind === 249 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 97 /* ThisKeyword */ - || kind === 69 /* Identifier */ - || kind === 172 /* PropertyAccessExpression */; + return kind === 98 /* ThisKeyword */ + || kind === 70 /* Identifier */ + || kind === 177 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 241 /* JsxElement */ - || kind === 248 /* JsxExpression */ - || kind === 242 /* JsxSelfClosingElement */ - || kind === 244 /* JsxText */; + return kind === 246 /* JsxElement */ + || kind === 252 /* JsxExpression */ + || kind === 247 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 246 /* JsxAttribute */ - || kind === 247 /* JsxSpreadAttribute */; + return kind === 250 /* JsxAttribute */ + || kind === 251 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; function isJsxSpreadAttribute(node) { - return node.kind === 247 /* JsxSpreadAttribute */; + return node.kind === 251 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxAttribute(node) { - return node.kind === 246 /* JsxAttribute */; + return node.kind === 250 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 248 /* JsxExpression */; + || kind === 252 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 249 /* CaseClause */ - || kind === 250 /* DefaultClause */; + return kind === 253 /* CaseClause */ + || kind === 254 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isHeritageClause(node) { - return node.kind === 251 /* HeritageClause */; + return node.kind === 255 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 252 /* CatchClause */; + return node.kind === 256 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 253 /* PropertyAssignment */; + return node.kind === 257 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 254 /* ShorthandPropertyAssignment */; + return node.kind === 258 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; // Enum function isEnumMember(node) { - return node.kind === 255 /* EnumMember */; + return node.kind === 260 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 256 /* SourceFile */; + return node.kind === 261 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isWatchSet(options) { @@ -9688,10 +10292,19 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { - return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case 5 /* ESNext */: + case 4 /* ES2017 */: + return "lib.es2017.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } } ts.getDefaultLibFileName = getDefaultLibFileName; function textSpanEnd(span) { @@ -9900,9 +10513,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 141 /* TypeParameter */) { + if (d && d.kind === 143 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 222 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227 /* InterfaceDeclaration */) { return current; } } @@ -9910,11 +10523,11 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 150 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 /* BindingElement */ || ts.isBindingPattern(node))) { + while (node && (node.kind === 174 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -9922,14 +10535,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 219 /* VariableDeclarationList */) { + if (node && node.kind === 224 /* VariableDeclarationList */) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 200 /* VariableStatement */) { + if (node && node.kind === 205 /* VariableStatement */) { flags |= ts.getModifierFlags(node); } return flags; @@ -9945,19 +10558,73 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 219 /* VariableDeclarationList */) { + if (node && node.kind === 224 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 200 /* VariableStatement */) { + if (node && node.kind === 205 /* VariableStatement */) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; })(ts || (ts = {})); /// /// @@ -9967,7 +10634,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, location, flags) { - var ConstructorForKind = kind === 256 /* SourceFile */ + var ConstructorForKind = kind === 261 /* SourceFile */ ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); var node = location @@ -10029,7 +10696,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10057,14 +10724,14 @@ var ts; return node; } else if (typeof value === "boolean") { - return createNode(value ? 99 /* TrueKeyword */ : 84 /* FalseKeyword */, location, /*flags*/ undefined); + return createNode(value ? 100 /* TrueKeyword */ : 85 /* FalseKeyword */, location, /*flags*/ undefined); } else if (typeof value === "string") { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10075,7 +10742,7 @@ var ts; // Identifiers var nextAutoGenerateId = 0; function createIdentifier(text, location) { - var node = createNode(69 /* Identifier */, location); + var node = createNode(70 /* Identifier */, location); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = ts.stringToToken(text); node.autoGenerateKind = 0 /* None */; @@ -10084,7 +10751,7 @@ var ts; } ts.createIdentifier = createIdentifier; function createTempVariable(recordTempVariable, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = ""; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 1 /* Auto */; @@ -10097,7 +10764,7 @@ var ts; } ts.createTempVariable = createTempVariable; function createLoopVariable(location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = ""; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 2 /* Loop */; @@ -10107,7 +10774,7 @@ var ts; } ts.createLoopVariable = createLoopVariable; function createUniqueName(text, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = text; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 3 /* Unique */; @@ -10117,7 +10784,7 @@ var ts; } ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.original = node; name.text = ""; name.originalKeywordKind = 0 /* Unknown */; @@ -10134,23 +10801,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - var node = createNode(95 /* SuperKeyword */); + var node = createNode(96 /* SuperKeyword */); return node; } ts.createSuper = createSuper; function createThis(location) { - var node = createNode(97 /* ThisKeyword */, location); + var node = createNode(98 /* ThisKeyword */, location); return node; } ts.createThis = createThis; function createNull() { - var node = createNode(93 /* NullKeyword */); + var node = createNode(94 /* NullKeyword */); return node; } ts.createNull = createNull; // Names function createComputedPropertyName(expression, location) { - var node = createNode(140 /* ComputedPropertyName */, location); + var node = createNode(142 /* ComputedPropertyName */, location); node.expression = expression; return node; } @@ -10163,17 +10830,8 @@ var ts; } ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements - function createParameter(name, initializer, location) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, name, - /*questionToken*/ undefined, - /*type*/ undefined, initializer, location); - } - ts.createParameter = createParameter; - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { - var node = createNode(142 /* Parameter */, location, flags); + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(144 /* Parameter */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.dotDotDotToken = dotDotDotToken; @@ -10183,17 +10841,17 @@ var ts; node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; return node; } - ts.createParameterDeclaration = createParameterDeclaration; - function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); } return node; } - ts.updateParameterDeclaration = updateParameterDeclaration; + ts.updateParameter = updateParameter; // Type members function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { - var node = createNode(145 /* PropertyDeclaration */, location); + var node = createNode(147 /* PropertyDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10211,7 +10869,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(147 /* MethodDeclaration */, location, flags); + var node = createNode(149 /* MethodDeclaration */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -10231,7 +10889,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body, location, flags) { - var node = createNode(148 /* Constructor */, location, flags); + var node = createNode(150 /* Constructor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = undefined; @@ -10249,7 +10907,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { - var node = createNode(149 /* GetAccessor */, location, flags); + var node = createNode(151 /* GetAccessor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10268,7 +10926,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { - var node = createNode(150 /* SetAccessor */, location, flags); + var node = createNode(152 /* SetAccessor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10287,7 +10945,7 @@ var ts; ts.updateSetAccessor = updateSetAccessor; // Binding Patterns function createObjectBindingPattern(elements, location) { - var node = createNode(167 /* ObjectBindingPattern */, location); + var node = createNode(172 /* ObjectBindingPattern */, location); node.elements = createNodeArray(elements); return node; } @@ -10300,7 +10958,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements, location) { - var node = createNode(168 /* ArrayBindingPattern */, location); + var node = createNode(173 /* ArrayBindingPattern */, location); node.elements = createNodeArray(elements); return node; } @@ -10313,7 +10971,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { - var node = createNode(169 /* BindingElement */, location); + var node = createNode(174 /* BindingElement */, location); node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; node.dotDotDotToken = dotDotDotToken; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10321,16 +10979,16 @@ var ts; return node; } ts.createBindingElement = createBindingElement; - function updateBindingElement(node, propertyName, name, initializer) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, location, multiLine) { - var node = createNode(170 /* ArrayLiteralExpression */, location); + var node = createNode(175 /* ArrayLiteralExpression */, location); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) { node.multiLine = true; @@ -10346,7 +11004,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, location, multiLine) { - var node = createNode(171 /* ObjectLiteralExpression */, location); + var node = createNode(176 /* ObjectLiteralExpression */, location); node.properties = createNodeArray(properties); if (multiLine) { node.multiLine = true; @@ -10362,9 +11020,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name, location, flags) { - var node = createNode(172 /* PropertyAccessExpression */, location, flags); + var node = createNode(177 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 65536 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,14 +11031,14 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index, location) { - var node = createNode(173 /* ElementAccessExpression */, location); + var node = createNode(178 /* ElementAccessExpression */, location); node.expression = parenthesizeForAccess(expression); node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; return node; @@ -10394,7 +11052,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(174 /* CallExpression */, location, flags); + var node = createNode(179 /* CallExpression */, location, flags); node.expression = parenthesizeForAccess(expression); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -10411,7 +11069,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(175 /* NewExpression */, location, flags); + var node = createNode(180 /* NewExpression */, location, flags); node.expression = parenthesizeForNew(expression); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -10426,7 +11084,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template, location) { - var node = createNode(176 /* TaggedTemplateExpression */, location); + var node = createNode(181 /* TaggedTemplateExpression */, location); node.tag = parenthesizeForAccess(tag); node.template = template; return node; @@ -10440,7 +11098,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createParen(expression, location) { - var node = createNode(178 /* ParenthesizedExpression */, location); + var node = createNode(183 /* ParenthesizedExpression */, location); node.expression = expression; return node; } @@ -10452,9 +11110,9 @@ var ts; return node; } ts.updateParen = updateParen; - function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(179 /* FunctionExpression */, location, flags); - node.modifiers = undefined; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(184 /* FunctionExpression */, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -10464,20 +11122,20 @@ var ts; return node; } ts.createFunctionExpression = createFunctionExpression; - function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); } return node; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { - var node = createNode(180 /* ArrowFunction */, location, flags); + var node = createNode(185 /* ArrowFunction */, location, flags); node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10490,7 +11148,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression, location) { - var node = createNode(181 /* DeleteExpression */, location); + var node = createNode(186 /* DeleteExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10503,7 +11161,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression, location) { - var node = createNode(182 /* TypeOfExpression */, location); + var node = createNode(187 /* TypeOfExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10516,7 +11174,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression, location) { - var node = createNode(183 /* VoidExpression */, location); + var node = createNode(188 /* VoidExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10529,7 +11187,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression, location) { - var node = createNode(184 /* AwaitExpression */, location); + var node = createNode(189 /* AwaitExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10542,7 +11200,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand, location) { - var node = createNode(185 /* PrefixUnaryExpression */, location); + var node = createNode(190 /* PrefixUnaryExpression */, location); node.operator = operator; node.operand = parenthesizePrefixOperand(operand); return node; @@ -10556,7 +11214,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator, location) { - var node = createNode(186 /* PostfixUnaryExpression */, location); + var node = createNode(191 /* PostfixUnaryExpression */, location); node.operand = parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -10570,9 +11228,9 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; - var node = createNode(187 /* BinaryExpression */, location); + var node = createNode(192 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); node.operatorToken = operatorToken; node.right = parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); @@ -10586,13 +11244,23 @@ var ts; return node; } ts.updateBinary = updateBinary; - function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { - var node = createNode(188 /* ConditionalExpression */, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) { + var node = createNode(193 /* ConditionalExpression */, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + // second overload + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + // first overload + node.questionToken = createToken(54 /* QuestionToken */); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(55 /* ColonToken */); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } ts.createConditional = createConditional; @@ -10604,7 +11272,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans, location) { - var node = createNode(189 /* TemplateExpression */, location); + var node = createNode(194 /* TemplateExpression */, location); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -10618,7 +11286,7 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createYield(asteriskToken, expression, location) { - var node = createNode(190 /* YieldExpression */, location); + var node = createNode(195 /* YieldExpression */, location); node.asteriskToken = asteriskToken; node.expression = expression; return node; @@ -10632,7 +11300,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression, location) { - var node = createNode(191 /* SpreadElementExpression */, location); + var node = createNode(196 /* SpreadElement */, location); node.expression = parenthesizeExpressionForList(expression); return node; } @@ -10645,7 +11313,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(192 /* ClassExpression */, location); + var node = createNode(197 /* ClassExpression */, location); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -10663,12 +11331,12 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression(location) { - var node = createNode(193 /* OmittedExpression */, location); + var node = createNode(198 /* OmittedExpression */, location); return node; } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression, location) { - var node = createNode(194 /* ExpressionWithTypeArguments */, location); + var node = createNode(199 /* ExpressionWithTypeArguments */, location); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.expression = parenthesizeForAccess(expression); return node; @@ -10683,7 +11351,7 @@ var ts; ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; // Misc function createTemplateSpan(expression, literal, location) { - var node = createNode(197 /* TemplateSpan */, location); + var node = createNode(202 /* TemplateSpan */, location); node.expression = expression; node.literal = literal; return node; @@ -10698,7 +11366,7 @@ var ts; ts.updateTemplateSpan = updateTemplateSpan; // Element function createBlock(statements, location, multiLine, flags) { - var block = createNode(199 /* Block */, location, flags); + var block = createNode(204 /* Block */, location, flags); block.statements = createNodeArray(statements); if (multiLine) { block.multiLine = true; @@ -10714,7 +11382,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList, location, flags) { - var node = createNode(200 /* VariableStatement */, location, flags); + var node = createNode(205 /* VariableStatement */, location, flags); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -10729,7 +11397,7 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createVariableDeclarationList(declarations, location, flags) { - var node = createNode(219 /* VariableDeclarationList */, location, flags); + var node = createNode(224 /* VariableDeclarationList */, location, flags); node.declarations = createNodeArray(declarations); return node; } @@ -10742,7 +11410,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createVariableDeclaration(name, type, initializer, location, flags) { - var node = createNode(218 /* VariableDeclaration */, location, flags); + var node = createNode(223 /* VariableDeclaration */, location, flags); node.name = typeof name === "string" ? createIdentifier(name) : name; node.type = type; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -10757,11 +11425,11 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement(location) { - return createNode(201 /* EmptyStatement */, location); + return createNode(206 /* EmptyStatement */, location); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression, location, flags) { - var node = createNode(202 /* ExpressionStatement */, location, flags); + var node = createNode(207 /* ExpressionStatement */, location, flags); node.expression = parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -10774,7 +11442,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement, location) { - var node = createNode(203 /* IfStatement */, location); + var node = createNode(208 /* IfStatement */, location); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -10789,7 +11457,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression, location) { - var node = createNode(204 /* DoStatement */, location); + var node = createNode(209 /* DoStatement */, location); node.statement = statement; node.expression = expression; return node; @@ -10803,7 +11471,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement, location) { - var node = createNode(205 /* WhileStatement */, location); + var node = createNode(210 /* WhileStatement */, location); node.expression = expression; node.statement = statement; return node; @@ -10817,7 +11485,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement, location) { - var node = createNode(206 /* ForStatement */, location, /*flags*/ undefined); + var node = createNode(211 /* ForStatement */, location, /*flags*/ undefined); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -10833,7 +11501,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement, location) { - var node = createNode(207 /* ForInStatement */, location); + var node = createNode(212 /* ForInStatement */, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -10848,7 +11516,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(initializer, expression, statement, location) { - var node = createNode(208 /* ForOfStatement */, location); + var node = createNode(213 /* ForOfStatement */, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -10863,7 +11531,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label, location) { - var node = createNode(209 /* ContinueStatement */, location); + var node = createNode(214 /* ContinueStatement */, location); if (label) { node.label = label; } @@ -10878,7 +11546,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label, location) { - var node = createNode(210 /* BreakStatement */, location); + var node = createNode(215 /* BreakStatement */, location); if (label) { node.label = label; } @@ -10893,7 +11561,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression, location) { - var node = createNode(211 /* ReturnStatement */, location); + var node = createNode(216 /* ReturnStatement */, location); node.expression = expression; return node; } @@ -10906,7 +11574,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement, location) { - var node = createNode(212 /* WithStatement */, location); + var node = createNode(217 /* WithStatement */, location); node.expression = expression; node.statement = statement; return node; @@ -10920,7 +11588,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock, location) { - var node = createNode(213 /* SwitchStatement */, location); + var node = createNode(218 /* SwitchStatement */, location); node.expression = parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -10934,7 +11602,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement, location) { - var node = createNode(214 /* LabeledStatement */, location); + var node = createNode(219 /* LabeledStatement */, location); node.label = typeof label === "string" ? createIdentifier(label) : label; node.statement = statement; return node; @@ -10948,7 +11616,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression, location) { - var node = createNode(215 /* ThrowStatement */, location); + var node = createNode(220 /* ThrowStatement */, location); node.expression = expression; return node; } @@ -10961,7 +11629,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock, location) { - var node = createNode(216 /* TryStatement */, location); + var node = createNode(221 /* TryStatement */, location); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -10976,7 +11644,7 @@ var ts; } ts.updateTry = updateTry; function createCaseBlock(clauses, location) { - var node = createNode(227 /* CaseBlock */, location); + var node = createNode(232 /* CaseBlock */, location); node.clauses = createNodeArray(clauses); return node; } @@ -10989,7 +11657,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(220 /* FunctionDeclaration */, location, flags); + var node = createNode(225 /* FunctionDeclaration */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -11009,7 +11677,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(221 /* ClassDeclaration */, location); + var node = createNode(226 /* ClassDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -11027,7 +11695,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { - var node = createNode(230 /* ImportDeclaration */, location); + var node = createNode(235 /* ImportDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.importClause = importClause; @@ -11043,7 +11711,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings, location) { - var node = createNode(231 /* ImportClause */, location); + var node = createNode(236 /* ImportClause */, location); node.name = name; node.namedBindings = namedBindings; return node; @@ -11057,7 +11725,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name, location) { - var node = createNode(232 /* NamespaceImport */, location); + var node = createNode(237 /* NamespaceImport */, location); node.name = name; return node; } @@ -11070,7 +11738,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements, location) { - var node = createNode(233 /* NamedImports */, location); + var node = createNode(238 /* NamedImports */, location); node.elements = createNodeArray(elements); return node; } @@ -11083,7 +11751,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name, location) { - var node = createNode(234 /* ImportSpecifier */, location); + var node = createNode(239 /* ImportSpecifier */, location); node.propertyName = propertyName; node.name = name; return node; @@ -11097,7 +11765,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { - var node = createNode(235 /* ExportAssignment */, location); + var node = createNode(240 /* ExportAssignment */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.isExportEquals = isExportEquals; @@ -11113,7 +11781,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { - var node = createNode(236 /* ExportDeclaration */, location); + var node = createNode(241 /* ExportDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.exportClause = exportClause; @@ -11129,7 +11797,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements, location) { - var node = createNode(237 /* NamedExports */, location); + var node = createNode(242 /* NamedExports */, location); node.elements = createNodeArray(elements); return node; } @@ -11142,7 +11810,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(name, propertyName, location) { - var node = createNode(238 /* ExportSpecifier */, location); + var node = createNode(243 /* ExportSpecifier */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; return node; @@ -11157,7 +11825,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // JSX function createJsxElement(openingElement, children, closingElement, location) { - var node = createNode(241 /* JsxElement */, location); + var node = createNode(246 /* JsxElement */, location); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -11172,7 +11840,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes, location) { - var node = createNode(242 /* JsxSelfClosingElement */, location); + var node = createNode(247 /* JsxSelfClosingElement */, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -11186,7 +11854,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes, location) { - var node = createNode(243 /* JsxOpeningElement */, location); + var node = createNode(248 /* JsxOpeningElement */, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -11200,7 +11868,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName, location) { - var node = createNode(245 /* JsxClosingElement */, location); + var node = createNode(249 /* JsxClosingElement */, location); node.tagName = tagName; return node; } @@ -11213,7 +11881,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxAttribute(name, initializer, location) { - var node = createNode(246 /* JsxAttribute */, location); + var node = createNode(250 /* JsxAttribute */, location); node.name = name; node.initializer = initializer; return node; @@ -11227,7 +11895,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxSpreadAttribute(expression, location) { - var node = createNode(247 /* JsxSpreadAttribute */, location); + var node = createNode(251 /* JsxSpreadAttribute */, location); node.expression = expression; return node; } @@ -11240,7 +11908,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(expression, location) { - var node = createNode(248 /* JsxExpression */, location); + var node = createNode(252 /* JsxExpression */, location); node.expression = expression; return node; } @@ -11254,7 +11922,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createHeritageClause(token, types, location) { - var node = createNode(251 /* HeritageClause */, location); + var node = createNode(255 /* HeritageClause */, location); node.token = token; node.types = createNodeArray(types); return node; @@ -11268,7 +11936,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements, location) { - var node = createNode(249 /* CaseClause */, location); + var node = createNode(253 /* CaseClause */, location); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -11282,7 +11950,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements, location) { - var node = createNode(250 /* DefaultClause */, location); + var node = createNode(254 /* DefaultClause */, location); node.statements = createNodeArray(statements); return node; } @@ -11295,7 +11963,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createCatchClause(variableDeclaration, block, location) { - var node = createNode(252 /* CatchClause */, location); + var node = createNode(256 /* CatchClause */, location); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -11310,7 +11978,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer, location) { - var node = createNode(253 /* PropertyAssignment */, location); + var node = createNode(257 /* PropertyAssignment */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.questionToken = undefined; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -11325,12 +11993,18 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { - var node = createNode(254 /* ShorthandPropertyAssignment */, location); + var node = createNode(258 /* ShorthandPropertyAssignment */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function createSpreadAssignment(expression, location) { + var node = createNode(259 /* SpreadAssignment */, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -11338,10 +12012,17 @@ var ts; return node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSpreadAssignment(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; // Top-level nodes function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createNode(256 /* SourceFile */, /*location*/ node, node.flags); + var updated = createNode(261 /* SourceFile */, /*location*/ node, node.flags); updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; @@ -11395,8 +12076,6 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) - updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } return node; @@ -11410,11 +12089,33 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createNode(287 /* NotEmittedStatement */, /*location*/ original); + var node = createNode(293 /* NotEmittedStatement */, /*location*/ original); node.original = original; return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + function createEndOfDeclarationMarker(original) { + var node = createNode(296 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + function createMergeDeclarationMarker(original) { + var node = createNode(295 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; /** * Creates a synthetic expression to act as a placeholder for a not-emitted expression in * order to preserve comments or sourcemap positions. @@ -11424,7 +12125,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original, location) { - var node = createNode(288 /* PartiallyEmittedExpression */, /*location*/ location || original); + var node = createNode(294 /* PartiallyEmittedExpression */, /*location*/ location || original); node.expression = expression; node.original = original; return node; @@ -11437,75 +12138,85 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + /** + * Creates a node that emits a string of raw text in an expression position. Raw text is never + * transformed, should be ES3 compliant, and should have the same precedence as + * PrimaryExpression. + * + * @param text The raw text of the node. + */ + function createRawExpression(text) { + var node = createNode(297 /* RawExpression */); + node.text = text; + return node; + } + ts.createRawExpression = createRawExpression; // Compound nodes function createComma(left, right) { - return createBinary(left, 24 /* CommaToken */, right); + return createBinary(left, 25 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right, location) { - return createBinary(left, 25 /* LessThanToken */, right, location); + return createBinary(left, 26 /* LessThanToken */, right, location); } ts.createLessThan = createLessThan; function createAssignment(left, right, location) { - return createBinary(left, 56 /* EqualsToken */, right, location); + return createBinary(left, 57 /* EqualsToken */, right, location); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 32 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 33 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 33 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 34 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 35 /* PlusToken */, right); + return createBinary(left, 36 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 36 /* MinusToken */, right); + return createBinary(left, 37 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand, location) { - return createPostfix(operand, 41 /* PlusPlusToken */, location); + return createPostfix(operand, 42 /* PlusPlusToken */, location); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 51 /* AmpersandAmpersandToken */, right); + return createBinary(left, 52 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 52 /* BarBarToken */, right); + return createBinary(left, 53 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(49 /* ExclamationToken */, operand); + return createPrefix(50 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { return createVoid(createLiteral(0)); } ts.createVoidZero = createVoidZero; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; function createMemberAccessForPropertyName(target, memberName, location) { if (ts.isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 64 /* NoNestedSourceMaps */; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; - function createRestParameter(name) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, - /*questionToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); - } - ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { return createCall(createPropertyAccess(func, "call"), /*typeArguments*/ undefined, [ @@ -11545,10 +12256,28 @@ var ts; // flag and setting a parent node. var react = createIdentifier(reactNamespace || "React"); react.flags &= ~8 /* Synthesized */; - react.parent = parent; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); return react; } - function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = createSynthesizedNode(70 /* Identifier */); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { var argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -11568,10 +12297,22 @@ var ts; argumentsList.push(children[0]); } } - return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), + return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), /*typeArguments*/ undefined, argumentsList, location); } - ts.createReactCreateElement = createReactCreateElement; + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function createLetStatement(name, initializer, location) { + return createVariableStatement(/*modifiers*/ undefined, createLetDeclarationList([createVariableDeclaration(name, /*type*/ undefined, initializer)]), location); + } + ts.createLetStatement = createLetStatement; function createLetDeclarationList(declarations, location) { return createVariableDeclarationList(declarations, location, 1 /* Let */); } @@ -11581,187 +12322,26 @@ var ts; } ts.createConstDeclarationList = createConstDeclarationList; // Helpers - function createHelperName(externalHelpersModuleName, name) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + function getHelperName(name) { + return setEmitFlags(createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); } - ts.createHelperName = createHelperName; - function createExtendsHelper(externalHelpersModuleName, name) { - return createCall(createHelperName(externalHelpersModuleName, "__extends"), - /*typeArguments*/ undefined, [ - name, - createIdentifier("_super") - ]); - } - ts.createExtendsHelper = createExtendsHelper; - function createAssignHelper(externalHelpersModuleName, attributesSegments) { - return createCall(createHelperName(externalHelpersModuleName, "__assign"), - /*typeArguments*/ undefined, attributesSegments); - } - ts.createAssignHelper = createAssignHelper; - function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { - return createCall(createHelperName(externalHelpersModuleName, "__param"), - /*typeArguments*/ undefined, [ - createLiteral(parameterOffset), - expression - ], location); - } - ts.createParamHelper = createParamHelper; - function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { - return createCall(createHelperName(externalHelpersModuleName, "__metadata"), - /*typeArguments*/ undefined, [ - createLiteral(metadataKey), - metadataValue - ]); - } - ts.createMetadataHelper = createMetadataHelper; - function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { - var argumentsArray = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), /*typeArguments*/ undefined, argumentsArray, location); - } - ts.createDecorateHelper = createDecorateHelper; - function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, body); - // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; - return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), - /*typeArguments*/ undefined, [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ]); - } - ts.createAwaiterHelper = createAwaiterHelper; - function createHasOwnProperty(target, propertyName) { - return createCall(createPropertyAccess(target, "hasOwnProperty"), - /*typeArguments*/ undefined, [propertyName]); - } - ts.createHasOwnProperty = createHasOwnProperty; - function createObjectCreate(prototype) { - return createCall(createPropertyAccess(createIdentifier("Object"), "create"), - /*typeArguments*/ undefined, [prototype]); - } - function createGeti(target) { - // name => super[name] - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createElementAccess(target, createIdentifier("name"))); - } - function createSeti(target) { - // (name, value) => super[name] = value - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [ - createParameter("name"), - createParameter("value") - ], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); - } - function createAdvancedAsyncSuperHelper() { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - // const cache = Object.create(null); - var createCache = createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("cache", - /*type*/ undefined, createObjectCreate(createNull())) - ])); - // get value() { return geti(name); } - var getter = createGetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, "value", - /*parameters*/ [], - /*type*/ undefined, createBlock([ - createReturn(createCall(createIdentifier("geti"), - /*typeArguments*/ undefined, [createIdentifier("name")])) - ])); - // set value(v) { seti(name, v); } - var setter = createSetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, "value", [createParameter("v")], createBlock([ - createStatement(createCall(createIdentifier("seti"), - /*typeArguments*/ undefined, [ - createIdentifier("name"), - createIdentifier("v") - ])) - ])); - // return name => cache[name] || ... - var getOrCreateAccessorsForName = createReturn(createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ - getter, - setter - ])))))); - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - return createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("_super", - /*type*/ undefined, createCall(createParen(createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - createParameter("geti"), - createParameter("seti") - ], - /*type*/ undefined, createBlock([ - createCache, - getOrCreateAccessorsForName - ]))), - /*typeArguments*/ undefined, [ - createGeti(createSuper()), - createSeti(createSuper()) - ])) - ])); - } - ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; - function createSimpleAsyncSuperHelper() { - return createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("_super", - /*type*/ undefined, createGeti(createSuper())) - ])); - } - ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + ts.getHelperName = getHelperName; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return cacheIdentifiers; - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -11775,13 +12355,13 @@ var ts; thisArg = createThis(); target = callee; } - else if (callee.kind === 95 /* SuperKeyword */) { + else if (callee.kind === 96 /* SuperKeyword */) { thisArg = createThis(); - target = languageVersion < 2 /* ES6 */ ? createIdentifier("_super", /*location*/ callee) : callee; + target = languageVersion < 2 /* ES2015 */ ? createIdentifier("_super", /*location*/ callee) : callee; } else { switch (callee.kind) { - case 172 /* PropertyAccessExpression */: { + case 177 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); @@ -11795,7 +12375,7 @@ var ts; } break; } - case 173 /* ElementAccessExpression */: { + case 178 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); @@ -11849,14 +12429,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -11866,7 +12446,7 @@ var ts; if (property === firstAccessor) { var properties_1 = []; if (getAccessor) { - var getterFunction = createFunctionExpression( + var getterFunction = createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, @@ -11877,7 +12457,7 @@ var ts; properties_1.push(getter); } if (setAccessor) { - var setterFunction = createFunctionExpression( + var setterFunction = createFunctionExpression(setAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -11911,7 +12491,7 @@ var ts; /*original*/ property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body, @@ -11920,7 +12500,116 @@ var ts; /*location*/ method), /*original*/ method)); } - // Utilities + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { + var name_8 = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + setEmitFlags(name_8, emitFlags); + return name_8; + } + return getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), /*location*/ name); + var emitFlags; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node, multiLine); + } + ts.convertToFunctionBody = convertToFunctionBody; function isUseStrictPrologue(node) { return node.expression.text === "use strict"; } @@ -11936,7 +12625,7 @@ var ts; * @param visitor: Optional callback used to visit any custom prologue directives. */ function addPrologueDirectives(target, source, ensureUseStrict, visitor) { - ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; var statementOffset = 0; var numStatements = source.length; @@ -11949,22 +12638,60 @@ var ts; target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (getEmitFlags(statement) & 524288 /* CustomPrologue */) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = false; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))) + ].concat(statements), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -11977,7 +12704,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 178 /* ParenthesizedExpression */) { + if (skipped.kind === 183 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -12011,8 +12738,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(187 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(192 /* BinaryExpression */, binaryOperator); var emittedOperand = skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -12021,7 +12748,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 190 /* YieldExpression */) { + && operand.kind === 195 /* YieldExpression */) { return false; } return true; @@ -12058,7 +12785,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 35 /* PlusToken */) { + if (binaryOperator === 36 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -12093,10 +12820,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 37 /* AsteriskToken */ - || binaryOperator === 47 /* BarToken */ - || binaryOperator === 46 /* AmpersandToken */ - || binaryOperator === 48 /* CaretToken */; + return binaryOperator === 38 /* AsteriskToken */ + || binaryOperator === 48 /* BarToken */ + || binaryOperator === 47 /* AmpersandToken */ + || binaryOperator === 49 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -12109,7 +12836,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 35 /* PlusToken */) { + if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 36 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -12123,6 +12850,24 @@ var ts; } return 0 /* Unknown */; } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(193 /* ConditionalExpression */, 54 /* QuestionToken */); + var emittedCondition = skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + return e.kind === 192 /* BinaryExpression */ && e.operatorToken.kind === 25 /* CommaToken */ + ? createParen(e) + : e; + } /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a NewExpression node. @@ -12132,9 +12877,9 @@ var ts; function parenthesizeForNew(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return createParen(expression); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return emittedExpression.arguments ? expression : createParen(expression); @@ -12159,7 +12904,7 @@ var ts; // var emittedExpression = skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 175 /* NewExpression */ || emittedExpression.arguments) + && (emittedExpression.kind !== 180 /* NewExpression */ || emittedExpression.arguments) && emittedExpression.kind !== 8 /* NumericLiteral */) { return expression; } @@ -12197,7 +12942,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, 24 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, 25 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : createParen(expression, /*location*/ expression); @@ -12208,7 +12953,7 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 179 /* FunctionExpression */ || kind === 180 /* ArrowFunction */) { + if (kind === 184 /* FunctionExpression */ || kind === 185 /* ArrowFunction */) { var mutableCall = getMutableClone(emittedExpression); mutableCall.expression = createParen(callee, /*location*/ callee); return recreatePartiallyEmittedExpressions(expression, mutableCall); @@ -12216,7 +12961,7 @@ var ts; } else { var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 171 /* ObjectLiteralExpression */ || leftmostExpressionKind === 179 /* FunctionExpression */) { + if (leftmostExpressionKind === 176 /* ObjectLiteralExpression */ || leftmostExpressionKind === 184 /* FunctionExpression */) { return createParen(expression, /*location*/ expression); } } @@ -12240,21 +12985,21 @@ var ts; function getLeftmostExpression(node) { while (true) { switch (node.kind) { - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: node = node.operand; continue; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: node = node.left; continue; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: node = node.condition; continue; - case 174 /* CallExpression */: - case 173 /* ElementAccessExpression */: - case 172 /* PropertyAccessExpression */: + case 179 /* CallExpression */: + case 178 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: node = node.expression; continue; - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -12263,19 +13008,19 @@ var ts; } function parenthesizeConciseBody(body) { var emittedBody = skipPartiallyEmittedExpressions(body); - if (emittedBody.kind === 171 /* ObjectLiteralExpression */) { + if (emittedBody.kind === 176 /* ObjectLiteralExpression */) { return createParen(body, /*location*/ body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; - })(ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); - var OuterExpressionKinds = ts.OuterExpressionKinds; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } var previousNode; @@ -12295,7 +13040,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */) { + while (node.kind === 183 /* ParenthesizedExpression */) { node = node.expression; } return node; @@ -12309,7 +13054,7 @@ var ts; } ts.skipAssertions = skipAssertions; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288 /* PartiallyEmittedExpression */) { + while (node.kind === 294 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12323,17 +13068,297 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + if (!destEmitNode) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 261 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { + if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var helpers = getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + if (!helper.scoped) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!ts.contains(emitNode.helpers, helper)) { + emitNode.helpers = ts.append(emitNode.helpers, helper); + } + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!ts.contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12366,23 +13391,23 @@ var ts; var name_9 = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } - if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 235 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 241 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -12426,6 +13451,391 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) + ? bindingElement.initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadExpression(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 257 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 258 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 259 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadExpression(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 144 /* Parameter */: + case 174 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 196 /* SpreadElement */: + case 259 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 174 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 257 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 259 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 176 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 172 /* ObjectBindingPattern */: + case 176 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportedBindings = ts.createMap(); + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 235 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + break; + case 234 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 245 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 241 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports[specifier.name.text]) { + var name_10 = specifier.propertyName || specifier.name; + ts.multiMapAdd(exportSpecifiers, name_10.text, specifier); + var decl = resolver.getReferencedImportDeclaration(name_10) + || resolver.getReferencedValueDeclaration(name_10); + if (decl) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); + } + uniqueExports[specifier.name.text] = true; + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 240 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 205 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 225 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name_11 = node.name; + if (!uniqueExports[name_11.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_11); + uniqueExports[name_11.text] = true; + exportedNames = ts.append(exportedNames, name_11); + } + } + } + break; + case 226 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name_12 = node.name; + if (!uniqueExports[name_12.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_12); + uniqueExports[name_12.text] = true; + exportedNames = ts.append(exportedNames, name_12); + } + } + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } })(ts || (ts = {})); /// /// @@ -12437,13 +13847,13 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 256 /* SourceFile */) { + if (kind === 261 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69 /* Identifier */) { + else if (kind === 70 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } - else if (kind < 139 /* FirstNode */) { + else if (kind < 141 /* FirstNode */) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); } else { @@ -12486,26 +13896,28 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: + case 259 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -12514,24 +13926,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -12542,308 +13954,320 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 161 /* TupleType */: + case 163 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return visitNodes(cbNodes, node.types); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: + case 168 /* TypeOperator */: return visitNode(cbNode, node.type); - case 166 /* LiteralType */: + case 169 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 170 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 171 /* LiteralType */: return visitNode(cbNode, node.literal); - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 177 /* TypeAssertionExpression */: + case 182 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 195 /* AsExpression */: + case 200 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 199 /* Block */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: return visitNode(cbNode, node.label); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 249 /* CaseClause */: + case 253 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 143 /* Decorator */: + case 145 /* Decorator */: return visitNode(cbNode, node.expression); - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 233 /* NamedImports */: - case 237 /* NamedExports */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 240 /* ExternalModuleReference */: + case 245 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 257 /* JSDocTypeExpression */: + case 262 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 261 /* JSDocUnionType */: + case 266 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 262 /* JSDocTupleType */: + case 267 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 260 /* JSDocArrayType */: + case 265 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 264 /* JSDocNonNullableType */: + case 269 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 263 /* JSDocNullableType */: + case 268 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 265 /* JSDocRecordType */: + case 270 /* JSDocRecordType */: return visitNode(cbNode, node.literal); - case 267 /* JSDocTypeReference */: + case 272 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 268 /* JSDocOptionalType */: + case 273 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 269 /* JSDocFunctionType */: + case 274 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 270 /* JSDocVariadicType */: + case 275 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 271 /* JSDocConstructorType */: + case 276 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 272 /* JSDocThisType */: + case 277 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 266 /* JSDocRecordMember */: + case 271 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 273 /* JSDocComment */: + case 278 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 275 /* JSDocParameterTag */: + case 281 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 276 /* JSDocReturnTag */: + case 282 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 277 /* JSDocTypeTag */: + case 283 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 278 /* JSDocTemplateTag */: + case 280 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.typeExpression); + case 284 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.jsDocTypeLiteral); - case 281 /* JSDocTypeLiteral */: + case 287 /* JSDocTypeLiteral */: return visitNodes(cbNodes, node.jsDocPropertyTags); - case 280 /* JSDocPropertyTag */: + case 286 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); - case 282 /* JSDocLiteralType */: + case 288 /* JSDocLiteralType */: return visitNode(cbNode, node.literal); } } @@ -12857,6 +14281,10 @@ var ts; return result; } ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } @@ -12898,8 +14326,8 @@ var ts; (function (Parser) { // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 32768 /* DisallowInContext */ | 131072 /* DecoratorContext */; + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; var TokenConstructor; @@ -12989,19 +14417,29 @@ var ts; // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; function getLanguageVariant(scriptKind) { // .tsx and .jsx files are treated as jsx language variant. return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; } - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); TokenConstructor = ts.objectAllocator.getTokenConstructor(); IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); @@ -13013,7 +14451,7 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 1048576 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 65536 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -13052,7 +14490,7 @@ var ts; return sourceFile; } function addJSDocComment(node) { - var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; @@ -13060,10 +14498,10 @@ var ts; if (!jsDoc) { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } return node; @@ -13085,12 +14523,12 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -13101,7 +14539,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(256 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(261 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -13121,16 +14559,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 32768 /* DisallowInContext */); + setContextFlag(val, 2048 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 65536 /* YieldContext */); + setContextFlag(val, 4096 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 131072 /* DecoratorContext */); + setContextFlag(val, 8192 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 262144 /* AwaitContext */); + setContextFlag(val, 16384 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -13171,40 +14609,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(32768 /* DisallowInContext */, func); + return doOutsideOfContext(2048 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(32768 /* DisallowInContext */, func); + return doInsideOfContext(2048 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(65536 /* YieldContext */, func); + return doInsideOfContext(4096 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(131072 /* DecoratorContext */, func); + return doInsideOfContext(8192 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(262144 /* AwaitContext */, func); + return doInsideOfContext(16384 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(262144 /* AwaitContext */, func); + return doOutsideOfContext(16384 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(65536 /* YieldContext */ | 262144 /* AwaitContext */, func); + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(65536 /* YieldContext */); + return inContext(4096 /* YieldContext */); } function inDisallowInContext() { - return inContext(32768 /* DisallowInContext */); + return inContext(2048 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(131072 /* DecoratorContext */); + return inContext(8192 /* DecoratorContext */); } function inAwaitContext() { - return inContext(262144 /* AwaitContext */); + return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -13305,20 +14743,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 69 /* Identifier */) { + if (token() === 70 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 114 /* YieldKeyword */ && inYieldContext()) { + if (token() === 115 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 120 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 105 /* LastReservedWord */; + return token() > 106 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -13361,22 +14799,22 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 23 /* SemicolonToken */) { + if (token() === 24 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 17 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23 /* SemicolonToken */) { + if (token() === 24 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(23 /* SemicolonToken */); + return parseExpected(24 /* SemicolonToken */); } } // note: this function creates only node @@ -13385,8 +14823,8 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + return kind >= 141 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : + kind === 70 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } function createNodeArray(elements, pos) { @@ -13408,7 +14846,7 @@ var ts; // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 524288 /* ThisNodeHasError */; + node.flags |= 32768 /* ThisNodeHasError */; } return node; } @@ -13433,16 +14871,16 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(69 /* Identifier */); + var node = createNode(70 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 69 /* Identifier */) { + if (token() !== 70 /* Identifier */) { node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); } - return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -13459,7 +14897,7 @@ var ts; if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 20 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -13477,13 +14915,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(140 /* ComputedPropertyName */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(142 /* ComputedPropertyName */); + parseExpected(20 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -13497,21 +14935,21 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74 /* ConstKeyword */) { + if (token() === 75 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 81 /* EnumKeyword */; + return nextToken() === 82 /* EnumKeyword */; } - if (token() === 82 /* ExportKeyword */) { + if (token() === 83 /* ExportKeyword */) { nextToken(); - if (token() === 77 /* DefaultKeyword */) { + if (token() === 78 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token() !== 38 /* AsteriskToken */ && token() !== 117 /* AsKeyword */ && token() !== 16 /* OpenBraceToken */ && canFollowModifier(); } - if (token() === 77 /* DefaultKeyword */) { + if (token() === 78 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113 /* StaticKeyword */) { + if (token() === 114 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } @@ -13521,16 +14959,16 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 /* OpenBracketToken */ - || token() === 15 /* OpenBraceToken */ - || token() === 37 /* AsteriskToken */ - || token() === 22 /* DotDotDotToken */ + return token() === 20 /* OpenBracketToken */ + || token() === 16 /* OpenBraceToken */ + || token() === 38 /* AsteriskToken */ + || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || - (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 74 /* ClassKeyword */ || token() === 88 /* FunctionKeyword */ || + (token() === 119 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -13548,9 +14986,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 24 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token() === 72 /* CaseKeyword */ || token() === 78 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -13558,19 +14996,21 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 24 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || token() === 38 /* AsteriskToken */ || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); + case 17 /* RestProperties */: + return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -13585,37 +15025,37 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 17 /* TypeParameters */: + return token() === 25 /* CommaToken */ || token() === 23 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 18 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* CommaToken */ || token() === 23 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); - case 18 /* TypeArguments */: - case 19 /* TupleElementTypes */: - return token() === 24 /* CommaToken */ || isStartOfType(); - case 20 /* HeritageClauses */: + case 19 /* TypeArguments */: + case 20 /* TupleElementTypes */: + return token() === 25 /* CommaToken */ || isStartOfType(); + case 21 /* HeritageClauses */: return isHeritageClause(); - case 21 /* ImportOrExportSpecifiers */: + case 22 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 16 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; - case 22 /* JSDocFunctionParameters */: - case 23 /* JSDocTypeArguments */: - case 25 /* JSDocTupleTypes */: + case 23 /* JSDocFunctionParameters */: + case 24 /* JSDocTypeArguments */: + case 26 /* JSDocTupleTypes */: return JSDocParser.isJSDocType(); - case 24 /* JSDocRecordMembers */: + case 25 /* JSDocRecordMembers */: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15 /* OpenBraceToken */); - if (nextToken() === 16 /* CloseBraceToken */) { + ts.Debug.assert(token() === 16 /* OpenBraceToken */); + if (nextToken() === 17 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -13624,7 +15064,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 24 /* CommaToken */ || next === 15 /* OpenBraceToken */ || next === 83 /* ExtendsKeyword */ || next === 106 /* ImplementsKeyword */; + return next === 25 /* CommaToken */ || next === 16 /* OpenBraceToken */ || next === 84 /* ExtendsKeyword */ || next === 107 /* ImplementsKeyword */; } return true; } @@ -13637,8 +15077,8 @@ var ts; return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 /* ImplementsKeyword */ || - token() === 83 /* ExtendsKeyword */) { + if (token() === 107 /* ImplementsKeyword */ || + token() === 84 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -13661,44 +15101,45 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 21 /* ImportOrExportSpecifiers */: - return token() === 16 /* CloseBraceToken */; + case 22 /* ImportOrExportSpecifiers */: + return token() === 17 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token() === 17 /* CloseBraceToken */ || token() === 72 /* CaseKeyword */ || token() === 78 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 16 /* OpenBraceToken */ || token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 17 /* TypeParameters */: + case 18 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 28 /* GreaterThanToken */ || token() === 18 /* OpenParenToken */ || token() === 16 /* OpenBraceToken */ || token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; + return token() === 19 /* CloseParenToken */ || token() === 24 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 19 /* TupleElementTypes */: + case 20 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 20 /* CloseBracketToken */; + return token() === 21 /* CloseBracketToken */; case 16 /* Parameters */: + case 17 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; - case 20 /* HeritageClauses */: - return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; + return token() === 19 /* CloseParenToken */ || token() === 21 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 19 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 25 /* CommaToken */; + case 21 /* HeritageClauses */: + return token() === 16 /* OpenBraceToken */ || token() === 17 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; + return token() === 28 /* GreaterThanToken */ || token() === 40 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); - case 22 /* JSDocFunctionParameters */: - return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; - case 23 /* JSDocTypeArguments */: - return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; - case 25 /* JSDocTupleTypes */: - return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; - case 24 /* JSDocRecordMembers */: - return token() === 16 /* CloseBraceToken */; + return token() === 26 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + case 23 /* JSDocFunctionParameters */: + return token() === 19 /* CloseParenToken */ || token() === 55 /* ColonToken */ || token() === 17 /* CloseBraceToken */; + case 24 /* JSDocTypeArguments */: + return token() === 28 /* GreaterThanToken */ || token() === 17 /* CloseBraceToken */; + case 26 /* JSDocTupleTypes */: + return token() === 21 /* CloseBracketToken */ || token() === 17 /* CloseBraceToken */; + case 25 /* JSDocRecordMembers */: + return token() === 17 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -13716,7 +15157,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -13724,7 +15165,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 26 /* Count */; kind++) { + for (var kind = 0; kind < 27 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -13799,7 +15240,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 1540096 /* ContextFlags */; + var nodeContextFlags = node.flags & 96256 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -13834,20 +15275,22 @@ var ts; return isReusableVariableDeclaration(node); case 16 /* Parameters */: return isReusableParameter(node); + case 17 /* RestProperties */: + return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 20 /* HeritageClauses */: + case 21 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 17 /* TypeParameters */: + case 18 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 19 /* TupleElementTypes */: + case 20 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -13855,7 +15298,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 18 /* TypeArguments */: + case 19 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -13879,20 +15322,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 148 /* Constructor */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 145 /* PropertyDeclaration */: - case 198 /* SemicolonClassElement */: + case 150 /* Constructor */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 203 /* SemicolonClassElement */: return true; - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 69 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 121 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 70 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 122 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -13901,8 +15344,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: return true; } } @@ -13911,58 +15354,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 200 /* VariableStatement */: - case 199 /* Block */: - case 203 /* IfStatement */: - case 202 /* ExpressionStatement */: - case 215 /* ThrowStatement */: - case 211 /* ReturnStatement */: - case 213 /* SwitchStatement */: - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 201 /* EmptyStatement */: - case 216 /* TryStatement */: - case 214 /* LabeledStatement */: - case 204 /* DoStatement */: - case 217 /* DebuggerStatement */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + case 205 /* VariableStatement */: + case 204 /* Block */: + case 208 /* IfStatement */: + case 207 /* ExpressionStatement */: + case 220 /* ThrowStatement */: + case 216 /* ReturnStatement */: + case 218 /* SwitchStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 211 /* ForStatement */: + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + case 206 /* EmptyStatement */: + case 221 /* TryStatement */: + case 219 /* LabeledStatement */: + case 209 /* DoStatement */: + case 222 /* DebuggerStatement */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 228 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 255 /* EnumMember */; + return node.kind === 260 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 152 /* ConstructSignature */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 144 /* PropertySignature */: - case 151 /* CallSignature */: + case 154 /* ConstructSignature */: + case 148 /* MethodSignature */: + case 155 /* IndexSignature */: + case 146 /* PropertySignature */: + case 153 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 218 /* VariableDeclaration */) { + if (node.kind !== 223 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -13983,7 +15426,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 142 /* Parameter */) { + if (node.kind !== 144 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -14005,6 +15448,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; + case 17 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -14016,17 +15460,17 @@ var ts; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 17 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 18 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 19 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 20 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 21 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; - case 22 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 23 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 25 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; - case 24 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; + case 23 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 24 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 26 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; + case 25 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -14040,7 +15484,7 @@ var ts; if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(24 /* CommaToken */)) { + if (parseOptional(25 /* CommaToken */)) { continue; } commaStart = -1; // Back to the state where the last token was not a comma @@ -14049,13 +15493,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(24 /* CommaToken */); + parseExpected(25 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 24 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -14094,8 +15538,8 @@ var ts; // The allowReservedWords parameter controls whether reserved words are permitted after the first dot function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(21 /* DotToken */)) { - var node = createNode(139 /* QualifiedName */, entity.pos); // !!! + while (parseOptional(22 /* DotToken */)) { + var node = createNode(141 /* QualifiedName */, entity.pos); // !!! node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -14128,33 +15572,33 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); - ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + var template = createNode(194 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 13 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 13 /* TemplateMiddle */); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 14 /* TemplateMiddle */); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(197 /* TemplateSpan */); + var span = createNode(202 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16 /* CloseBraceToken */) { + if (token() === 17 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); + literal = parseExpectedToken(15 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(17 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -14162,8 +15606,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 14 /* TemplateMiddle */ || fragment.kind === 15 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14194,35 +15645,35 @@ var ts; // TYPES function parseTypeReference() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - var node = createNode(155 /* TypeReference */, typeName.pos); + var node = createNode(157 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { - node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 26 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(154 /* TypePredicate */, lhs.pos); + var node = createNode(156 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(165 /* ThisType */); + var node = createNode(167 /* ThisType */); nextToken(); return finishNode(node); } function parseTypeQuery() { - var node = createNode(158 /* TypeQuery */); - parseExpected(101 /* TypeOfKeyword */); + var node = createNode(160 /* TypeQuery */); + parseExpected(102 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(141 /* TypeParameter */); + var node = createNode(143 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(83 /* ExtendsKeyword */)) { + if (parseOptional(84 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -14244,29 +15695,29 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25 /* LessThanToken */) { - return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (token() === 26 /* LessThanToken */) { + return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(54 /* ColonToken */)) { + if (parseOptional(55 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; + return token() === 23 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 /* AtToken */ || token() === 98 /* ThisKeyword */; } function parseParameter() { - var node = createNode(142 /* Parameter */); - if (token() === 97 /* ThisKeyword */) { + var node = createNode(144 /* Parameter */); + if (token() === 98 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -14281,7 +15732,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(53 /* QuestionToken */); + node.questionToken = parseOptionalToken(54 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(/*inParameter*/ true); // Do not check for initializers in an ambient context for parameters. This is not @@ -14301,7 +15752,7 @@ var ts; return parseInitializer(/*inParameter*/ true); } function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 34 /* EqualsGreaterThanToken */; + var returnTokenRequired = returnToken === 35 /* EqualsGreaterThanToken */; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { @@ -14326,7 +15777,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(17 /* OpenParenToken */)) { + if (parseExpected(18 /* OpenParenToken */)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); @@ -14334,7 +15785,7 @@ var ts; var result = parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(18 /* CloseParenToken */) && requireCompleteParameterList) { + if (!parseExpected(19 /* CloseParenToken */) && requireCompleteParameterList) { // Caller insisted that we had to end with a ) We didn't. So just return // undefined here. return undefined; @@ -14349,7 +15800,7 @@ var ts; function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(24 /* CommaToken */)) { + if (parseOptional(25 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -14357,15 +15808,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 152 /* ConstructSignature */) { - parseExpected(92 /* NewKeyword */); + if (kind === 154 /* ConstructSignature */) { + parseExpected(93 /* NewKeyword */); } - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token() !== 19 /* OpenBracketToken */) { + if (token() !== 20 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -14388,7 +15839,7 @@ var ts; // [] // nextToken(); - if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { + if (token() === 23 /* DotDotDotToken */ || token() === 21 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -14407,49 +15858,49 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { + if (token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 53 /* QuestionToken */) { + if (token() !== 54 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; + return token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */ || token() === 21 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(153 /* IndexSignature */, fullStart); + var node = createNode(155 /* IndexSignature */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { - var method = createNode(146 /* MethodSignature */, fullStart); + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { + var method = createNode(148 /* MethodSignature */, fullStart); method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(method)); } else { - var property = createNode(144 /* PropertySignature */, fullStart); + var property = createNode(146 /* PropertySignature */, fullStart); property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56 /* EqualsToken */) { + if (token() === 57 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -14462,7 +15913,7 @@ var ts; function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier @@ -14471,7 +15922,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -14482,21 +15933,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 17 /* OpenParenToken */ || - token() === 25 /* LessThanToken */ || - token() === 53 /* QuestionToken */ || - token() === 54 /* ColonToken */ || - token() === 24 /* CommaToken */ || + return token() === 18 /* OpenParenToken */ || + token() === 26 /* LessThanToken */ || + token() === 54 /* QuestionToken */ || + token() === 55 /* ColonToken */ || + token() === 25 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { - return parseSignatureMember(151 /* CallSignature */); + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { + return parseSignatureMember(153 /* CallSignature */); } - if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(152 /* ConstructSignature */); + if (token() === 93 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(154 /* ConstructSignature */); } var fullStart = getNodePos(); var modifiers = parseModifiers(); @@ -14507,50 +15958,77 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; + return token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(159 /* TypeLiteral */); + var node = createNode(161 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(15 /* OpenBraceToken */)) { + if (parseExpected(16 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { members = createMissingList(); } return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === 130 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 20 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 91 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(143 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(91 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(170 /* MappedType */); + parseExpected(16 /* OpenBraceToken */); + node.readonlyToken = parseOptionalToken(130 /* ReadonlyKeyword */); + parseExpected(20 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(21 /* CloseBracketToken */); + node.questionToken = parseOptionalToken(54 /* QuestionToken */); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(17 /* CloseBraceToken */); + return finishNode(node); + } function parseTupleType() { - var node = createNode(161 /* TupleType */); - node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + var node = createNode(163 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(164 /* ParenthesizedType */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(166 /* ParenthesizedType */); + parseExpected(18 /* OpenParenToken */); node.type = parseType(); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 157 /* ConstructorType */) { - parseExpected(92 /* NewKeyword */); + if (kind === 159 /* ConstructorType */) { + parseExpected(93 /* NewKeyword */); } - fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(35 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 /* DotToken */ ? undefined : node; + return token() === 22 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode() { - var node = createNode(166 /* LiteralType */); + var node = createNode(171 /* LiteralType */); node.literal = parseSimpleUnaryExpression(); finishNode(node); return node; @@ -14560,42 +16038,42 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseLiteralTypeNode(); - case 36 /* MinusToken */: + case 37 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: + case 104 /* VoidKeyword */: + case 94 /* NullKeyword */: return parseTokenNode(); - case 97 /* ThisKeyword */: { + case 98 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 101 /* TypeOfKeyword */: + case 102 /* TypeOfKeyword */: return parseTypeQuery(); - case 15 /* OpenBraceToken */: - return parseTypeLiteral(); - case 19 /* OpenBracketToken */: + case 16 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 20 /* OpenBracketToken */: return parseTupleType(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseParenthesizedType(); default: return parseTypeReference(); @@ -14603,29 +16081,31 @@ var ts; } function isStartOfType() { switch (token()) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 97 /* ThisKeyword */: - case 101 /* TypeOfKeyword */: - case 127 /* NeverKeyword */: - case 15 /* OpenBraceToken */: - case 19 /* OpenBracketToken */: - case 25 /* LessThanToken */: - case 92 /* NewKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 98 /* ThisKeyword */: + case 102 /* TypeOfKeyword */: + case 129 /* NeverKeyword */: + case 16 /* OpenBraceToken */: + case 20 /* OpenBracketToken */: + case 26 /* LessThanToken */: + case 48 /* BarToken */: + case 47 /* AmpersandToken */: + case 93 /* NewKeyword */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return true; - case 36 /* MinusToken */: + case 37 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return lookAhead(isStartOfParenthesizedOrFunctionType); @@ -14635,19 +16115,43 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 19 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { - parseExpected(20 /* CloseBracketToken */); - var node = createNode(160 /* ArrayType */, type.pos); - node.elementType = type; - type = finishNode(node); + while (!scanner.hasPrecedingLineBreak() && parseOptional(20 /* OpenBracketToken */)) { + if (isStartOfType()) { + var node = createNode(169 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(21 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(162 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(21 /* CloseBracketToken */); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator) { + var node = createNode(168 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 126 /* KeyOfKeyword */: + return parseTypeOperator(126 /* KeyOfKeyword */); + } + return parseArrayTypeOrHigher(); + } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { var types = createNodeArray([type], type.pos); @@ -14662,27 +16166,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(163 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + return parseUnionOrIntersectionType(165 /* IntersectionType */, parseTypeOperatorOrHigher, 47 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + return parseUnionOrIntersectionType(164 /* UnionType */, parseIntersectionTypeOrHigher, 48 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { return true; } - return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 18 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 97 /* ThisKeyword */) { + if (isIdentifier() || token() === 98 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { + if (token() === 20 /* OpenBracketToken */ || token() === 16 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -14692,7 +16196,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { + if (token() === 19 /* CloseParenToken */ || token() === 23 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -14700,17 +16204,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || - token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { + if (token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */ || + token() === 54 /* QuestionToken */ || token() === 57 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 18 /* CloseParenToken */) { + if (token() === 19 /* CloseParenToken */) { nextToken(); - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -14722,7 +16226,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(154 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(156 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -14733,7 +16237,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -14741,41 +16245,41 @@ var ts; function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(327680 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(156 /* FunctionType */); + return parseFunctionOrConstructorType(158 /* FunctionType */); } - if (token() === 92 /* NewKeyword */) { - return parseFunctionOrConstructorType(157 /* ConstructorType */); + if (token() === 93 /* NewKeyword */) { + return parseFunctionOrConstructorType(159 /* ConstructorType */); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(54 /* ColonToken */) ? parseType() : undefined; + return parseOptional(55 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 17 /* OpenParenToken */: - case 19 /* OpenBracketToken */: - case 15 /* OpenBraceToken */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 92 /* NewKeyword */: - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - case 69 /* Identifier */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 18 /* OpenParenToken */: + case 20 /* OpenBracketToken */: + case 16 /* OpenBraceToken */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 93 /* NewKeyword */: + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + case 70 /* Identifier */: return true; default: return isIdentifier(); @@ -14786,18 +16290,18 @@ var ts; return true; } switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 78 /* DeleteKeyword */: - case 101 /* TypeOfKeyword */: - case 103 /* VoidKeyword */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: - case 25 /* LessThanToken */: - case 119 /* AwaitKeyword */: - case 114 /* YieldKeyword */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 79 /* DeleteKeyword */: + case 102 /* TypeOfKeyword */: + case 104 /* VoidKeyword */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: + case 26 /* LessThanToken */: + case 120 /* AwaitKeyword */: + case 115 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -14815,10 +16319,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 15 /* OpenBraceToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && - token() !== 55 /* AtToken */ && + return token() !== 16 /* OpenBraceToken */ && + token() !== 88 /* FunctionKeyword */ && + token() !== 74 /* ClassKeyword */ && + token() !== 56 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -14832,7 +16336,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(24 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(25 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -14841,7 +16345,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56 /* EqualsToken */) { + if (token() !== 57 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -14850,7 +16354,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 16 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -14858,7 +16362,7 @@ var ts; } // Initializer[In, Yield] : // = AssignmentExpression[?In, ?Yield] - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); return parseAssignmentExpressionOrHigher(); } function parseAssignmentExpressionOrHigher() { @@ -14904,7 +16408,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 70 /* Identifier */ && token() === 35 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -14920,7 +16424,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114 /* YieldKeyword */) { + if (token() === 115 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -14949,15 +16453,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(190 /* YieldExpression */); + var node = createNode(195 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + (token() === 38 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -14968,21 +16472,21 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 35 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(180 /* ArrowFunction */, asyncModifier.pos); + node = createNode(185 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(180 /* ArrowFunction */, identifier.pos); + node = createNode(185 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(142 /* Parameter */, identifier.pos); + var parameter = createNode(144 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(35 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -15007,8 +16511,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(35 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 35 /* EqualsGreaterThanToken */ || lastToken === 16 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return addJSDocComment(finishNode(arrowFunction)); @@ -15018,10 +16522,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */ || token() === 119 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -15031,28 +16535,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { + if (token() !== 18 /* OpenParenToken */ && token() !== 26 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 17 /* OpenParenToken */) { - if (second === 18 /* CloseParenToken */) { + if (first === 18 /* OpenParenToken */) { + if (second === 19 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 34 /* EqualsGreaterThanToken */: - case 54 /* ColonToken */: - case 15 /* OpenBraceToken */: + case 35 /* EqualsGreaterThanToken */: + case 55 /* ColonToken */: + case 16 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -15064,12 +16568,12 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 19 /* OpenBracketToken */ || second === 15 /* OpenBraceToken */) { + if (second === 20 /* OpenBracketToken */ || second === 16 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 22 /* DotDotDotToken */) { + if (second === 23 /* DotDotDotToken */) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, @@ -15082,7 +16586,7 @@ var ts; } // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. - if (nextToken() === 54 /* ColonToken */) { + if (nextToken() === 55 /* ColonToken */) { return 1 /* True */; } // This *could* be a parenthesized arrow function. @@ -15090,7 +16594,7 @@ var ts; return 2 /* Unknown */; } else { - ts.Debug.assert(first === 25 /* LessThanToken */); + ts.Debug.assert(first === 26 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -15100,17 +16604,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 83 /* ExtendsKeyword */) { + if (third === 84 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 56 /* EqualsToken */: - case 27 /* GreaterThanToken */: + case 57 /* EqualsToken */: + case 28 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 24 /* CommaToken */) { + else if (third === 25 /* CommaToken */) { return true; } return false; @@ -15129,7 +16633,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -15143,23 +16647,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 35 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 70 /* Identifier */ && token() === 35 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(180 /* ArrowFunction */); + var node = createNode(185 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); // Arrow functions are never generators. @@ -15169,7 +16673,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; @@ -15182,19 +16686,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 35 /* EqualsGreaterThanToken */ && token() !== 16 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token() !== 23 /* SemicolonToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && + if (token() !== 24 /* SemicolonToken */ && + token() !== 88 /* FunctionKeyword */ && + token() !== 74 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -15219,17 +16723,17 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(53 /* QuestionToken */); + var questionToken = parseOptionalToken(54 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(188 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(193 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(54 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(54 /* ColonToken */)); + node.colonToken = parseExpectedToken(55 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(55 /* ColonToken */)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -15238,7 +16742,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 /* InKeyword */ || t === 138 /* OfKeyword */; + return t === 91 /* InKeyword */ || t === 140 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -15267,16 +16771,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 39 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 /* InKeyword */ && inDisallowInContext()) { + if (token() === 91 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 116 /* AsKeyword */) { + if (token() === 117 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -15297,48 +16801,48 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90 /* InKeyword */) { + if (inDisallowInContext() && token() === 91 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return 1; - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return 2; - case 47 /* BarToken */: + case 48 /* BarToken */: return 3; - case 48 /* CaretToken */: + case 49 /* CaretToken */: return 4; - case 46 /* AmpersandToken */: + case 47 /* AmpersandToken */: return 5; - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return 6; - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: + case 92 /* InstanceOfKeyword */: + case 91 /* InKeyword */: + case 117 /* AsKeyword */: return 7; - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return 8; - case 35 /* PlusToken */: - case 36 /* MinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: return 9; - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: return 10; - case 38 /* AsteriskAsteriskToken */: + case 39 /* AsteriskAsteriskToken */: return 11; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -15346,45 +16850,45 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(187 /* BinaryExpression */, left.pos); + var node = createNode(192 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(195 /* AsExpression */, left.pos); + var node = createNode(200 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(185 /* PrefixUnaryExpression */); + var node = createNode(190 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(181 /* DeleteExpression */); + var node = createNode(186 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(182 /* TypeOfExpression */); + var node = createNode(187 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(183 /* VoidExpression */); + var node = createNode(188 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 119 /* AwaitKeyword */) { + if (token() === 120 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -15394,7 +16898,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(184 /* AwaitExpression */); + var node = createNode(189 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15418,7 +16922,7 @@ var ts; */ if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 /* AsteriskAsteriskToken */ ? + return token() === 39 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } @@ -15435,9 +16939,9 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38 /* AsteriskAsteriskToken */) { + if (token() === 39 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 182 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -15462,23 +16966,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 78 /* DeleteKeyword */: + case 79 /* DeleteKeyword */: return parseDeleteExpression(); - case 101 /* TypeOfKeyword */: + case 102 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return parseVoidExpression(); - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 119 /* AwaitKeyword */: + case 120 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -15500,16 +17004,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 78 /* DeleteKeyword */: - case 101 /* TypeOfKeyword */: - case 103 /* VoidKeyword */: - case 119 /* AwaitKeyword */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 79 /* DeleteKeyword */: + case 102 /* TypeOfKeyword */: + case 104 /* VoidKeyword */: + case 120 /* AwaitKeyword */: return false; - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -15532,21 +17036,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { - var node = createNode(185 /* PrefixUnaryExpression */); + if (token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) { + var node = createNode(190 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 26 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(191 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -15585,7 +17089,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token() === 95 /* SuperKeyword */ + var expression = token() === 96 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -15645,14 +17149,14 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { + if (token() === 18 /* OpenParenToken */ || token() === 22 /* DotToken */ || token() === 20 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(172 /* PropertyAccessExpression */, expression.pos); + var node = createNode(177 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(22 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -15660,10 +17164,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 69 /* Identifier */) { + if (lhs.kind === 70 /* Identifier */) { return lhs.text === rhs.text; } - if (lhs.kind === 97 /* ThisKeyword */) { + if (lhs.kind === 98 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -15675,8 +17179,8 @@ var ts; function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 243 /* JsxOpeningElement */) { - var node = createNode(241 /* JsxElement */, opening.pos); + if (opening.kind === 248 /* JsxOpeningElement */) { + var node = createNode(246 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -15686,7 +17190,7 @@ var ts; result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 242 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 247 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -15697,15 +17201,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 25 /* LessThanToken */) { + if (inExpressionContext && token() === 26 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(187 /* BinaryExpression */, result.pos); + var badNode = createNode(192 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(24 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(25 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -15713,17 +17217,17 @@ var ts; return result; } function parseJsxText() { - var node = createNode(244 /* JsxText */, scanner.getStartPos()); + var node = createNode(10 /* JsxText */, scanner.getStartPos()); currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 244 /* JsxText */: + case 10 /* JsxText */: return parseJsxText(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } ts.Debug.fail("Unknown JSX child kind " + token()); @@ -15734,7 +17238,7 @@ var ts; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 26 /* LessThanSlashToken */) { + if (token() === 27 /* LessThanSlashToken */) { // Closing tag break; } @@ -15752,27 +17256,27 @@ var ts; } function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(25 /* LessThanToken */); + parseExpected(26 /* LessThanToken */); var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token() === 27 /* GreaterThanToken */) { + if (token() === 28 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(243 /* JsxOpeningElement */, fullStart); + node = createNode(248 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(39 /* SlashToken */); + parseExpected(40 /* SlashToken */); if (inExpressionContext) { - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(28 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(242 /* JsxSelfClosingElement */, fullStart); + node = createNode(247 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -15785,10 +17289,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 97 /* ThisKeyword */ ? + var expression = token() === 98 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(21 /* DotToken */)) { - var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(22 /* DotToken */)) { + var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15796,28 +17300,28 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(248 /* JsxExpression */); - parseExpected(15 /* OpenBraceToken */); - if (token() !== 16 /* CloseBraceToken */) { + var node = createNode(252 /* JsxExpression */); + parseExpected(16 /* OpenBraceToken */); + if (token() !== 17 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(17 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(246 /* JsxAttribute */); + var node = createNode(250 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 56 /* EqualsToken */) { + if (token() === 57 /* EqualsToken */) { switch (scanJsxAttributeValue()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); @@ -15830,72 +17334,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(247 /* JsxSpreadAttribute */); - parseExpected(15 /* OpenBraceToken */); - parseExpected(22 /* DotDotDotToken */); + var node = createNode(251 /* JsxSpreadAttribute */); + parseExpected(16 /* OpenBraceToken */); + parseExpected(23 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(245 /* JsxClosingElement */); - parseExpected(26 /* LessThanSlashToken */); + var node = createNode(249 /* JsxClosingElement */); + parseExpected(27 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(28 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(177 /* TypeAssertionExpression */); - parseExpected(25 /* LessThanToken */); + var node = createNode(182 /* TypeAssertionExpression */); + parseExpected(26 /* LessThanToken */); node.type = parseType(); - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(21 /* DotToken */); + var dotToken = parseOptionalToken(22 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 50 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(201 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(173 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(20 /* OpenBracketToken */)) { + var indexedAccess = createNode(178 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token() !== 20 /* CloseBracketToken */) { + if (token() !== 21 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } - if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { - var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); + if (token() === 12 /* NoSubstitutionTemplateLiteral */ || token() === 13 /* TemplateHead */) { + var tagExpression = createNode(181 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 12 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -15907,7 +17411,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -15916,15 +17420,15 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(174 /* CallExpression */, expression.pos); + var callExpr = createNode(179 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 17 /* OpenParenToken */) { - var callExpr = createNode(174 /* CallExpression */, expression.pos); + else if (token() === 18 /* OpenParenToken */) { + var callExpr = createNode(179 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -15934,17 +17438,17 @@ var ts; } } function parseArgumentList() { - parseExpected(17 /* OpenParenToken */); + parseExpected(18 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(25 /* LessThanToken */)) { + if (!parseOptional(26 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(18 /* TypeArguments */, parseType); - if (!parseExpected(27 /* GreaterThanToken */)) { + var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + if (!parseExpected(28 /* GreaterThanToken */)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; } @@ -15956,32 +17460,32 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 17 /* OpenParenToken */: // foo( + case 18 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. - case 21 /* DotToken */: // foo. - case 18 /* CloseParenToken */: // foo) - case 20 /* CloseBracketToken */: // foo] - case 54 /* ColonToken */: // foo: - case 23 /* SemicolonToken */: // foo; - case 53 /* QuestionToken */: // foo? - case 30 /* EqualsEqualsToken */: // foo == - case 32 /* EqualsEqualsEqualsToken */: // foo === - case 31 /* ExclamationEqualsToken */: // foo != - case 33 /* ExclamationEqualsEqualsToken */: // foo !== - case 51 /* AmpersandAmpersandToken */: // foo && - case 52 /* BarBarToken */: // foo || - case 48 /* CaretToken */: // foo ^ - case 46 /* AmpersandToken */: // foo & - case 47 /* BarToken */: // foo | - case 16 /* CloseBraceToken */: // foo } + case 22 /* DotToken */: // foo. + case 19 /* CloseParenToken */: // foo) + case 21 /* CloseBracketToken */: // foo] + case 55 /* ColonToken */: // foo: + case 24 /* SemicolonToken */: // foo; + case 54 /* QuestionToken */: // foo? + case 31 /* EqualsEqualsToken */: // foo == + case 33 /* EqualsEqualsEqualsToken */: // foo === + case 32 /* ExclamationEqualsToken */: // foo != + case 34 /* ExclamationEqualsEqualsToken */: // foo !== + case 52 /* AmpersandAmpersandToken */: // foo && + case 53 /* BarBarToken */: // foo || + case 49 /* CaretToken */: // foo ^ + case 47 /* AmpersandToken */: // foo & + case 48 /* BarToken */: // foo | + case 17 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 24 /* CommaToken */: // foo, - case 15 /* OpenBraceToken */: // foo { + case 25 /* CommaToken */: // foo, + case 16 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -15994,21 +17498,21 @@ var ts; switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseTokenNode(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseParenthesizedExpression(); - case 19 /* OpenBracketToken */: + case 20 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 118 /* AsyncKeyword */: + case 119 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -16016,77 +17520,83 @@ var ts; break; } return parseFunctionExpression(); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassExpression(); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionExpression(); - case 92 /* NewKeyword */: + case 93 /* NewKeyword */: return parseNewExpression(); - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - if (reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + if (reScanSlashToken() === 11 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 12 /* TemplateHead */: + case 13 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(178 /* ParenthesizedExpression */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(183 /* ParenthesizedExpression */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(191 /* SpreadElementExpression */); - parseExpected(22 /* DotDotDotToken */); + var node = createNode(196 /* SpreadElement */); + parseExpected(23 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token() === 23 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 25 /* CommaToken */ ? createNode(198 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(170 /* ArrayLiteralExpression */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(175 /* ArrayLiteralExpression */); + parseExpected(20 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(123 /* GetKeyword */)) { - return parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers); + if (parseContextualModifier(124 /* GetKeyword */)) { + return parseAccessorDeclaration(151 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(131 /* SetKeyword */)) { - return parseAccessorDeclaration(150 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(133 /* SetKeyword */)) { + return parseAccessorDeclaration(152 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); + if (dotDotDotToken) { + var spreadElement = createNode(259 /* SpreadAssignment */, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } var decorators = parseDecorators(); var modifiers = parseModifiers(); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (asteriskToken || token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -16094,12 +17604,12 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 /* CommaToken */ || token() === 17 /* CloseBraceToken */ || token() === 57 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(258 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(56 /* EqualsToken */); + var equalsToken = parseOptionalToken(57 /* EqualsToken */); if (equalsToken) { shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); @@ -16107,23 +17617,23 @@ var ts; return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(253 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(257 /* PropertyAssignment */, fullStart); propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(171 /* ObjectLiteralExpression */); - parseExpected(15 /* OpenBraceToken */); + var node = createNode(176 /* ObjectLiteralExpression */); + parseExpected(16 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -16136,10 +17646,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNode(179 /* FunctionExpression */); + var node = createNode(184 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(87 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + parseExpected(88 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); node.name = @@ -16147,7 +17657,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -16158,24 +17668,24 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(175 /* NewExpression */); - parseExpected(92 /* NewKeyword */); + var node = createNode(180 /* NewExpression */); + parseExpected(93 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17 /* OpenParenToken */) { + if (node.typeArguments || token() === 18 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(199 /* Block */); - if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(204 /* Block */); + if (parseExpected(16 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -16202,51 +17712,51 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(201 /* EmptyStatement */); - parseExpected(23 /* SemicolonToken */); + var node = createNode(206 /* EmptyStatement */); + parseExpected(24 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(203 /* IfStatement */); - parseExpected(88 /* IfKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(208 /* IfStatement */); + parseExpected(89 /* IfKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(80 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(81 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(204 /* DoStatement */); - parseExpected(79 /* DoKeyword */); + var node = createNode(209 /* DoStatement */); + parseExpected(80 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(104 /* WhileKeyword */); - parseExpected(17 /* OpenParenToken */); + parseExpected(105 /* WhileKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(23 /* SemicolonToken */); + parseOptional(24 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(205 /* WhileStatement */); - parseExpected(104 /* WhileKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(210 /* WhileStatement */); + parseExpected(105 /* WhileKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(86 /* ForKeyword */); - parseExpected(17 /* OpenParenToken */); + parseExpected(87 /* ForKeyword */); + parseExpected(18 /* OpenParenToken */); var initializer = undefined; - if (token() !== 23 /* SemicolonToken */) { - if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { + if (token() !== 24 /* SemicolonToken */) { + if (token() === 103 /* VarKeyword */ || token() === 109 /* LetKeyword */ || token() === 75 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -16254,32 +17764,32 @@ var ts; } } var forOrForInOrForOfStatement; - if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(207 /* ForInStatement */, pos); + if (parseOptional(91 /* InKeyword */)) { + var forInStatement = createNode(212 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(138 /* OfKeyword */)) { - var forOfStatement = createNode(208 /* ForOfStatement */, pos); + else if (parseOptional(140 /* OfKeyword */)) { + var forOfStatement = createNode(213 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(206 /* ForStatement */, pos); + var forStatement = createNode(211 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(23 /* SemicolonToken */); - if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { + parseExpected(24 /* SemicolonToken */); + if (token() !== 24 /* SemicolonToken */ && token() !== 19 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(23 /* SemicolonToken */); - if (token() !== 18 /* CloseParenToken */) { + parseExpected(24 /* SemicolonToken */); + if (token() !== 19 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -16287,7 +17797,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 210 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 215 /* BreakStatement */ ? 71 /* BreakKeyword */ : 76 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -16295,8 +17805,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(211 /* ReturnStatement */); - parseExpected(94 /* ReturnKeyword */); + var node = createNode(216 /* ReturnStatement */); + parseExpected(95 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -16304,42 +17814,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(212 /* WithStatement */); - parseExpected(105 /* WithKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(217 /* WithStatement */); + parseExpected(106 /* WithKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseCaseClause() { - var node = createNode(249 /* CaseClause */); - parseExpected(71 /* CaseKeyword */); + var node = createNode(253 /* CaseClause */); + parseExpected(72 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(250 /* DefaultClause */); - parseExpected(77 /* DefaultKeyword */); - parseExpected(54 /* ColonToken */); + var node = createNode(254 /* DefaultClause */); + parseExpected(78 /* DefaultKeyword */); + parseExpected(55 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 72 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(213 /* SwitchStatement */); - parseExpected(96 /* SwitchKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(218 /* SwitchStatement */); + parseExpected(97 /* SwitchKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(227 /* CaseBlock */, scanner.getStartPos()); - parseExpected(15 /* OpenBraceToken */); + parseExpected(19 /* CloseParenToken */); + var caseBlock = createNode(232 /* CaseBlock */, scanner.getStartPos()); + parseExpected(16 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -16351,39 +17861,39 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(215 /* ThrowStatement */); - parseExpected(98 /* ThrowKeyword */); + var node = createNode(220 /* ThrowStatement */); + parseExpected(99 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(216 /* TryStatement */); - parseExpected(100 /* TryKeyword */); + var node = createNode(221 /* TryStatement */); + parseExpected(101 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 73 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 85 /* FinallyKeyword */) { - parseExpected(85 /* FinallyKeyword */); + if (!node.catchClause || token() === 86 /* FinallyKeyword */) { + parseExpected(86 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(252 /* CatchClause */); - parseExpected(72 /* CatchKeyword */); - if (parseExpected(17 /* OpenParenToken */)) { + var result = createNode(256 /* CatchClause */); + parseExpected(73 /* CatchKeyword */); + if (parseExpected(18 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); } - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(217 /* DebuggerStatement */); - parseExpected(76 /* DebuggerKeyword */); + var node = createNode(222 /* DebuggerStatement */); + parseExpected(77 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -16393,14 +17903,14 @@ var ts; // a colon. var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); - if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(214 /* LabeledStatement */, fullStart); + if (expression.kind === 70 /* Identifier */ && parseOptional(55 /* ColonToken */)) { + var labeledStatement = createNode(219 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(202 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(207 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return addJSDocComment(finishNode(expressionStatement)); @@ -16412,7 +17922,7 @@ var ts; } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 88 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); @@ -16421,12 +17931,12 @@ var ts; function isDeclaration() { while (true) { switch (token()) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -16449,41 +17959,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 107 /* InterfaceKeyword */: - case 134 /* TypeKeyword */: + case 108 /* InterfaceKeyword */: + case 136 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 122 /* DeclareKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 128 /* ReadonlyKeyword */: + case 116 /* AbstractKeyword */: + case 119 /* AsyncKeyword */: + case 123 /* DeclareKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 130 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 137 /* GlobalKeyword */: + case 139 /* GlobalKeyword */: nextToken(); - return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; - case 89 /* ImportKeyword */: + return token() === 16 /* OpenBraceToken */ || token() === 70 /* Identifier */ || token() === 83 /* ExportKeyword */; + case 90 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 82 /* ExportKeyword */: + return token() === 9 /* StringLiteral */ || token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 83 /* ExportKeyword */: nextToken(); - if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || - token() === 116 /* AsKeyword */) { + if (token() === 57 /* EqualsToken */ || token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */ || token() === 78 /* DefaultKeyword */ || + token() === 117 /* AsKeyword */) { return true; } continue; - case 113 /* StaticKeyword */: + case 114 /* StaticKeyword */: nextToken(); continue; default: @@ -16496,49 +18006,49 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 55 /* AtToken */: - case 23 /* SemicolonToken */: - case 15 /* OpenBraceToken */: - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 88 /* IfKeyword */: - case 79 /* DoKeyword */: - case 104 /* WhileKeyword */: - case 86 /* ForKeyword */: - case 75 /* ContinueKeyword */: - case 70 /* BreakKeyword */: - case 94 /* ReturnKeyword */: - case 105 /* WithKeyword */: - case 96 /* SwitchKeyword */: - case 98 /* ThrowKeyword */: - case 100 /* TryKeyword */: - case 76 /* DebuggerKeyword */: + case 56 /* AtToken */: + case 24 /* SemicolonToken */: + case 16 /* OpenBraceToken */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: + case 89 /* IfKeyword */: + case 80 /* DoKeyword */: + case 105 /* WhileKeyword */: + case 87 /* ForKeyword */: + case 76 /* ContinueKeyword */: + case 71 /* BreakKeyword */: + case 95 /* ReturnKeyword */: + case 106 /* WithKeyword */: + case 97 /* SwitchKeyword */: + case 99 /* ThrowKeyword */: + case 101 /* TryKeyword */: + case 77 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return true; - case 74 /* ConstKeyword */: - case 82 /* ExportKeyword */: - case 89 /* ImportKeyword */: + case 75 /* ConstKeyword */: + case 83 /* ExportKeyword */: + case 90 /* ImportKeyword */: return isStartOfDeclaration(); - case 118 /* AsyncKeyword */: - case 122 /* DeclareKeyword */: - case 107 /* InterfaceKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: - case 134 /* TypeKeyword */: - case 137 /* GlobalKeyword */: + case 119 /* AsyncKeyword */: + case 123 /* DeclareKeyword */: + case 108 /* InterfaceKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 136 /* TypeKeyword */: + case 139 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); @@ -16548,7 +18058,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; + return isIdentifier() || token() === 16 /* OpenBraceToken */ || token() === 20 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -16557,67 +18067,67 @@ var ts; } function parseStatement() { switch (token()) { - case 23 /* SemicolonToken */: + case 24 /* SemicolonToken */: return parseEmptyStatement(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 102 /* VarKeyword */: + case 103 /* VarKeyword */: return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 108 /* LetKeyword */: + case 109 /* LetKeyword */: if (isLetDeclaration()) { return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); } break; - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 88 /* IfKeyword */: + case 89 /* IfKeyword */: return parseIfStatement(); - case 79 /* DoKeyword */: + case 80 /* DoKeyword */: return parseDoStatement(); - case 104 /* WhileKeyword */: + case 105 /* WhileKeyword */: return parseWhileStatement(); - case 86 /* ForKeyword */: + case 87 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(209 /* ContinueStatement */); - case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(210 /* BreakStatement */); - case 94 /* ReturnKeyword */: + case 76 /* ContinueKeyword */: + return parseBreakOrContinueStatement(214 /* ContinueStatement */); + case 71 /* BreakKeyword */: + return parseBreakOrContinueStatement(215 /* BreakStatement */); + case 95 /* ReturnKeyword */: return parseReturnStatement(); - case 105 /* WithKeyword */: + case 106 /* WithKeyword */: return parseWithStatement(); - case 96 /* SwitchKeyword */: + case 97 /* SwitchKeyword */: return parseSwitchStatement(); - case 98 /* ThrowKeyword */: + case 99 /* ThrowKeyword */: return parseThrowStatement(); - case 100 /* TryKeyword */: + case 101 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return parseTryStatement(); - case 76 /* DebuggerKeyword */: + case 77 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 55 /* AtToken */: + case 56 /* AtToken */: return parseDeclaration(); - case 118 /* AsyncKeyword */: - case 107 /* InterfaceKeyword */: - case 134 /* TypeKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: - case 122 /* DeclareKeyword */: - case 74 /* ConstKeyword */: - case 81 /* EnumKeyword */: - case 82 /* ExportKeyword */: - case 89 /* ImportKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 115 /* AbstractKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: - case 137 /* GlobalKeyword */: + case 119 /* AsyncKeyword */: + case 108 /* InterfaceKeyword */: + case 136 /* TypeKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 123 /* DeclareKeyword */: + case 75 /* ConstKeyword */: + case 82 /* EnumKeyword */: + case 83 /* ExportKeyword */: + case 90 /* ImportKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 116 /* AbstractKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: + case 139 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -16630,33 +18140,33 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token()) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: return parseVariableStatement(fullStart, decorators, modifiers); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassDeclaration(fullStart, decorators, modifiers); - case 107 /* InterfaceKeyword */: + case 108 /* InterfaceKeyword */: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 134 /* TypeKeyword */: + case 136 /* TypeKeyword */: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 81 /* EnumKeyword */: + case 82 /* EnumKeyword */: return parseEnumDeclaration(fullStart, decorators, modifiers); - case 137 /* GlobalKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: + case 139 /* GlobalKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: return parseModuleDeclaration(fullStart, decorators, modifiers); - case 89 /* ImportKeyword */: + case 90 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 82 /* ExportKeyword */: + case 83 /* ExportKeyword */: nextToken(); switch (token()) { - case 77 /* DefaultKeyword */: - case 56 /* EqualsToken */: + case 78 /* DefaultKeyword */: + case 57 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); - case 116 /* AsKeyword */: + case 117 /* AsKeyword */: return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); @@ -16665,7 +18175,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(239 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(244 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; node.modifiers = modifiers; @@ -16678,7 +18188,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 16 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -16686,24 +18196,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 24 /* CommaToken */) { - return createNode(193 /* OmittedExpression */); + if (token() === 25 /* CommaToken */) { + return createNode(198 /* OmittedExpression */); } - var node = createNode(169 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + var node = createNode(174 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(169 /* BindingElement */); + var node = createNode(174 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 55 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -16711,33 +18222,33 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(167 /* ObjectBindingPattern */); - parseExpected(15 /* OpenBraceToken */); + var node = createNode(172 /* ObjectBindingPattern */); + parseExpected(16 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(168 /* ArrayBindingPattern */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(173 /* ArrayBindingPattern */); + parseExpected(20 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); + return token() === 16 /* OpenBraceToken */ || token() === 20 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(218 /* VariableDeclaration */); + var node = createNode(223 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { @@ -16746,14 +18257,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(219 /* VariableDeclarationList */); + var node = createNode(224 /* VariableDeclarationList */); switch (token()) { - case 102 /* VarKeyword */: + case 103 /* VarKeyword */: break; - case 108 /* LetKeyword */: + case 109 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 74 /* ConstKeyword */: + case 75 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -16769,7 +18280,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 140 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -16781,10 +18292,10 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 19 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(200 /* VariableStatement */, fullStart); + var node = createNode(205 /* VariableStatement */, fullStart); node.decorators = decorators; node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -16792,29 +18303,29 @@ var ts; return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(220 /* FunctionDeclaration */, fullStart); + var node = createNode(225 /* FunctionDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(87 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + parseExpected(88 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; var isAsync = ts.hasModifier(node, 256 /* Async */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(148 /* Constructor */, pos); + var node = createNode(150 /* Constructor */, pos); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(121 /* ConstructorKeyword */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + parseExpected(122 /* ConstructorKeyword */); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(147 /* MethodDeclaration */, fullStart); + var method = createNode(149 /* MethodDeclaration */, fullStart); method.decorators = decorators; method.modifiers = modifiers; method.asteriskToken = asteriskToken; @@ -16822,12 +18333,12 @@ var ts; method.questionToken = questionToken; var isGenerator = !!asteriskToken; var isAsync = ts.hasModifier(method, 256 /* Async */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(145 /* PropertyDeclaration */, fullStart); + var property = createNode(147 /* PropertyDeclaration */, fullStart); property.decorators = decorators; property.modifiers = modifiers; property.name = name; @@ -16844,17 +18355,17 @@ var ts; // The checker may still error in the static case to explicitly disallow the yield expression. property.initializer = ts.hasModifier(property, 32 /* Static */) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(65536 /* YieldContext */ | 32768 /* DisallowInContext */, parseNonParameterInitializer); + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (asteriskToken || token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -16869,17 +18380,17 @@ var ts; node.decorators = decorators; node.modifiers = modifiers; node.name = parsePropertyName(); - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: return true; default: return false; @@ -16887,7 +18398,7 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55 /* AtToken */) { + if (token() === 56 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -16904,7 +18415,7 @@ var ts; } nextToken(); } - if (token() === 37 /* AsteriskToken */) { + if (token() === 38 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -16914,23 +18425,23 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 131 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 133 /* SetKeyword */ || idToken === 124 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 17 /* OpenParenToken */: // Method declaration - case 25 /* LessThanToken */: // Generic Method declaration - case 54 /* ColonToken */: // Type Annotation for declaration - case 56 /* EqualsToken */: // Initializer for declaration - case 53 /* QuestionToken */: + case 18 /* OpenParenToken */: // Method declaration + case 26 /* LessThanToken */: // Generic Method declaration + case 55 /* ColonToken */: // Type Annotation for declaration + case 57 /* EqualsToken */: // Initializer for declaration + case 54 /* QuestionToken */: return true; default: // Covers @@ -16947,10 +18458,10 @@ var ts; var decorators; while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(55 /* AtToken */)) { + if (!parseOptional(56 /* AtToken */)) { break; } - var decorator = createNode(143 /* Decorator */, decoratorStart); + var decorator = createNode(145 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); if (!decorators) { @@ -16977,7 +18488,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 75 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -17004,7 +18515,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -17015,8 +18526,8 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23 /* SemicolonToken */) { - var result = createNode(198 /* SemicolonClassElement */); + if (token() === 24 /* SemicolonToken */) { + var result = createNode(203 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -17027,7 +18538,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121 /* ConstructorKeyword */) { + if (token() === 122 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -17038,14 +18549,14 @@ var ts; if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 37 /* AsteriskToken */ || - token() === 19 /* OpenBracketToken */) { + token() === 38 /* AsteriskToken */ || + token() === 20 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_10 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, /*questionToken*/ undefined); + var name_13 = createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, /*questionToken*/ undefined); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); @@ -17054,24 +18565,24 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 192 /* ClassExpression */); + /*modifiers*/ undefined, 197 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 221 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(73 /* ClassKeyword */); + parseExpected(74 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ true); - if (parseExpected(15 /* OpenBraceToken */)) { + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(16 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -17089,19 +18600,19 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 107 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause) { + function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(20 /* HeritageClauses */, parseHeritageClause); + return parseList(21 /* HeritageClauses */, parseHeritageClause); } return undefined; } function parseHeritageClause() { - if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { - var node = createNode(251 /* HeritageClause */); + if (token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */) { + var node = createNode(255 /* HeritageClause */); node.token = token(); nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -17110,61 +18621,61 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(194 /* ExpressionWithTypeArguments */); + var node = createNode(199 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25 /* LessThanToken */) { - node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (token() === 26 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(222 /* InterfaceDeclaration */, fullStart); + var node = createNode(227 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(107 /* InterfaceKeyword */); + parseExpected(108 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(223 /* TypeAliasDeclaration */, fullStart); + var node = createNode(228 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(134 /* TypeKeyword */); + parseExpected(136 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(255 /* EnumMember */, scanner.getStartPos()); + var node = createNode(260 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(224 /* EnumDeclaration */, fullStart); + var node = createNode(229 /* EnumDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(81 /* EnumKeyword */); + parseExpected(82 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(15 /* OpenBraceToken */)) { + if (parseExpected(16 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -17172,10 +18683,10 @@ var ts; return addJSDocComment(finishNode(node)); } function parseModuleBlock() { - var node = createNode(226 /* ModuleBlock */, scanner.getStartPos()); - if (parseExpected(15 /* OpenBraceToken */)) { + var node = createNode(231 /* ModuleBlock */, scanner.getStartPos()); + if (parseExpected(16 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -17183,7 +18694,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(225 /* ModuleDeclaration */, fullStart); + var node = createNode(230 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; @@ -17191,16 +18702,16 @@ var ts; node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(21 /* DotToken */) + node.body = parseOptional(22 /* DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(225 /* ModuleDeclaration */, fullStart); + var node = createNode(230 /* ModuleDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (token() === 137 /* GlobalKeyword */) { + if (token() === 139 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -17208,7 +18719,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -17218,15 +18729,15 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = 0; - if (token() === 137 /* GlobalKeyword */) { + if (token() === 139 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } - else if (parseOptional(126 /* NamespaceKeyword */)) { + else if (parseOptional(128 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(125 /* ModuleKeyword */); + parseExpected(127 /* ModuleKeyword */); if (token() === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -17234,57 +18745,57 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 /* RequireKeyword */ && + return token() === 131 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 17 /* OpenParenToken */; + return nextToken() === 18 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 39 /* SlashToken */; + return nextToken() === 40 /* SlashToken */; } function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228 /* NamespaceExportDeclaration */, fullStart); + var exportDeclaration = createNode(233 /* NamespaceExportDeclaration */, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; - parseExpected(116 /* AsKeyword */); - parseExpected(126 /* NamespaceKeyword */); + parseExpected(117 /* AsKeyword */); + parseExpected(128 /* NamespaceKeyword */); exportDeclaration.name = parseIdentifier(); - parseExpected(23 /* SemicolonToken */); + parseSemicolon(); return finishNode(exportDeclaration); } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(89 /* ImportKeyword */); + parseExpected(90 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { + if (token() !== 25 /* CommaToken */ && token() !== 138 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(229 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(234 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); return addJSDocComment(finishNode(importEqualsDeclaration)); } } // Import statement - var importDeclaration = createNode(230 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(235 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; importDeclaration.modifiers = modifiers; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */) { + token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(136 /* FromKeyword */); + parseExpected(138 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -17297,7 +18808,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(231 /* ImportClause */, fullStart); + var importClause = createNode(236 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -17306,8 +18817,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + parseOptional(25 /* CommaToken */)) { + importClause.namedBindings = token() === 38 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(238 /* NamedImports */); } return finishNode(importClause); } @@ -17317,11 +18828,11 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(240 /* ExternalModuleReference */); - parseExpected(129 /* RequireKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(245 /* ExternalModuleReference */); + parseExpected(131 /* RequireKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { @@ -17340,9 +18851,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(232 /* NamespaceImport */); - parseExpected(37 /* AsteriskToken */); - parseExpected(116 /* AsKeyword */); + var namespaceImport = createNode(237 /* NamespaceImport */); + parseExpected(38 /* AsteriskToken */); + parseExpected(117 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -17355,14 +18866,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 233 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 238 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 16 /* OpenBraceToken */, 17 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(238 /* ExportSpecifier */); + return parseImportOrExportSpecifier(243 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(234 /* ImportSpecifier */); + return parseImportOrExportSpecifier(239 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -17376,9 +18887,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116 /* AsKeyword */) { + if (token() === 117 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(116 /* AsKeyword */); + parseExpected(117 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -17387,27 +18898,27 @@ var ts; else { node.name = identifierName; } - if (kind === 234 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 239 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(236 /* ExportDeclaration */, fullStart); + var node = createNode(241 /* ExportDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(37 /* AsteriskToken */)) { - parseExpected(136 /* FromKeyword */); + if (parseOptional(38 /* AsteriskToken */)) { + parseExpected(138 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(237 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(242 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(136 /* FromKeyword */); + if (token() === 138 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(138 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -17415,14 +18926,14 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(235 /* ExportAssignment */, fullStart); + var node = createNode(240 /* ExportAssignment */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(56 /* EqualsToken */)) { + if (parseOptional(57 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(77 /* DefaultKeyword */); + parseExpected(78 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -17497,10 +19008,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */ - || node.kind === 230 /* ImportDeclaration */ - || node.kind === 235 /* ExportAssignment */ - || node.kind === 236 /* ExportDeclaration */ + || node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */ + || node.kind === 235 /* ImportDeclaration */ + || node.kind === 240 /* ExportAssignment */ + || node.kind === 241 /* ExportDeclaration */ ? node : undefined; }); @@ -17524,16 +19035,17 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["TypeParameters"] = 17] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 18] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 19] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 20] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 21] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["JSDocFunctionParameters"] = 22] = "JSDocFunctionParameters"; - ParsingContext[ParsingContext["JSDocTypeArguments"] = 23] = "JSDocTypeArguments"; - ParsingContext[ParsingContext["JSDocRecordMembers"] = 24] = "JSDocRecordMembers"; - ParsingContext[ParsingContext["JSDocTupleTypes"] = 25] = "JSDocTupleTypes"; - ParsingContext[ParsingContext["Count"] = 26] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 23] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 24] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 25] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 26] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 27] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -17545,24 +19057,24 @@ var ts; (function (JSDocParser) { function isJSDocType() { switch (token()) { - case 37 /* AsteriskToken */: - case 53 /* QuestionToken */: - case 17 /* OpenParenToken */: - case 19 /* OpenBracketToken */: - case 49 /* ExclamationToken */: - case 15 /* OpenBraceToken */: - case 87 /* FunctionKeyword */: - case 22 /* DotDotDotToken */: - case 92 /* NewKeyword */: - case 97 /* ThisKeyword */: + case 38 /* AsteriskToken */: + case 54 /* QuestionToken */: + case 18 /* OpenParenToken */: + case 20 /* OpenBracketToken */: + case 50 /* ExclamationToken */: + case 16 /* OpenBraceToken */: + case 88 /* FunctionKeyword */: + case 23 /* DotDotDotToken */: + case 93 /* NewKeyword */: + case 98 /* ThisKeyword */: return true; } return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = createSourceFile("file.js", 2 /* Latest */, 1 /* JS */); + initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 5 /* Latest */, 1 /* JS */); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -17574,23 +19086,23 @@ var ts; // Parses out a JSDoc type expression. /* @internal */ function parseJSDocTypeExpression() { - var result = createNode(257 /* JSDocTypeExpression */, scanner.getTokenPos()); - parseExpected(15 /* OpenBraceToken */); + var result = createNode(262 /* JSDocTypeExpression */, scanner.getTokenPos()); + parseExpected(16 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47 /* BarToken */) { - var unionType = createNode(261 /* JSDocUnionType */, type.pos); + if (token() === 48 /* BarToken */) { + var unionType = createNode(266 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56 /* EqualsToken */) { - var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); + if (token() === 57 /* EqualsToken */) { + var optionalType = createNode(273 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -17600,21 +19112,21 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19 /* OpenBracketToken */) { - var arrayType = createNode(260 /* JSDocArrayType */, type.pos); + if (token() === 20 /* OpenBracketToken */) { + var arrayType = createNode(265 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token() === 53 /* QuestionToken */) { - var nullableType = createNode(263 /* JSDocNullableType */, type.pos); + else if (token() === 54 /* QuestionToken */) { + var nullableType = createNode(268 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49 /* ExclamationToken */) { - var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); + else if (token() === 50 /* ExclamationToken */) { + var nonNullableType = createNode(269 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -17627,94 +19139,95 @@ var ts; } function parseBasicTypeExpression() { switch (token()) { - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: return parseJSDocAllType(); - case 53 /* QuestionToken */: + case 54 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseJSDocUnionType(); - case 19 /* OpenBracketToken */: + case 20 /* OpenBracketToken */: return parseJSDocTupleType(); - case 49 /* ExclamationToken */: + case 50 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseJSDocRecordType(); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 22 /* DotDotDotToken */: + case 23 /* DotDotDotToken */: return parseJSDocVariadicType(); - case 92 /* NewKeyword */: + case 93 /* NewKeyword */: return parseJSDocConstructorType(); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: return parseJSDocThisType(); - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 94 /* NullKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: return parseTokenNode(); case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(272 /* JSDocThisType */); + var result = createNode(277 /* JSDocThisType */); nextToken(); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(271 /* JSDocConstructorType */); + var result = createNode(276 /* JSDocConstructorType */); nextToken(); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(270 /* JSDocVariadicType */); + var result = createNode(275 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(269 /* JSDocFunctionType */); + var result = createNode(274 /* JSDocFunctionType */); nextToken(); - parseExpected(17 /* OpenParenToken */); - result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); + parseExpected(18 /* OpenParenToken */); + result.parameters = parseDelimitedList(23 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); - parseExpected(18 /* CloseParenToken */); - if (token() === 54 /* ColonToken */) { + parseExpected(19 /* CloseParenToken */); + if (token() === 55 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(142 /* Parameter */); + var parameter = createNode(144 /* Parameter */); parameter.type = parseJSDocType(); - if (parseOptional(56 /* EqualsToken */)) { - parameter.questionToken = createNode(56 /* EqualsToken */); + if (parseOptional(57 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? + parameter.questionToken = createNode(57 /* EqualsToken */); } return finishNode(parameter); } function parseJSDocTypeReference() { - var result = createNode(267 /* JSDocTypeReference */); + var result = createNode(272 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { - while (parseOptional(21 /* DotToken */)) { - if (token() === 25 /* LessThanToken */) { + while (parseOptional(22 /* DotToken */)) { + if (token() === 26 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -17728,10 +19241,10 @@ var ts; function parseTypeArguments() { // Move past the < nextToken(); - var typeArguments = parseDelimitedList(23 /* JSDocTypeArguments */, parseJSDocType); + var typeArguments = parseDelimitedList(24 /* JSDocTypeArguments */, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); return typeArguments; } function checkForEmptyTypeArgumentList(typeArguments) { @@ -17742,28 +19255,28 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(139 /* QualifiedName */, left.pos); + var result = createNode(141 /* QualifiedName */, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(265 /* JSDocRecordType */); + var result = createNode(270 /* JSDocRecordType */); result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(264 /* JSDocNonNullableType */); + var result = createNode(269 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(262 /* JSDocTupleType */); + var result = createNode(267 /* JSDocTupleType */); nextToken(); - result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); + result.types = parseDelimitedList(26 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(result); } function checkForTrailingComma(list) { @@ -17773,28 +19286,28 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(261 /* JSDocUnionType */); + var result = createNode(266 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(result); } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(47 /* BarToken */)) { + while (parseOptional(48 /* BarToken */)) { types.push(parseJSDocType()); } types.end = scanner.getStartPos(); return types; } function parseJSDocAllType() { - var result = createNode(258 /* JSDocAllType */); + var result = createNode(263 /* JSDocAllType */); nextToken(); return finishNode(result); } function parseJSDocLiteralType() { - var result = createNode(282 /* JSDocLiteralType */); + var result = createNode(288 /* JSDocLiteralType */); result.literal = parseLiteralTypeNode(); return finishNode(result); } @@ -17811,23 +19324,23 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 24 /* CommaToken */ || - token() === 16 /* CloseBraceToken */ || - token() === 18 /* CloseParenToken */ || - token() === 27 /* GreaterThanToken */ || - token() === 56 /* EqualsToken */ || - token() === 47 /* BarToken */) { - var result = createNode(259 /* JSDocUnknownType */, pos); + if (token() === 25 /* CommaToken */ || + token() === 17 /* CloseBraceToken */ || + token() === 19 /* CloseParenToken */ || + token() === 28 /* GreaterThanToken */ || + token() === 57 /* EqualsToken */ || + token() === 48 /* BarToken */) { + var result = createNode(264 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(263 /* JSDocNullableType */, pos); + var result = createNode(268 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -17892,11 +19405,12 @@ var ts; } if (token() === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; + indent = 0; nextJSDocToken(); } while (token() !== 1 /* EndOfFileToken */) { switch (token()) { - case 55 /* AtToken */: + case 56 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); parseTag(indent); @@ -17917,9 +19431,9 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */) { + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line state = 2 /* SavingComments */; pushComment(asterisk); @@ -17930,7 +19444,7 @@ var ts; indent += asterisk.length; } break; - case 69 /* Identifier */: + case 70 /* Identifier */: // Anything else is doc comment text. We just save it. Because it // wasn't a tag, we can no longer parse a tag on this line until we hit the next // line break. @@ -17940,7 +19454,10 @@ var ts; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -17948,6 +19465,8 @@ var ts; case 1 /* EndOfFileToken */: break; default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } @@ -17980,7 +19499,7 @@ var ts; content.charCodeAt(start + 3) !== 42 /* asterisk */; } function createJSDocComment() { - var result = createNode(273 /* JSDocComment */, start); + var result = createNode(278 /* JSDocComment */, start); result.tags = tags; result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -17991,8 +19510,8 @@ var ts; } } function parseTag(indent) { - ts.Debug.assert(token() === 55 /* AtToken */); - var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); + ts.Debug.assert(token() === 56 /* AtToken */); + var atToken = createNode(56 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18003,6 +19522,9 @@ var ts; var tag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -18044,7 +19566,7 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 55 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + while (token() !== 56 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { switch (token()) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { @@ -18053,7 +19575,7 @@ var ts; } indent = 0; break; - case 55 /* AtToken */: + case 56 /* AtToken */: // Done break; case 5 /* WhitespaceTrivia */: @@ -18069,7 +19591,7 @@ var ts; indent += whitespace.length; } break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -18082,7 +19604,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 55 /* AtToken */) { + if (token() === 56 /* AtToken */) { // Done break; } @@ -18093,7 +19615,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(274 /* JSDocTag */, atToken.pos); + var result = createNode(279 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -18111,7 +19633,7 @@ var ts; function tryParseTypeExpression() { return tryParse(function () { skipWhitespace(); - if (token() !== 15 /* OpenBraceToken */) { + if (token() !== 16 /* OpenBraceToken */) { return undefined; } return parseJSDocTypeExpression(); @@ -18123,15 +19645,15 @@ var ts; var name; var isBracketed; // Looking for something like '[foo]' or 'foo' - if (parseOptionalToken(19 /* OpenBracketToken */)) { + if (parseOptionalToken(20 /* OpenBracketToken */)) { name = parseJSDocIdentifierName(); skipWhitespace(); isBracketed = true; // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(56 /* EqualsToken */)) { + if (parseOptionalToken(57 /* EqualsToken */)) { parseExpression(); } - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); } else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); @@ -18150,7 +19672,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(275 /* JSDocParameterTag */, atToken.pos); + var result = createNode(281 /* JSDocParameterTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -18161,20 +19683,20 @@ var ts; return finishNode(result); } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 276 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(276 /* JSDocReturnTag */, atToken.pos); + var result = createNode(282 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 277 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 283 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(277 /* JSDocTypeTag */, atToken.pos); + var result = createNode(283 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -18189,28 +19711,43 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(280 /* JSDocPropertyTag */, atToken.pos); + var result = createNode(286 /* JSDocPropertyTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.name = name; result.typeExpression = typeExpression; return finishNode(result); } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(280 /* JSDocAugmentsTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(279 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(285 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (rightNode.kind !== 70 /* Identifier */) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); if (typeExpression) { - if (typeExpression.type.kind === 267 /* JSDocTypeReference */) { + if (typeExpression.type.kind === 272 /* JSDocTypeReference */) { var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 69 /* Identifier */) { - var name_11 = jsDocTypeReference.name; - if (name_11.text === "Object") { + if (jsDocTypeReference.name.kind === 70 /* Identifier */) { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -18224,7 +19761,7 @@ var ts; } return finishNode(typedefTag); function scanChildTags() { - var jsDocTypeLiteral = createNode(281 /* JSDocTypeLiteral */, scanner.getStartPos()); + var jsDocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, scanner.getStartPos()); var resumePos = scanner.getStartPos(); var canParseTag = true; var seenAsterisk = false; @@ -18232,7 +19769,7 @@ var ts; while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); switch (token()) { - case 55 /* AtToken */: + case 56 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); if (!parentTagTerminated) { @@ -18246,13 +19783,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 69 /* Identifier */: + case 70 /* Identifier */: canParseTag = false; case 1 /* EndOfFileToken */: break; @@ -18261,10 +19798,25 @@ var ts; scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(22 /* DotToken */)) { + var jsDocNamespaceNode = createNode(230 /* ModuleDeclaration */, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); + return jsDocNamespaceNode; + } + if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55 /* AtToken */); - var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); + ts.Debug.assert(token() === 56 /* AtToken */); + var atToken = createNode(56 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18282,33 +19834,37 @@ var ts; return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } var propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = []; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + // Error parsing property tag + return false; } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 278 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 284 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } // Type parameter list looks like '@template T,U,V' var typeParameters = createNodeArray(); while (true) { - var name_12 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_12) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141 /* TypeParameter */, name_12.pos); - typeParameter.name = name_12; + var typeParameter = createNode(143 /* TypeParameter */, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24 /* CommaToken */) { + if (token() === 25 /* CommaToken */) { nextJSDocToken(); skipWhitespace(); } @@ -18316,7 +19872,7 @@ var ts; break; } } - var result = createNode(278 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(284 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -18337,7 +19893,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(69 /* Identifier */, pos); + var result = createNode(70 /* Identifier */, pos); result.text = content.substring(pos, end); finishNode(result, end); nextJSDocToken(); @@ -18443,8 +19999,8 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); } @@ -18455,8 +20011,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += 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); } } @@ -18465,7 +20021,7 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 69 /* Identifier */: + case 70 /* Identifier */: return true; } return false; @@ -18593,8 +20149,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_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -18827,25 +20383,25 @@ var ts; /* @internal */ var ts; (function (ts) { + var ModuleInstanceState; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); - var ModuleInstanceState = ts.ModuleInstanceState; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 222 /* InterfaceDeclaration */ || node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 228 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { + else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } - else if (node.kind === 226 /* ModuleBlock */) { + else if (node.kind === 231 /* ModuleBlock */) { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -18864,10 +20420,13 @@ var ts; }); return state_1; } - else if (node.kind === 225 /* ModuleDeclaration */) { + else if (node.kind === 230 /* ModuleDeclaration */) { var body = node.body; return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } + else if (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } else { return 1 /* Instantiated */; } @@ -18895,6 +20454,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +20487,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +20502,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +20532,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -18991,7 +20561,7 @@ var ts; if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 225 /* ModuleDeclaration */)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230 /* ModuleDeclaration */)) { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } @@ -19004,10 +20574,10 @@ var ts; if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -19016,21 +20586,21 @@ var ts; return node.name.text; } switch (node.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: return "__constructor"; - case 156 /* FunctionType */: - case 151 /* CallSignature */: + case 158 /* FunctionType */: + case 153 /* CallSignature */: return "__call"; - case 157 /* ConstructorType */: - case 152 /* ConstructSignature */: + case 159 /* ConstructorType */: + case 154 /* ConstructSignature */: return "__new"; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return "__index"; - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return "__export"; - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2 /* ModuleExports */: // module.exports = ... @@ -19045,25 +20615,25 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + case 226 /* ClassDeclaration */: return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; - case 269 /* JSDocFunctionType */: + case 274 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 142 /* Parameter */: + case 144 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 274 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode && parentNode.kind === 205 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { + if (nameIdentifier.kind === 70 /* Identifier */) { nameFromParentNode = nameIdentifier.text; } } @@ -19134,11 +20704,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 240 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19154,7 +20737,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 238 /* ExportSpecifier */ || (node.kind === 229 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 243 /* ExportSpecifier */ || (node.kind === 234 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -19177,7 +20760,11 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) { + var isJSDocTypedefInJSDocNamespace = node.kind === 285 /* JSDocTypedefTag */ && + node.name && + node.name.kind === 70 /* Identifier */ && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); @@ -19235,15 +20822,15 @@ var ts; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !!ts.getImmediatelyInvokedFunctionExpression(node); - // An IIFE is considered part of the containing control flow. Return statements behave + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19254,14 +20841,13 @@ var ts; hasExplicitReturn = false; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) - // Reset all emit helper flags on node (for incremental scenarios) - node.flags &= ~32128 /* ReachabilityAndEmitFlags */; + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { node.flags |= 128 /* HasImplicitReturn */; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 256 /* SourceFile */) { + if (node.kind === 261 /* SourceFile */) { node.flags |= emitFlags; } if (isIIFE) { @@ -19296,6 +20882,7 @@ var ts; skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -19304,104 +20891,127 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } function bindChildrenWorker(node) { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - ts.forEach(node.jsDocComments, bind); + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + ts.forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - ts.forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: bindWhileStatement(node); break; - case 204 /* DoStatement */: + case 209 /* DoStatement */: bindDoStatement(node); break; - case 206 /* ForStatement */: + case 211 /* ForStatement */: bindForStatement(node); break; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 203 /* IfStatement */: + case 208 /* IfStatement */: bindIfStatement(node); break; - case 211 /* ReturnStatement */: - case 215 /* ThrowStatement */: + case 216 /* ReturnStatement */: + case 220 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 216 /* TryStatement */: + case 221 /* TryStatement */: bindTryStatement(node); break; - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: bindSwitchStatement(node); break; - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: bindCaseBlock(node); break; - case 249 /* CaseClause */: + case 253 /* CaseClause */: bindCaseClause(node); break; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: bindLabeledStatement(node); break; - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 174 /* CallExpression */: + case 179 /* CallExpression */: bindCallExpressionFlow(node); break; default: - ts.forEachChild(node, bind); + bindEachChild(node); break; } } function isNarrowingExpression(expr) { switch (expr.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: + case 177 /* PropertyAccessExpression */: return isNarrowableReference(expr); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return hasNarrowableArgument(expr); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 185 /* PrefixUnaryExpression */: - return expr.operator === 49 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 190 /* PrefixUnaryExpression */: + return expr.operator === 50 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 70 /* Identifier */ || + expr.kind === 98 /* ThisKeyword */ || + expr.kind === 177 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -19412,41 +21022,41 @@ var ts; } } } - if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + if (expr.expression.kind === 177 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 187 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return isNarrowableReference(expr.left); - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -19466,7 +21076,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -19481,8 +21091,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 99 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 84 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 100 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 85 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -19516,6 +21126,14 @@ var ts; node: node }; } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256 /* ArrayMutation */, + antecedent: antecedent, + node: node + }; + } function finishFlowLabel(flow) { var antecedents = flow.antecedents; if (!antecedents) { @@ -19529,34 +21147,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 203 /* IfStatement */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: + case 208 /* IfStatement */: + case 210 /* WhileStatement */: + case 209 /* DoStatement */: return parent.expression === node; - case 206 /* ForStatement */: - case 188 /* ConditionalExpression */: + case 211 /* ForStatement */: + case 193 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 178 /* ParenthesizedExpression */) { + if (node.kind === 183 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 185 /* PrefixUnaryExpression */ && node.operator === 49 /* ExclamationToken */) { + else if (node.kind === 190 /* PrefixUnaryExpression */ && node.operator === 50 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 187 /* BinaryExpression */ && (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 52 /* BarBarToken */); + return node.kind === 192 /* BinaryExpression */ && (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 53 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 178 /* ParenthesizedExpression */ || - node.parent.kind === 185 /* PrefixUnaryExpression */ && - node.parent.operator === 49 /* ExclamationToken */) { + while (node.parent.kind === 183 /* ParenthesizedExpression */ || + node.parent.kind === 190 /* PrefixUnaryExpression */ && + node.parent.operator === 50 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -19597,8 +21215,13 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var preConditionLabel = createBranchLabel(); - var postDoLabel = createBranchLabel(); + var enclosingLabeledStatement = node.parent.kind === 219 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -19629,7 +21252,7 @@ var ts; bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 219 /* VariableDeclarationList */) { + if (node.initializer.kind !== 224 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -19651,7 +21274,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 211 /* ReturnStatement */) { + if (node.kind === 216 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -19670,8 +21293,8 @@ var ts; } return undefined; } - function bindbreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 210 /* BreakStatement */ ? breakTarget : continueTarget; + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 215 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -19683,29 +21306,50 @@ var ts; var activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node) { - var postFinallyLabel = createBranchLabel(); + var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; // TODO: Every statement in try block is potentially an exit point! bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); } - currentFlow = finishFlowLabel(postFinallyLabel); } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19716,7 +21360,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254 /* 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; @@ -19728,6 +21372,8 @@ var ts; currentFlow = finishFlowLabel(postSwitchLabel); } function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; var clauses = node.clauses; var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { @@ -19747,13 +21393,15 @@ var ts; errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { var saveCurrentFlow = currentFlow; currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - ts.forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name, breakTarget, continueTarget) { var activeLabel = { @@ -19779,11 +21427,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== 209 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node) { - if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */) { + if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -19794,10 +21445,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 170 /* ArrayLiteralExpression */) { + else if (node.kind === 175 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 191 /* SpreadElementExpression */) { + if (e.kind === 196 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -19805,21 +21456,24 @@ var ts; } } } - else if (node.kind === 171 /* ObjectLiteralExpression */) { + else if (node.kind === 176 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 253 /* PropertyAssignment */) { + if (p.kind === 257 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 254 /* ShorthandPropertyAssignment */) { + else if (p.kind === 258 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } + else if (p.kind === 259 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } } } } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -19830,30 +21484,30 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 49 /* ExclamationToken */) { + if (node.operator === 50 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - ts.forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + bindEachChild(node); + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + bindEachChild(node); + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 51 /* AmpersandAmpersandToken */ || operator === 52 /* BarBarToken */) { + if (operator === 52 /* AmpersandAmpersandToken */ || operator === 53 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -19864,15 +21518,21 @@ var ts; } } else { - ts.forEachChild(node, bind); - if (operator === 56 /* EqualsToken */ && !ts.isAssignmentTarget(node)) { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === 57 /* EqualsToken */ && node.left.kind === 178 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.expression.kind === 172 /* PropertyAccessExpression */) { + bindEachChild(node); + if (node.expression.kind === 177 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -19882,9 +21542,11 @@ var ts; var postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -19902,8 +21564,8 @@ var ts; } } function bindVariableDeclarationFlow(node) { - ts.forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === 207 /* ForInStatement */ || node.parent.parent.kind === 208 /* ForOfStatement */) { + bindEachChild(node); + if (node.initializer || node.parent.parent.kind === 212 /* ForInStatement */ || node.parent.parent.kind === 213 /* ForOfStatement */) { bindInitializedVariableFlow(node); } } @@ -19912,62 +21574,72 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 178 /* ParenthesizedExpression */) { + while (expr.kind === 183 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 179 /* FunctionExpression */ || expr.kind === 180 /* ArrowFunction */) { - ts.forEach(node.typeArguments, bind); - ts.forEach(node.arguments, bind); + if (expr.kind === 184 /* FunctionExpression */ || expr.kind === 185 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - ts.forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === 177 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } function getContainerFlags(node) { switch (node.kind) { - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 265 /* JSDocRecordType */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 161 /* TypeLiteral */: + case 287 /* JSDocTypeLiteral */: + case 270 /* JSDocRecordType */: return 1 /* IsContainer */; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 269 /* JSDocFunctionType */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 274 /* JSDocFunctionType */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 170 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 256 /* SourceFile */: + case 261 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 148 /* Constructor */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 149 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + case 150 /* Constructor */: + case 225 /* FunctionDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 252 /* CatchClause */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 227 /* CaseBlock */: + case 256 /* CatchClause */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 232 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 199 /* Block */: + case 204 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -20004,41 +21676,42 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 159 /* TypeLiteral */: - case 171 /* ObjectLiteralExpression */: - case 222 /* InterfaceDeclaration */: - case 265 /* JSDocRecordType */: - case 281 /* JSDocTypeLiteral */: + case 161 /* TypeLiteral */: + case 176 /* ObjectLiteralExpression */: + case 227 /* InterfaceDeclaration */: + case 270 /* JSDocRecordType */: + case 287 /* JSDocTypeLiteral */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 269 /* JSDocFunctionType */: - case 223 /* TypeAliasDeclaration */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 274 /* JSDocFunctionType */: + case 228 /* TypeAliasDeclaration */: + case 170 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -20059,11 +21732,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { + var body = node.kind === 261 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 261 /* SourceFile */ || body.kind === 231 /* 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 */) { + if (stat.kind === 241 /* ExportDeclaration */ || stat.kind === 240 /* ExportAssignment */) { return true; } } @@ -20156,7 +21829,7 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.name.kind !== 69 /* Identifier */) { + if (prop.kind === 259 /* SpreadAssignment */ || prop.name.kind !== 70 /* Identifier */) { continue; } var identifier = prop.name; @@ -20168,7 +21841,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */ || prop.kind === 147 /* MethodDeclaration */ + var currentKind = prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */ || prop.kind === 149 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen[identifier.text]; @@ -20190,10 +21863,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -20214,8 +21887,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 107 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 115 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file @@ -20251,7 +21924,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 69 /* Identifier */) { + if (inStrictMode && node.expression.kind === 70 /* Identifier */) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name var span_2 = ts.getErrorSpanForNode(file, node.expression); @@ -20259,11 +21932,11 @@ var ts; } } function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* Identifier */ && + return node.kind === 70 /* Identifier */ && (node.text === "eval" || node.text === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69 /* Identifier */) { + if (name && name.kind === 70 /* Identifier */) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message @@ -20302,10 +21975,10 @@ var ts; return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; } function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 256 /* SourceFile */ && - blockScopeContainer.kind !== 225 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 261 /* SourceFile */ && + blockScopeContainer.kind !== 230 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -20331,7 +22004,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -20371,7 +22044,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 138 /* LastToken */) { + if (node.kind > 140 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -20390,8 +22063,8 @@ var ts; } function updateStrictModeStatementList(statements) { if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -20412,18 +22085,29 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 254 /* ShorthandPropertyAssignment */)) { + case 70 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 285 /* JSDocTypedefTag */) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + break; + } + case 98 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 258 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } break; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: if (ts.isInJavaScriptFile(node)) { var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { @@ -20447,128 +22131,145 @@ var ts; } } return checkStrictModeBinaryExpression(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return checkStrictModeCatchClause(node); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return checkStrictModeWithStatement(node); - case 165 /* ThisType */: + case 167 /* ThisType */: seenThisKeyword = true; return; - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return checkTypePredicate(node); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 142 /* Parameter */: + case 144 /* Parameter */: return bindParameter(node); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: return bindVariableDeclarationOrBindingElement(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 266 /* JSDocRecordMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 271 /* JSDocRecordMember */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 280 /* JSDocPropertyTag */: + case 286 /* JSDocPropertyTag */: return bindJSDocProperty(node); - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 247 /* JsxSpreadAttribute */: - emitFlags |= 16384 /* HasJsxSpreadAttributes */; + case 259 /* SpreadAssignment */: + case 251 /* JsxSpreadAttribute */: + var root = container; + var hasRest = false; + while (root.parent) { + if (root.kind === 176 /* ObjectLiteralExpression */ && + root.parent.kind === 192 /* BinaryExpression */ && + root.parent.operatorToken.kind === 57 /* EqualsToken */ && + root.parent.left === root) { + hasRest = true; + break; + } + root = root.parent; + } return; - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 269 /* JSDocFunctionType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 274 /* JSDocFunctionType */: return bindFunctionOrConstructorType(node); - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 265 /* JSDocRecordType */: + case 161 /* TypeLiteral */: + case 170 /* MappedType */: + case 287 /* JSDocTypeLiteral */: + case 270 /* JSDocRecordType */: return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return bindFunctionExpression(node); - case 174 /* CallExpression */: + case 179 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 279 /* JSDocTypedefTag */: - case 223 /* TypeAliasDeclaration */: + case 285 /* JSDocTypedefTag */: + if (!node.fullName || node.fullName.kind === 70 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + case 228 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Imports and exports - case 229 /* ImportEqualsDeclaration */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return bindImportClause(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return bindExportDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return bindExportAssignment(node); - case 256 /* SourceFile */: + case 261 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 199 /* Block */: + case 204 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // Fall through - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); } } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 69 /* Identifier */) { + if (parameterName && parameterName.kind === 70 /* Identifier */) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 165 /* ThisType */) { + if (parameterName && parameterName.kind === 167 /* ThisType */) { seenThisKeyword = true; } bind(type); @@ -20588,27 +22289,30 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. + var flags = node.kind === 240 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 256 /* SourceFile */) { + if (node.parent.kind !== 261 /* SourceFile */) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -20634,7 +22338,9 @@ var ts; function setCommonJsModuleIndicator(node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } function bindExportsPropertyAssignment(node) { @@ -20651,12 +22357,12 @@ var ts; function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); // Declare a 'member' if the container is an ES5 class or ES6 constructor - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { + if (container.kind === 225 /* FunctionDeclaration */ || container.kind === 184 /* FunctionExpression */) { container.symbol.members = container.symbol.members || ts.createMap(); // It's acceptable for multiple 'this' assignments of the same identifier to occur declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } - else if (container.kind === 148 /* Constructor */) { + else if (container.kind === 150 /* Constructor */) { // this.foo assignment in a JavaScript class // Bind this property to the containing class var saveContainer = container; @@ -20699,15 +22405,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 1024 /* HasClassExtends */; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048 /* HasDecorators */; - } - } - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -20769,11 +22467,6 @@ var ts; } } function bindParameter(node) { - if (!ts.isDeclarationFile(file) && - !ts.isInAmbientContext(node) && - ts.nodeIsDecorated(node)) { - emitFlags |= (2048 /* HasDecorators */ | 4096 /* HasParamDecorators */); - } if (inStrictMode) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -20795,7 +22488,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } checkStrictModeFunctionName(node); @@ -20810,7 +22503,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } if (currentFlow) { @@ -20823,12 +22516,12 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048 /* HasDecorators */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20848,13 +22541,13 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 201 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 206 /* EmptyStatement */) || // report error on class declarations - node.kind === 221 /* ClassDeclaration */ || + node.kind === 226 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 225 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 230 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 224 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 229 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; // unreachable code is reported if @@ -20868,7 +22561,7 @@ var ts; // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 200 /* VariableStatement */ || + (node.kind !== 205 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -20888,52 +22581,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 225 /* ModuleDeclaration */: + case 180 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 230 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 142 /* Parameter */: + case 144 /* Parameter */: return computeParameter(node, subtreeFlags); - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 194 /* ExpressionWithTypeArguments */: + case 256 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 199 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 148 /* Constructor */: + case 150 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -20944,44 +22641,63 @@ var ts; var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */ + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537133909 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 95 /* SuperKeyword */: + case 96 /* SuperKeyword */: return true; - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 95 /* SuperKeyword */; + return expressionKind === 96 /* SuperKeyword */; } return false; } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 56 /* EqualsToken */ - && (leftKind === 171 /* ObjectLiteralExpression */ - || leftKind === 170 /* ArrayLiteralExpression */)) { - // Destructuring assignments are ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 256 /* DestructuringAssignment */; + if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 176 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 38 /* AsteriskAsteriskToken */ - || operatorTokenKind === 60 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES7 syntax. - transformFlags |= 48 /* AssertES7 */; + else if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 175 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 39 /* AsteriskAsteriskToken */ + || operatorTokenKind === 61 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20989,26 +22705,29 @@ var ts; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; - // If the parameter has a question token, then it is TypeScript syntax. - if (node.questionToken) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (modifierFlags & 92 /* ParameterPropertyModifier */) { - transformFlags |= 3 /* AssertTypeScript */ | 131072 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES6 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~538968917 /* ParameterExcludes */; + return transformFlags & ~536872257 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21018,17 +22737,17 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (expressionKind === 195 /* AsExpression */ - || expressionKind === 177 /* TypeAssertionExpression */) { + if (expressionKind === 200 /* AsExpression */ + || expressionKind === 182 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 256 /* DestructuringAssignment */) { - transformFlags |= 256 /* DestructuringAssignment */; + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -21039,47 +22758,49 @@ var ts; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES6 */; + transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - // An exported declaration may be TypeScript syntax. - if ((subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) - || (modifierFlags & 1 /* Export */)) { + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537590613 /* ClassExcludes */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) { + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537590613 /* ClassExcludes */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 83 /* ExtendsKeyword */: + case 84 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 106 /* ImplementsKeyword */: + case 107 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -21088,65 +22809,85 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537920833 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var body = node.body; - if (body === undefined) { - // An overload constructor is TypeScript syntax. + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* ConstructorExcludes */; + return transformFlags & ~601015617 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - var typeParameters = node.typeParameters; - var asteriskToken = node.asteriskToken; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || typeParameters - || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) - || (subtreeFlags & 2048 /* ContainsDecorators */)) { + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) - || (subtreeFlags & 2048 /* ContainsDecorators */)) { + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -21154,88 +22895,113 @@ var ts; // If the PropertyDeclaration has an initializer, we need to inform its ancestor // so that it handle the transformation. if (node.initializer) { - transformFlags |= 4096 /* ContainsPropertyInitializer */; + transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - var asteriskToken = node.asteriskToken; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & 1 /* Export */) { - transformFlags |= 3 /* AssertTypeScript */ | 192 /* AssertES6 */; - } - // If a FunctionDeclaration is async, then it is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550726485 /* FunctionExcludes */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var asteriskToken = node.asteriskToken; - // An async function expression is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550726485 /* FunctionExcludes */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; - var modifierFlags = ts.getModifierFlags(node); - // An async arrow function is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550710101 /* ArrowFunctionExcludes */; + return transformFlags & ~601249089 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21243,21 +23009,25 @@ var ts; var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 95 /* SuperKeyword */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + if (expressionKind === 96 /* SuperKeyword */) { + transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - var nameKind = node.name.kind; - // A VariableDeclaration with a binding pattern is ES6 syntax. - if (nameKind === 167 /* ObjectBindingPattern */ || nameKind === 168 /* ArrayBindingPattern */) { - transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -21269,26 +23039,22 @@ var ts; } else { transformFlags = subtreeFlags; - // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & 1 /* Export */) { - transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; - } - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES6 */; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21297,18 +23063,18 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // If the expression of an expression statement is a destructuring assignment, // then we treat the statement as ES6 so that we can indicate that we do not // need to hold on to the right-hand side. - if (node.expression.transformFlags & 256 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES6 */; + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -21317,111 +23083,116 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546335573 /* ModuleExcludes */; + return transformFlags & ~574674241 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES6 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~538968917 /* VariableDeclarationListExcludes */; + return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536871765 /* NodeExcludes */; + var excludeFlags = 536872257 /* NodeExcludes */; switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 115 /* AbstractKeyword */: - case 122 /* DeclareKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 184 /* AwaitExpression */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: - case 196 /* NonNullExpression */: - case 128 /* ReadonlyKeyword */: + case 119 /* AsyncKeyword */: + case 189 /* AwaitExpression */: + // async/await is ES2017 syntax + transformFlags |= 16 /* AssertES2017 */; + break; + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 116 /* AbstractKeyword */: + case 123 /* DeclareKeyword */: + case 75 /* ConstKeyword */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: + case 201 /* NonNullExpression */: + case 130 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - case 244 /* JsxText */: - case 245 /* JsxClosingElement */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - case 248 /* JsxExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 249 /* JsxClosingElement */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: + case 252 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 12 /* AssertJsx */; + transformFlags |= 4 /* AssertJsx */; break; - case 82 /* ExportKeyword */: - // This node is both ES6 and TypeScript syntax. - transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; - break; - case 77 /* DefaultKeyword */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - case 189 /* TemplateExpression */: - case 176 /* TaggedTemplateExpression */: - case 254 /* ShorthandPropertyAssignment */: - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: + // for-of might be ESNext if it has a rest destructuring + transformFlags |= 8 /* AssertESNext */; + // FALLTHROUGH + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: + case 194 /* TemplateExpression */: + case 181 /* TaggedTemplateExpression */: + case 258 /* ShorthandPropertyAssignment */: + case 114 /* StaticKeyword */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 4194304 /* ContainsYield */; + transformFlags |= 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; break; - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 141 /* TypeParameter */: - case 144 /* PropertySignature */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 154 /* TypePredicate */: - case 155 /* TypeReference */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 143 /* TypeParameter */: + case 146 /* PropertySignature */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 156 /* TypePredicate */: + case 157 /* TypeReference */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 160 /* TypeQuery */: + case 161 /* TypeLiteral */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 167 /* ThisType */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 171 /* LiteralType */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -21430,76 +23201,877 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 191 /* SpreadElementExpression */: - // This node is ES6 syntax, but is handled by a containing node. - transformFlags |= 262144 /* ContainsSpreadElementExpression */; + case 196 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 95 /* SuperKeyword */: + case 259 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 96 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + case 172 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 143 /* Decorator */: + case 173 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 174 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 145 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 2048 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 171 /* ObjectLiteralExpression */: - excludeFlags = 537430869 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + case 176 /* ObjectLiteralExpression */: + excludeFlags = 540087617 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; } break; - case 170 /* ArrayLiteralExpression */: - case 175 /* NewExpression */: - excludeFlags = 537133909 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */) { - // If the this node contains a SpreadElementExpression, then it is an ES6 + case 175 /* ArrayLiteralExpression */: + case 180 /* NewExpression */: + excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 // node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } break; - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 256 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES6 */; + case 261 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 211 /* ReturnStatement */: - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + case 216 /* ReturnStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 175 /* ArrayLiteralExpression */: + return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + case 230 /* ModuleDeclaration */: + return 574674241 /* ModuleExcludes */; + case 144 /* Parameter */: + return 536872257 /* ParameterExcludes */; + case 185 /* ArrowFunction */: + return 601249089 /* ArrowFunctionExcludes */; + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + return 601281857 /* FunctionExcludes */; + case 224 /* VariableDeclarationList */: + return 546309441 /* VariableDeclarationListExcludes */; + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return 539358529 /* ClassExcludes */; + case 150 /* Constructor */: + return 601015617 /* ConstructorExcludes */; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return 601015617 /* MethodOrAccessorExcludes */; + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 143 /* TypeParameter */: + case 146 /* PropertySignature */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 176 /* ObjectLiteralExpression */: + return 540087617 /* ObjectLiteralExcludes */; + case 256 /* CatchClause */: + return 537920833 /* CatchClauseExcludes */; + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + return 537396545 /* BindingPatternExcludes */; + default: + return 536872257 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + /** Create Resolved from a file with unknown extension. */ + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2 /* DtsOnly */: + case 0 /* TypeScript */: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1 /* JavaScript */: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @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 + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === 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, typeRoots); + } + } + else { + 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, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2 /* DtsOnly */, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2 /* DtsOnly */, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, 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, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + return path_1 && { path: path_1, extension: tsExtension }; + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; + } + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case 2 /* DtsOnly */: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0 /* TypeScript */: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1 /* JavaScript */: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocations.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + // Note: this would allow a package.json to specify a ".js" file as typings. Maybe that should be forbidden. + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0 /* TypeScript */, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(2 /* DtsOnly */, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== 1 /* JavaScript */) { + return loadModuleFromNodeModulesFolder(2 /* DtsOnly */, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + // Climb up parent directories looking for a module. + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === 0 /* TypeScript */) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2 /* DtsOnly */, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21536,6 +24108,8 @@ var ts; // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if // they no longer need the information (for example, if the user started editing again). var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); @@ -21597,21 +24171,30 @@ var ts; getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + tryGetMemberInModuleExports: tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + } }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var stringLiteralTypes = ts.createMap(); var numericLiteralTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); @@ -21622,12 +24205,15 @@ var ts; var neverType = createIntrinsicType(8192 /* Never */, "never"); var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ | 67108864 /* Transient */, "__type"); + emptyTypeLiteralSymbol.members = ts.createMap(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -21653,6 +24239,7 @@ var ts; var globalBooleanType; var globalRegExpType; var anyArrayType; + var autoArrayType; var anyReadonlyArrayType; // The library files are only loaded when the feature is used. // This allows users to just specify library files they want to used through --lib @@ -21785,6 +24372,8 @@ var ts; "undefined": undefinedType }); var jsxElementType; + var _jsxNamespace; + var _jsxFactoryEntity; /** Things we lazy load from the JSX namespace */ var jsxTypes = ts.createMap(); var JsxNames = { @@ -21814,6 +24403,21 @@ var ts; builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; + function getJsxNamespace() { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. @@ -21897,13 +24501,11 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 225 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 225 /* ModuleDeclaration */))) { + (target.valueDeclaration.kind === 230 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 230 /* ModuleDeclaration */))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } - ts.forEach(source.declarations, function (node) { - target.declarations.push(node); - }); + ts.addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = ts.createMap(); @@ -21959,7 +24561,7 @@ var ts; var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); if (!mainModule) { return; } @@ -22000,8 +24602,11 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type) { + return type.flags & 32768 /* Object */ ? type.objectFlags : 0; + } function isGlobalSourceFile(node) { - return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 261 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -22047,24 +24652,30 @@ var ts; // nodes are in different files and order cannot be determines return true; } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } var sourceFiles = host.getSourceFiles(); return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 218 /* VariableDeclaration */ || + return declaration.kind !== 223 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 200 /* VariableStatement */: - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 205 /* VariableStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -22073,8 +24684,8 @@ var ts; break; } switch (declaration.parent.parent.kind) { - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: // ForIn/ForOf case - use site should not be used in expression part if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { return true; @@ -22082,8 +24693,7 @@ var ts; } return false; } - function isUsedInFunctionOrNonStaticProperty(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage, container) { var current = usage; while (current) { if (current === container) { @@ -22093,7 +24703,7 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 145 /* PropertyDeclaration */ && + current.parent.kind === 147 /* PropertyDeclaration */ && (ts.getModifierFlags(current.parent) & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { @@ -22126,11 +24736,11 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 278 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || - lastLocation.kind === 142 /* Parameter */ || - lastLocation.kind === 141 /* TypeParameter */ + lastLocation.kind === 144 /* Parameter */ || + lastLocation.kind === 143 /* TypeParameter */ : false; } if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { @@ -22139,9 +24749,9 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 142 /* Parameter */ || + lastLocation.kind === 144 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 142 /* Parameter */); + result.valueDeclaration.kind === 144 /* Parameter */); } } if (useResult) { @@ -22153,13 +24763,13 @@ var ts; } } switch (location.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 261 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports["default"]) { @@ -22182,7 +24792,7 @@ var ts; // which is not the desired behavior. if (moduleExports[name] && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 243 /* ExportSpecifier */)) { break; } } @@ -22190,13 +24800,13 @@ var ts; break loop; } break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -22213,9 +24823,9 @@ var ts; } } break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -22226,7 +24836,7 @@ var ts; } break loop; } - if (location.kind === 192 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 197 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -22242,9 +24852,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 227 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -22252,19 +24862,19 @@ var ts; } } break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -22277,7 +24887,7 @@ var ts; } } break; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -22286,7 +24896,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 142 /* Parameter */) { + if (location.parent && location.parent.kind === 144 /* Parameter */) { location = location.parent; } // @@ -22314,6 +24924,7 @@ var ts; if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } @@ -22349,15 +24960,15 @@ var ts; // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + if (decls && decls.length === 1 && decls[0].kind === 233 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 70 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -22402,16 +25013,26 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920 /* Namespace */) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); @@ -22427,7 +25048,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -22448,23 +25069,23 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 230 /* ImportDeclaration */) { + while (node && node.kind !== 235 /* ImportDeclaration */) { node = node.parent; } return node; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 240 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 245 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -22540,31 +25161,31 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_13 = specifier.propertyName || specifier.name; - if (name_13.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { 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="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -22586,19 +25207,19 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return getTargetOfImportClause(node); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return getTargetOfExportAssignment(node); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node); } } @@ -22645,11 +25266,11 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 235 /* ExportAssignment */) { + if (node.kind === 240 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 238 /* ExportSpecifier */) { + else if (node.kind === 243 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -22660,24 +25281,24 @@ var ts; } } // This function is only for imports with entity names - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 70 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { + if (entityName.kind === 70 /* Identifier */ || entityName.parent.kind === 141 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 234 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -22690,16 +25311,16 @@ var ts; return undefined; } var symbol; - if (name.kind === 69 /* Identifier */) { + if (name.kind === 70 /* Identifier */) { var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } } - else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { - var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 141 /* QualifiedName */ || name.kind === 177 /* PropertyAccessExpression */) { + var left = name.kind === 141 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 141 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -22724,30 +25345,30 @@ var ts; function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); - if (symbol) { - // merged symbol is module declaration symbol combined with all augmentations - return getMergedSymbol(symbol); - } + var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; } + var isRelative = ts.isExternalModuleNameRelative(moduleName); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { // merged symbol is module declaration symbol combined with all augmentations @@ -22765,15 +25386,32 @@ var ts; return getMergedSymbol(pattern.symbol); } } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } if (moduleNotFoundError) { // report errors only if it was requested - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -22800,6 +25438,12 @@ var ts; function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } function getExportsOfSymbol(symbol) { return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -22833,6 +25477,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -22904,7 +25550,7 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 148 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 150 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -22926,8 +25572,9 @@ var ts; type.intrinsicName = "boolean"; return type; } - function createObjectType(kind, symbol) { - var type = createType(kind); + function createObjectType(objectFlags, symbol) { + var type = createType(32768 /* Object */); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -22955,7 +25602,7 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; @@ -22967,7 +25614,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -22979,11 +25626,11 @@ var ts; } } switch (location_1.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } @@ -22998,6 +25645,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { @@ -23016,31 +25673,33 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 /* Alias */ + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -23063,7 +25722,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -23078,10 +25737,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: continue; default: return false; @@ -23112,7 +25771,7 @@ var ts; return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, }; } return hasAccessibleDeclarations; @@ -23149,7 +25808,7 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; @@ -23162,7 +25821,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -23203,12 +25862,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 158 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 160 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 139 /* QualifiedName */ || entityName.kind === 172 /* PropertyAccessExpression */ || - entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 141 /* QualifiedName */ || entityName.kind === 177 /* PropertyAccessExpression */ || + entityName.parent.kind === 234 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -23304,10 +25963,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 164 /* ParenthesizedType */) { + while (node.kind === 166 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 228 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -23315,7 +25974,7 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 226 /* ModuleBlock */ && + node.parent.kind === 231 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { @@ -23329,10 +25988,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return "(Anonymous class)"; - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -23355,17 +26014,17 @@ var ts; var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 19 /* OpenBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } else { - writePunctuation(writer, 21 /* DotToken */); + writePunctuation(writer, 22 /* DotToken */); writer.writeSymbol(symbolName, symbol); } } @@ -23407,9 +26066,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_5) { + walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,59 +26112,69 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072 /* Reference */) { + else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } else if (type.flags & 256 /* EnumLiteral */) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 21 /* DotToken */); + writePunctuation(writer, 22 /* DotToken */); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 196608 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 2097152 /* Anonymous */) { + else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { writeAnonymousType(type, nextFlags); } else if (type.flags & 96 /* StringOrNumberLiteral */) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & 262144 /* Index */) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 64 /* InElementType */); + } + else if (type.flags & 524288 /* IndexedAccess */) { + writeType(type.objectType, 64 /* InElementType */); + writePunctuation(writer, 20 /* OpenBracketToken */); + writeType(type.indexType, 0 /* None */); + writePunctuation(writer, 21 /* CloseBracketToken */); + } else { // Should never get here // { ... } - writePunctuation(writer, 15 /* OpenBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); writeSpace(writer); - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); writeSpace(writer); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 24 /* CommaToken */) { + if (delimiter !== 25 /* CommaToken */) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 24 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); + writeType(types[i], delimiter === 25 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { @@ -23514,29 +26183,29 @@ var ts; buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } if (pos < end) { - writePunctuation(writer, 25 /* LessThanToken */); + writePunctuation(writer, 26 /* LessThanToken */); writeType(typeArguments[pos], 256 /* InFirstTypeArgument */); pos++; while (pos < end) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); writeType(typeArguments[pos], 0 /* None */); pos++; } - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { writeType(typeArguments[0], 64 /* InElementType */); - writePunctuation(writer, 19 /* OpenBracketToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } - else if (type.target.flags & 262144 /* Tuple */) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); + else if (type.target.objectFlags & 8 /* Tuple */) { + writePunctuation(writer, 20 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 25 /* CommaToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } else { // Write the type reference in the format f.g.C where A and B are type arguments @@ -23549,15 +26218,15 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); - writePunctuation(writer, 21 /* DotToken */); + writeSymbolTypeReference(parent_6, typeArguments, start, i, flags); + writePunctuation(writer, 22 /* DotToken */); } } } @@ -23567,16 +26236,16 @@ var ts; } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } - if (type.flags & 524288 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); + if (type.flags & 65536 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 48 /* BarToken */); } else { - writeTypeList(type.types, 46 /* AmpersandToken */); + writeTypeList(type.types, 47 /* AmpersandToken */); } if (flags & 64 /* InElementType */) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } } function writeAnonymousType(type, flags) { @@ -23598,7 +26267,7 @@ var ts; } else { // Recursive usage, use any - writeKeyword(writer, 117 /* AnyKeyword */); + writeKeyword(writer, 118 /* AnyKeyword */); } } else { @@ -23622,7 +26291,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 256 /* SourceFile */ || declaration.parent.kind === 226 /* ModuleBlock */; + return declaration.parent.kind === 261 /* SourceFile */ || declaration.parent.kind === 231 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -23632,37 +26301,37 @@ var ts; } } function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 101 /* TypeOfKeyword */); + writeKeyword(writer, 102 /* TypeOfKeyword */); writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); } function writeIndexSignature(info, keyword) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 128 /* ReadonlyKeyword */); + writeKeyword(writer, 130 /* ReadonlyKeyword */); writeSpace(writer); } - writePunctuation(writer, 19 /* OpenBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeKeyword(writer, keyword); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeType(info.type, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 128 /* ReadonlyKeyword */); + writeKeyword(writer, 130 /* ReadonlyKeyword */); writeSpace(writer); } buildSymbolDisplay(prop, writer); if (prop.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); + writePunctuation(writer, 54 /* QuestionToken */); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { @@ -23678,56 +26347,68 @@ var ts; return false; } function writeLiteralType(type, flags) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + writeMappedType(type); + return; + } + } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 15 /* OpenBraceToken */); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { if (flags & 64 /* InElementType */) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } - writeKeyword(writer, 92 /* NewKeyword */); + writeKeyword(writer, 93 /* NewKeyword */); writeSpace(writer); buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 15 /* OpenBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 17 /* CloseBraceToken */); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } - writeIndexSignature(resolved.stringIndexInfo, 132 /* StringKeyword */); - writeIndexSignature(resolved.numberIndexInfo, 130 /* NumberKeyword */); + writeIndexSignature(resolved.stringIndexInfo, 134 /* StringKeyword */); + writeIndexSignature(resolved.numberIndexInfo, 132 /* NumberKeyword */); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -23737,22 +26418,45 @@ var ts; var signature = signatures_1[_f]; writePropertyWithModifiers(p); buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeType(t, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } + } + function writeMappedType(type) { + writePunctuation(writer, 16 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 130 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 20 /* OpenBracketToken */); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 91 /* InKeyword */); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 21 /* CloseBracketToken */); + if (type.declaration.questionToken) { + writePunctuation(writer, 54 /* QuestionToken */); + } + writePunctuation(writer, 55 /* ColonToken */); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 24 /* SemicolonToken */); + writer.writeLine(); writer.decreaseIndent(); - writePunctuation(writer, 16 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; + writePunctuation(writer, 17 /* CloseBraceToken */); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { @@ -23766,7 +26470,7 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 83 /* ExtendsKeyword */); + writeKeyword(writer, 84 /* ExtendsKeyword */); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } @@ -23774,7 +26478,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (ts.isRestParameter(parameterNode)) { - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); } if (ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -23783,37 +26487,37 @@ var ts; appendSymbolNameOnly(p, writer); } if (isOptionalParameter(parameterNode)) { - writePunctuation(writer, 53 /* QuestionToken */); + writePunctuation(writer, 54 /* QuestionToken */); } - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 167 /* ObjectBindingPattern */) { - writePunctuation(writer, 15 /* OpenBraceToken */); + if (bindingPattern.kind === 172 /* ObjectBindingPattern */) { + writePunctuation(writer, 16 /* OpenBraceToken */); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); } - else if (bindingPattern.kind === 168 /* ArrayBindingPattern */) { - writePunctuation(writer, 19 /* OpenBracketToken */); + else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) { + writePunctuation(writer, 20 /* OpenBracketToken */); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); } - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 169 /* BindingElement */); + ts.Debug.assert(bindingElement.kind === 174 /* BindingElement */); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); - writePunctuation(writer, 54 /* ColonToken */); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -23821,75 +26525,75 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25 /* LessThanToken */); + writePunctuation(writer, 26 /* LessThanToken */); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); } action(list[i]); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25 /* LessThanToken */); - var flags_1 = 256 /* InFirstTypeArgument */; + writePunctuation(writer, 26 /* LessThanToken */); + var flags = 256 /* InFirstTypeArgument */; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); - flags_1 = 0 /* None */; + flags = 0 /* None */; } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags_1); + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 97 /* ThisKeyword */); + writeKeyword(writer, 98 /* ThisKeyword */); } writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); + writeKeyword(writer, 125 /* IsKeyword */); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); - writePunctuation(writer, 34 /* EqualsGreaterThanToken */); + writePunctuation(writer, 35 /* EqualsGreaterThanToken */); } else { - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); } writeSpace(writer); if (signature.typePredicate) { @@ -23902,7 +26606,7 @@ var ts; } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { if (kind === 1 /* Construct */) { - writeKeyword(writer, 92 /* NewKeyword */); + writeKeyword(writer, 93 /* NewKeyword */); writeSpace(writer); } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { @@ -23940,75 +26644,75 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 169 /* BindingElement */: + case 174 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 220 /* FunctionDeclaration */: - case 224 /* EnumDeclaration */: - case 229 /* ImportEqualsDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + case 229 /* EnumDeclaration */: + case 234 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_7 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 234 /* ImportEqualsDeclaration */ && parent_7.kind !== 261 /* SourceFile */ && ts.isInAmbientContext(parent_7))) { + return isGlobalSourceFile(parent_7); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + return isDeclarationVisible(parent_7); + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so const it fall into next case statement - case 148 /* Constructor */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 153 /* IndexSignature */: - case 142 /* Parameter */: - case 226 /* ModuleBlock */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 159 /* TypeLiteral */: - case 155 /* TypeReference */: - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: + case 150 /* Constructor */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 155 /* IndexSignature */: + case 144 /* Parameter */: + case 231 /* ModuleBlock */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 161 /* TypeLiteral */: + case 157 /* TypeReference */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: return false; // Type parameters are always visible - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: // Source file and namespace export are always visible - case 256 /* SourceFile */: - case 228 /* NamespaceExportDeclaration */: + case 261 /* SourceFile */: + case 233 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return false; default: return false; @@ -24017,10 +26721,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 240 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 238 /* ExportSpecifier */) { + else if (node.parent.kind === 243 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -24095,7 +26799,6 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 32768 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -24114,12 +26817,12 @@ var ts; node = ts.getRootDeclaration(node); while (node) { switch (node.kind) { - case 218 /* VariableDeclaration */: - case 219 /* VariableDeclarationList */: - case 234 /* ImportSpecifier */: - case 233 /* NamedImports */: - case 232 /* NamespaceImport */: - case 231 /* ImportClause */: + case 223 /* VariableDeclaration */: + case 224 /* VariableDeclarationList */: + case 239 /* ImportSpecifier */: + case 238 /* NamedImports */: + case 237 /* NamespaceImport */: + case 236 /* ImportClause */: node = node.parent; break; default: @@ -24152,22 +26855,36 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function getTextOfPropertyName(name) { - switch (name.kind) { - case 69 /* Identifier */: - return name.text; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - case 140 /* ComputedPropertyName */: - if (ts.isStringOrNumericLiteral(name.expression.kind)) { - return name.expression.text; - } - } - return undefined; - } function isComputedNonLiteralName(name) { - return name.kind === 140 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind); + return name.kind === 142 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (source.flags & 8192 /* Never */) { + return emptyObjectType; + } + if (source.flags & 65536 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createMap(); + var names = ts.createMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name_17 = properties_2[_i]; + names[ts.getTextOfPropertyName(name_17)] = true; + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = prop.name in names; + var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isMethod = prop.flags & 8192 /* Method */; + var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { @@ -24187,25 +26904,41 @@ var ts; return parentType; } var type; - if (pattern.kind === 167 /* ObjectBindingPattern */) { - // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_14 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_14)) { - // computed properties with non-literal names are treated as 'any' - return anyType; + if (pattern.kind === 172 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - var text = getTextOfPropertyName(name_14); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); - return unknownType; + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name_18 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_18)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + var text = ts.getTextOfPropertyName(name_18); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); + if (!type) { + error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); + return unknownType; + } } } else { @@ -24213,7 +26946,11 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + else { // Use specific property type when parent is a tuple or numeric index type when parent is an array var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) @@ -24229,10 +26966,6 @@ var ts; return unknownType; } } - else { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); - } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. @@ -24244,42 +26977,26 @@ var ts; type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); - } - } - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - // First, see if this node has an @type annotation on it directly. - var typeTag = ts.getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - if (declaration.kind === 218 /* VariableDeclaration */ && - declaration.parent.kind === 219 /* VariableDeclarationList */ && - declaration.parent.parent.kind === 200 /* VariableStatement */) { - // @type annotation might have been on the variable statement, try that instead. - var annotation = ts.getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === 142 /* Parameter */) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } return undefined; } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 94 /* NullKeyword */ || expr.kind === 70 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 175 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. @@ -24288,11 +27005,13 @@ var ts; return type; } } - // A variable declared in a for..in statement is always of type string - if (declaration.parent.parent.kind === 207 /* ForInStatement */) { - return stringType; + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (declaration.parent.parent.kind === 212 /* ForInStatement */) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 208 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 213 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -24306,11 +27025,26 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } - if (declaration.kind === 142 /* Parameter */) { + if ((compilerOptions.noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && + declaration.kind === 223 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 144 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 150 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149 /* GetAccessor */); + if (func.kind === 152 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -24325,8 +27059,7 @@ var ts; // Use contextual parameter type if one is available var type = void 0; if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -24341,7 +27074,7 @@ var ts; return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 258 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -24369,6 +27102,7 @@ var ts; // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createMap(); + var stringIndexInfo; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -24377,19 +27111,23 @@ var ts; hasComputedProperties = true; return; } - var text = getTextOfPropertyName(name); + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } return result; } @@ -24398,7 +27136,7 @@ var ts; var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); @@ -24417,7 +27155,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 167 /* ObjectBindingPattern */ + return pattern.kind === 172 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -24439,7 +27177,7 @@ var ts; // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - if (declaration.kind === 253 /* PropertyAssignment */) { + if (declaration.kind === 257 /* PropertyAssignment */) { return type; } return getWidenedType(type); @@ -24456,7 +27194,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 142 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 144 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -24468,14 +27206,14 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 252 /* CatchClause */) { + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 235 /* ExportAssignment */) { + if (declaration.kind === 240 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 1048576 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { + if (declaration.flags & 65536 /* JavaScriptFile */ && declaration.kind === 286 /* JSDocPropertyTag */ && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } // Handle variable, parameter or property @@ -24488,16 +27226,16 @@ var ts; // * exports.p = expr // * this.p = expr // * className.prototype.method = expr - if (declaration.kind === 187 /* BinaryExpression */ || - declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { + if (declaration.kind === 192 /* BinaryExpression */ || + declaration.kind === 177 /* PropertyAccessExpression */ && declaration.parent.kind === 192 /* BinaryExpression */) { // Use JS Doc type if present on parent expression statement - if (declaration.flags & 1048576 /* JavaScriptFile */) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + if (declaration.flags & 65536 /* JavaScriptFile */) { + var jsdocType = ts.getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 /* BinaryExpression */ ? checkExpressionCached(decl.right) : checkExpressionCached(decl.parent.right); }); type = getUnionType(declaredTypes, /*subtypeReduction*/ true); @@ -24506,18 +27244,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - // Variable has type annotation that circularly references the variable itself - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -24525,7 +27252,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 149 /* GetAccessor */) { + if (accessor.kind === 151 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -24545,9 +27272,9 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 150 /* SetAccessor */); - if (getter && getter.flags & 1048576 /* JavaScriptFile */) { + var getter = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 152 /* SetAccessor */); + if (getter && getter.flags & 65536 /* JavaScriptFile */) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -24590,7 +27317,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -24601,11 +27328,11 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(2097152 /* Anonymous */, symbol); + var type = createObjectType(16 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24637,10 +27364,29 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); @@ -24663,7 +27409,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 /* Reference */ ? type.target : type; + return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -24697,9 +27443,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 221 /* ClassDeclaration */ || node.kind === 192 /* ClassExpression */ || - node.kind === 220 /* FunctionDeclaration */ || node.kind === 179 /* FunctionExpression */ || - node.kind === 147 /* MethodDeclaration */ || node.kind === 180 /* ArrowFunction */) { + if (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */ || + node.kind === 225 /* FunctionDeclaration */ || node.kind === 184 /* FunctionExpression */ || + node.kind === 149 /* MethodDeclaration */ || node.kind === 185 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -24709,7 +27455,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 222 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -24718,8 +27464,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 222 /* InterfaceDeclaration */ || node.kind === 221 /* ClassDeclaration */ || - node.kind === 192 /* ClassExpression */ || node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 226 /* ClassDeclaration */ || + node.kind === 197 /* ClassExpression */ || node.kind === 228 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -24734,7 +27480,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -24746,7 +27492,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -24766,7 +27512,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 32768 /* Object */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -24785,7 +27531,7 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.flags & 262144 /* Tuple */) { + if (type.objectFlags & 8 /* Tuple */) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -24805,7 +27551,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { + if (!(baseConstructorType.flags & 32768 /* Object */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -24829,15 +27575,23 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } + // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { + if (!(getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } if (type.resolvedBaseTypes === emptyArray) { @@ -24862,12 +27616,12 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 227 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { + if (getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -24894,7 +27648,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 /* InterfaceDeclaration */) { + if (declaration.kind === 227 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -24917,7 +27671,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -24926,8 +27680,8 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 131072 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -24935,7 +27689,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -24950,8 +27705,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); + var declaration = ts.getDeclarationOfKind(symbol, 285 /* JSDocTypedefTag */); var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -24962,16 +27716,17 @@ var ts; } } else { - declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + declaration = ts.getDeclarationOfKind(symbol, 228 /* TypeAliasDeclaration */); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; links.instantiations = ts.createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -24988,14 +27743,14 @@ var ts; return !ts.isInAmbientContext(member); } return expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; + expr.kind === 70 /* Identifier */ && !!symbol.exports[expr.text]; } function enumHasLiteralMembers(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { + if (declaration.kind === 229 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!isLiteralEnumMember(symbol, member)) { @@ -25023,7 +27778,7 @@ var ts; var memberTypes = ts.createMap(); for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { + if (declaration.kind === 229 /* EnumDeclaration */) { computeEnumMemberValues(declaration); for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; @@ -25038,7 +27793,7 @@ var ts; } enumType.memberTypes = memberTypes; if (memberTypeList.length > 1) { - enumType.flags |= 524288 /* Union */; + enumType.flags |= 65536 /* Union */; enumType.types = memberTypeList; unionTypes[getTypeListId(memberTypeList)] = enumType; } @@ -25050,7 +27805,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 /* Union */ ? + links.declaredType = enumType.flags & 65536 /* Union */ ? enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : enumType; } @@ -25061,7 +27816,7 @@ var ts; if (!links.declaredType) { var type = createType(16384 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -25114,20 +27869,20 @@ var ts; // considered independent. function isIndependentType(node) { switch (node.kind) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 127 /* NeverKeyword */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 129 /* NeverKeyword */: + case 171 /* LiteralType */: return true; - case 160 /* ArrayType */: + case 162 /* ArrayType */: return isIndependentType(node.elementType); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return isIndependentTypeReference(node); } return false; @@ -25140,7 +27895,7 @@ var ts; // A function-like declaration is considered independent (free of this references) if it has a return type // annotation that is considered independent and if each parameter is considered independent. function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 148 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 150 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -25161,12 +27916,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return isIndependentVariableLikeDeclaration(declaration); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -25211,7 +27966,7 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072 /* Reference */) { + if (getObjectFlags(type) & 4 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; @@ -25234,8 +27989,8 @@ var ts; else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -25255,7 +28010,7 @@ var ts; numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -25290,14 +28045,14 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -25394,7 +28149,7 @@ var ts; var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); @@ -25402,6 +28157,9 @@ var ts; function intersectIndexInfos(info1, info2) { return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). @@ -25416,17 +28174,17 @@ var ts; stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { var members = symbol.members; @@ -25434,7 +28192,7 @@ var ts; var constructSignatures = getSignaturesOfSymbol(members["__new"]); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module @@ -25450,13 +28208,13 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 32768 /* Object */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are // in the process of resolving (see issue #6072). The temporarily empty signature list @@ -25466,21 +28224,124 @@ var ts; } } } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createMap(); + var stringIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 168 /* TypeOperator */) { + // We have a { [P in keyof T]: X } + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + } + else { + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var iterationMapper = createUnaryTypeMapper(typeParameter, t); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 32 /* StringLiteral */) { + var propName = t.text; + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); + var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & 2 /* String */) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getErasedTemplateTypeFromMappedType(type) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, 540672 /* TypeVariable */ | 262144 /* Index */); + } + return false; + } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Reference */) { - resolveTypeReferenceMembers(type); + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & 2097152 /* Anonymous */) { - resolveAnonymousTypeMembers(type); - } - else if (type.flags & 524288 /* Union */) { + else if (type.flags & 65536 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576 /* Intersection */) { + else if (type.flags & 131072 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -25488,7 +28349,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -25496,7 +28357,7 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -25509,29 +28370,43 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 196608 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter * as the type argument for the 'this' type. */ - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } @@ -25543,29 +28418,20 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 16384 /* TypeParameter */) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & 34 /* StringLike */) { - type = globalStringType; - } - else if (type.flags & 340 /* NumberLike */) { - type = globalNumberType; - } - else if (type.flags & 136 /* BooleanLike */) { - type = globalBooleanType; - } - else if (type.flags & 512 /* ESSymbol */) { - type = getGlobalESSymbolType(); - } - return type; + var t = type.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & 262178 /* StringLike */ ? globalStringType : + t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 136 /* BooleanLike */ ? globalBooleanType : + t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 131072 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25583,22 +28449,21 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + else if (containingType.flags & 65536 /* Union */) { + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +28474,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 65536 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +28503,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -25645,7 +28518,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -25659,13 +28532,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 196608 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 229376 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -25679,7 +28552,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 229376 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -25714,7 +28587,7 @@ var ts; return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -25744,21 +28617,32 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 1048576 /* JavaScriptFile */) { - if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { + if (node.flags & 65536 /* JavaScriptFile */) { + if (node.type && node.type.kind === 273 /* JSDocOptionalType */) { return true; } - var paramTag = ts.getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 268 /* JSDocOptionalType */; + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 273 /* JSDocOptionalType */; + } } } } } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } function isOptionalParameter(node) { if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -25773,7 +28657,7 @@ var ts; return false; } function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 69 /* Identifier */) { + if (node.parameterName.kind === 70 /* Identifier */) { var parameterName = node.parameterName; return { kind: 1 /* Identifier */, @@ -25816,7 +28700,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* LiteralType */) { + if (param.type && param.type.kind === 171 /* LiteralType */) { hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { @@ -25830,10 +28714,10 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 149 /* GetAccessor */ || declaration.kind === 150 /* SetAccessor */) && + if ((declaration.kind === 151 /* GetAccessor */ || declaration.kind === 152 /* SetAccessor */) && !ts.hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; + var otherKind = declaration.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */; var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); @@ -25845,24 +28729,21 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } - var classType = declaration.kind === 148 /* Constructor */ ? + var classType = declaration.kind === 150 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 156 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType) { + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -25872,7 +28753,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -25880,8 +28761,8 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 149 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 150 /* SetAccessor */); + if (declaration.kind === 151 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 152 /* SetAccessor */); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -25895,20 +28776,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 269 /* JSDocFunctionType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 274 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -25972,13 +28853,18 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { + if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } return anyType; } function getSignatureInstantiation(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + function createSignatureInstantiation(signature, typeArguments) { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { @@ -25995,8 +28881,8 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(2097152 /* Anonymous */); + var isConstructor = signature.declaration.kind === 150 /* Constructor */ || signature.declaration.kind === 154 /* ConstructSignature */; + var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -26009,7 +28895,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 130 /* NumberKeyword */ : 132 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 132 /* NumberKeyword */ : 134 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -26036,11 +28922,11 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 141 /* TypeParameter */).constraint; + return ts.getDeclarationOfKind(type.symbol, 143 /* TypeParameter */).constraint; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26068,8 +28954,13 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 524288 /* IndexedAccess */ ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -26106,22 +28997,23 @@ var ts; result |= type.flags; } } - return result & 234881024 /* PropagatingFlags */; + return result & 14680064 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 131072 /* Reference */ | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(4 /* Reference */, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } return type; } function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -26141,7 +29033,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -26149,21 +29041,26 @@ var ts; } return type; } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. function getTypeFromTypeAliasReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; + var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); - var id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -26181,11 +29078,11 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 155 /* TypeReference */: + case 157 /* TypeReference */: return node.typeName; - case 267 /* JSDocTypeReference */: + case 272 /* JSDocTypeReference */: return node.name; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -26195,7 +29092,7 @@ var ts; } return undefined; } - function resolveTypeReferenceName(node, typeReferenceName) { + function resolveTypeReferenceName(typeReferenceName) { if (!typeReferenceName) { return unknownSymbol; } @@ -26211,7 +29108,7 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getTypeFromTypeAliasReference(node, symbol); } - if (symbol.flags & 107455 /* Value */ && node.kind === 267 /* JSDocTypeReference */) { + if (symbol.flags & 107455 /* Value */ && node.kind === 272 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In // that case, the type of this reference is just the type of the value we resolved // to. @@ -26224,14 +29121,14 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - if (node.kind === 267 /* JSDocTypeReference */) { + if (node.kind === 272 /* JSDocTypeReference */) { var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ + var typeNameOrExpression = node.kind === 157 /* TypeReference */ ? node.typeName : ts.isEntityNameExpression(node.expression) ? node.expression @@ -26266,9 +29163,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: return declaration; } } @@ -26277,7 +29174,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672 /* ObjectType */)) { + if (!(type.flags & 32768 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -26357,7 +29254,7 @@ var ts; property.type = typeParameter; properties.push(property); } - var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -26365,7 +29262,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26383,7 +29281,7 @@ var ts; function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -26411,7 +29309,7 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 524288 /* Union */) { + if (flags & 65536 /* Union */) { addTypesToUnion(typeSet, type.types); } else if (flags & 1 /* Any */) { @@ -26422,7 +29320,7 @@ var ts; typeSet.containsUndefined = true; if (flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(flags & 33554432 /* ContainsWideningType */)) + if (!(flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } else if (!(flags & 8192 /* Never */)) { @@ -26435,7 +29333,8 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -26466,7 +29365,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -26482,7 +29398,7 @@ var ts; var t = types[i]; var remove = t.flags & 32 /* StringLiteral */ && types.containsString || t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 16777216 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -26532,28 +29448,31 @@ var ts; var type = unionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); + type = unionTypes[id] = createType(65536 /* Union */ | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 131072 /* Intersection */) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1 /* Any */) { typeSet.containsAny = true; } else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -26565,6 +29484,11 @@ var ts; addTypeToIntersection(typeSet, type); } } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. @@ -26582,44 +29506,335 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); + type = intersectionTypes[id] = createType(131072 /* Intersection */ | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + // We eagerly compute the constraint of the indexed access type such that circularity + // errors are immediately caught and reported. For example, class C { x: this["x"] } + // becomes an error only when the constraint is eagerly computed. + if (type.objectType.flags & 229376 /* StructuredType */) { + // The constraint of T[K], where T is an object, union, or intersection type, + // is the type of the string index signature of T, if any. + type.constraint = getIndexTypeOfType(type.objectType, 0 /* String */); + } + else if (type.objectType.flags & 540672 /* TypeVariable */) { + // The constraint of T[K], where T is a type variable, is A[K], where A is the + // apparent type of T. + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178 /* StringLike */) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0 /* String */); + } + } + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? + indexType.text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : + undefined; + if (propName) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + var indexNode = accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + } + else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 178 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1 /* Any */) { + return objectType; + } + // We first check that the index type is assignable to 'keyof T' for the object type. + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes + // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the + // type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise we defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + // In the following we resolve T[K] to the type of the property in T selected by K. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - var type = createObjectType(2097152 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (ts.isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } } return links.resolvedType; } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 228 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, isFromObjectLiteral) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + left = filterType(left, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (left.flags & 8192 /* Never */) { + return right; + } + right = filterType(right, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (right.flags & 8192 /* Never */) { + return left; + } + if (left.flags & 65536 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, isFromObjectLiteral); }); + } + if (right.flags & 65536 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, isFromObjectLiteral); }); + } + var members = ts.createMap(); + var skippedPrivateMembers = ts.createMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + // we approximate own properties as non-methods plus methods that are inside the object literal + var isOwnProperty = !(rightProp.flags & 8192 /* Method */) || isFromObjectLiteral; + var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + var rightProp = members[leftProp.name]; + var rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 536870912 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | 67108864 /* Transient */ | (leftProp.flags & 536870912 /* Optional */); + var result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } function createLiteralType(flags, text) { var type = createType(flags); type.text = text; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 16777216 /* FreshLiteral */)) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 16777216 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); freshType.regularType = type; type.freshType = freshType; } @@ -26628,7 +29843,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } function getLiteralTypeForText(flags, text) { var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; @@ -26652,7 +29867,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); + var types = ts.map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -26660,9 +29875,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 222 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 227 /* InterfaceDeclaration */)) { if (!(ts.getModifierFlags(container) & 32 /* Static */) && - (container.kind !== 148 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 150 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -26676,87 +29891,90 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type) { - return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); - } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { - case 117 /* AnyKeyword */: - case 258 /* JSDocAllType */: - case 259 /* JSDocUnknownType */: + case 118 /* AnyKeyword */: + case 263 /* JSDocAllType */: + case 264 /* JSDocUnknownType */: return anyType; - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: return stringType; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: return numberType; - case 120 /* BooleanKeyword */: + case 121 /* BooleanKeyword */: return booleanType; - case 133 /* SymbolKeyword */: + case 135 /* SymbolKeyword */: return esSymbolType; - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return voidType; - case 135 /* UndefinedKeyword */: + case 137 /* UndefinedKeyword */: return undefinedType; - case 93 /* NullKeyword */: + case 94 /* NullKeyword */: return nullType; - case 127 /* NeverKeyword */: + case 129 /* NeverKeyword */: return neverType; - case 283 /* JSDocNullKeyword */: + case 289 /* JSDocNullKeyword */: return nullType; - case 284 /* JSDocUndefinedKeyword */: + case 290 /* JSDocUndefinedKeyword */: return undefinedType; - case 285 /* JSDocNeverKeyword */: + case 291 /* JSDocNeverKeyword */: return neverType; - case 165 /* ThisType */: - case 97 /* ThisKeyword */: + case 167 /* ThisType */: + case 98 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* LiteralType */: + case 171 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 282 /* JSDocLiteralType */: + case 288 /* JSDocLiteralType */: return getTypeFromLiteralTypeNode(node.literal); - case 155 /* TypeReference */: - case 267 /* JSDocTypeReference */: + case 157 /* TypeReference */: + case 272 /* JSDocTypeReference */: return getTypeFromTypeReference(node); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return booleanType; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 160 /* ArrayType */: - case 260 /* JSDocArrayType */: + case 162 /* ArrayType */: + case 265 /* JSDocArrayType */: return getTypeFromArrayTypeNode(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 162 /* UnionType */: - case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 164 /* ParenthesizedType */: - case 263 /* JSDocNullableType */: - case 264 /* JSDocNonNullableType */: - case 271 /* JSDocConstructorType */: - case 272 /* JSDocThisType */: - case 268 /* JSDocOptionalType */: + case 164 /* UnionType */: + case 266 /* JSDocUnionType */: + return getTypeFromUnionTypeNode(node); + case 165 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 166 /* ParenthesizedType */: + case 268 /* JSDocNullableType */: + case 269 /* JSDocNonNullableType */: + case 276 /* JSDocConstructorType */: + case 277 /* JSDocThisType */: + case 273 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); - case 265 /* JSDocRecordType */: + case 270 /* JSDocRecordType */: return getTypeFromTypeNode(node.literal); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 269 /* JSDocFunctionType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 161 /* TypeLiteral */: + case 287 /* JSDocTypeLiteral */: + case 274 /* JSDocFunctionType */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 168 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 169 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 170 /* MappedType */: + return getTypeFromMappedTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 69 /* Identifier */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 141 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 262 /* JSDocTupleType */: + case 267 /* JSDocTupleType */: return getTypeFromJSDocTupleType(node); - case 270 /* JSDocVariadicType */: + case 275 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); default: return unknownType; @@ -26773,6 +29991,16 @@ var ts; } return items; } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } function createUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -26795,7 +30023,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -26893,25 +30120,52 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - if (mapper.instantiations) { - var cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); + result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144 /* Index */) { + var typeVariable_1 = constraintType.type; + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + var replacementMapper = createUnaryTypeMapper(typeVariable_1, t); + var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } var mappedTypes = mapper.mappedTypes; // Starting with the parent of the symbol's declaration, check if the mapper maps any of // the type parameters introduced by enclosing declarations. We just pick the first @@ -26919,23 +30173,23 @@ var ts; var node = symbol.declarations[0].parent; while (node) { switch (node.kind) { - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: var declaration = node; if (declaration.typeParameters) { for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { @@ -26945,27 +30199,63 @@ var ts; } } } - if (ts.isClassLike(node) || node.kind === 222 /* InterfaceDeclaration */) { + if (ts.isClassLike(node) || node.kind === 227 /* InterfaceDeclaration */) { var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; if (thisType && ts.contains(mappedTypes, thisType)) { return true; } } break; - case 225 /* ModuleDeclaration */: - case 256 /* SourceFile */: + case 230 /* ModuleDeclaration */: + case 261 /* SourceFile */: return false; } node = node.parent; } return false; } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 261 /* SourceFile */ || parentKind === 231 /* ModuleBlock */; + } + return false; + } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); + // If we are instantiating a type that has a top-level type alias, obtain the instantiation through + // the type alias instead in order to share instantiations for the same type arguments. This can + // dramatically reduce the number of structurally identical types we generate. Note that we can only + // perform this optimization for top-level type aliases. Consider: + // + // function f1(x: T) { + // type Foo = { x: X, t: T }; + // let obj: Foo = { x: x }; + // return obj; + // } + // function f2(x: U) { return f1(x); } + // let z = f2(42); + // + // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo + // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's + // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been + // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & 2097152 /* Anonymous */) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -26974,19 +30264,28 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & 131072 /* Reference */) { - return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + if (type.objectFlags & 32 /* Mapped */) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & 1048576 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } return type; } function instantiateIndexInfo(info, mapper) { @@ -26995,44 +30294,59 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 187 /* BinaryExpression */: - return node.operatorToken.kind === 52 /* BarBarToken */ && + case 192 /* BinaryExpression */: + return node.operatorToken.kind === 53 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - var areAllParametersUntyped = !ts.forEach(node.parameters, function (p) { return p.type; }); - var isNullaryArrow = node.kind === 180 /* ArrowFunction */ && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.forEach(node.parameters, function (p) { return !p.type; })) { + return true; + } + // For arrow functions we now know we're not context sensitive. + if (node.kind === 185 /* ArrowFunction */) { + return false; + } + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. Otherwise we + // know that all parameters (including 'this') have type annotations and nothing is + // subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152 /* Anonymous */, type.symbol); + var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -27235,7 +30549,7 @@ var ts; } if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { + (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { return enumRelation[id] = false; } var targetEnumType = getTypeOfSymbol(target.symbol); @@ -27258,7 +30572,7 @@ var ts; return false; if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) return true; - if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) + if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) return true; if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) return true; @@ -27292,23 +30606,23 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { target = target.regularType; } if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { + if (source.flags & 507904 /* StructuredOrTypeParameter */ || target.flags & 507904 /* StructuredOrTypeParameter */) { return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); } return false; @@ -27355,9 +30669,15 @@ var ts; targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); } if (!message) { - message = relation === comparableRelation ? - ts.Diagnostics.Type_0_is_not_comparable_to_type_1 : - ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); } @@ -27371,16 +30691,35 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source, target, reportErrors, headMessage) { var result; - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { target = target.regularType; } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases @@ -27391,7 +30730,7 @@ var ts; } if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (source.flags & 8388608 /* ObjectLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -27402,13 +30741,15 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 1572864 /* UnionOrIntersection */) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 524288 /* Union */) { + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 65536 /* Union */) { if (relation === comparableRelation) { result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } @@ -27419,56 +30760,128 @@ var ts; return result; } } - else if (target.flags & 1048576 /* Intersection */) { - result = typeRelatedToEachType(source, target, reportErrors); - if (result) { + else if (target.flags & 65536 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { return result; } } - else { - // It is necessary to try these "some" checks on both sides because there may be nested "each" checks - // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or - // A & B = (A & B) | (C & D). - if (source.flags & 1048576 /* Intersection */) { - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + else if (target.flags & 131072 /* Intersection */) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else if (source.flags & 131072 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + return result; + } + } + else if (target.flags & 16384 /* TypeParameter */) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + // Given a type parameter K with a constraint keyof T, a type S is + // assignable to K if S is assignable to keyof T. + var constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & 262144 /* Index */) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 262144 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } } - if (target.flags & 524288 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { + // Given a type variable T with a constraint C, a type S is assignable to + // keyof T if S is assignable to keyof C. + if (target.type.flags & 540672 /* TypeVariable */) { + var constraint = getConstraintOfTypeVariable(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 524288 /* IndexedAccess */) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. + if (source.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(source); - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // The constraint may need to be further instantiated with its 'this' type. + constraint = getTypeWithThisArgument(constraint, source); + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -27480,7 +30893,7 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { + if (apparentSource.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { @@ -27490,10 +30903,10 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 2588672 /* ObjectType */ && globalObjectType === source) { + else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -27502,8 +30915,8 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -27511,10 +30924,10 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { - if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { - if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -27526,7 +30939,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -27535,7 +30948,7 @@ var ts; return true; } } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 196608 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -27553,7 +30966,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -27571,7 +30984,7 @@ var ts; } return false; } - function eachTypeRelatedToSomeType(source, target, reportErrors) { + function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { @@ -27586,7 +30999,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } var len = targetTypes.length; @@ -27613,7 +31026,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -27708,6 +31121,9 @@ var ts; if (expandingFlags === 3) { result = 1 /* Maybe */; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -27738,15 +31154,43 @@ var ts; } return result; } + // A type [P in S]: X is related to a type [P in T]: Y if T is related to S and X is related to Y. + function mappedTypeRelatedTo(source, target, reportErrors) { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + var result_2; + if (relation === identityRelation) { + var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken; + var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) { + return -1 /* True */; + } + return 0 /* False */; + } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -27798,7 +31242,8 @@ var ts; return 0 /* False */; } result &= related; - if (sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -27817,7 +31262,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { + if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -28002,7 +31447,7 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 2097152 /* Anonymous */) { + if (getObjectFlags(type) & 16 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -28020,12 +31465,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { + if (getObjectFlags(type) & (4 /* Reference */ | 64 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { + if (getObjectFlags(t) & (4 /* Reference */ | 64 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -28211,12 +31656,12 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 /* Reference */ && type.target === globalArrayType; + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { @@ -28227,7 +31672,7 @@ var ts; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -28235,15 +31680,15 @@ var ts; type.flags & 64 /* NumberLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? numberType : + return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -28251,7 +31696,7 @@ var ts; * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); + return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -28265,7 +31710,7 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : @@ -28276,7 +31721,7 @@ var ts; return type; } var types = [type]; - if (flags & 34 /* StringLike */) + if (flags & 262178 /* StringLike */) types.push(emptyStringType); if (flags & 340 /* NumberLike */) types.push(zeroType); @@ -28335,7 +31780,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 8388608 /* ObjectLiteral */ && type.flags & 16777216 /* FreshLiteral */)) { + if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -28345,7 +31790,8 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -28362,18 +31808,18 @@ var ts; return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296 /* RequiresWidening */) { + if (type.flags & 6291456 /* RequiresWidening */) { if (type.flags & 6144 /* Nullable */) { return anyType; } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 65536 /* Union */) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } } return type; @@ -28391,7 +31837,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -28407,11 +31853,11 @@ var ts; } } } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432 /* ContainsWideningType */) { + if (t.flags & 2097152 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -28425,25 +31871,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 142 /* Parameter */: + case 144 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 169 /* BindingElement */: + case 174 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -28456,7 +31902,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -28489,7 +31935,7 @@ var ts; signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length), }; } function createTypeInferencesObject() { @@ -28497,29 +31943,79 @@ var ts; primary: undefined, secondary: undefined, topLevel: true, - isFixed: false + isFixed: false, }; } // Return true if the given type could possibly reference a type parameter for which // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 /* TypeParameter */ || - type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 /* TypeVariable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 1572864 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypes(context, originalSource, originalTarget) { - var typeParameters = context.signature.typeParameters; + // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + // an object type with the same set of properties as the source type, where the type of each + // property is computed by inferring from the source property type to X for the type + // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0 /* String */); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var typeVariableArray = [typeVariable]; + var typeInferences = createTypeInferencesObject(); + var typeInferencesArray = [typeInferences]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 536870912 /* Optional */; + var members = createSymbolTable(properties); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 /* Property */ | 67108864 /* Transient */ | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + var inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, /*subtypeReduction*/ true); + } + } + function inferTypesWithContext(context, originalSource, originalTarget) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { var sourceStack; var targetStack; var depth = 0; @@ -28535,11 +32031,21 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { return; } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -28577,19 +32083,19 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 540672 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 134217728 /* ContainsAnyFunctionType */) { + if (source.flags & 8388608 /* ContainsAnyFunctionType */) { return; } - for (var i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - var inferences = context.inferences[i]; + for (var i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + var inferences = typeInferences[i]; if (!inferences.isFixed) { // Any inferences that are made to a type parameter in a union type are inferior // to inferences made to a flat (non-union) type. This is because if we infer to @@ -28603,7 +32109,7 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -28611,7 +32117,7 @@ var ts; } } } - else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -28620,31 +32126,31 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864 /* UnionOrIntersection */) { + else if (target.flags & 196608 /* UnionOrIntersection */) { var targetTypes = target.types; - var typeParameterCount = 0; - var typeParameter = void 0; - // First infer to each type in union or intersection that isn't a type parameter + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { var t = targetTypes_2[_d]; - if (t.flags & 16384 /* TypeParameter */ && ts.contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - // Next, if target containings a single naked type parameter, make a secondary inference to that type - // parameter. This gives meaningful results for union types in co-variant positions and intersection + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection // types in contra-variant positions (such as callback parameters). - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } - else if (source.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 196608 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -28654,7 +32160,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 2588672 /* ObjectType */) { + if (source.flags & 32768 /* Object */) { if (isInProcess(source, target)) { return; } @@ -28673,18 +32179,47 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var index = ts.indexOf(typeVariables, constraintType.type); + if (index >= 0 && !typeInferences[index].isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & 16384 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -28754,7 +32289,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -28762,7 +32297,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; @@ -28778,7 +32313,7 @@ var ts; var widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; @@ -28832,10 +32367,10 @@ var ts; // The expression is restricted to a single identifier or a sequence of identifiers separated by periods while (node) { switch (node.kind) { - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return true; - case 69 /* Identifier */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 141 /* QualifiedName */: node = node.parent; continue; default: @@ -28849,14 +32384,14 @@ var ts; // leftmost identifier followed by zero or more property names separated by dots. // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 98 /* ThisKeyword */) { return "0"; } - if (node.kind === 172 /* PropertyAccessExpression */) { + if (node.kind === 177 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + node.name.text; } @@ -28864,31 +32399,31 @@ var ts; } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: return node; - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return getLeftmostIdentifierOrThis(node.expression); } return undefined; } function isMatchingReference(source, target) { switch (source.kind) { - case 69 /* Identifier */: - return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && + case 70 /* Identifier */: + return target.kind === 70 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 223 /* VariableDeclaration */ || target.kind === 174 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97 /* ThisKeyword */: - return target.kind === 97 /* ThisKeyword */; - case 172 /* PropertyAccessExpression */: - return target.kind === 172 /* PropertyAccessExpression */ && + case 98 /* ThisKeyword */: + return target.kind === 98 /* ThisKeyword */; + case 177 /* PropertyAccessExpression */: + return target.kind === 177 /* PropertyAccessExpression */ && source.name.text === target.name.text && isMatchingReference(source.expression, target.expression); } return false; } function containsMatchingReference(source, target) { - while (source.kind === 172 /* PropertyAccessExpression */) { + while (source.kind === 177 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -28901,37 +32436,26 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 /* PropertyAccessExpression */ && + return target.kind === 177 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69 /* Identifier */) { + if (expr.kind === 70 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 172 /* PropertyAccessExpression */) { + if (expr.kind === 177 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.text); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + if (type && type.flags & 65536 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -28950,7 +32474,7 @@ var ts; } } } - if (callExpression.expression.kind === 172 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 177 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -28964,7 +32488,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288 /* Union */)) { + if (!(source.flags & 65536 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -29032,7 +32556,7 @@ var ts; type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 2588672 /* ObjectType */) { + if (flags & 32768 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; @@ -29050,7 +32574,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type); return getTypeFacts(constraint || emptyObjectType); } - if (flags & 1572864 /* UnionOrIntersection */) { + if (flags & 196608 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 8388607 /* All */; @@ -29060,13 +32584,13 @@ var ts; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { - var defaultType = checkExpression(defaultExpression); + var defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { - var text = getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || @@ -29077,19 +32601,19 @@ var ts; checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType; } - function getTypeOfDestructuredSpreadElement(type) { + function getTypeOfDestructuredSpreadExpression(type) { return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 170 /* ArrayLiteralExpression */ || node.parent.kind === 253 /* PropertyAssignment */ ? + return node.parent.kind === 175 /* ArrayLiteralExpression */ || node.parent.kind === 257 /* PropertyAssignment */ ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node) { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node) { return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); @@ -29100,21 +32624,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return stringType; - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression) || unknownType; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return undefinedType; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 191 /* SpreadElementExpression */: - return getAssignedTypeOfSpreadElement(parent); - case 253 /* PropertyAssignment */: + case 196 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 257 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -29122,11 +32646,11 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 167 /* ObjectBindingPattern */ ? + var type = pattern.kind === 172 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { @@ -29134,47 +32658,60 @@ var ts; // from its initializer, we'll already have cached the type. Otherwise we compute it now // without caching such that transient types are reflected. var links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 207 /* ForInStatement */) { + if (node.parent.parent.kind === 212 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 208 /* ForOfStatement */) { + if (node.parent.parent.kind === 213 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 218 /* VariableDeclaration */ ? + return node.kind === 223 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? + return node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } + function isEmptyArrayAssignment(node) { + return node.kind === 223 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 174 /* BindingElement */ && node.parent.kind === 192 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } function getReferenceCandidate(node) { switch (node.kind) { - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return getReferenceCandidate(node.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return getReferenceCandidate(node.right); } } return node; } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 183 /* ParenthesizedExpression */ || + parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 57 /* EqualsToken */ && parent.left === node || + parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 25 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } function getTypeOfSwitchClause(clause) { - if (clause.kind === 249 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + if (clause.kind === 253 /* CaseClause */) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -29190,13 +32727,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288 /* Union */) { + if (source.flags & 65536 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -29210,14 +32747,37 @@ var ts; } return containsType(target.types, source); } + function forEachType(type, f) { + return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + } function filterType(type, f) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 65536 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29227,22 +32787,122 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 65536 /* Union */ ? + getUnionType(elementType.types, /*subtypeReduction*/ true) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + if (!(t.flags & 8192 /* Never */)) { + if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 177 /* PropertyAccessExpression */ && (parent.name.text === "length" || + parent.parent.kind === 179 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 178 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 192 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 57 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 96 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 201 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 512 /* Shared */) { + if (flow.flags & 1024 /* 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. @@ -29275,10 +32935,17 @@ var ts; getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { + if (container && container !== flowContainer && reference.kind !== 177 /* PropertyAccessExpression */) { flow = container.flowNode; continue; } @@ -29287,10 +32954,10 @@ var ts; } else { // Unreachable code errors are reported in the binding phase. Here we - // simply return the declared type to reduce follow-on errors. - type = declaredType; + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); } - if (flow.flags & 512 /* Shared */) { + if (flow.flags & 1024 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -29304,10 +32971,21 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29319,24 +32997,56 @@ var ts; // Assignment doesn't affect reference return undefined; } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 179 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 179 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (!(type.flags & 8192 /* Never */)) { - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & 8192 /* Never */ && isIncomplete(flowType)) { - type = silentNeverType; - } + if (type.flags & 8192 /* Never */) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); @@ -29378,7 +33088,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at @@ -29393,11 +33103,15 @@ var ts; } // If this flow loop junction and reference are already being processed, return // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -29441,15 +33155,15 @@ var ts; } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - var result = getUnionType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } return cache[key] = result; } function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && - declaredType.flags & 524288 /* Union */ && + return expr.kind === 177 /* PropertyAccessExpression */ && + declaredType.flags & 65536 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(declaredType, expr.name.text); } @@ -29473,19 +33187,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 187 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 187 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29504,9 +33218,9 @@ var ts; return declaredType; } break; - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -29515,28 +33229,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 32 /* ExclamationEqualsToken */ || operator === 34 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); + var valueType = getTypeOfExpression(value); if (valueType.flags & 6144 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var doubleEquals = operator === 31 /* EqualsEqualsToken */ || operator === 32 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 93 /* NullKeyword */ ? + value.kind === 94 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 33281 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29555,10 +33269,10 @@ var ts; } return type; } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 32 /* ExclamationEqualsToken */ || operator === 34 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288 /* Union */)) { + if (assumeTrue && !(type.flags & 65536 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. @@ -29581,7 +33295,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29599,7 +33314,7 @@ var ts; return type; } // Check that right operand is a function type with a prototype property - var rightType = checkExpression(expr.right); + var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -29619,10 +33334,10 @@ var ts; if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 65536 /* Interface */) { + if (getObjectFlags(rightType) & 2 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152 /* Anonymous */) { + else if (getObjectFlags(rightType) & 16 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -29630,18 +33345,18 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type, candidate, assumeTrue) { + function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return filterType(type, function (t) { return !isRelated(t, candidate); }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 524288 /* Union */) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (type.flags & 65536 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); if (!(assignableType.flags & 8192 /* Never */)) { return assignableType; } @@ -29658,7 +33373,7 @@ var ts; getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } var signature = getResolvedSignature(callExpression); @@ -29674,7 +33389,7 @@ var ts; var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -29682,12 +33397,12 @@ var ts; } } else { - var invokedExpression = skipParenthesizedNodes(callExpression.expression); - if (invokedExpression.kind === 173 /* ElementAccessExpression */ || invokedExpression.kind === 172 /* PropertyAccessExpression */) { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 178 /* ElementAccessExpression */ || invokedExpression.kind === 177 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; - var possibleReference = skipParenthesizedNodes(accessExpression.expression); + var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -29700,18 +33415,18 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: + case 177 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 185 /* PrefixUnaryExpression */: - if (expr.operator === 49 /* ExclamationToken */) { + case 190 /* PrefixUnaryExpression */: + if (expr.operator === 50 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -29724,12 +33439,12 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 69 /* Identifier */) { + if (location.kind === 70 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { - var type = checkExpression(location); + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -29742,19 +33457,13 @@ var ts; // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression) { - while (expression.kind === 178 /* ParenthesizedExpression */) { - expression = expression.expression; - } - return expression; - } function getControlFlowContainer(node) { while (true) { node = node.parent; if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 /* ModuleBlock */ || - node.kind === 256 /* SourceFile */ || - node.kind === 145 /* PropertyDeclaration */) { + node.kind === 231 /* ModuleBlock */ || + node.kind === 261 /* SourceFile */ || + node.kind === 147 /* PropertyDeclaration */) { return node; } } @@ -29783,10 +33492,10 @@ var ts; } } function markParameterAssignments(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144 /* Parameter */) { symbol.isAssigned = true; } } @@ -29795,8 +33504,14 @@ var ts; ts.forEachChild(node, markParameterAssignments); } } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects @@ -29805,17 +33520,18 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (languageVersion < 2 /* ES6 */) { - if (container.kind === 180 /* ArrowFunction */) { + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 185 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - if (node.flags & 262144 /* AwaitContext */) { + if (node.flags & 16384 /* AwaitContext */) { getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } + return getTypeOfSymbol(symbol); } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); @@ -29826,8 +33542,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (languageVersion === 2 /* ES6 */ - && declaration_1.kind === 221 /* ClassDeclaration */ + if (declaration_1.kind === 226 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration_1)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -29839,14 +33554,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration_1.kind === 192 /* ClassExpression */) { + else if (declaration_1.kind === 197 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); while (container !== undefined) { if (container.parent === declaration_1) { - if (container.kind === 145 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 147 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -29861,41 +33576,62 @@ var ts; checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); var declaration = localOrExportSymbol.valueDeclaration; + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } // We only narrow variables and parameters occurring in a non-assignment position. For all other // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) || assignmentKind === 1 /* Definite */ || !declaration) { return type; } // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 144 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === 184 /* FunctionExpression */ || + flowContainer.kind === 185 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node, threshold) { var current = node; @@ -29908,9 +33644,9 @@ var ts; return false; } function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 /* ES6 */ || + if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 252 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 256 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -29935,8 +33671,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 206 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 219 /* VariableDeclarationList */).parent === container && + if (container.kind === 211 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 224 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -29950,7 +33686,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { var current = node; // skip parenthesized nodes - while (current.parent.kind === 178 /* ParenthesizedExpression */) { + while (current.parent.kind === 183 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -29958,9 +33694,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 185 /* PrefixUnaryExpression */ || current.parent.kind === 186 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 190 /* PrefixUnaryExpression */ || current.parent.kind === 191 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 41 /* PlusPlusToken */ || expr.operator === 42 /* MinusMinusToken */; + isAssigned = expr.operator === 42 /* PlusPlusToken */ || expr.operator === 43 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -29979,7 +33715,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 145 /* PropertyDeclaration */ || container.kind === 148 /* Constructor */) { + if (container.kind === 147 /* PropertyDeclaration */ || container.kind === 150 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -29988,7 +33724,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30022,58 +33758,61 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 148 /* Constructor */) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + if (container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 180 /* ArrowFunction */) { + if (container.kind === 185 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); + needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 148 /* Constructor */: + case 150 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -30081,11 +33820,11 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 179 /* FunctionExpression */ && + if (container.kind === 184 /* FunctionExpression */ && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') @@ -30098,7 +33837,7 @@ var ts; return getInferredClassType(classSymbol); } } - var thisType = getThisTypeOfDeclaration(container); + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -30121,31 +33860,31 @@ var ts; return anyType; } function getTypeForThisExpressionFromJSDoc(node) { - var typeTag = ts.getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 269 /* JSDocFunctionType */) { - var jsDocFunctionType = typeTag.typeExpression.type; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 272 /* JSDocThisType */) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 274 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277 /* JSDocThisType */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 142 /* Parameter */) { + if (n.kind === 144 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 179 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 180 /* ArrowFunction */) { + while (container && container.kind === 185 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); @@ -30157,16 +33896,16 @@ var ts; // [super.foo()]() {} // } var current = node; - while (current && current !== container && current.kind !== 140 /* ComputedPropertyName */) { + while (current && current !== container && current.kind !== 142 /* ComputedPropertyName */) { current = current.parent; } - if (current && current.kind === 140 /* ComputedPropertyName */) { + if (current && current.kind === 142 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -30174,6 +33913,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } @@ -30237,7 +33979,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 147 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (container.kind === 149 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -30251,8 +33993,8 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 171 /* ObjectLiteralExpression */) { - if (languageVersion < 2 /* ES6 */) { + if (container.parent.kind === 176 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; } @@ -30271,7 +34013,7 @@ var ts; } return unknownType; } - if (container.kind === 148 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 150 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -30286,7 +34028,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 148 /* Constructor */; + return container.kind === 150 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -30294,32 +34036,35 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */) { if (ts.getModifierFlags(container) & 32 /* Static */) { - return container.kind === 147 /* MethodDeclaration */ || - container.kind === 146 /* MethodSignature */ || - container.kind === 149 /* GetAccessor */ || - container.kind === 150 /* SetAccessor */; + return container.kind === 149 /* MethodDeclaration */ || + container.kind === 148 /* MethodSignature */ || + container.kind === 151 /* GetAccessor */ || + container.kind === 152 /* SetAccessor */; } else { - return container.kind === 147 /* MethodDeclaration */ || - container.kind === 146 /* MethodSignature */ || - container.kind === 149 /* GetAccessor */ || - container.kind === 150 /* SetAccessor */ || - container.kind === 145 /* PropertyDeclaration */ || - container.kind === 144 /* PropertySignature */ || - container.kind === 148 /* Constructor */; + return container.kind === 149 /* MethodDeclaration */ || + container.kind === 148 /* MethodSignature */ || + container.kind === 151 /* GetAccessor */ || + container.kind === 152 /* SetAccessor */ || + container.kind === 147 /* PropertyDeclaration */ || + container.kind === 146 /* PropertySignature */ || + container.kind === 150 /* Constructor */; } } } return false; } } - function getContextualThisParameter(func) { - if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { + function getContextualThisParameterType(func) { + if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } return undefined; @@ -30379,7 +34124,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 142 /* Parameter */) { + if (declaration.kind === 144 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -30390,11 +34135,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_15 = declaration.propertyName || declaration.name; + var name_19 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_15)) { - var text = getTextOfPropertyName(name_15); + !ts.isBindingPattern(name_19)) { + var text = ts.getTextOfPropertyName(name_19); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -30431,7 +34176,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 142 /* Parameter */ && node.parent.initializer === node) { + if (node.parent.kind === 144 /* Parameter */ && node.parent.initializer === node) { return true; } node = node.parent; @@ -30442,8 +34187,8 @@ var ts; // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed if (functionDecl.type || - functionDecl.kind === 148 /* Constructor */ || - functionDecl.kind === 149 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 150 /* SetAccessor */))) { + functionDecl.kind === 150 /* Constructor */ || + functionDecl.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152 /* SetAccessor */))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature @@ -30465,7 +34210,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 176 /* TaggedTemplateExpression */) { + if (template.parent.kind === 181 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -30473,26 +34218,26 @@ var ts; function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; - if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + if (operator >= 57 /* FirstAssignment */ && operator <= 69 /* LastAssignment */) { // Don't do this for special property assignments to avoid circularity if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { return undefined; } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } - else if (operator === 52 /* BarBarToken */) { + else if (operator === 53 /* BarBarToken */) { // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand. var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } - else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + else if (operator === 52 /* AmpersandAmpersandToken */ || operator === 25 /* CommaToken */) { if (node === binaryExpression.right) { return getContextualType(binaryExpression); } @@ -30503,14 +34248,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 65536 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30528,7 +34273,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -30537,7 +34282,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -30580,7 +34325,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1 /* Number */) - || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); + || (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); } return undefined; } @@ -30593,13 +34338,13 @@ var ts; var kind = attribute.kind; var jsxElement = attribute.parent; var attrsType = getJsxElementAttributesType(jsxElement); - if (attribute.kind === 246 /* JsxAttribute */) { + if (attribute.kind === 250 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - else if (attribute.kind === 247 /* JsxSpreadAttribute */) { + else if (attribute.kind === 251 /* JsxSpreadAttribute */) { return attrsType; } ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); @@ -30637,58 +34382,73 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 218 /* VariableDeclaration */: - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 174 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 180 /* ArrowFunction */: - case 211 /* ReturnStatement */: + case 185 /* ArrowFunction */: + case 216 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 197 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 189 /* TemplateExpression */); + case 202 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 194 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return getContextualType(parent); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return getContextualType(parent); - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); } return undefined; } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. - function getNonGenericSignature(type) { + function getNonGenericSignature(type, node) { var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */; + return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -30707,19 +34467,19 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 524288 /* Union */)) { - return getNonGenericSignature(type); + if (!(type.flags & 65536 /* Union */)) { + return getNonGenericSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; - var signature = getNonGenericSignature(current); + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -30763,19 +34523,13 @@ var ts; function isInferentialContext(mapper) { return mapper && mapper.context; } - function checkSpreadElementExpression(node, contextualMapper) { - // It is usually not safe to call checkExpressionCached if we can be contextually typing. - // You can tell that we are contextually typing because of the contextualMapper parameter. - // While it is true that a spread element can have a contextual type, it does not do anything - // with this type. It is neither affected by it, nor does it propagate it to its operand. - // So the fact that contextualMapper is passed is not important, because the operand of a spread - // element is not contextually typed. - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node, contextualMapper) { + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 169 /* BindingElement */ && !!node.initializer) || - (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 174 /* BindingElement */ && !!node.initializer) || + (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -30784,7 +34538,7 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 191 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 196 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -30799,7 +34553,7 @@ var ts; // if there is no index type / iterated type. var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); + (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -30808,7 +34562,7 @@ var ts; var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 191 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 196 /* SpreadElement */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -30823,7 +34577,7 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 168 /* ArrayBindingPattern */ || pattern.kind === 170 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 173 /* ArrayBindingPattern */ || pattern.kind === 175 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -30831,7 +34585,7 @@ var ts; elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 193 /* OmittedExpression */) { + if (patternElement.kind !== 198 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -30848,7 +34602,7 @@ var ts; strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { - return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 142 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, @@ -30891,7 +34645,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -30900,10 +34654,10 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(node, properties, kind) { + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 /* String */ || isNumericName(node.properties[i].name)) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -30916,28 +34670,31 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createMap(); var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 167 /* ObjectBindingPattern */ || contextualType.pattern.kind === 171 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 172 /* ObjectBindingPattern */ || contextualType.pattern.kind === 176 /* ObjectLiteralExpression */); var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var memberDecl = _a[_i]; + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; var member = memberDecl.symbol; - if (memberDecl.kind === 253 /* PropertyAssignment */ || - memberDecl.kind === 254 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 257 /* PropertyAssignment */ || + memberDecl.kind === 258 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 253 /* PropertyAssignment */) { + if (memberDecl.kind === 257 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 147 /* MethodDeclaration */) { + else if (memberDecl.kind === 149 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 254 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 258 /* ShorthandPropertyAssignment */); type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -30945,8 +34702,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 253 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 254 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 257 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 258 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } @@ -30954,14 +34711,14 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912 /* Optional */; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -30974,13 +34731,34 @@ var ts; prop.target = member; member = prop; } + else if (memberDecl.kind === 259 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + propertiesArray = []; + propertiesTable = ts.createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, /*isFromObjectLiteral*/ false); + offset = i + 1; + continue; + } else { // TypeScript 1.0 spec (April 2014) // A get accessor declaration is processed in the same manner as // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 149 /* GetAccessor */ || memberDecl.kind === 150 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 151 /* GetAccessor */ || memberDecl.kind === 152 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } if (ts.hasDynamicName(memberDecl)) { @@ -30999,8 +34777,8 @@ var ts; // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { - for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { - var prop = _c[_b]; + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); @@ -31010,15 +34788,41 @@ var ts; } } } - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); - if (inDestructuringPattern) { - result.pattern = node; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + } + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - return result; + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; + result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.objectFlags |= 128 /* ObjectLiteral */; + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144 /* Nullable */)) { + propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */) || + type.flags & 32768 /* Object */ && !isGenericMappedType(type) || + type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); @@ -31038,13 +34842,13 @@ var ts; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: checkJsxExpression(child); break; - case 241 /* JsxElement */: + case 246 /* JsxElement */: checkJsxElement(child); break; - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -31063,7 +34867,7 @@ var ts; */ function isJsxIntrinsicIdentifier(tagName) { // TODO (yuisu): comment - if (tagName.kind === 172 /* PropertyAccessExpression */ || tagName.kind === 97 /* ThisKeyword */) { + if (tagName.kind === 177 /* PropertyAccessExpression */ || tagName.kind === 98 /* ThisKeyword */) { return false; } else { @@ -31081,7 +34885,7 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); + var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); if (attributeType) { correspondingPropType = attributeType; } @@ -31109,6 +34913,9 @@ var ts; return exprType; } function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + if (compilerOptions.jsx === 2 /* React */) { + checkExternalEmitHelpers(node, 2 /* Assign */); + } var type = checkExpression(node.expression); var props = getPropertiesOfType(type); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { @@ -31174,7 +34981,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); + ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -31190,7 +34997,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -31232,9 +35039,9 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288 /* Union */) { + if (elemType.flags & 65536 /* Union */) { var types = elemType.types; - return getUnionType(types.map(function (type) { + return getUnionType(ts.map(types, function (type) { return getResolvedJsxType(node, type, elemClassType); }), /*subtypeReduction*/ true); } @@ -31306,7 +35113,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 524288 /* Union */) { + else if (attributesType.flags & 65536 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -31395,13 +35202,19 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there - // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactNamespace = getJsxNamespace(); var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = true; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 8388608 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = ts.createMap(); @@ -31410,11 +35223,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 246 /* JsxAttribute */) { + if (node.attributes[i].kind === 250 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 247 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 251 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -31444,7 +35257,7 @@ var ts; // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 145 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 147 /* PropertyDeclaration */; } function getDeclarationModifierFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; @@ -31463,10 +35276,10 @@ var ts; function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); - var errorNode = node.kind === 172 /* PropertyAccessExpression */ || node.kind === 218 /* VariableDeclaration */ ? + var errorNode = node.kind === 177 /* PropertyAccessExpression */ || node.kind === 223 /* VariableDeclaration */ ? node.name : node.right; - if (left.kind === 95 /* SuperKeyword */) { + if (left.kind === 96 /* SuperKeyword */) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -31474,7 +35287,7 @@ var ts; // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 147 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES2015 */ && getDeclarationKindFromSymbol(prop) !== 149 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -31505,7 +35318,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 95 /* SuperKeyword */) { + if (left.kind === 96 /* SuperKeyword */) { return true; } // Get the enclosing class that has the declaring class as its base type @@ -31523,12 +35336,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -31554,6 +35367,33 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (prop.flags & 16777216 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -31567,51 +35407,36 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (prop.flags & 16777216 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & 32 /* Class */) { checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || + if (node.kind !== 177 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 524288 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + var flowType = getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 172 /* PropertyAccessExpression */ + var left = node.kind === 177 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -31628,13 +35453,13 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 219 /* VariableDeclarationList */) { + if (initializer.kind === 224 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 69 /* Identifier */) { + else if (initializer.kind === 70 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -31650,17 +35475,17 @@ var ts; * that references a for-in variable for an object with numeric property names. */ function isForInVariableForNumericPropertyNames(expr) { - var e = skipParenthesizedNodes(expr); - if (e.kind === 69 /* Identifier */) { + var e = ts.skipParentheses(expr); + if (e.kind === 70 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 207 /* ForInStatement */ && + if (node.kind === 212 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression(node.expression))) { + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { return true; } child = node; @@ -31671,10 +35496,11 @@ var ts; return false; } function checkIndexedAccess(node) { - // Grammar checking - if (!node.argumentExpression) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 175 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 180 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -31684,101 +35510,18 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } + return unknownType; } - // Obtain base constraint such that we can bail out if the constraint is an unknown type - var objectType = getApparentType(checkNonNullExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - var isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== 9 /* StringLiteral */)) { - error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - // TypeScript 1.0 spec (April 2014): 4.10 Property Access - // - If IndexExpr is a string literal or a numeric literal and ObjExpr's apparent type has a property with the name - // given by that literal(converted to its string representation in the case of a numeric literal), the property access is of the type of that property. - // - Otherwise, if ObjExpr's apparent type has a numeric index signature and IndexExpr is of type Any, the Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if ObjExpr's apparent type has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. - // See if we can index as a property. - if (node.argumentExpression) { - var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_16 !== undefined) { - var prop = getPropertyOfType(objectType, name_16); - 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_16, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - // Check for compatible indexer types. - var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { - // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - // Try to use string indexing. - var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, 1 /* Number */) ? - ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - return anyType; - } - // REVIEW: Users should know the type that was actually used. - error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - return unknownType; + return getIndexedAccessType(objectType, indexType, node); } - /** - * If indexArgumentExpression is a string literal or number literal, returns its text. - * If indexArgumentExpression is a constant value, returns its string value. - * If indexArgumentExpression is a well known symbol, returns the property name corresponding - * to this symbol, as long as it is a proper symbol reference. - * Otherwise, returns undefined. - */ - function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { - if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { - return indexArgumentExpression.text; - } - if (indexArgumentExpression.kind === 173 /* ElementAccessExpression */ || indexArgumentExpression.kind === 172 /* PropertyAccessExpression */) { - var value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - var rightHandSideName = indexArgumentExpression.name.text; - return ts.getPropertyNameForKnownSymbolName(rightHandSideName); - } - return undefined; - } - /** - * A proper symbol reference requires the following: - * 1. The property access denotes a property that exists - * 2. The expression is of the form Symbol. - * 3. The property access is of the primitive type symbol. - * 4. Symbol in this context resolves to the global Symbol object - */ function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { // There is already an error, so no need to report one. @@ -31815,10 +35558,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 143 /* Decorator */) { + else if (node.kind !== 145 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -31848,13 +35591,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_8 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_8 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_8; index = cutoffIndex; } } @@ -31862,7 +35605,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_8; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -31884,7 +35627,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 191 /* SpreadElementExpression */) { + if (arg && arg.kind === 196 /* SpreadElement */) { return i; } } @@ -31897,13 +35640,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 189 /* TemplateExpression */) { + if (tagExpression.template.kind === 194 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -31916,11 +35659,11 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 11 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 12 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 143 /* Decorator */) { + else if (node.kind === 145 /* Decorator */) { isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); @@ -31929,7 +35672,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 175 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 180 /* NewExpression */); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -31960,7 +35703,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -31974,7 +35717,7 @@ var ts; var context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -32005,7 +35748,7 @@ var ts; if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. @@ -32013,9 +35756,9 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 193 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { @@ -32024,7 +35767,7 @@ var ts; var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this @@ -32038,7 +35781,7 @@ var ts; if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -32070,7 +35813,7 @@ var ts; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 175 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 180 /* 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. @@ -32087,10 +35830,10 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 193 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { @@ -32109,12 +35852,12 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 174 /* CallExpression */) { + if (node.kind === 179 /* CallExpression */) { var callee = node.expression; - if (callee.kind === 172 /* PropertyAccessExpression */) { + if (callee.kind === 177 /* PropertyAccessExpression */) { return callee.expression; } - else if (callee.kind === 173 /* ElementAccessExpression */) { + else if (callee.kind === 178 /* ElementAccessExpression */) { return callee.expression; } } @@ -32130,16 +35873,16 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 189 /* TemplateExpression */) { + if (template.kind === 194 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 143 /* Decorator */) { + else if (node.kind === 145 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -32164,19 +35907,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { switch (node.parent.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -32186,7 +35929,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 142 /* Parameter */: + case 144 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -32210,25 +35953,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -32255,32 +35998,32 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { node = node.parent; - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; switch (element.name.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { return nameType; @@ -32306,21 +36049,21 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 145 /* PropertyDeclaration */) { + if (node.kind === 147 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -32348,14 +36091,14 @@ var ts; /** * Gets the effective argument type for an argument in a call expression. */ - function getEffectiveArgumentType(node, argIndex, arg) { + function getEffectiveArgumentType(node, argIndex) { // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -32367,8 +36110,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 143 /* Decorator */ || - (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */)) { + if (node.kind === 145 /* Decorator */ || + (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -32377,11 +36120,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -32390,13 +36133,13 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 176 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 143 /* Decorator */; + var isTaggedTemplate = node.kind === 181 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 145 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 95 /* SuperKeyword */) { + if (node.expression.kind !== 96 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -32462,7 +36205,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 174 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -32501,7 +36244,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -32528,7 +36271,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -32560,7 +36303,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -32608,7 +36351,7 @@ var ts; } } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (node.expression.kind === 96 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated @@ -32676,7 +36419,7 @@ var ts; if (!numCallSignatures && !numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have // no common signatures. - if (funcType.flags & 524288 /* Union */) { + if (funcType.flags & 65536 /* Union */) { return false; } return isTypeAssignableTo(funcType, globalFunctionType); @@ -32769,12 +36512,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 /* Protected */ && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8 /* Private */) { @@ -32810,16 +36554,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 142 /* Parameter */: + case 144 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -32849,13 +36593,13 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 143 /* Decorator */: + case 145 /* Decorator */: return resolveDecorator(node, candidatesOutArray); } ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); @@ -32901,22 +36645,22 @@ var ts; // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 95 /* SuperKeyword */) { + if (node.expression.kind === 96 /* SuperKeyword */) { return voidType; } - if (node.kind === 175 /* NewExpression */) { + if (node.kind === 180 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 148 /* Constructor */ && - declaration.kind !== 152 /* ConstructSignature */ && - declaration.kind !== 157 /* ConstructorType */ && + declaration.kind !== 150 /* Constructor */ && + declaration.kind !== 154 /* ConstructSignature */ && + declaration.kind !== 159 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // 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 // 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 */ ? + var funcSymbol = node.expression.kind === 70 /* Identifier */ ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { @@ -32929,11 +36673,37 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + // Make sure require is not a local function + var resolvedRequire = resolveName(node.expression, node.expression.text, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require + return true; + } + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & 8388608 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 225 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 223 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return ts.isInAmbientContext(decl); + } + return false; + } function checkTaggedTemplateExpression(node) { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -32969,21 +36739,36 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push @@ -32993,7 +36778,7 @@ var ts; for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 69 /* Identifier */) { + if (element.name.kind === 70 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } assignBindingElementTypes(element); @@ -33007,8 +36792,8 @@ var ts; links.type = instantiateType(contextualType, mapper); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 167 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 168 /* ArrayBindingPattern */)) { + (parameter.valueDeclaration.name.kind === 172 /* ObjectBindingPattern */ || + parameter.valueDeclaration.name.kind === 173 /* ArrayBindingPattern */)) { links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); } assignBindingElementTypes(parameter.valueDeclaration); @@ -33043,7 +36828,7 @@ var ts; // T in the second overload so that we do not infer Base as a candidate for T // (inferring Base would make type argument inference inconsistent between the two // overloads). - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } function getReturnTypeFromJSDocComment(func) { @@ -33066,7 +36851,7 @@ var ts; 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); + error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } return promiseType; @@ -33078,7 +36863,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 199 /* Block */) { + if (func.body.kind !== 204 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -33121,7 +36906,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33151,7 +36938,7 @@ var ts; if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(node.expression); + var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -33159,14 +36946,14 @@ var ts; if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + if (lastStatement && lastStatement.kind === 218 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { return false; } return true; @@ -33199,7 +36986,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */)) { + func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -33228,7 +37015,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 */ || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; @@ -33261,10 +37048,10 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 179 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 184 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards @@ -33305,14 +37092,14 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 149 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); if (!node.asteriskToken) { @@ -33328,7 +37115,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 199 /* Block */) { + if (node.body.kind === 204 /* Block */) { checkSourceElement(node.body); } else { @@ -33375,11 +37162,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) && - expr.expression.kind === 97 /* ThisKeyword */) { + (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) && + expr.expression.kind === 98 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 148 /* Constructor */)) + if (!(func && func.kind === 150 /* Constructor */)) return true; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, @@ -33391,50 +37178,25 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) { - var node = skipParenthesizedNodes(expr.expression); - if (node.kind === 69 /* Identifier */) { + if (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 70 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 8388608 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 232 /* NamespaceImport */; + return declaration && declaration.kind === 237 /* NamespaceImport */; } } } return false; } - function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. - var node = skipParenthesizedNodes(expr); - if (node.kind !== 69 /* Identifier */ && node.kind !== 172 /* PropertyAccessExpression */ && node.kind !== 173 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr); + if (node.kind !== 70 /* Identifier */ && node.kind !== 177 /* PropertyAccessExpression */ && node.kind !== 178 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } - // Because we get the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - var links = getNodeLinks(node); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - // Only variables (and not functions, classes, namespaces, enum objects, or enum members) - // are considered references when referenced using a simple identifier. - if (node.kind === 69 /* Identifier */ && !(symbol.flags & 3 /* Variable */)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === 173 /* ElementAccessExpression */) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } function checkDeleteExpression(node) { @@ -33452,7 +37214,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 262144 /* AwaitContext */)) { + if (!(node.flags & 16384 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -33467,28 +37229,28 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + if (node.operator === 37 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); } switch (node.operator) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 49 /* ExclamationToken */: + case 50 /* ExclamationToken */: var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : booleanType; - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -33502,7 +37264,7 @@ var ts; var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -33512,10 +37274,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33530,20 +37292,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { - var t = types_16[_a]; + for (var _a = 0, types_17 = types; _a < types_17.length; _a++) { + var t = types_17[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -33552,7 +37314,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -33583,39 +37345,40 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var p = properties_4[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { - if (property.kind === 253 /* PropertyAssignment */ || property.kind === 254 /* ShorthandPropertyAssignment */) { - var name_17 = property.name; - if (name_17.kind === 140 /* ComputedPropertyName */) { - checkComputedPropertyName(name_17); + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 257 /* PropertyAssignment */ || property.kind === 258 /* ShorthandPropertyAssignment */) { + var name_20 = property.name; + if (name_20.kind === 142 /* ComputedPropertyName */) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_17)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_17); + var text = ts.getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 254 /* ShorthandPropertyAssignment */) { + if (property.kind === 258 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -33624,9 +37387,22 @@ var ts; } } else { - error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } + else if (property.kind === 259 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, ts.Diagnostics.Property_assignment_expected); } @@ -33645,8 +37421,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 193 /* OmittedExpression */) { - if (element.kind !== 191 /* SpreadElementExpression */) { + if (element.kind !== 198 /* OmittedExpression */) { + if (element.kind !== 196 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -33670,11 +37446,11 @@ var ts; } else { if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { var restExpression = element.expression; - if (restExpression.kind === 187 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 192 /* BinaryExpression */ && restExpression.operatorToken.kind === 57 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -33687,7 +37463,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 254 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 258 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -33703,21 +37479,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 187 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 192 /* BinaryExpression */ && target.operatorToken.kind === 57 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 171 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + if (target.kind === 176 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 170 /* ArrayLiteralExpression */) { + if (target.kind === 175 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + var error = target.parent.kind === 259 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -33733,52 +37512,52 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 176 /* TaggedTemplateExpression */: - case 189 /* TemplateExpression */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 11 /* RegularExpressionLiteral */: + case 181 /* TaggedTemplateExpression */: + case 194 /* TemplateExpression */: + case 12 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 179 /* FunctionExpression */: - case 192 /* ClassExpression */: - case 180 /* ArrowFunction */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 182 /* TypeOfExpression */: - case 196 /* NonNullExpression */: - case 242 /* JsxSelfClosingElement */: - case 241 /* JsxElement */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: + case 94 /* NullKeyword */: + case 137 /* UndefinedKeyword */: + case 184 /* FunctionExpression */: + case 197 /* ClassExpression */: + case 185 /* ArrowFunction */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 187 /* TypeOfExpression */: + case 201 /* NonNullExpression */: + case 247 /* JsxSelfClosingElement */: + case 246 /* JsxElement */: return true; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 49 /* ExclamationToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: + case 50 /* ExclamationToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 183 /* VoidExpression */: // Explicit opt-out - case 177 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 195 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 188 /* VoidExpression */: // Explicit opt-out + case 182 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 200 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -33798,34 +37577,34 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 171 /* ObjectLiteralExpression */ || left.kind === 170 /* ArrayLiteralExpression */)) { + if (operator === 57 /* EqualsToken */ && (left.kind === 176 /* ObjectLiteralExpression */ || left.kind === 175 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); var rightType = checkExpression(right, contextualMapper); switch (operator) { - case 37 /* AsteriskToken */: - case 38 /* AsteriskAsteriskToken */: - case 59 /* AsteriskEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - case 40 /* PercentToken */: - case 62 /* PercentEqualsToken */: - case 36 /* MinusToken */: - case 58 /* MinusEqualsToken */: - case 43 /* LessThanLessThanToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* BarToken */: - case 67 /* BarEqualsToken */: - case 48 /* CaretToken */: - case 68 /* CaretEqualsToken */: - case 46 /* AmpersandToken */: - case 66 /* AmpersandEqualsToken */: + case 38 /* AsteriskToken */: + case 39 /* AsteriskAsteriskToken */: + case 60 /* AsteriskEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + case 41 /* PercentToken */: + case 63 /* PercentEqualsToken */: + case 37 /* MinusToken */: + case 59 /* MinusEqualsToken */: + case 44 /* LessThanLessThanToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* BarToken */: + case 68 /* BarEqualsToken */: + case 49 /* CaretToken */: + case 69 /* CaretEqualsToken */: + case 47 /* AmpersandToken */: + case 67 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -33858,8 +37637,8 @@ var ts; } } return numberType; - case 35 /* PlusToken */: - case 57 /* PlusEqualsToken */: + case 36 /* PlusToken */: + case 58 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -33880,7 +37659,7 @@ var ts; resultType = numberType; } else { - if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { + if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -33898,24 +37677,26 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 57 /* PlusEqualsToken */) { + if (operator === 58 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } } return booleanType; - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -33926,22 +37707,22 @@ var ts; reportOperatorError(); } return booleanType; - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 90 /* InKeyword */: + case 91 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : leftType; - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 24 /* CommaToken */: + case 25 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -33960,30 +37741,28 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 47 /* BarToken */: - case 67 /* BarEqualsToken */: - return 52 /* BarBarToken */; - case 48 /* CaretToken */: - case 68 /* CaretEqualsToken */: - return 33 /* ExclamationEqualsEqualsToken */; - case 46 /* AmpersandToken */: - case 66 /* AmpersandEqualsToken */: - return 51 /* AmpersandAmpersandToken */; + case 48 /* BarToken */: + case 68 /* BarEqualsToken */: + return 53 /* BarBarToken */; + case 49 /* CaretToken */: + case 69 /* CaretEqualsToken */: + return 34 /* ExclamationEqualsEqualsToken */; + case 47 /* AmpersandToken */: + case 67 /* AmpersandEqualsToken */: + return 52 /* AmpersandAmpersandToken */; default: return undefined; } } function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + if (produceDiagnostics && operator >= 57 /* FirstAssignment */ && operator <= 69 /* LastAssignment */) { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - // Use default messages - if (ok) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); } @@ -34011,7 +37790,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 65536 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -34061,9 +37840,9 @@ var ts; return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); case 8 /* NumericLiteral */: return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); - case 99 /* TrueKeyword */: + case 100 /* TrueKeyword */: return trueType; - case 84 /* FalseKeyword */: + case 85 /* FalseKeyword */: return falseType; } } @@ -34099,19 +37878,19 @@ var ts; return links.resolvedType; } function isTypeAssertion(node) { - node = skipParenthesizedNodes(node); - return node.kind === 177 /* TypeAssertionExpression */ || node.kind === 195 /* AsExpression */; + node = ts.skipParentheses(node); + return node.kind === 182 /* TypeAssertionExpression */ || node.kind === 200 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var type = checkExpressionCached(declaration.initializer); return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672 /* TypeVariable */) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); // If the type parameter is constrained to the base primitive type we're checking for, // consider this a literal context. For example, given a type parameter 'T extends string', // this causes us to infer string literal types for T. @@ -34120,7 +37899,7 @@ var ts; } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, 480 /* Literal */); + return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); } return false; } @@ -34132,7 +37911,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, contextualMapper); @@ -34143,7 +37922,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -34164,6 +37943,23 @@ var ts; } return type; } + // Returns the type of an expression. Unlike checkExpression, this function is simply concerned + // with computing the type and may not fully check all contained sub-expressions for errors. + function getTypeOfExpression(node) { + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (node.kind === 179 /* CallExpression */ && node.expression.kind !== 96 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -34173,7 +37969,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, contextualMapper) { var type; - if (node.kind === 139 /* QualifiedName */) { + if (node.kind === 141 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -34185,9 +37981,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -34196,79 +37992,79 @@ var ts; } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return checkIdentifier(node); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: return checkThisExpression(node); - case 95 /* SuperKeyword */: + case 96 /* SuperKeyword */: return checkSuperExpression(node); - case 93 /* NullKeyword */: + case 94 /* NullKeyword */: return nullWideningType; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return checkLiteralExpression(node); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: return checkTemplateExpression(node); - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return stringType; - case 10 /* RegularExpressionLiteral */: + case 11 /* RegularExpressionLiteral */: return globalRegExpType; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return checkCallExpression(node); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return checkClassExpression(node); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return checkAssertion(node); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return checkNonNullAssertion(node); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return checkDeleteExpression(node); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return checkVoidExpression(node); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return checkAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 191 /* SpreadElementExpression */: - return checkSpreadElementExpression(node, contextualMapper); - case 193 /* OmittedExpression */: + case 196 /* SpreadElement */: + return checkSpreadExpression(node, contextualMapper); + case 198 /* OmittedExpression */: return undefinedWideningType; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return checkYieldExpression(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return checkJsxExpression(node); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return checkJsxElement(node); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -34296,7 +38092,7 @@ var ts; var func = ts.getContainingFunction(node); if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 148 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 150 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -34307,7 +38103,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); } - if (func.kind === 148 /* Constructor */ || func.kind === 152 /* ConstructSignature */ || func.kind === 157 /* ConstructorType */) { + if (func.kind === 150 /* Constructor */ || func.kind === 154 /* ConstructSignature */ || func.kind === 159 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -34321,15 +38117,15 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 147 /* MethodDeclaration */ || - node.kind === 220 /* FunctionDeclaration */ || - node.kind === 179 /* FunctionExpression */; + return node.kind === 149 /* MethodDeclaration */ || + node.kind === 225 /* FunctionDeclaration */ || + node.kind === 184 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 69 /* Identifier */ && + if (param.name.kind === 70 /* Identifier */ && param.name.text === parameter.text) { return i; } @@ -34366,9 +38162,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_18 = _a[_i].name; - if (ts.isBindingPattern(name_18) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -34381,16 +38177,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 180 /* ArrowFunction */: - case 151 /* CallSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 156 /* FunctionType */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + case 185 /* ArrowFunction */: + case 153 /* CallSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 158 /* FunctionType */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + var parent_9 = node.parent; + if (node === parent_9.type) { + return parent_9; } } } @@ -34400,15 +38196,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_19 = element.name; - if (name_19.kind === 69 /* Identifier */ && - name_19.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 70 /* Identifier */ && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_19.kind === 168 /* ArrayBindingPattern */ || - name_19.kind === 167 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 173 /* ArrayBindingPattern */ || + name_22.kind === 172 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -34416,14 +38212,20 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 156 /* FunctionType */ || node.kind === 220 /* FunctionDeclaration */ || node.kind === 157 /* ConstructorType */ || - node.kind === 151 /* CallSignature */ || node.kind === 148 /* Constructor */ || - node.kind === 152 /* ConstructSignature */) { + else if (node.kind === 158 /* FunctionType */ || node.kind === 225 /* FunctionDeclaration */ || node.kind === 159 /* ConstructorType */ || + node.kind === 153 /* CallSignature */ || node.kind === 150 /* Constructor */ || + node.kind === 154 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } + if (ts.isAsyncFunctionLike(node) && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { @@ -34433,16 +38235,16 @@ var ts; checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } if (node.type) { - if (languageVersion >= 2 /* ES6 */ && isSyntacticallyValidGenerator(node)) { + if (languageVersion >= 2 /* ES2015 */ && isSyntacticallyValidGenerator(node)) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34479,7 +38281,7 @@ var ts; var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { + if (member.kind === 150 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { @@ -34488,18 +38290,18 @@ var ts; } } else { - var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 113 /* StaticKeyword */; }); + var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114 /* StaticKeyword */; }); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: addName(names, member.name, memberName, 1 /* Getter */); break; - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: addName(names, member.name, memberName, 2 /* Setter */); break; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: addName(names, member.name, memberName, 3 /* Property */); break; } @@ -34525,12 +38327,12 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind == 144 /* PropertySignature */) { + if (member.kind == 146 /* PropertySignature */) { var memberName = void 0; switch (member.name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 69 /* Identifier */: + case 70 /* Identifier */: memberName = member.name.text; break; default: @@ -34547,7 +38349,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 222 /* InterfaceDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -34567,7 +38369,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -34575,7 +38377,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -34628,7 +38430,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34640,15 +38442,15 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function markThisReferencesAsErrors(n) { - if (n.kind === 97 /* ThisKeyword */) { + if (n.kind === 98 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 179 /* FunctionExpression */ && n.kind !== 220 /* FunctionDeclaration */) { + else if (n.kind !== 184 /* FunctionExpression */ && n.kind !== 225 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 145 /* PropertyDeclaration */ && + return n.kind === 147 /* PropertyDeclaration */ && !(ts.getModifierFlags(n) & 32 /* Static */) && !!n.initializer; } @@ -34657,6 +38459,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34675,9 +38478,9 @@ var ts; if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -34701,7 +38504,7 @@ var ts; checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 149 /* GetAccessor */) { + if (node.kind === 151 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -34711,13 +38514,13 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; + var otherKind = node.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { @@ -34733,11 +38536,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149 /* GetAccessor */) { + if (node.kind === 151 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { + if (node.parent.kind !== 176 /* ObjectLiteralExpression */) { checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); } @@ -34767,7 +38570,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -34820,6 +38623,17 @@ var ts; function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node) { + getTypeFromIndexedAccessTypeNode(node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } function isPrivateWithinAmbient(node) { return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); } @@ -34827,9 +38641,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 222 /* InterfaceDeclaration */ && - n.parent.kind !== 221 /* ClassDeclaration */ && - n.parent.kind !== 192 /* ClassExpression */ && + if (n.parent.kind !== 227 /* InterfaceDeclaration */ && + n.parent.kind !== 226 /* ClassDeclaration */ && + n.parent.kind !== 197 /* ClassExpression */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported @@ -34917,7 +38731,7 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && + var reportError = (node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */) && (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -34956,7 +38770,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 222 /* InterfaceDeclaration */ || node.parent.kind === 159 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 227 /* InterfaceDeclaration */ || node.parent.kind === 161 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -34967,7 +38781,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 220 /* FunctionDeclaration */ || node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */ || node.kind === 148 /* Constructor */) { + if (node.kind === 225 /* FunctionDeclaration */ || node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */ || node.kind === 150 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -35089,20 +38903,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 229 /* ImportEqualsDeclaration */: - var result_2 = 0; + case 234 /* ImportEqualsDeclaration */: + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; default: return 1048576 /* ExportValue */; } @@ -35139,7 +38953,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072 /* Reference */) { + if (getObjectFlags(promise) & 4 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -35157,7 +38971,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -35183,7 +38997,7 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -35262,56 +39076,19 @@ var ts; } } /** - * Checks that the return type provided is an instantiation of the global Promise type - * and returns the awaited type of the return type. + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. * - * @param returnType The return type of a FunctionLikeDeclaration - * @param location The node on which to report the error. + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check */ - function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { - if (returnType === unknownType) { - // The return type already had some other error, so we ignore and return - // the unknown type. - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - // Either we couldn't resolve the global promise type, which would have already - // reported an error, or we could resolve it and the return type is a valid type - // reference to the global type. In either case, we return the awaited type for - // the return type. - return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - // The promise type was not a valid type reference to the global promise type, so we - // report an error and return the unknown type. - error(location, diagnostic, typeName); - return unknownType; - } - /** - * Checks the return type of an async function to ensure it is a compatible - * Promise implementation. - * @param node The signature to check - * @param returnType The return type for the function - * @remarks - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. - */ function checkAsyncFunctionReturnType(node) { - if (languageVersion >= 2 /* ES6 */) { - var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - // If we couldn't resolve the global PromiseConstructorLike type we cannot verify - // compatibility with __awaiter. - return unknownType; - } // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -35336,39 +39113,56 @@ var ts; // then(...): Promise; // } // - // When we get the type of the `Promise` symbol here, we get the type of the static - // side of the `Promise` class, which would be `{ new (...): Promise }`. - var promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - // If we are compiling with isolatedModules, we may not be able to resolve the - // type as a value. As such, we will just return unknownType; - return unknownType; + var returnType = getTypeFromTypeNode(node.type); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } - var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - // try to fall back to global promise type. - var typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } - // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. - checkReturnTypeAnnotationAsExpression(node); - // Validate the promise constructor type. - var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } - // Verify there is no local declaration that could collide with the promise constructor. - var promiseName = ts.getEntityNameFromTypeNode(node.type); - var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); - return unknownType; + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(node.type); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.text, 107455 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } } // Get and return the awaited type of the return type. - return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } /** Check a decorator */ function checkDecorator(node) { @@ -35381,22 +39175,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 142 /* Parameter */: + case 144 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -35404,44 +39198,24 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } - /** Checks a type reference node as an expression. */ - function checkTypeNodeAsExpression(node) { - // When we are emitting type metadata for decorators, we need to try to check the type - // as if it were an expression so that we can emit the type in a value position when we - // serialize the type metadata. - if (node && node.kind === 155 /* TypeReference */) { - var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; - // Resolve type so we know which symbol is referenced - var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - // Resolved symbol is alias - if (rootSymbol && rootSymbol.flags & 8388608 /* Alias */) { - var aliasTarget = resolveAlias(rootSymbol); - // If alias has value symbol - mark alias as referenced - if (aliasTarget.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } - } - } /** - * Checks the type annotation of an accessor declaration or property declaration as - * an expression if it is a type reference to a type with a value declaration. - */ - function checkTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkReturnTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ - function checkParameterTypeAnnotationsAsExpressions(node) { - // ensure all type annotations with a value declaration are checked as an expression - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - checkTypeAnnotationAsExpression(parameter); + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + var typeName = node && ts.getEntityNameFromTypeNode(node); + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 70 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (rootSymbol + && rootSymbol.flags & 8388608 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } /** Check the decorators of a node */ function checkDecorators(node) { if (!node.decorators) { @@ -35455,24 +39229,38 @@ var ts; if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 144 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markTypeNodeAsReferenced(node.type); break; - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: - checkTypeAnnotationAsExpression(node); + case 147 /* PropertyDeclaration */: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + case 144 /* Parameter */: + markTypeNodeAsReferenced(node.type); break; } } @@ -35494,7 +39282,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 142 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -35554,43 +39342,43 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 256 /* SourceFile */: - case 225 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 230 /* ModuleDeclaration */: checkUnusedModuleMembers(node); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: checkUnusedTypeParameters(node); break; - case 199 /* Block */: - case 227 /* CaseBlock */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: checkUnusedLocalsAndParameters(node); break; - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: checkUnusedTypeParameters(node); break; } @@ -35599,46 +39387,66 @@ var ts; } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function (key) { + if (node.parent.kind !== 227 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + var _loop_2 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local.valueDeclaration; + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144 /* Parameter */) { + var parameter = ts.getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !ts.parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); } } }; for (var key in node.locals) { - _loop_1(key); + _loop_2(key); } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; } - function parameterNameStartsWithUnderscore(parameter) { - return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 223 /* VariableDeclaration */ && + (declaration.parent.parent.kind === 212 /* ForInStatement */ || + declaration.parent.parent.kind === 213 /* ForOfStatement */)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 70 /* Identifier */ && node.text.charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 145 /* PropertyDeclaration */) { + if (member.kind === 149 /* MethodDeclaration */ || member.kind === 147 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } - else if (member.kind === 148 /* Constructor */) { + else if (member.kind === 150 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { @@ -35686,7 +39494,7 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 199 /* Block */) { + if (node.kind === 204 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -35709,12 +39517,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 144 /* PropertySignature */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 146 /* MethodSignature */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 146 /* PropertySignature */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 148 /* MethodSignature */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -35723,7 +39531,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 142 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 144 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -35739,7 +39547,7 @@ var ts; var current = node; while (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 69 /* Identifier */; + var isDeclaration_1 = node.kind !== 70 /* Identifier */; if (isDeclaration_1) { error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -35762,7 +39570,7 @@ var ts; return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_2 = node.kind !== 69 /* Identifier */; + var isDeclaration_2 = node.kind !== 70 /* Identifier */; if (isDeclaration_2) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -35772,31 +39580,35 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 225 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 225 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192 /* HasAsyncFunctions */) { + if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -35831,7 +39643,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 218 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 223 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -35841,24 +39653,24 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 200 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 205 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 199 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 226 /* ModuleBlock */ || - container.kind === 225 /* ModuleDeclaration */ || - container.kind === 256 /* SourceFile */); + (container.kind === 204 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 231 /* ModuleBlock */ || + container.kind === 230 /* ModuleDeclaration */ || + container.kind === 261 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_20 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -35866,7 +39678,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 142 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 144 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -35877,11 +39689,11 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 172 /* PropertyAccessExpression */) { + if (n.kind === 177 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 69 /* Identifier */) { + else if (n.kind === 70 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name var symbol = resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -35896,7 +39708,7 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 142 /* Parameter */) { + if (symbol.valueDeclaration.kind === 144 /* Parameter */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -35910,7 +39722,7 @@ var ts; } // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - if (current.parent.kind === 145 /* PropertyDeclaration */ && + if (current.parent.kind === 147 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)) { return; @@ -35926,6 +39738,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35934,24 +39749,28 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 169 /* BindingElement */) { + if (node.kind === 174 /* BindingElement */) { + if (node.parent.kind === 172 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 140 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_21 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_10 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_10); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_24)); + markPropertyAsReferenced(property); + if (parent_10.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35959,25 +39778,25 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 142 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 144 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 207 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 207 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -35985,7 +39804,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -35997,10 +39816,10 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */) { + if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) { + if (node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -36010,8 +39829,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 142 /* Parameter */ && right.kind === 218 /* VariableDeclaration */) || - (left.kind === 218 /* VariableDeclaration */ && right.kind === 142 /* Parameter */)) { + if ((left.kind === 144 /* Parameter */ && right.kind === 223 /* VariableDeclaration */) || + (left.kind === 223 /* VariableDeclaration */ && right.kind === 144 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -36041,7 +39860,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 176 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -36062,7 +39881,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 201 /* EmptyStatement */) { + if (node.thenStatement.kind === 206 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -36082,12 +39901,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 224 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -36110,14 +39929,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { + if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -36125,8 +39944,7 @@ var ts; } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); // iteratedType will be undefined if the rightType was missing properties/signatures // required to get its iteratedType (like [Symbol.iterator] or next). This may be // because we accessed properties from anyType, or it may have led to an error inside @@ -36144,12 +39962,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -36163,21 +39982,20 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { + if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -36201,7 +40019,7 @@ var ts; if (isTypeAny(inputType)) { return inputType; } - if (languageVersion >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES2015 */) { return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { @@ -36259,7 +40077,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -36300,7 +40118,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -36337,7 +40155,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -36361,14 +40179,18 @@ var ts; * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable). */ function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { - ts.Debug.assert(languageVersion < 2 /* ES6 */); - // After we remove all types that are StringLike, we will know if there was a string constituent - // based on whether the remaining type is the same as the initial type. + ts.Debug.assert(languageVersion < 2 /* ES2015 */); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); + if (arrayOrStringType.flags & 65536 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = arrayOrStringType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + } } - else if (arrayOrStringType.flags & 34 /* StringLike */) { + else if (arrayOrStringType.flags & 262178 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -36400,7 +40222,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 34 /* StringLike */) { + if (arrayElementType.flags & 262178 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); @@ -36413,7 +40235,7 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 149 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 150 /* SetAccessor */))); + return !!(node.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; @@ -36440,12 +40262,12 @@ var ts; // for generators. return; } - if (func.kind === 150 /* SetAccessor */) { + if (func.kind === 152 /* SetAccessor */) { if (node.expression) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 148 /* Constructor */) { + else if (func.kind === 150 /* Constructor */) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -36466,7 +40288,7 @@ var ts; } } } - else if (func.kind !== 148 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 150 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -36475,12 +40297,17 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 262144 /* AwaitContext */) { + if (node.flags & 16384 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -36488,9 +40315,10 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 250 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 254 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -36502,15 +40330,21 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 249 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 253 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. var caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -36527,7 +40361,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 214 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 219 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -36557,22 +40391,20 @@ var ts; if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== 69 /* Identifier */) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = catchClause.variableDeclaration.name.text; - var locals = catchClause.block.locals; - if (locals) { - var localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + var blockLocals = catchClause.block.locals; + if (blockLocals) { + for (var caughtName in catchClause.locals) { + var blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -36594,7 +40426,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -36613,7 +40445,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 65536 /* Interface */)) { + if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -36632,13 +40464,13 @@ var ts; // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (prop.valueDeclaration.name.kind === 140 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 142 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536 /* Interface */) { + else if (getObjectFlags(containingType) & 2 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -36690,7 +40522,7 @@ var ts; var firstDecl; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 /* ClassDeclaration */ || declaration.kind === 222 /* InterfaceDeclaration */) { + if (declaration.kind === 226 /* ClassDeclaration */ || declaration.kind === 227 /* InterfaceDeclaration */) { if (!firstDecl) { firstDecl = declaration; } @@ -36736,6 +40568,9 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */ && !ts.isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType_1 = baseTypes[0]; @@ -36753,7 +40588,9 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (baseType_1.symbol.valueDeclaration && + !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) && + baseType_1.symbol.valueDeclaration.kind === 226 /* ClassDeclaration */) { if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -36782,8 +40619,8 @@ var ts; if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; - if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { + var declaredType = getObjectFlags(t) & 4 /* Reference */ ? t.target : t; + if (getObjectFlags(declaredType) & 3 /* ClassOrInterface */) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -36805,7 +40642,7 @@ var ts; if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -36854,7 +40691,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 192 /* ClassExpression */) { + if (derivedClassDecl.kind === 197 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -36902,7 +40739,7 @@ var ts; } } function isAccessor(kind) { - return kind === 149 /* GetAccessor */ || kind === 150 /* SetAccessor */; + return kind === 151 /* GetAccessor */ || kind === 152 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -36943,8 +40780,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var prop = properties_5[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen[prop.name]; if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; @@ -36974,7 +40811,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(node, symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 222 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -37005,6 +40842,7 @@ var ts; // Grammar checking checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } function computeEnumMemberValues(node) { @@ -37021,7 +40859,7 @@ var ts; error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - var text = getTextOfPropertyName(member.name); + var text = ts.getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -37080,18 +40918,18 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; } switch (e.operator) { - case 35 /* PlusToken */: return value_1; - case 36 /* MinusToken */: return -value_1; - case 50 /* TildeToken */: return ~value_1; + case 36 /* PlusToken */: return value_1; + case 37 /* MinusToken */: return -value_1; + case 51 /* TildeToken */: return ~value_1; } return undefined; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -37101,31 +40939,31 @@ var ts; return undefined; } switch (e.operatorToken.kind) { - case 47 /* BarToken */: return left | right; - case 46 /* AmpersandToken */: return left & right; - case 44 /* GreaterThanGreaterThanToken */: return left >> right; - case 45 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 43 /* LessThanLessThanToken */: return left << right; - case 48 /* CaretToken */: return left ^ right; - case 37 /* AsteriskToken */: return left * right; - case 39 /* SlashToken */: return left / right; - case 35 /* PlusToken */: return left + right; - case 36 /* MinusToken */: return left - right; - case 40 /* PercentToken */: return left % right; + case 48 /* BarToken */: return left | right; + case 47 /* AmpersandToken */: return left & right; + case 45 /* GreaterThanGreaterThanToken */: return left >> right; + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 44 /* LessThanLessThanToken */: return left << right; + case 49 /* CaretToken */: return left ^ right; + case 38 /* AsteriskToken */: return left * right; + case 40 /* SlashToken */: return left / right; + case 36 /* PlusToken */: return left + right; + case 37 /* MinusToken */: return left - right; + case 41 /* PercentToken */: return left % right; } return undefined; case 8 /* NumericLiteral */: return +e.text; - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return evalConstant(e.expression); - case 69 /* Identifier */: - case 173 /* ElementAccessExpression */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 178 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; var propertyName = void 0; - if (e.kind === 69 /* Identifier */) { + if (e.kind === 70 /* Identifier */) { // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. // instead pick current enum type and later try to fetch member from the type enumType_1 = currentType; @@ -37133,7 +40971,7 @@ var ts; } else { var expression = void 0; - if (e.kind === 173 /* ElementAccessExpression */) { + if (e.kind === 178 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -37148,17 +40986,17 @@ var ts; // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName var current = expression; while (current) { - if (current.kind === 69 /* Identifier */) { + if (current.kind === 70 /* Identifier */) { break; } - else if (current.kind === 172 /* PropertyAccessExpression */) { + else if (current.kind === 177 /* PropertyAccessExpression */) { current = current.expression; } else { return undefined; } } - enumType_1 = checkExpression(expression); + enumType_1 = getTypeOfExpression(expression); // allow references to constant members of other enums if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { return undefined; @@ -37223,7 +41061,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 224 /* EnumDeclaration */) { + if (declaration.kind !== 229 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -37246,8 +41084,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 221 /* ClassDeclaration */ || - (declaration.kind === 220 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 226 /* ClassDeclaration */ || + (declaration.kind === 225 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -37288,9 +41126,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37309,7 +41149,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 221 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 226 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -37360,26 +41200,26 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 241 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 235 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - var name_22 = node.name; - if (ts.isBindingPattern(name_22)) { - for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { + case 174 /* BindingElement */: + case 223 /* VariableDeclaration */: + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); @@ -37387,12 +41227,12 @@ var ts; break; } // fallthrough - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 220 /* FunctionDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 225 /* FunctionDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -37413,17 +41253,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return node; - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 69 /* Identifier */); + } while (node.kind !== 70 /* Identifier */); return node; - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 69 /* Identifier */); + } while (node.kind !== 70 /* Identifier */); return node; } } @@ -37433,9 +41273,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 226 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 236 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 241 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -37468,7 +41308,7 @@ var ts; (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 238 /* ExportSpecifier */ ? + var message = node.kind === 243 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -37496,7 +41336,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 237 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -37533,7 +41373,7 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.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); } @@ -37553,8 +41393,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 226 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -37568,9 +41408,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 261 /* SourceFile */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 230 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37592,8 +41434,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 256 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 225 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 261 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 230 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -37601,7 +41443,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { markExportAsReferenced(node); } else { @@ -37609,7 +41451,7 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES6) { + if (modulekind === ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -37668,7 +41510,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 225 /* FunctionDeclaration */ && declaration.kind !== 149 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -37680,118 +41523,123 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return checkTypeParameter(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return checkParameter(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return checkPropertyDeclaration(node); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return checkSignatureDeclaration(node); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return checkMethodDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return checkConstructorDeclaration(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return checkAccessorDeclaration(node); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return checkTypeReferenceNode(node); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return checkTypePredicate(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return checkTypeQuery(node); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return checkTypeLiteral(node); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return checkArrayType(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return checkTupleType(node); - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: + case 168 /* TypeOperator */: return checkSourceElement(node.type); - case 220 /* FunctionDeclaration */: + case 169 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 170 /* MappedType */: + return checkMappedType(node); + case 225 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 199 /* Block */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return checkBlock(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return checkVariableStatement(node); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return checkExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return checkIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return checkDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return checkWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return checkForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return checkForInStatement(node); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return checkForOfStatement(node); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return checkReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return checkWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return checkSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return checkLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return checkThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return checkTryStatement(node); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return checkBindingElement(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return checkClassDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return checkImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return checkExportDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return checkExportAssignment(node); - case 201 /* EmptyStatement */: + case 206 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -37813,17 +41661,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: checkAccessorDeferred(node); break; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: checkClassExpressionDeferred(node); break; } @@ -37885,9 +41733,29 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); } @@ -37904,7 +41772,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 212 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 217 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -37927,25 +41795,25 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -37954,7 +41822,7 @@ var ts; copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -37997,34 +41865,34 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 69 /* Identifier */ && + return name.kind === 70 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 141 /* TypeParameter */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: + case 143 /* TypeParameter */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: return true; } } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 139 /* QualifiedName */) { + while (node.parent && node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } - return node.parent && (node.parent.kind === 155 /* TypeReference */ || node.parent.kind === 267 /* JSDocTypeReference */); + return node.parent && (node.parent.kind === 157 /* TypeReference */ || node.parent.kind === 272 /* JSDocTypeReference */); } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 172 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 177 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 194 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 199 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -38041,13 +41909,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 139 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 141 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 229 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 234 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 235 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 240 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -38059,7 +41927,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 172 /* PropertyAccessExpression */) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177 /* PropertyAccessExpression */) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: @@ -38071,15 +41939,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 240 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + if (entityName.kind !== 177 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 234 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -38087,7 +41955,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 199 /* ExpressionWithTypeArguments */) { meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -38105,20 +41973,20 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 69 /* Identifier */) { + if (entityName.kind === 70 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 172 /* PropertyAccessExpression */) { + else if (entityName.kind === 177 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 139 /* QualifiedName */) { + else if (entityName.kind === 141 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -38127,20 +41995,20 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = (entityName.parent.kind === 157 /* TypeReference */ || entityName.parent.kind === 272 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 246 /* JsxAttribute */) { + else if (entityName.parent.kind === 250 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 154 /* TypePredicate */) { + if (entityName.parent.kind === 156 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 256 /* SourceFile */) { + if (node.kind === 261 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } if (isInsideWithStatementBody(node)) { @@ -38154,12 +42022,12 @@ var ts; else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 169 /* BindingElement */ && - node.parent.parent.kind === 167 /* ObjectBindingPattern */ && + else if (node.parent.kind === 174 /* BindingElement */ && + node.parent.parent.kind === 172 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -38169,11 +42037,11 @@ var ts; } } switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -38182,15 +42050,15 @@ var ts; } } // fallthrough - case 95 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + case 96 /* SuperKeyword */: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; - case 165 /* ThisType */: + case 167 /* ThisType */: return getTypeFromTypeNode(node).symbol; - case 121 /* ConstructorKeyword */: + case 122 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 148 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 150 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -38198,15 +42066,18 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 230 /* ImportDeclaration */ || node.parent.kind === 236 /* ExportDeclaration */) && + ((node.parent.kind === 235 /* ImportDeclaration */ || node.parent.kind === 241 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = checkExpression(node.parent.expression); + if (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); if (objectType === unknownType) return undefined; var apparentType = getApparentType(objectType); @@ -38222,7 +42093,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 254 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 258 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); } return undefined; @@ -38242,7 +42113,7 @@ var ts; return getTypeFromTypeNode(node); } if (ts.isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the @@ -38284,28 +42155,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 171 /* ObjectLiteralExpression */ || expr.kind === 170 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 176 /* ObjectLiteralExpression */ || expr.kind === 175 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 208 /* ForOfStatement */) { + if (expr.parent.kind === 213 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 187 /* BinaryExpression */) { - var iteratedType = checkExpression(expr.parent.right); + if (expr.parent.kind === 192 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 253 /* PropertyAssignment */) { + if (expr.parent.kind === 257 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 170 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 175 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false) || unknownType; @@ -38322,11 +42193,11 @@ var ts; var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr) { + function getRegularTypeOfExpression(expr) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } /** * Gets either the static or instance type of a class element, based on @@ -38355,9 +42226,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { var symbols_3 = []; - var name_23 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_23); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -38365,6 +42236,10 @@ var ts; return symbols_3; } else if (symbol.flags & 67108864 /* Transient */) { + if (symbol.leftSpread) { + var links = symbol; + return [links.leftSpread, links.rightSpread]; + } var target = void 0; var next = symbol; while (next = getSymbolLinks(next).target) { @@ -38412,7 +42287,7 @@ var ts; } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; - return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. @@ -38437,7 +42312,7 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 261 /* SourceFile */) { var symbolFile = parentSymbol.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -38494,7 +42369,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 199 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 204 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -38540,18 +42415,18 @@ var ts; return true; } switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return node.expression - && node.expression.kind === 69 /* Identifier */ + && node.expression.kind === 70 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -38559,7 +42434,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 261 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -38625,7 +42500,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 255 /* EnumMember */) { + if (node.kind === 260 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -38638,7 +42513,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -38673,7 +42548,7 @@ var ts; else if (isTypeOfKind(type, 340 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34 /* StringLike */)) { + else if (isTypeOfKind(type, 262178 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { @@ -38705,7 +42580,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getTypeOfExpression(expr)); + var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { @@ -38726,9 +42601,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_11 = reference.parent; + if (ts.isDeclaration(parent_11) && reference === parent_11.name) { + location = getDeclarationContainer(parent_11); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38748,7 +42623,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); } return false; } @@ -38802,7 +42677,8 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -38813,7 +42689,7 @@ var ts; // property access can only be used as values // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) + var meaning = (node.kind === 177 /* PropertyAccessExpression */) || (node.kind === 70 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -38839,6 +42715,10 @@ var ts; if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } } } return typeReferenceDirectives; @@ -38852,15 +42732,15 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_12 = getParentOfSymbol(current); + if (parent_12) { + current = parent_12; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 256 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 261 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -38880,7 +42760,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 256 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 261 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -38890,8 +42770,6 @@ var ts; } // Initialize global symbol table var augmentations; - var requestedExternalEmitHelpers = 0; - var firstFileRequestingExternalHelpers; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { @@ -38912,15 +42790,6 @@ var ts; } } } - if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { - var fileRequestedExternalEmitHelpers = file.flags & 31744 /* EmitHelperFlags */; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { // merge module augmentations. @@ -38962,7 +42831,7 @@ var ts; getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); - if (languageVersion >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES2015 */) { getGlobalESSymbolType = ts.memoize(function () { return getGlobalType("Symbol"); }); getGlobalIterableType = ts.memoize(function () { return getGlobalType("Iterable", /*arity*/ 1); }); getGlobalIteratorType = ts.memoize(function () { return getGlobalType("Iterator", /*arity*/ 1); }); @@ -38975,49 +42844,50 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - // If we have specified that we are importing helpers, we should report global - // errors if we cannot resolve the helpers external module, or if it does not have - // the necessary helpers exported. - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - // Find the first reference to the helpers module. - var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, - /*errorNode*/ undefined); - // If we found the module, report errors if it does not have the necessary exports. - if (helpersModule) { - var exports = helpersModule.exports; - if (requestedExternalEmitHelpers & 1024 /* HasClassExtends */ && languageVersion < 2 /* ES6 */) { - verifyHelperSymbol(exports, "__extends", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 16384 /* HasJsxSpreadAttributes */ && compilerOptions.jsx !== 1 /* Preserve */) { - verifyHelperSymbol(exports, "__assign", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 2048 /* HasDecorators */) { - verifyHelperSymbol(exports, "__decorate", 107455 /* Value */); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455 /* Value */); - } - } - if (requestedExternalEmitHelpers & 4096 /* HasParamDecorators */) { - verifyHelperSymbol(exports, "__param", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 8192 /* HasAsyncFunctions */) { - verifyHelperSymbol(exports, "__awaiter", 107455 /* Value */); - if (languageVersion < 2 /* ES6 */) { - verifyHelperSymbol(exports, "__generator", 107455 /* Value */); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 128 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name_27 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name_27), 107455 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_27); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols, name, meaning) { - var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); - if (!symbol) { - error(/*location*/ undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; } } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -39029,7 +42899,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152 /* Anonymous */); + var thenableType = createObjectType(16 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -39042,14 +42912,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 147 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 149 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 149 /* GetAccessor */ || node.kind === 150 /* SetAccessor */) { + else if (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -39066,28 +42936,28 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 128 /* ReadonlyKeyword */) { - if (node.kind === 144 /* PropertySignature */ || node.kind === 146 /* MethodSignature */) { + if (modifier.kind !== 130 /* ReadonlyKeyword */) { + if (node.kind === 146 /* PropertySignature */ || node.kind === 148 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 74 /* ConstKeyword */: - if (node.kind !== 224 /* EnumDeclaration */ && node.parent.kind === 221 /* ClassDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + case 75 /* ConstKeyword */: + if (node.kind !== 229 /* EnumDeclaration */ && node.parent.kind === 226 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75 /* ConstKeyword */)); } break; - case 112 /* PublicKeyword */: - case 111 /* ProtectedKeyword */: - case 110 /* PrivateKeyword */: + case 113 /* PublicKeyword */: + case 112 /* ProtectedKeyword */: + case 111 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 111 /* ProtectedKeyword */) { + if (modifier.kind === 112 /* ProtectedKeyword */) { lastProtected = modifier; } - else if (modifier.kind === 110 /* PrivateKeyword */) { + else if (modifier.kind === 111 /* PrivateKeyword */) { lastPrivate = modifier; } if (flags & 28 /* AccessibilityModifier */) { @@ -39102,11 +42972,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 110 /* PrivateKeyword */) { + if (modifier.kind === 111 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -39115,7 +42985,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 113 /* StaticKeyword */: + case 114 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -39125,10 +42995,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -39137,18 +43007,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 128 /* ReadonlyKeyword */: + case 130 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */ && node.kind !== 153 /* IndexSignature */ && node.kind !== 142 /* Parameter */) { + else if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */ && node.kind !== 155 /* IndexSignature */ && node.kind !== 144 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 82 /* ExportKeyword */: + case 83 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -39161,45 +43031,45 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 122 /* DeclareKeyword */: + case 123 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 226 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 115 /* AbstractKeyword */: + case 116 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 221 /* ClassDeclaration */) { - if (node.kind !== 147 /* MethodDeclaration */ && - node.kind !== 145 /* PropertyDeclaration */ && - node.kind !== 149 /* GetAccessor */ && - node.kind !== 150 /* SetAccessor */) { + if (node.kind !== 226 /* ClassDeclaration */) { + if (node.kind !== 149 /* MethodDeclaration */ && + node.kind !== 147 /* PropertyDeclaration */ && + node.kind !== 151 /* GetAccessor */ && + node.kind !== 152 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + if (!(node.parent.kind === 226 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -39211,14 +43081,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 118 /* AsyncKeyword */: + case 119 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -39226,7 +43096,7 @@ var ts; break; } } - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -39241,13 +43111,13 @@ var ts; } return; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { 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)) { + else if (node.kind === 144 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { 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) { + else if (node.kind === 144 /* 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 */) { @@ -39267,38 +43137,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 155 /* IndexSignature */: + case 230 /* ModuleDeclaration */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 144 /* Parameter */: return false; default: - if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return false; } switch (node.kind) { - case 220 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); - case 221 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 119 /* AsyncKeyword */); + case 226 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 116 /* AbstractKeyword */); + case 227 /* InterfaceDeclaration */: + case 205 /* VariableStatement */: + case 228 /* TypeAliasDeclaration */: return true; - case 224 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); + case 229 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 75 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -39310,10 +43180,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 147 /* MethodDeclaration */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -39329,7 +43199,7 @@ var ts; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } - function checkGrammarTypeParameterList(node, typeParameters, file) { + function checkGrammarTypeParameterList(typeParameters, file) { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -39372,11 +43242,11 @@ var ts; function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 180 /* ArrowFunction */) { + if (node.kind === 185 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -39411,7 +43281,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 132 /* StringKeyword */ && parameter.type.kind !== 130 /* NumberKeyword */) { + if (parameter.type.kind !== 134 /* StringKeyword */ && parameter.type.kind !== 132 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -39437,9 +43307,9 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 193 /* OmittedExpression */) { + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; + if (arg.kind === 198 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -39465,7 +43335,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (heritageClause.token === 84 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -39478,7 +43348,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 107 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -39494,14 +43364,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (heritageClause.token === 84 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 107 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -39512,31 +43382,31 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 140 /* ComputedPropertyName */) { + if (node.kind !== 142 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 187 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 192 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 25 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 220 /* FunctionDeclaration */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 147 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 225 /* FunctionDeclaration */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 149 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); } - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES2015 */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher); } } } - function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + function checkGrammarForInvalidQuestionMark(questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -39549,13 +43419,15 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { - // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_24); + if (prop.kind === 259 /* SpreadAssignment */) { + continue; } - if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + var name_28 = prop.name; + if (name_28.kind === 142 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name_28); + } + if (prop.kind === 258 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -39564,7 +43436,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { + if (mod.kind !== 119 /* AsyncKeyword */ || prop.kind !== 149 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -39578,27 +43450,27 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */) { + if (prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_24.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_24); + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_28.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_28); } currentKind = Property; } - else if (prop.kind === 147 /* MethodDeclaration */) { + else if (prop.kind === 149 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 149 /* GetAccessor */) { + else if (prop.kind === 151 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 150 /* SetAccessor */) { + else if (prop.kind === 152 /* SetAccessor */) { currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_28); if (effectiveName === undefined) { continue; } @@ -39608,18 +43480,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); + grammarErrorOnNode(name_28, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_28)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -39628,19 +43500,19 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 247 /* JsxSpreadAttribute */) { + if (attr.kind === 251 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_25 = jsxAttr.name; - if (!seen[name_25.text]) { - seen[name_25.text] = true; + var name_29 = jsxAttr.name; + if (!seen[name_29.text]) { + seen[name_29.text] = true; } else { - return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_29, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 248 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 252 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -39649,7 +43521,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 219 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 224 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -39664,20 +43536,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -39697,15 +43569,18 @@ var ts; else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } + else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 149 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 151 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 150 /* SetAccessor */) { + else if (kind === 152 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -39728,20 +43603,11 @@ var ts; A get accessor has no parameters or a single `this` parameter. A set accessor has one parameter or a `this` parameter and one more parameter */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -39755,8 +43621,8 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 171 /* ObjectLiteralExpression */) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (node.parent.kind === 176 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -39776,10 +43642,10 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 222 /* InterfaceDeclaration */) { + else if (node.parent.kind === 227 /* InterfaceDeclaration */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } - else if (node.parent.kind === 159 /* TypeLiteral */) { + else if (node.parent.kind === 161 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -39790,11 +43656,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 209 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 214 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -39802,8 +43668,8 @@ var ts; return false; } break; - case 213 /* SwitchStatement */: - if (node.kind === 210 /* BreakStatement */ && !node.label) { + case 218 /* SwitchStatement */: + if (node.kind === 215 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -39818,13 +43684,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 210 /* BreakStatement */ + var message = node.kind === 215 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 210 /* BreakStatement */ + var message = node.kind === 215 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -39834,24 +43700,24 @@ var ts; if (node.dotDotDotToken) { var elements = node.parent.elements; if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 168 /* ArrayBindingPattern */ || node.name.kind === 167 /* ObjectBindingPattern */) { + if (node.name.kind === 173 /* ArrayBindingPattern */ || node.name.kind === 172 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { - // Error on equals token which immediate precedes the initializer + // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 207 /* ForInStatement */ && node.parent.parent.kind !== 208 /* ForOfStatement */) { + if (node.parent.parent.kind !== 212 /* ForInStatement */ && node.parent.parent.kind !== 213 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { if (ts.isConst(node) && !node.type) { @@ -39890,8 +43756,8 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 69 /* Identifier */) { - if (name.originalKeywordKind === 108 /* LetKeyword */) { + if (name.kind === 70 /* Identifier */) { + if (name.originalKeywordKind === 109 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -39916,15 +43782,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: return false; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -39979,7 +43845,7 @@ var ts; return true; } } - else if (node.parent.kind === 222 /* InterfaceDeclaration */) { + else if (node.parent.kind === 227 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -39987,7 +43853,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 159 /* TypeLiteral */) { + else if (node.parent.kind === 161 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -40012,13 +43878,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 222 /* InterfaceDeclaration */ || - node.kind === 223 /* TypeAliasDeclaration */ || - node.kind === 230 /* ImportDeclaration */ || - node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 236 /* ExportDeclaration */ || - node.kind === 235 /* ExportAssignment */ || - node.kind === 228 /* NamespaceExportDeclaration */ || + if (node.kind === 227 /* InterfaceDeclaration */ || + node.kind === 228 /* TypeAliasDeclaration */ || + node.kind === 235 /* ImportDeclaration */ || + node.kind === 234 /* ImportEqualsDeclaration */ || + node.kind === 241 /* ExportDeclaration */ || + node.kind === 240 /* ExportAssignment */ || + node.kind === 233 /* NamespaceExportDeclaration */ || ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -40027,7 +43893,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 200 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 205 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -40053,7 +43919,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 199 /* Block */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 204 /* Block */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -40113,49 +43979,49 @@ var ts; * significantly impacted. */ var nodeEdgeTraversalMap = ts.createMap((_a = {}, - _a[139 /* QualifiedName */] = [ + _a[141 /* QualifiedName */] = [ { name: "left", test: ts.isEntityName }, { name: "right", test: ts.isIdentifier } ], - _a[143 /* Decorator */] = [ + _a[145 /* Decorator */] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[177 /* TypeAssertionExpression */] = [ + _a[182 /* TypeAssertionExpression */] = [ { name: "type", test: ts.isTypeNode }, { name: "expression", test: ts.isUnaryExpression } ], - _a[195 /* AsExpression */] = [ + _a[200 /* AsExpression */] = [ { name: "expression", test: ts.isExpression }, { name: "type", test: ts.isTypeNode } ], - _a[196 /* NonNullExpression */] = [ + _a[201 /* NonNullExpression */] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[224 /* EnumDeclaration */] = [ + _a[229 /* EnumDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "members", test: ts.isEnumMember } ], - _a[225 /* ModuleDeclaration */] = [ + _a[230 /* ModuleDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isModuleName }, { name: "body", test: ts.isModuleBody } ], - _a[226 /* ModuleBlock */] = [ + _a[231 /* ModuleBlock */] = [ { name: "statements", test: ts.isStatement } ], - _a[229 /* ImportEqualsDeclaration */] = [ + _a[234 /* ImportEqualsDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "moduleReference", test: ts.isModuleReference } ], - _a[240 /* ExternalModuleReference */] = [ + _a[245 /* ExternalModuleReference */] = [ { name: "expression", test: ts.isExpression, optional: true } ], - _a[255 /* EnumMember */] = [ + _a[260 /* EnumMember */] = [ { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], @@ -40163,355 +44029,363 @@ var ts; function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } /** * Similar to `reduceLeft`, performs a reduction against each child of a node. * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the * `nodeEdgeTraversalMap` above will be visited. * * @param node The node containing the children to reduce. - * @param f The callback function * @param initial The initial value to supply to the reduction. + * @param f The callback function */ - function reduceEachChild(node, f, initial) { + function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 198 /* SemicolonClassElement */: - case 201 /* EmptyStatement */: - case 193 /* OmittedExpression */: - case 217 /* DebuggerStatement */: - case 287 /* NotEmittedStatement */: + case 203 /* SemicolonClassElement */: + case 206 /* EmptyStatement */: + case 198 /* OmittedExpression */: + case 222 /* DebuggerStatement */: + case 293 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 140 /* ComputedPropertyName */: - result = reduceNode(node.expression, f, result); + case 142 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 142 /* Parameter */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 144 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 143 /* Decorator */: - result = reduceNode(node.expression, f, result); + case 145 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); break; // Type member - case 145 /* PropertyDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 147 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 147 /* MethodDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 149 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 148 /* Constructor */: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + case 150 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; - case 149 /* GetAccessor */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 151 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 150 /* SetAccessor */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + case 152 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - result = ts.reduceLeft(node.elements, f, result); + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 169 /* BindingElement */: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 174 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 170 /* ArrayLiteralExpression */: - result = ts.reduceLeft(node.elements, f, result); + case 175 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 171 /* ObjectLiteralExpression */: - result = ts.reduceLeft(node.properties, f, result); + case 176 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); break; - case 172 /* PropertyAccessExpression */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.name, f, result); + case 177 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; - case 173 /* ElementAccessExpression */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.argumentExpression, f, result); + case 178 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); break; - case 174 /* CallExpression */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + case 179 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); break; - case 175 /* NewExpression */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + case 180 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); break; - case 176 /* TaggedTemplateExpression */: - result = reduceNode(node.tag, f, result); - result = reduceNode(node.template, f, result); + case 181 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNode(node.template, cbNode, result); break; - case 179 /* FunctionExpression */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 184 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 180 /* ArrowFunction */: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 185 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 178 /* ParenthesizedExpression */: - case 181 /* DeleteExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 184 /* AwaitExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: - case 196 /* NonNullExpression */: - result = reduceNode(node.expression, f, result); + case 183 /* ParenthesizedExpression */: + case 186 /* DeleteExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 189 /* AwaitExpression */: + case 195 /* YieldExpression */: + case 196 /* SpreadElement */: + case 201 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); break; - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - result = reduceNode(node.operand, f, result); + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); break; - case 187 /* BinaryExpression */: - result = reduceNode(node.left, f, result); - result = reduceNode(node.right, f, result); + case 192 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); break; - case 188 /* ConditionalExpression */: - result = reduceNode(node.condition, f, result); - result = reduceNode(node.whenTrue, f, result); - result = reduceNode(node.whenFalse, f, result); + case 193 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); break; - case 189 /* TemplateExpression */: - result = reduceNode(node.head, f, result); - result = ts.reduceLeft(node.templateSpans, f, result); + case 194 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 192 /* ClassExpression */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + case 197 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; - case 194 /* ExpressionWithTypeArguments */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); + case 199 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); break; // Misc - case 197 /* TemplateSpan */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.literal, f, result); + case 202 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); break; // Element - case 199 /* Block */: - result = ts.reduceLeft(node.statements, f, result); + case 204 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 200 /* VariableStatement */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.declarationList, f, result); + case 205 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); break; - case 202 /* ExpressionStatement */: - result = reduceNode(node.expression, f, result); + case 207 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); break; - case 203 /* IfStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.thenStatement, f, result); - result = reduceNode(node.elseStatement, f, result); + case 208 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); break; - case 204 /* DoStatement */: - result = reduceNode(node.statement, f, result); - result = reduceNode(node.expression, f, result); + case 209 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 206 /* ForStatement */: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.condition, f, result); - result = reduceNode(node.incrementor, f, result); - result = reduceNode(node.statement, f, result); + case 211 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 211 /* ReturnStatement */: - case 215 /* ThrowStatement */: - result = reduceNode(node.expression, f, result); + case 216 /* ReturnStatement */: + case 220 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); break; - case 213 /* SwitchStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.caseBlock, f, result); + case 218 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); break; - case 214 /* LabeledStatement */: - result = reduceNode(node.label, f, result); - result = reduceNode(node.statement, f, result); + case 219 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 216 /* TryStatement */: - result = reduceNode(node.tryBlock, f, result); - result = reduceNode(node.catchClause, f, result); - result = reduceNode(node.finallyBlock, f, result); + case 221 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); break; - case 218 /* VariableDeclaration */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 223 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 219 /* VariableDeclarationList */: - result = ts.reduceLeft(node.declarations, f, result); + case 224 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); break; - case 220 /* FunctionDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 225 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 221 /* ClassDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + case 226 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; - case 227 /* CaseBlock */: - result = ts.reduceLeft(node.clauses, f, result); + case 232 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); break; - case 230 /* ImportDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.importClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 235 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 231 /* ImportClause */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.namedBindings, f, result); + case 236 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); break; - case 232 /* NamespaceImport */: - result = reduceNode(node.name, f, result); + case 237 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); break; - case 233 /* NamedImports */: - case 237 /* NamedExports */: - result = ts.reduceLeft(node.elements, f, result); + case 238 /* NamedImports */: + case 242 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; - case 235 /* ExportAssignment */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.expression, f, result); + case 240 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; - case 236 /* ExportDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.exportClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 241 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; // JSX - case 241 /* JsxElement */: - result = reduceNode(node.openingElement, f, result); - result = ts.reduceLeft(node.children, f, result); - result = reduceNode(node.closingElement, f, result); + case 246 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); break; - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - result = reduceNode(node.tagName, f, result); - result = ts.reduceLeft(node.attributes, f, result); + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.attributes, cbNodes, result); break; - case 245 /* JsxClosingElement */: - result = reduceNode(node.tagName, f, result); + case 249 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); break; - case 246 /* JsxAttribute */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 250 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 247 /* JsxSpreadAttribute */: - result = reduceNode(node.expression, f, result); + case 251 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); break; - case 248 /* JsxExpression */: - result = reduceNode(node.expression, f, result); + case 252 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 249 /* CaseClause */: - result = reduceNode(node.expression, f, result); + case 253 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); // fall-through - case 250 /* DefaultClause */: - result = ts.reduceLeft(node.statements, f, result); + case 254 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 251 /* HeritageClause */: - result = ts.reduceLeft(node.types, f, result); + case 255 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); break; - case 252 /* CatchClause */: - result = reduceNode(node.variableDeclaration, f, result); - result = reduceNode(node.block, f, result); + case 256 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 253 /* PropertyAssignment */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 257 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 254 /* ShorthandPropertyAssignment */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.objectAssignmentInitializer, f, result); + case 258 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 259 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); break; // Top-level nodes - case 256 /* SourceFile */: - result = ts.reduceLeft(node.statements, f, result); + case 261 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 288 /* PartiallyEmittedExpression */: - result = reduceNode(node.expression, f, result); + case 294 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); break; default: var edgeTraversalPath = nodeEdgeTraversalMap[kind]; @@ -40521,8 +44395,8 @@ var ts; var value = node[edge.name]; if (value !== undefined) { result = ts.isArray(value) - ? ts.reduceLeft(value, f, result) - : f(result, value); + ? reduceNodes(value, cbNodes, result) + : cbNode(result, value); } } } @@ -40532,9 +44406,10 @@ var ts; } ts.reduceEachChild = reduceEachChild; function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); var visited = visitor(node); if (visited === node) { return node; @@ -40583,6 +44458,7 @@ var ts; // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; + aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -40615,198 +44491,236 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.createNodeArray(ts.concatenate(statements, declarations), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context) { + context.startLexicalEnvironment(); + var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; function visitEachChild(node, visitor, context) { if (node === undefined) { return undefined; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) { return node; } // We do not yet support types. - if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) { return node; } switch (node.kind) { - case 198 /* SemicolonClassElement */: - case 201 /* EmptyStatement */: - case 193 /* OmittedExpression */: - case 217 /* DebuggerStatement */: + case 203 /* SemicolonClassElement */: + case 206 /* EmptyStatement */: + case 198 /* OmittedExpression */: + case 222 /* DebuggerStatement */: // No need to visit nodes with no children. return node; // Names - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 142 /* Parameter */: - return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 144 /* Parameter */: + return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); // Type member - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); - case 147 /* MethodDeclaration */: - return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 148 /* Constructor */: - return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 149 /* GetAccessor */: - return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 150 /* SetAccessor */: - return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 149 /* MethodDeclaration */: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 150 /* Constructor */: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 151 /* GetAccessor */: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 152 /* SetAccessor */: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); // Binding patterns - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); - case 169 /* BindingElement */: - return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 174 /* BindingElement */: + return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); // Expression - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); - case 178 /* ParenthesizedExpression */: + case 181 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 183 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 179 /* FunctionExpression */: - return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 180 /* ArrowFunction */: - return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, /*optional*/ true), context.endLexicalEnvironment())); - case 181 /* DeleteExpression */: + case 184 /* FunctionExpression */: + return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 185 /* ArrowFunction */: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 186 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); - case 190 /* YieldExpression */: + case 194 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 195 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc - case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + case 202 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 199 /* Block */: + case 204 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, /*optional*/ true, liftToBlock)); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true)); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, /*optional*/ true), visitNode(node.finallyBlock, visitor, ts.isBlock, /*optional*/ true)); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); - case 220 /* FunctionDeclaration */: - return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 221 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 226 /* ClassDeclaration */: return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true)); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 233 /* NamedImports */: + case 238 /* NamedImports */: return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, /*optional*/ true)); - case 237 /* NamedExports */: + case 242 /* NamedExports */: return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); // JSX - case 241 /* JsxElement */: + case 246 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 249 /* CaseClause */: + case 253 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 259 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Top-level nodes - case 256 /* SourceFile */: - context.startLexicalEnvironment(); - return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + case 261 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); default: var updated = void 0; @@ -40835,6 +44749,15 @@ var ts; // return node; } ts.visitEachChild = visitEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.createNodeArray(ts.concatenate(statements, declarations), statements) + : ts.addRange(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function mergeFunctionBodyLexicalEnvironment(body, declarations) { if (body && declarations !== undefined && declarations.length > 0) { if (ts.isBlock(body)) { @@ -40887,13 +44810,25 @@ var ts; if (node === undefined) { return 0 /* None */; } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } - else { - var subtreeFlags = aggregateTransformFlagsForSubtree(node); - return ts.computeTransformFlagsForNode(node, subtreeFlags); + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; } /** * Aggregates the transform flags for the subtree of a node. @@ -40905,84 +44840,41 @@ var ts; return 0 /* None */; } // Aggregate the transform flags of each child. - return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0 /* None */); + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } /** * Aggregates the TransformFlags of a child node with the TransformFlags of its * siblings. */ - function aggregateTransformFlagsForChildNode(transformFlags, child) { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 170 /* ArrayLiteralExpression */: - return 537133909 /* ArrayLiteralOrCallOrNewExcludes */; - case 225 /* ModuleDeclaration */: - return 546335573 /* ModuleExcludes */; - case 142 /* Parameter */: - return 538968917 /* ParameterExcludes */; - case 180 /* ArrowFunction */: - return 550710101 /* ArrowFunctionExcludes */; - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - return 550726485 /* FunctionExcludes */; - case 219 /* VariableDeclarationList */: - return 538968917 /* VariableDeclarationListExcludes */; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - return 537590613 /* ClassExcludes */; - case 148 /* Constructor */: - return 550593365 /* ConstructorExcludes */; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return 550593365 /* MethodOrAccessorExcludes */; - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 141 /* TypeParameter */: - case 144 /* PropertySignature */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 171 /* ObjectLiteralExpression */: - return 537430869 /* ObjectLiteralExcludes */; - default: - return 536871765 /* NodeExcludes */; - } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } var Debug; (function (Debug) { Debug.failNotOptional = Debug.shouldAssert(1 /* Normal */) ? function (message) { return Debug.assert(false, message || "Node not optional."); } - : function (message) { }; + : ts.noop; Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } - : function (node, message) { }; + : ts.noop; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; Debug.assertNode = Debug.shouldAssert(1 /* Normal */) ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } - : function (node, test, message) { }; + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + : ts.noop; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -41004,334 +44896,348 @@ var ts; /*@internal*/ var ts; (function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); /** - * Flattens a destructuring assignment expression. + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. * - * @param root The destructuring assignment expression. - * @param needsValue Indicates whether the value from the right-hand-side of the - * destructuring assignment is needed as part of a larger expression. - * @param recordTempVariable A callback used to record new temporary variables. - * @param visitor An optional visitor to use to visit expressions. + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. */ - function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { - if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { - var right = node.right; - if (ts.isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; - var value = node.right; - var expressions = []; - if (needsValue) { - // If the right-hand value of the destructuring assignment needs to be preserved (as - // is the case when the destructuring assignmen) is part of a larger expression), - // then we need to cache the right-hand value. - // - // The source map location for the assignment should point to the entire binary - // expression. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor); + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - else if (ts.nodeIsSynthesized(node)) { - // Generally, the source map location for a destructuring assignment is the root - // expression. - // - // However, if the root expression is synthesized (as in the case - // of the initializer when transforming a ForOfStatement), then the source map - // location should point to the right-hand value of the expression. - location = value; + var expressions; + var flattenContext = { + context: context, + level: level, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); - if (needsValue) { + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } expressions.push(value); } - var expression = ts.inlineExpressions(expressions); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location) { - var expression = ts.createAssignment(name, value, location); + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); - expressions.push(expression); + expressions = ts.append(expressions, expression); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location); + expression.original = original; + emitExpression(expression); } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; /** - * Flattens binding patterns in a parameter declaration. + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * - * @param node The ParameterDeclaration to flatten. - * @param value The rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. */ - function flattenParameterDestructuring(context, node, value, visitor) { + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + var pendingExpressions; + var pendingDeclarations = []; var declarations = []; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + var flattenContext = { + context: context, + level: level, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_30 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_30, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2); + variable.original = original; + if (ts.isIdentifier(name_30)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } return declarations; - function emitAssignment(name, value, location) { - var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); - ts.aggregateTransformFlags(declaration); - declarations.push(declaration); + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(/*recordTempVariable*/ undefined); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); } } - ts.flattenParameterDestructuring = flattenParameterDestructuring; + ts.flattenDestructuringBinding = flattenDestructuringBinding; /** - * Flattens binding patterns in a variable declaration. + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. * - * @param node The VariableDeclaration to flatten. - * @param value An optional rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. */ - function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { - var declarations = []; - var pendingAssignments; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - return declarations; - function emitAssignment(name, value, location, original) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = ts.inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); - declaration.original = original; - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); - declarations.push(declaration); - ts.aggregateTransformFlags(declaration); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - if (recordTempVariable) { - var assignment = ts.createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, /*original*/ undefined); - } - return name; - } - } - ts.flattenVariableDestructuring = flattenVariableDestructuring; - /** - * Flattens binding patterns in a variable declaration and transforms them into an expression. - * - * @param node The VariableDeclaration to flatten. - * @param recordTempVariable A callback used to record new temporary variables. - * @param nameSubstitution An optional callback used to substitute binding names. - * @param visitor An optional visitor to use to visit expressions. - */ - function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { - var pendingAssignments = []; - flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - var expression = ts.inlineExpressions(pendingAssignments); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location, original) { - var left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, /*original*/ undefined); - return name; - } - function emitPendingAssignment(name, value, location, original) { - var expression = ts.createAssignment(name, value, location); - expression.original = original; - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); - pendingAssignments.push(expression); - return expression; - } - } - ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; - function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { - if (value && visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); - } - if (ts.isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - function emitDestructuringAssignment(bindingTarget, value, location) { - // When emitting target = value use source map node to highlight, including any temporary assignments needed for this - var target; - if (ts.isShorthandPropertyAssignment(bindingTarget)) { - var initializer = visitor - ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) - : bindingTarget.objectAssignmentInitializer; - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - target = bindingTarget.name; - } - else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56 /* EqualsToken */) { - var initializer = visitor - ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) - : bindingTarget.right; - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - if (target.kind === 171 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === 170 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value, location); - } - else { - var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); - emitAssignment(name_26, value, location, /*original*/ undefined); - } - } - function emitObjectLiteralAssignment(target, value, location) { - var properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; - if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { - var propName = p.name; - var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - // Assignment for target = value.propName should highligh whole property, hence use p as source map node - emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, location) { - var elements = target.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var e = elements[i]; - if (e.kind !== 193 /* OmittedExpression */) { - // Assignment for target = value.propName should highligh whole property, hence use e as source map node - if (e.kind !== 191 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); - } - } - } - } - function emitBindingElement(target, value) { - // Any temporary assignments needed to emit target = value should point to target - var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer value = ts.createVoidZero(); } - var name = target.name; - if (ts.isBindingPattern(name)) { - var elements = name.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything other than a single-element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. Additionally, if we have zero elements - // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, - // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (ts.isOmittedExpression(element)) { - continue; - } - else if (name.kind === 167 /* ObjectBindingPattern */) { - // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, ts.createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, ts.createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - function createDefaultValueCheck(value, defaultValue, location) { - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53 /* QuestionToken */), defaultValue, ts.createToken(54 /* ColonToken */), value); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } - /** - * Creates either a PropertyAccessExpression or an ElementAccessExpression for the - * right-hand side of a transformed destructuring assignment. - * - * @param expression The right-hand expression that is the source of the property. - * @param propertyName The destructuring property name. - */ - function createDestructuringPropertyAccess(expression, propertyName) { - if (ts.isComputedPropertyName(propertyName)) { - return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)); - } - else if (ts.isLiteralExpression(propertyName)) { - var clone_2 = ts.getSynthesizedClone(propertyName); - clone_2.text = ts.unescapeIdentifier(clone_2.text); - return ts.createElementAccess(expression, clone_2); - } - else { - if (ts.isGeneratedIdentifier(propertyName)) { - var clone_3 = ts.getSynthesizedClone(propertyName); - clone_3.text = ts.unescapeIdentifier(clone_3.text); - return ts.createPropertyAccess(expression, clone_3); + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); } else { - return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteral(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + return ts.createElementAccess(value, argumentExpression); + } + else { + var name_31 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + return ts.createPropertyAccess(value, name_31); } } /** @@ -41339,24 +45245,75 @@ var ts; * This function is useful to ensure that the expression's value can be read from in subsequent expressions. * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. * + * @param flattenContext Options used to control flattening. * @param value the expression whose value needs to be bound. * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; - * false if it is necessary to always emit an identifier. + * false if it is necessary to always emit an identifier. * @param location The location to use for source maps and comments. - * @param emitTempVariableAssignment A callback used to emit a temporary variable. - * @param visitor An optional callback used to visit the value. */ - function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.createAssignment(temp, value, location)); } - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; } } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*propertyName*/ undefined, /*dotDotDotToken*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]); + } })(ts || (ts = {})); /// /// @@ -41374,13 +45331,11 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; - /** Enables substitutions for async methods with `super` calls. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["AsyncMethodsWithSuper"] = 4] = "AsyncMethodsWithSuper"; /* Enables substitutions for unqualified enum members */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,12 +45346,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(178 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; - var currentSourceFileExternalHelpersModuleName; + var currentScopeFirstDeclarationsOfName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. * They are persisted between each SourceFile transformation and should not be reset. @@ -41412,11 +45370,6 @@ var ts; * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; - /** - * This keeps track of containers where `super` is valid, for use with - * just-in-time substitution for `super` expressions inside of async methods. - */ - var currentSuperContainer; return transformSourceFile; /** * Transform TypeScript-specific syntax in a SourceFile. @@ -41424,7 +45377,14 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - return ts.visitNode(node, visitor, ts.isSourceFile); + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } /** * Visits a node, saving and restoring state variables on the stack. @@ -41434,13 +45394,40 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 261 /* SourceFile */: + case 232 /* CaseBlock */: + case 231 /* ModuleBlock */: + case 204 /* Block */: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 226 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); + break; + } + } /** * General-purpose node visitor. * @@ -41455,10 +45442,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.kind === 256 /* SourceFile */) { - return visitSourceFile(node); - } - else if (node.transformFlags & 1 /* TypeScript */) { + if (node.transformFlags & 1 /* TypeScript */) { // This node is explicitly marked as TypeScript, so we should transform the node. return visitTypeScript(node); } @@ -41468,6 +45452,33 @@ var ts; } return node; } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + case 241 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } /** * Specialized visitor that visits the immediate children of a namespace. * @@ -41482,11 +45493,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 236 /* ExportDeclaration */ || - node.kind === 230 /* ImportDeclaration */ || - node.kind === 231 /* ImportClause */ || - (node.kind === 229 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 240 /* ExternalModuleReference */)) { + if (node.kind === 241 /* ExportDeclaration */ || + node.kind === 235 /* ImportDeclaration */ || + node.kind === 236 /* ImportClause */ || + (node.kind === 234 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 245 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -41516,25 +45527,34 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 145 /* PropertyDeclaration */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: + case 147 /* PropertyDeclaration */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 198 /* SemicolonClassElement */: + case 203 /* SemicolonClassElement */: return node; default: ts.Debug.failBadSyntaxKind(node); return undefined; } } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 83 /* ExportKeyword */) { + return undefined; + } + return node; + } /** * Branching visitor, visits a TypeScript syntax node. * @@ -41547,57 +45567,59 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 82 /* ExportKeyword */: - case 77 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 122 /* DeclareKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 116 /* AbstractKeyword */: + case 75 /* ConstKeyword */: + case 123 /* DeclareKeyword */: + case 130 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 159 /* TypeLiteral */: - case 154 /* TypePredicate */: - case 141 /* TypeParameter */: - case 117 /* AnyKeyword */: - case 120 /* BooleanKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 103 /* VoidKeyword */: - case 133 /* SymbolKeyword */: - case 157 /* ConstructorType */: - case 156 /* FunctionType */: - case 158 /* TypeQuery */: - case 155 /* TypeReference */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 161 /* TypeLiteral */: + case 156 /* TypePredicate */: + case 143 /* TypeParameter */: + case 118 /* AnyKeyword */: + case 121 /* BooleanKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 104 /* VoidKeyword */: + case 135 /* SymbolKeyword */: + case 159 /* ConstructorType */: + case 158 /* FunctionType */: + case 160 /* TypeQuery */: + case 157 /* TypeReference */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: + case 167 /* ThisType */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 171 /* LiteralType */: // TypeScript type nodes are elided. - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: // TypeScript index signatures are elided. - case 143 /* Decorator */: + case 145 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. - case 145 /* PropertyDeclaration */: - // TypeScript property declarations are elided. - case 148 /* Constructor */: - // TypeScript constructors are transformed in `visitClassDeclaration`. + case 147 /* PropertyDeclaration */: + // TypeScript property declarations are elided. return undefined; - case 222 /* InterfaceDeclaration */: + case 150 /* Constructor */: + return visitConstructor(node); + case 227 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -41607,9 +45629,8 @@ var ts; // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassDeclaration(node); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -41619,37 +45640,36 @@ var ts; // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassExpression(node); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 147 /* MethodDeclaration */: - // TypeScript method declarations may be 'async', and may have decorators, modifiers + case 149 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 150 /* SetAccessor */: - // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + case 152 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 220 /* FunctionDeclaration */: - // TypeScript function declarations may be 'async' + case 225 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: - // TypeScript function expressions may be 'async' + case 184 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 180 /* ArrowFunction */: - // TypeScript arrow functions may be 'async' + case 185 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 142 /* Parameter */: + case 144 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -41659,30 +45679,33 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 196 /* NonNullExpression */: + case 179 /* CallExpression */: + return visitCallExpression(node); + case 180 /* NewExpression */: + return visitNewExpression(node); + case 201 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 184 /* AwaitExpression */: - // TypeScript 'await' expressions must be transformed. - return visitAwaitExpression(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 225 /* ModuleDeclaration */: + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 230 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -41690,51 +45713,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } } - /** - * Performs actions that should always occur immediately before visiting a node. - * - * @param node The node to visit. - */ - function onBeforeVisitNode(node) { - switch (node.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 226 /* ModuleBlock */: - case 199 /* Block */: - currentScope = node; - break; - } - } function visitSourceFile(node) { - currentSourceFile = node; - // If the source file requires any helpers and is an external module, and - // the importHelpers compiler option is enabled, emit a synthesized import - // statement for the helpers library. - if (node.flags & 31744 /* EmitHelperFlags */ - && compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); - var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); - var externalHelpersModuleImport = ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~8 /* Synthesized */; - statements.push(externalHelpersModuleImport); - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = ts.visitEachChild(node, visitor, context); - } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); - return node; + var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** * Tests whether we should emit a __decorate call for a class declaration. @@ -41770,7 +45751,6 @@ var ts; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var classAlias; // emit name if // - node has a name // - node has static initializers @@ -41779,38 +45759,22 @@ var ts; if (!name && staticProperties.length > 0) { name = ts.getGeneratedNameForNode(node); } - var statements = []; - if (!isDecoratedClass) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - var classDeclaration = ts.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), - /*location*/ node); - ts.setOriginalNode(classDeclaration, node); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); - } - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + var classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var statements = [classStatement]; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, /*noSourceMaps*/ true)); + addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); } // Write any decorators of the node. addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); // If the class is exported as part of a TypeScript namespace, emit the namespace export. // Otherwise, if the class was exported at the top level and was decorated, emit an export // declaration or export default for the class. @@ -41819,26 +45783,54 @@ var ts; } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(ts.createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, getLocalName(node))); + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } - return statements; + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param hasStaticProperties A value indicating whether the class has static properties. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + var emitFlags = ts.getEmitFlags(node); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + if (hasStaticProperties) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; } /** * Transforms a decorated class declaration and appends the resulting statements. If * the class requires an alias to avoid issues with double-binding, the alias is returned. * + * @param statements A statement list to which to add the declaration. * @param node A ClassDeclaration node. * @param name The name of the class. - * @param hasExtendsClause A value indicating whether + * @param hasExtendsClause A value indicating whether the class has an extends clause. */ - function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { // When we emit an ES6 class that has a class decorator, we must tailor the // emit to certain specific cases. // @@ -41873,20 +45865,20 @@ var ts; // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = C_1 = class C { // class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export { C }; + // | var C_1; // --------------------------------------------------------------------- // // If a class declaration is the default export of a module, we instead emit @@ -41915,59 +45907,31 @@ var ts; // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export default class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export default C; + // | var C_1; // --------------------------------------------------------------------- // var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // ... = class ${name} ${heritageClauses} { // ${members} // } - var classExpression = ts.setOriginalNode(ts.createClassExpression( - /*modifiers*/ undefined, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), - /*location*/ location), node); - if (!name) { - name = ts.getGeneratedNameForNode(node); - } - // Record an alias to avoid class double-binding. - var classAlias; - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - } - var declaredName = getDeclarationName(node, /*allowComments*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, hasExtendsClause); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members, location); + ts.setOriginalNode(classExpression, node); // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference // or decoratedClassAlias if the class contain self-reference. - var transformedClassExpression = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(classAlias || declaredName, - /*type*/ undefined, classExpression) - ]), - /*location*/ location); - setCommentRange(transformedClassExpression, node); - statements.push(ts.setOriginalNode( - /*node*/ transformedClassExpression, - /*original*/ node)); - if (classAlias) { - // We emit the class alias as a `let` declaration here so that it has the same - // TDZ as the class. - // let ${declaredName} = ${decoratedClassAlias} - statements.push(ts.setOriginalNode(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(declaredName, - /*type*/ undefined, classAlias) - ]), - /*location*/ location), - /*original*/ node)); - } - return classAlias; + var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location); + ts.setOriginalNode(statement, node); + ts.setCommentRange(statement, node); + return statement; } /** * Transforms a class expression with TypeScript syntax into compatible ES6. @@ -41981,7 +45945,7 @@ var ts; function visitClassExpression(node) { var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, heritageClauses !== undefined); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84 /* ExtendsKeyword */; })); var classExpression = ts.setOriginalNode(ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members, @@ -41996,9 +45960,9 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 32768 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); - ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } @@ -42030,7 +45994,7 @@ var ts; // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 131072 /* ContainsParameterPropertyAssignments */; + var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -42038,7 +46002,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + var body = transformConstructorBody(node, constructor, hasExtendsClause); // constructor(${parameters}) { // ${body} // } @@ -42070,9 +46034,8 @@ var ts; // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. // Instead, we'll avoid using a rest parameter and spread into the super call as // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". - return constructor - ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) - : []; + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } /** * Transforms (or creates) a constructor body for a class with parameter property @@ -42081,13 +46044,11 @@ var ts; * @param node The current class. * @param constructor The current class constructor. * @param hasExtendsClause A value indicating whether the class has an extends clause. - * @param parameters The transformed parameters for the constructor. */ - function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + function transformConstructorBody(node, constructor, hasExtendsClause) { var statements = []; var indexOfFirstStatement = 0; - // The body of a constructor is a new lexical environment - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); // Add parameters with property assignments. Transforms this: @@ -42124,16 +46085,17 @@ var ts; // } // var properties = getInitializedProperties(node, /*isStatic*/ false); - addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { // The class already had a constructor, so we should add the existing statements, skipping the initial super call. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } // End the lexical environment. ts.addRange(statements, endLexicalEnvironment()); - return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, + return ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), - /*location*/ constructor ? constructor.body : undefined), true); + /*location*/ constructor ? constructor.body : undefined, + /*multiLine*/ true); } /** * Adds super call and preceding prologue directives into the list of statements. @@ -42151,7 +46113,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +46147,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 1536 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42224,41 +46186,39 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 145 /* PropertyDeclaration */ + return member.kind === 147 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } /** * Generates assignment statements for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function addInitializedPropertyStatements(statements, node, properties, receiver) { - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; - var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } /** * Generates assignment expressions for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function generateInitializedPropertyExpressions(node, properties, receiver) { + function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { - var property = properties_8[_i]; - var expression = transformInitializedProperty(node, property, receiver); + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42266,11 +46226,10 @@ var ts; /** * Transforms a property initializer into an assignment statement. * - * @param node The class containing the property. * @param property The property declaration. * @param receiver The object receiving the property assignment. */ - function transformInitializedProperty(node, property, receiver) { + function transformInitializedProperty(property, receiver) { var propertyName = visitPropertyNameOfClassElement(property); var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -42362,12 +46321,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -42384,10 +46343,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -42428,14 +46388,14 @@ var ts; * @param node The declaration node. * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } /** @@ -42482,7 +46442,7 @@ var ts; */ function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -42502,13 +46462,13 @@ var ts; // __metadata("design:type", Function), // __metadata("design:paramtypes", [Object]), // __metadata("design:returntype", void 0) - // ], C.prototype, "method", undefined); + // ], C.prototype, "method", null); // // The emit for an accessor is: // // __decorate([ // dec - // ], C.prototype, "accessor", undefined); + // ], C.prototype, "accessor", null); // // The emit for a property is: // @@ -42519,12 +46479,12 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 145 /* PropertyDeclaration */ + ? member.kind === 147 /* PropertyDeclaration */ ? ts.createVoidZero() : ts.createNull() : undefined; - var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); return helper; } /** @@ -42532,8 +46492,8 @@ var ts; * * @param node The class node. */ - function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { - var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } @@ -42543,33 +46503,19 @@ var ts; * * @param node The class node. */ - function generateConstructorDecorationExpression(node, decoratedClassAlias) { + function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = C_1 = __decorate([dec], C); - // - if (decoratedClassAlias) { - var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); - var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); - return result; - } - else { - var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); - return result; - } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; } /** * Transforms a decorator into an expression. @@ -42591,9 +46537,9 @@ var ts; expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 1536 /* NoComments */); expressions.push(helper); } } @@ -42605,41 +46551,41 @@ var ts; * @param node The declaration node. * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); } } } @@ -42652,10 +46598,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 145 /* PropertyDeclaration */; + return kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 147 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -42665,7 +46611,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 147 /* MethodDeclaration */; + return node.kind === 149 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -42675,12 +46621,16 @@ var ts; * @param node The node to test. */ function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 221 /* ClassDeclaration */ - || kind === 192 /* ClassExpression */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */; + switch (node.kind) { + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return true; + } + return false; } /** * Serializes the type of a node for use with decorator type metadata. @@ -42689,43 +46639,26 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: - case 149 /* GetAccessor */: + case 147 /* PropertyDeclaration */: + case 144 /* Parameter */: + case 151 /* GetAccessor */: return serializeTypeNode(node.type); - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 147 /* MethodDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 149 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node) { - if (node && node.kind === 160 /* ArrayType */) { - return node.elementType; - } - else if (node && node.kind === 155 /* TypeReference */) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } /** * Serializes the types of the parameters of a node for use with decorator type metadata. * * @param node The node that should have its parameter types serialized. */ - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -42733,7 +46666,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -42741,7 +46674,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -42750,6 +46683,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } /** * Serializes the return type of a node for use with decorator type metadata. * @@ -42787,49 +46729,80 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return ts.createVoidZero(); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return ts.createIdentifier("Function"); - case 160 /* ArrayType */: - case 161 /* TupleType */: + case 162 /* ArrayType */: + case 163 /* TupleType */: return ts.createIdentifier("Array"); - case 154 /* TypePredicate */: - case 120 /* BooleanKeyword */: + case 156 /* TypePredicate */: + case 121 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: return ts.createIdentifier("String"); - case 166 /* LiteralType */: + case 171 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 133 /* SymbolKeyword */: - return languageVersion < 2 /* ES6 */ + case 135 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return serializeTypeReferenceNode(node); - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 117 /* AnyKeyword */: - case 165 /* ThisType */: + case 165 /* IntersectionType */: + case 164 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 70 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough + case 160 /* TypeQuery */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 161 /* TypeLiteral */: + case 118 /* AnyKeyword */: + case 167 /* ThisType */: break; default: ts.Debug.failBadSyntaxKind(node); @@ -42848,7 +46821,7 @@ var ts; case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: @@ -42862,7 +46835,7 @@ var ts; case ts.TypeReferenceSerializationKind.ArrayLikeType: return ts.createIdentifier("Array"); case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ES6 */ + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); case ts.TypeReferenceSerializationKind.TypeWithCallSignature: @@ -42883,18 +46856,18 @@ var ts; */ function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. - var name_27 = ts.getMutableClone(node); - name_27.flags &= ~8 /* Synthesized */; - name_27.original = undefined; - name_27.parent = currentScope; + var name_32 = ts.getMutableClone(node); + name_32.flags &= ~8 /* Synthesized */; + name_32.original = undefined; + name_32.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_32), ts.createLiteral("undefined")), name_32); } - return name_27; - case 139 /* QualifiedName */: + return name_32; + case 141 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -42907,7 +46880,7 @@ var ts; */ function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 69 /* Identifier */) { + if (node.left.kind === 70 /* Identifier */) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { @@ -42924,7 +46897,7 @@ var ts; * available. */ function getGlobalSymbolNameWithFallback() { - return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53 /* QuestionToken */), ts.createIdentifier("Symbol"), ts.createToken(54 /* ColonToken */), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } /** * Gets an expression that represents a property name. For a computed property, a @@ -42940,7 +46913,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeIdentifier(name.text)); } else { return ts.getSynthesizedClone(name); @@ -42978,9 +46951,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 83 /* ExtendsKeyword */) { + if (node.token === 84 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.createHeritageClause(83 /* ExtendsKeyword */, types, node); + return ts.createHeritageClause(84 /* ExtendsKeyword */, types, node); } return undefined; } @@ -43006,12 +46979,18 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.visitEachChild(node, visitor, context); + } /** * Visits a method declaration of a class. * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node is marked as abstract, public, private, protected, or readonly * - The node has both a decorator and a computed property name * * @param node The method node. @@ -43020,17 +46999,17 @@ var ts; if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var method = ts.createMethod( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(method, node); - return method; + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -43054,16 +47033,16 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createGetAccessor( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Visits a set accessor declaration of a class. @@ -43078,23 +47057,23 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createSetAccessor( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Visits a function declaration. * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked async * - The node is exported from a TypeScript namespace + * - The node has decorators * * @param node The function node. */ @@ -43102,24 +47081,22 @@ var ts; if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var func = ts.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isNamespaceExport(node)) { - var statements = [func]; + var statements = [updated]; addExportMemberAssignment(statements, node); return statements; } - return func; + return updated; } /** * Visits a function expression node. * * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations * * @param node The function expression node. */ @@ -43127,111 +47104,21 @@ var ts; if (ts.nodeIsMissing(node.body)) { return ts.createOmittedExpression(); } - var func = ts.createFunctionExpression(node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); - return func; + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } /** * @remarks * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations */ function visitArrowFunction(node) { - var func = ts.createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, node.equalsGreaterThanToken, transformConciseBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); - return func; - } - function transformFunctionBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformFunctionBodyWorker(node.body); - } - function transformFunctionBodyWorker(body, start) { - if (start === void 0) { start = 0; } - var savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); - var visited = ts.updateBlock(body, statements); - var declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - function transformConciseBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); - } - function transformConciseBodyWorker(body, forceBlockFunctionBody) { - if (ts.isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - var visited = ts.visitNode(body, visitor, ts.isConciseBody); - var declarations = endLexicalEnvironment(); - var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !ts.isBlock(merged)) { - return ts.createBlock([ - ts.createReturn(merged) - ]); - } - else { - return merged; - } - } - } - function getPromiseConstructor(type) { - var typeName = ts.getEntityNameFromTypeNode(type); - if (typeName && ts.isEntityName(typeName)) { - var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - return undefined; - } - function transformAsyncFunctionBody(node) { - var promiseConstructor = languageVersion < 2 /* ES6 */ ? getPromiseConstructor(node.type) : undefined; - var isArrowFunction = node.kind === 180 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - if (!isArrowFunction) { - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); - var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES6 */) { - if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); - } - else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); - } - } - return block; - } - else { - return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)); - } + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } /** * Visits a parameter declaration node. @@ -43244,10 +47131,10 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameterDeclaration( + var parameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, @@ -43256,9 +47143,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); return parameter; } /** @@ -43284,24 +47171,17 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); } else { return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), /*location*/ node); } } - /** - * Visits an await expression. - * - * This function will be called any time a TypeScript await expression is encountered. - * - * @param node The await expression node. - */ - function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.createYield( - /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), - /*location*/ node), node); + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } /** * Visits a parenthesized expression that contains either a type assertion or an `as` @@ -43340,6 +47220,14 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return ts.createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } /** * Determines whether to emit an enum declaration. * @@ -43350,20 +47238,6 @@ var ts; || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); - } - /* - * Adds a trailing VariableStatement for an enum or module declaration. - */ - function addVarForEnumExportedFromNamespace(statements, node) { - var statement = ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), - /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); - statements.push(statement); - } /** * Visits an enum declaration. * @@ -43378,15 +47252,14 @@ var ts; var statements = []; // We request to be advised when the printer is about to print this node. This allows // us to set up the correct state for later substitutions. - var emitFlags = 64 /* AdviseOnEmitNode */; + var emitFlags = 2 /* AdviseOnEmitNode */; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384 /* NoLeadingComments */; + emitFlags |= 512 /* NoLeadingComments */; } } // `parameterName` is the declaration name used inside of the enum. @@ -43394,24 +47267,36 @@ var ts; // `containerName` is the expression used inside of the enum for assignments. var containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } // (function (x) { // x[x["y"] = 0] = "y"; // ... // })(x || (x = {})); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), - /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), + /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); - } + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } /** @@ -43473,58 +47358,98 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.System); } - function isES6ExportedDeclaration(node) { - return isExternalModuleExport(node) - && moduleKind === ts.ModuleKind.ES6; + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } } - function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_33 = node.symbol && node.symbol.name; + if (name_33) { + return currentScopeFirstDeclarationsOfName[name_33] === node; + } + } + return false; } /** * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { // Emit a variable statement for the module. - var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) - ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) - : undefined, [ - ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) ]); - ts.setOriginalNode(statement, /*original*/ node); - // Adjust the source map emit to match the old emitter. - if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 229 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 2097152 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 2097152 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; } - // Trailing comments for module declaration should be emitted after the function closure - // instead of the variable statement: - // - // /** Module comment*/ - // module m1 { - // function foo4Export() { - // } - // } // trailing comment module - // - // Should emit: - // - // /** Module comment*/ - // var m1; - // (function (m1) { - // function foo4Export() { - // } - // })(m1 || (m1 = {})); // trailing comment module - // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); - statements.push(statement); } /** * Visits a module declaration node. @@ -43542,15 +47467,14 @@ var ts; var statements = []; // We request to be advised when the printer is about to print this node. This allows // us to set up the correct state for later substitutions. - var emitFlags = 64 /* AdviseOnEmitNode */; + var emitFlags = 2 /* AdviseOnEmitNode */; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384 /* NoLeadingComments */; + emitFlags |= 512 /* NoLeadingComments */; } } // `parameterName` is the declaration name used inside of the namespace. @@ -43558,13 +47482,15 @@ var ts; // `containerName` is the expression used inside of the namespace for exports. var containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x || (x = {}) // exports.x || (exports.x = {}) var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); - if (ts.hasModifier(node, 1 /* Export */) && !isES6ExportedDeclaration(node)) { + if (hasNamespaceQualifiedExportName(node)) { // `localName` is the expression used within this node's containing scope for any local references. - var localName = getLocalName(node); + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x = (exports.x || (exports.x = {})) moduleArg = ts.createAssignment(localName, moduleArg); } @@ -43572,15 +47498,19 @@ var ts; // x_1.y = ...; // })(x || (x = {})); var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } /** @@ -43591,14 +47521,16 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 226 /* ModuleBlock */) { + if (body.kind === 231 /* ModuleBlock */) { ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); statementsLocation = body.statements; blockLocation = body; @@ -43619,6 +47551,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43643,17 +47576,127 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + if (body.kind !== 231 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, /*optional*/ true); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, /*optional*/ true); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 237 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, /*optional*/ true); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } /** * Determines whether to emit an import equals declaration. * @@ -43674,19 +47717,22 @@ var ts; */ function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { - return ts.visitEachChild(node, visitor, context); + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; - return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(node.name, - /*type*/ undefined, moduleReference) + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) ]), node), node); } else { @@ -43735,45 +47781,27 @@ var ts; return ts.createStatement(expression, /*location*/ undefined); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); + return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); } - function createExternalModuleExport(exportName) { - return ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports([ - ts.createExportSpecifier(exportName) - ])); - } - function getNamespaceMemberName(name, allowComments, allowSourceMaps) { - var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), /*location*/ name); - var emitFlags; - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; - } - if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return getNamespaceMemberName(name, /*allowComments*/ false, /*allowSourceMaps*/ true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); } /** * Gets the declaration name used inside of a namespace or enum. */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43784,89 +47812,31 @@ var ts; return ts.getGeneratedNameForNode(node); } /** - * Gets the local name for a declaration for use in expressions. - * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. */ - function getLocalName(node, noSourceMaps, allowComments) { - return getDeclarationName(node, allowComments, !noSourceMaps, 262144 /* LocalName */); - } - /** - * Gets the export name for a declaration for use in expressions. - * - * An export name will *always* be prefixed with an module or namespace export modifier - * like "exports." if one is required. - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. - */ - function getExportName(node, noSourceMaps, allowComments) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - return getDeclarationName(node, allowComments, !noSourceMaps, 131072 /* ExportName */); - } - /** - * Gets the name for a declaration for use in declarations. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - * @param emitFlags Additional NodeEmitFlags to specify for the name. - */ - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; - } - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); - } - return name_28; - } - else { - return ts.getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } function getClassPrototype(node) { - return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { return ts.hasModifier(member, 32 /* Static */) - ? getDeclarationName(node) + ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(69 /* Identifier */); - } - } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) === 0) { - enabledSubstitutions |= 4 /* AsyncMethodsWithSuper */; - // We need to enable substitutions for call, property access, and element access - // if we need to rewrite super calls. - context.enableSubstitution(174 /* CallExpression */); - context.enableSubstitution(172 /* PropertyAccessExpression */); - context.enableSubstitution(173 /* ElementAccessExpression */); - // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(221 /* ClassDeclaration */); - context.enableEmitNotification(147 /* MethodDeclaration */); - context.enableEmitNotification(149 /* GetAccessor */); - context.enableEmitNotification(150 /* SetAccessor */); - context.enableEmitNotification(148 /* Constructor */); + context.enableSubstitution(70 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -43874,7 +47844,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(70 /* Identifier */); // Keep track of class aliases. classAliases = ts.createMap(); } @@ -43884,60 +47854,45 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + context.enableSubstitution(70 /* Identifier */); + context.enableSubstitution(258 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(225 /* ModuleDeclaration */); + context.enableEmitNotification(230 /* ModuleDeclaration */); } } - function isSuperContainer(node) { - var kind = node.kind; - return kind === 221 /* ClassDeclaration */ - || kind === 148 /* Constructor */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */; - } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 225 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 230 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 224 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 229 /* EnumDeclaration */; } /** * Hook for node emit. * + * @param emitContext A context hint for the emitter. * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; - var savedCurrentSuperContainer = currentSuperContainer; - // If we need to support substitutions for `super` in an async method, - // we should track it here. - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2 /* NamespaceExports */; } if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } /** * Hooks node substitutions. * + * @param emitContext A context hint for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,34 +47902,28 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_34 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_34); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_34, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_34, exportedName, /*location*/ node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: - return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + case 177 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); } return node; } @@ -43995,10 +47944,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); - return clone_4; + var clone_2 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -44007,13 +47956,13 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 225 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 224 /* EnumDeclaration */); + if (container && container.kind !== 261 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 230 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 229 /* EnumDeclaration */); if (substitute) { return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, /*location*/ node); } @@ -44021,2073 +47970,368 @@ var ts; } return undefined; } - function substituteCallExpression(node) { - var expression = node.expression; - if (ts.isSuperProperty(expression)) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - var argumentExpression = ts.isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), - /*typeArguments*/ undefined, [ - ts.createThis() - ].concat(node.arguments)); - } - } - return node; - } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); - } - } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; } + ts.setConstantValue(node, constantValue); + return substitute; } return node; } - function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { - if (flags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), - /*typeArguments*/ undefined, [argumentExpression]), "value", location); + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; } - else { - return ts.createCall(ts.createIdentifier("_super"), - /*typeArguments*/ undefined, [argumentExpression], location); - } - } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; } } ts.transformTypeScript = transformTypeScript; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformES6Module(context) { - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var currentSourceFile; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return ts.visitEachChild(node, visitor, context); - } - return node; - } - function visitor(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 231 /* ImportClause */: - return visitImportClause(node); - case 233 /* NamedImports */: - case 232 /* NamespaceImport */: - return visitNamedBindings(node); - case 234 /* ImportSpecifier */: - return visitImportSpecifier(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 237 /* NamedExports */: - return visitNamedExports(node); - case 238 /* ExportSpecifier */: - return visitExportSpecifier(node); - } - return node; - } - function visitExportAssignment(node) { - if (node.isExportEquals) { - return undefined; // do not emit export equals for ES6 - } - var original = ts.getOriginalNode(node); - return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; - } - function visitExportDeclaration(node) { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; - } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; - } - var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true); - if (node.exportClause === newExportClause) { - return node; - } - return newExportClause - ? ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, newExportClause, node.moduleSpecifier) - : undefined; - } - function visitNamedExports(node) { - var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? ts.createNamedExports(newExports) : undefined; - } - function visitExportSpecifier(node) { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - function visitImportEqualsDeclaration(node) { - return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - function visitImportDeclaration(node) { - if (node.importClause) { - var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, newImportClause, node.moduleSpecifier); - } - } - return node; - } - function visitImportClause(node) { - var newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? ts.createImportClause(newDefaultImport, newNamedBindings) - : node; - } - function visitNamedBindings(node) { - if (node.kind === 232 /* NamespaceImport */) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === node.elements) { - return node; - } - return ts.createNamedImports(newNamedImportElements); - } - } - function visitImportSpecifier(node) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ], location); } - ts.transformES6Module = transformES6Module; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(187 /* BinaryExpression */); - context.enableSubstitution(185 /* PrefixUnaryExpression */); - context.enableSubstitution(186 /* PostfixUnaryExpression */); - context.enableEmitNotification(256 /* SourceFile */); - var exportFunctionForFileMap = []; - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var exportFunctionForFile; - var contextObjectForFile; - var exportedLocalNames; - var exportedFunctionDeclarations; - var enclosingBlockScopedContainer; - var currentParent; - var currentNode; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; - // Perform the transformation. - var updated = transformSystemModuleWorker(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - return node; - } - function transformSystemModuleWorker(node) { - // System modules have the following shape: - // - // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) - // - // The parameter 'exports' here is a callback '(name: string, value: T) => T' that - // is used to publish exported values. 'exports' returns its 'value' argument so in - // most cases expressions that mutate exported values can be rewritten as: - // - // expr -> exports('name', expr) - // - // The only exception in this rule is postfix unary operators, - // see comment to 'substitutePostfixUnaryExpression' for more details - ts.Debug.assert(!exportFunctionForFile); - // Collect information about the external module and dependency groups. - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - // Make sure that the name of the 'exports' function does not conflict with - // existing identifiers. - exportFunctionForFile = ts.createUniqueName("exports"); - contextObjectForFile = ts.createUniqueName("context"); - exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; - var dependencyGroups = collectDependencyGroups(externalImports); - var statements = []; - // Add the body of the module. - addSystemModuleBody(statements, node, dependencyGroups); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); - var body = ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(exportFunctionForFile), - ts.createParameter(contextObjectForFile) - ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); - // Write the call to `System.register` - // Clear the emit-helpers flag for later passes since we'll have already used it in the module body - // So the helper will be emit at the correct position instead of at the top of the source-file - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), - /*typeArguments*/ undefined, moduleName - ? [moduleName, dependencies, body] - : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); - var _a; - } - /** - * Adds the statements for the module body function for the source file. - * - * @param statements The output statements for the module body. - * @param node The source file for the module. - * @param statementOffset The offset at which to begin visiting the statements of the SourceFile. - */ - function addSystemModuleBody(statements, node, dependencyGroups) { - // Shape of the body in system modules: - // - // function (exports) { - // - // - // - // return { - // setters: [ - // - // ], - // execute: function() { - // - // } - // } - // - // } - // - // i.e: - // - // import {x} from 'file1' - // var y = 1; - // export function foo() { return y + x(); } - // console.log(y); - // - // Will be transformed to: - // - // function(exports) { - // var file_1; // local alias - // var y; - // function foo() { return y + file_1.x(); } - // exports("foo", foo); - // return { - // setters: [ - // function(v) { file_1 = v } - // ], - // execute(): function() { - // y = 1; - // console.log(y); - // } - // }; - // } - // We start a new lexical environment in this function body, but *not* in the - // body of the execute function. This allows us to emit temporary declarations - // only in the outer module body and not in the inner one. - startLexicalEnvironment(); - // Add any prologue directives. - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitSourceElement); - // var __moduleName = context_1 && context_1.id; - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", - /*type*/ undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) - ]))); - // Visit the statements of the source file, emitting any transformations into - // the `executeStatements` array. We do this *before* we fill the `setters` array - // as we both emit transformations as well as aggregate some data used when creating - // setters. This allows us to reduce the number of times we need to loop through the - // statements of the source file. - var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); - // We emit the lexical environment (hoisted variables and function declarations) - // early to align roughly with our previous emit output. - // Two key differences in this approach are: - // - Temporary variables will appear at the top rather than at the bottom of the file - // - Calls to the exporter for exported function declarations are grouped after - // the declarations. - ts.addRange(statements, endLexicalEnvironment()); - // Emit early exports for function declarations. - ts.addRange(statements, exportedFunctionDeclarations); - var exportStarFunction = addExportStarIfNeeded(statements); - statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ - ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, ts.createBlock(executeStatements, - /*location*/ undefined, - /*multiLine*/ true))) - ]), - /*multiLine*/ true))); - } - function addExportStarIfNeeded(statements) { - if (!hasExportStarsToExportValues) { - return; - } - // when resolving exports local exported entries/indirect exported entries in the module - // should always win over entries with similar names that were added via star exports - // to support this we store names of local/indirect exported entries in a set. - // this set is used to filter names brought by star expors. - // local names set should only be added if we have anything exported - if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { - // no exported declarations (export var ...) or export specifiers (export {x}) - // check if we have any non star export declarations. - var hasExportDeclarationWithExportClause = false; - for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { - var externalImport = externalImports_1[_i]; - if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - // we still need to emit exportStar helper - return addExportStarFunction(statements, /*localNames*/ undefined); - } - } - var exportedNames = []; - if (exportedLocalNames) { - for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { - var exportedLocalName = exportedLocalNames_1[_a]; - // write name of exported declaration, i.e 'export var x...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); - } - } - for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { - var externalImport = externalImports_2[_b]; - if (externalImport.kind !== 236 /* ExportDeclaration */) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - // export * from ... - continue; - } - for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { - var element = _d[_c]; - // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); - } - } - var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, - /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) - ]))); - return addExportStarFunction(statements, exportedNamesStorageRef); - } - /** - * Emits a setter callback for each dependency group. - * @param write The callback used to write each callback. - */ - function generateSetters(exportStarFunction, dependencyGroups) { - var setters = []; - for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group = dependencyGroups_1[_i]; - // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); - var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); - var statements = []; - for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { - var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); - switch (entry.kind) { - case 230 /* ImportDeclaration */: - if (!entry.importClause) { - // 'import "..."' case - // module is imported only for side-effects, no emit required - break; - } - // fall-through - case 229 /* ImportEqualsDeclaration */: - ts.Debug.assert(importVariableName !== undefined); - // save import into the local - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); - break; - case 236 /* ExportDeclaration */: - ts.Debug.assert(importVariableName !== undefined); - if (entry.exportClause) { - // export {a, b as c} from 'foo' - // - // emit as: - // - // exports_({ - // "a": _["a"], - // "c": _["b"] - // }); - var properties = []; - for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { - var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); - } - statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, - /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); - } - else { - // export * from 'foo' - // - // emit as: - // - // exportStar(foo_1_1); - statements.push(ts.createStatement(ts.createCall(exportStarFunction, - /*typeArguments*/ undefined, [parameterName]))); - } - break; - } - } - setters.push(ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], - /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); - } - return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); - } - function visitSourceElement(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - default: - return visitNestedNode(node); - } - } - function visitNestedNode(node) { - var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; - } - var result = visitNestedNodeWorker(node); - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return result; - } - function visitNestedNodeWorker(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 206 /* ForStatement */: - return visitForStatement(node); - case 207 /* ForInStatement */: - return visitForInStatement(node); - case 208 /* ForOfStatement */: - return visitForOfStatement(node); - case 204 /* DoStatement */: - return visitDoStatement(node); - case 205 /* WhileStatement */: - return visitWhileStatement(node); - case 214 /* LabeledStatement */: - return visitLabeledStatement(node); - case 212 /* WithStatement */: - return visitWithStatement(node); - case 213 /* SwitchStatement */: - return visitSwitchStatement(node); - case 227 /* CaseBlock */: - return visitCaseBlock(node); - case 249 /* CaseClause */: - return visitCaseClause(node); - case 250 /* DefaultClause */: - return visitDefaultClause(node); - case 216 /* TryStatement */: - return visitTryStatement(node); - case 252 /* CatchClause */: - return visitCatchClause(node); - case 199 /* Block */: - return visitBlock(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (node.importClause && ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitImportEqualsDeclaration(node) { - if (ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - // NOTE(rbuckton): Do we support export import = require('') in System? - return undefined; - } - function visitExportDeclaration(node) { - if (!node.moduleSpecifier) { - var statements = []; - ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - return undefined; - } - function visitExportSpecifier(specifier) { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement(specifier.name, specifier.propertyName || specifier.name); - } - return undefined; - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement(ts.createLiteral("default"), node.expression); - } - } - return undefined; - } - /** - * Visits a variable statement, hoisting declared names to the top-level module body. - * Each declaration is rewritten into an assignment expression. - * - * @param node The variable statement to visit. - */ - function visitVariableStatement(node) { - // hoist only non-block scoped declarations or block scoped declarations parented by source file - var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3 /* BlockScoped */) == 0) || - enclosingBlockScopedContainer.kind === 256 /* SourceFile */; - if (!shouldHoist) { - return node; - } - var isExported = ts.hasModifier(node, 1 /* Export */); - var expressions = []; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } - } - if (expressions.length) { - return ts.createStatement(ts.inlineExpressions(expressions), node); - } - return undefined; - } - /** - * Transforms a VariableDeclaration into one or more assignment expressions. - * - * @param node The VariableDeclaration to transform. - * @param isExported A value used to indicate whether the containing statement was exported. - */ - function transformVariable(node, isExported) { - // Hoist any bound names within the declaration. - hoistBindingElement(node, isExported); - if (!node.initializer) { - // If the variable has no initializer, ignore it. - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - // If the variable has an IdentifierName, write out an assignment expression in its place. - return ts.createAssignment(name, node.initializer); - } - else { - // If the variable has a BindingPattern, flatten the variable into multiple assignment expressions. - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - /** - * Visits a FunctionDeclaration, hoisting it to the outer module body function. - * - * @param node The function declaration to visit. - */ - function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1 /* Export */)) { - // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body, - /*location*/ node); - // Record a declaration export in the outer module body function. - recordExportedFunctionDeclaration(node); - if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); - } - ts.setOriginalNode(newNode, node); - node = newNode; - } - // Hoist the function declaration to the outer module body function. - hoistFunctionDeclaration(node); - return undefined; - } - function visitExpressionStatement(node) { - var originalNode = ts.getOriginalNode(node); - if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); - // We only need to hoistVariableDeclaration for EnumDeclaration - // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement - // which then call transformsVariable for each declaration in declarationList - if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); - } - return [ - node, - createExportStatement(name_31, name_31) - ]; - } - return node; - } - /** - * Visits a ClassDeclaration, hoisting its name to the outer module body function. - * - * @param node The class declaration to visit. - */ - function visitClassDeclaration(node) { - // Hoist the name of the class declaration to the outer module body function. - var name = getDeclarationName(node); - hoistVariableDeclaration(name); - var statements = []; - // Rewrite the class declaration into an assignment of a class expression. - statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression( - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, node.heritageClauses, node.members, - /*location*/ node)), - /*location*/ node)); - // If the class was exported, write a declaration export to the inner module body function. - if (ts.hasModifier(node, 1 /* Export */)) { - if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name); - } - statements.push(createDeclarationExport(node)); - } - return statements; - } - function shouldHoistLoopInitializer(node) { - return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) === 0; - } - /** - * Visits the body of a ForStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var expressions = []; - for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, /*isExported*/ false); - if (visited) { - expressions.push(visited); - } - } - ; - return ts.createFor(expressions.length - ? ts.inlineExpressions(expressions) - : ts.createSynthesizedNode(193 /* OmittedExpression */), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), - /*location*/ node); - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Transforms and hoists the declaration list of a ForInStatement or ForOfStatement into an expression. - * - * @param node The decalaration list to transform. - */ - function transformForBinding(node) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, /*isExported*/ false); - var name = firstDeclaration.name; - return ts.isIdentifier(name) - ? name - : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); - } - /** - * Visits the body of a ForInStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForInStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Visits the body of a ForOfStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForOfStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Visits the body of a DoStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitDoStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a WhileStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitWhileStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a LabeledStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitLabeledStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a WithStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitWithStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a SwitchStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitSwitchStatement(node) { - var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); - if (caseBlock !== node.caseBlock) { - var updated = ts.getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; - } - /** - * Visits the body of a CaseBlock to hoist declarations. - * - * @param node The node to visit. - */ - function visitCaseBlock(node) { - var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); - if (clauses !== node.clauses) { - var updated = ts.getMutableClone(node); - updated.clauses = clauses; - return updated; - } - return node; - } - /** - * Visits the body of a CaseClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitCaseClause(node) { - var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); - if (statements !== node.statements) { - var updated = ts.getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; - } - /** - * Visits the body of a DefaultClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitDefaultClause(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - /** - * Visits the body of a TryStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitTryStatement(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - /** - * Visits the body of a CatchClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitCatchClause(node) { - var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); - if (block !== node.block) { - var updated = ts.getMutableClone(node); - updated.block = block; - return updated; - } - return node; - } - /** - * Visits the body of a Block to hoist declarations. - * - * @param node The block to visit. - */ - function visitBlock(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - // - // Substitutions - // - function onEmitNode(node, emit) { - if (node.kind === 256 /* SourceFile */) { - exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - exportFunctionForFile = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - /** - * Hooks node substitutions. - * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. - */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - return node; - } - /** - * Substitute the expression, if necessary. - * - * @param node The node to substitute. - */ - function substituteExpression(node) { - switch (node.kind) { - case 69 /* Identifier */: - return substituteExpressionIdentifier(node); - case 187 /* BinaryExpression */: - return substituteBinaryExpression(node); - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - return substituteUnaryExpression(node); - } - return node; - } - /** - * Substitution for identifiers exported at the top level of a module. - */ - function substituteExpressionIdentifier(node) { - var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - var importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; - } - } - return node; - } - function substituteBinaryExpression(node) { - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); - } - return node; - } - function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var left = node.left; - switch (left.kind) { - case 69 /* Identifier */: - var exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); - } - break; - case 171 /* ObjectLiteralExpression */: - case 170 /* ArrayLiteralExpression */: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - return node; - } - function isExportedBinding(name) { - var container = resolver.getReferencedExportContainer(name); - return container && container.kind === 256 /* SourceFile */; - } - function hasExportedReferenceInDestructuringPattern(node) { - switch (node.kind) { - case 69 /* Identifier */: - return isExportedBinding(node); - case 171 /* ObjectLiteralExpression */: - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var property = _a[_i]; - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - break; - case 170 /* ArrayLiteralExpression */: - for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - break; - } - return false; - } - function hasExportedReferenceInObjectDestructuringElement(node) { - if (ts.isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (ts.isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - function hasExportedReferenceInArrayDestructuringElement(node) { - if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - function hasExportedReferenceInDestructuringElement(node) { - if (ts.isBinaryExpression(node)) { - var left = node.left; - return node.operatorToken.kind === 56 /* EqualsToken */ - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (ts.isIdentifier(node)) { - return isExportedBinding(node); - } - else if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - function isDestructuringPattern(node) { - var kind = node.kind; - return kind === 69 /* Identifier */ - || kind === 171 /* ObjectLiteralExpression */ - || kind === 170 /* ArrayLiteralExpression */; - } - function substituteDestructuring(node) { - return ts.flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration); - } - function substituteUnaryExpression(node) { - var operand = node.operand; - var operator = node.operator; - var substitute = ts.isIdentifier(operand) && - (node.kind === 186 /* PostfixUnaryExpression */ || - (node.kind === 185 /* PrefixUnaryExpression */ && (operator === 41 /* PlusPlusToken */ || operator === 42 /* MinusMinusToken */))); - if (substitute) { - var exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); - var call = createExportExpression(operand, expr); - if (node.kind === 185 /* PrefixUnaryExpression */) { - return call; - } - else { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - return operator === 41 /* PlusPlusToken */ - ? ts.createSubtract(call, ts.createLiteral(1)) - : ts.createAdd(call, ts.createLiteral(1)); - } - } - } - return node; - } - /** - * Gets a name to use for a DeclarationStatement. - * @param node The declaration statement. - */ - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function addExportStarFunction(statements, localNames) { - var exportStarFunction = ts.createUniqueName("exportStar"); - var m = ts.createIdentifier("m"); - var n = ts.createIdentifier("n"); - var exports = ts.createIdentifier("exports"); - var condition = ts.createStrictInequality(n, ts.createLiteral("default")); - if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); - } - statements.push(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [ts.createParameter(m)], - /*type*/ undefined, ts.createBlock([ - ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, - /*type*/ undefined, ts.createObjectLiteral([])) - ])), - ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, /*type*/ undefined) - ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) - ])), - ts.createStatement(ts.createCall(exportFunctionForFile, - /*typeArguments*/ undefined, [exports])) - ], - /*location*/ undefined, - /*multiline*/ true))); - return exportStarFunction; - } - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportExpression(name, value) { - var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; - return ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exportName, value]); - } - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportStatement(name, value) { - return ts.createStatement(createExportExpression(name, value)); - } - /** - * Creates a call to the current file's export function to export a declaration. - * @param node The declaration to export. - */ - function createDeclarationExport(node) { - var declarationName = getDeclarationName(node); - var exportName = ts.hasModifier(node, 512 /* Default */) ? ts.createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - function createImportBinding(importDeclaration) { - var importAlias; - var name; - if (ts.isImportClause(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); - name = ts.createIdentifier("default"); - } - else if (ts.isImportSpecifier(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - if (name.originalKeywordKind && languageVersion === 0 /* ES3 */) { - return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); - } - else { - return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); - } - } - function collectDependencyGroups(externalImports) { - var groupIndices = ts.createMap(); - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; - var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); - var text = externalModuleName.text; - if (ts.hasProperty(groupIndices, text)) { - // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[text]; - dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; - } - else { - groupIndices[text] = dependencyGroups.length; - dependencyGroups.push({ - name: externalModuleName, - externalImports: [externalImport] - }); - } - } - return dependencyGroups; - } - function getNameOfDependencyGroup(dependencyGroup) { - return dependencyGroup.name; - } - function recordExportName(name) { - if (!exportedLocalNames) { - exportedLocalNames = []; - } - exportedLocalNames.push(name); - } - function recordExportedFunctionDeclaration(node) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; - } - exportedFunctionDeclarations.push(createDeclarationExport(node)); - } - function hoistBindingElement(node, isExported) { - if (ts.isOmittedExpression(node)) { - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - hoistVariableDeclaration(ts.getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); - } - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); - } - } - function hoistExportedBindingElement(node) { - hoistBindingElement(node, /*isExported*/ true); - } - function hoistNonExportedBindingElement(node) { - hoistBindingElement(node, /*isExported*/ false); - } - function updateSourceFile(node, statements, nodeEmitFlags) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); - return updated; - } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); } - ts.transformSystemModule = transformSystemModule; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformModule(context) { - var transformModuleDelegates = ts.createMap((_a = {}, - _a[ts.ModuleKind.None] = transformCommonJSModule, - _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, - _a[ts.ModuleKind.AMD] = transformAMDModule, - _a[ts.ModuleKind.UMD] = transformUMDModule, - _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var moduleKind = ts.getEmitModuleKind(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(187 /* BinaryExpression */); - context.enableSubstitution(185 /* PrefixUnaryExpression */); - context.enableSubstitution(186 /* PostfixUnaryExpression */); - context.enableSubstitution(254 /* ShorthandPropertyAssignment */); - context.enableEmitNotification(256 /* SourceFile */); - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var bindingNameExportSpecifiersMap; - // Subset of exportSpecifiers that is a binding-name. - // This is to reduce amount of memory we have to keep around even after we done with module-transformer - var bindingNameExportSpecifiersForFileMap = ts.createMap(); - var hasExportStarsToExportValues; - return transformSourceFile; - /** - * Transforms the module aspects of a SourceFile. - * - * @param node The SourceFile node. - */ - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - // Collect information about the external module. - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - // Perform the transformation. - var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; - var updated = transformModule_1(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; - } - return node; - var _a; - } - /** - * Transforms a SourceFile into a CommonJS module. - * - * @param node The SourceFile node. - */ - function transformCommonJSModule(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - var updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); - } - return updated; - } - /** - * Transforms a SourceFile into an AMD module. - * - * @param node The SourceFile node. - */ - function transformAMDModule(node) { - var define = ts.createIdentifier("define"); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); - } - /** - * Transforms a SourceFile into a UMD module. - * - * @param node The SourceFile node. - */ - function transformUMDModule(node) { - var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); - return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); - } - /** - * Transforms a SourceFile into an AMD or UMD module. - * - * @param node The SourceFile node. - * @param define The expression used to define the module. - * @param moduleName An expression for the module name, if available. - * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. - */ - function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { - // An AMD define function has the following shape: - // - // define(id?, dependencies?, factory); - // - // This has the shape of the following: - // - // define(name, ["module1", "module2"], function (module1Alias) { ... } - // - // The location of the alias in the parameter list in the factory function needs to - // match the position of the module name in the dependency list. - // - // To ensure this is true in cases of modules with no aliases, e.g.: - // - // import "module" - // - // or - // - // /// - // - // we need to add modules without alias names to the end of the dependencies list - var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - // Create an updated SourceFile: - // - // define(moduleName?, ["module1", "module2"], function ... - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(define, - /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ - // Add the dependency array argument: - // - // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ - ts.createLiteral("require"), - ts.createLiteral("exports") - ].concat(aliasedModuleNames, unaliasedModuleNames)), - // Add the module body function argument: - // - // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter("require"), - ts.createParameter("exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) - ]))) - ]); - } - /** - * Transforms a SourceFile into an AMD or UMD module body. - * - * @param node The SourceFile node. - */ - function transformAsynchronousModuleBody(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); - // Visit each statement of the module body. - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - // End the lexical environment for the module body - // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); - // Append the 'export =' statement if provided. - addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); - var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); - if (hasExportStarsToExportValues) { - // If we have any `export * from ...` declarations - // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); - } - return body; - } - function addExportEqualsIfNeeded(statements, emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - if (emitAsReturn) { - var statement = ts.createReturn(exportEquals.expression, - /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), - /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); - statements.push(statement); - } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + context.requestEmitHelper(decorateHelper); + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); } } - /** - * Visits a node at the top level of the source file. - * - * @param node The node. - */ - function visitor(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - default: - // This visitor does not descend into the tree, as export/import statements - // are only transformed at the top level of a file. - return node; - } - } - /** - * Visits an ImportDeclaration node. - * - * @param node The ImportDeclaration node. - */ - function visitImportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var statements = []; - var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); - if (moduleKind !== ts.ModuleKind.AMD) { - if (!node.importClause) { - // import "mod"; - statements.push(ts.createStatement(createRequireCall(node), - /*location*/ node)); - } - else { - var variables = []; - if (namespaceDeclaration && !ts.isDefaultImport(node)) { - // import * as n from "mod"; - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); - } - else { - // import d from "mod"; - // import { x, y } from "mod"; - // import d, { x, y } from "mod"; - // import d, * as n from "mod"; - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); - if (namespaceDeclaration && ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, ts.getGeneratedNameForNode(node))); - } - } - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createConstDeclarationList(variables), - /*location*/ node)); - } - } - else if (namespaceDeclaration && ts.isDefaultImport(node)) { - // import d, * as n from "mod"; - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, ts.getGeneratedNameForNode(node), - /*location*/ node) - ]))); - } - addExportImportAssignments(statements, node); - return ts.singleOrMany(statements); - } - function visitImportEqualsDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - // Set emitFlags on the name of the importEqualsDeclaration - // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); - var statements = []; - if (moduleKind !== ts.ModuleKind.AMD) { - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), - /*location*/ node)); - } - else { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), - /*type*/ undefined, createRequireCall(node)) - ], - /*location*/ undefined, - /*flags*/ languageVersion >= 2 /* ES6 */ ? 2 /* Const */ : 0 /* None */), - /*location*/ node)); - } - } - else { - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.createStatement(createExportAssignment(node.name, node.name), - /*location*/ node)); - } - } - addExportImportAssignments(statements, node); - return statements; - } - function visitExportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var generatedName = ts.getGeneratedNameForNode(node); - if (node.exportClause) { - var statements = []; - // export { x, y } from "mod"; - if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(generatedName, - /*type*/ undefined, createRequireCall(node)) - ]), - /*location*/ node)); - } - for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { - var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), - /*location*/ specifier)); - } - } - return ts.singleOrMany(statements); - } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - // export * from "mod"; - return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), - /*typeArguments*/ undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ]), - /*location*/ node); - } - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - var statements = []; - addExportDefault(statements, node.expression, /*location*/ node); - return statements; - } - } - return undefined; - } - function addExportDefault(statements, expression, location) { - tryAddExportDefaultCompat(statements); - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); - } - function tryAddExportDefaultCompat(statements) { - var original = ts.getOriginalNode(currentSourceFile); - ts.Debug.assert(original.kind === 256 /* SourceFile */); - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === 0 /* ES3 */) { - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); - } - else { - statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) - ]) - ]))); - } - } - } - function addExportImportAssignments(statements, node) { - if (ts.isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); - } - else { - var names = ts.reduceEachChild(node, collectExportMembers, []); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); - } - } - } - function collectExportMembers(names, node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); - } - } - return ts.reduceEachChild(node, collectExportMembers, names); - } - function addExportMemberAssignments(statements, name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), - /*location*/ specifier.name))); - } - } - } - function addExportMemberAssignment(statements, node) { - if (ts.hasModifier(node, 512 /* Default */)) { - addExportDefault(statements, getDeclarationName(node), /*location*/ node); - } - else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); - } - } - function visitVariableStatement(node) { - // If the variable is for a generated declaration, - // we should maintain it and just strip off the 'export' modifier if necessary. - var originalKind = ts.getOriginalNode(node).kind; - if (originalKind === 225 /* ModuleDeclaration */ || - originalKind === 224 /* EnumDeclaration */ || - originalKind === 221 /* ClassDeclaration */) { - if (!ts.hasModifier(node, 1 /* Export */)) { - return node; - } - return ts.setOriginalNode(ts.createVariableStatement( - /*modifiers*/ undefined, node.declarationList), node); - } - var resultStatements = []; - // If we're exporting these variables, then these just become assignments to 'exports.blah'. - // We only want to emit assignments for variables with initializers. - if (ts.hasModifier(node, 1 /* Export */)) { - var variables = ts.getInitializedVariables(node.declarationList); - if (variables.length > 0) { - var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - // While we might not have been exported here, each variable might have been exported - // later on in an export specifier (e.g. `export {foo as blah, bar}`). - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - return resultStatements; - } - /** - * Creates appropriate assignments for each binding identifier that is exported in an export specifier, - * and inserts it into 'resultStatements'. - */ - function addExportMemberAssignmentsForBindingName(resultStatements, name) { - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - var sourceFileId = ts.getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - function transformInitializedVariable(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); - } - else { - return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); - } - } - function visitFunctionDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name, - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body, - /*location*/ node), - /*original*/ node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - if (node.name) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitClassDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.setOriginalNode(ts.createClassDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, name, - /*typeParameters*/ undefined, node.heritageClauses, node.members, - /*location*/ node), - /*original*/ node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - // Decorators end up creating a series of assignment expressions which overwrite - // the local binding that we export, so we need to defer from exporting decorated classes - // until the decoration assignments take place. We do this when visiting expression-statements. - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitExpressionStatement(node) { - var original = ts.getOriginalNode(node); - var origKind = original.kind; - if (origKind === 224 /* EnumDeclaration */ || origKind === 225 /* ModuleDeclaration */) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === 221 /* ClassDeclaration */) { - // The decorated assignment for a class name may need to be transformed. - var classDecl = original; - if (classDecl.name) { - var statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; - } - } - return node; - } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { - var statements = [node]; - // Preserve old behavior for enums in which a variable statement is emitted after the body itself. - if (ts.hasModifier(original, 1 /* Export */) && - original.kind === 224 /* EnumDeclaration */ && - ts.isFirstDeclarationOfKind(original, 224 /* EnumDeclaration */)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); - } - addExportMemberAssignments(statements, original.name); - return statements; - } - /** - * Adds a trailing VariableStatement for an enum or module declaration. - */ - function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { - var transformedStatement = ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), - /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], - /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); - statements.push(transformedStatement); - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function onEmitNode(node, emit) { - if (node.kind === 256 /* SourceFile */) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - bindingNameExportSpecifiersMap = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - /** - * Hooks node substitutions. - * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. - */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - else if (ts.isShorthandPropertyAssignment(node)) { - return substituteShorthandPropertyAssignment(node); - } - return node; - } - function substituteShorthandPropertyAssignment(node) { - var name = node.name; - var exportedOrImportedName = substituteExpressionIdentifier(name); - if (exportedOrImportedName !== name) { - // A shorthand property with an assignment initializer is probably part of a - // destructuring assignment - if (node.objectAssignmentInitializer) { - var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name, initializer, /*location*/ node); - } - return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69 /* Identifier */: - return substituteExpressionIdentifier(node); - case 187 /* BinaryExpression */: - return substituteBinaryExpression(node); - case 186 /* PostfixUnaryExpression */: - case 185 /* PrefixUnaryExpression */: - return substituteUnaryExpression(node); - } - return node; - } - function substituteExpressionIdentifier(node) { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; - } - function substituteBinaryExpression(node) { - var left = node.left; - // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier - if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); - } - return nestedExportAssignment; - } - } - return node; - } - function substituteUnaryExpression(node) { - // Because how the compiler only parse plusplus and minusminus to be either prefixUnaryExpression or postFixUnaryExpression depended on where they are - // We don't need to check that the operator has SyntaxKind.plusplus or SyntaxKind.minusminus - var operator = node.operator; - var operand = node.operand; - if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var transformedUnaryExpression = void 0; - if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), - /*location*/ node); - // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); - } - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; - } - } - return node; - } - function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); - if ((emitFlags & 262144 /* LocalName */) === 0) { - var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); - if (container) { - if (container.kind === 256 /* SourceFile */) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), - /*location*/ node); - } - } - } - return undefined; - } - function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (ts.isImportClause(declaration)) { - if (languageVersion >= 1 /* ES5 */) { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), - /*location*/ node); - } - else { - // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), - /*location*/ node); - } - } - else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { - // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), - /*location*/ node); - } - else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), - /*location*/ node); - } - } - } - } - return undefined; - } - function getModuleMemberName(name) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), name, - /*location*/ name); - } - function createRequireCall(importNode) { - var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var args = []; - if (ts.isDefined(moduleName)) { - args.push(moduleName); - } - return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); - } - function createExportStatement(name, value, location) { - var statement = ts.createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - return statement; - } - function createExportAssignment(name, value) { - return ts.createAssignment(name.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion === 0 /* ES3 */ - ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) - : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); - } - function collectAsynchronousDependencies(node, includeNonAmdDependencies) { - // names of modules with corresponding parameter in the factory function - var aliasedModuleNames = []; - // names of modules with no corresponding parameters in factory function - var unaliasedModuleNames = []; - // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - var importAliasNames = []; - // Fill in amd-dependency tags - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - } - } - for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { - var importNode = externalImports_3[_b]; - // Find the name of the external module - var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - // Find the name of the module alias, if there is one - var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - // Set emitFlags on the name of the classDeclaration - // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function updateSourceFile(node, statements) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - return updated; - } - var _a; + return ts.createCall(ts.getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray, location); } - ts.transformModule = transformModule; })(ts || (ts = {})); /// /// /*@internal*/ var ts; (function (ts) { - var entities = createEntitiesMap(); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 176 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 192 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 188 /* VoidExpression */: + return visitVoidExpression(node); + case 150 /* Constructor */: + return visitConstructorDeclaration(node); + case 149 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 151 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 152 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 184 /* FunctionExpression */: + return visitFunctionExpression(node); + case 185 /* ArrowFunction */: + return visitArrowFunction(node); + case 144 /* Parameter */: + return visitParameter(node); + case 207 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 183 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; + if (e.kind === 259 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === 257 /* PropertyAssignment */) { + var p = e; + chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); + } + else { + chunkObject.push(e); + } + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 176 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 25 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + var leadingStatements; + var temp; + var initializer = ts.skipParentheses(node.initializer); + if (initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isVariableDeclarationList(initializer)) { + temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var firstDeclaration = ts.firstOrUndefined(initializer.declarations); + var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(initializer, declarations), + /*location*/ initializer); + leadingStatements = ts.append(leadingStatements, statement); + } + } + else if (ts.isAssignmentPattern(initializer)) { + temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, /*location*/ node.initializer)), visitor, context, 1 /* ObjectRest */); + leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, /*location*/ node.initializer)); + } + } + if (temp) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var block = ts.isBlock(statement) + ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements)) + : ts.createBlock(ts.append(leadingStatements, statement), statement, /*multiLine*/ true); + return ts.updateForOf(node, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer) + ], node.initializer, 1 /* Let */), expression, block); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParameter(node) { + if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + return ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitGetAccessorDeclaration(node) { + return ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitSetAccessorDeclaration(node) { + return ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var leadingStatements; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + leadingStatements = ts.append(leadingStatements, statement); + } + } + } + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + var trailingStatements = endLexicalEnvironment(); + if (ts.some(leadingStatements) || ts.some(trailingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); + } + return body; + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + }; + function createAssignHelper(context, attributesSegments) { + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; @@ -46098,44 +48342,44 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; - return node; + return visited; } function visitor(node) { - if (node.transformFlags & 4 /* Jsx */) { + if (node.transformFlags & 4 /* ContainsJsx */) { return visitorWorker(node); } - else if (node.transformFlags & 8 /* ContainsJsx */) { - return ts.visitEachChild(node, visitor, context); - } else { return node; } } function visitorWorker(node) { switch (node.kind) { - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitJsxExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.visitEachChild(node, visitor, context); } } function transformJsxChildToExpression(node) { switch (node.kind) { - case 244 /* JsxText */: + case 10 /* JsxText */: return visitJsxText(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitJsxExpression(node); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); default: ts.Debug.failBadSyntaxKind(node); @@ -46169,10 +48413,12 @@ var ts; } // Either emit one big object literal (no spread attribs), or // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) - || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } } - var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -46194,7 +48440,7 @@ var ts; var decoded = tryDecodeEntities(node.text); return decoded ? ts.createLiteral(decoded, /*location*/ node) : node; } - else if (node.kind === 248 /* JsxExpression */) { + else if (node.kind === 252 /* JsxExpression */) { return visitJsxExpression(node); } else { @@ -46276,7 +48522,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 241 /* JsxElement */) { + if (node.kind === 246 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -46308,337 +48554,3217 @@ var ts; } } ts.transformJsx = transformJsx; - function createEntitiesMap() { - return ts.createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + var entities = ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); })(ts || (ts = {})); /// /// /*@internal*/ var ts; (function (ts) { - function transformES7(context) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var currentSuperContainer; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 119 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 189 /* AwaitExpression */: + // ES2017 'await' expressions must be transformed for targets < ES2017. + return visitAwaitExpression(node); + case 149 /* MethodDeclaration */: + // ES2017 method declarations may be 'async' + return visitMethodDeclaration(node); + case 225 /* FunctionDeclaration */: + // ES2017 function declarations may be 'async' + return visitFunctionDeclaration(node); + case 184 /* FunctionExpression */: + // ES2017 function expressions may be 'async' + return visitFunctionExpression(node); + case 185 /* ArrowFunction */: + // ES2017 arrow functions may be 'async' + return visitArrowFunction(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 185 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES2015 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, asyncSuperHelper); + } + } + return block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements)); + } + return expression; + } + } + function transformFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); + var declarations = endLexicalEnvironment(); + return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(179 /* CallExpression */); + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(178 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(226 /* ClassDeclaration */); + context.enableEmitNotification(149 /* MethodDeclaration */); + context.enableEmitNotification(151 /* GetAccessor */); + context.enableEmitNotification(152 /* SetAccessor */); + context.enableEmitNotification(150 /* Constructor */); + } + } + function substituteExpression(node) { + switch (node.kind) { + case 177 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 179 /* CallExpression */: + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) { + return substituteCallExpression(node); + } + break; + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 226 /* ClassDeclaration */ + || kind === 150 /* Constructor */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */; + } + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + } + } + ts.transformES2017 = transformES2017; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(38 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: "\n const _super = name => super[name];" + }; + var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);" + }; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if (node.transformFlags & 16 /* ES7 */) { - return visitorWorker(node); + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; } - else if (node.transformFlags & 32 /* ContainsES7 */) { + switch (node.kind) { + case 192 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 61 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 39 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), + /*location*/ left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, + /*location*/ left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, + /*location*/ left); + value = ts.createPropertyAccess(expressionTemp, left.name, + /*location*/ left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var isInConstructorWithCapturedSuper; + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + // don't treat content of nodes that start new lexical environment as part of converted loop copy or constructor body + isInConstructorWithCapturedSuper = false; + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 185 /* ArrowFunction */) { + enclosingNonArrowFunction = currentNode; + if (!(ts.getEmitFlags(currentNode) & 131072 /* AsyncFunctionBody */)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + // keep track of the enclosing variable statement when in the context of + // variable statements, variable declarations, binding elements, and binding + // patterns. + switch (currentNode.kind) { + case 205 /* VariableStatement */: + enclosingVariableStatement = currentNode; + break; + case 224 /* VariableDeclarationList */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return isInConstructorWithCapturedSuper && node.kind === 216 /* ReturnStatement */ && !node.expression; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64 /* ES2015 */) !== 0 || + node.kind === 219 /* LabeledStatement */ || + (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128 /* ContainsES2015 */ || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) { + // we want to dive in this branch either if node has children with ES2015 specific syntax + // or we are inside constructor that captures result of the super call so all returns without expression should be + // rewritten. Note: we skip expressions since returns should never appear there return ts.visitEachChild(node, visitor, context); } else { return node; } } - function visitorWorker(node) { + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 187 /* BinaryExpression */: - return visitBinaryExpression(node); + case 216 /* ReturnStatement */: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; + return visitReturnStatement(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 218 /* SwitchStatement */: + return visitSwitchStatement(node); + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 98 /* ThisKeyword */: + return visitThisKeyword(node); + case 70 /* Identifier */: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 114 /* StaticKeyword */: + return undefined; // elide static keyword + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 197 /* ClassExpression */: + return visitClassExpression(node); + case 144 /* Parameter */: + return visitParameter(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 185 /* ArrowFunction */: + return visitArrowFunction(node); + case 184 /* FunctionExpression */: + return visitFunctionExpression(node); + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 70 /* Identifier */: + return visitIdentifier(node); + case 224 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 219 /* LabeledStatement */: + return visitLabeledStatement(node); + case 209 /* DoStatement */: + return visitDoStatement(node); + case 210 /* WhileStatement */: + return visitWhileStatement(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 212 /* ForInStatement */: + return visitForInStatement(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 207 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 176 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 256 /* CatchClause */: + return visitCatchClause(node); + case 258 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 175 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 179 /* CallExpression */: + return visitCallExpression(node); + case 180 /* NewExpression */: + return visitNewExpression(node); + case 183 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 192 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: + return visitTemplateLiteral(node); + case 181 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 194 /* TemplateExpression */: + return visitTemplateExpression(node); + case 195 /* YieldExpression */: + return visitYieldExpression(node); + case 196 /* SpreadElement */: + return visitSpreadElement(node); + case 96 /* SuperKeyword */: + return visitSuperKeyword(); + case 195 /* YieldExpression */: + // `yield` will be handled by a generators transform. + return ts.visitEachChild(node, visitor, context); + case 149 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function visitBinaryExpression(node) { - // We are here because ES7 adds support for the exponentiation operator. - var left = ts.visitNode(node.left, visitor, ts.isExpression); - var right = ts.visitNode(node.right, visitor, ts.isExpression); - if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var target = void 0; - var value = void 0; - if (ts.isElementAccessExpression(left)) { - // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), - /*location*/ left); - value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, - /*location*/ left); - } - else if (ts.isPropertyAccessExpression(left)) { - // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, - /*location*/ left); - value = ts.createPropertyAccess(expressionTemp, left.name, - /*location*/ left); - } - else { - // Transforms `a **= b` into `a = Math.pow(a, b)` - target = left; - value = left; - } - return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + function visitSourceFile(node) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8 /* Return */; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 185 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; } - else if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */) { - // Transforms `a ** b` into `Math.pow(a, b)` - return ts.createMathPow(left, right, /*location*/ node); + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; } - else { - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 215 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 215 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 215 /* BreakStatement */) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 25 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 25 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]), /*location*/ node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 2097152 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 2097152 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + if (ts.getEmitFlags(node) & 32768 /* Indented */) { + ts.setEmitFlags(classFunction, 32768 /* Indented */); + } + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + return ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 17 /* CloseBraceToken */); + var localName = ts.getLocalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)), + /*location*/ extendsClauseElement)); } } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getDeclarationName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + var body = saveStateAndInvoke(constructor, function (constructor) { + isInConstructorWithCapturedSuper = superCaptureStatus === 1 /* ReplaceSuperCapture */; + return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); + }); + ts.addRange(statements, body); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : node, + /*multiLine*/ true); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 216 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 208 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 204 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 192 /* BinaryExpression */ + || superCallExpression.left.kind !== 179 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_36 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_36)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_36, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_36, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 524288 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer)), + /*location*/ parameter)) + ], /*location*/ parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */), + /*elseStatement*/ undefined, + /*location*/ parameter); + statement.startsOnNewLine = true; + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 524288 /* CustomPrologue */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 70 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ]), + /*location*/ parameter), 524288 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), + /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 524288 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 185 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 524288 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 203 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 149 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 150 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(/*location*/ member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 185 /* ArrowFunction */) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), + /*original*/ node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); + // If we added any generated statements, this must be a multi-line block. + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 185 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, /*location*/ body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + // If we added any final generated statements, this must be a multi-line block + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 17 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 183 /* ParenthesizedExpression */: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 192 /* BinaryExpression */: + return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + switch (node.expression.kind) { + case 183 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 192 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 57 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25 /* CommaToken */, acc); }), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); + ts.setOriginalNode(declarationList, node); + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 212 /* ForInStatement */ + && enclosingBlockScopeContainer.kind !== 213 /* ForOfStatement */ + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_3 = ts.getMutableClone(node); + clone_3.initializer = ts.createVoidZero(); + return clone_3; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern. + if (ts.isBindingPattern(node.name)) { + var hoistTempVariables = enclosingVariableStatement + && ts.hasModifier(enclosingVariableStatement, 1 /* Export */); + return ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, hoistTempVariables); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + /** + * Visits a ForOfStatement and converts it into a compatible ForStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 70 /* Identifier */ + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + var elementAccess = ts.createElementAccess(rhsReference, counter); + // Initialize LHS + // var v = _a[_i]; + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, elementAccess); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); + ts.setOriginalNode(declarationList, initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) + ], /*location*/ ts.moveRangePos(initializer, -1)), initializer), + /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, elementAccess); + if (ts.isDestructuringAssignment(assignment)) { + // This is a destructuring pattern, so we flatten the destructuring instead. + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0 /* All */))); + } + else { + // Currently there is not way to check that assignment is binary expression of destructing assignment + // so we have to cast never type to binaryExpression + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + // The old emitter does not emit source maps for the block. + // We add the location to preserve comments. + var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), + /*location*/ bodyLocation); + ts.setEmitFlags(body, 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) + ], /*location*/ node.expression), 1048576 /* NoHoisting */), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), + /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + return forStatement; + } + /** + * Visits an ObjectLiteralExpression with computed propety names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 16777216 /* ContainsYield */ + || property.name.kind === 142 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, node.multiLine), 32768 /* Indented */)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 70 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 224 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (outerConvertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + startLexicalEnvironment(); + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length || lexicalEnvironment) { + var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); + loopBody = ts.createBlock(statements_4, /*location*/ undefined, /*multiline*/ true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072 /* AsyncFunctionBody */) !== 0 + && (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 8 /* CapturesThis */; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 131072 /* AsyncFunctionBody */; + } + var convertedLoopVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, isAsyncBlockContainingAwait ? ts.createToken(38 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, loopParameters, + /*type*/ undefined, loopBody), loopBodyFlags)) + ]), 1048576 /* NoHoisting */)); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (currentState.argumentsName) { + // if alias for arguments is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + // if alias for this is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerConvertedLoopState) { + // pass them to outer converted loop + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + // clean statement part + loop.statement = undefined; + // visit childnodes to transform initializer/condition/incrementor parts + loop = ts.visitEachChild(loop, visitor, context); + // set loop statement + loop.statement = ts.createBlock(convertedLoopBodyStatements, + /*location*/ undefined, + /*multiline*/ true); + // reset and re-aggregate the transform flags + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 219 /* LabeledStatement */ + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 57 /* EqualsToken */, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38 /* AsteriskToken */), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 33 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 33 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 257 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 258 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 149 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), + /*location*/ method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitCatchClause(node) { + ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name)); + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars, /*location*/ node.variableDeclaration, /*flags*/ node.variableDeclaration.flags); + var destructure = ts.createVariableStatement(undefined, list); + return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, + /*location*/ node); + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), + /*location*/ node); + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 96 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall; + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 96 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + // We are here because we contain a SpreadElementExpression. + ts.Debug.assert((node.transformFlags & 524288 /* ContainsSpread */) !== 0); + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpread(node) { + return ts.isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), + /*location*/ undefined, multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, /*location*/ node); + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Allocate storage for the template site object + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Build up the template arguments and the raw and cooked strings for the template. + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + // NOTE: The parentheses here is entirely optional as we are now able to auto- + // parenthesize when rebuilding the tree. This should be removed in a + // future version. It is here for now to match our existing emit. + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) + ])); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 12 /* NoSubstitutionTemplateLiteral */ || node.kind === 15 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, /*location*/ node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword() { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) + && currentParent.kind !== 179 /* CallExpression */ + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + /** + * Called by the printer just before a node is printed. + * + * @param node The node to be printed. + */ + function onEmitNode(emitContext, node, emitCallback) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + enclosingFunction = node; + } + previousOnEmitNode(emitContext, node, emitCallback); + enclosingFunction = savedEnclosingFunction; + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(70 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(98 /* ThisKeyword */); + context.enableEmitNotification(150 /* Constructor */); + context.enableEmitNotification(149 /* MethodDeclaration */); + context.enableEmitNotification(151 /* GetAccessor */); + context.enableEmitNotification(152 /* SetAccessor */); + context.enableEmitNotification(185 /* ArrowFunction */); + context.enableEmitNotification(184 /* FunctionExpression */); + context.enableEmitNotification(225 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param emitContext The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 174 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 223 /* VariableDeclaration */: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 70 /* Identifier */: + return substituteExpressionIdentifier(node); + case 98 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && enclosingFunction + && ts.getEmitFlags(enclosingFunction) & 8 /* CapturesThis */) { + return ts.createIdentifier("_this", /*location*/ node); + } + return node; + } + function getClassMemberPrefix(node, member) { + var expression = ts.getLocalName(node); + return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 96 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.text === "arguments"; + } } - ts.transformES7 = transformES7; + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createIdentifier("_super") + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };" + }; })(ts || (ts = {})); /// /// @@ -46820,7 +51946,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,12 +51996,15 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (node.transformFlags & 1024 /* ContainsGenerator */) { - currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); - currentSourceFile = undefined; + if (ts.isDeclarationFile(node) + || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; } - return node; + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } /** * Visits a node. @@ -46890,10 +52019,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 512 /* Generator */) { + else if (transformFlags & 256 /* Generator */) { return visitGenerator(node); } - else if (transformFlags & 1024 /* ContainsGenerator */) { + else if (transformFlags & 512 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -46907,13 +52036,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 204 /* DoStatement */: + case 209 /* DoStatement */: return visitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return visitWhileStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return visitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -46926,30 +52055,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return visitFunctionExpression(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return visitAccessorDeclaration(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return visitVariableStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return visitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return visitForInStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return visitBreakStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return visitContinueStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 16777216 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -46964,21 +52093,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return visitBinaryExpression(node); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return visitConditionalExpression(node); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return visitYieldExpression(node); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return visitCallExpression(node); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -46991,9 +52120,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -47011,12 +52140,11 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, + /*decorators*/ undefined, node.modifiers, /*asteriskToken*/ undefined, node.name, - /*typeParameters*/ undefined, node.parameters, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node), node); } @@ -47050,10 +52178,11 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, node.name, - /*typeParameters*/ undefined, node.parameters, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node), node); } @@ -47099,6 +52228,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +52242,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47120,7 +52251,7 @@ var ts; operationLocations = undefined; state = ts.createTempVariable(/*recordTempVariable*/ undefined); // Build the generator - startLexicalEnvironment(); + resumeLexicalEnvironment(); var statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); @@ -47132,6 +52263,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47150,13 +52282,13 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 16777216 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 524288 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -47189,23 +52321,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 57 /* FirstCompoundAssignment */ - && kind <= 68 /* LastCompoundAssignment */; + return kind >= 58 /* FirstCompoundAssignment */ + && kind <= 69 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 57 /* PlusEqualsToken */: return 35 /* PlusToken */; - case 58 /* MinusEqualsToken */: return 36 /* MinusToken */; - case 59 /* AsteriskEqualsToken */: return 37 /* AsteriskToken */; - case 60 /* AsteriskAsteriskEqualsToken */: return 38 /* AsteriskAsteriskToken */; - case 61 /* SlashEqualsToken */: return 39 /* SlashToken */; - case 62 /* PercentEqualsToken */: return 40 /* PercentToken */; - case 63 /* LessThanLessThanEqualsToken */: return 43 /* LessThanLessThanToken */; - case 64 /* GreaterThanGreaterThanEqualsToken */: return 44 /* GreaterThanGreaterThanToken */; - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanGreaterThanToken */; - case 66 /* AmpersandEqualsToken */: return 46 /* AmpersandToken */; - case 67 /* BarEqualsToken */: return 47 /* BarToken */; - case 68 /* CaretEqualsToken */: return 48 /* CaretToken */; + case 58 /* PlusEqualsToken */: return 36 /* PlusToken */; + case 59 /* MinusEqualsToken */: return 37 /* MinusToken */; + case 60 /* AsteriskEqualsToken */: return 38 /* AsteriskToken */; + case 61 /* AsteriskAsteriskEqualsToken */: return 39 /* AsteriskAsteriskToken */; + case 62 /* SlashEqualsToken */: return 40 /* SlashToken */; + case 63 /* PercentEqualsToken */: return 41 /* PercentToken */; + case 64 /* LessThanLessThanEqualsToken */: return 44 /* LessThanLessThanToken */; + case 65 /* GreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanToken */; + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanGreaterThanToken */; + case 67 /* AmpersandEqualsToken */: return 47 /* AmpersandToken */; + case 68 /* BarEqualsToken */: return 48 /* BarToken */; + case 69 /* CaretEqualsToken */: return 49 /* CaretToken */; } } /** @@ -47218,7 +52350,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -47230,7 +52362,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -47249,7 +52381,7 @@ var ts; } var operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return ts.createBinary(target, 56 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + return ts.createBinary(target, 57 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); } else { return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); @@ -47262,7 +52394,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 24 /* CommaToken */) { + else if (node.operatorToken.kind === 25 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -47273,10 +52405,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -47317,7 +52449,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -47348,7 +52480,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 25 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -47429,7 +52561,7 @@ var ts; * @param node The node to visit. */ function visitArrayLiteralExpression(node) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); } /** * Visits an array of expressions containing one or more YieldExpression nodes @@ -47438,7 +52570,7 @@ var ts; * @param elements The elements to visit. * @param multiLine Whether array literals created should be emitted on multiple lines. */ - function visitElements(elements, multiLine) { + function visitElements(elements, leadingElement, location, multiLine) { // [source] // ar = [1, yield, 2]; // @@ -47452,19 +52584,24 @@ var ts; var temp = declareLocal(); var hasAssignedTemp = false; if (numInitialElements > 0) { - emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; hasAssignedTemp = true; } var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine); function reduceElement(expressions, element) { if (containsYield(element) && expressions.length > 0) { emitAssignment(temp, hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions)); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, + /*location*/ undefined, multiLine)); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } expressions.push(ts.visitNode(element, visitor, ts.isExpression)); @@ -47530,10 +52667,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -47550,7 +52687,7 @@ var ts; // .mark resumeLabel // _b.apply(_a, _c.concat([%sent%, 2])); var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false), + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); @@ -47568,7 +52705,8 @@ var ts; // .mark resumeLabel // new (_b.apply(_a, _c.concat([%sent%, 2]))); var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false)), + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), /*typeArguments*/ undefined, [], /*location*/ node), node); } @@ -47599,35 +52737,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 199 /* Block */: + case 204 /* Block */: return transformAndEmitBlock(node); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return transformAndEmitIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return transformAndEmitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return transformAndEmitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return transformAndEmitWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement, /*optional*/ true)); @@ -48047,7 +53185,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 250 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 254 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -48060,7 +53198,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 249 /* CaseClause */) { + if (clause.kind === 253 /* CaseClause */) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -48191,7 +53329,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -48202,9 +53340,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,12 +53359,12 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); - return clone_7; + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_6 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -48368,7 +53506,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = ts.createMap(); - context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(70 /* Identifier */); } renamedCatchVariables[text] = true; renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -48625,7 +53763,7 @@ var ts; if (labelExpressions === undefined) { labelExpressions = []; } - var expression = ts.createSynthesizedNode(8 /* NumericLiteral */); + var expression = ts.createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -48634,7 +53772,7 @@ var ts; } return expression; } - return ts.createNode(193 /* OmittedExpression */); + return ts.createOmittedExpression(); } /** * Creates a numeric literal for the provided instruction. @@ -48812,17 +53950,14 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), - /*typeArguments*/ undefined, [ - ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(state)], - /*type*/ undefined, ts.createBlock(buildResult, - /*location*/ undefined, - /*multiLine*/ buildResult.length > 0)), 4194304 /* ReuseTempVariableScope */) - ]); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*location*/ undefined, + /*multiLine*/ buildResult.length > 0)), 262144 /* ReuseTempVariableScope */)); } /** * Builds the statements for the generator function body. @@ -49193,6 +54328,76 @@ var ts; } } ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; var _a; })(ts || (ts = {})); /// @@ -49200,2329 +54405,2634 @@ var ts; /*@internal*/ var ts; (function (ts) { - var ES6SubstitutionFlags; - (function (ES6SubstitutionFlags) { - /** Enables substitutions for captured `this` */ - ES6SubstitutionFlags[ES6SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; - /** Enables substitutions for block-scoped bindings. */ - ES6SubstitutionFlags[ES6SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; - })(ES6SubstitutionFlags || (ES6SubstitutionFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; - var resolver = context.getEmitResolver(); + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; - var currentText; - var currentParent; - var currentNode; - var enclosingVariableStatement; - var enclosingBlockScopeContainer; - var enclosingBlockScopeContainerParent; - var enclosingFunction; - var enclosingNonArrowFunction; - var enclosingNonAsyncFunctionBody; - /** - * Used to track if we are emitting body of the converted loop - */ - var convertedLoopState; - /** - * Keeps track of whether substitutions have been enabled for specific cases. - * They are persisted between each SourceFile transformation and should not - * be reset. - */ - var enabledSubstitutions; + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(257 /* PropertyAssignment */); return transformSourceFile; + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ function transformSourceFile(node) { - currentSourceFile = node; - currentText = node.text; - return ts.visitNode(node, visitor, ts.isSourceFile); - } - function visitor(node) { - return saveStateAndInvoke(node, dispatcher); - } - function dispatcher(node) { - return convertedLoopState - ? visitorForConvertedLoopWorker(node) - : visitorWorker(node); - } - function saveStateAndInvoke(node, f) { - var savedEnclosingFunction = enclosingFunction; - var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; - var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; - var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; - var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; - var savedEnclosingVariableStatement = enclosingVariableStatement; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var savedConvertedLoopState = convertedLoopState; - if (ts.nodeStartsNewLexicalEnvironment(node)) { - // don't treat content of nodes that start new lexical environment as part of converted loop copy - convertedLoopState = undefined; - } - onBeforeVisitNode(node); - var visited = f(node); - convertedLoopState = savedConvertedLoopState; - enclosingFunction = savedEnclosingFunction; - enclosingNonArrowFunction = savedEnclosingNonArrowFunction; - enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; - enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; - enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; - enclosingVariableStatement = savedEnclosingVariableStatement; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return visited; - } - function shouldCheckNode(node) { - return (node.transformFlags & 64 /* ES6 */) !== 0 || - node.kind === 214 /* LabeledStatement */ || - (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); - } - function visitorWorker(node) { - if (shouldCheckNode(node)) { - return visitJavaScript(node); - } - else if (node.transformFlags & 128 /* ContainsES6 */) { - return ts.visitEachChild(node, visitor, context); - } - else { - return node; - } - } - function visitorForConvertedLoopWorker(node) { - var result; - if (shouldCheckNode(node)) { - result = visitJavaScript(node); - } - else { - result = visitNodesInConvertedLoop(node); - } - return result; - } - function visitNodesInConvertedLoop(node) { - switch (node.kind) { - case 211 /* ReturnStatement */: - return visitReturnStatement(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 213 /* SwitchStatement */: - return visitSwitchStatement(node); - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - return visitBreakOrContinueStatement(node); - case 97 /* ThisKeyword */: - return visitThisKeyword(node); - case 69 /* Identifier */: - return visitIdentifier(node); - default: - return ts.visitEachChild(node, visitor, context); - } - } - function visitJavaScript(node) { - switch (node.kind) { - case 82 /* ExportKeyword */: - return node; - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 192 /* ClassExpression */: - return visitClassExpression(node); - case 142 /* Parameter */: - return visitParameter(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 180 /* ArrowFunction */: - return visitArrowFunction(node); - case 179 /* FunctionExpression */: - return visitFunctionExpression(node); - case 218 /* VariableDeclaration */: - return visitVariableDeclaration(node); - case 69 /* Identifier */: - return visitIdentifier(node); - case 219 /* VariableDeclarationList */: - return visitVariableDeclarationList(node); - case 214 /* LabeledStatement */: - return visitLabeledStatement(node); - case 204 /* DoStatement */: - return visitDoStatement(node); - case 205 /* WhileStatement */: - return visitWhileStatement(node); - case 206 /* ForStatement */: - return visitForStatement(node); - case 207 /* ForInStatement */: - return visitForInStatement(node); - case 208 /* ForOfStatement */: - return visitForOfStatement(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - case 171 /* ObjectLiteralExpression */: - return visitObjectLiteralExpression(node); - case 254 /* ShorthandPropertyAssignment */: - return visitShorthandPropertyAssignment(node); - case 170 /* ArrayLiteralExpression */: - return visitArrayLiteralExpression(node); - case 174 /* CallExpression */: - return visitCallExpression(node); - case 175 /* NewExpression */: - return visitNewExpression(node); - case 178 /* ParenthesizedExpression */: - return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 187 /* BinaryExpression */: - return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - return visitTemplateLiteral(node); - case 176 /* TaggedTemplateExpression */: - return visitTaggedTemplateExpression(node); - case 189 /* TemplateExpression */: - return visitTemplateExpression(node); - case 190 /* YieldExpression */: - return visitYieldExpression(node); - case 95 /* SuperKeyword */: - return visitSuperKeyword(node); - case 190 /* YieldExpression */: - // `yield` will be handled by a generators transform. - return ts.visitEachChild(node, visitor, context); - case 147 /* MethodDeclaration */: - return visitMethodDeclaration(node); - case 256 /* SourceFile */: - return visitSourceFileNode(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); - } - } - function onBeforeVisitNode(node) { - if (currentNode) { - if (ts.isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - if (ts.isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== 180 /* ArrowFunction */) { - enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - // keep track of the enclosing variable statement when in the context of - // variable statements, variable declarations, binding elements, and binding - // patterns. - switch (currentNode.kind) { - case 200 /* VariableStatement */: - enclosingVariableStatement = currentNode; - break; - case 219 /* VariableDeclarationList */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - break; - default: - enclosingVariableStatement = undefined; - } - } - currentParent = currentNode; - currentNode = node; - } - function visitSwitchStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - // for switch statement allow only non-labeled break - convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; - var result = ts.visitEachChild(node, visitor, context); - convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; - return result; - } - function visitReturnStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - convertedLoopState.nonLocalJumps |= 8 /* Return */; - return ts.createReturn(ts.createObjectLiteral([ - ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression - ? ts.visitNode(node.expression, visitor, ts.isExpression) - : ts.createVoidZero()) - ])); - } - function visitThisKeyword(node) { - ts.Debug.assert(convertedLoopState !== undefined); - if (enclosingFunction && enclosingFunction.kind === 180 /* ArrowFunction */) { - // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. - convertedLoopState.containsLexicalThis = true; - return node; - } - return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); - } - function visitIdentifier(node) { - if (!convertedLoopState) { - return node; - } - if (ts.isGeneratedIdentifier(node)) { - return node; - } - if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { - return node; - } - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); - } - function visitBreakOrContinueStatement(node) { - if (convertedLoopState) { - // check if we can emit break/continue as is - // it is possible if either - // - break/continue is labeled and label is located inside the converted loop - // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - var labelMarker = void 0; - if (!node.label) { - if (node.kind === 210 /* BreakStatement */) { - convertedLoopState.nonLocalJumps |= 2 /* Break */; - labelMarker = "break"; - } - else { - convertedLoopState.nonLocalJumps |= 4 /* Continue */; - // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. - labelMarker = "continue"; - } - } - else { - if (node.kind === 210 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); - } - } - var returnExpression = ts.createLiteral(labelMarker); - if (convertedLoopState.loopOutParameters.length) { - var outParams = convertedLoopState.loopOutParameters; - var expr = void 0; - for (var i = 0; i < outParams.length; i++) { - var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); - if (i === 0) { - expr = copyExpr; - } - else { - expr = ts.createBinary(expr, 24 /* CommaToken */, copyExpr); - } - } - returnExpression = ts.createBinary(expr, 24 /* CommaToken */, returnExpression); - } - return ts.createReturn(returnExpression); - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a ClassDeclaration and transforms it into a variable statement. - * - * @param node A ClassDeclaration node. - */ - function visitClassDeclaration(node) { - // [source] - // class C { } - // - // [output] - // var C = (function () { - // function C() { - // } - // return C; - // }()); - var modifierFlags = ts.getModifierFlags(node); - var isExported = modifierFlags & 1 /* Export */; - var isDefault = modifierFlags & 512 /* Default */; - // Add an `export` modifier to the statement if needed (for `--target es5 --module es6`) - var modifiers = isExported && !isDefault - ? ts.filter(node.modifiers, isExportModifier) - : undefined; - var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ true), - /*type*/ undefined, transformClassLikeDeclarationToExpression(node)) - ]), - /*location*/ node); - ts.setOriginalNode(statement, node); - ts.startOnNewLine(statement); - // Add an `export default` statement for default exports (for `--target es5 --module es6`) - if (isExported && isDefault) { - var statements = [statement]; - statements.push(ts.createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, getDeclarationName(node, /*allowComments*/ false))); - return statements; - } - return statement; - } - function isExportModifier(node) { - return node.kind === 82 /* ExportKeyword */; - } - /** - * Visits a ClassExpression and transforms it into an expression. - * - * @param node A ClassExpression node. - */ - function visitClassExpression(node) { - // [source] - // C = class { } - // - // [output] - // C = (function () { - // function class_1() { - // } - // return class_1; - // }()) - return transformClassLikeDeclarationToExpression(node); - } - /** - * Transforms a ClassExpression or ClassDeclaration into an expression. - * - * @param node A ClassExpression or ClassDeclaration node. - */ - function transformClassLikeDeclarationToExpression(node) { - // [source] - // class C extends D { - // constructor() {} - // method() {} - // get prop() {} - // set prop(v) {} - // } - // - // [output] - // (function (_super) { - // __extends(C, _super); - // function C() { - // } - // C.prototype.method = function () {} - // Object.defineProperty(C.prototype, "prop", { - // get: function() {}, - // set: function() {}, - // enumerable: true, - // configurable: true - // }); - // return C; - // }(D)) - if (node.name) { - enableSubstitutionsForBlockScopedBindings(); - } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], - /*type*/ undefined, transformClassBody(node, extendsClauseElement)); - // To preserve the behavior of the old emitter, we explicitly indent - // the body of the function here if it was requested in an earlier - // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); - } - // "inner" and "outer" below are added purely to preserve source map locations from - // the old emitter - var inner = ts.createPartiallyEmittedExpression(classFunction); - inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); - var outer = ts.createPartiallyEmittedExpression(inner); - outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); - return ts.createParen(ts.createCall(outer, - /*typeArguments*/ undefined, extendsClauseElement - ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] - : [])); - } - /** - * Transforms a ClassExpression or ClassDeclaration into a function body. - * - * @param node A ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function transformClassBody(node, extendsClauseElement) { - var statements = []; - startLexicalEnvironment(); - addExtendsHelperIfNeeded(statements, node, extendsClauseElement); - addConstructor(statements, node, extendsClauseElement); - addClassMembers(statements, node); - // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16 /* CloseBraceToken */); - var localName = getLocalName(node); - // The following partially-emitted expression exists purely to align our sourcemap - // emit with the original emitter. - var outer = ts.createPartiallyEmittedExpression(localName); - outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); - var statement = ts.createReturn(outer); - statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); - statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); - return block; - } - /** - * Adds a call to the `__extends` helper if needed for a class. - * - * @param statements The statements of the class body function. - * @param node The ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { - if (extendsClauseElement) { - statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), - /*location*/ extendsClauseElement)); - } - } - /** - * Adds the constructor of the class to a class body function. - * - * @param statements The statements of the class body function. - * @param node The ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function addConstructor(statements, node, extendsClauseElement) { - var constructor = ts.getFirstConstructorWithBody(node); - var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, getDeclarationName(node), - /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), - /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); - } - /** - * Transforms the parameters of the constructor declaration of a class. - * - * @param constructor The constructor for the class. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function transformConstructorParameters(constructor, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, we do not include the synthetic `...args` parameter and - // will instead use the `arguments` object in ES5/3. - if (constructor && !hasSynthesizedSuper) { - return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); - } - return []; - } - /** - * Transforms the body of a constructor declaration of a class. - * - * @param constructor The constructor for the class. - * @param node The node which contains the constructor. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - startLexicalEnvironment(); - if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); - if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); - ts.addRange(statements, body); - } - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, - /*location*/ constructor ? constructor.body.statements : node.members), - /*location*/ constructor ? constructor.body : node, - /*multiLine*/ true); - if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); - } - return block; - } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - /** - * Adds a synthesized call to `_super` if it is needed. - * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); - } - } - /** - * Visits a parameter declaration. - * - * @param node A ParameterDeclaration node. - */ - function visitParameter(node) { - if (node.dotDotDotToken) { - // rest parameters are elided - return undefined; - } - else if (ts.isBindingPattern(node.name)) { - // Binding patterns are converted into a generated name and are - // evaluated inside the function body. - return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), - /*initializer*/ undefined, - /*location*/ node), - /*original*/ node); - } - else if (node.initializer) { - // Initializers are elided - return ts.setOriginalNode(ts.createParameter(node.name, - /*initializer*/ undefined, - /*location*/ node), - /*original*/ node); - } - else { - return node; - } - } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; - } - /** - * Adds statements to the body of a function-like node if it contains parameters with - * binding patterns or initializers. - * - * @param statements The statements for the new function body. - * @param node A function-like node. - */ - function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; - // A rest parameter cannot have a binding pattern or an initializer, - // so let's just ignore it. - if (dotDotDotToken) { - continue; - } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); - } - else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); - } - } - } - /** - * Adds statements to the body of a function-like node for parameters with binding patterns - * - * @param statements The statements for the new function body. - * @param parameter The parameter for the function. - * @param name The name of the parameter. - * @param initializer The initializer for the parameter. - */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); - // In cases where a binding pattern is simply '[]' or '{}', - // we usually don't want to emit a var declaration; however, in the presence - // of an initializer, we must emit that expression to preserve side effects. - if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); - } - else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); - } - } - /** - * Adds statements to the body of a function-like node for parameters with initializers. - * - * @param statements The statements for the new function body. - * @param parameter The parameter for the function. - * @param name The name of the parameter. - * @param initializer The initializer for the parameter. - */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { - initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), - /*location*/ parameter)) - ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), - /*elseStatement*/ undefined, - /*location*/ parameter); - statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); - statements.push(statement); - } - /** - * Gets a value indicating whether we need to add statements to handle a rest parameter. - * - * @param node A ParameterDeclaration node. - * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is - * part of a constructor declaration with a - * synthesized call to `super` - */ - function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 69 /* Identifier */ && !inConstructorWithSynthesizedSuper; - } - /** - * Adds statements to the body of a function-like node if it contains a rest parameter. - * - * @param statements The statements for the new function body. - * @param node A function-like node. - * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is - * part of a constructor declaration with a - * synthesized call to `super` - */ - function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { - var parameter = ts.lastOrUndefined(node.parameters); - if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; - } - // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); - // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); - var restIndex = node.parameters.length - 1; - var temp = ts.createLoopVariable(); - // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(declarationName, - /*type*/ undefined, ts.createArrayLiteral([])) - ]), - /*location*/ parameter), 8388608 /* CustomPrologue */)); - // for (var _i = restIndex; _i < arguments.length; _i++) { - // param[_i - restIndex] = arguments[_i]; - // } - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) - ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), - /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ - ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), - /*location*/ parameter)) - ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); - ts.startOnNewLine(forStatement); - statements.push(forStatement); - } - /** - * Adds a statement to capture the `this` of a function declaration if it is needed. - * - * @param statements The statements for the new function body. - * @param node A node. - */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); - } - } - /** - * Adds statements to the class body function for a class to define the members of the - * class. - * - * @param statements The statements for the class body function. - * @param node The ClassExpression or ClassDeclaration node. - */ - function addClassMembers(statements, node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 198 /* SemicolonClassElement */: - statements.push(transformSemicolonClassElementToStatement(member)); - break; - case 147 /* MethodDeclaration */: - statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); - break; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); - } - break; - case 148 /* Constructor */: - // Constructors are handled in visitClassExpression/visitClassDeclaration - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - /** - * Transforms a SemicolonClassElement into a statement for a class body function. - * - * @param member The SemicolonClassElement node. - */ - function transformSemicolonClassElementToStatement(member) { - return ts.createEmptyStatement(/*location*/ member); - } - /** - * Transforms a MethodDeclaration into a statement for a class body function. - * - * @param receiver The receiver for the member. - * @param member The MethodDeclaration node. - */ - function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); - var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); - var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), - /*location*/ member.name), func), - /*location*/ member); - ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - // The location for the statement is used to emit comments only. - // No source map should be emitted for this statement to align with the - // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); - return statement; - } - /** - * Transforms a set of related of get/set accessors into a statement for a class body function. - * - * @param receiver The receiver for the member. - * @param accessors The set of related get/set accessors. - */ - function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); - // The location for the statement is used to emit source maps only. - // No comments should be emitted for this statement to align with the - // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); - return statement; - } - /** - * Transforms a set of related get/set accessors into an expression for either a class - * body function or an ObjectLiteralExpression with computed properties. - * - * @param receiver The receiver for the member. - */ - function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { - var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - // To align with source maps in the old emitter, the receiver and property name - // arguments are both mapped contiguously to the accessor name. - var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); - var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); - var properties = []; - if (getAccessor) { - var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); - var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); - properties.push(getter); - } - if (setAccessor) { - var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); - var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); - properties.push(setter); - } - properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); - var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - target, - propertyName, - ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) - ]); - if (startsOnNewLine) { - call.startsOnNewLine = true; - } - return call; - } - /** - * Visits an ArrowFunction and transforms it into a FunctionExpression. - * - * @param node An ArrowFunction node. - */ - function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); - } - var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); - return func; - } - /** - * Visits a FunctionExpression node. - * - * @param node a FunctionExpression node. - */ - function visitFunctionExpression(node) { - return transformFunctionLikeToExpression(node, /*location*/ node, node.name); - } - /** - * Visits a FunctionDeclaration node. - * - * @param node a FunctionDeclaration node. - */ - function visitFunctionDeclaration(node) { - return ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node), - /*original*/ node); - } - /** - * Transforms a function-like node into a FunctionExpression. - * - * @param node The function-like node to transform. - * @param location The source-map location for the new FunctionExpression. - * @param name The name of the new FunctionExpression. - */ - function transformFunctionLikeToExpression(node, location, name) { - var savedContainingNonArrowFunction = enclosingNonArrowFunction; - if (node.kind !== 180 /* ArrowFunction */) { - enclosingNonArrowFunction = node; - } - var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), - /*original*/ node); - enclosingNonArrowFunction = savedContainingNonArrowFunction; - return expression; - } - /** - * Transforms the body of a function-like node. - * - * @param node A function-like node. - */ - function transformFunctionBody(node) { - var multiLine = false; // indicates whether the block *must* be emitted as multiple lines - var singleLine = false; // indicates whether the block *may* be emitted as a single line - var statementsLocation; - var closeBraceLocation; - var statements = []; - var body = node.body; - var statementOffset; - startLexicalEnvironment(); - if (ts.isBlock(body)) { - // ensureUseStrict is false because no new prologue-directive should be added. - // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; - } - if (ts.isBlock(body)) { - statementsLocation = body.statements; - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); - // If the original body was a multi-line block, this must be a multi-line block. - if (!multiLine && body.multiLine) { - multiLine = true; - } - } - else { - ts.Debug.assert(node.kind === 180 /* ArrowFunction */); - // To align with the old emitter, we use a synthetic end position on the location - // for the statement list we synthesize when we down-level an arrow function with - // an expression function body. This prevents both comments and source maps from - // being emitted for the end position only. - statementsLocation = ts.moveRangeEnd(body, -1); - var equalsGreaterThanToken = node.equalsGreaterThanToken; - if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { - if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { - singleLine = true; - } - else { - multiLine = true; - } - } - var expression = ts.visitNode(body, visitor, ts.isExpression); - var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); - statements.push(returnStatement); - // To align with the source map emit for the old emitter, we set a custom - // source map location for the close brace. - closeBraceLocation = body; - } - var lexicalEnvironment = endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); - // If we added any final generated statements, this must be a multi-line block - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { - multiLine = true; - } - var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); - if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); - } - if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); - } - ts.setOriginalNode(block, node.body); - return block; - } - /** - * Visits an ExpressionStatement that contains a destructuring assignment. - * - * @param node An ExpressionStatement node. - */ - function visitExpressionStatement(node) { - // If we are here it is most likely because our expression is a destructuring assignment. - switch (node.expression.kind) { - case 178 /* ParenthesizedExpression */: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 187 /* BinaryExpression */: - return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a ParenthesizedExpression that may contain a destructuring assignment. - * - * @param node A ParenthesizedExpression node. - * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs - * of a destructuring assignment. - */ - function visitParenthesizedExpression(node, needsDestructuringValue) { - // If we are here it is most likely because our expression is a destructuring assignment. - if (needsDestructuringValue) { - switch (node.expression.kind) { - case 178 /* ParenthesizedExpression */: - return ts.createParen(visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node); - case 187 /* BinaryExpression */: - return ts.createParen(visitBinaryExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node); - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a BinaryExpression that contains a destructuring assignment. - * - * @param node A BinaryExpression node. - * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs - * of a destructuring assignment. - */ - function visitBinaryExpression(node, needsDestructuringValue) { - // If we are here it is because this is a destructuring assignment. - ts.Debug.assert(ts.isDestructuringAssignment(node)); - return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); - } - function visitVariableStatement(node) { - if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { - // we are inside a converted loop - hoist variable declarations - var assignments = void 0; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); - if (decl.initializer) { - var assignment = void 0; - if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); - } - else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); - } - (assignments || (assignments = [])).push(assignment); - } - } - if (assignments) { - return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24 /* CommaToken */, acc); }), node); - } - else { - // none of declarations has initializer - the entire variable statement can be deleted - return undefined; - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). - * - * @param node A VariableDeclarationList node. - */ - function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */) { - enableSubstitutionsForBlockScopedBindings(); - } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ - ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); - var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); - ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - } - return declarationList; - } - /** - * Gets a value indicating whether we should emit an explicit initializer for a variable - * declaration in a `let` declaration list. - * - * @param node A VariableDeclaration node. - */ - function shouldEmitExplicitInitializerForLetDeclaration(node) { - // Nested let bindings might need to be initialized explicitly to preserve - // ES6 semantic: - // - // { let x = 1; } - // { let x; } // x here should be undefined. not 1 - // - // Top level bindings never collide with anything and thus don't require - // explicit initialization. As for nested let bindings there are two cases: - // - // - Nested let bindings that were not renamed definitely should be - // initialized explicitly: - // - // { let x = 1; } - // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } - // - // Without explicit initialization code in /*1*/ can be executed even if - // some-condition is evaluated to false. - // - // - Renaming introduces fresh name that should not collide with any - // existing names, however renamed bindings sometimes also should be - // explicitly initialized. One particular case: non-captured binding - // declared inside loop body (but not in loop initializer): - // - // let x; - // for (;;) { - // let x; - // } - // - // In downlevel codegen inner 'x' will be renamed so it won't collide - // with outer 'x' however it will should be reset on every iteration as - // if it was declared anew. - // - // * Why non-captured binding? - // - Because if loop contains block scoped binding captured in some - // function then loop body will be rewritten to have a fresh scope - // on every iteration so everything will just work. - // - // * Why loop initializer is excluded? - // - Since we've introduced a fresh name it already will be undefined. - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) - || (isCapturedInFunction - && isDeclaredInLoop - && ts.isBlock(enclosingBlockScopeContainer) - && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); - var emitExplicitInitializer = !emittedAsTopLevel - && enclosingBlockScopeContainer.kind !== 207 /* ForInStatement */ - && enclosingBlockScopeContainer.kind !== 208 /* ForOfStatement */ - && (!resolver.isDeclarationWithCollidingName(node) - || (isDeclaredInLoop - && !isCapturedInFunction - && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); - return emitExplicitInitializer; - } - /** - * Visits a VariableDeclaration in a `let` declaration list. - * - * @param node A VariableDeclaration node. - */ - function visitVariableDeclarationInLetDeclarationList(node) { - // For binding pattern names that lack initializers there is no point to emit - // explicit initializer since downlevel codegen for destructuring will fail - // in the absence of initializer so all binding elements will say uninitialized - var name = node.name; - if (ts.isBindingPattern(name)) { - return visitVariableDeclaration(node); - } - if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_8 = ts.getMutableClone(node); - clone_8.initializer = ts.createVoidZero(); - return clone_8; - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a VariableDeclaration node with a binding pattern. - * - * @param node A VariableDeclaration node. - */ - function visitVariableDeclaration(node) { - // If we are here it is because the name contains a binding pattern. - if (ts.isBindingPattern(node.name)) { - var recordTempVariablesInLine = !enclosingVariableStatement - || !ts.hasModifier(enclosingVariableStatement, 1 /* Export */); - return ts.flattenVariableDestructuring(context, node, /*value*/ undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); - } - return ts.visitEachChild(node, visitor, context); - } - function visitLabeledStatement(node) { - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - var result; - if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { - result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); - } - else { - result = ts.visitEachChild(node, visitor, context); - } - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - return result; - } - function visitDoStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitWhileStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForInStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - /** - * Visits a ForOfStatement and converts it into a compatible ForStatement. - * - * @param node A ForOfStatement. - */ - function visitForOfStatement(node) { - return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); - } - function convertForOfToFor(node, convertedLoopBodyStatements) { - // The following ES6 code: - // - // for (let v of expr) { } - // - // should be emitted as - // - // for (var _i = 0, _a = expr; _i < _a.length; _i++) { - // var v = _a[_i]; - // } - // - // where _a and _i are temps emitted to capture the RHS and the counter, - // respectively. - // When the left hand side is an expression instead of a let declaration, - // the "let v" is not emitted. - // When the left hand side is a let/const, the v is renamed if there is - // another v in scope. - // Note that all assignments to the LHS are emitted in the body, including - // all destructuring. - // Note also that because an extra statement is needed to assign to the LHS, - // for-of bodies are always emitted as blocks. - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - var initializer = node.initializer; - var statements = []; - // In the case where the user wrote an identifier as the RHS, like this: - // - // for (let v of arr) { } - // - // we don't want to emit a temporary variable for the RHS, just use it directly. - var counter = ts.createLoopVariable(); - var rhsReference = expression.kind === 69 /* Identifier */ - ? ts.createUniqueName(expression.text) - : ts.createTempVariable(/*recordTempVariable*/ undefined); - // Initialize LHS - // var v = _a[_i]; - if (ts.isVariableDeclarationList(initializer)) { - if (initializer.flags & 3 /* BlockScoped */) { - enableSubstitutionsForBlockScopedBindings(); - } - var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); - if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - // This works whether the declaration is a var, let, or const. - // It will use rhsIterationValue _a[_i] as the initializer. - var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); - var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); - ts.setOriginalNode(declarationList, initializer); - // Adjust the source map range for the first declaration to align with the old - // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, declarationList)); - } - else { - // The following call does not include the initializer, so we have - // to emit it separately. - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), - /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) - ], /*location*/ ts.moveRangePos(initializer, -1)), - /*location*/ ts.moveRangeEnd(initializer, -1))); - } - } - else { - // Initializer is an expression. Emit the expression in the body, so that it's - // evaluated on every iteration. - var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); - if (ts.isDestructuringAssignment(assignment)) { - // This is a destructuring pattern, so we flatten the destructuring instead. - statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, - /*needsValue*/ false, hoistVariableDeclaration, visitor))); - } - else { - // Currently there is not way to check that assignment is binary expression of destructing assignment - // so we have to cast never type to binaryExpression - assignment.end = initializer.end; - statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); - } - } - var bodyLocation; - var statementsLocation; - if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); - } - else { - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); - if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; - } - else { - statements.push(statement); - } - } - // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); - // The old emitter does not emit source maps for the block. - // We add the location to preserve comments. - var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), - /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), - ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) - ], /*location*/ node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), - /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, - /*location*/ node); - // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); - return forStatement; - } - /** - * Visits an ObjectLiteralExpression with computed propety names. - * - * @param node An ObjectLiteralExpression node. - */ - function visitObjectLiteralExpression(node) { - // We are here because a ComputedPropertyName was used somewhere in the expression. - var properties = node.properties; - var numProperties = properties.length; - // Find the first computed property. - // Everything until that point can be emitted as part of the initial object literal. - var numInitialProperties = numProperties; - for (var i = 0; i < numProperties; i++) { - var property = properties[i]; - if (property.transformFlags & 4194304 /* ContainsYield */ - || property.name.kind === 140 /* ComputedPropertyName */) { - numInitialProperties = i; - break; - } - } - ts.Debug.assert(numInitialProperties !== numProperties); - // For computed properties, we need to create a unique handle to the object - // literal so we can modify it without risking internal assignments tainting the object. - var temp = ts.createTempVariable(hoistVariableDeclaration); - // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. - var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), - /*location*/ undefined, node.multiLine), 524288 /* Indented */)); - if (node.multiLine) { - assignment.startsOnNewLine = true; - } - expressions.push(assignment); - addObjectLiteralMembers(expressions, node, temp, numInitialProperties); - // We need to clone the temporary identifier so that we can write it on a - // new line - expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); - return ts.inlineExpressions(expressions); - } - function shouldConvertIterationStatementBody(node) { - return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; - } - /** - * Records constituents of name for the given variable to be hoisted in the outer scope. - */ - function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(node.name); - function visit(node) { - if (node.kind === 69 /* Identifier */) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - visit(element.name); - } - } - } - } - } - function convertIterationStatementBodyIfNecessary(node, convert) { - if (!shouldConvertIterationStatementBody(node)) { - var saveAllowedNonLabeledJumps = void 0; - if (convertedLoopState) { - // we get here if we are trying to emit normal loop loop inside converted loop - // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; - } - var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - return result; - } - var functionName = ts.createUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - var initializer = node.initializer; - if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { - loopInitializer = initializer; - } - break; - } - // variables that will be passed to the loop as parameters - var loopParameters = []; - // variables declared in the loop initializer that will be changed inside the loop - var loopOutParameters = []; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { - for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); - } - } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. - // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { - // outer loop has already used 'arguments' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; - } - if (outerConvertedLoopState.thisName) { - // outer loop has already used 'this' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; - } - if (outerConvertedLoopState.hoistedLocalVariables) { - // we've already collected some non-block scoped variable declarations in enclosing loop - // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; - } - } - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { - var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_3); - loopBody = ts.createBlock(statements_3, /*location*/ undefined, /*multiline*/ true); - } - if (!ts.isBlock(loopBody)) { - loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); - } - var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 - && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 256 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 2097152 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ])); - var statements = [convertedLoopVariable]; - var extraVariableDeclarations; - // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { - // if alias for arguments is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, - /*type*/ undefined, ts.createIdentifier("arguments"))); - } - } - if (currentState.thisName) { - // if alias for this is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; - } - else { - // this is top level converted loop so we need to create an alias for 'this' here - // NOTE: - // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. - // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, - /*type*/ undefined, ts.createIdentifier("this"))); - } - } - if (currentState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { - // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; - } - else { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; - extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); - } - } - } - // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; - extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); - } - } - // create variable statement to hold all introduced variable declarations - if (extraVariableDeclarations) { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); - } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); - var loop; - if (convert) { - loop = convert(node, convertedLoopBodyStatements); - } - else { - loop = ts.getMutableClone(node); - // clean statement part - loop.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - loop = ts.visitEachChild(loop, visitor, context); - // set loop statement - loop.statement = ts.createBlock(convertedLoopBodyStatements, - /*location*/ undefined, - /*multiline*/ true); - // reset and re-aggregate the transform flags - loop.transformFlags = 0; - ts.aggregateTransformFlags(loop); - } - statements.push(currentParent.kind === 214 /* LabeledStatement */ - ? ts.createLabel(currentParent.label, loop) - : loop); - return statements; - } - function copyOutParameter(outParam, copyDirection) { - var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; - var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 56 /* EqualsToken */, source); - } - function copyOutParameters(outParams, copyDirection, statements) { - for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { - var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); - } - } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; - var statements = []; - // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop - // simple loops are emitted as just 'loop()'; - // NOTE: if loop uses only 'continue' it still will be emitted as simple loop - var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && - !state.labeledNonLocalBreaks && - !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37 /* AsteriskToken */), call) : call; - if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); - } - else { - var loopResultName = ts.createUniqueName("state"); - var stateVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); - statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); - if (state.nonLocalJumps & 8 /* Return */) { - var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; - returnStatement = ts.createReturn(loopResultName); - } - else { - returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); - } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); - } - if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); - } - if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { - var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); - statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); - } - } - return statements; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - var statements = []; - // if there are no outer converted loop or outer label in question is located inside outer converted loop - // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - var label = ts.createIdentifier(labelText); - statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - statements.push(ts.createReturn(loopResultName)); - } - caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); - } - } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { - var name = decl.name; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); - } - } - } - else { - loopParameters.push(ts.createParameter(name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + name.text); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); - } - } - } - /** - * Adds the members of an object literal to an array of expressions. - * - * @param expressions An array of expressions. - * @param node An ObjectLiteralExpression node. - * @param receiver The receiver for members of the ObjectLiteralExpression. - * @param numInitialNonComputedProperties The number of initial properties without - * computed property names. - */ - function addObjectLiteralMembers(expressions, node, receiver, start) { - var properties = node.properties; - var numProperties = properties.length; - for (var i = start; i < numProperties; i++) { - var property = properties[i]; - switch (property.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); - } - break; - case 253 /* PropertyAssignment */: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 254 /* ShorthandPropertyAssignment */: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 147 /* MethodDeclaration */: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - /** - * Transforms a PropertyAssignment node into an expression. - * - * @param node The ObjectLiteralExpression that contains the PropertyAssignment. - * @param property The PropertyAssignment node. - * @param receiver The receiver for the assignment. - */ - function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), - /*location*/ property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Transforms a ShorthandPropertyAssignment node into an expression. - * - * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. - * @param property The ShorthandPropertyAssignment node. - * @param receiver The receiver for the assignment. - */ - function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), - /*location*/ property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. - * - * @param node The ObjectLiteralExpression that contains the MethodDeclaration. - * @param method The MethodDeclaration node. - * @param receiver The receiver for the assignment. - */ - function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), - /*location*/ method); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a - * PropertyAssignment. - * - * @param node A MethodDeclaration node. - */ - function visitMethodDeclaration(node) { - // We should only get here for methods on an object literal with regular identifier names. - // Methods on classes are handled in visitClassDeclaration/visitClassExpression. - // Methods with computed property names are handled in visitObjectLiteralExpression. - ts.Debug.assert(!ts.isComputedPropertyName(node.name)); - var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); - return ts.createPropertyAssignment(node.name, functionExpression, - /*location*/ node); - } - /** - * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. - * - * @param node A ShorthandPropertyAssignment node. - */ - function visitShorthandPropertyAssignment(node) { - return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), - /*location*/ node); - } - /** - * Visits a YieldExpression node. - * - * @param node A YieldExpression node. - */ - function visitYieldExpression(node) { - // `yield` expressions are transformed using the generators transformer. - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits an ArrayLiteralExpression that contains a spread element. - * - * @param node An ArrayLiteralExpression node. - */ - function visitArrayLiteralExpression(node) { - // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); - } - /** - * Visits a CallExpression that contains either a spread element or `super`. - * - * @param node a CallExpression. - */ - function visitCallExpression(node) { - // We are here either because SuperKeyword was used somewhere in the expression, or - // because we contain a SpreadElementExpression. - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { - // [source] - // f(...a, b) - // x.m(...a, b) - // super(...a, b) - // super.m(...a, b) // in static - // super.m(...a, b) // in instance - // - // [output] - // f.apply(void 0, a.concat([b])) - // (_a = x).m.apply(_a, a.concat([b])) - // _super.apply(this, a.concat([b])) - // _super.m.apply(this, a.concat([b])) - // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); - } - else { - // [source] - // super(a) - // super.m(a) // in static - // super.m(a) // in instance - // - // [output] - // _super.call(this, a) - // _super.m.call(this, a) - // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), - /*location*/ node); - } - } - /** - * Visits a NewExpression that contains a spread element. - * - * @param node A NewExpression node. - */ - function visitNewExpression(node) { - // We are here because we contain a SpreadElementExpression. - ts.Debug.assert((node.transformFlags & 262144 /* ContainsSpreadElementExpression */) !== 0); - // [source] - // new C(...a) - // - // [output] - // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() - var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), - /*typeArguments*/ undefined, []); - } - /** - * Transforms an array of Expression nodes that contains a SpreadElementExpression. - * - * @param elements The array of Expression nodes. - * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. - * @param multiLine A value indicating whether the result should be emitted on multiple lines. - */ - function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { - // [source] - // [a, ...b, c] - // - // [output] - // [a].concat(b, [c]) - // Map spans of spread expressions into their expressions and spans of other - // expressions into an array literal. - var numElements = elements.length; - var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { - return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); - })); - if (segments.length === 1) { - var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 /* ArrayLiteralExpression */ - ? ts.createArraySlice(segments[0]) - : segments[0]; - } - // Rewrite using the pattern .concat(, , ...) - return ts.createArrayConcat(segments.shift(), segments); - } - function partitionSpreadElement(node) { - return ts.isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; - } - function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.map(chunk, visitExpressionOfSpreadElement); - } - function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), - /*location*/ undefined, multiLine); - } - /** - * Transforms the expression of a SpreadElementExpression node. - * - * @param node A SpreadElementExpression node. - */ - function visitExpressionOfSpreadElement(node) { - return ts.visitNode(node.expression, visitor, ts.isExpression); - } - /** - * Visits a template literal. - * - * @param node A template literal. - */ - function visitTemplateLiteral(node) { - return ts.createLiteral(node.text, /*location*/ node); - } - /** - * Visits a TaggedTemplateExpression node. - * - * @param node A TaggedTemplateExpression node. - */ - function visitTaggedTemplateExpression(node) { - // Visit the tag expression - var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - // Allocate storage for the template site object - var temp = ts.createTempVariable(hoistVariableDeclaration); - // Build up the template arguments and the raw and cooked strings for the template. - var templateArguments = [temp]; - var cookedStrings = []; - var rawStrings = []; - var template = node.template; - if (ts.isNoSubstitutionTemplateLiteral(template)) { - cookedStrings.push(ts.createLiteral(template.text)); - rawStrings.push(getRawLiteral(template)); - } - else { - cookedStrings.push(ts.createLiteral(template.head.text)); - rawStrings.push(getRawLiteral(template.head)); - for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { - var templateSpan = _a[_i]; - cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); - rawStrings.push(getRawLiteral(templateSpan.literal)); - templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); - } - } - // NOTE: The parentheses here is entirely optional as we are now able to auto- - // parenthesize when rebuilding the tree. This should be removed in a - // future version. It is here for now to match our existing emit. - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) - ])); - } - /** - * Creates an ES5 compatible literal from an ES6 template literal. - * - * @param node The ES6 template literal. - */ - function getRawLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - return ts.createLiteral(text, /*location*/ node); - } - /** - * Visits a TemplateExpression node. - * - * @param node A TemplateExpression node. - */ - function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, ts.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(ts.createLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { - for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { - var span_6 = _a[_i]; - expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); - } - } - } - /** - * Visits the `super` keyword - */ - function visitSuperKeyword(node) { - return enclosingNonAsyncFunctionBody - && ts.isClassElement(enclosingNonAsyncFunctionBody) - && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) - && currentParent.kind !== 174 /* CallExpression */ - ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") - : ts.createIdentifier("_super"); - } - function visitSourceFileNode(node) { - var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; - var statements = []; - startLexicalEnvironment(); - ts.addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); - ts.addRange(statements, endLexicalEnvironment()); - var clone = ts.getMutableClone(node); - clone.statements = ts.createNodeArray(statements, /*location*/ node.statements); - return clone; - } - /** - * Called by the printer just before a node is printed. - * - * @param node The node to be printed. - */ - function onEmitNode(node, emit) { - var savedEnclosingFunction = enclosingFunction; - if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { - // If we are tracking a captured `this`, keep track of the enclosing function. - enclosingFunction = node; - } - previousOnEmitNode(node, emit); - enclosingFunction = savedEnclosingFunction; - } - /** - * Enables a more costly code path for substitutions when we determine a source file - * contains block-scoped bindings (e.g. `let` or `const`). - */ - function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { - enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(69 /* Identifier */); - } - } - /** - * Enables a more costly code path for substitutions when we determine a source file - * contains a captured `this`. - */ - function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { - enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(97 /* ThisKeyword */); - context.enableEmitNotification(148 /* Constructor */); - context.enableEmitNotification(147 /* MethodDeclaration */); - context.enableEmitNotification(149 /* GetAccessor */); - context.enableEmitNotification(150 /* SetAccessor */); - context.enableEmitNotification(180 /* ArrowFunction */); - context.enableEmitNotification(179 /* FunctionExpression */); - context.enableEmitNotification(220 /* FunctionDeclaration */); - } + return node; } /** * Hooks node substitutions. * + * @param emitContext The context for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); } - if (ts.isIdentifier(node)) { - return substituteIdentifier(node); + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); } return node; } /** - * Hooks substitutions for non-expression identifiers. + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression */ - function substituteIdentifier(node) { - // Only substitute the identifier if we have enabled substitutions for block-scoped - // bindings. - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { - var original = ts.getParseTreeNode(node, ts.isIdentifier); - if (original && isNameOfDeclarationWithCollidingName(original)) { - return ts.getGeneratedNameForNode(original); + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.createElementAccess(node.expression, literalName, /*location*/ node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + if (token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */) { + return ts.createLiteral(name, /*location*/ name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(261 /* SourceFile */); + context.enableSubstitution(70 /* Identifier */); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements); + ts.append(statements, ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); } } return node; } - /** - * Determines whether a name is the name of a declaration with a colliding name. - * NOTE: This function expects to be called with an original source tree node. - * - * @param node An original source tree node. - */ - function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 218 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + function visitor(node) { + switch (node.kind) { + case 234 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 240 /* ExportAssignment */: + return visitExportAssignment(node); } - return false; + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isIdentifier(node) && emitContext === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file. + var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = ts.createMap(); // The export function associated with a source file. + var noSubstitutionMap = ts.createMap(); // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports"); + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ], node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); } /** - * Substitutes an expression. + * Collects the dependency groups for this files imports. * - * @param node An Expression node. + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addRange(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, + /*location*/ undefined, + /*multiLine*/ true))) + ]), + /*multiLine*/ true))); + return ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 241 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.text === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true))); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 241 /* ExportDeclaration */) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], + /*location*/ undefined, + /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 235 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // fall-through + case 234 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 241 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 241 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement), + /*location*/ node)), + /*location*/ node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 1048576 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 261 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location))) + : preventSubstitution(ts.createAssignment(name, value, location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = decl.name.text; + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = exportName.text; + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + return ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 212 /* ForInStatement */: + return visitForInStatement(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 209 /* DoStatement */: + return visitDoStatement(node); + case 210 /* WhileStatement */: + return visitWhileStatement(node); + case 219 /* LabeledStatement */: + return visitLabeledStatement(node); + case 217 /* WithStatement */: + return visitWithStatement(node); + case 218 /* SwitchStatement */: + return visitSwitchStatement(node); + case 232 /* CaseBlock */: + return visitCaseBlock(node); + case 253 /* CaseClause */: + return visitCaseClause(node); + case 254 /* DefaultClause */: + return visitDefaultClause(node); + case 221 /* TryStatement */: + return visitTryStatement(node); + case 256 /* CatchClause */: + return visitCatchClause(node); + case 204 /* Block */: + return visitBlock(node); + case 295 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 296 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 192 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & 2048 /* ContainsDestructuringAssignment */) { + return ts.visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 261 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. */ function substituteExpression(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return substituteExpressionIdentifier(node); - case 97 /* ThisKeyword */: - return substituteThisKeyword(node); + case 192 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); } return node; } /** - * Substitutes an expression identifier. + * Substitution for an Identifier expression that may contain an imported or exported symbol. * - * @param node An Identifier node. + * @param node The node to substitute. */ function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.getGeneratedNameForNode(declaration.name); + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), + /*location*/ node); + } } } return node; } /** - * Substitutes `this` when contained within an arrow function. + * Substitution for a BinaryExpression that may contain an imported or exported symbol. * - * @param node The ThisKeyword node. + * @param node The node to substitute. */ - function substituteThisKeyword(node) { - if (enabledSubstitutions & 1 /* CapturedThis */ - && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { - return ts.createIdentifier("_this", /*location*/ node); + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } } return node; } /** - * Gets the local name for a declaration for use in expressions. + * Substitution for a UnaryExpression that may contain an imported or exported symbol. * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + * @param node The node to substitute. */ - function getLocalName(node, allowComments, allowSourceMaps) { - return getDeclarationName(node, allowComments, allowSourceMaps, 262144 /* LocalName */); + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 /* PostfixUnaryExpression */ + ? ts.createPrefix(node.operator, node.operand, + /*location*/ node) + : node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 191 /* PostfixUnaryExpression */) { + expression = node.operator === 42 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; } /** - * Gets the name of a declaration, without source map or comments. + * Gets the exports of a name. * - * @param node The declaration. - * @param allowComments Allow comments for the name. + * @param name The name. */ - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 261 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); } - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); - } - return name_39; } - return ts.getGeneratedNameForNode(node); + return exportedNames; } - function getClassMemberPrefix(node, member) { - var expression = getLocalName(node); - return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = ts.createMap(); + noSubstitution[ts.getNodeId(node)] = true; + return node; } - function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { - if (!constructor || !hasExtendsClause) { - return false; - } - var parameter = ts.singleOrUndefined(constructor.parameters); - if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { - return false; - } - var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202 /* ExpressionStatement */) { - return false; - } - var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174 /* CallExpression */) { - return false; - } - var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95 /* SuperKeyword */) { - return false; - } - var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191 /* SpreadElementExpression */) { - return false; - } - var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression === parameter.name; + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; } } - ts.transformES6 = transformES6; + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(258 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file. + var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Perform the transformation. + var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(updated, exportStarHelper); + } + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var define = ts.createRawExpression(umdHelper); + return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); + } + /** + * Transforms a SourceFile into an AMD or UMD module. + * + * @param node The SourceFile node. + * @param define The expression used to define the module. + * @param moduleName An expression for the module name, if available. + * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. + */ + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + return ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ], + /*location*/ node.statements)); + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + if (emitAsReturn) { + var statement = ts.createReturn(currentModuleInfo.exportEquals.expression, + /*location*/ currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression), + /*location*/ currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 241 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 295 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 296 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + // This visitor does not descend into the tree, as export/import statements + // are only transformed at the top level of a file. + return node; + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.createStatement(createRequireCall(node), /*location*/ node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, createRequireCall(node))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, + /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node), + /*location*/ node) + ], + /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)), + /*location*/ node)); + } + else { + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*location*/ undefined, + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)), + /*location*/ node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ]), + /*location*/ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue), + /*location*/ specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), + /*typeArguments*/ undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), + /*location*/ node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node)); + } + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(node, + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createExportExpression); + } + else { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name, + /*location*/ node.name), node.initializer); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + if (exportName.text === "default") { + var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 0 /* ES3 */) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = ts.createMap(); + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 70 /* Identifier */: + return substituteExpressionIdentifier(node); + case 192 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 191 /* PostfixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 261 /* SourceFile */) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name_38 = importDeclaration.propertyName || importDeclaration.name; + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_38), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 /* PostfixUnaryExpression */ + ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 /* PlusPlusToken */ ? 58 /* PlusEqualsToken */ : 59 /* MinusEqualsToken */), ts.createLiteral(1), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + var _a; + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + // emit output for the UMD helper function. + var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })"; })(ts || (ts = {})); /// /// /// -/// -/// +/// +/// +/// +/// /// +/// /// /// -/// +/// /* @internal */ var ts; (function (ts) { var moduleTransformerMap = ts.createMap((_a = {}, - _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.ES2015] = ts.transformES2015Module, _a[ts.ModuleKind.System] = ts.transformSystemModule, _a[ts.ModuleKind.AMD] = ts.transformModule, _a[ts.ModuleKind.CommonJS] = ts.transformModule, @@ -51540,25 +57050,31 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var transformers = []; transformers.push(ts.transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - transformers.push(ts.transformES7); - if (languageVersion < 2 /* ES6 */) { - transformers.push(ts.transformES6); + if (languageVersion < 5 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,76 +57084,46 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); + var enabledSyntaxKindFeatures = new Array(298 /* Count */); + var lexicalEnvironmentDisabled = false; + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; - var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; - var hoistedVariableDeclarations; - var hoistedFunctionDeclarations; - var lexicalEnvironmentDisabled; + var lexicalEnvironmentSuspended = false; + var emitHelpers; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, - startLexicalEnvironment: startLexicalEnvironment, - endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + onSubstituteNode: function (_emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +57146,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +57180,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51826,11 +57205,11 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); var decl = ts.createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } /** @@ -51838,11 +57217,11 @@ var ts; */ function hoistFunctionDeclaration(func) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } /** @@ -51851,15 +57230,28 @@ var ts; */ function startLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); // Save the current lexical environment. Rather than resizing the array we adjust the // stack size variable. This allows us to reuse existing array slots we've // already allocated between transformations to avoid allocation and GC overhead during // transformation. - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } /** * Ends a lexical environment. The previous set of hoisted declarations are restored and @@ -51867,14 +57259,15 @@ var ts; */ function endLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = hoistedFunctionDeclarations.slice(); + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); } - if (hoistedVariableDeclarations) { + if (lexicalEnvironmentVariableDeclarations) { var statement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -51885,101 +57278,33 @@ var ts; } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + function requestEmitHelper(helper) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +57313,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,26 +57327,17 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, - getSourceMappingURL: getSourceMappingURL + getSourceMappingURL: getSourceMappingURL, }; /** * Initialize the SourceMapWriter for a new output file. @@ -52034,12 +57348,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +57409,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +57419,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +57466,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +57495,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 293 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 293 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +57574,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,21 +57600,27 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, sources: sourceMapData.sourceMapSources, names: sourceMapData.sourceMapNames, mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent + sourcesContent: sourceMapData.sourceMapSourcesContent, }); } /** * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +57631,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52455,32 +57688,34 @@ var ts; setSourceFile: setSourceFile, emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; - var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + var isEmittedNode = node.kind !== 293 /* NotEmittedStatement */; + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { @@ -52497,18 +57732,20 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 219 /* VariableDeclarationList */) { + if (node.kind === 224 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitNodeWithComment"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,17 +57770,19 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; - var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52553,6 +57792,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -52580,7 +57822,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -52599,7 +57841,7 @@ var ts; function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -52623,7 +57865,7 @@ var ts; ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } } - function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); @@ -52664,16 +57906,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +57967,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52757,7 +57989,7 @@ var ts; var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; var noDeclare; var moduleElementDeclarationEmitInfo = []; @@ -52786,7 +58018,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52813,7 +58045,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 230 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 235 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -52847,7 +58079,7 @@ var ts; reportedDeclarationError: reportedDeclarationError, moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput + referencesOutput: referencesOutput, }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); @@ -52872,6 +58104,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -52887,10 +58120,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 218 /* VariableDeclaration */) { + if (declaration.kind === 223 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 233 /* NamedImports */ || declaration.kind === 234 /* ImportSpecifier */ || declaration.kind === 231 /* ImportClause */) { + else if (declaration.kind === 238 /* NamedImports */ || declaration.kind === 239 /* ImportSpecifier */ || declaration.kind === 236 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -52908,7 +58141,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 230 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 235 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -52918,12 +58151,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 225 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 230 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 225 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 230 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -52987,7 +58220,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,20 +58233,20 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } function emitLines(nodes) { - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -53028,7 +58261,7 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); @@ -53040,53 +58273,59 @@ var ts; } function emitType(type) { switch (type.kind) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 127 /* NeverKeyword */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 129 /* NeverKeyword */: + case 167 /* ThisType */: + case 171 /* LiteralType */: return writeTextOfNode(currentText, type); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return emitTypeReference(type); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return emitTypeQuery(type); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return emitArrayType(type); - case 161 /* TupleType */: + case 163 /* TupleType */: return emitTupleType(type); - case 162 /* UnionType */: + case 164 /* UnionType */: return emitUnionType(type); - case 163 /* IntersectionType */: + case 165 /* IntersectionType */: return emitIntersectionType(type); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return emitParenType(type); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 168 /* TypeOperator */: + return emitTypeOperator(type); + case 169 /* IndexedAccessType */: + return emitIndexedAccessType(type); + case 170 /* MappedType */: + return emitMappedType(type); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return emitTypeLiteral(type); - case 69 /* Identifier */: + case 70 /* Identifier */: return emitEntityName(type); - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return emitEntityName(type); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 69 /* Identifier */) { + if (entityName.kind === 70 /* Identifier */) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 139 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 139 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 141 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 141 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); @@ -53095,14 +58334,14 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 229 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 234 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 70 /* Identifier */ || node.expression.kind === 177 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -53148,6 +58387,42 @@ var ts; emitType(type.type); write(")"); } + function emitTypeOperator(type) { + write(ts.tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + function emitIndexedAccessType(node) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + function emitMappedType(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } function emitTypeLiteral(type) { write("{"); if (type.members.length) { @@ -53181,14 +58456,14 @@ var ts; var count = 0; while (true) { count++; - var name_40 = baseName + "_" + count; - if (!(name_40 in currentIdentifiers)) { - return name_40; + var name_39 = baseName + "_" + count; + if (!(name_39 in currentIdentifiers)) { + return name_39; } } } function emitExportAssignment(node) { - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -53202,7 +58477,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53211,12 +58486,12 @@ var ts; write(";"); writeLine(); // Make all the declarations visible for the export name - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { var nodes = resolver.collectLinkedAliases(node.expression); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic) { + function getDefaultExportAccessibilityDiagnostic() { return { diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -53230,10 +58505,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 229 /* ImportEqualsDeclaration */ || - (node.parent.kind === 256 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 234 /* ImportEqualsDeclaration */ || + (node.parent.kind === 261 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 256 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -53243,7 +58518,7 @@ var ts; }); } else { - if (node.kind === 230 /* ImportDeclaration */) { + if (node.kind === 235 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -53261,23 +58536,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return writeVariableStatement(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return writeClassDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -53285,7 +58560,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 261 /* SourceFile */) { var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { @@ -53294,7 +58569,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 222 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 227 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } @@ -53336,7 +58611,7 @@ var ts; write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult) { + function getImportEntityNameVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -53346,7 +58621,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 232 /* NamespaceImport */) { + if (namedBindings.kind === 237 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -53370,7 +58645,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 237 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -53391,13 +58666,13 @@ var ts; // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 225 /* ModuleDeclaration */; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230 /* ModuleDeclaration */; var moduleSpecifier; - if (parent.kind === 229 /* ImportEqualsDeclaration */) { + if (parent.kind === 234 /* ImportEqualsDeclaration */) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 225 /* ModuleDeclaration */) { + else if (parent.kind === 230 /* ModuleDeclaration */) { moduleSpecifier = parent.name; } else { @@ -53467,7 +58742,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 231 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -53501,7 +58776,7 @@ var ts; write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + function getTypeAliasDeclarationVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -53537,7 +58812,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 149 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -53548,52 +58823,55 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 159 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 147 /* MethodDeclaration */ || - node.parent.kind === 146 /* MethodSignature */ || - node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - node.parent.kind === 151 /* CallSignature */ || - node.parent.kind === 152 /* ConstructSignature */); + if (node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 161 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 149 /* MethodDeclaration */ || + node.parent.kind === 148 /* MethodSignature */ || + node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + node.parent.kind === 153 /* CallSignature */ || + node.parent.kind === 154 /* ConstructSignature */); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { + function getTypeParameterConstraintVisibilityError() { // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 226 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case 228 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; default: ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -53619,17 +58897,17 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { + else if (!isImplementsList && node.expression.kind === 94 /* NullKeyword */) { write("null"); } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult) { + function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + if (node.parent.parent.kind === 226 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -53690,7 +58968,10 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); + var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); + } write(" {"); writeLine(); increaseIndent(); @@ -53713,7 +58994,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 218 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 223 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -53724,11 +59005,11 @@ var ts; writeTextOfNode(currentText, node.name); // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor // we don't want to emit property declaration with "?" - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || - (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */ || + (node.kind === 144 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { + if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) && node.parent.kind === 161 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -53741,14 +59022,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) { + else if (node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -53757,7 +59038,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -53789,7 +59070,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (element.kind !== 198 /* OmittedExpression */) { elements.push(element); } } @@ -53859,7 +59140,7 @@ var ts; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 149 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 151 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -53872,7 +59153,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 149 /* GetAccessor */ + return accessor.kind === 151 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -53881,7 +59162,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 150 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 152 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? @@ -53931,17 +59212,17 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 220 /* FunctionDeclaration */) { + if (node.kind === 225 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 147 /* MethodDeclaration */ || node.kind === 148 /* Constructor */) { + else if (node.kind === 149 /* MethodDeclaration */ || node.kind === 150 /* Constructor */) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 220 /* FunctionDeclaration */) { + if (node.kind === 225 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 148 /* Constructor */) { + else if (node.kind === 150 /* Constructor */) { write("constructor"); } else { @@ -53961,17 +59242,17 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { // Index signature can have readonly modifier emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { // Construct signature or constructor type write new Signature - if (node.kind === 152 /* ConstructSignature */ || node.kind === 157 /* ConstructorType */) { + if (node.kind === 154 /* ConstructSignature */ || node.kind === 159 /* ConstructorType */) { write("new "); } - else if (node.kind === 156 /* FunctionType */) { + else if (node.kind === 158 /* FunctionType */) { var currentOutput = writer.getText(); // Do not generate incorrect type when function type with type parameters is type argument // This could happen if user used space between two '<' making it error free @@ -53986,22 +59267,22 @@ var ts; } // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 156 /* FunctionType */ || node.kind === 157 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 159 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 158 /* FunctionType */ || node.kind === 159 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 161 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 148 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { + else if (node.kind !== 150 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -54015,26 +59296,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -54042,7 +59323,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54056,7 +59337,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54091,9 +59372,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - node.parent.parent.kind === 159 /* TypeLiteral */) { + if (node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + node.parent.parent.kind === 161 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8 /* Private */)) { @@ -54109,24 +59390,29 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151 /* CallSignature */: + case 153 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 155 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -54134,7 +59420,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 226 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54147,7 +59433,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54159,12 +59445,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 167 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 172 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 168 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -54175,7 +59461,7 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 193 /* OmittedExpression */) { + if (bindingElement.kind === 198 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -54184,7 +59470,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 169 /* BindingElement */) { + else if (bindingElement.kind === 174 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -54207,7 +59493,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 69 /* Identifier */); + ts.Debug.assert(bindingElement.name.kind === 70 /* Identifier */); // If the node is just an identifier, we will simply emit the text associated with the node's name // Example: // original: function foo({y = 10, x}) {} @@ -54223,40 +59509,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 225 /* ModuleDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 222 /* InterfaceDeclaration */: - case 221 /* ClassDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: + case 225 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 227 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return emitExportDeclaration(node); - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return writeFunctionDeclaration(node); - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 153 /* IndexSignature */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 155 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return emitAccessorDeclaration(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return emitPropertyDeclaration(node); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return emitExportAssignment(node); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return emitSourceFile(node); } } @@ -54265,7 +59551,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +59560,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54282,7 +59568,7 @@ var ts; referencesOutput += "/// " + newLine; } return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) { // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path if (isBundledEmit && !addBundledFileReference) { return; @@ -54294,8 +59580,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,90 +59621,12 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (_) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); - // emit output for the __extends helper function - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; - // Emit output for the __assign helper function. - // This is typically used for JSX spread attributes, - // and can be used for object literal spread properties. - var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; - // emit output for the __decorate helper function - var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; - // emit output for the __metadata helper function - var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; - // emit output for the __param helper function - var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; - // The __generator helper is used by down-level transformations to emulate the runtime - // semantics of an ES2015 generator function. When called, this helper returns an - // object that implements the Iterator protocol, in that it has `next`, `return`, and - // `throw` methods that step through the generator when invoked. - // - // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. - // - // variables: - // _ Persistent state for the generator that is shared between the helper and the - // generator body. The state object has the following members: - // sent() - A method that returns or throws the current completion value. - // label - The next point at which to resume evaluation of the generator body. - // trys - A stack of protected regions (try/catch/finally blocks). - // ops - A stack of pending instructions when inside of a finally block. - // f A value indicating whether the generator is executing. - // y An iterator to delegate for a yield*. - // t A temporary variable that holds one of the following values (note that these - // cases do not overlap): - // - The completion value when resuming from a `yield` or `yield*`. - // - The error value for a catch block. - // - The current protected region (array of try/catch/finally/end labels). - // - The verb (`next`, `throw`, or `return` method) to delegate to the expression - // of a `yield*`. - // - The result of evaluating the verb delegated to the expression of a `yield*`. - // - // functions: - // verb(n) Creates a bound callback to the `step` function for opcode `n`. - // step(op) Evaluates opcodes in a generator body until execution is suspended or - // completed. - // - // The __generator helper understands a limited set of instructions: - // 0: next(value?) - Start or resume the generator with the specified value. - // 1: throw(error) - Resume the generator with an exception. If the generator is - // suspended inside of one or more protected regions, evaluates - // any intervening finally blocks between the current label and - // the nearest catch block or function boundary. If uncaught, the - // exception is thrown to the caller. - // 2: return(value?) - Resume the generator as if with a return. If the generator is - // suspended inside of one or more protected regions, evaluates any - // intervening finally blocks. - // 3: break(label) - Jump to the specified label. If the label is outside of the - // current protected region, evaluates any intervening finally - // blocks. - // 4: yield(value?) - Yield execution to the caller with an optional value. When - // resumed, the generator will continue at the next label. - // 5: yield*(value) - Delegates evaluation to the supplied iterator. When - // delegation completes, the generator will continue at the next - // label. - // 6: catch(error) - Handles an exception thrown from within the generator body. If - // the current label is inside of one or more protected regions, - // evaluates any intervening finally blocks between the current - // label and the nearest catch block or function boundary. If - // uncaught, the exception is thrown to the caller. - // 7: endfinally - Ends a finally block, resuming the last instruction prior to - // entering a finally block. - // - // For examples of how these are used, see the comments in ./transformers/generators.ts - var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; - // emit output for the __export helper function - var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; - // emit output for the UMD helper function. - var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; - var superHelper = "\nconst _super = name => super[name];"; - var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -54426,11 +59634,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54440,25 +59648,23 @@ var ts; var currentSourceFile; var currentText; var currentFileIdentifiers; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; + var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +59674,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54491,12 +59701,13 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = ts.createMap(); + bundledHelpers = isBundledEmit ? ts.createMap() : undefined; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; - emitEmitHelpers(sourceFile); + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; + emitHelpers(sourceFile, /*isBundle*/ true); } } // Print each transformed source file. @@ -54508,14 +59719,14 @@ var ts; } // Write the source map if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Record source map data for the test harness. if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); comments.reset(); @@ -54523,11 +59734,6 @@ var ts; tempFlags = 0 /* Auto */; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } function printSourceFile(node) { @@ -54536,448 +59742,465 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 261 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 70 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: return emitLiteral(node); // Identifiers - case 69 /* Identifier */: + case 70 /* Identifier */: return emitIdentifier(node); // Reserved words - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 82 /* ExportKeyword */: - case 103 /* VoidKeyword */: + case 75 /* ConstKeyword */: + case 78 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 104 /* VoidKeyword */: // Strict mode reserved words - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 113 /* StaticKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 114 /* StaticKeyword */: // Contextual keywords - case 115 /* AbstractKeyword */: - case 117 /* AnyKeyword */: - case 118 /* AsyncKeyword */: - case 120 /* BooleanKeyword */: - case 122 /* DeclareKeyword */: - case 130 /* NumberKeyword */: - case 128 /* ReadonlyKeyword */: - case 132 /* StringKeyword */: - case 133 /* SymbolKeyword */: - case 137 /* GlobalKeyword */: - return writeTokenNode(node); + case 116 /* AbstractKeyword */: + case 117 /* AsKeyword */: + case 118 /* AnyKeyword */: + case 119 /* AsyncKeyword */: + case 120 /* AwaitKeyword */: + case 121 /* BooleanKeyword */: + case 122 /* ConstructorKeyword */: + case 123 /* DeclareKeyword */: + case 124 /* GetKeyword */: + case 125 /* IsKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 129 /* NeverKeyword */: + case 130 /* ReadonlyKeyword */: + case 131 /* RequireKeyword */: + case 132 /* NumberKeyword */: + case 133 /* SetKeyword */: + case 134 /* StringKeyword */: + case 135 /* SymbolKeyword */: + case 136 /* TypeKeyword */: + case 137 /* UndefinedKeyword */: + case 138 /* FromKeyword */: + case 139 /* GlobalKeyword */: + case 140 /* OfKeyword */: + writeTokenText(kind); + return; // Parse tree nodes // Names - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return emitQualifiedName(node); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return emitTypeParameter(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return emitParameter(node); - case 143 /* Decorator */: + case 145 /* Decorator */: return emitDecorator(node); // Type members - case 144 /* PropertySignature */: + case 146 /* PropertySignature */: return emitPropertySignature(node); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 146 /* MethodSignature */: + case 148 /* MethodSignature */: return emitMethodSignature(node); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return emitConstructor(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return emitAccessorDeclaration(node); - case 151 /* CallSignature */: + case 153 /* CallSignature */: return emitCallSignature(node); - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: return emitConstructSignature(node); - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return emitIndexSignature(node); // Types - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return emitTypePredicate(node); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return emitTypeReference(node); - case 156 /* FunctionType */: + case 158 /* FunctionType */: return emitFunctionType(node); - case 157 /* ConstructorType */: + case 159 /* ConstructorType */: return emitConstructorType(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return emitTypeQuery(node); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return emitTypeLiteral(node); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return emitArrayType(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return emitTupleType(node); - case 162 /* UnionType */: + case 164 /* UnionType */: return emitUnionType(node); - case 163 /* IntersectionType */: + case 165 /* IntersectionType */: return emitIntersectionType(node); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return emitParenthesizedType(node); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 165 /* ThisType */: - return emitThisType(node); - case 166 /* LiteralType */: + case 167 /* ThisType */: + return emitThisType(); + case 168 /* TypeOperator */: + return emitTypeOperator(node); + case 169 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 170 /* MappedType */: + return emitMappedType(node); + case 171 /* LiteralType */: return emitLiteralType(node); // Binding patterns - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return emitBindingElement(node); // Misc - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return emitTemplateSpan(node); - case 198 /* SemicolonClassElement */: - return emitSemicolonClassElement(node); + case 203 /* SemicolonClassElement */: + return emitSemicolonClassElement(); // Statements - case 199 /* Block */: + case 204 /* Block */: return emitBlock(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return emitVariableStatement(node); - case 201 /* EmptyStatement */: - return emitEmptyStatement(node); - case 202 /* ExpressionStatement */: + case 206 /* EmptyStatement */: + return emitEmptyStatement(); + case 207 /* ExpressionStatement */: return emitExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return emitIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return emitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return emitWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return emitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return emitForInStatement(node); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return emitForOfStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return emitContinueStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return emitBreakStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return emitReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return emitWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return emitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return emitLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return emitThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return emitTryStatement(node); - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return emitClassDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return emitModuleBlock(node); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return emitCaseBlock(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return emitImportDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return emitImportClause(node); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return emitNamespaceImport(node); - case 233 /* NamedImports */: + case 238 /* NamedImports */: return emitNamedImports(node); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return emitImportSpecifier(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return emitExportAssignment(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return emitExportDeclaration(node); - case 237 /* NamedExports */: + case 242 /* NamedExports */: return emitNamedExports(node); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return emitExportSpecifier(node); - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return; // Module references - case 240 /* ExternalModuleReference */: + case 245 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 244 /* JsxText */: + case 10 /* JsxText */: return emitJsxText(node); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: return emitJsxOpeningElement(node); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return emitJsxClosingElement(node); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return emitJsxAttribute(node); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 249 /* CaseClause */: + case 253 /* CaseClause */: return emitCaseClause(node); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return emitDefaultClause(node); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return emitHeritageClause(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); + case 259 /* SpreadAssignment */: + return emitSpreadAssignment(node); // Enum - case 255 /* EnumMember */: + case 260 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals case 8 /* NumericLiteral */: return emitNumericLiteral(node); case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 11 /* RegularExpressionLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 69 /* Identifier */: + case 70 /* Identifier */: return emitIdentifier(node); // Reserved words - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 95 /* SuperKeyword */: - case 99 /* TrueKeyword */: - case 97 /* ThisKeyword */: - return writeTokenNode(node); - // Expressions - case 170 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 171 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 172 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 174 /* CallExpression */: - return emitCallExpression(node); - case 175 /* NewExpression */: - return emitNewExpression(node); - case 176 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 177 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 178 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 179 /* FunctionExpression */: - return emitFunctionExpression(node); - case 180 /* ArrowFunction */: - return emitArrowFunction(node); - case 181 /* DeleteExpression */: - return emitDeleteExpression(node); - case 182 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 183 /* VoidExpression */: - return emitVoidExpression(node); - case 184 /* AwaitExpression */: - return emitAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: - return emitBinaryExpression(node); - case 188 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 189 /* TemplateExpression */: - return emitTemplateExpression(node); - case 190 /* YieldExpression */: - return emitYieldExpression(node); - case 191 /* SpreadElementExpression */: - return emitSpreadElementExpression(node); - case 192 /* ClassExpression */: - return emitClassExpression(node); - case 193 /* OmittedExpression */: + case 85 /* FalseKeyword */: + case 94 /* NullKeyword */: + case 96 /* SuperKeyword */: + case 100 /* TrueKeyword */: + case 98 /* ThisKeyword */: + writeTokenText(kind); return; - case 195 /* AsExpression */: + // Expressions + case 175 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 176 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 177 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 179 /* CallExpression */: + return emitCallExpression(node); + case 180 /* NewExpression */: + return emitNewExpression(node); + case 181 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 182 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 183 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 184 /* FunctionExpression */: + return emitFunctionExpression(node); + case 185 /* ArrowFunction */: + return emitArrowFunction(node); + case 186 /* DeleteExpression */: + return emitDeleteExpression(node); + case 187 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 188 /* VoidExpression */: + return emitVoidExpression(node); + case 189 /* AwaitExpression */: + return emitAwaitExpression(node); + case 190 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 191 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 192 /* BinaryExpression */: + return emitBinaryExpression(node); + case 193 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 194 /* TemplateExpression */: + return emitTemplateExpression(node); + case 195 /* YieldExpression */: + return emitYieldExpression(node); + case 196 /* SpreadElement */: + return emitSpreadExpression(node); + case 197 /* ClassExpression */: + return emitClassExpression(node); + case 198 /* OmittedExpression */: + return; + case 200 /* AsExpression */: return emitAsExpression(node); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return emitNonNullExpression(node); // JSX - case 241 /* JsxElement */: + case 246 /* JsxElement */: return emitJsxElement(node); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* RawExpression */: + return writeLines(node.text); } } // @@ -55010,12 +60233,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, /*includeTrivia*/ false)); - } + write(getTextOfNode(node, /*includeTrivia*/ false)); } // // Names @@ -55026,7 +60244,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -55102,7 +60320,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 151 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55130,7 +60348,7 @@ var ts; emitWithPrefix(": ", node.type); write(";"); } - function emitSemicolonClassElement(node) { + function emitSemicolonClassElement() { write(";"); } // @@ -55187,9 +60405,42 @@ var ts; emit(node.type); write(")"); } - function emitThisType(node) { + function emitThisType() { write("this"); } + function emitTypeOperator(node) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + function emitMappedType(node) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } function emitLiteralType(node) { emitExpression(node.literal); } @@ -55243,7 +60494,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +60507,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 65536 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = { kind: 22 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55282,19 +60530,18 @@ var ts; if (expression.kind === 8 /* NumericLiteral */) { // check if numeric literal was originally written with a dot var text = getLiteralTextOfNode(expression); - return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; + return text.indexOf(ts.tokenToString(22 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55302,11 +60549,13 @@ var ts; } function emitCallExpression(node) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { @@ -55378,16 +60627,16 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 185 /* PrefixUnaryExpression */ - && ((node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) - || (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */))); + return operand.kind === 190 /* PrefixUnaryExpression */ + && ((node.operator === 36 /* PlusToken */ && (operand.operator === 36 /* PlusToken */ || operand.operator === 42 /* PlusPlusToken */)) + || (node.operator === 37 /* MinusToken */ && (operand.operator === 37 /* MinusToken */ || operand.operator === 43 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 24 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 25 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); @@ -55422,7 +60671,7 @@ var ts; write(node.asteriskToken ? "yield*" : "yield"); emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node) { + function emitSpreadExpression(node) { write("..."); emitExpression(node.expression); } @@ -55454,20 +60703,20 @@ var ts; // // Statements // - function emitBlock(node, format) { + function emitBlock(node) { if (isSingleLineEmptyBlock(node)) { - writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); write(" "); - writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } else { - writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); emitBlockStatements(node); - writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55479,7 +60728,7 @@ var ts; emit(node.declarationList); write(";"); } - function emitEmptyStatement(node) { + function emitEmptyStatement() { write(";"); } function emitExpressionStatement(node) { @@ -55487,16 +60736,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(88 /* IfKeyword */, node.pos, node); + var openParenPos = writeToken(89 /* IfKeyword */, node.pos, node); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos, node); + writeToken(18 /* OpenParenToken */, openParenPos, node); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end, node); + writeToken(19 /* CloseParenToken */, node.expression.end, node); emitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { writeLine(); - writeToken(80 /* ElseKeyword */, node.thenStatement.end, node); - if (node.elseStatement.kind === 203 /* IfStatement */) { + writeToken(81 /* ElseKeyword */, node.thenStatement.end, node); + if (node.elseStatement.kind === 208 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -55525,9 +60774,9 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + writeToken(18 /* OpenParenToken */, openParenPos, /*contextNode*/ node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -55537,28 +60786,28 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 219 /* VariableDeclarationList */) { + if (node.kind === 224 /* VariableDeclarationList */) { emit(node); } else { @@ -55567,17 +60816,17 @@ var ts; } } function emitContinueStatement(node) { - writeToken(75 /* ContinueKeyword */, node.pos); + writeToken(76 /* ContinueKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(70 /* BreakKeyword */, node.pos); + writeToken(71 /* BreakKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitReturnStatement(node) { - writeToken(94 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + writeToken(95 /* ReturnKeyword */, node.pos, /*contextNode*/ node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -55588,11 +60837,11 @@ var ts; emitEmbeddedStatement(node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(96 /* SwitchKeyword */, node.pos); + var openParenPos = writeToken(97 /* SwitchKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); write(" "); emit(node.caseBlock); } @@ -55617,7 +60866,7 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(76 /* DebuggerKeyword */, node.pos); + writeToken(77 /* DebuggerKeyword */, node.pos); write(";"); } // @@ -55625,6 +60874,7 @@ var ts; // function emitVariableDeclaration(node) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } function emitVariableDeclarationList(node) { @@ -55645,19 +60895,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 262144 /* ReuseTempVariableScope */) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { var savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } if (indentedFlag) { @@ -55680,14 +60930,14 @@ var ts; emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: // * The body has NodeEmitFlags.SingleLine specified. // We must emit a function body as a multi-line body in the following cases: // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55710,14 +60960,14 @@ var ts; } return true; } - function emitBlockFunctionBody(parentNode, body) { + function emitBlockFunctionBody(body) { write(" {"); increaseIndent(); - emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); decreaseIndent(); - writeToken(16 /* CloseBraceToken */, body.statements.end, body); + writeToken(17 /* CloseBraceToken */, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -55743,7 +60993,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55796,7 +61046,7 @@ var ts; write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); emit(node.name); var body = node.body; - while (body.kind === 225 /* ModuleDeclaration */) { + while (body.kind === 230 /* ModuleDeclaration */) { write("."); emit(body.name); body = body.body; @@ -55805,7 +61055,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -55819,9 +61069,9 @@ var ts; } } function emitCaseBlock(node) { - writeToken(15 /* OpenBraceToken */, node.pos); + writeToken(16 /* OpenBraceToken */, node.pos); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(16 /* CloseBraceToken */, node.clauses.end); + writeToken(17 /* CloseBraceToken */, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -55832,7 +61082,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -55958,7 +61208,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -56001,11 +61251,11 @@ var ts; } function emitCatchClause(node) { writeLine(); - var openParenPos = writeToken(72 /* CatchKeyword */, node.pos); + var openParenPos = writeToken(73 /* CatchKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emit(node.variableDeclaration); - writeToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + writeToken(19 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); write(" "); emit(node.block); } @@ -56023,8 +61273,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56036,6 +61286,12 @@ var ts; emitExpression(node.objectAssignmentInitializer); } } + function emitSpreadAssignment(node) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } // // Enum // @@ -56083,68 +61339,37 @@ var ts; } return statements.length; } - function emitHelpers(node) { - var emitFlags = node.emitFlags; + function emitHelpers(node, isBundle) { + var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile; + var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit; var helpersEmitted = false; - if (emitFlags & 1 /* EmitEmitHelpers */) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - if (emitFlags & 2 /* EmitExportStar */) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - if (emitFlags & 4 /* EmitSuperHelper */) { - writeLines(superHelper); - helpersEmitted = true; - } - if (emitFlags & 8 /* EmitAdvancedSuperHelper */) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - return helpersEmitted; - } - function emitEmitHelpers(node) { - // Only emit helpers if the user did not say otherwise. - if (compilerOptions.noEmitHelpers) { - return false; - } - // Don't emit helpers if we can import them. - if (compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } - var helpersEmitted = false; - // Only Emit __extends function when target ES5. - // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 1024 /* HasClassExtends */)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } - if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 16384 /* HasJsxSpreadAttributes */)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 2048 /* HasDecorators */) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + writeLines(helper.text); + helpersEmitted = true; } - decorateEmitted = true; - helpersEmitted = true; - } - if (!paramEmitted && node.flags & 4096 /* HasParamDecorators */) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - if (!awaiterEmitted && node.flags & 8192 /* HasAsyncFunctions */) { - writeLines(awaiterHelper); - if (languageVersion < 2 /* ES6 */) { - writeLines(generatorHelper); - } - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { writeLine(); @@ -56152,9 +61377,10 @@ var ts; return helpersEmitted; } function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); + var lines = text.split(/\r\n?|\n/g); + var indentation = guessIndentation(lines); for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + var line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -56163,6 +61389,21 @@ var ts; } } } + function guessIndentation(lines) { + var indentation; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var line = lines_1[_a]; + for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!ts.isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } // // Helpers // @@ -56197,31 +61438,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +61545,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +61591,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56507,7 +61708,7 @@ var ts; && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 183 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -56539,17 +61740,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56575,10 +61771,10 @@ var ts; */ function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_41 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_41)) { + var name_40 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_40)) { tempFlags |= flags; - return name_41; + return name_40; } } while (true) { @@ -56586,11 +61782,11 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_42 = count < 26 + var name_41 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_42)) { - return name_42; + if (isUniqueName(name_41)) { + return name_41; } } } @@ -56637,19 +61833,19 @@ var ts; */ function generateNameForNode(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return makeUniqueName(getTextOfNode(node)); - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 230 /* ImportDeclaration */: - case 236 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: + case 241 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 235 /* ExportAssignment */: + case 225 /* FunctionDeclaration */: + case 226 /* ClassDeclaration */: + case 240 /* ExportAssignment */: return generateNameForExportDefault(); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return generateNameForClassExpression(); default: return makeTempVariableName(0 /* Auto */); @@ -56815,8 +62011,6 @@ var ts; /// var ts; (function (ts) { - /** The version of the TypeScript compiler release */ - ts.version = "2.1.0"; var emptyArray = []; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -56878,695 +62072,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @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 - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === 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, typeRoots); - } - } - else { - 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, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +62177,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); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57731,54 +62236,15 @@ var ts; } var resolutions = []; var cache = ts.createMap(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var result = name_43 in cache - ? cache[name_43] - : cache[name_43] = loader(name_43, containingFile); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_42 = names_1[_i]; + var result = name_42 in cache + ? cache[name_42] + : cache[name_42] = loader(name_42, containingFile); resolutions.push(result); } return resolutions; } - /** - * Given a set of options, 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, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57795,7 +62261,7 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. @@ -57812,10 +62278,18 @@ var ts; var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +62297,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,10 +62307,11 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -57884,20 +62359,23 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { // Make sure directory path ends with directory separator so this string can directly @@ -57920,6 +62398,112 @@ var ts; } return classifiableNames; } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + // if old program state is not supplied and file does not contain locally defined ambient modules + // then the best we can do is fallback to the default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + // at this point we know that either + // - file has local declarations for ambient modules + // OR + // - old program state is available + // OR + // - both of items above + // With this it is possible that we can tell how some module names from the initial list will be resolved + // without doing actual resolution (in particular if some name was resolved to ambient module). + // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` + // since we don't want to resolve them again. + // this is a list of modules for which we cannot predict resolution so they should be actually resolved + var unknownModuleNames; + // this is a list of combined results assembles from predicted and resolved results. + // Order in this list matches the order in the original list of module names `moduleNames` which is important + // so later we can split results to resolutions of modules and resolutions of module augmentations. + var result; + // a transient placeholder that is used to mark predicted resolution in the result list + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // module name is known to be resolved to ambient module if + // - module name is contained in the list of ambient modules that are locally declared in the file + // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // (so the same module declaration will land in the new program) + var isKnownToResolveToAmbientModule = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + // found a first module name for which result can be prediced + // this means that this module name should not be passed to `resolveModuleNamesWorker`. + // We'll use a separate list for module names that are definitely unknown. + result = new Array(moduleNames.length); + // copy all module names that appear before the current one in the list + // since they are known to be unknown + unknownModuleNames = moduleNames.slice(0, i); + } + // mark prediced resolution in the result list + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + // found unknown module name and we are already using separate list for those - add it to the list + unknownModuleNames.push(moduleName); + } + } + if (!unknownModuleNames) { + // we've looked throught the list but have not seen any predicted resolution + // use default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + // combine results of resolutions and predicted results + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState) { + return false; + } + var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + // module used to be resolved to file - ignore it + return false; + } + var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + // at least one of declarations should come from non-modified source file + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return false; @@ -57927,20 +62511,7 @@ var ts; // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + if (ts.changesAffectModuleResolution(oldOptions, options)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -57991,29 +62562,8 @@ var ts; // 'types' references has changed return false; } - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - // ensure that module resolution results are still correct - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - // ensure that types resolutions are still correct - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { // file has no changes - use it as is @@ -58022,15 +62572,42 @@ var ts; // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } + var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + // try to verify results of module resolution + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + // pass the cache of module/types resolutions from the old source file + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } // update fileName -> file mapping for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { - var modifiedFile = modifiedSourceFiles_1[_b]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { + var modifiedFile = modifiedSourceFiles_2[_d]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -58046,24 +62623,30 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked + isEmitBlocked: isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file) { + return sourceFilesFoundSearchingNodeModules[file.path]; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +62678,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58135,7 +62718,15 @@ var ts; return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } } - function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } function runWithCancellationToken(func) { @@ -58164,179 +62755,180 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report semantic errors. + // Instead, we'll report errors for using TypeScript-only constructs from within a + // JavaScript file when we get syntactic diagnostics for the file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; + var parent = sourceFile; walk(sourceFile); return diagnostics; function walk(node) { - if (!node) { - return false; + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // Pass through + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 223 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } } switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 235 /* ExportAssignment */: + case 234 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 240 /* ExportAssignment */: if (node.isExportEquals) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; } break; - case 221 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; + if (heritageClause.token === 107 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; } break; - case 222 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 225 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 223 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; + case 227 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 230 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 228 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 229 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 182 /* TypeAssertionExpression */: + var typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 226 /* ClassDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // pass through + case 205 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 205 /* VariableStatement */); } break; - case 200 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 218 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 174 /* CallExpression */: - case 175 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 142 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 145 /* PropertyDeclaration */: - var propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + case 147 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _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 (modifier.kind !== 114 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } - } - if (checkTypeAnnotation(node.type)) { - return true; + return; } break; - case 224 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 177 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* Decorator */: - if (!options.experimentalDecorators) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + case 144 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 128 /* ReadonlyKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: + break; + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 199 /* ExpressionWithTypeArguments */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 75 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // Fallthrough to report error + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 130 /* ReadonlyKeyword */: + case 123 /* DeclareKeyword */: + case 116 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 114 /* StaticKeyword */: + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: } } - return false; + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } @@ -58344,8 +62936,7 @@ var ts; return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - var writeFile = function () { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { @@ -58362,11 +62953,8 @@ var ts; ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName) { - return ts.getBaseFileName(fileName).indexOf(".") >= 0; - } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*isReference*/ true); + processSourceFile(ts.normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -58383,16 +62971,21 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; + var ambientModules; // If we are importing helpers, we need to add a synthetic reference to resolve the // helpers library. if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - var externalHelpersModuleReference = ts.createNode(9 /* StringLiteral */); + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createSynthesizedNode(9 /* StringLiteral */); externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + var importDecl = ts.createSynthesizedNode(235 /* ImportDeclaration */); + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { @@ -58404,12 +62997,13 @@ var ts; } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -58424,7 +63018,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. @@ -58436,6 +63030,10 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(moduleName.text); + } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. @@ -58461,18 +63059,15 @@ var ts; } } } - /** - * 'isReference' indicates whether the file was brought in via a reference directive (rather than an import declaration) - */ - function processSourceFile(fileName, isDefaultLib, isReference, refFile, refPos, refEnd) { + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { var diagnosticArgument; var diagnostic; - if (hasExtension(fileName)) { + if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -58482,13 +63077,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -58513,7 +63108,7 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, path, isDefaultLib, isReference, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { if (filesByName.contains(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -58526,16 +63121,16 @@ var ts; if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } } return file_1; @@ -58564,13 +63159,12 @@ var ts; } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - var basePath = ts.getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } // always process imported modules to record module name resolutions - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); } @@ -58580,10 +63174,10 @@ var ts; } return file; } - function processReferencedFiles(file, basePath, isDefaultLib) { + function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, /*isReference*/ true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -58609,22 +63203,25 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents // for sameness and possibly issue an error if (previousResolution) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } } // don't overwrite previous resolution result saveResolution = false; } else { // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } } } @@ -58650,34 +63247,43 @@ var ts; function getCanonicalFileName(fileName) { return host.getCanonicalFileName(fileName); } - function processImportedModules(file, basePath) { + function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = ts.createMap(); - var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); + var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name comes from the list of imports // - it's not a top level JavaScript module that exceeded the search max - var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); - if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, - /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -58688,12 +63294,11 @@ var ts; // no imports - drop cached module resolutions file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +63309,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +63353,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +63364,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,11 +63404,14 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { - if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58812,7 +63420,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); @@ -58846,14 +63454,22 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); - ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); @@ -58864,12 +63480,18 @@ var ts; var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + var chain_1; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -58877,12 +63499,40 @@ var ts; } } } - function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); } } ts.createProgram = createProgram; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ts.Extension.Ts: + case ts.Extension.Dts: + // These are always allowed. + return undefined; + case ts.Extension.Tsx: + return needJsx(); + case ts.Extension.Jsx: + return needJsx() || needAllowJs(); + case ts.Extension.Js: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; })(ts || (ts = {})); /// /// @@ -58891,27 +63541,30 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -58926,7 +63579,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -58936,15 +63589,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -58953,27 +63606,32 @@ var ts; "react": 2 /* React */ }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -58984,11 +63642,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -58997,12 +63655,12 @@ var ts; "lf": 1 /* LineFeed */ }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -59011,7 +63669,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -59020,60 +63678,60 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, // for correct behaviour, please use outFile - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -59096,30 +63754,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -59130,7 +63788,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -59144,23 +63802,26 @@ var ts; type: ts.createMap({ "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, - "es6": 2 /* ES6 */, - "es2015": 2 /* ES2015 */ + "es6": 2 /* ES2015 */, + "es2015": 2 /* ES2015 */, + "es2016": 3 /* ES2016 */, + "es2017": 4 /* ES2017 */, + "esnext": 5 /* ESNext */, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -59177,10 +63838,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -59309,8 +63970,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -59327,13 +63989,25 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -59357,10 +64031,24 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -59379,23 +64067,13 @@ var ts; ts.getOptionNameMap = getOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; /* @internal */ function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ @@ -59419,7 +64097,6 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - /* @internal */ function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; @@ -59461,7 +64138,13 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -59547,10 +64230,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59597,11 +64281,11 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_44 in options) { - if (ts.hasProperty(options, name_44)) { + for (var name_43 in options) { + if (ts.hasProperty(options, name_43)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean - switch (name_44) { + switch (name_43) { case "init": case "watch": case "version": @@ -59609,14 +64293,14 @@ var ts; case "project": break; default: - var value = options[name_44]; - var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + var value = options[name_43]; + var optionDefinition = optionsNameMap[name_43.toLowerCase()]; if (optionDefinition) { var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result[name_44] = value; + result[name_43] = value; } else { if (optionDefinition.type === "list") { @@ -59625,11 +64309,11 @@ var ts; var element = _a[_i]; convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); } - result[name_44] = convertedValue; + result[name_43] = convertedValue; } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + result[name_43] = getNameOfCompilerOptionValue(value, customTypeMap); } } } @@ -59672,9 +64356,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -59682,14 +64367,17 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -59712,18 +64400,20 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); @@ -59757,6 +64447,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -59784,8 +64477,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders and the outDir - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + // If no includes were specified, exclude common package folders and the outDir + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -59794,33 +64487,49 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -59955,7 +64664,7 @@ var ts; * @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) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { 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 @@ -59982,7 +64691,7 @@ var ts; 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); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (fileNames) { @@ -60051,6 +64760,7 @@ var ts; // // /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 + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler // // We watch a directory without recursion if it contains a wildcard in the file segment of // the pattern: @@ -60064,14 +64774,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_45 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_45)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_45); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_45) ? 1 /* Recursive */ : 0 /* None */; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -60093,6 +64802,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } /** * Determines whether a literal or wildcard file has already been included that has a higher * extension priority. @@ -60166,12 +64888,14 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + StringScriptSnapshot.prototype.getChangeRange = function () { // Text-based snapshots do not support incremental parsing. Return undefined // to signal that to the caller. return undefined; @@ -60196,12 +64920,13 @@ var ts; HighlightSpanKind.reference = "reference"; HighlightSpanKind.writtenReference = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; (function (IndentStyle) { IndentStyle[IndentStyle["None"] = 0] = "None"; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -60225,14 +64950,14 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; - })(ts.OutputFileType || (ts.OutputFileType = {})); - var OutputFileType = ts.OutputFileType; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; (function (EndOfLineState) { EndOfLineState[EndOfLineState["None"] = 0] = "None"; EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; @@ -60241,8 +64966,8 @@ var ts; EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; - })(ts.EndOfLineState || (ts.EndOfLineState = {})); - var EndOfLineState = ts.EndOfLineState; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -60253,8 +64978,7 @@ var ts; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); // TODO: move these to enums var ScriptElementKind; (function (ScriptElementKind) { @@ -60361,6 +65085,7 @@ var ts; ClassificationTypeNames.jsxText = "jsx text"; ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; @@ -60386,52 +65111,51 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; - })(ts.ClassificationType || (ts.ClassificationType = {})); - var ClassificationType = ts.ClassificationType; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); ts.emptyArray = []; + var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; - })(ts.SemanticMeaning || (ts.SemanticMeaning = {})); - var SemanticMeaning = ts.SemanticMeaning; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 252 /* CatchClause */: + case 144 /* Parameter */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: + case 260 /* EnumMember */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 256 /* CatchClause */: return 1 /* Value */; - case 141 /* TypeParameter */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 159 /* TypeLiteral */: + case 143 /* TypeParameter */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 161 /* TypeLiteral */: return 2 /* Type */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -60441,22 +65165,22 @@ var ts; else { return 4 /* Namespace */; } - case 233 /* NamedImports */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: + case 238 /* NamedImports */: + case 239 /* ImportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 235 /* ImportDeclaration */: + case 240 /* ExportAssignment */: + case 241 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 256 /* SourceFile */: + case 261 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.parent.kind === 235 /* ExportAssignment */) { + if (node.parent.kind === 240 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -60477,19 +65201,19 @@ var ts; } ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69 /* Identifier */); + ts.Debug.assert(node.kind === 70 /* Identifier */); // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 139 /* QualifiedName */ && + if (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 234 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function isInRightSideOfImport(node) { - while (node.parent.kind === 139 /* QualifiedName */) { + while (node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -60500,27 +65224,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 139 /* QualifiedName */) { - while (root.parent && root.parent.kind === 139 /* QualifiedName */) { + if (root.parent.kind === 141 /* QualifiedName */) { + while (root.parent && root.parent.kind === 141 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 155 /* TypeReference */ && !isLastClause; + return root.parent.kind === 157 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 172 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { + if (root.parent.kind === 177 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 177 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 199 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 255 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 226 /* ClassDeclaration */ && root.parent.parent.token === 107 /* ImplementsKeyword */) || + (decl.kind === 227 /* InterfaceDeclaration */ && root.parent.parent.token === 84 /* ExtendsKeyword */); } return false; } @@ -60528,17 +65252,17 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 155 /* TypeReference */ || - (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || - node.kind === 165 /* ThisType */; + return node.parent.kind === 157 /* TypeReference */ || + (node.parent.kind === 199 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 98 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || + node.kind === 167 /* ThisType */; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 174 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 179 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 175 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 180 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -60551,7 +65275,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 219 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -60560,14 +65284,14 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 69 /* Identifier */ && - (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && + return node.kind === 70 /* Identifier */ && + (node.parent.kind === 215 /* BreakStatement */ || node.parent.kind === 214 /* ContinueStatement */) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 69 /* Identifier */ && - node.parent.kind === 214 /* LabeledStatement */ && + return node.kind === 70 /* Identifier */ && + node.parent.kind === 219 /* LabeledStatement */ && node.parent.label === node; } function isLabelName(node) { @@ -60575,38 +65299,38 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 230 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 69 /* Identifier */ && + return node.kind === 70 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 225 /* ModuleDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 260 /* EnumMember */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 230 /* ModuleDeclaration */: return node.parent.name === node; - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return true; } } @@ -60655,17 +65379,17 @@ var ts; return undefined; } switch (node.kind) { - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: return node; } } @@ -60673,46 +65397,46 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return ts.ScriptElementKind.moduleElement; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return ts.ScriptElementKind.classElement; - case 222 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; - case 223 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; - case 224 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; - case 218 /* VariableDeclaration */: + case 227 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; + case 228 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; + case 229 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + case 223 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return ts.ScriptElementKind.functionElement; - case 149 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 151 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; + case 152 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return ts.ScriptElementKind.memberFunctionElement; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return ts.ScriptElementKind.memberVariableElement; - case 153 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; - case 152 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; - case 151 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; - case 148 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; - case 141 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; - case 255 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; - case 142 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 231 /* ImportClause */: - case 238 /* ExportSpecifier */: - case 232 /* NamespaceImport */: + case 155 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; + case 154 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; + case 153 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; + case 150 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; + case 143 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; + case 260 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; + case 144 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 234 /* ImportEqualsDeclaration */: + case 239 /* ImportSpecifier */: + case 236 /* ImportClause */: + case 243 /* ExportSpecifier */: + case 237 /* NamespaceImport */: return ts.ScriptElementKind.alias; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return ts.ScriptElementKind.typeElement; default: return ts.ScriptElementKind.unknown; @@ -60727,7 +65451,7 @@ var ts; } ts.getNodeKind = getNodeKind; function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 171 /* LiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); if (type && type.flags & 32 /* StringLiteral */) { return type; @@ -60737,12 +65461,12 @@ var ts; ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; function isThis(node) { switch (node.kind) { - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 69 /* Identifier */: + case 70 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 144 /* Parameter */; default: return false; } @@ -60787,42 +65511,42 @@ var ts; return false; } switch (n.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 167 /* ObjectBindingPattern */: - case 159 /* TypeLiteral */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 227 /* CaseBlock */: - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 252 /* CatchClause */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 172 /* ObjectBindingPattern */: + case 161 /* TypeLiteral */: + case 204 /* Block */: + case 231 /* ModuleBlock */: + case 232 /* CaseBlock */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: + return nodeEndsWith(n, 17 /* CloseBraceToken */, sourceFile); + case 256 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 175 /* NewExpression */: + case 180 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - case 164 /* ParenthesizedType */: - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 179 /* CallExpression */: + case 183 /* ParenthesizedExpression */: + case 166 /* ParenthesizedType */: + return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 180 /* ArrowFunction */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 185 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -60831,68 +65555,68 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 225 /* ModuleDeclaration */: + return hasChildOfKind(n, 19 /* CloseParenToken */, sourceFile); + case 230 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 203 /* IfStatement */: + case 208 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23 /* SemicolonToken */); - case 170 /* ArrayLiteralExpression */: - case 168 /* ArrayBindingPattern */: - case 173 /* ElementAccessExpression */: - case 140 /* ComputedPropertyName */: - case 161 /* TupleType */: - return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 153 /* IndexSignature */: + hasChildOfKind(n, 24 /* SemicolonToken */); + case 175 /* ArrayLiteralExpression */: + case 173 /* ArrayBindingPattern */: + case 178 /* ElementAccessExpression */: + case 142 /* ComputedPropertyName */: + case 163 /* TupleType */: + return nodeEndsWith(n, 21 /* CloseBracketToken */, sourceFile); + case 155 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + return hasChildOfKind(n, 21 /* CloseBracketToken */, sourceFile); + case 253 /* CaseClause */: + case 254 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 210 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 204 /* DoStatement */: + case 209 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); + var hasWhileKeyword = findChildOfKind(n, 105 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 182 /* TypeOfExpression */: - case 181 /* DeleteExpression */: - case 183 /* VoidExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: + case 187 /* TypeOfExpression */: + case 186 /* DeleteExpression */: + case 188 /* VoidExpression */: + case 195 /* YieldExpression */: + case 196 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 236 /* ExportDeclaration */: - case 230 /* ImportDeclaration */: + case 241 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -60910,7 +65634,7 @@ var ts; if (last.kind === expectedLastToken) { return true; } - else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { + else if (last.kind === 24 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -60948,7 +65672,7 @@ var ts; // for the position of the relevant node (or comma). var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { // find syntax list that covers the span of the node - if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 292 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -61083,7 +65807,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -61091,7 +65815,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -61105,10 +65829,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -61120,7 +65844,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 261 /* SourceFile */); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -61171,25 +65895,25 @@ var ts; if (!token) { return false; } - if (token.kind === 244 /* JsxText */) { + if (token.kind === 10 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 252 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { + if (token && token.kind === 17 /* CloseBraceToken */ && token.parent.kind === 252 /* JsxExpression */) { return true; } //
|
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 249 /* JsxClosingElement */) { return true; } return false; @@ -61246,9 +65970,9 @@ var ts; var node = ts.getTokenAtPosition(sourceFile, position); if (isToken(node)) { switch (node.kind) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: // if the current token is var, let or const, skip the VariableDeclarationList node = node.parent === undefined ? undefined : node.parent.parent; break; @@ -61258,11 +65982,11 @@ var ts; } } if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - if (jsDocComment.tags) { - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (jsDoc.tags) { + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; if (tag.pos <= position && position <= tag.end) { return tag; @@ -61301,21 +66025,21 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { + if (node.kind === 157 /* TypeReference */ || node.kind === 179 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 226 /* ClassDeclaration */ || node.kind === 227 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 140 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { - return kind === 69 /* Identifier */ || ts.isKeyword(kind); + return kind === 70 /* Identifier */ || ts.isKeyword(kind); } ts.isWord = isWord; function isPropertyName(kind) { @@ -61327,7 +66051,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ - || kind === 10 /* RegularExpressionLiteral */ + || kind === 11 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -61335,7 +66059,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; + return 16 /* FirstPunctuation */ <= kind && kind <= 69 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position) { @@ -61345,9 +66069,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: return true; } return false; @@ -61370,18 +66094,18 @@ var ts; } ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 /* ArrayLiteralExpression */ || - node.kind === 171 /* ObjectLiteralExpression */) { + if (node.kind === 175 /* ArrayLiteralExpression */ || + node.kind === 176 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 187 /* BinaryExpression */ && + if (node.parent.kind === 192 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 56 /* EqualsToken */) { + node.parent.operatorToken.kind === 57 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 208 /* ForOfStatement */ && + if (node.parent.kind === 213 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -61389,7 +66113,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 257 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -61420,10 +66144,9 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 144 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -61440,13 +66163,14 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; function writeIndent() { if (lineStart) { @@ -61476,7 +66200,7 @@ var ts; } } function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); + return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol) { var flags = symbol.flags; if (flags & 3 /* Variable */) { @@ -61525,7 +66249,7 @@ var ts; } } ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { + function displayPart(text, kind) { return { text: text, kind: ts.SymbolDisplayPartKind[kind] @@ -61602,8 +66326,8 @@ var ts; if (isImportOrExportSpecifierName(location)) { return location.getText(); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140 /* ComputedPropertyName */) { + else if (ts.isStringOrNumericLiteral(location) && + location.parent.kind === 142 /* ComputedPropertyName */) { return location.text; } // Try to get the local symbol if we're dealing with an 'export default' @@ -61615,7 +66339,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && + (location.parent.kind === 239 /* ImportSpecifier */ || location.parent.kind === 243 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -61657,11 +66381,11 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { - target: 2 /* ES6 */, + target: 2 /* ES2015 */, removeComments: true }, reportDiagnostics: true @@ -61671,37 +66395,40 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { /// Classifier function createClassifier() { - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false); /// We do not have a full parser support to know when we should parse a regex or not /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = []; - noRegexTable[69 /* Identifier */] = true; + noRegexTable[70 /* Identifier */] = true; noRegexTable[9 /* StringLiteral */] = true; noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[10 /* RegularExpressionLiteral */] = true; - noRegexTable[97 /* ThisKeyword */] = true; - noRegexTable[41 /* PlusPlusToken */] = true; - noRegexTable[42 /* MinusMinusToken */] = true; - noRegexTable[18 /* CloseParenToken */] = true; - noRegexTable[20 /* CloseBracketToken */] = true; - noRegexTable[16 /* CloseBraceToken */] = true; - noRegexTable[99 /* TrueKeyword */] = true; - noRegexTable[84 /* FalseKeyword */] = true; + noRegexTable[11 /* RegularExpressionLiteral */] = true; + noRegexTable[98 /* ThisKeyword */] = true; + noRegexTable[42 /* PlusPlusToken */] = true; + noRegexTable[43 /* MinusMinusToken */] = true; + noRegexTable[19 /* CloseParenToken */] = true; + noRegexTable[21 /* CloseBracketToken */] = true; + noRegexTable[17 /* CloseBraceToken */] = true; + noRegexTable[100 /* TrueKeyword */] = true; + noRegexTable[85 /* FalseKeyword */] = true; // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) // classification on template strings. Because of the context free nature of templates, // the only precise way to classify a template portion would be by propagating the stack across @@ -61726,10 +66453,10 @@ var ts; /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 131 /* SetKeyword */ || - keyword2 === 121 /* ConstructorKeyword */ || - keyword2 === 113 /* StaticKeyword */) { + if (keyword2 === 124 /* GetKeyword */ || + keyword2 === 133 /* SetKeyword */ || + keyword2 === 122 /* ConstructorKeyword */ || + keyword2 === 114 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; @@ -61828,7 +66555,7 @@ var ts; offset = 2; // fallthrough case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(12 /* TemplateHead */); + templateStack.push(13 /* TemplateHead */); break; } scanner.setText(text); @@ -61859,71 +66586,71 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { - token = 10 /* RegularExpressionLiteral */; + if ((token === 40 /* SlashToken */ || token === 62 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 11 /* RegularExpressionLiteral */) { + token = 11 /* RegularExpressionLiteral */; } } - else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { - token = 69 /* Identifier */; + else if (lastNonTriviaToken === 22 /* DotToken */ && isKeyword(token)) { + token = 70 /* Identifier */; } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 69 /* Identifier */; + token = 70 /* Identifier */; } - else if (lastNonTriviaToken === 69 /* Identifier */ && - token === 25 /* LessThanToken */) { + else if (lastNonTriviaToken === 70 /* Identifier */ && + token === 26 /* LessThanToken */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } - else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { + else if (token === 28 /* GreaterThanToken */ && angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } - else if (token === 117 /* AnyKeyword */ || - token === 132 /* StringKeyword */ || - token === 130 /* NumberKeyword */ || - token === 120 /* BooleanKeyword */ || - token === 133 /* SymbolKeyword */) { + else if (token === 118 /* AnyKeyword */ || + token === 134 /* StringKeyword */ || + token === 132 /* NumberKeyword */ || + token === 121 /* BooleanKeyword */ || + token === 135 /* SymbolKeyword */) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, // causing a noisy experience for the user. - token = 69 /* Identifier */; + token = 70 /* Identifier */; } } - else if (token === 12 /* TemplateHead */) { + else if (token === 13 /* TemplateHead */) { templateStack.push(token); } - else if (token === 15 /* OpenBraceToken */) { + else if (token === 16 /* OpenBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } } - else if (token === 16 /* CloseBraceToken */) { + else if (token === 17 /* CloseBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12 /* TemplateHead */) { + if (lastTemplateStackToken === 13 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 14 /* TemplateTail */) { + if (token === 15 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + ts.Debug.assert(token === 14 /* TemplateMiddle */, "Should have been a template middle. Was " + token); } } else { - ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + ts.Debug.assert(lastTemplateStackToken === 16 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); templateStack.pop(); } } @@ -61964,10 +66691,10 @@ var ts; } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { - if (token === 14 /* TemplateTail */) { + if (token === 15 /* TemplateTail */) { result.endOfLineState = 5 /* InTemplateMiddleOrTail */; } - else if (token === 11 /* NoSubstitutionTemplateLiteral */) { + else if (token === 12 /* NoSubstitutionTemplateLiteral */) { result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; } else { @@ -61975,7 +66702,7 @@ var ts; } } } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 13 /* TemplateHead */) { result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; } } @@ -62005,43 +66732,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 46 /* AmpersandToken */: - case 48 /* CaretToken */: - case 47 /* BarToken */: - case 51 /* AmpersandAmpersandToken */: - case 52 /* BarBarToken */: - case 67 /* BarEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 56 /* EqualsToken */: - case 24 /* CommaToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: + case 92 /* InstanceOfKeyword */: + case 91 /* InKeyword */: + case 117 /* AsKeyword */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: + case 47 /* AmpersandToken */: + case 49 /* CaretToken */: + case 48 /* BarToken */: + case 52 /* AmpersandAmpersandToken */: + case 53 /* BarBarToken */: + case 68 /* BarEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 57 /* EqualsToken */: + case 25 /* CommaToken */: return true; default: return false; @@ -62049,19 +66776,19 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: return true; default: return false; } } function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; + return token >= 71 /* FirstKeyword */ && token <= 140 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -62070,7 +66797,7 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { + else if (token >= 16 /* FirstPunctuation */ && token <= 69 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { @@ -62078,7 +66805,7 @@ var ts; return 4 /* numericLiteral */; case 9 /* StringLiteral */: return 6 /* stringLiteral */; - case 10 /* RegularExpressionLiteral */: + case 11 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -62087,7 +66814,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 69 /* Identifier */: + case 70 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -62118,10 +66845,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -62172,7 +66899,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 /* ModuleDeclaration */ && + return declaration.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -62182,7 +66909,7 @@ var ts; if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { var kind = node.kind; checkForClassificationCancellation(cancellationToken, kind); - if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { + if (kind === 70 /* Identifier */ && !ts.nodeIsMissing(node)) { var identifier = node; // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run @@ -62251,8 +66978,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -62336,16 +67063,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 275 /* JSDocParameterTag */: + case 281 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 278 /* JSDocTemplateTag */: + case 284 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 277 /* JSDocTypeTag */: + case 283 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 276 /* JSDocReturnTag */: + case 282 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -62416,10 +67143,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -62432,22 +67159,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -62464,7 +67191,7 @@ var ts; } // Special case < and > If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { + if (tokenKind === 26 /* LessThanToken */ || tokenKind === 28 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -62473,19 +67200,19 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { - if (tokenKind === 56 /* EqualsToken */) { + if (tokenKind === 57 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 218 /* VariableDeclaration */ || - token.parent.kind === 145 /* PropertyDeclaration */ || - token.parent.kind === 142 /* Parameter */ || - token.parent.kind === 246 /* JsxAttribute */) { + if (token.parent.kind === 223 /* VariableDeclaration */ || + token.parent.kind === 147 /* PropertyDeclaration */ || + token.parent.kind === 144 /* Parameter */ || + token.parent.kind === 250 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 187 /* BinaryExpression */ || - token.parent.kind === 185 /* PrefixUnaryExpression */ || - token.parent.kind === 186 /* PostfixUnaryExpression */ || - token.parent.kind === 188 /* ConditionalExpression */) { + if (token.parent.kind === 192 /* BinaryExpression */ || + token.parent.kind === 190 /* PrefixUnaryExpression */ || + token.parent.kind === 191 /* PostfixUnaryExpression */ || + token.parent.kind === 193 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -62495,9 +67222,9 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token.parent.kind === 250 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } - else if (tokenKind === 10 /* RegularExpressionLiteral */) { + else if (tokenKind === 11 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -62505,41 +67232,40 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 244 /* JsxText */) { + else if (tokenKind === 10 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 69 /* Identifier */) { + else if (tokenKind === 70 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 142 /* Parameter */: + case 144 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62567,6 +67293,7 @@ var ts; } ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; })(ts || (ts = {})); +/// /* @internal */ var ts; (function (ts) { @@ -62583,20 +67310,20 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 245 /* JsxClosingElement */) { + location.parent && location.parent.kind === 249 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: @@ -62606,7 +67333,7 @@ var ts; name: tagName.text, kind: undefined, kindModifiers: undefined, - sortText: "0" + sortText: "0", }); } else { @@ -62619,18 +67346,18 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { + for (var name_44 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_46] === position) { + if (nameTable[name_44] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_44]) { + uniqueNames[name_44] = name_44; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_44), compilerOptions.target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -62663,7 +67390,7 @@ var ts; name: displayName, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - sortText: "0" + sortText: "0", }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { @@ -62690,7 +67417,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 257 /* PropertyAssignment */ && + node.parent.parent.kind === 176 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62714,7 +67443,7 @@ var ts; // a['/*completion position*/'] return getStringLiteralCompletionEntriesFromElementAccess(node.parent); } - else if (node.parent.kind === 230 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + else if (node.parent.kind === 235 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // import x = require("/*completion position*/"); @@ -62727,7 +67456,7 @@ var ts; // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); } // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" @@ -62740,11 +67469,11 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { var candidates = []; var entries = []; typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); @@ -62756,7 +67485,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +67495,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +67506,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62786,7 +67515,7 @@ var ts; if (!type) { return; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { @@ -62819,6 +67548,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +67584,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +67609,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +67784,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +67804,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63084,7 +67836,7 @@ var ts; if (typeRoots) { for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); + getCompletionEntriesFromDirectories(host, root, span, result); } } } @@ -63093,12 +67845,12 @@ var ts; for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { var packageJson = _d[_c]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + getCompletionEntriesFromDirectories(host, typesDir, span, result); } } return result; } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + function getCompletionEntriesFromDirectories(host, directory, span, result) { if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { @@ -63118,11 +67870,11 @@ var ts; if (currentConfigPath) { paths.push(currentConfigPath); currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_16 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_16) { + var parent_13 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_13) { break; } - currentDir = parent_16; + currentDir = parent_13; } else { break; @@ -63203,14 +67955,14 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; + var symbols = completionData.symbols, location_3 = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -63238,12 +67990,12 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location; + var symbols = completionData.symbols, location_4 = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_4) === entryName ? s : undefined; }); } return undefined; } @@ -63274,9 +68026,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 277 /* JSDocTypeTag */: - case 275 /* JSDocParameterTag */: - case 276 /* JSDocReturnTag */: + case 283 /* JSDocTypeTag */: + case 281 /* JSDocParameterTag */: + case 282 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -63285,7 +68037,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63321,13 +68073,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21 /* DotToken */) { - if (parent_17.kind === 172 /* PropertyAccessExpression */) { + var parent_14 = contextToken.parent, kind = contextToken.kind; + if (kind === 22 /* DotToken */) { + if (parent_14.kind === 177 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_17.kind === 139 /* QualifiedName */) { + else if (parent_14.kind === 141 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -63338,17 +68090,18 @@ var ts; } } else if (sourceFile.languageVariant === 1 /* JSX */) { - if (kind === 25 /* LessThanToken */) { + if (kind === 26 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { + else if (kind === 40 /* SlashToken */ && contextToken.parent.kind === 249 /* JsxClosingElement */) { isStartingCloseTag = true; location = contextToken; } } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63384,12 +68137,13 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { + if (node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -63417,7 +68171,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 524288 /* Union */) { + if (isJavaScriptFile && type.flags & 65536 /* Union */) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that // each individual type has. This is because we're going to add all identifiers @@ -63445,7 +68199,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 247 /* JsxSelfClosingElement */) || (jsxContainer.kind === 248 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -63491,6 +68245,13 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + if (scopeNode) { + isGlobalCompletion = + scopeNode.kind === 261 /* SourceFile */ || + scopeNode.kind === 194 /* TemplateExpression */ || + scopeNode.kind === 252 /* JsxExpression */ || + ts.isStatement(scopeNode); + } /// TODO filter meaning based on the current context var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -63517,15 +68278,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 244 /* JsxText */) { + if (contextToken.kind === 10 /* JsxText */) { return true; } - if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { + if (contextToken.kind === 28 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 248 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; + if (contextToken.parent.kind === 249 /* JsxClosingElement */ || contextToken.parent.kind === 247 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 246 /* JsxElement */; } } return false; @@ -63534,41 +68295,41 @@ var ts; if (previousToken) { var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 174 /* CallExpression */ // func( a, | - || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 175 /* NewExpression */ // new C(a, | - || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| - case 17 /* OpenParenToken */: - return containingNodeKind === 174 /* CallExpression */ // func( | - || containingNodeKind === 148 /* Constructor */ // constructor( | - || containingNodeKind === 175 /* NewExpression */ // new C(a| - || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 19 /* OpenBracketToken */: - return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 125 /* ModuleKeyword */: // module | - case 126 /* NamespaceKeyword */: + case 25 /* CommaToken */: + return containingNodeKind === 179 /* CallExpression */ // func( a, | + || containingNodeKind === 150 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 180 /* NewExpression */ // new C(a, | + || containingNodeKind === 175 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 192 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 158 /* FunctionType */; // var x: (s: string, list| + case 18 /* OpenParenToken */: + return containingNodeKind === 179 /* CallExpression */ // func( | + || containingNodeKind === 150 /* Constructor */ // constructor( | + || containingNodeKind === 180 /* NewExpression */ // new C(a| + || containingNodeKind === 183 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 166 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 20 /* OpenBracketToken */: + return containingNodeKind === 175 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 155 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 142 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 127 /* ModuleKeyword */: // module | + case 128 /* NamespaceKeyword */: return true; - case 21 /* DotToken */: - return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| - case 15 /* OpenBraceToken */: - return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | - case 56 /* EqualsToken */: - return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 187 /* BinaryExpression */; // x = a| - case 12 /* TemplateHead */: - return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| - case 13 /* TemplateMiddle */: - return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | + case 22 /* DotToken */: + return containingNodeKind === 230 /* ModuleDeclaration */; // module A.| + case 16 /* OpenBraceToken */: + return containingNodeKind === 226 /* ClassDeclaration */; // class A{ | + case 57 /* EqualsToken */: + return containingNodeKind === 223 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 192 /* BinaryExpression */; // x = a| + case 13 /* TemplateHead */: + return containingNodeKind === 194 /* TemplateExpression */; // `aa ${| + case 14 /* TemplateMiddle */: + return containingNodeKind === 202 /* TemplateSpan */; // `aa ${10} dd ${| + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + return containingNodeKind === 147 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -63582,7 +68343,7 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ - || contextToken.kind === 10 /* RegularExpressionLiteral */ + || contextToken.kind === 11 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); @@ -63595,7 +68356,7 @@ var ts; } if (position === end) { return !!contextToken.isUnterminated - || contextToken.kind === 10 /* RegularExpressionLiteral */; + || contextToken.kind === 11 /* RegularExpressionLiteral */; } } return false; @@ -63611,7 +68372,7 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 176 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; @@ -63621,7 +68382,7 @@ var ts; typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 172 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -63632,11 +68393,11 @@ var ts; // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { + if (!canGetType && rootDeclaration.kind === 144 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 149 /* MethodDeclaration */ || rootDeclaration.parent.kind === 152 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -63678,9 +68439,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? - 230 /* ImportDeclaration */ : - 236 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 238 /* NamedImports */ ? + 235 /* ImportDeclaration */ : + 241 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -63703,11 +68464,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // const x = { | - case 24 /* CommaToken */: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { - return parent_18; + case 16 /* OpenBraceToken */: // const x = { | + case 25 /* CommaToken */: + var parent_15 = contextToken.parent; + if (parent_15 && (parent_15.kind === 176 /* ObjectLiteralExpression */ || parent_15.kind === 172 /* ObjectBindingPattern */)) { + return parent_15; } break; } @@ -63721,11 +68482,11 @@ var ts; function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // import { | - case 24 /* CommaToken */: + case 16 /* OpenBraceToken */: // import { | + case 25 /* CommaToken */: switch (contextToken.parent.kind) { - case 233 /* NamedImports */: - case 237 /* NamedExports */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: return contextToken.parent; } } @@ -63734,37 +68495,37 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_19 = contextToken.parent; + var parent_16 = contextToken.parent; switch (contextToken.kind) { - case 26 /* LessThanSlashToken */: - case 39 /* SlashToken */: - case 69 /* Identifier */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { - return parent_19; + case 27 /* LessThanSlashToken */: + case 40 /* SlashToken */: + case 70 /* Identifier */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: + if (parent_16 && (parent_16.kind === 247 /* JsxSelfClosingElement */ || parent_16.kind === 248 /* JsxOpeningElement */)) { + return parent_16; } - else if (parent_19.kind === 246 /* JsxAttribute */) { - return parent_19.parent; + else if (parent_16.kind === 250 /* JsxAttribute */) { + return parent_16.parent; } break; // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { - return parent_19.parent; + if (parent_16 && ((parent_16.kind === 250 /* JsxAttribute */) || (parent_16.kind === 251 /* JsxSpreadAttribute */))) { + return parent_16.parent; } break; - case 16 /* CloseBraceToken */: - if (parent_19 && - parent_19.kind === 248 /* JsxExpression */ && - parent_19.parent && - (parent_19.parent.kind === 246 /* JsxAttribute */)) { - return parent_19.parent.parent; + case 17 /* CloseBraceToken */: + if (parent_16 && + parent_16.kind === 252 /* JsxExpression */ && + parent_16.parent && + (parent_16.parent.kind === 250 /* JsxAttribute */)) { + return parent_16.parent.parent; } - if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { - return parent_19.parent; + if (parent_16 && parent_16.kind === 251 /* JsxSpreadAttribute */) { + return parent_16.parent; } break; } @@ -63773,16 +68534,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return true; } return false; @@ -63793,67 +68554,67 @@ var ts; function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 218 /* VariableDeclaration */ || - containingNodeKind === 219 /* VariableDeclarationList */ || - containingNodeKind === 200 /* VariableStatement */ || - containingNodeKind === 224 /* EnumDeclaration */ || + case 25 /* CommaToken */: + return containingNodeKind === 223 /* VariableDeclaration */ || + containingNodeKind === 224 /* VariableDeclarationList */ || + containingNodeKind === 205 /* VariableStatement */ || + containingNodeKind === 229 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 168 /* ArrayBindingPattern */ || - containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | - case 21 /* DotToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| - case 54 /* ColonToken */: - return containingNodeKind === 169 /* BindingElement */; // var {x :html| - case 19 /* OpenBracketToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| - case 17 /* OpenParenToken */: - return containingNodeKind === 252 /* CatchClause */ || + containingNodeKind === 226 /* ClassDeclaration */ || + containingNodeKind === 197 /* ClassExpression */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 173 /* ArrayBindingPattern */ || + containingNodeKind === 228 /* TypeAliasDeclaration */; // type Map, K, | + case 22 /* DotToken */: + return containingNodeKind === 173 /* ArrayBindingPattern */; // var [.| + case 55 /* ColonToken */: + return containingNodeKind === 174 /* BindingElement */; // var {x :html| + case 20 /* OpenBracketToken */: + return containingNodeKind === 173 /* ArrayBindingPattern */; // var [x| + case 18 /* OpenParenToken */: + return containingNodeKind === 256 /* CatchClause */ || isFunction(containingNodeKind); - case 15 /* OpenBraceToken */: - return containingNodeKind === 224 /* EnumDeclaration */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 159 /* TypeLiteral */; // const x : { | - case 23 /* SemicolonToken */: - return containingNodeKind === 144 /* PropertySignature */ && + case 16 /* OpenBraceToken */: + return containingNodeKind === 229 /* EnumDeclaration */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 161 /* TypeLiteral */; // const x : { | + case 24 /* SemicolonToken */: + return containingNodeKind === 146 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | - case 25 /* LessThanToken */: - return containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 223 /* TypeAliasDeclaration */ || + (contextToken.parent.parent.kind === 227 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 161 /* TypeLiteral */); // const x : { a; | + case 26 /* LessThanToken */: + return containingNodeKind === 226 /* ClassDeclaration */ || + containingNodeKind === 197 /* ClassExpression */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 228 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); - case 113 /* StaticKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; - case 22 /* DotDotDotToken */: - return containingNodeKind === 142 /* Parameter */ || + case 114 /* StaticKeyword */: + return containingNodeKind === 147 /* PropertyDeclaration */; + case 23 /* DotDotDotToken */: + return containingNodeKind === 144 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 142 /* Parameter */; - case 116 /* AsKeyword */: - return containingNodeKind === 234 /* ImportSpecifier */ || - containingNodeKind === 238 /* ExportSpecifier */ || - containingNodeKind === 232 /* NamespaceImport */; - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 107 /* InterfaceKeyword */: - case 87 /* FunctionKeyword */: - case 102 /* VarKeyword */: - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - case 89 /* ImportKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 114 /* YieldKeyword */: - case 134 /* TypeKeyword */: + contextToken.parent.parent.kind === 173 /* ArrayBindingPattern */); // var [...z| + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + return containingNodeKind === 144 /* Parameter */; + case 117 /* AsKeyword */: + return containingNodeKind === 239 /* ImportSpecifier */ || + containingNodeKind === 243 /* ExportSpecifier */ || + containingNodeKind === 237 /* NamespaceImport */; + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: + case 108 /* InterfaceKeyword */: + case 88 /* FunctionKeyword */: + case 103 /* VarKeyword */: + case 124 /* GetKeyword */: + case 133 /* SetKeyword */: + case 90 /* ImportKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: + case 115 /* YieldKeyword */: + case 136 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -63901,8 +68662,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_45 = element.propertyName || element.name; + existingImportsOrExports[name_45.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -63923,10 +68684,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 253 /* PropertyAssignment */ && - m.kind !== 254 /* ShorthandPropertyAssignment */ && - m.kind !== 169 /* BindingElement */ && - m.kind !== 147 /* MethodDeclaration */) { + if (m.kind !== 257 /* PropertyAssignment */ && + m.kind !== 258 /* ShorthandPropertyAssignment */ && + m.kind !== 174 /* BindingElement */ && + m.kind !== 149 /* MethodDeclaration */ && + m.kind !== 151 /* GetAccessor */ && + m.kind !== 152 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -63934,9 +68697,9 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 169 /* BindingElement */ && m.propertyName) { + if (m.kind === 174 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 69 /* Identifier */) { + if (m.propertyName.kind === 70 /* Identifier */) { existingName = m.propertyName.text; } } @@ -63964,7 +68727,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 246 /* JsxAttribute */) { + if (attr.kind === 250 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -64014,7 +68777,7 @@ var ts; } // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { + for (var i = 71 /* FirstKeyword */; i <= 140 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ts.ScriptElementKind.keyword, @@ -64026,9 +68789,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// = 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 105 /* WhileKeyword */)) { break; } } @@ -64455,7 +69224,7 @@ var ts; var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */, 76 /* ContinueKeyword */); } }); return ts.map(keywords, getHighlightSpanForNode); @@ -64464,13 +69233,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -64478,14 +69247,14 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 97 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 72 /* CaseKeyword */, 78 /* DefaultKeyword */); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */); } }); }); @@ -64493,13 +69262,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 101 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 86 /* FinallyKeyword */); } return ts.map(keywords, getHighlightSpanForNode); } @@ -64510,13 +69279,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */); }); } return ts.map(keywords, getHighlightSpanForNode); @@ -64524,36 +69293,36 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 199 /* Block */))) { + if (!(func && hasKind(func.body, 204 /* Block */))) { return undefined; } var keywords = []; ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */); }); return ts.map(keywords, getHighlightSpanForNode); } function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 208 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (ifStatement) { var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 89 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 81 /* ElseKeyword */)) { break; } } - if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 208 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -64562,7 +69331,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 81 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombindElseAndIf = true; @@ -64596,7 +69365,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 219 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -64734,10 +69503,10 @@ var ts; break; } // Fallthrough - case 69 /* Identifier */: - case 97 /* ThisKeyword */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: // case SyntaxKind.SuperKeyword: TODO:GH#9268 - case 121 /* ConstructorKeyword */: + case 122 /* ConstructorKeyword */: case 9 /* StringLiteral */: return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, /*implementations*/ false); } @@ -64762,7 +69531,7 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } - if (node.kind === 95 /* SuperKeyword */) { + if (node.kind === 96 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } } @@ -64798,9 +69567,9 @@ var ts; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var internedName = getInternedName(symbol, node); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = ts.getNameTable(sourceFile); if (nameTable[internedName] !== undefined) { @@ -64830,12 +69599,12 @@ var ts; function getAliasSymbolForPropertyNameSymbol(symbol, location) { if (symbol.flags & 8388608 /* Alias */) { // Default import get alias - var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); + var defaultImport = ts.getDeclarationOfKind(symbol, 236 /* ImportClause */); if (defaultImport) { return typeChecker.getAliasedSymbol(symbol); } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || - declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 239 /* ImportSpecifier */ || + declaration.kind === 243 /* ExportSpecifier */) ? declaration : undefined; }); if (importOrExportSpecifier && // export { a } (!importOrExportSpecifier.propertyName || @@ -64843,7 +69612,7 @@ var ts; importOrExportSpecifier.propertyName === location)) { // If Import specifier -> get alias // else Export specifier -> get local target - return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? + return importOrExportSpecifier.kind === 239 /* ImportSpecifier */ ? typeChecker.getAliasedSymbol(symbol) : typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); } @@ -64858,20 +69627,20 @@ var ts; typeChecker.getPropertySymbolOfDestructuringAssignment(location); } function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */); return bindingElement && - bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 172 /* ObjectBindingPattern */ && !bindingElement.propertyName; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */); var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } return undefined; } - function getInternedName(symbol, location, declarations) { + function getInternedName(symbol, location) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever under the cursor. if (ts.isImportOrExportSpecifierName(location)) { @@ -64895,14 +69664,14 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 184 /* FunctionExpression */ || valueDeclaration.kind === 197 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 226 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -64933,7 +69702,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -64964,8 +69733,8 @@ var ts; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } @@ -65005,7 +69774,7 @@ var ts; if (node) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return node.getWidth() === searchSymbolName.length; case 9 /* StringLiteral */: if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || @@ -65069,14 +69838,14 @@ var ts; var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, - /*searchLocationIsConstructor*/ searchLocation.kind === 121 /* ConstructorKeyword */, parents, inheritsFromCache); + /*searchLocationIsConstructor*/ searchLocation.kind === 122 /* ConstructorKeyword */, parents, inheritsFromCache); if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } - else if (searchLocation.kind === 121 /* ConstructorKeyword */) { + else if (searchLocation.kind === 122 /* ConstructorKeyword */) { findAdditionalConstructorReferences(referenceSymbol, referenceLocation); } } @@ -65097,7 +69866,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== searchSymbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 1572864 /* UnionOrIntersection */) { + else if (localParentType.flags & 196608 /* UnionOrIntersection */) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -65137,17 +69906,17 @@ var ts; var result = []; for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148 /* Constructor */); + ts.Debug.assert(decl.kind === 150 /* Constructor */); var ctrKeyword = decl.getChildAt(0); - ts.Debug.assert(ctrKeyword.kind === 121 /* ConstructorKeyword */); + ts.Debug.assert(ctrKeyword.kind === 122 /* ConstructorKeyword */); result.push(ctrKeyword); } ts.forEachProperty(classSymbol.exports, function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 147 /* MethodDeclaration */) { + if (decl && decl.kind === 149 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 98 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { result.push(thisKeyword); } @@ -65167,10 +69936,10 @@ var ts; var result = []; for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148 /* Constructor */); + ts.Debug.assert(decl.kind === 150 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 95 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 96 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { result.push(node); } @@ -65208,8 +69977,8 @@ var ts; if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { result.push(getReferenceEntryFromNode(refNode.parent)); } - else if (refNode.kind === 69 /* Identifier */) { - if (refNode.parent.kind === 254 /* ShorthandPropertyAssignment */) { + else if (refNode.kind === 70 /* Identifier */) { + if (refNode.parent.kind === 258 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); } @@ -65222,24 +69991,24 @@ var ts; // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference) { - var parent_21 = containingTypeReference.parent; - if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { - maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + var parent_18 = containingTypeReference.parent; + if (ts.isVariableLike(parent_18) && parent_18.type === containingTypeReference && parent_18.initializer && isImplementationExpression(parent_18.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_18.initializer)); } - else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { - if (parent_21.body.kind === 199 /* Block */) { - ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + else if (ts.isFunctionLike(parent_18) && parent_18.type === containingTypeReference && parent_18.body) { + if (parent_18.body.kind === 204 /* Block */) { + ts.forEachReturnStatement(parent_18.body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); } }); } - else if (isImplementationExpression(parent_21.body)) { - maybeAdd(getReferenceEntryFromNode(parent_21.body)); + else if (isImplementationExpression(parent_18.body)) { + maybeAdd(getReferenceEntryFromNode(parent_18.body)); } } - else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { - maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + else if (ts.isAssertionExpression(parent_18) && isImplementationExpression(parent_18.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_18.expression)); } } } @@ -65261,7 +70030,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 1572864 /* UnionOrIntersection */) { + if (componentType.getFlags() & 196608 /* UnionOrIntersection */) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -65279,12 +70048,12 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 194 /* ExpressionWithTypeArguments */ - && node.parent.kind === 251 /* HeritageClause */ + if (node.kind === 199 /* ExpressionWithTypeArguments */ + && node.parent.kind === 255 /* HeritageClause */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 69 /* Identifier */ || node.kind === 172 /* PropertyAccessExpression */) { + else if (node.kind === 70 /* Identifier */ || node.kind === 177 /* PropertyAccessExpression */) { return getContainingClassIfInHeritageClause(node.parent); } } @@ -65295,14 +70064,14 @@ var ts; */ function isImplementationExpression(node) { // Unwrap parentheses - if (node.kind === 178 /* ParenthesizedExpression */) { + if (node.kind === 183 /* ParenthesizedExpression */) { return isImplementationExpression(node.expression); } - return node.kind === 180 /* ArrowFunction */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 171 /* ObjectLiteralExpression */ || - node.kind === 192 /* ClassExpression */ || - node.kind === 170 /* ArrayLiteralExpression */; + return node.kind === 185 /* ArrowFunction */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 176 /* ObjectLiteralExpression */ || + node.kind === 197 /* ClassExpression */ || + node.kind === 175 /* ArrayLiteralExpression */; } /** * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol @@ -65351,7 +70120,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { + else if (declaration.kind === 227 /* InterfaceDeclaration */) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -65379,13 +70148,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -65398,7 +70167,7 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95 /* SuperKeyword */) { + if (!node || node.kind !== 96 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -65417,27 +70186,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -65446,7 +70215,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 256 /* SourceFile */) { + if (searchSpaceNode.kind === 261 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -65480,28 +70249,28 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 256 /* SourceFile */: - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + case 261 /* SourceFile */: + if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -65516,8 +70285,8 @@ var ts; return undefined; } var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var sourceFile = sourceFiles_9[_i]; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); } @@ -65555,7 +70324,7 @@ var ts; // Search the property symbol // for ( { property: p2 } of elems) { } var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 258 /* ShorthandPropertyAssignment */) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); if (propertySymbol) { result.push(propertySymbol); @@ -65603,7 +70372,7 @@ var ts; // we should include both parameter declaration symbol and property declaration symbol // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 144 /* Parameter */ && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); } @@ -65658,7 +70427,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { + else if (declaration.kind === 227 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -65734,18 +70503,18 @@ var ts; return undefined; } } - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, /*previousIterationSymbolsCache*/ ts.createMap()); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } return undefined; @@ -65757,20 +70526,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_4 = []; + var result_5 = []; var symbol_2 = contextualType.getProperty(name); if (symbol_2) { - result_4.push(symbol_2); + result_5.push(symbol_2); } - if (contextualType.flags & 524288 /* Union */) { + if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); } - return result_4; + return result_5; } return undefined; } @@ -65824,7 +70593,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 218 /* VariableDeclaration */) { + else if (node.kind === 223 /* VariableDeclaration */) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } @@ -65834,18 +70603,18 @@ var ts; } else { switch (node.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 200 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 219 /* VariableDeclarationList */); + if (node.parent && node.parent.parent && node.parent.parent.kind === 205 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 224 /* VariableDeclarationList */); return node.parent.parent; } } @@ -65879,17 +70648,17 @@ var ts; FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node) { - if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { + if (node.kind === 70 /* Identifier */ && ts.isDeclarationName(node)) { return true; } var parent = node.parent; if (parent) { - if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { + if (parent.kind === 191 /* PostfixUnaryExpression */ || parent.kind === 190 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 192 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; - return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; + return 57 /* FirstAssignment */ <= operator && operator <= 69 /* LastAssignment */; } } return false; @@ -65909,22 +70678,22 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 140 /* ComputedPropertyName */) { + if (node.parent.kind === 142 /* ComputedPropertyName */) { return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; } // intential fall through - case 69 /* Identifier */: + case 70 /* Identifier */: return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; } return undefined; } function isObjectLiteralPropertyDeclaration(node) { switch (node.kind) { - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return true; } return false; @@ -65997,9 +70766,9 @@ var ts; // (1) when the aliased symbol was declared in the location(parent). // (2) when the aliased symbol is originating from a named import. // - if (node.kind === 69 /* Identifier */ && + if (node.kind === 70 /* Identifier */ && (node.parent === declaration || - (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { + (declaration.kind === 239 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 238 /* NamedImports */))) { symbol = typeChecker.getAliasedSymbol(symbol); } } @@ -66008,7 +70777,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -66036,14 +70805,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_5 = []; + if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_5; + return result_6; } if (!type.symbol) { return undefined; @@ -66066,7 +70835,7 @@ var ts; function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 121 /* ConstructorKeyword */) { + if (ts.isNewExpressionTarget(location) || location.kind === 122 /* ConstructorKeyword */) { if (symbol.flags & 32 /* Class */) { // Find the first class-like declaration and try to get the construct signature. for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { @@ -66091,8 +70860,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148 /* Constructor */) || - (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 150 /* Constructor */) || + (!selectConstructors && (d.kind === 225 /* FunctionDeclaration */ || d.kind === 149 /* MethodDeclaration */ || d.kind === 148 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -66172,12 +70941,12 @@ var ts; function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) { var result = []; ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); return result.length > 0 ? result : undefined; } - else if (node.kind === 95 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 96 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = typeChecker.getSymbolAtLocation(node); @@ -66226,6 +70995,7 @@ var ts; "lends", "link", "memberOf", + "method", "name", "namespace", "param", @@ -66245,7 +71015,7 @@ var ts; "version" ]; var jsDocCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + function getJsDocCommentsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -66254,7 +71024,7 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getJSDocComments(declaration, /*checkParentVariableStatement*/ true); + var comments = ts.getCommentsFromJSDoc(declaration); if (!comments) { return; } @@ -66295,7 +71065,7 @@ var ts; name: tagName, kind: ts.ScriptElementKind.keyword, kindModifiers: "", - sortText: "0" + sortText: "0", }; })); } @@ -66338,19 +71108,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - case 221 /* ClassDeclaration */: - case 200 /* VariableStatement */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 150 /* Constructor */: + case 226 /* ClassDeclaration */: + case 205 /* VariableStatement */: break findOwner; - case 256 /* SourceFile */: + case 261 /* SourceFile */: return undefined; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 230 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -66363,13 +71133,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; - var paramName = currentName.kind === 69 /* Identifier */ ? + var paramName = currentName.kind === 70 /* Identifier */ ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } // A doc comment consists of the following // * The opening comment line @@ -66391,7 +71167,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 200 /* VariableStatement */) { + if (commentOwner.kind === 205 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -66409,17 +71185,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 183 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return rightHandSide.parameters; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { + if (member.kind === 150 /* Constructor */) { return member.parameters; } } @@ -66431,7 +71207,9 @@ var ts; })(ts || (ts = {})); // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. -/// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,35 +71220,49 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); + /* @internal */ + JsTyping.nodeCoreModuleList = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console" + ]; + var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project * @param projectRootPath is the path to the project root directory * @param safeListPath is the path used to retrieve the safe list * @param packageNameToTypingLocation is the map of package names to their cached typing locations - * @param typingOptions are used to customize the typing inference process + * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { // A typing name to typing file path mapping var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { + if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information var searchDirs = []; var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { + if (projectRootPath) { possibleSearchDirs.push(projectRootPath); } searchDirs = ts.deduplicate(possibleSearchDirs); @@ -66484,15 +71276,25 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { + var moduleId = unresolvedImports_1[_a]; + var typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } + } + } // Add the cached typing locations for inferred typings that are already installed - for (var name_48 in packageNameToTypingLocation) { - if (name_48 in inferredTypings && !inferredTypings[name_48]) { - inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + for (var name_46 in packageNameToTypingLocation) { + if (name_46 in inferredTypings && !inferredTypings[name_46]) { + inferredTypings[name_46] = packageNameToTypingLocation[name_46]; } } // Remove typings that the user has added to the exclude list - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; + for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { + var excludeTypingName = exclude_1[_b]; delete inferredTypings[excludeTypingName]; } var newTypingNames = []; @@ -66524,10 +71326,12 @@ var ts; * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -66552,13 +71356,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +71374,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + 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); @@ -66616,21 +71417,22 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_49 in nameToDeclarations) { - var declarations = nameToDeclarations[name_49]; + for (var name_47 in nameToDeclarations) { + var declarations = nameToDeclarations[name_47]; 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_49); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_47); if (!matches) { continue; } @@ -66643,14 +71445,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_49); + matches = patternMatcher.getMatches(containers, name_47); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_47, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -66658,7 +71460,7 @@ var ts; // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; - if (decl.kind === 231 /* ImportClause */ || decl.kind === 234 /* ImportSpecifier */ || decl.kind === 229 /* ImportEqualsDeclaration */) { + if (decl.kind === 236 /* ImportClause */ || decl.kind === 239 /* ImportSpecifier */ || decl.kind === 234 /* ImportEqualsDeclaration */) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; @@ -66686,7 +71488,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { return node.text; @@ -66700,7 +71502,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 140 /* ComputedPropertyName */) { + else if (declaration.name.kind === 142 /* ComputedPropertyName */) { return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { @@ -66721,7 +71523,7 @@ var ts; } return true; } - if (expression.kind === 172 /* PropertyAccessExpression */) { + if (expression.kind === 177 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -66734,7 +71536,7 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 140 /* ComputedPropertyName */) { + if (declaration.name.kind === 142 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } @@ -66767,8 +71569,8 @@ var ts; // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -66803,6 +71605,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -66880,7 +71689,7 @@ var ts; return; } switch (node.kind) { - case 148 /* Constructor */: + case 150 /* 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); @@ -66892,21 +71701,21 @@ var ts; } } break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 148 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 231 /* ImportClause */: + case 236 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -66918,7 +71727,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 232 /* NamespaceImport */) { + if (namedBindings.kind === 237 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -66929,12 +71738,12 @@ var ts; } } break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 223 /* VariableDeclaration */: var decl = node; - var name_50 = decl.name; - if (ts.isBindingPattern(name_50)) { - addChildrenRecursively(name_50); + var name_48 = decl.name; + if (ts.isBindingPattern(name_48)) { + addChildrenRecursively(name_48); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -66944,12 +71753,12 @@ var ts; addNodeWithRecursiveChild(decl, decl.initializer); } break; - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: startNode(node); for (var _d = 0, _e = node.members; _d < _e.length; _d++) { var member = _e[_d]; @@ -66959,9 +71768,9 @@ var ts; } endNode(); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: startNode(node); for (var _f = 0, _g = node.members; _f < _g.length; _f++) { var member = _g[_f]; @@ -66969,21 +71778,21 @@ var ts; } endNode(); break; - case 225 /* ModuleDeclaration */: + case 230 /* 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 */: + case 243 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 155 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 228 /* TypeAliasDeclaration */: addLeafNode(node); break; default: - ts.forEach(node.jsDocComments, function (jsDocComment) { - ts.forEach(jsDocComment.tags, function (tag) { - if (tag.kind === 279 /* JSDocTypedefTag */) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 285 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -67034,14 +71843,14 @@ var ts; }); /** 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)); + return a.kind === b.kind && (a.kind !== 230 /* 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; } - if (a.body.kind !== 225 /* ModuleDeclaration */) { + if (a.body.kind !== 230 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); @@ -67076,11 +71885,9 @@ var ts; 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) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.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); @@ -67090,7 +71897,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -67103,7 +71910,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 225 /* ModuleDeclaration */) { + if (node.kind === 230 /* ModuleDeclaration */) { return getModuleName(node); } var decl = node; @@ -67111,18 +71918,18 @@ var ts; return ts.getPropertyNameForPropertyNameNode(decl.name); } switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 197 /* ClassExpression */: return getFunctionOrClassName(node); - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 225 /* ModuleDeclaration */) { + if (node.kind === 230 /* ModuleDeclaration */) { return getModuleName(node); } var name = node.name; @@ -67133,29 +71940,32 @@ var ts; } } switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* 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 */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. return getFunctionOrClassName(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return "constructor"; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: return "new()"; - case 151 /* CallSignature */: + case 153 /* CallSignature */: return "()"; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return "[]"; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -67167,10 +71977,10 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode && parentNode.kind === 205 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { + if (nameIdentifier.kind === 70 /* Identifier */) { return nameIdentifier.text; } } @@ -67196,24 +72006,24 @@ var ts; 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 */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 228 /* TypeAliasDeclaration */: + case 285 /* JSDocTypedefTag */: return true; - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 218 /* VariableDeclaration */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 223 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -67223,10 +72033,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 226 /* ModuleBlock */: - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: + case 231 /* ModuleBlock */: + case 261 /* SourceFile */: + case 149 /* MethodDeclaration */: + case 150 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -67235,13 +72045,22 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + return childKind !== 223 /* VariableDeclaration */ && childKind !== 174 /* BindingElement */; }); } } } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +72084,16 @@ var ts; grayed: false }; } - 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)); - } + } + 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 spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -67284,7 +72103,7 @@ var ts; // 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 */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -67295,13 +72114,13 @@ var ts; * 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; + return decl.body.kind === 230 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + return !member.name || member.name.kind === 142 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ + return node.kind === 261 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); } @@ -67309,14 +72128,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 218 /* VariableDeclaration */) { + else if (node.parent.kind === 223 /* 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 === 192 /* BinaryExpression */ && + node.parent.operatorToken.kind === 57 /* EqualsToken */) { + return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 257 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512 /* Default */) { @@ -67327,8 +72146,22 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */ || node.kind === 197 /* ClassExpression */; } + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -67403,7 +72236,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 185 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -67415,34 +72248,34 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 199 /* Block */: + case 204 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_22 = n.parent; - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + var parent_19 = n.parent; + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. - if (parent_22.kind === 204 /* DoStatement */ || - parent_22.kind === 207 /* ForInStatement */ || - parent_22.kind === 208 /* ForOfStatement */ || - parent_22.kind === 206 /* ForStatement */ || - parent_22.kind === 203 /* IfStatement */ || - parent_22.kind === 205 /* WhileStatement */ || - parent_22.kind === 212 /* WithStatement */ || - parent_22.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + if (parent_19.kind === 209 /* DoStatement */ || + parent_19.kind === 212 /* ForInStatement */ || + parent_19.kind === 213 /* ForOfStatement */ || + parent_19.kind === 211 /* ForStatement */ || + parent_19.kind === 208 /* IfStatement */ || + parent_19.kind === 210 /* WhileStatement */ || + parent_19.kind === 217 /* WithStatement */ || + parent_19.kind === 256 /* CatchClause */) { + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_22.kind === 216 /* TryStatement */) { + if (parent_19.kind === 221 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_22; + var tryStatement = parent_19; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile); if (finallyKeyword) { addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); break; @@ -67461,25 +72294,25 @@ var ts; break; } // Fallthrough. - case 226 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + case 231 /* ModuleBlock */: { + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 227 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 232 /* CaseBlock */: { + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 170 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + case 175 /* ArrayLiteralExpression */: + var openBracket = ts.findChildOfKind(n, 20 /* OpenBracketToken */, sourceFile); + var closeBracket = ts.findChildOfKind(n, 21 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); break; } @@ -67497,13 +72330,13 @@ var ts; var ts; (function (ts) { // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; - })(ts.PatternMatchKind || (ts.PatternMatchKind = {})); - var PatternMatchKind = ts.PatternMatchKind; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { return { kind: kind, @@ -67834,7 +72667,7 @@ var ts; if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -67847,7 +72680,7 @@ var ts; if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -68068,10 +72901,10 @@ var ts; var externalModule = false; function nextToken() { var token = ts.scanner.scan(); - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { braceNesting++; } - else if (token === 16 /* CloseBraceToken */) { + else if (token === 17 /* CloseBraceToken */) { braceNesting--; } return token; @@ -68122,10 +72955,10 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 122 /* DeclareKeyword */) { + if (token === 123 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 125 /* ModuleKeyword */) { + if (token === 127 /* ModuleKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { recordAmbientExternalModule(); @@ -68140,7 +72973,7 @@ var ts; */ function tryConsumeImport() { var token = ts.scanner.getToken(); - if (token === 89 /* ImportKeyword */) { + if (token === 90 /* ImportKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import "mod"; @@ -68148,9 +72981,9 @@ var ts; return true; } else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -68158,12 +72991,12 @@ var ts; return true; } } - else if (token === 56 /* EqualsToken */) { + else if (token === 57 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 24 /* CommaToken */) { + else if (token === 25 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -68172,16 +73005,16 @@ var ts; return true; } } - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 17 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 16 /* CloseBraceToken */) { + if (token === 17 /* CloseBraceToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -68191,13 +73024,13 @@ var ts; } } } - else if (token === 37 /* AsteriskToken */) { + else if (token === 38 /* AsteriskToken */) { token = nextToken(); - if (token === 116 /* AsKeyword */) { + if (token === 117 /* AsKeyword */) { token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -68215,19 +73048,19 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 82 /* ExportKeyword */) { + if (token === 83 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 17 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 16 /* CloseBraceToken */) { + if (token === 17 /* CloseBraceToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -68237,9 +73070,9 @@ var ts; } } } - else if (token === 37 /* AsteriskToken */) { + else if (token === 38 /* AsteriskToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -68247,11 +73080,11 @@ var ts; } } } - else if (token === 89 /* ImportKeyword */) { + else if (token === 90 /* ImportKeyword */) { token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 56 /* EqualsToken */) { + if (token === 57 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -68264,9 +73097,9 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 129 /* RequireKeyword */) { + if (token === 131 /* RequireKeyword */) { token = nextToken(); - if (token === 17 /* OpenParenToken */) { + if (token === 18 /* OpenParenToken */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // require("mod"); @@ -68279,16 +73112,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 69 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 70 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 17 /* OpenParenToken */) { + if (token !== 18 /* OpenParenToken */) { return true; } token = nextToken(); if (token === 9 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 24 /* CommaToken */) { + if (token === 25 /* CommaToken */) { token = nextToken(); } else { @@ -68297,14 +73130,14 @@ var ts; } } // should be start of dependency list - if (token !== 19 /* OpenBracketToken */) { + if (token !== 20 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); var i = 0; // scan until ']' or EOF - while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 21 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names if (token === 9 /* StringLiteral */) { recordModuleName(); @@ -68394,7 +73227,7 @@ var ts; var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || ts.isThis(node)) { @@ -68619,12 +73452,12 @@ var ts; // return null; // } var emptyArray = []; + var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - })(SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); - var ArgumentListKind = SignatureHelp.ArgumentListKind; + })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help @@ -68655,15 +73488,15 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 174 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 179 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. var callExpression = argumentInfo.invocation; var expression = callExpression.expression; - var name = expression.kind === 69 /* Identifier */ + var name = expression.kind === 70 /* Identifier */ ? expression - : expression.kind === 172 /* PropertyAccessExpression */ + : expression.kind === 177 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -68696,7 +73529,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 174 /* CallExpression */ || node.parent.kind === 175 /* NewExpression */) { + if (node.parent.kind === 179 /* CallExpression */ || node.parent.kind === 180 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -68712,8 +73545,8 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give sig help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 25 /* LessThanToken */ || - node.kind === 17 /* OpenParenToken */) { + if (node.kind === 26 /* LessThanToken */ || + node.kind === 18 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); @@ -68750,27 +73583,27 @@ var ts; } return undefined; } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 181 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.kind === 13 /* TemplateHead */ && node.parent.parent.kind === 181 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 197 /* TemplateSpan */ && node.parent.parent.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 202 /* TemplateSpan */ && node.parent.parent.parent.kind === 181 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. - if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { + if (node.kind === 15 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); @@ -68798,7 +73631,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 24 /* CommaToken */) { + if (child.kind !== 25 /* CommaToken */) { argumentIndex++; } } @@ -68817,8 +73650,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 24 /* CommaToken */; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 24 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 25 /* CommaToken */; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 25 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -68848,7 +73681,7 @@ var ts; } function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. - var argumentCount = tagExpression.template.kind === 11 /* NoSubstitutionTemplateLiteral */ + var argumentCount = tagExpression.template.kind === 12 /* NoSubstitutionTemplateLiteral */ ? 1 : tagExpression.template.templateSpans.length + 1; ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); @@ -68886,7 +73719,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 189 /* TemplateExpression */) { + if (template.kind === 194 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -68895,7 +73728,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 256 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 261 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -68955,35 +73788,38 @@ var ts; if (callTargetDisplayParts) { ts.addRange(prefixDisplayParts, callTargetDisplayParts); } + var isVariadic; if (isTypeParameterList) { - prefixDisplayParts.push(ts.punctuationPart(25 /* LessThanToken */)); + isVariadic = false; // type parameter lists are not variadic + prefixDisplayParts.push(ts.punctuationPart(26 /* LessThanToken */)); var typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(27 /* GreaterThanToken */)); + suffixDisplayParts.push(ts.punctuationPart(28 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); }); ts.addRange(suffixDisplayParts, parameterParts); } else { + isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); }); ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + prefixDisplayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); var parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + suffixDisplayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); }); ts.addRange(suffixDisplayParts, returnTypeParts); return { - isVariadic: candidateSignature.hasRestParameter, + isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(24 /* CommaToken */), ts.spacePart()], + separatorDisplayParts: [ts.punctuationPart(25 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, documentation: candidateSignature.getDocumentationComment() }; @@ -69037,7 +73873,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */) ? ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ts.ScriptElementKind.enumElement; @@ -69068,7 +73904,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return ts.ScriptElementKind.localVariableElement; } - if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 98 /* ThisKeyword */ && ts.isExpression(location)) { return ts.ScriptElementKind.parameterElement; } if (flags & 3 /* Variable */) { @@ -69132,7 +73968,7 @@ var ts; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 98 /* ThisKeyword */ && ts.isExpression(location); var type; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { @@ -69143,7 +73979,7 @@ var ts; var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 177 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -69152,7 +73988,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression = void 0; - if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { + if (location.kind === 179 /* CallExpression */ || location.kind === 180 /* NewExpression */) { callExpression = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -69165,7 +74001,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 180 /* NewExpression */ || callExpression.expression.kind === 96 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -69183,7 +74019,7 @@ var ts; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -69199,13 +74035,13 @@ var ts; case ts.ScriptElementKind.parameterElement: case ts.ScriptElementKind.localVariableElement: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.punctuationPart(55 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); @@ -69218,24 +74054,24 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { + (location.kind === 122 /* ConstructorKeyword */ && location.parent.kind === 150 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration.kind === 150 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 148 /* Constructor */) { + if (functionDeclaration.kind === 150 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ts.ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 153 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -69244,7 +74080,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -69252,7 +74088,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(74 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -69260,77 +74096,77 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(108 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(136 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(75 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(82 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 230 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 70 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 128 /* NamespaceKeyword */ : 127 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90 /* InKeyword */)); - displayParts.push(ts.spacePart()); if (symbol.parent) { // Class/Interface type parameter + addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { // Method/function type parameter - var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); + var declaration = ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */); ts.Debug.assert(declaration !== undefined); declaration = declaration.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + if (declaration.kind === 154 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 153 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else { + else if (declaration.kind === 228 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + addInPrefix(); + displayParts.push(ts.keywordPart(136 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -69341,11 +74177,11 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 255 /* EnumMember */) { + if (declaration.kind === 260 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); } @@ -69353,33 +74189,33 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); + if (symbol.declarations[0].kind === 233 /* NamespaceExportDeclaration */) { + displayParts.push(ts.keywordPart(83 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(128 /* NamespaceKeyword */)); } else { - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(90 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229 /* ImportEqualsDeclaration */) { + if (declaration.kind === 234 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(131 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -69393,7 +74229,7 @@ var ts; if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(98 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -69403,7 +74239,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === ts.ScriptElementKind.localVariableElement || isThisExpression) { - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.punctuationPart(55 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -69437,10 +74273,10 @@ var ts; // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 192 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -69461,6 +74297,11 @@ var ts; displayParts.push(ts.lineBreakPart()); } } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(91 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } function addFullSymbolName(symbol, enclosingDeclaration) { var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); @@ -69483,9 +74324,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); return; } } @@ -69493,12 +74334,12 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(35 /* PlusToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(36 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } documentation = signature.getDocumentationComment(); } @@ -69516,16 +74357,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 179 /* FunctionExpression */) { + if (declaration.kind === 184 /* FunctionExpression */) { return true; } - if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { + if (declaration.kind !== 223 /* VariableDeclaration */ && declaration.kind !== 225 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + for (var parent_20 = declaration.parent; !ts.isFunctionBlock(parent_20); parent_20 = parent_20.parent) { // Reached source file or module block - if (parent_23.kind === 256 /* SourceFile */ || parent_23.kind === 226 /* ModuleBlock */) { + if (parent_20.kind === 261 /* SourceFile */ || parent_20.kind === 231 /* ModuleBlock */) { return false; } } @@ -69586,8 +74427,8 @@ var ts; var sourceMapText; // Create a compilerHost object to allow the compiler to read and write files var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); sourceMapText = text; @@ -69603,9 +74444,9 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -69636,7 +74477,7 @@ var ts; return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_2 = function (opt) { + var _loop_3 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -69655,7 +74496,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_2(opt); + _loop_3(opt); } return options; } @@ -69667,8 +74508,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); - var jsxScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); /** * Scanner that is currently used for formatting */ @@ -69683,7 +74524,7 @@ var ts; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { - ts.Debug.assert(scanner === undefined); + ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; scanner.setText(sourceFile.text); scanner.setTextPos(startPos); @@ -69708,7 +74549,7 @@ var ts; } }; function advance() { - ts.Debug.assert(scanner !== undefined); + ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { @@ -69750,11 +74591,11 @@ var ts; function shouldRescanGreaterThanToken(node) { if (node) { switch (node.kind) { - case 29 /* GreaterThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 44 /* GreaterThanGreaterThanToken */: + case 30 /* GreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanToken */: return true; } } @@ -69763,27 +74604,27 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 246 /* JsxAttribute */: - case 243 /* JsxOpeningElement */: - case 245 /* JsxClosingElement */: - case 242 /* JsxSelfClosingElement */: - return node.kind === 69 /* Identifier */; + case 250 /* JsxAttribute */: + case 248 /* JsxOpeningElement */: + case 249 /* JsxClosingElement */: + case 247 /* JsxSelfClosingElement */: + return node.kind === 70 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 244 /* JsxText */; + return node && node.kind === 10 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 10 /* RegularExpressionLiteral */; + return container.kind === 11 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 13 /* TemplateMiddle */ || - container.kind === 14 /* TemplateTail */; + return container.kind === 14 /* TemplateMiddle */ || + container.kind === 15 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 39 /* SlashToken */ || t === 61 /* SlashEqualsToken */; + return t === 40 /* SlashToken */ || t === 62 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(scanner !== undefined); @@ -69824,7 +74665,7 @@ var ts; scanner.scan(); } var currentToken = scanner.getToken(); - if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 27 /* GreaterThanToken */) { + if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 28 /* GreaterThanToken */) { currentToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 1 /* RescanGreaterThanToken */; @@ -69834,11 +74675,11 @@ var ts; ts.Debug.assert(n.kind === currentToken); lastScanAction = 2 /* RescanSlashToken */; } - else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 16 /* CloseBraceToken */) { + else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 17 /* CloseBraceToken */) { currentToken = scanner.reScanTemplateToken(); lastScanAction = 3 /* RescanTemplateToken */; } - else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 69 /* Identifier */) { + else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 70 /* Identifier */) { currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } @@ -69981,8 +74822,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 15 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 16 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 16 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 17 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -70001,14 +74842,14 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var FormattingRequestKind; (function (FormattingRequestKind) { FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; - })(formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - var FormattingRequestKind = formatting.FormattingRequestKind; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70040,13 +74881,13 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; RuleAction[RuleAction["Space"] = 2] = "Space"; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; - })(formatting.RuleAction || (formatting.RuleAction = {})); - var RuleAction = formatting.RuleAction; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70087,11 +74928,11 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; - })(formatting.RuleFlags || (formatting.RuleFlags = {})); - var RuleFlags = formatting.RuleFlags; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70130,7 +74971,7 @@ var ts; function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i - 0] = arguments[_i]; + funcs[_i] = arguments[_i]; } this.customContextChecks = funcs; } @@ -70170,125 +75011,125 @@ var ts; this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 3 /* MultiLineCommentTrivia */, 73 /* ClassKeyword */, 82 /* ExportKeyword */, 89 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([70 /* Identifier */, 3 /* MultiLineCommentTrivia */, 74 /* ClassKeyword */, 83 /* ExportKeyword */, 90 /* ImportKeyword */]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a control flow construct - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 79 /* DoKeyword */, 100 /* TryKeyword */, 85 /* FinallyKeyword */, 80 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 80 /* DoKeyword */, 101 /* TryKeyword */, 86 /* FinallyKeyword */, 81 /* ElseKeyword */]); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* OpenBraceToken */, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // For functions and control block place } on a new line [multi-line rule] - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 42 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 43 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* PlusPlusToken */, 36 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* PlusToken */, 36 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* PlusToken */, 42 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(43 /* MinusMinusToken */, 37 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* MinusToken */, 37 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* MinusToken */, 43 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([103 /* VarKeyword */, 99 /* ThrowKeyword */, 93 /* NewKeyword */, 79 /* DeleteKeyword */, 95 /* ReturnKeyword */, 102 /* TypeOfKeyword */, 120 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([109 /* LetKeyword */, 75 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); + this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(88 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(104 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(95 /* ReturnKeyword */, 24 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 80 /* DoKeyword */, 81 /* ElseKeyword */, 72 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([101 /* TryKeyword */, 86 /* FinallyKeyword */]), 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 131 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124 /* GetKeyword */, 133 /* SetKeyword */]), 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); // TypeScript-specific higher priority rules // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122 /* ConstructorKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 129 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([127 /* ModuleKeyword */, 131 /* RequireKeyword */]), 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 131 /* SetKeyword */, 113 /* StaticKeyword */, 134 /* TypeKeyword */, 136 /* FromKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */, 136 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 74 /* ClassKeyword */, 123 /* DeclareKeyword */, 78 /* DefaultKeyword */, 82 /* EnumKeyword */, 83 /* ExportKeyword */, 84 /* ExtendsKeyword */, 124 /* GetKeyword */, 107 /* ImplementsKeyword */, 90 /* ImportKeyword */, 108 /* InterfaceKeyword */, 127 /* ModuleKeyword */, 128 /* NamespaceKeyword */, 111 /* PrivateKeyword */, 113 /* PublicKeyword */, 112 /* ProtectedKeyword */, 133 /* SetKeyword */, 114 /* StaticKeyword */, 136 /* TypeKeyword */, 138 /* FromKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84 /* ExtendsKeyword */, 107 /* ImplementsKeyword */, 138 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); + this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 35 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(35 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(23 /* DotDotDotToken */, 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 25 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 26 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* CloseParenToken */, 26 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 28 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([18 /* OpenParenToken */, 20 /* OpenBracketToken */, 28 /* GreaterThanToken */, 25 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* OpenBraceToken */, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 131 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 70 /* Identifier */, 83 /* ExportKeyword */, 78 /* DefaultKeyword */, 74 /* ClassKeyword */, 114 /* StaticKeyword */, 113 /* PublicKeyword */, 111 /* PrivateKeyword */, 112 /* ProtectedKeyword */, 124 /* GetKeyword */, 133 /* SetKeyword */, 20 /* OpenBracketToken */, 38 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(38 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(115 /* YieldKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* YieldKeyword */, 38 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(119 /* AsyncKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(119 /* AsyncKeyword */, 88 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(70 /* Identifier */, formatting.Shared.TokenRange.FromTokens([12 /* NoSubstitutionTemplateLiteral */, 13 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 40 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(40 /* SlashToken */, 28 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(57 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -70350,60 +75191,60 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); // Insert space after keywords in control flow statements - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after TypeScript module/class/interface - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after control block - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* OpenParenToken */, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(20 /* OpenBracketToken */, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing template string braces - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13 /* TemplateHead */, 14 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13 /* TemplateHead */, 14 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14 /* TemplateMiddle */, 15 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14 /* TemplateMiddle */, 15 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); // No space after type assertion - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_51 in o) { - if (o[name_51] === rule) { - return name_51; + for (var name_49 in o) { + if (o[name_49] === rule) { + return name_49; } } throw new Error("Unknown rule"); @@ -70412,42 +75253,42 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 206 /* ForStatement */; + return context.contextNode.kind === 211 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 187 /* BinaryExpression */: - case 188 /* ConditionalExpression */: - case 195 /* AsExpression */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 154 /* TypePredicate */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 192 /* BinaryExpression */: + case 193 /* ConditionalExpression */: + case 200 /* AsExpression */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 156 /* TypePredicate */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 169 /* BindingElement */: + case 174 /* BindingElement */: // equals in type X = ... - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: // equal in p = 0; - case 142 /* Parameter */: - case 255 /* EnumMember */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; + case 144 /* Parameter */: + case 260 /* EnumMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + return context.currentTokenSpan.kind === 57 /* EqualsToken */ || context.nextTokenSpan.kind === 57 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 207 /* ForInStatement */: - return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; + case 212 /* ForInStatement */: + return context.currentTokenSpan.kind === 91 /* InKeyword */ || context.nextTokenSpan.kind === 91 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 208 /* ForOfStatement */: - return context.currentTokenSpan.kind === 138 /* OfKeyword */ || context.nextTokenSpan.kind === 138 /* OfKeyword */; + case 213 /* ForOfStatement */: + return context.currentTokenSpan.kind === 140 /* OfKeyword */ || context.nextTokenSpan.kind === 140 /* OfKeyword */; } return false; }; @@ -70455,7 +75296,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 188 /* ConditionalExpression */; + return context.contextNode.kind === 193 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -70499,127 +75340,127 @@ var ts; return true; } switch (node.kind) { - case 199 /* Block */: - case 227 /* CaseBlock */: - case 171 /* ObjectLiteralExpression */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 176 /* ObjectLiteralExpression */: + case 231 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 151 /* CallSignature */: - case 179 /* FunctionExpression */: - case 148 /* Constructor */: - case 180 /* ArrowFunction */: + case 153 /* CallSignature */: + case 184 /* FunctionExpression */: + case 150 /* Constructor */: + case 185 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 220 /* FunctionDeclaration */ || context.contextNode.kind === 179 /* FunctionExpression */; + return context.contextNode.kind === 225 /* FunctionDeclaration */ || context.contextNode.kind === 184 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 159 /* TypeLiteral */: - case 225 /* ModuleDeclaration */: - case 236 /* ExportDeclaration */: - case 237 /* NamedExports */: - case 230 /* ImportDeclaration */: - case 233 /* NamedImports */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 161 /* TypeLiteral */: + case 230 /* ModuleDeclaration */: + case 241 /* ExportDeclaration */: + case 242 /* NamedExports */: + case 235 /* ImportDeclaration */: + case 238 /* NamedImports */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 221 /* ClassDeclaration */: - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - case 199 /* Block */: - case 252 /* CatchClause */: - case 226 /* ModuleBlock */: - case 213 /* SwitchStatement */: + case 226 /* ClassDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: + case 204 /* Block */: + case 256 /* CatchClause */: + case 231 /* ModuleBlock */: + case 218 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 203 /* IfStatement */: - case 213 /* SwitchStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - case 216 /* TryStatement */: - case 204 /* DoStatement */: - case 212 /* WithStatement */: + case 208 /* IfStatement */: + case 218 /* SwitchStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 210 /* WhileStatement */: + case 221 /* TryStatement */: + case 209 /* DoStatement */: + case 217 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 252 /* CatchClause */: + case 256 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 171 /* ObjectLiteralExpression */; + return context.contextNode.kind === 176 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 174 /* CallExpression */; + return context.contextNode.kind === 179 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 175 /* NewExpression */; + return context.contextNode.kind === 180 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); }; Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 24 /* CommaToken */; + return context.currentTokenSpan.kind !== 25 /* CommaToken */; }; Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 21 /* CloseBracketToken */; }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 180 /* ArrowFunction */; + return context.contextNode.kind === 185 /* ArrowFunction */; }; Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; }; Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 241 /* JsxElement */; + return context.contextNode.kind !== 246 /* JsxElement */; }; Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 248 /* JsxExpression */; + return context.contextNode.kind === 252 /* JsxExpression */; }; Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246 /* JsxAttribute */; + return context.nextTokenParent.kind === 250 /* JsxAttribute */; }; Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246 /* JsxAttribute */; + return context.contextNode.kind === 250 /* JsxAttribute */; }; Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242 /* JsxSelfClosingElement */; + return context.contextNode.kind === 247 /* JsxSelfClosingElement */; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -70634,41 +75475,41 @@ var ts; while (ts.isPartOfExpression(node)) { node = node.parent; } - return node.kind === 143 /* Decorator */; + return node.kind === 145 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 219 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 224 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 225 /* ModuleDeclaration */; + return context.contextNode.kind === 230 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 159 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 161 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 25 /* LessThanToken */ && token.kind !== 27 /* GreaterThanToken */) { + if (token.kind !== 26 /* LessThanToken */ && token.kind !== 28 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 155 /* TypeReference */: - case 177 /* TypeAssertionExpression */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 194 /* ExpressionWithTypeArguments */: + case 157 /* TypeReference */: + case 182 /* TypeAssertionExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 199 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -70679,13 +75520,13 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 177 /* TypeAssertionExpression */; + return context.contextNode.kind === 182 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 183 /* VoidExpression */; + return context.currentTokenSpan.kind === 104 /* VoidKeyword */ && context.currentTokenParent.kind === 188 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 190 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 195 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; }()); @@ -70709,7 +75550,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 138 /* LastToken */ + 1; + this.mapRowLength = 140 /* LastToken */ + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); @@ -70723,8 +75564,8 @@ var ts; }); }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + ts.Debug.assert(row <= 140 /* LastKeyword */ && column <= 140 /* LastKeyword */, "Must compute formatting context from tokens"); var rulesBucketIndex = (row * this.mapRowLength) + column; - // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { @@ -70760,6 +75601,7 @@ var ts; formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; + var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; @@ -70767,8 +75609,7 @@ var ts; RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesPosition = formatting.RulesPosition; + })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); var RulesBucketConstructionState = (function () { function RulesBucketConstructionState() { //// The Rules list contains all the inserted rules into a rulebucket in the following order: @@ -70904,12 +75745,12 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 138 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 140 /* LastToken */; token++) { result.push(token); } return result; }; - TokenAllAccess.prototype.Contains = function (tokenValue) { + TokenAllAccess.prototype.Contains = function () { return true; }; TokenAllAccess.prototype.toString = function () { @@ -70948,17 +75789,17 @@ var ts; }()); TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.Keywords = TokenRange.FromRange(71 /* FirstKeyword */, 140 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(26 /* FirstBinaryOperator */, 69 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91 /* InKeyword */, 92 /* InstanceOfKeyword */, 140 /* OfKeyword */, 117 /* AsKeyword */, 125 /* IsKeyword */]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([42 /* PlusPlusToken */, 43 /* MinusMinusToken */, 51 /* TildeToken */, 50 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 70 /* Identifier */, 18 /* OpenParenToken */, 20 /* OpenBracketToken */, 16 /* OpenBraceToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 19 /* CloseParenToken */, 21 /* CloseBracketToken */, 93 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 19 /* CloseParenToken */, 21 /* CloseBracketToken */, 93 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([70 /* Identifier */, 132 /* NumberKeyword */, 134 /* StringKeyword */, 121 /* BooleanKeyword */, 135 /* SymbolKeyword */, 104 /* VoidKeyword */, 118 /* AnyKeyword */]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -71005,25 +75846,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +75874,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +75886,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +75896,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +75904,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +75912,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +75926,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71149,11 +75990,11 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 23 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + return formatOutermostParent(position, 24 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 16 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); + return formatOutermostParent(position, 17 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -71217,17 +76058,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 256 /* SourceFile */: - case 199 /* Block */: - case 226 /* ModuleBlock */: + return body && body.kind === 231 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 261 /* SourceFile */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -71282,7 +76123,7 @@ var ts; index++; } }; - function rangeHasNoErrors(r) { + function rangeHasNoErrors() { return false; } } @@ -71332,7 +76173,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +76245,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +76253,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71432,20 +76273,20 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 221 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 222 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 220 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 224 /* EnumDeclaration */: return 224 /* EnumDeclaration */; - case 149 /* GetAccessor */: return 123 /* GetKeyword */; - case 150 /* SetAccessor */: return 131 /* SetKeyword */; - case 147 /* MethodDeclaration */: + case 226 /* ClassDeclaration */: return 74 /* ClassKeyword */; + case 227 /* InterfaceDeclaration */: return 108 /* InterfaceKeyword */; + case 225 /* FunctionDeclaration */: return 88 /* FunctionKeyword */; + case 229 /* EnumDeclaration */: return 229 /* EnumDeclaration */; + case 151 /* GetAccessor */: return 124 /* GetKeyword */; + case 152 /* SetAccessor */: return 133 /* SetKeyword */; + case 149 /* MethodDeclaration */: if (node.asteriskToken) { - return 37 /* AsteriskToken */; + return 38 /* AsteriskToken */; } /* fall-through */ - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 144 /* Parameter */: return node.name.kind; } } @@ -71457,9 +76298,9 @@ var ts; // .. { // // comment // } - case 16 /* CloseBraceToken */: - case 20 /* CloseBracketToken */: - case 18 /* CloseParenToken */: + case 17 /* CloseBraceToken */: + case 21 /* CloseBracketToken */: + case 19 /* CloseParenToken */: return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; @@ -71473,15 +76314,15 @@ var ts; } switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 15 /* OpenBraceToken */: - case 16 /* CloseBraceToken */: - case 19 /* OpenBracketToken */: - case 20 /* CloseBracketToken */: - case 17 /* OpenParenToken */: - case 18 /* CloseParenToken */: - case 80 /* ElseKeyword */: - case 104 /* WhileKeyword */: - case 55 /* AtToken */: + case 16 /* OpenBraceToken */: + case 17 /* CloseBraceToken */: + case 20 /* OpenBracketToken */: + case 21 /* CloseBracketToken */: + case 18 /* OpenParenToken */: + case 19 /* CloseParenToken */: + case 81 /* ElseKeyword */: + case 105 /* WhileKeyword */: + case 56 /* AtToken */: return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation @@ -71493,13 +76334,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71581,18 +76422,19 @@ var ts; if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (ts.isToken(child)) { + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); - ts.Debug.assert(tokenInfo.token.end === child.end); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 143 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 145 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent.kind === 170 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 175 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -71790,11 +76632,23 @@ var ts; else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); - if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } } } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } @@ -71919,7 +76773,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71937,41 +76791,41 @@ var ts; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 148 /* Constructor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 180 /* ArrowFunction */: + case 150 /* Constructor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 185 /* ArrowFunction */: if (node.typeParameters === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } else if (node.parameters === list) { - return 17 /* OpenParenToken */; + return 18 /* OpenParenToken */; } break; - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: if (node.typeArguments === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } else if (node.arguments === list) { - return 17 /* OpenParenToken */; + return 18 /* OpenParenToken */; } break; - case 155 /* TypeReference */: + case 157 /* TypeReference */: if (node.typeArguments === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 17 /* OpenParenToken */: - return 18 /* CloseParenToken */; - case 25 /* LessThanToken */: - return 27 /* GreaterThanToken */; + case 18 /* OpenParenToken */: + return 19 /* CloseParenToken */; + case 26 /* LessThanToken */: + return 28 /* GreaterThanToken */; } return 0 /* Unknown */; } @@ -71980,14 +76834,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +76856,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +76899,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +76915,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72075,7 +76929,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 187 /* BinaryExpression */) { + if (precedingToken.kind === 25 /* CommaToken */ && precedingToken.parent.kind !== 192 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -72095,7 +76949,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +76960,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +76972,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +77015,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72198,7 +77052,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 256 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 261 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -72209,11 +77063,11 @@ var ts; if (!nextToken) { return false; } - if (nextToken.kind === 15 /* OpenBraceToken */) { + if (nextToken.kind === 16 /* OpenBraceToken */) { // open braces are always indented at the parent level return true; } - else if (nextToken.kind === 16 /* CloseBraceToken */) { + else if (nextToken.kind === 17 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -72231,8 +77085,8 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 203 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); + if (parent.kind === 208 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 81 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -72243,23 +77097,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 155 /* TypeReference */: + case 157 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return node.parent.properties; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return node.parent.elements; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: { + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -72270,8 +77124,8 @@ var ts; } break; } - case 175 /* NewExpression */: - case 174 /* CallExpression */: { + case 180 /* NewExpression */: + case 179 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -72298,11 +77152,11 @@ var ts; function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: // - node is close parenthesis - this is the end of the expression - if (node.kind === 18 /* CloseParenToken */) { + if (node.kind === 19 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 174 /* CallExpression */ || - node.parent.kind === 175 /* NewExpression */) && + if (node.parent && (node.parent.kind === 179 /* CallExpression */ || + node.parent.kind === 180 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -72320,10 +77174,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: node = node.expression; break; default: @@ -72339,7 +77193,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 24 /* CommaToken */) { + if (list[i].kind === 25 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -72371,7 +77225,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72387,48 +77241,48 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202 /* ExpressionStatement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 170 /* ArrayLiteralExpression */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 171 /* ObjectLiteralExpression */: - case 159 /* TypeLiteral */: - case 161 /* TupleType */: - case 227 /* CaseBlock */: - case 250 /* DefaultClause */: - case 249 /* CaseClause */: - case 178 /* ParenthesizedExpression */: - case 172 /* PropertyAccessExpression */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 200 /* VariableStatement */: - case 218 /* VariableDeclaration */: - case 235 /* ExportAssignment */: - case 211 /* ReturnStatement */: - case 188 /* ConditionalExpression */: - case 168 /* ArrayBindingPattern */: - case 167 /* ObjectBindingPattern */: - case 243 /* JsxOpeningElement */: - case 242 /* JsxSelfClosingElement */: - case 248 /* JsxExpression */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 142 /* Parameter */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 164 /* ParenthesizedType */: - case 176 /* TaggedTemplateExpression */: - case 184 /* AwaitExpression */: - case 237 /* NamedExports */: - case 233 /* NamedImports */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: + case 207 /* ExpressionStatement */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 175 /* ArrayLiteralExpression */: + case 204 /* Block */: + case 231 /* ModuleBlock */: + case 176 /* ObjectLiteralExpression */: + case 161 /* TypeLiteral */: + case 163 /* TupleType */: + case 232 /* CaseBlock */: + case 254 /* DefaultClause */: + case 253 /* CaseClause */: + case 183 /* ParenthesizedExpression */: + case 177 /* PropertyAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 205 /* VariableStatement */: + case 223 /* VariableDeclaration */: + case 240 /* ExportAssignment */: + case 216 /* ReturnStatement */: + case 193 /* ConditionalExpression */: + case 173 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 248 /* JsxOpeningElement */: + case 247 /* JsxSelfClosingElement */: + case 252 /* JsxExpression */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 144 /* Parameter */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 166 /* ParenthesizedType */: + case 181 /* TaggedTemplateExpression */: + case 189 /* AwaitExpression */: + case 242 /* NamedExports */: + case 238 /* NamedImports */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: return true; } return false; @@ -72437,27 +77291,27 @@ var ts; function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 203 /* IfStatement */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 180 /* ArrowFunction */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return childKind !== 199 /* Block */; - case 236 /* ExportDeclaration */: - return childKind !== 237 /* NamedExports */; - case 230 /* ImportDeclaration */: - return childKind !== 231 /* ImportClause */ || - (child.namedBindings && child.namedBindings.kind !== 233 /* NamedImports */); - case 241 /* JsxElement */: - return childKind !== 245 /* JsxClosingElement */; + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 211 /* ForStatement */: + case 208 /* IfStatement */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 185 /* ArrowFunction */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return childKind !== 204 /* Block */; + case 241 /* ExportDeclaration */: + return childKind !== 242 /* NamedExports */; + case 235 /* ImportDeclaration */: + return childKind !== 236 /* ImportClause */ || + (child.namedBindings && child.namedBindings.kind !== 238 /* NamedImports */); + case 246 /* JsxElement */: + return childKind !== 249 /* JsxClosingElement */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -72473,6 +77327,776 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 122 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 98 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 179 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var ModuleSpecifierComparison; + (function (ModuleSpecifierComparison) { + ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; + })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); + var ImportCodeActionMap = (function () { + function ImportCodeActionMap() { + this.symbolIdToActionMap = ts.createMap(); + } + ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { + if (!newAction) { + return; + } + if (!this.symbolIdToActionMap[symbolId]) { + this.symbolIdToActionMap[symbolId] = [newAction]; + return; + } + if (newAction.kind === "CodeChange") { + this.symbolIdToActionMap[symbolId].push(newAction); + return; + } + var updatedNewImports = []; + for (var _i = 0, _a = this.symbolIdToActionMap[symbolId]; _i < _a.length; _i++) { + var existingAction = _a[_i]; + if (existingAction.kind === "CodeChange") { + // only import actions should compare + updatedNewImports.push(existingAction); + continue; + } + switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { + case ModuleSpecifierComparison.Better: + // the new one is not worth considering if it is a new improt. + // However if it is instead a insertion into existing import, the user might want to use + // the module specifier even it is worse by our standards. So keep it. + if (newAction.kind === "NewImport") { + return; + } + case ModuleSpecifierComparison.Equal: + // the current one is safe. But it is still possible that the new one is worse + // than another existing one. For example, you may have new imports from "./foo/bar" + // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new + // one and the current one are not comparable (one relative path and one absolute path), + // but the new one is worse than the other one, so should not add to the list. + updatedNewImports.push(existingAction); + break; + case ModuleSpecifierComparison.Worse: + // the existing one is worse, remove from the list. + continue; + } + } + // if we reach here, it means the new one is better or equal to all of the existing ones. + updatedNewImports.push(newAction); + this.symbolIdToActionMap[symbolId] = updatedNewImports; + }; + ImportCodeActionMap.prototype.addActions = function (symbolId, newActions) { + for (var _i = 0, newActions_1 = newActions; _i < newActions_1.length; _i++) { + var newAction = newActions_1[_i]; + this.addAction(symbolId, newAction); + } + }; + ImportCodeActionMap.prototype.getAllActions = function () { + var result = []; + for (var symbolId in this.symbolIdToActionMap) { + result = ts.concatenate(result, this.symbolIdToActionMap[symbolId]); + } + return result; + }; + ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { + if (moduleSpecifier1 === moduleSpecifier2) { + return ModuleSpecifierComparison.Equal; + } + // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better + if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { + return ModuleSpecifierComparison.Better; + } + if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { + return ModuleSpecifierComparison.Worse; + } + // if both are relative paths, and ms1 has fewer levels, then it is better + if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { + var regex = new RegExp(ts.directorySeparator, "g"); + var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; + var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; + return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Better + : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Equal + : ModuleSpecifierComparison.Worse; + } + // the equal cases include when the two specifiers are not comparable. + return ModuleSpecifierComparison.Equal; + }; + return ImportCodeActionMap; + }()); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = ts.createMap(); + var cachedNewImportInsertPosition; + var allPotentialModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + allPotentialModules.push(otherSourceFile.symbol); + } + } + var currentTokenMeaning = ts.getMeaningFromLocation(token); + for (var _a = 0, allPotentialModules_1 = allPotentialModules; _a < allPotentialModules_1.length; _a++) { + var moduleSymbol = allPotentialModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + if (cachedImportDeclarations[moduleSymbolId]) { + return cachedImportDeclarations[moduleSymbolId]; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 235 /* ImportDeclaration */) { + return node; + } + if (node.kind === 234 /* ImportEqualsDeclaration */) { + return node; + } + node = node.parent; + } + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (declaration.kind === 235 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 237 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; + } + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; + } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + } + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + if (namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var textChange = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], textChange.newText, textChange.span, sourceFile.fileName, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + } + else { + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 245 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); + } + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var newImportText = isDefault ? "default as " + name : name; + var importList = importClause.namedBindings; + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + if (!importList && importClause.name) { + var start = importClause.name.getEnd(); + return { + newText: ", { " + newImportText + " }", + span: { start: start, length: 0 } + }; + } + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (importList.elements.length === 0) { + var start = importList.getStart(); + return { + newText: "{ " + newImportText + " }", + span: { start: start, length: importList.getEnd() - start } + }; + } + // case 3: + // original text: import { foo, bar } from "module" + // change to: import { foo, bar, name } from "module" + var insertPoint = importList.elements[importList.elements.length - 1].getEnd(); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + var startLine = ts.getLineOfLocalPosition(sourceFile, importList.getStart()); + var endLine = ts.getLineOfLocalPosition(sourceFile, importList.getEnd()); + var oneImportPerLine = endLine - startLine > importList.elements.length; + return { + newText: "," + (oneImportPerLine ? context.newLineCharacter : " ") + newImportText, + span: { start: insertPoint, length: 0 } + }; + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 235 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); + } + else { + namespacePrefix = declaration.name.getText(); + } + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], namespacePrefix + ".", { start: token.getStart(), length: 0 }, sourceFile.fileName, "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!cachedNewImportInsertPosition) { + // insert after any existing imports + var lastModuleSpecifierEnd = -1; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier_1 = _a[_i]; + var end = moduleSpecifier_1.getEnd(); + if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) { + lastModuleSpecifierEnd = end; + } + } + cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart(); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var importStatementText = isDefault + ? "import " + name + " from \"" + moduleSpecifierWithoutQuotes + "\"" + : "import { " + name + " } from \"" + moduleSpecifierWithoutQuotes + "\""; + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + var newText = cachedNewImportInsertPosition === sourceFile.getStart() + ? importStatementText + ";" + context.newLineCharacter + context.newLineCharacter + : "" + context.newLineCharacter + importStatementText + ";"; + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], newText, { start: cachedNewImportInsertPosition, length: 0 }, sourceFile.fileName, "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.path; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 261 /* SourceFile */) { + return moduleSymbol.name; + } + } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { + return undefined; + } + var normalizedBaseUrl = ts.toPath(options.baseUrl, ts.getDirectoryPath(options.baseUrl), getCanonicalFileName); + var relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl); + if (!relativeName) { + return undefined; + } + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName) { + return key; + } + } + } + } + return relativeName; + } + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedRootDirs = ts.map(options.rootDirs, function (rootDir) { return ts.toPath(rootDir, /*basePath*/ undefined, getCanonicalFileName); }); + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + } + return undefined; + } + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } + } + } + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; + } + } + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = tryRemoveParentDirectoryName(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } + function tryRemoveParentDirectoryName(path, parentDirectory) { + var index = path.indexOf(parentDirectory); + if (index === 0) { + return ts.endsWith(parentDirectory, ts.directorySeparator) + ? path.substring(parentDirectory.length) + : path.substring(parentDirectory.length + 1); + } + return undefined; + } + } + } + function createCodeAction(description, diagnosticArgs, newText, span, fileName, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: [{ fileName: fileName, textChanges: [{ newText: newText, span: span }] }], + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_never_used.code + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start); + // this handles var ["computed"] = 12; + if (token.kind === 20 /* OpenBracketToken */) { + token = ts.getTokenAtPosition(sourceFile, start + 1); + } + switch (token.kind) { + case 70 /* Identifier */: + switch (token.parent.kind) { + case 223 /* VariableDeclaration */: + switch (token.parent.parent.parent.kind) { + case 211 /* ForStatement */: + var forStatement = token.parent.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos); + } + else { + return removeSingleItem(forInitializer.declarations, token); + } + case 213 /* ForOfStatement */: + var forOfStatement = token.parent.parent.parent; + if (forOfStatement.initializer.kind === 224 /* VariableDeclarationList */) { + var forOfInitializer = forOfStatement.initializer; + return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos); + } + break; + case 212 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + case 256 /* CatchClause */: + var catchClause = token.parent.parent; + var parameter = catchClause.variableDeclaration.getChildren()[0]; + return createCodeFix("", parameter.pos, parameter.end - parameter.pos); + default: + var variableStatement = token.parent.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos); + } + else { + var declarations = variableStatement.declarationList.declarations; + return removeSingleItem(declarations, token); + } + } + case 143 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2); + } + else { + return removeSingleItem(typeParameters, token); + } + case 144 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else { + return removeSingleItem(functionDeclaration.parameters, token); + } + // handle case where 'import a = A;' + case 234 /* ImportEqualsDeclaration */: + var importEquals = findImportDeclaration(token); + return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos); + case 239 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = findImportDeclaration(token); + return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos); + } + else { + return removeSingleItem(namedImports.elements, token); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 236 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = findImportDeclaration(importClause); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos); + } + case 237 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name == token && !namespaceImport.parent.name) { + var importDecl = findImportDeclaration(namespaceImport); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + var start_4 = namespaceImport.parent.name.end; + return createCodeFix("", start_4, namespaceImport.parent.namedBindings.end - start_4); + } + } + break; + case 147 /* PropertyDeclaration */: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + case 237 /* NamespaceImport */: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + if (ts.isDeclarationName(token)) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos); + } + else { + return undefined; + } + function findImportDeclaration(token) { + var importDecl = token; + while (importDecl.kind != 235 /* ImportDeclaration */ && importDecl.parent) { + importDecl = importDecl.parent; + } + return importDecl; + } + function createCodeFix(newText, start, length) { + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_unused_identifiers), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ newText: newText, span: { start: start, length: length } }] + }] + }]; + } + function removeSingleItem(elements, token) { + if (elements[0] === token.parent) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1); + } + else { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1); + } + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// +/// +/// /// /// /// @@ -72498,13 +78122,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { - var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + var node = kind >= 141 /* FirstNode */ ? new NodeObject(kind, pos, end) : + kind === 70 /* Identifier */ ? new IdentifierObject(70 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72515,7 +78141,6 @@ var ts; this.end = end; this.flags = 0 /* None */; this.transformFlags = undefined; - this.excludeTransformFlags = undefined; this.parent = undefined; this.kind = kind; } @@ -72562,11 +78187,11 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(292 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -72581,11 +78206,11 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 139 /* FirstNode */) { + if (this.kind >= 141 /* FirstNode */) { ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 278 /* FirstJSDocTagNode */ && this.kind <= 291 /* LastJSDocTagNode */; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { @@ -72604,8 +78229,8 @@ var ts; pos_3 = nodes.end; }; // jsDocComments need to be the first children - if (this.jsDocComments) { - for (var _i = 0, _a = this.jsDocComments; _i < _a.length; _i++) { + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; processNode(jsDocComment); } @@ -72643,7 +78268,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 139 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + return child.kind < 141 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -72651,7 +78276,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 139 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 141 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; }()); @@ -72690,19 +78315,19 @@ var ts; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + TokenOrIdentifierObject.prototype.getChildAt = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getLastToken = function () { return undefined; }; return TokenOrIdentifierObject; @@ -72723,7 +78348,7 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); } return this.documentationComment; }; @@ -72732,19 +78357,20 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69 /* Identifier */; + IdentifierObject.prototype.kind = 70 /* Identifier */; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -72778,7 +78404,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 /* Class */ | 65536 /* Interface */) + return this.flags & 32768 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -72805,9 +78431,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], - /*name*/ undefined, - /*canUseParsedParamTagComments*/ false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; } return this.documentationComment; }; @@ -72816,7 +78440,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72830,6 +78454,20 @@ var ts; SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { return ts.getPositionOfLineAndCharacter(this, line, character); }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); @@ -72851,13 +78489,13 @@ var ts; } function getDeclarationName(declaration) { if (declaration.name) { - var result_6 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_6 !== undefined) { - return result_6; + var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_7 !== undefined) { + return result_7; } - if (declaration.name.kind === 140 /* ComputedPropertyName */) { + if (declaration.name.kind === 142 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 172 /* PropertyAccessExpression */) { + if (expr.kind === 177 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -72867,7 +78505,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { return node.text; @@ -72877,10 +78515,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -72897,35 +78535,35 @@ var ts; else { declarations.push(functionDeclaration); } - ts.forEachChild(node, visit); } + ts.forEachChild(node, visit); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 159 /* TypeLiteral */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 161 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 142 /* Parameter */: + case 144 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // fall through - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: { + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -72934,19 +78572,19 @@ var ts; if (decl.initializer) visit(decl.initializer); } - case 255 /* EnumMember */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 260 /* EnumMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: addDeclaration(node); break; - case 236 /* ExportDeclaration */: + case 241 /* 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 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -72958,7 +78596,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 237 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -72982,9 +78620,33 @@ var ts; getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } + getSignatureConstructor: function () { return SignatureObject; }, }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +78662,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73053,7 +78719,7 @@ var ts; }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (path, value) { + this.fileNameToEntry.forEachValue(function (_path, value) { if (value) { fileNames.push(value.hostFileName); } @@ -73085,7 +78751,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -73185,7 +78851,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +78891,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73256,7 +78929,7 @@ var ts; useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: function (fileName, data, writeByteOrderMark) { }, + writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality @@ -73390,7 +79063,7 @@ var ts; return program; } function cleanupSemanticCache() { - // TODO: Should we jettison the program (or it's type checker) here? + program = undefined; } function dispose() { if (program) { @@ -73452,12 +79125,12 @@ var ts; if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: - case 97 /* ThisKeyword */: - case 165 /* ThisType */: - case 95 /* SuperKeyword */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: + case 98 /* ThisKeyword */: + case 167 /* ThisType */: + case 96 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); if (type) { @@ -73553,12 +79226,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +79242,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73591,7 +79264,7 @@ var ts; function getSourceFile(fileName) { return getNonBoundSourceFile(fileName); } - function getNameOrDottedNameSpan(fileName, startPos, endPos) { + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location var node = ts.getTouchingPropertyName(sourceFile, startPos); @@ -73599,16 +79272,16 @@ var ts; return; } switch (node.kind) { - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: case 9 /* StringLiteral */: - case 84 /* FalseKeyword */: - case 99 /* TrueKeyword */: - case 93 /* NullKeyword */: - case 95 /* SuperKeyword */: - case 97 /* ThisKeyword */: - case 165 /* ThisType */: - case 69 /* Identifier */: + case 85 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 94 /* NullKeyword */: + case 96 /* SuperKeyword */: + case 98 /* ThisKeyword */: + case 167 /* ThisType */: + case 70 /* Identifier */: break; // Cant create the text span default: @@ -73624,7 +79297,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 225 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 230 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -73647,14 +79320,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73701,48 +79388,76 @@ var ts; return result; function getMatchingTokenKind(token) { switch (token.kind) { - case 15 /* OpenBraceToken */: return 16 /* CloseBraceToken */; - case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; - case 19 /* OpenBracketToken */: return 20 /* CloseBracketToken */; - case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; - case 16 /* CloseBraceToken */: return 15 /* OpenBraceToken */; - case 18 /* CloseParenToken */: return 17 /* OpenParenToken */; - case 20 /* CloseBracketToken */: return 19 /* OpenBracketToken */; - case 27 /* GreaterThanToken */: return 25 /* LessThanToken */; + case 16 /* OpenBraceToken */: return 17 /* CloseBraceToken */; + case 18 /* OpenParenToken */: return 19 /* CloseParenToken */; + case 20 /* OpenBracketToken */: return 21 /* CloseBracketToken */; + case 26 /* LessThanToken */: return 28 /* GreaterThanToken */; + case 17 /* CloseBraceToken */: return 16 /* OpenBraceToken */; + case 19 /* CloseParenToken */: return 18 /* OpenParenToken */; + case 21 /* CloseBracketToken */: return 20 /* OpenBracketToken */; + case 28 /* GreaterThanToken */: return 26 /* LessThanToken */; } return undefined; } } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar, + host: host, + cancellationToken: cancellationToken + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73758,7 +79473,7 @@ var ts; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -73926,6 +79641,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +79651,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -73956,7 +79673,7 @@ var ts; sourceFile.nameTable = nameTable; function walk(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9 /* StringLiteral */: @@ -73966,7 +79683,7 @@ var ts; // then we want 'something' to be in the name table. Similarly, if we have // "a['propname']" then we want to store "propname" in the name table. if (ts.isDeclarationName(node) || - node.parent.kind === 240 /* ExternalModuleReference */ || + node.parent.kind === 245 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node)) { nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; @@ -73974,10 +79691,10 @@ var ts; break; default: ts.forEachChild(node, walk); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - ts.forEachChild(jsDocComment, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); } } } @@ -73986,7 +79703,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 173 /* ElementAccessExpression */ && + node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -74070,143 +79787,143 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 218 /* VariableDeclaration */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 223 /* VariableDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return spanInVariableDeclaration(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return spanInParameterDeclaration(node); - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 199 /* Block */: + case 204 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return spanInBlock(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return spanInBlock(node.block); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 204 /* DoStatement */: + case 209 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 203 /* IfStatement */: + case 208 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return spanInForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 216 /* TryStatement */: + case 221 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 169 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 174 /* BindingElement */: // span on complete node return textSpan(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 143 /* Decorator */: + case 145 /* Decorator */: return spanInNodeArray(node.parent.decorators); - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 23 /* SemicolonToken */: + case 24 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return spanInPreviousNode(node); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 16 /* CloseBraceToken */: + case 17 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 20 /* CloseBracketToken */: + case 21 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return spanInOpenParenToken(node); - case 18 /* CloseParenToken */: + case 19 /* CloseParenToken */: return spanInCloseParenToken(node); - case 54 /* ColonToken */: + case 55 /* ColonToken */: return spanInColonToken(node); - case 27 /* GreaterThanToken */: - case 25 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 26 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 104 /* WhileKeyword */: + case 105 /* WhileKeyword */: return spanInWhileKeyword(node); - case 80 /* ElseKeyword */: - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 81 /* ElseKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return spanInNextNode(node); - case 138 /* OfKeyword */: + case 140 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -74218,14 +79935,14 @@ var ts; // Set breakpoint on identifier element of destructuring pattern // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern - if ((node.kind === 69 /* Identifier */ || - node.kind == 191 /* SpreadElementExpression */ || - node.kind === 253 /* PropertyAssignment */ || - node.kind === 254 /* ShorthandPropertyAssignment */) && + if ((node.kind === 70 /* Identifier */ || + node.kind == 196 /* SpreadElement */ || + node.kind === 257 /* PropertyAssignment */ || + node.kind === 258 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 187 /* BinaryExpression */) { + if (node.kind === 192 /* BinaryExpression */) { var binaryExpression = node; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -74234,7 +79951,7 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); } - if (binaryExpression.operatorToken.kind === 56 /* EqualsToken */ && + if (binaryExpression.operatorToken.kind === 57 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { // Set breakpoint on assignment expression element of destructuring pattern // a = expression of @@ -74242,28 +79959,28 @@ var ts; // { a = expression, b, c } = someExpression return textSpan(node); } - if (binaryExpression.operatorToken.kind === 24 /* CommaToken */) { + if (binaryExpression.operatorToken.kind === 25 /* CommaToken */) { return spanInNode(binaryExpression.left); } } if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { - case 204 /* DoStatement */: + case 209 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 143 /* Decorator */: + case 145 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: return textSpan(node); - case 187 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 24 /* CommaToken */) { + case 192 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 25 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -74272,13 +79989,13 @@ var ts; } } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 253 /* PropertyAssignment */ && + if (node.parent.kind === 257 /* PropertyAssignment */ && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 177 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 182 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNextNode(node.parent.type); } // return type of function go to previous token @@ -74286,8 +80003,8 @@ var ts; return spanInPreviousNode(node); } // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 218 /* VariableDeclaration */ || - node.parent.kind === 142 /* Parameter */)) { + if ((node.parent.kind === 223 /* VariableDeclaration */ || + node.parent.kind === 144 /* Parameter */)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -74295,7 +80012,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 187 /* BinaryExpression */) { + if (node.parent.kind === 192 /* BinaryExpression */) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -74321,7 +80038,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 207 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 212 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } // If this is a destructuring pattern, set breakpoint in binding pattern @@ -74332,7 +80049,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 208 /* ForOfStatement */) { + variableDeclaration.parent.parent.kind === 213 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } var declarations = variableDeclaration.parent.declarations; @@ -74372,7 +80089,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 221 /* ClassDeclaration */ && functionDeclaration.kind !== 148 /* Constructor */); + (functionDeclaration.parent.kind === 226 /* ClassDeclaration */ && functionDeclaration.kind !== 150 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -74395,25 +80112,25 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 205 /* WhileStatement */: - case 203 /* IfStatement */: - case 207 /* ForInStatement */: + case 210 /* WhileStatement */: + case 208 /* IfStatement */: + case 212 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 219 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 224 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -74438,23 +80155,23 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 193 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 169 /* BindingElement */) { + if (bindingPattern.parent.kind === 174 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 168 /* ArrayBindingPattern */ && node.kind !== 167 /* ObjectBindingPattern */); - var elements = node.kind === 170 /* ArrayLiteralExpression */ ? + ts.Debug.assert(node.kind !== 173 /* ArrayBindingPattern */ && node.kind !== 172 /* ObjectBindingPattern */); + var elements = node.kind === 175 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 193 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -74462,18 +80179,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 187 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 192 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -74481,24 +80198,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 224 /* EnumDeclaration */: - case 221 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 199 /* Block */: + case 204 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through - case 252 /* CatchClause */: + case 256 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -74506,7 +80223,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -74522,7 +80239,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -74537,12 +80254,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 204 /* DoStatement */ || - node.parent.kind === 174 /* CallExpression */ || - node.parent.kind === 175 /* NewExpression */) { + if (node.parent.kind === 209 /* DoStatement */ || + node.parent.kind === 179 /* CallExpression */ || + node.parent.kind === 180 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 178 /* ParenthesizedExpression */) { + if (node.parent.kind === 183 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -74551,21 +80268,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 178 /* ParenthesizedExpression */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 210 /* WhileStatement */: + case 209 /* DoStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 183 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -74575,20 +80292,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 253 /* PropertyAssignment */ || - node.parent.kind === 142 /* Parameter */) { + node.parent.kind === 257 /* PropertyAssignment */ || + node.parent.kind === 144 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 177 /* TypeAssertionExpression */) { + if (node.parent.kind === 182 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 204 /* DoStatement */) { + if (node.parent.kind === 209 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -74596,7 +80313,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 208 /* ForOfStatement */) { + if (node.parent.kind === 213 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -74624,7 +80341,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74678,7 +80395,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -74712,6 +80429,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74769,7 +80492,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -74818,7 +80541,7 @@ var ts; // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. try { - var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, 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) { @@ -74892,7 +80615,7 @@ var ts; this.factory = factory; factory.registerShim(this); } - ShimBase.prototype.dispose = function (dummy) { + ShimBase.prototype.dispose = function (_dummy) { this.factory.unregisterShim(this); }; return ShimBase; @@ -74914,11 +80637,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +80880,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +80910,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +80937,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75221,8 +80951,15 @@ var ts; return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (resolvedFileName && !compilerOptions.allowJs && ts.fileExtensionIs(resolvedFileName, ".js")) { + return { + resolvedFileName: undefined, + failedLookupLocations: [] + }; + } return { - resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations }; }); @@ -75283,7 +81020,7 @@ var ts; if (result.error) { return { options: {}, - typingOptions: {}, + typeAcquisition: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] @@ -75293,7 +81030,7 @@ var ts; var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, - typingOptions: configFile.typingOptions, + typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") @@ -75308,7 +81045,7 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typingOptions, info.compilerOptions); + return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -75391,9 +81128,7 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -/* tslint:disable:no-unused-variable */ // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.1"; -/* tslint:enable:no-unused-variable */ +var toolsVersion = "2.2"; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index e9c209674b5..e11c200ef44 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + declare namespace ts { interface MapLike { [index: string]: T; @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -46,315 +47,324 @@ declare namespace ts { ConflictMarkerTrivia = 7, NumericLiteral = 8, StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - AsteriskAsteriskToken = 38, - SlashToken = 39, - PercentToken = 40, - PlusPlusToken = 41, - MinusMinusToken = 42, - LessThanLessThanToken = 43, - GreaterThanGreaterThanToken = 44, - GreaterThanGreaterThanGreaterThanToken = 45, - AmpersandToken = 46, - BarToken = 47, - CaretToken = 48, - ExclamationToken = 49, - TildeToken = 50, - AmpersandAmpersandToken = 51, - BarBarToken = 52, - QuestionToken = 53, - ColonToken = 54, - AtToken = 55, - EqualsToken = 56, - PlusEqualsToken = 57, - MinusEqualsToken = 58, - AsteriskEqualsToken = 59, - AsteriskAsteriskEqualsToken = 60, - SlashEqualsToken = 61, - PercentEqualsToken = 62, - LessThanLessThanEqualsToken = 63, - GreaterThanGreaterThanEqualsToken = 64, - GreaterThanGreaterThanGreaterThanEqualsToken = 65, - AmpersandEqualsToken = 66, - BarEqualsToken = 67, - CaretEqualsToken = 68, - Identifier = 69, - BreakKeyword = 70, - CaseKeyword = 71, - CatchKeyword = 72, - ClassKeyword = 73, - ConstKeyword = 74, - ContinueKeyword = 75, - DebuggerKeyword = 76, - DefaultKeyword = 77, - DeleteKeyword = 78, - DoKeyword = 79, - ElseKeyword = 80, - EnumKeyword = 81, - ExportKeyword = 82, - ExtendsKeyword = 83, - FalseKeyword = 84, - FinallyKeyword = 85, - ForKeyword = 86, - FunctionKeyword = 87, - IfKeyword = 88, - ImportKeyword = 89, - InKeyword = 90, - InstanceOfKeyword = 91, - NewKeyword = 92, - NullKeyword = 93, - ReturnKeyword = 94, - SuperKeyword = 95, - SwitchKeyword = 96, - ThisKeyword = 97, - ThrowKeyword = 98, - TrueKeyword = 99, - TryKeyword = 100, - TypeOfKeyword = 101, - VarKeyword = 102, - VoidKeyword = 103, - WhileKeyword = 104, - WithKeyword = 105, - ImplementsKeyword = 106, - InterfaceKeyword = 107, - LetKeyword = 108, - PackageKeyword = 109, - PrivateKeyword = 110, - ProtectedKeyword = 111, - PublicKeyword = 112, - StaticKeyword = 113, - YieldKeyword = 114, - AbstractKeyword = 115, - AsKeyword = 116, - AnyKeyword = 117, - AsyncKeyword = 118, - AwaitKeyword = 119, - BooleanKeyword = 120, - ConstructorKeyword = 121, - DeclareKeyword = 122, - GetKeyword = 123, - IsKeyword = 124, - ModuleKeyword = 125, - NamespaceKeyword = 126, - NeverKeyword = 127, - ReadonlyKeyword = 128, - RequireKeyword = 129, - NumberKeyword = 130, - SetKeyword = 131, - StringKeyword = 132, - SymbolKeyword = 133, - TypeKeyword = 134, - UndefinedKeyword = 135, - FromKeyword = 136, - GlobalKeyword = 137, - OfKeyword = 138, - QualifiedName = 139, - ComputedPropertyName = 140, - TypeParameter = 141, - Parameter = 142, - Decorator = 143, - PropertySignature = 144, - PropertyDeclaration = 145, - MethodSignature = 146, - MethodDeclaration = 147, - Constructor = 148, - GetAccessor = 149, - SetAccessor = 150, - CallSignature = 151, - ConstructSignature = 152, - IndexSignature = 153, - TypePredicate = 154, - TypeReference = 155, - FunctionType = 156, - ConstructorType = 157, - TypeQuery = 158, - TypeLiteral = 159, - ArrayType = 160, - TupleType = 161, - UnionType = 162, - IntersectionType = 163, - ParenthesizedType = 164, - ThisType = 165, - LiteralType = 166, - ObjectBindingPattern = 167, - ArrayBindingPattern = 168, - BindingElement = 169, - ArrayLiteralExpression = 170, - ObjectLiteralExpression = 171, - PropertyAccessExpression = 172, - ElementAccessExpression = 173, - CallExpression = 174, - NewExpression = 175, - TaggedTemplateExpression = 176, - TypeAssertionExpression = 177, - ParenthesizedExpression = 178, - FunctionExpression = 179, - ArrowFunction = 180, - DeleteExpression = 181, - TypeOfExpression = 182, - VoidExpression = 183, - AwaitExpression = 184, - PrefixUnaryExpression = 185, - PostfixUnaryExpression = 186, - BinaryExpression = 187, - ConditionalExpression = 188, - TemplateExpression = 189, - YieldExpression = 190, - SpreadElementExpression = 191, - ClassExpression = 192, - OmittedExpression = 193, - ExpressionWithTypeArguments = 194, - AsExpression = 195, - NonNullExpression = 196, - TemplateSpan = 197, - SemicolonClassElement = 198, - Block = 199, - VariableStatement = 200, - EmptyStatement = 201, - ExpressionStatement = 202, - IfStatement = 203, - DoStatement = 204, - WhileStatement = 205, - ForStatement = 206, - ForInStatement = 207, - ForOfStatement = 208, - ContinueStatement = 209, - BreakStatement = 210, - ReturnStatement = 211, - WithStatement = 212, - SwitchStatement = 213, - LabeledStatement = 214, - ThrowStatement = 215, - TryStatement = 216, - DebuggerStatement = 217, - VariableDeclaration = 218, - VariableDeclarationList = 219, - FunctionDeclaration = 220, - ClassDeclaration = 221, - InterfaceDeclaration = 222, - TypeAliasDeclaration = 223, - EnumDeclaration = 224, - ModuleDeclaration = 225, - ModuleBlock = 226, - CaseBlock = 227, - NamespaceExportDeclaration = 228, - ImportEqualsDeclaration = 229, - ImportDeclaration = 230, - ImportClause = 231, - NamespaceImport = 232, - NamedImports = 233, - ImportSpecifier = 234, - ExportAssignment = 235, - ExportDeclaration = 236, - NamedExports = 237, - ExportSpecifier = 238, - MissingDeclaration = 239, - ExternalModuleReference = 240, - JsxElement = 241, - JsxSelfClosingElement = 242, - JsxOpeningElement = 243, - JsxText = 244, - JsxClosingElement = 245, - JsxAttribute = 246, - JsxSpreadAttribute = 247, - JsxExpression = 248, - CaseClause = 249, - DefaultClause = 250, - HeritageClause = 251, - CatchClause = 252, - PropertyAssignment = 253, - ShorthandPropertyAssignment = 254, - EnumMember = 255, - SourceFile = 256, - JSDocTypeExpression = 257, - JSDocAllType = 258, - JSDocUnknownType = 259, - JSDocArrayType = 260, - JSDocUnionType = 261, - JSDocTupleType = 262, - JSDocNullableType = 263, - JSDocNonNullableType = 264, - JSDocRecordType = 265, - JSDocRecordMember = 266, - JSDocTypeReference = 267, - JSDocOptionalType = 268, - JSDocFunctionType = 269, - JSDocVariadicType = 270, - JSDocConstructorType = 271, - JSDocThisType = 272, - JSDocComment = 273, - JSDocTag = 274, - JSDocParameterTag = 275, - JSDocReturnTag = 276, - JSDocTypeTag = 277, - JSDocTemplateTag = 278, - JSDocTypedefTag = 279, - JSDocPropertyTag = 280, - JSDocTypeLiteral = 281, - JSDocLiteralType = 282, - JSDocNullKeyword = 283, - JSDocUndefinedKeyword = 284, - JSDocNeverKeyword = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - Count = 289, - FirstAssignment = 56, - LastAssignment = 68, - FirstCompoundAssignment = 57, - LastCompoundAssignment = 68, - FirstReservedWord = 70, - LastReservedWord = 105, - FirstKeyword = 70, - LastKeyword = 138, - FirstFutureReservedWord = 106, - LastFutureReservedWord = 114, - FirstTypeNode = 154, - LastTypeNode = 166, - FirstPunctuation = 15, - LastPunctuation = 68, + JsxText = 10, + RegularExpressionLiteral = 11, + NoSubstitutionTemplateLiteral = 12, + TemplateHead = 13, + TemplateMiddle = 14, + TemplateTail = 15, + OpenBraceToken = 16, + CloseBraceToken = 17, + OpenParenToken = 18, + CloseParenToken = 19, + OpenBracketToken = 20, + CloseBracketToken = 21, + DotToken = 22, + DotDotDotToken = 23, + SemicolonToken = 24, + CommaToken = 25, + LessThanToken = 26, + LessThanSlashToken = 27, + GreaterThanToken = 28, + LessThanEqualsToken = 29, + GreaterThanEqualsToken = 30, + EqualsEqualsToken = 31, + ExclamationEqualsToken = 32, + EqualsEqualsEqualsToken = 33, + ExclamationEqualsEqualsToken = 34, + EqualsGreaterThanToken = 35, + PlusToken = 36, + MinusToken = 37, + AsteriskToken = 38, + AsteriskAsteriskToken = 39, + SlashToken = 40, + PercentToken = 41, + PlusPlusToken = 42, + MinusMinusToken = 43, + LessThanLessThanToken = 44, + GreaterThanGreaterThanToken = 45, + GreaterThanGreaterThanGreaterThanToken = 46, + AmpersandToken = 47, + BarToken = 48, + CaretToken = 49, + ExclamationToken = 50, + TildeToken = 51, + AmpersandAmpersandToken = 52, + BarBarToken = 53, + QuestionToken = 54, + ColonToken = 55, + AtToken = 56, + EqualsToken = 57, + PlusEqualsToken = 58, + MinusEqualsToken = 59, + AsteriskEqualsToken = 60, + AsteriskAsteriskEqualsToken = 61, + SlashEqualsToken = 62, + PercentEqualsToken = 63, + LessThanLessThanEqualsToken = 64, + GreaterThanGreaterThanEqualsToken = 65, + GreaterThanGreaterThanGreaterThanEqualsToken = 66, + AmpersandEqualsToken = 67, + BarEqualsToken = 68, + CaretEqualsToken = 69, + Identifier = 70, + BreakKeyword = 71, + CaseKeyword = 72, + CatchKeyword = 73, + ClassKeyword = 74, + ConstKeyword = 75, + ContinueKeyword = 76, + DebuggerKeyword = 77, + DefaultKeyword = 78, + DeleteKeyword = 79, + DoKeyword = 80, + ElseKeyword = 81, + EnumKeyword = 82, + ExportKeyword = 83, + ExtendsKeyword = 84, + FalseKeyword = 85, + FinallyKeyword = 86, + ForKeyword = 87, + FunctionKeyword = 88, + IfKeyword = 89, + ImportKeyword = 90, + InKeyword = 91, + InstanceOfKeyword = 92, + NewKeyword = 93, + NullKeyword = 94, + ReturnKeyword = 95, + SuperKeyword = 96, + SwitchKeyword = 97, + ThisKeyword = 98, + ThrowKeyword = 99, + TrueKeyword = 100, + TryKeyword = 101, + TypeOfKeyword = 102, + VarKeyword = 103, + VoidKeyword = 104, + WhileKeyword = 105, + WithKeyword = 106, + ImplementsKeyword = 107, + InterfaceKeyword = 108, + LetKeyword = 109, + PackageKeyword = 110, + PrivateKeyword = 111, + ProtectedKeyword = 112, + PublicKeyword = 113, + StaticKeyword = 114, + YieldKeyword = 115, + AbstractKeyword = 116, + AsKeyword = 117, + AnyKeyword = 118, + AsyncKeyword = 119, + AwaitKeyword = 120, + BooleanKeyword = 121, + ConstructorKeyword = 122, + DeclareKeyword = 123, + GetKeyword = 124, + IsKeyword = 125, + KeyOfKeyword = 126, + ModuleKeyword = 127, + NamespaceKeyword = 128, + NeverKeyword = 129, + ReadonlyKeyword = 130, + RequireKeyword = 131, + NumberKeyword = 132, + SetKeyword = 133, + StringKeyword = 134, + SymbolKeyword = 135, + TypeKeyword = 136, + UndefinedKeyword = 137, + FromKeyword = 138, + GlobalKeyword = 139, + OfKeyword = 140, + QualifiedName = 141, + ComputedPropertyName = 142, + TypeParameter = 143, + Parameter = 144, + Decorator = 145, + PropertySignature = 146, + PropertyDeclaration = 147, + MethodSignature = 148, + MethodDeclaration = 149, + Constructor = 150, + GetAccessor = 151, + SetAccessor = 152, + CallSignature = 153, + ConstructSignature = 154, + IndexSignature = 155, + TypePredicate = 156, + TypeReference = 157, + FunctionType = 158, + ConstructorType = 159, + TypeQuery = 160, + TypeLiteral = 161, + ArrayType = 162, + TupleType = 163, + UnionType = 164, + IntersectionType = 165, + ParenthesizedType = 166, + ThisType = 167, + TypeOperator = 168, + IndexedAccessType = 169, + MappedType = 170, + LiteralType = 171, + ObjectBindingPattern = 172, + ArrayBindingPattern = 173, + BindingElement = 174, + ArrayLiteralExpression = 175, + ObjectLiteralExpression = 176, + PropertyAccessExpression = 177, + ElementAccessExpression = 178, + CallExpression = 179, + NewExpression = 180, + TaggedTemplateExpression = 181, + TypeAssertionExpression = 182, + ParenthesizedExpression = 183, + FunctionExpression = 184, + ArrowFunction = 185, + DeleteExpression = 186, + TypeOfExpression = 187, + VoidExpression = 188, + AwaitExpression = 189, + PrefixUnaryExpression = 190, + PostfixUnaryExpression = 191, + BinaryExpression = 192, + ConditionalExpression = 193, + TemplateExpression = 194, + YieldExpression = 195, + SpreadElement = 196, + ClassExpression = 197, + OmittedExpression = 198, + ExpressionWithTypeArguments = 199, + AsExpression = 200, + NonNullExpression = 201, + TemplateSpan = 202, + SemicolonClassElement = 203, + Block = 204, + VariableStatement = 205, + EmptyStatement = 206, + ExpressionStatement = 207, + IfStatement = 208, + DoStatement = 209, + WhileStatement = 210, + ForStatement = 211, + ForInStatement = 212, + ForOfStatement = 213, + ContinueStatement = 214, + BreakStatement = 215, + ReturnStatement = 216, + WithStatement = 217, + SwitchStatement = 218, + LabeledStatement = 219, + ThrowStatement = 220, + TryStatement = 221, + DebuggerStatement = 222, + VariableDeclaration = 223, + VariableDeclarationList = 224, + FunctionDeclaration = 225, + ClassDeclaration = 226, + InterfaceDeclaration = 227, + TypeAliasDeclaration = 228, + EnumDeclaration = 229, + ModuleDeclaration = 230, + ModuleBlock = 231, + CaseBlock = 232, + NamespaceExportDeclaration = 233, + ImportEqualsDeclaration = 234, + ImportDeclaration = 235, + ImportClause = 236, + NamespaceImport = 237, + NamedImports = 238, + ImportSpecifier = 239, + ExportAssignment = 240, + ExportDeclaration = 241, + NamedExports = 242, + ExportSpecifier = 243, + MissingDeclaration = 244, + ExternalModuleReference = 245, + JsxElement = 246, + JsxSelfClosingElement = 247, + JsxOpeningElement = 248, + JsxClosingElement = 249, + JsxAttribute = 250, + JsxSpreadAttribute = 251, + JsxExpression = 252, + CaseClause = 253, + DefaultClause = 254, + HeritageClause = 255, + CatchClause = 256, + PropertyAssignment = 257, + ShorthandPropertyAssignment = 258, + SpreadAssignment = 259, + EnumMember = 260, + SourceFile = 261, + JSDocTypeExpression = 262, + JSDocAllType = 263, + JSDocUnknownType = 264, + JSDocArrayType = 265, + JSDocUnionType = 266, + JSDocTupleType = 267, + JSDocNullableType = 268, + JSDocNonNullableType = 269, + JSDocRecordType = 270, + JSDocRecordMember = 271, + JSDocTypeReference = 272, + JSDocOptionalType = 273, + JSDocFunctionType = 274, + JSDocVariadicType = 275, + JSDocConstructorType = 276, + JSDocThisType = 277, + JSDocComment = 278, + JSDocTag = 279, + JSDocAugmentsTag = 280, + JSDocParameterTag = 281, + JSDocReturnTag = 282, + JSDocTypeTag = 283, + JSDocTemplateTag = 284, + JSDocTypedefTag = 285, + JSDocPropertyTag = 286, + JSDocTypeLiteral = 287, + JSDocLiteralType = 288, + JSDocNullKeyword = 289, + JSDocUndefinedKeyword = 290, + JSDocNeverKeyword = 291, + SyntaxList = 292, + NotEmittedStatement = 293, + PartiallyEmittedExpression = 294, + MergeDeclarationMarker = 295, + EndOfDeclarationMarker = 296, + RawExpression = 297, + Count = 298, + FirstAssignment = 57, + LastAssignment = 69, + FirstCompoundAssignment = 58, + LastCompoundAssignment = 69, + FirstReservedWord = 71, + LastReservedWord = 106, + FirstKeyword = 71, + LastKeyword = 140, + FirstFutureReservedWord = 107, + LastFutureReservedWord = 115, + FirstTypeNode = 156, + LastTypeNode = 171, + FirstPunctuation = 16, + LastPunctuation = 69, FirstToken = 0, - LastToken = 138, + LastToken = 140, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 68, - FirstNode = 139, - FirstJSDocNode = 257, - LastJSDocNode = 282, - FirstJSDocTagNode = 273, - LastJSDocTagNode = 285, + LastLiteralToken = 12, + FirstTemplateToken = 12, + LastTemplateToken = 15, + FirstBinaryOperator = 26, + LastBinaryOperator = 69, + FirstNode = 141, + FirstJSDocNode = 262, + LastJSDocNode = 288, + FirstJSDocTagNode = 278, + LastJSDocTagNode = 291, } enum NodeFlags { None = 0, @@ -368,27 +378,21 @@ declare namespace ts { HasImplicitReturn = 128, HasExplicitReturn = 256, GlobalAugmentation = 512, - HasClassExtends = 1024, - HasDecorators = 2048, - HasParamDecorators = 4096, - HasAsyncFunctions = 8192, - HasJsxSpreadAttributes = 16384, - DisallowInContext = 32768, - YieldContext = 65536, - DecoratorContext = 131072, - AwaitContext = 262144, - ThisNodeHasError = 524288, - JavaScriptFile = 1048576, - ThisNodeOrAnySubNodesHasError = 2097152, - HasAggregatedChildData = 4194304, + HasAsyncFunctions = 1024, + DisallowInContext = 2048, + YieldContext = 4096, + DecoratorContext = 8192, + AwaitContext = 16384, + ThisNodeHasError = 32768, + JavaScriptFile = 65536, + ThisNodeOrAnySubNodesHasError = 131072, + HasAggregatedChildData = 262144, BlockScoped = 3, ReachabilityCheckFlags = 384, - EmitHelperFlags = 31744, - ReachabilityAndEmitFlags = 32128, - ContextFlags = 1540096, - TypeExcludesFlags = 327680, + ReachabilityAndEmitFlags = 1408, + ContextFlags = 96256, + TypeExcludesFlags = 20480, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -406,6 +410,8 @@ declare namespace ts { AccessibilityModifier = 28, ParameterPropertyModifier = 92, NonPublicAccessibilityModifier = 24, + TypeScriptModifier = 2270, + ExportDefault = 513, } enum JsxFlags { None = 0, @@ -425,39 +431,54 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type ReadonlyToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; + isInJSDocNamespace?: boolean; } interface TransientIdentifier extends Identifier { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } type EntityName = Identifier | QualifiedName; - type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; + type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +490,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -511,40 +540,45 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } - type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; + type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } + interface SpreadAssignment extends ObjectLiteralElement { + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyLikeDeclaration extends Declaration { name: PropertyName; } - interface BindingPattern extends Node { - elements: NodeArray; - } - interface ObjectBindingPattern extends BindingPattern { + interface ObjectBindingPattern extends Node { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } - type ArrayBindingElement = BindingElement | OmittedExpression; - interface ArrayBindingPattern extends BindingPattern { + interface ArrayBindingPattern extends Node { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } + type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + type ArrayBindingElement = BindingElement | OmittedExpression; /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -555,95 +589,133 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } + interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword; + type: TypeNode; + } + interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken; + type?: TypeNode; + } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,16 +723,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; + operator: PostfixUnaryOperator; } interface LeftHandSideExpression extends IncrementExpression { _leftHandSideExpressionBrand: any; @@ -671,42 +744,102 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } + type AssignmentOperatorToken = Token; + interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; + type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; + type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; + type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; + type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +850,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } - interface SpreadElementExpression extends Expression { + interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; expression: Expression; } /** @@ -752,104 +902,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1045,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1135,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1148,112 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { - name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + kind: SyntaxKind.ModuleDeclaration; + name: Identifier | StringLiteral; + body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; + } + interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: JSDocNamespaceDeclaration | Identifier; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1265,126 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { - name: Identifier | LiteralExpression; + kind: SyntaxKind.JSDocRecordMember; + name: Identifier | StringLiteral | NumericLiteral; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } + interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + typeExpression: JSDocTypeExpression; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1139,8 +1403,9 @@ declare namespace ts { TrueCondition = 32, FalseCondition = 64, SwitchClause = 128, - Referenced = 256, - Shared = 512, + ArrayMutation = 256, + Referenced = 512, + Shared = 1024, Label = 12, Condition = 96, } @@ -1149,7 +1414,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1168,6 +1433,10 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + interface FlowArrayMutation extends FlowNode { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } type FlowType = Type | IncompleteType; interface IncompleteType { flags: TypeFlags; @@ -1178,8 +1447,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1515,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1332,6 +1602,7 @@ declare namespace ts { getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; } interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1352,6 +1623,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -1372,6 +1644,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1660,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1487,29 +1761,24 @@ declare namespace ts { Null = 4096, Never = 8192, TypeParameter = 16384, - Class = 32768, - Interface = 65536, - Reference = 131072, - Tuple = 262144, - Union = 524288, - Intersection = 1048576, - Anonymous = 2097152, - Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, + Object = 32768, + Union = 65536, + Intersection = 131072, + Index = 262144, + IndexedAccess = 524288, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, - StringLike = 34, + StringLike = 262178, NumberLike = 340, BooleanLike = 136, EnumLike = 272, - ObjectType = 2588672, - UnionOrIntersection = 1572864, - StructuredType = 4161536, - StructuredOrTypeParameter = 4177920, - Narrowable = 4178943, - NotUnionOrUnit = 2589191, + UnionOrIntersection = 196608, + StructuredType = 229376, + StructuredOrTypeParameter = 507904, + TypeVariable = 540672, + Narrowable = 1033215, + NotUnionOrUnit = 33281, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1530,7 +1799,21 @@ declare namespace ts { interface EnumLiteralType extends LiteralType { baseType: EnumType & UnionType; } + enum ObjectFlags { + Class = 1, + Interface = 2, + Reference = 4, + Tuple = 8, + Anonymous = 16, + Mapped = 32, + Instantiated = 64, + ObjectLiteral = 128, + EvolvingArray = 256, + ObjectLiteralPatternWithComputedProperties = 512, + ClassOrInterface = 3, + } interface ObjectType extends Type { + objectFlags: ObjectFlags; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1558,9 +1841,24 @@ declare namespace ts { } interface IntersectionType extends UnionOrIntersectionType { } - interface TypeParameter extends Type { + type StructuredType = ObjectType | UnionType | IntersectionType; + interface EvolvingArrayType extends ObjectType { + elementType: Type; + finalArrayType?: Type; + } + interface TypeVariable extends Type { + } + interface TypeParameter extends TypeVariable { constraint: Type; } + interface IndexedAccessType extends TypeVariable { + objectType: Type; + indexType: Type; + constraint?: Type; + } + interface IndexType extends Type { + type: TypeVariable | UnionOrIntersectionType; + } enum SignatureKind { Call = 0, Construct = 1, @@ -1579,6 +1877,11 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -1614,15 +1917,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1961,14 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; + jsxFactory?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1677,12 +1979,13 @@ declare namespace ts { target?: ScriptTarget; traceResolution?: boolean; types?: string[]; - /** Paths used to used to compute primary types search locations */ + /** Paths used to compute primary types search locations */ typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - interface TypingOptions { + interface TypeAcquisition { enableAutoDiscovery?: boolean; + enable?: boolean; include?: string[]; exclude?: string[]; [option: string]: string[] | boolean | undefined; @@ -1692,8 +1995,9 @@ declare namespace ts { projectRootPath: string; safeListPath: string; packageNameToTypingLocation: Map; - typingOptions: TypingOptions; + typeAcquisition: TypeAcquisition; compilerOptions: CompilerOptions; + unresolvedImports: ReadonlyArray; } enum ModuleKind { None = 0, @@ -1701,7 +2005,6 @@ declare namespace ts { AMD = 2, UMD = 3, System = 4, - ES6 = 5, ES2015 = 5, } enum JsxEmit { @@ -1727,21 +2030,25 @@ declare namespace ts { enum ScriptTarget { ES3 = 0, ES5 = 1, - ES6 = 2, ES2015 = 2, - Latest = 2, + ES2016 = 3, + ES2017 = 4, + ESNext = 5, + Latest = 5, } enum LanguageVariant { Standard = 0, JSX = 1, } + /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { options: CompilerOptions; - typingOptions?: TypingOptions; + typeAcquisition?: TypeAcquisition; fileNames: string[]; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1760,12 +2067,45 @@ declare namespace ts { getCurrentDirectory?(): string; getDirectories?(path: string): string[]; } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ interface ResolvedModule { + /** Path of the file the module was resolved to. */ resolvedFileName: string; + /** + * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module: + * - be a .d.ts file + * - use top level imports\exports + * - don't use tripleslash references + */ isExternalLibraryImport?: boolean; } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + */ + interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + } + enum Extension { + Ts = 0, + Tsx = 1, + Dts = 2, + Js = 3, + Jsx = 4, + LastTypeScriptExtension = 2, + } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; + resolvedModule: ResolvedModuleFull | undefined; failedLookupLocations: string[]; } interface ResolvedTypeReferenceDirective { @@ -1807,6 +2147,10 @@ declare namespace ts { _children: Node[]; } } +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.2.0"; +} declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -1823,7 +2167,11 @@ declare namespace ts { readFile(path: string, encoding?: string): string; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; @@ -1838,6 +2186,8 @@ declare namespace ts { getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; } interface FileWatcher { close(): void; @@ -1846,7 +2196,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1932,22 +2282,30 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; - function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function isParameterPropertyDeclaration(node: Node): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + }, errors?: Diagnostic[]): void; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1957,19 +2315,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,9 +2325,26 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -1995,7 +2358,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2006,13 +2369,14 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; - function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; errors: Diagnostic[]; }; } @@ -2061,6 +2425,7 @@ declare namespace ts { } interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; getLineStarts(): number[]; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; @@ -2118,6 +2483,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2521,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2546,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2562,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2594,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2649,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2662,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2684,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2791,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +3116,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 14fbdce59a8..7f41e5d07f5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -22,6 +22,7 @@ var ts; (function (ts) { // token > SyntaxKind.Identifer => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; @@ -37,346 +38,355 @@ var ts; // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 10] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 11] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 11] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 12] = "NoSubstitutionTemplateLiteral"; // Pseudo-literals - SyntaxKind[SyntaxKind["TemplateHead"] = 12] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 13] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 14] = "TemplateTail"; + SyntaxKind[SyntaxKind["TemplateHead"] = 13] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 14] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 15] = "TemplateTail"; // Punctuation - SyntaxKind[SyntaxKind["OpenBraceToken"] = 15] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 16] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 17] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 18] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 19] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 20] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 21] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 22] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 23] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 24] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 25] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 26] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 27] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 28] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 29] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 30] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 31] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 32] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 33] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 34] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 35] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 36] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 37] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 38] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 39] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 40] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 41] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 42] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 43] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 44] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 45] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 46] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 47] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 48] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 49] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 50] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 51] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 52] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 53] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 54] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 55] = "AtToken"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 16] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 17] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 18] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 19] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 20] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 21] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 22] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 23] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 24] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 25] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 26] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 27] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 28] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 29] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 30] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 31] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 32] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 33] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 34] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 35] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 36] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 37] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 38] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 39] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 40] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 41] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 42] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 43] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 44] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 45] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 47] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 48] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 49] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 50] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 51] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 52] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 53] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 54] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 55] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 56] = "AtToken"; // Assignments - SyntaxKind[SyntaxKind["EqualsToken"] = 56] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 57] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 58] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 59] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 60] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 61] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 62] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 63] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 64] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 65] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 66] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 67] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 68] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 57] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 58] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 59] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 60] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 61] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 62] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 63] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 64] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 65] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 67] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 68] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 69] = "CaretEqualsToken"; // Identifiers - SyntaxKind[SyntaxKind["Identifier"] = 69] = "Identifier"; + SyntaxKind[SyntaxKind["Identifier"] = 70] = "Identifier"; // Reserved words - SyntaxKind[SyntaxKind["BreakKeyword"] = 70] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 71] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 72] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 73] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 74] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 75] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 76] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 77] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 78] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 79] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 80] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 81] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 82] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 83] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 84] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 85] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 86] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 87] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 88] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 89] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 90] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 91] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 92] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 93] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 94] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 95] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 96] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 97] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 98] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 99] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 100] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 101] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 102] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 103] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 104] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 105] = "WithKeyword"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 71] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 72] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 73] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 74] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 75] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 76] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 77] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 78] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 79] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 80] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 81] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 82] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 83] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 84] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 85] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 86] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 87] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 88] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 89] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 90] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 91] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 92] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 93] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 94] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 95] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 96] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 97] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 98] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 99] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 100] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 101] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 102] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 103] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 104] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 105] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 106] = "WithKeyword"; // Strict mode reserved words - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 106] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 107] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 108] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 109] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 110] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 111] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 112] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 113] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 114] = "YieldKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 107] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 108] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 109] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 110] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 111] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 112] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 113] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 114] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 115] = "YieldKeyword"; // Contextual keywords - SyntaxKind[SyntaxKind["AbstractKeyword"] = 115] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 116] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 117] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 118] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 119] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 120] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 121] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 122] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 123] = "GetKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 124] = "IsKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 125] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 126] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 127] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 128] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 129] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 130] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 131] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 132] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 133] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 134] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 135] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 136] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 137] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 138] = "OfKeyword"; + SyntaxKind[SyntaxKind["AbstractKeyword"] = 116] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 117] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 118] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 119] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 120] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 121] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 122] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 123] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 124] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 125] = "IsKeyword"; + SyntaxKind[SyntaxKind["KeyOfKeyword"] = 126] = "KeyOfKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 127] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 128] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["NeverKeyword"] = 129] = "NeverKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 130] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 131] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 132] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 133] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 134] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 135] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 136] = "TypeKeyword"; + SyntaxKind[SyntaxKind["UndefinedKeyword"] = 137] = "UndefinedKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 138] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 139] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 140] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 139] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 140] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 141] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 142] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 141] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 142] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 143] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 143] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 144] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 145] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 144] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 145] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 146] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 147] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 148] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 149] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 150] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 151] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 152] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 153] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 146] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 147] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 148] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 149] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 150] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 151] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 152] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 153] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 154] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 155] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 154] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 155] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 156] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 157] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 158] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 159] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 160] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 161] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 162] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 156] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 157] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 158] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 159] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 160] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 161] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 162] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 163] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 164] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 165] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 166] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 167] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 168] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 169] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 170] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 171] = "LiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 169] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 172] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 173] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 174] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 170] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 171] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 172] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 173] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 174] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 175] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 176] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 177] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 178] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 179] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 180] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 181] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 182] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 183] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 184] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 185] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 186] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 187] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 188] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 189] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 190] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 191] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 192] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 193] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 194] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 195] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 196] = "NonNullExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 175] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 176] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 177] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 178] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 179] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 180] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 181] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 182] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 183] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 184] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 185] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 186] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 187] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 188] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 189] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 190] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 191] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 192] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 193] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 194] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 195] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 196] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 197] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 198] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 199] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 200] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 201] = "NonNullExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 197] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 198] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 202] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 203] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 199] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 200] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 201] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 202] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 203] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 204] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 205] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 206] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 207] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 208] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 209] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 210] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 211] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 212] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 213] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 214] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 215] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 216] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 217] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 218] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 219] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 220] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 221] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 222] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 223] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 224] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 225] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 226] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 227] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 228] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 229] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 230] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 231] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 232] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 233] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 234] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 235] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 236] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 237] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 238] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 239] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 204] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 205] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 206] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 207] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 208] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 209] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 210] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 211] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 212] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 213] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 214] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 215] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 216] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 217] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 218] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 219] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 220] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 221] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 222] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 223] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 224] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 225] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 226] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 227] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 228] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 229] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 230] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 231] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 232] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 233] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 234] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 235] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 236] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 237] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 238] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 239] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 240] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 241] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 242] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 243] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 244] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 240] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 241] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 242] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 243] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 244] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 245] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 246] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 247] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 248] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 246] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 247] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 248] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 249] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 250] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 251] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 252] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 249] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 250] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 251] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 252] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 253] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 254] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 255] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 256] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 253] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 254] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 257] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 258] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 259] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 255] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 260] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 256] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 261] = "SourceFile"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 257] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 262] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 258] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 263] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 259] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 260] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 261] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 262] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 263] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 264] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 265] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 266] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 267] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 268] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 269] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 270] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 271] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 272] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 273] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 274] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 275] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 276] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 277] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 278] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; - SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; - SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; - SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 264] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 265] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 266] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 267] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 268] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 269] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 270] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 271] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 272] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 273] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 274] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 275] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 276] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 277] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 278] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 279] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 280] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 281] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 282] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 283] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 284] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 285] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 286] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 287] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocLiteralType"] = 288] = "JSDocLiteralType"; + SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 289] = "JSDocNullKeyword"; + SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 290] = "JSDocUndefinedKeyword"; + SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 291] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 292] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 293] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 294] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 295] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 296] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["RawExpression"] = 297] = "RawExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 289] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 298] = "Count"; // Markers - SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 57] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 68] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 138] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 154] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 166] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 57] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 69] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 58] = "FirstCompoundAssignment"; + SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 69] = "LastCompoundAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 71] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 106] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 71] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 140] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 107] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 115] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 156] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 171] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 16] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 69] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 138] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 140] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 11] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 11] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; - })(ts.SyntaxKind || (ts.SyntaxKind = {})); - var SyntaxKind = ts.SyntaxKind; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 12] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 12] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 15] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 26] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 69] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 141] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 262] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 288] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 278] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 291] = "LastJSDocTagNode"; + })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); + var NodeFlags; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; NodeFlags[NodeFlags["Let"] = 1] = "Let"; @@ -389,29 +399,24 @@ var ts; NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasClassExtends"] = 1024] = "HasClassExtends"; - NodeFlags[NodeFlags["HasDecorators"] = 2048] = "HasDecorators"; - NodeFlags[NodeFlags["HasParamDecorators"] = 4096] = "HasParamDecorators"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 8192] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["HasJsxSpreadAttributes"] = 16384] = "HasJsxSpreadAttributes"; - NodeFlags[NodeFlags["DisallowInContext"] = 32768] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 65536] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 131072] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 262144] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 524288] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 1048576] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 2097152] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 4194304] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["EmitHelperFlags"] = 31744] = "EmitHelperFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 32128] = "ReachabilityAndEmitFlags"; + NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 1540096] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; // Exclude these flags when parsing a Type - NodeFlags[NodeFlags["TypeExcludesFlags"] = 327680] = "TypeExcludesFlags"; - })(ts.NodeFlags || (ts.NodeFlags = {})); - var NodeFlags = ts.NodeFlags; + NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); + var ModifierFlags; (function (ModifierFlags) { ModifierFlags[ModifierFlags["None"] = 0] = "None"; ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; @@ -430,8 +435,10 @@ var ts; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - })(ts.ModifierFlags || (ts.ModifierFlags = {})); - var ModifierFlags = ts.ModifierFlags; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); + var JsxFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; /** An element from a named property of the JSX.IntrinsicElements interface */ @@ -439,24 +446,24 @@ var ts; /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(ts.JsxFlags || (ts.JsxFlags = {})); - var JsxFlags = ts.JsxFlags; + })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); /* @internal */ + var RelationComparisonResult; (function (RelationComparisonResult) { RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var RelationComparisonResult = ts.RelationComparisonResult; + })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ + var GeneratedIdentifierKind; (function (GeneratedIdentifierKind) { GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var GeneratedIdentifierKind = ts.GeneratedIdentifierKind; + })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; FlowFlags[FlowFlags["Start"] = 2] = "Start"; @@ -466,12 +473,12 @@ var ts; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; + FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(ts.FlowFlags || (ts.FlowFlags = {})); - var FlowFlags = ts.FlowFlags; + })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } @@ -479,6 +486,7 @@ var ts; }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ + var ExitStatus; (function (ExitStatus) { // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, // when -version or -help was provided, or this was a normal compilation, no diagnostics @@ -488,8 +496,8 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; @@ -502,8 +510,9 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var TypeFormatFlags = ts.TypeFormatFlags; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; + })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol @@ -515,23 +524,29 @@ var ts; // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - })(ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolFormatFlags = ts.SymbolFormatFlags; + })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ + var SymbolAccessibility; (function (SymbolAccessibility) { SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SymbolAccessibility = ts.SymbolAccessibility; + })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ + var SyntheticSymbolKind; + (function (SyntheticSymbolKind) { + SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; + SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; + })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); + var TypePredicateKind; (function (TypePredicateKind) { TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); - var TypePredicateKind = ts.TypePredicateKind; + })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; // should be emitted using a safe fallback. @@ -549,8 +564,8 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; // with call signatures. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var SymbolFlags; (function (SymbolFlags) { SymbolFlags[SymbolFlags["None"] = 0] = "None"; SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; @@ -625,9 +640,9 @@ var ts; // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; - })(ts.SymbolFlags || (ts.SymbolFlags = {})); - var SymbolFlags = ts.SymbolFlags; + })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; @@ -649,8 +664,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var NodeCheckFlags = ts.NodeCheckFlags; + })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var TypeFlags; (function (TypeFlags) { TypeFlags[TypeFlags["Any"] = 1] = "Any"; TypeFlags[TypeFlags["String"] = 2] = "String"; @@ -667,26 +682,19 @@ var ts; TypeFlags[TypeFlags["Null"] = 4096] = "Null"; TypeFlags[TypeFlags["Never"] = 8192] = "Never"; TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 32768] = "Class"; - TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 524288] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; + TypeFlags[TypeFlags["Object"] = 32768] = "Object"; + TypeFlags[TypeFlags["Union"] = 65536] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 262144] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; /* @internal */ - TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 16777216] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; - /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -698,35 +706,49 @@ var ts; TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; /* @internal */ TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; + TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 507904] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 1033215] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33281] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; - })(ts.TypeFlags || (ts.TypeFlags = {})); - var TypeFlags = ts.TypeFlags; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + var ObjectFlags; + (function (ObjectFlags) { + ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; + ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; + ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; + ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; + ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; + ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; + ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; + ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(ts.SignatureKind || (ts.SignatureKind = {})); - var SignatureKind = ts.SignatureKind; + })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; - })(ts.IndexKind || (ts.IndexKind = {})); - var IndexKind = ts.IndexKind; + })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); /* @internal */ + var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; /// exports.name = expr @@ -737,73 +759,74 @@ var ts; SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); - var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; + })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var JsxEmit; (function (JsxEmit) { JsxEmit[JsxEmit["None"] = 0] = "None"; JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; JsxEmit[JsxEmit["React"] = 2] = "React"; - })(ts.JsxEmit || (ts.JsxEmit = {})); - var JsxEmit = ts.JsxEmit; + })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); + var NewLineKind; (function (NewLineKind) { NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(ts.NewLineKind || (ts.NewLineKind = {})); - var NewLineKind = ts.NewLineKind; + })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); + var ScriptKind; (function (ScriptKind) { ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; ScriptKind[ScriptKind["JS"] = 1] = "JS"; ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - })(ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptKind = ts.ScriptKind; + })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptTarget; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES6"] = 2] = "ES6"; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["Latest"] = 2] = "Latest"; - })(ts.ScriptTarget || (ts.ScriptTarget = {})); - var ScriptTarget = ts.ScriptTarget; + ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; + ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; + ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); + var LanguageVariant; (function (LanguageVariant) { LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(ts.LanguageVariant || (ts.LanguageVariant = {})); - var LanguageVariant = ts.LanguageVariant; + })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); /* @internal */ + var DiagnosticStyle; (function (DiagnosticStyle) { DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; - })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); - var DiagnosticStyle = ts.DiagnosticStyle; + })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var WatchDirectoryFlags; (function (WatchDirectoryFlags) { WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var WatchDirectoryFlags = ts.WatchDirectoryFlags; + })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); /* @internal */ + var CharacterCodes; (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; @@ -930,99 +953,140 @@ var ts; CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(ts.CharacterCodes || (ts.CharacterCodes = {})); - var CharacterCodes = ts.CharacterCodes; + })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ + var TransformFlags; (function (TransformFlags) { TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["Jsx"] = 4] = "Jsx"; - TransformFlags[TransformFlags["ContainsJsx"] = 8] = "ContainsJsx"; - TransformFlags[TransformFlags["ES7"] = 16] = "ES7"; - TransformFlags[TransformFlags["ContainsES7"] = 32] = "ContainsES7"; - TransformFlags[TransformFlags["ES6"] = 64] = "ES6"; - TransformFlags[TransformFlags["ContainsES6"] = 128] = "ContainsES6"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 256] = "DestructuringAssignment"; - TransformFlags[TransformFlags["Generator"] = 512] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; + TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; + TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; + TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; + TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 2048] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 4096] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 131072] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpreadElementExpression"] = 262144] = "ContainsSpreadElementExpression"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; + TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; + TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; + TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; + TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 12] = "AssertJsx"; - TransformFlags[TransformFlags["AssertES7"] = 48] = "AssertES7"; - TransformFlags[TransformFlags["AssertES6"] = 192] = "AssertES6"; - TransformFlags[TransformFlags["AssertGenerator"] = 1536] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536871765] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 550710101] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 550726485] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 550593365] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 550593365] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 537590613] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546335573] = "ModuleExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 537430869] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537133909] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 538968917] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 538968917] = "ParameterExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 137216] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES6FunctionSyntaxMask"] = 81920] = "ES6FunctionSyntaxMask"; - })(ts.TransformFlags || (ts.TransformFlags = {})); - var TransformFlags = ts.TransformFlags; + TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + var EmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; + EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; + EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; + })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + var ExternalEmitHelpers; + (function (ExternalEmitHelpers) { + ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; + ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; + ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; + ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; + ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; + ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; + ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; + ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 128] = "LastEmitHelper"; + })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); + /* @internal */ + var EmitContext; + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(EmitContext = ts.EmitContext || (ts.EmitContext = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,13 +1096,12 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -1121,8 +1184,12 @@ var ts; })(ts || (ts = {})); /// /// -/* @internal */ var ts; +(function (ts) { + /** The version of the TypeScript compiler release */ + ts.version = "2.2.0"; +})(ts || (ts = {})); +/* @internal */ (function (ts) { /** * Ternary values are defined such that @@ -1133,13 +1200,15 @@ var ts; * x | y is Maybe if either x or y is Maybe, but neither x or y is True. * x | y is True if either x or y is True. */ + var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; Ternary[Ternary["Maybe"] = 1] = "Maybe"; Ternary[Ternary["True"] = -1] = "True"; - })(ts.Ternary || (ts.Ternary = {})); - var Ternary = ts.Ternary; + })(Ternary = ts.Ternary || (ts.Ternary = {})); var createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); // tslint:disable-line:no-null-keyword // Using 'delete' on an object causes V8 to put the object in dictionary mode. @@ -1164,13 +1233,21 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, - clear: clear + getKeys: getKeys, + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1200,12 +1277,12 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; + var Comparison; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(ts.Comparison || (ts.Comparison = {})); - var Comparison = ts.Comparison; + })(Comparison = ts.Comparison || (ts.Comparison = {})); /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -1223,6 +1300,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -1364,13 +1448,33 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + // Maps from T to T and avoids allocation if all elements map to themselves + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; /** * Flattens an array containing a mix of array or non-array elements. * @@ -1493,20 +1597,38 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -1519,6 +1641,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; /** * Compacts an array, removing any falsey elements. */ @@ -1540,26 +1697,86 @@ var ts; return result || array; } ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: break inner; + case 0 /* EqualTo */: continue outer; + case 1 /* GreaterThan */: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + /** + * Appends a value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param value The value to append to the array. If `value` is `undefined`, nothing is + * appended. + */ + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Appends a range of value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) // create array of indices + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) // sort indices by value then position + .map(function (i) { return array[i]; }); // get sorted array + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -1570,26 +1787,17 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ function firstOrUndefined(array) { return array && array.length > 0 ? array[0] : undefined; } ts.firstOrUndefined = firstOrUndefined; - function singleOrUndefined(array) { - return array && array.length === 1 - ? array[0] - : undefined; - } - ts.singleOrUndefined = singleOrUndefined; - function singleOrMany(array) { - return array && array.length === 1 - ? array[0] - : array; - } - ts.singleOrMany = singleOrMany; /** - * Returns the last element of an array if non-empty, undefined otherwise. + * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { return array && array.length > 0 @@ -1597,6 +1805,31 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + /** + * Returns the only element of an array if it contains only one element; otheriwse, returns the + * array. + */ + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; /** * Performs a binary search, finding the index at which 'value' occurs in 'array'. * If no such index is found, returns the 2's-complement of first index at which @@ -1604,16 +1837,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { - var low = 0; + function binarySearch(array, value, comparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1756,6 +1995,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -1789,25 +2037,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -1836,8 +2065,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -1918,6 +2147,14 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + /** Does nothing. */ + function noop() { } + ts.noop = noop; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -1929,9 +2166,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -1956,12 +2243,12 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; /* internal */ - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -1984,6 +2271,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -2024,7 +2322,8 @@ var ts; if (b === undefined) return 1 /* GreaterThan */; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { + // accent means a ≠ b, a ≠ á, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -2096,7 +2395,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2430,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2484,57 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2384,6 +2737,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -2424,73 +2781,93 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - // The * and ? wildcards should not match directories or files that start with . if they - // appear first in a component. Dotted directories and files can be included explicitly - // like so: **/.*/.* - if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -2500,7 +2877,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -2515,7 +2892,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -2564,29 +2941,35 @@ var ts; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); // Append the literal and canonical candidate base paths. - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; // 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); + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -2621,15 +3004,34 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; - function isSupportedSourceFileName(fileName, compilerOptions) { + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -2643,14 +3045,14 @@ var ts; * aligned to the offset of the highest priority extension in the * allSupportedExtensions array. */ + var ExtensionPriority; (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; + })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -2709,10 +3111,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -2722,10 +3120,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -2737,7 +3135,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2748,18 +3145,18 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + var AssertionLevel; (function (AssertionLevel) { AssertionLevel[AssertionLevel["None"] = 0] = "None"; AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(ts.AssertionLevel || (ts.AssertionLevel = {})); - var AssertionLevel = ts.AssertionLevel; + })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,31 +3174,19 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. for (var i = index; i < array.length - 1; i++) { @@ -2836,6 +3221,119 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); /// var ts; @@ -3040,10 +3538,18 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -3149,6 +3655,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3158,7 +3665,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -3166,7 +3673,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -3182,6 +3689,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3261,7 +3771,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -3272,7 +3784,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { // encoding is automatically handled by the implementation in ChakraHost return ChakraHost.readFile(path); }, @@ -3290,30 +3802,55 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3362,7 +3899,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -3472,7 +4009,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -3535,6 +4071,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -3578,6 +4115,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -3588,16 +4126,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -3637,11 +4176,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3675,8 +4214,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -3688,7 +4225,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -3710,9 +4247,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -3759,6 +4294,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3782,6 +4324,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -3802,7 +4345,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -3813,6 +4356,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -3883,7 +4431,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -3912,6 +4463,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3924,7 +4476,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -3995,7 +4547,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -4032,9 +4584,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4043,7 +4602,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -4059,6 +4619,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4076,6 +4637,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -4086,9 +4648,24 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); /// @@ -4097,133 +4674,134 @@ var ts; (function (ts) { /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 69 /* Identifier */; + return token >= 70 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115 /* AbstractKeyword */, - "any": 117 /* AnyKeyword */, - "as": 116 /* AsKeyword */, - "boolean": 120 /* BooleanKeyword */, - "break": 70 /* BreakKeyword */, - "case": 71 /* CaseKeyword */, - "catch": 72 /* CatchKeyword */, - "class": 73 /* ClassKeyword */, - "continue": 75 /* ContinueKeyword */, - "const": 74 /* ConstKeyword */, - "constructor": 121 /* ConstructorKeyword */, - "debugger": 76 /* DebuggerKeyword */, - "declare": 122 /* DeclareKeyword */, - "default": 77 /* DefaultKeyword */, - "delete": 78 /* DeleteKeyword */, - "do": 79 /* DoKeyword */, - "else": 80 /* ElseKeyword */, - "enum": 81 /* EnumKeyword */, - "export": 82 /* ExportKeyword */, - "extends": 83 /* ExtendsKeyword */, - "false": 84 /* FalseKeyword */, - "finally": 85 /* FinallyKeyword */, - "for": 86 /* ForKeyword */, - "from": 136 /* FromKeyword */, - "function": 87 /* FunctionKeyword */, - "get": 123 /* GetKeyword */, - "if": 88 /* IfKeyword */, - "implements": 106 /* ImplementsKeyword */, - "import": 89 /* ImportKeyword */, - "in": 90 /* InKeyword */, - "instanceof": 91 /* InstanceOfKeyword */, - "interface": 107 /* InterfaceKeyword */, - "is": 124 /* IsKeyword */, - "let": 108 /* LetKeyword */, - "module": 125 /* ModuleKeyword */, - "namespace": 126 /* NamespaceKeyword */, - "never": 127 /* NeverKeyword */, - "new": 92 /* NewKeyword */, - "null": 93 /* NullKeyword */, - "number": 130 /* NumberKeyword */, - "package": 109 /* PackageKeyword */, - "private": 110 /* PrivateKeyword */, - "protected": 111 /* ProtectedKeyword */, - "public": 112 /* PublicKeyword */, - "readonly": 128 /* ReadonlyKeyword */, - "require": 129 /* RequireKeyword */, - "global": 137 /* GlobalKeyword */, - "return": 94 /* ReturnKeyword */, - "set": 131 /* SetKeyword */, - "static": 113 /* StaticKeyword */, - "string": 132 /* StringKeyword */, - "super": 95 /* SuperKeyword */, - "switch": 96 /* SwitchKeyword */, - "symbol": 133 /* SymbolKeyword */, - "this": 97 /* ThisKeyword */, - "throw": 98 /* ThrowKeyword */, - "true": 99 /* TrueKeyword */, - "try": 100 /* TryKeyword */, - "type": 134 /* TypeKeyword */, - "typeof": 101 /* TypeOfKeyword */, - "undefined": 135 /* UndefinedKeyword */, - "var": 102 /* VarKeyword */, - "void": 103 /* VoidKeyword */, - "while": 104 /* WhileKeyword */, - "with": 105 /* WithKeyword */, - "yield": 114 /* YieldKeyword */, - "async": 118 /* AsyncKeyword */, - "await": 119 /* AwaitKeyword */, - "of": 138 /* OfKeyword */, - "{": 15 /* OpenBraceToken */, - "}": 16 /* CloseBraceToken */, - "(": 17 /* OpenParenToken */, - ")": 18 /* CloseParenToken */, - "[": 19 /* OpenBracketToken */, - "]": 20 /* CloseBracketToken */, - ".": 21 /* DotToken */, - "...": 22 /* DotDotDotToken */, - ";": 23 /* SemicolonToken */, - ",": 24 /* CommaToken */, - "<": 25 /* LessThanToken */, - ">": 27 /* GreaterThanToken */, - "<=": 28 /* LessThanEqualsToken */, - ">=": 29 /* GreaterThanEqualsToken */, - "==": 30 /* EqualsEqualsToken */, - "!=": 31 /* ExclamationEqualsToken */, - "===": 32 /* EqualsEqualsEqualsToken */, - "!==": 33 /* ExclamationEqualsEqualsToken */, - "=>": 34 /* EqualsGreaterThanToken */, - "+": 35 /* PlusToken */, - "-": 36 /* MinusToken */, - "**": 38 /* AsteriskAsteriskToken */, - "*": 37 /* AsteriskToken */, - "/": 39 /* SlashToken */, - "%": 40 /* PercentToken */, - "++": 41 /* PlusPlusToken */, - "--": 42 /* MinusMinusToken */, - "<<": 43 /* LessThanLessThanToken */, - ">": 44 /* GreaterThanGreaterThanToken */, - ">>>": 45 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 46 /* AmpersandToken */, - "|": 47 /* BarToken */, - "^": 48 /* CaretToken */, - "!": 49 /* ExclamationToken */, - "~": 50 /* TildeToken */, - "&&": 51 /* AmpersandAmpersandToken */, - "||": 52 /* BarBarToken */, - "?": 53 /* QuestionToken */, - ":": 54 /* ColonToken */, - "=": 56 /* EqualsToken */, - "+=": 57 /* PlusEqualsToken */, - "-=": 58 /* MinusEqualsToken */, - "*=": 59 /* AsteriskEqualsToken */, - "**=": 60 /* AsteriskAsteriskEqualsToken */, - "/=": 61 /* SlashEqualsToken */, - "%=": 62 /* PercentEqualsToken */, - "<<=": 63 /* LessThanLessThanEqualsToken */, - ">>=": 64 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 66 /* AmpersandEqualsToken */, - "|=": 67 /* BarEqualsToken */, - "^=": 68 /* CaretEqualsToken */, - "@": 55 /* AtToken */ + "abstract": 116 /* AbstractKeyword */, + "any": 118 /* AnyKeyword */, + "as": 117 /* AsKeyword */, + "boolean": 121 /* BooleanKeyword */, + "break": 71 /* BreakKeyword */, + "case": 72 /* CaseKeyword */, + "catch": 73 /* CatchKeyword */, + "class": 74 /* ClassKeyword */, + "continue": 76 /* ContinueKeyword */, + "const": 75 /* ConstKeyword */, + "constructor": 122 /* ConstructorKeyword */, + "debugger": 77 /* DebuggerKeyword */, + "declare": 123 /* DeclareKeyword */, + "default": 78 /* DefaultKeyword */, + "delete": 79 /* DeleteKeyword */, + "do": 80 /* DoKeyword */, + "else": 81 /* ElseKeyword */, + "enum": 82 /* EnumKeyword */, + "export": 83 /* ExportKeyword */, + "extends": 84 /* ExtendsKeyword */, + "false": 85 /* FalseKeyword */, + "finally": 86 /* FinallyKeyword */, + "for": 87 /* ForKeyword */, + "from": 138 /* FromKeyword */, + "function": 88 /* FunctionKeyword */, + "get": 124 /* GetKeyword */, + "if": 89 /* IfKeyword */, + "implements": 107 /* ImplementsKeyword */, + "import": 90 /* ImportKeyword */, + "in": 91 /* InKeyword */, + "instanceof": 92 /* InstanceOfKeyword */, + "interface": 108 /* InterfaceKeyword */, + "is": 125 /* IsKeyword */, + "keyof": 126 /* KeyOfKeyword */, + "let": 109 /* LetKeyword */, + "module": 127 /* ModuleKeyword */, + "namespace": 128 /* NamespaceKeyword */, + "never": 129 /* NeverKeyword */, + "new": 93 /* NewKeyword */, + "null": 94 /* NullKeyword */, + "number": 132 /* NumberKeyword */, + "package": 110 /* PackageKeyword */, + "private": 111 /* PrivateKeyword */, + "protected": 112 /* ProtectedKeyword */, + "public": 113 /* PublicKeyword */, + "readonly": 130 /* ReadonlyKeyword */, + "require": 131 /* RequireKeyword */, + "global": 139 /* GlobalKeyword */, + "return": 95 /* ReturnKeyword */, + "set": 133 /* SetKeyword */, + "static": 114 /* StaticKeyword */, + "string": 134 /* StringKeyword */, + "super": 96 /* SuperKeyword */, + "switch": 97 /* SwitchKeyword */, + "symbol": 135 /* SymbolKeyword */, + "this": 98 /* ThisKeyword */, + "throw": 99 /* ThrowKeyword */, + "true": 100 /* TrueKeyword */, + "try": 101 /* TryKeyword */, + "type": 136 /* TypeKeyword */, + "typeof": 102 /* TypeOfKeyword */, + "undefined": 137 /* UndefinedKeyword */, + "var": 103 /* VarKeyword */, + "void": 104 /* VoidKeyword */, + "while": 105 /* WhileKeyword */, + "with": 106 /* WithKeyword */, + "yield": 115 /* YieldKeyword */, + "async": 119 /* AsyncKeyword */, + "await": 120 /* AwaitKeyword */, + "of": 140 /* OfKeyword */, + "{": 16 /* OpenBraceToken */, + "}": 17 /* CloseBraceToken */, + "(": 18 /* OpenParenToken */, + ")": 19 /* CloseParenToken */, + "[": 20 /* OpenBracketToken */, + "]": 21 /* CloseBracketToken */, + ".": 22 /* DotToken */, + "...": 23 /* DotDotDotToken */, + ";": 24 /* SemicolonToken */, + ",": 25 /* CommaToken */, + "<": 26 /* LessThanToken */, + ">": 28 /* GreaterThanToken */, + "<=": 29 /* LessThanEqualsToken */, + ">=": 30 /* GreaterThanEqualsToken */, + "==": 31 /* EqualsEqualsToken */, + "!=": 32 /* ExclamationEqualsToken */, + "===": 33 /* EqualsEqualsEqualsToken */, + "!==": 34 /* ExclamationEqualsEqualsToken */, + "=>": 35 /* EqualsGreaterThanToken */, + "+": 36 /* PlusToken */, + "-": 37 /* MinusToken */, + "**": 39 /* AsteriskAsteriskToken */, + "*": 38 /* AsteriskToken */, + "/": 40 /* SlashToken */, + "%": 41 /* PercentToken */, + "++": 42 /* PlusPlusToken */, + "--": 43 /* MinusMinusToken */, + "<<": 44 /* LessThanLessThanToken */, + ">": 45 /* GreaterThanGreaterThanToken */, + ">>>": 46 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 47 /* AmpersandToken */, + "|": 48 /* BarToken */, + "^": 49 /* CaretToken */, + "!": 50 /* ExclamationToken */, + "~": 51 /* TildeToken */, + "&&": 52 /* AmpersandAmpersandToken */, + "||": 53 /* BarBarToken */, + "?": 54 /* QuestionToken */, + ":": 55 /* ColonToken */, + "=": 57 /* EqualsToken */, + "+=": 58 /* PlusEqualsToken */, + "-=": 59 /* MinusEqualsToken */, + "*=": 60 /* AsteriskEqualsToken */, + "**=": 61 /* AsteriskAsteriskEqualsToken */, + "/=": 62 /* SlashEqualsToken */, + "%=": 63 /* PercentEqualsToken */, + "<<=": 64 /* LessThanLessThanEqualsToken */, + ">>=": 65 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 67 /* AmpersandEqualsToken */, + "|=": 68 /* BarEqualsToken */, + "^=": 69 /* CaretEqualsToken */, + "@": 56 /* AtToken */, }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers @@ -4727,7 +5305,7 @@ var ts; return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -4800,8 +5378,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 /* Identifier */ || token > 105 /* LastReservedWord */; }, - isReservedWord: function () { return token >= 70 /* FirstReservedWord */ && token <= 105 /* LastReservedWord */; }, + isIdentifier: function () { return token === 70 /* Identifier */ || token > 106 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -4820,7 +5398,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -4949,7 +5527,7 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + resultingToken = startedWithBacktick ? 12 /* NoSubstitutionTemplateLiteral */ : 15 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); @@ -4957,14 +5535,14 @@ var ts; if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + resultingToken = startedWithBacktick ? 12 /* NoSubstitutionTemplateLiteral */ : 15 /* TemplateTail */; break; } // '${' if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */; + resultingToken = startedWithBacktick ? 13 /* TemplateHead */ : 14 /* TemplateMiddle */; break; } // Escape character @@ -5142,10 +5720,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69 /* Identifier */; + return token = 70 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -5222,12 +5800,12 @@ var ts; case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 33 /* ExclamationEqualsEqualsToken */; + return pos += 3, token = 34 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 31 /* ExclamationEqualsToken */; + return pos += 2, token = 32 /* ExclamationEqualsToken */; } pos++; - return token = 49 /* ExclamationToken */; + return token = 50 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -5236,68 +5814,68 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 62 /* PercentEqualsToken */; + return pos += 2, token = 63 /* PercentEqualsToken */; } pos++; - return token = 40 /* PercentToken */; + return token = 41 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - return pos += 2, token = 51 /* AmpersandAmpersandToken */; + return pos += 2, token = 52 /* AmpersandAmpersandToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 66 /* AmpersandEqualsToken */; + return pos += 2, token = 67 /* AmpersandEqualsToken */; } pos++; - return token = 46 /* AmpersandToken */; + return token = 47 /* AmpersandToken */; case 40 /* openParen */: pos++; - return token = 17 /* OpenParenToken */; + return token = 18 /* OpenParenToken */; case 41 /* closeParen */: pos++; - return token = 18 /* CloseParenToken */; + return token = 19 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 59 /* AsteriskEqualsToken */; + return pos += 2, token = 60 /* AsteriskEqualsToken */; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 60 /* AsteriskAsteriskEqualsToken */; + return pos += 3, token = 61 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 38 /* AsteriskAsteriskToken */; + return pos += 2, token = 39 /* AsteriskAsteriskToken */; } pos++; - return token = 37 /* AsteriskToken */; + return token = 38 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { - return pos += 2, token = 41 /* PlusPlusToken */; + return pos += 2, token = 42 /* PlusPlusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 57 /* PlusEqualsToken */; + return pos += 2, token = 58 /* PlusEqualsToken */; } pos++; - return token = 35 /* PlusToken */; + return token = 36 /* PlusToken */; case 44 /* comma */: pos++; - return token = 24 /* CommaToken */; + return token = 25 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { - return pos += 2, token = 42 /* MinusMinusToken */; + return pos += 2, token = 43 /* MinusMinusToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 58 /* MinusEqualsToken */; + return pos += 2, token = 59 /* MinusEqualsToken */; } pos++; - return token = 36 /* MinusToken */; + return token = 37 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { - return pos += 3, token = 22 /* DotDotDotToken */; + return pos += 3, token = 23 /* DotDotDotToken */; } pos++; - return token = 21 /* DotToken */; + return token = 22 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -5343,10 +5921,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 61 /* SlashEqualsToken */; + return pos += 2, token = 62 /* SlashEqualsToken */; } pos++; - return token = 39 /* SlashToken */; + return token = 40 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -5399,10 +5977,10 @@ var ts; return token = 8 /* NumericLiteral */; case 58 /* colon */: pos++; - return token = 54 /* ColonToken */; + return token = 55 /* ColonToken */; case 59 /* semicolon */: pos++; - return token = 23 /* SemicolonToken */; + return token = 24 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5415,20 +5993,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 63 /* LessThanLessThanEqualsToken */; + return pos += 3, token = 64 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 43 /* LessThanLessThanToken */; + return pos += 2, token = 44 /* LessThanLessThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 28 /* LessThanEqualsToken */; + return pos += 2, token = 29 /* LessThanEqualsToken */; } if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { - return pos += 2, token = 26 /* LessThanSlashToken */; + return pos += 2, token = 27 /* LessThanSlashToken */; } pos++; - return token = 25 /* LessThanToken */; + return token = 26 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5441,15 +6019,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 32 /* EqualsEqualsEqualsToken */; + return pos += 3, token = 33 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 30 /* EqualsEqualsToken */; + return pos += 2, token = 31 /* EqualsEqualsToken */; } if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - return pos += 2, token = 34 /* EqualsGreaterThanToken */; + return pos += 2, token = 35 /* EqualsGreaterThanToken */; } pos++; - return token = 56 /* EqualsToken */; + return token = 57 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -5461,43 +6039,43 @@ var ts; } } pos++; - return token = 27 /* GreaterThanToken */; + return token = 28 /* GreaterThanToken */; case 63 /* question */: pos++; - return token = 53 /* QuestionToken */; + return token = 54 /* QuestionToken */; case 91 /* openBracket */: pos++; - return token = 19 /* OpenBracketToken */; + return token = 20 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 20 /* CloseBracketToken */; + return token = 21 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 68 /* CaretEqualsToken */; + return pos += 2, token = 69 /* CaretEqualsToken */; } pos++; - return token = 48 /* CaretToken */; + return token = 49 /* CaretToken */; case 123 /* openBrace */: pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { - return pos += 2, token = 52 /* BarBarToken */; + return pos += 2, token = 53 /* BarBarToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 67 /* BarEqualsToken */; + return pos += 2, token = 68 /* BarEqualsToken */; } pos++; - return token = 47 /* BarToken */; + return token = 48 /* BarToken */; case 125 /* closeBrace */: pos++; - return token = 16 /* CloseBraceToken */; + return token = 17 /* CloseBraceToken */; case 126 /* tilde */: pos++; - return token = 50 /* TildeToken */; + return token = 51 /* TildeToken */; case 64 /* at */: pos++; - return token = 55 /* AtToken */; + return token = 56 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -5535,29 +6113,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27 /* GreaterThanToken */) { + if (token === 28 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { - return pos += 3, token = 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + return pos += 3, token = 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 45 /* GreaterThanGreaterThanGreaterThanToken */; + return pos += 2, token = 46 /* GreaterThanGreaterThanGreaterThanToken */; } if (text.charCodeAt(pos + 1) === 61 /* equals */) { - return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; + return pos += 2, token = 65 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 44 /* GreaterThanGreaterThanToken */; + return token = 45 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 29 /* GreaterThanEqualsToken */; + return token = 30 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) { + if (token === 40 /* SlashToken */ || token === 62 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -5602,7 +6180,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10 /* RegularExpressionLiteral */; + token = 11 /* RegularExpressionLiteral */; } return token; } @@ -5610,7 +6188,7 @@ var ts; * Unconditionally back up and scan a template expression portion. */ function reScanTemplateToken() { - ts.Debug.assert(token === 16 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -5627,14 +6205,14 @@ var ts; if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 26 /* LessThanSlashToken */; + return token = 27 /* LessThanSlashToken */; } pos++; - return token = 25 /* LessThanToken */; + return token = 26 /* LessThanToken */; } if (char === 123 /* openBrace */) { pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; } while (pos < end) { pos++; @@ -5643,7 +6221,7 @@ var ts; break; } } - return token = 244 /* JsxText */; + return token = 10 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -5693,39 +6271,42 @@ var ts; return token = 5 /* WhitespaceTrivia */; case 64 /* at */: pos++; - return token = 55 /* AtToken */; + return token = 56 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: pos++; - return token = 37 /* AsteriskToken */; + return token = 38 /* AsteriskToken */; case 123 /* openBrace */: pos++; - return token = 15 /* OpenBraceToken */; + return token = 16 /* OpenBraceToken */; case 125 /* closeBrace */: pos++; - return token = 16 /* CloseBraceToken */; + return token = 17 /* CloseBraceToken */; case 91 /* openBracket */: pos++; - return token = 19 /* OpenBracketToken */; + return token = 20 /* OpenBracketToken */; case 93 /* closeBracket */: pos++; - return token = 20 /* CloseBracketToken */; + return token = 21 /* CloseBracketToken */; case 61 /* equals */: pos++; - return token = 56 /* EqualsToken */; + return token = 57 /* EqualsToken */; case 44 /* comma */: pos++; - return token = 24 /* CommaToken */; + return token = 25 /* CommaToken */; + case 46 /* dot */: + pos++; + return token = 22 /* DotToken */; } - if (isIdentifierStart(ch, 2 /* Latest */)) { + if (isIdentifierStart(ch, 5 /* Latest */)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2 /* Latest */) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5 /* Latest */) && pos < end) { pos++; } - return token = 69 /* Identifier */; + return token = 70 /* Identifier */; } else { return pos += 1, token = 0 /* Unknown */; @@ -5843,15 +6424,16 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str_1 += " "; }, - increaseIndent: function () { }, - decreaseIndent: function () { }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, clear: function () { return str_1 = ""; }, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; } return stringWriters.pop(); @@ -5866,22 +6448,6 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(array1, array2, equaler) { - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } @@ -5906,7 +6472,9 @@ var ts; ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; /* @internal */ function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; /* @internal */ @@ -5935,28 +6503,28 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.flags & 2097152 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 4194304 /* HasAggregatedChildData */)) { + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - var thisNodeOrAnySubNodesHasError = ((node.flags & 524288 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.flags |= 2097152 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propagated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.flags |= 4194304 /* HasAggregatedChildData */; + node.flags |= 262144 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 256 /* SourceFile */) { + while (node && node.kind !== 261 /* SourceFile */) { node = node.parent; } return node; @@ -5964,11 +6532,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 199 /* Block */: - case 227 /* CaseBlock */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: return true; } return false; @@ -6043,7 +6611,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function getTokenPosOfNode(node, sourceFile, includeJsDocComment) { + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { @@ -6052,25 +6620,25 @@ var ts; if (isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); + if (node.kind === 292 /* SyntaxList */ && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; + return node.kind >= 262 /* FirstJSDocNode */ && node.kind <= 288 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; function isJSDocTag(node) { - return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + return node.kind >= 278 /* FirstJSDocTagNode */ && node.kind <= 291 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -6104,14 +6672,14 @@ var ts; function getLiteralText(node, sourceFile, languageVersion) { // Any template literal or string literal with an extended escape // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < 2 /* ES6 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + if (languageVersion < 2 /* ES2015 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { return getQuotedEscapedLiteralText('"', node.text, '"'); } // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { var text = getSourceTextOfNodeFromSourceFile(sourceFile, node); - if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { + if (languageVersion < 2 /* ES2015 */ && isBinaryOrOctalIntegerLiteral(node, text)) { return node.text; } return text; @@ -6121,13 +6689,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: return getQuotedEscapedLiteralText('"', node.text, '"'); - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return getQuotedEscapedLiteralText("`", node.text, "`"); - case 12 /* TemplateHead */: + case 13 /* TemplateHead */: return getQuotedEscapedLiteralText("`", node.text, "${"); - case 13 /* TemplateMiddle */: + case 14 /* TemplateMiddle */: return getQuotedEscapedLiteralText("}", node.text, "${"); - case 14 /* TemplateTail */: + case 15 /* TemplateTail */: return getQuotedEscapedLiteralText("}", node.text, "`"); case 8 /* NumericLiteral */: return node.text; @@ -6169,25 +6737,31 @@ var ts; ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 223 /* VariableDeclaration */ && node.parent.kind === 256 /* CatchClause */; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 225 /* ModuleDeclaration */ && + return node && node.kind === 230 /* ModuleDeclaration */ && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + /** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; 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); + return node.kind === 230 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 256 /* SourceFile */ || - node.kind === 225 /* ModuleDeclaration */ || + return node.kind === 261 /* SourceFile */ || + node.kind === 230 /* ModuleDeclaration */ || isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -6203,32 +6777,36 @@ var ts; return false; } switch (node.parent.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: return ts.isExternalModule(node.parent); - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 252 /* CatchClause */: - case 225 /* ModuleDeclaration */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 261 /* SourceFile */: + case 232 /* CaseBlock */: + case 256 /* CatchClause */: + case 230 /* ModuleDeclaration */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return true; - case 199 /* Block */: + case 204 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return parentNode && !isFunctionLike(parentNode); @@ -6248,13 +6826,6 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 218 /* VariableDeclaration */ && - declaration.parent && - declaration.parent.kind === 252 /* CatchClause */; - } - ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. @@ -6262,12 +6833,42 @@ var ts; return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 70 /* Identifier */: + return name.text; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + case 142 /* ComputedPropertyName */: + if (isStringOrNumericLiteral(name.expression)) { + return name.expression.text; + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 70 /* Identifier */: + return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name); + case 141 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 177 /* PropertyAccessExpression */: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; function createDiagnosticForNode(node, message, arg0, arg1, arg2) { var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { var span = getErrorSpanForNode(sourceFile, node); return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } - ts.createDiagnosticForNode = createDiagnosticForNode; + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -6290,7 +6891,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 199 /* Block */) { + if (node.body && node.body.kind === 204 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -6304,7 +6905,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -6313,23 +6914,23 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 223 /* TypeAliasDeclaration */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 228 /* TypeAliasDeclaration */: errorNode = node.name; break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -6352,7 +6953,7 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 224 /* EnumDeclaration */ && isConst(node); + return node.kind === 229 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -6364,12 +6965,13 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { - return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + function isSuperCall(n) { + return n.kind === 179 /* CallExpression */ && n.expression.kind === 96 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { - return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 207 /* ExpressionStatement */ + && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -6380,63 +6982,58 @@ var ts; return ts.getLeadingCommentRanges(text, node.pos); } ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJsDocComments(node, sourceFileOfNode) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - ts.getJsDocComments = getJsDocComments; - function getJsDocCommentsFromText(node, text) { - var commentRanges = (node.kind === 142 /* Parameter */ || - node.kind === 141 /* TypeParameter */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 180 /* ArrowFunction */) ? + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 144 /* Parameter */ || + node.kind === 143 /* TypeParameter */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 185 /* ArrowFunction */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { - // True if the comment starts with '/**' but not if it is '/**/' + // True if the comment starts with '/**' but not if it is '/**/' + return ts.filter(commentRanges, function (comment) { return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */; - } + }); } - ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.getJSDocCommentRanges = getJSDocCommentRanges; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (154 /* FirstTypeNode */ <= node.kind && node.kind <= 166 /* LastTypeNode */) { + if (156 /* FirstTypeNode */ <= node.kind && node.kind <= 171 /* LastTypeNode */) { return true; } switch (node.kind) { - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: return true; - case 103 /* VoidKeyword */: - return node.parent.kind !== 183 /* VoidExpression */; - case 194 /* ExpressionWithTypeArguments */: + case 104 /* VoidKeyword */: + return node.parent.kind !== 188 /* VoidExpression */; + case 199 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container - case 69 /* Identifier */: + case 70 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 139 /* QualifiedName */: - case 172 /* PropertyAccessExpression */: - case 97 /* ThisKeyword */: + ts.Debug.assert(node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 141 /* QualifiedName */: + case 177 /* PropertyAccessExpression */: + case 98 /* ThisKeyword */: var parent_1 = node.parent; - if (parent_1.kind === 158 /* TypeQuery */) { + if (parent_1.kind === 160 /* TypeQuery */) { return false; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -6445,38 +7042,38 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (154 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 166 /* LastTypeNode */) { + if (156 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 171 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return node === parent_1.constraint; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 144 /* Parameter */: + case 223 /* VariableDeclaration */: return node === parent_1.type; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return node === parent_1.type; - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return node === parent_1.type; - case 177 /* TypeAssertionExpression */: + case 182 /* TypeAssertionExpression */: return node === parent_1.type; - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -6490,23 +7087,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitor(node); - case 227 /* CaseBlock */: - case 199 /* Block */: - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 212 /* WithStatement */: - case 213 /* SwitchStatement */: - case 249 /* CaseClause */: - case 250 /* DefaultClause */: - case 214 /* LabeledStatement */: - case 216 /* TryStatement */: - case 252 /* CatchClause */: + case 232 /* CaseBlock */: + case 204 /* Block */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 217 /* WithStatement */: + case 218 /* SwitchStatement */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: + case 219 /* LabeledStatement */: + case 221 /* TryStatement */: + case 256 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -6516,18 +7113,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -6535,7 +7132,7 @@ var ts; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 140 /* ComputedPropertyName */) { + if (name_5 && name_5.kind === 142 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(name_5.expression); @@ -6551,17 +7148,35 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 162 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 157 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { - case 169 /* BindingElement */: - case 255 /* EnumMember */: - case 142 /* Parameter */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 254 /* ShorthandPropertyAssignment */: - case 218 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 260 /* EnumMember */: + case 144 /* Parameter */: + case 257 /* PropertyAssignment */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 258 /* ShorthandPropertyAssignment */: + case 223 /* VariableDeclaration */: return true; } } @@ -6569,11 +7184,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 149 /* GetAccessor */ || node.kind === 150 /* SetAccessor */); + return node && (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 221 /* ClassDeclaration */ || node.kind === 192 /* ClassExpression */); + return node && (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6582,19 +7197,19 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return true; } return false; @@ -6602,13 +7217,13 @@ var ts; ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return true; } return false; @@ -6616,26 +7231,32 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: return true; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 199 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 204 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; + return node && node.kind === 149 /* MethodDeclaration */ && node.parent.kind === 176 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 149 /* MethodDeclaration */ && + (node.parent.kind === 176 /* ObjectLiteralExpression */ || + node.parent.kind === 197 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6669,7 +7290,7 @@ var ts; return undefined; } switch (node.kind) { - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -6684,9 +7305,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 142 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -6697,37 +7318,37 @@ var ts; node = node.parent; } break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 225 /* ModuleDeclaration */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 224 /* EnumDeclaration */: - case 256 /* SourceFile */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 230 /* ModuleDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 229 /* EnumDeclaration */: + case 261 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6737,26 +7358,26 @@ var ts; return node; } switch (node.kind) { - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: node = node.parent; break; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!stopOnFunctions) { continue; } - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return node; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 142 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -6772,14 +7393,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */) { + if (func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */) { var prev = func; var parent_2 = func.parent; - while (parent_2.kind === 178 /* ParenthesizedExpression */) { + while (parent_2.kind === 183 /* ParenthesizedExpression */) { prev = parent_2; parent_2 = parent_2.parent; } - if (parent_2.kind === 174 /* CallExpression */ && parent_2.expression === prev) { + if (parent_2.kind === 179 /* CallExpression */ && parent_2.expression === prev) { return parent_2; } } @@ -6790,32 +7411,32 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 172 /* PropertyAccessExpression */ || kind === 173 /* ElementAccessExpression */) - && node.expression.kind === 95 /* SuperKeyword */; + return (kind === 177 /* PropertyAccessExpression */ || kind === 178 /* ElementAccessExpression */) + && node.expression.kind === 96 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; function getEntityNameFromTypeNode(node) { - if (node) { - switch (node.kind) { - case 155 /* TypeReference */: - return node.typeName; - case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(isEntityNameExpression(node.expression)); - return node.expression; - case 69 /* Identifier */: - case 139 /* QualifiedName */: - return node; - } + switch (node.kind) { + case 157 /* TypeReference */: + case 272 /* JSDocTypeReference */: + return node.typeName; + case 199 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 70 /* Identifier */: + case 141 /* QualifiedName */: + return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function isCallLikeExpression(node) { switch (node.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 176 /* TaggedTemplateExpression */: - case 143 /* Decorator */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 181 /* TaggedTemplateExpression */: + case 145 /* Decorator */: return true; default: return false; @@ -6823,7 +7444,7 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function getInvokedExpression(node) { - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -6832,25 +7453,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: // classes are valid targets return true; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 221 /* ClassDeclaration */; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: + return node.parent.kind === 226 /* ClassDeclaration */; + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && node.parent.kind === 221 /* ClassDeclaration */; - case 142 /* Parameter */: + && node.parent.kind === 226 /* ClassDeclaration */; + case 144 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return node.parent.body !== undefined - && (node.parent.kind === 148 /* Constructor */ - || node.parent.kind === 147 /* MethodDeclaration */ - || node.parent.kind === 150 /* SetAccessor */) - && node.parent.parent.kind === 221 /* ClassDeclaration */; + && (node.parent.kind === 150 /* Constructor */ + || node.parent.kind === 149 /* MethodDeclaration */ + || node.parent.kind === 152 /* SetAccessor */) + && node.parent.parent.kind === 226 /* ClassDeclaration */; } return false; } @@ -6866,19 +7487,19 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 147 /* MethodDeclaration */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 152 /* SetAccessor */: return ts.forEach(node.parameters, nodeIsDecorated); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 243 /* JsxOpeningElement */ || - parent.kind === 242 /* JsxSelfClosingElement */ || - parent.kind === 245 /* JsxClosingElement */) { + if (parent.kind === 248 /* JsxOpeningElement */ || + parent.kind === 247 /* JsxSelfClosingElement */ || + parent.kind === 249 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -6886,98 +7507,99 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - case 10 /* RegularExpressionLiteral */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 176 /* TaggedTemplateExpression */: - case 195 /* AsExpression */: - case 177 /* TypeAssertionExpression */: - case 196 /* NonNullExpression */: - case 178 /* ParenthesizedExpression */: - case 179 /* FunctionExpression */: - case 192 /* ClassExpression */: - case 180 /* ArrowFunction */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 182 /* TypeOfExpression */: - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - case 187 /* BinaryExpression */: - case 188 /* ConditionalExpression */: - case 191 /* SpreadElementExpression */: - case 189 /* TemplateExpression */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 193 /* OmittedExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 190 /* YieldExpression */: - case 184 /* AwaitExpression */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: + case 11 /* RegularExpressionLiteral */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 181 /* TaggedTemplateExpression */: + case 200 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 201 /* NonNullExpression */: + case 183 /* ParenthesizedExpression */: + case 184 /* FunctionExpression */: + case 197 /* ClassExpression */: + case 185 /* ArrowFunction */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 187 /* TypeOfExpression */: + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + case 192 /* BinaryExpression */: + case 193 /* ConditionalExpression */: + case 196 /* SpreadElement */: + case 194 /* TemplateExpression */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 198 /* OmittedExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 195 /* YieldExpression */: + case 189 /* AwaitExpression */: return true; - case 139 /* QualifiedName */: - while (node.parent.kind === 139 /* QualifiedName */) { + case 141 /* QualifiedName */: + while (node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 158 /* TypeQuery */ || isJSXTagName(node); - case 69 /* Identifier */: - if (node.parent.kind === 158 /* TypeQuery */ || isJSXTagName(node)) { + return node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node); + case 70 /* Identifier */: + if (node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node)) { return true; } // fall through case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: var parent_3 = node.parent; switch (parent_3.kind) { - case 218 /* VariableDeclaration */: - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 255 /* EnumMember */: - case 253 /* PropertyAssignment */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 260 /* EnumMember */: + case 257 /* PropertyAssignment */: + case 174 /* BindingElement */: return parent_3.initializer === node; - case 202 /* ExpressionStatement */: - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 211 /* ReturnStatement */: - case 212 /* WithStatement */: - case 213 /* SwitchStatement */: - case 249 /* CaseClause */: - case 215 /* ThrowStatement */: - case 213 /* SwitchStatement */: + case 207 /* ExpressionStatement */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 216 /* ReturnStatement */: + case 217 /* WithStatement */: + case 218 /* SwitchStatement */: + case 253 /* CaseClause */: + case 220 /* ThrowStatement */: + case 218 /* SwitchStatement */: return parent_3.expression === node; - case 206 /* ForStatement */: + case 211 /* ForStatement */: var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 219 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 224 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224 /* VariableDeclarationList */) || forInStatement.expression === node; - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return node === parent_3.expression; - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return node === parent_3.expression; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return node === parent_3.expression; - case 143 /* Decorator */: - case 248 /* JsxExpression */: - case 247 /* JsxSpreadAttribute */: + case 145 /* Decorator */: + case 252 /* JsxExpression */: + case 251 /* JsxSpreadAttribute */: + case 259 /* SpreadAssignment */: return true; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); default: if (isPartOfExpression(parent_3)) { @@ -6988,12 +7610,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7001,7 +7617,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */; + return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -7010,7 +7626,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 240 /* ExternalModuleReference */; + return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 245 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -7018,7 +7634,7 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 1048576 /* JavaScriptFile */); + return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; /** @@ -7028,8 +7644,8 @@ var ts; */ function isRequireCall(expression, checkArgumentIsStringLiteral) { // of the form 'require("name")' - var isRequire = expression.kind === 174 /* CallExpression */ && - expression.expression.kind === 69 /* Identifier */ && + var isRequire = expression.kind === 179 /* CallExpression */ && + expression.expression.kind === 70 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1; return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); @@ -7044,9 +7660,9 @@ var ts; * 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 */) { + if (s.valueDeclaration && s.valueDeclaration.kind === 223 /* VariableDeclaration */) { var declaration = s.valueDeclaration; - return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + return declaration.initializer && declaration.initializer.kind === 184 /* FunctionExpression */; } return false; } @@ -7057,15 +7673,15 @@ var ts; if (!isInJavaScriptFile(expression)) { return 0 /* None */; } - if (expression.kind !== 187 /* BinaryExpression */) { + if (expression.kind !== 192 /* BinaryExpression */) { return 0 /* None */; } var expr = expression; - if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 172 /* PropertyAccessExpression */) { + if (expr.operatorToken.kind !== 57 /* EqualsToken */ || expr.left.kind !== 177 /* PropertyAccessExpression */) { return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 69 /* Identifier */) { + if (lhs.expression.kind === 70 /* Identifier */) { var lhsId = lhs.expression; if (lhsId.text === "exports") { // exports.name = expr @@ -7076,13 +7692,13 @@ var ts; return 2 /* ModuleExports */; } } - else if (lhs.expression.kind === 97 /* ThisKeyword */) { + else if (lhs.expression.kind === 98 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 172 /* PropertyAccessExpression */) { + else if (lhs.expression.kind === 177 /* PropertyAccessExpression */) { // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 69 /* Identifier */) { + if (innerPropertyAccess.expression.kind === 70 /* Identifier */) { // module.exports.name = expr var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { @@ -7097,35 +7713,35 @@ var ts; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 230 /* ImportDeclaration */) { + if (node.kind === 235 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 240 /* ExternalModuleReference */) { + if (reference.kind === 245 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 236 /* ExportDeclaration */) { + if (node.kind === 241 /* ExportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 225 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (node.kind === 230 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237 /* NamespaceImport */) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 230 /* ImportDeclaration */ + return node.kind === 235 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } @@ -7133,13 +7749,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 142 /* Parameter */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 254 /* ShorthandPropertyAssignment */: - case 253 /* PropertyAssignment */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 144 /* Parameter */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 258 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -7147,132 +7763,103 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 269 /* JSDocFunctionType */ && + return node.kind === 274 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 271 /* JSDocConstructorType */; + node.parameters[0].type.kind === 276 /* JSDocConstructorType */; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getJSDocTag(node, kind, checkParentVariableStatement) { - if (!node) { - return undefined; - } - var jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_1 = jsDocTags; _i < jsDocTags_1.length; _i++) { - var tag = jsDocTags_1[_i]; - if (tag.kind === kind) { - return tag; - } - } + function getCommentsFromJSDoc(node) { + return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } - function append(previous, additional) { - if (additional) { - if (!previous) { - previous = []; - } - for (var _i = 0, additional_1 = additional; _i < additional_1.length; _i++) { - var x = additional_1[_i]; - previous.push(x); - } - } - return previous; - } - function getJSDocComments(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { return ts.map(docs, function (doc) { return doc.comment; }); }, function (tags) { return ts.map(tags, function (tag) { return tag.comment; }); }); - } - ts.getJSDocComments = getJSDocComments; - function getJSDocTags(node, checkParentVariableStatement) { - return getJSDocs(node, checkParentVariableStatement, function (docs) { + ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function getJSDocTags(node, kind) { + var docs = getJSDocs(node); + if (docs) { var result = []; for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { var doc = docs_1[_i]; - if (doc.tags) { - result.push.apply(result, doc.tags); + if (doc.kind === 281 /* JSDocParameterTag */) { + if (doc.kind === kind) { + result.push(doc); + } + } + else { + result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; })); } } return result; - }, function (tags) { return tags; }); + } } - function getJSDocs(node, checkParentVariableStatement, getDocs, getTags) { - // TODO: Get rid of getJsDocComments and friends (note the lowercase 's' in Js) - // TODO: A lot of this work should be cached, maybe. I guess it's only used in services right now... - var result = undefined; - // prepend documentation from parent sources - if (checkParentVariableStatement) { + function getFirstJSDocTag(node, kind) { + return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + } + function getJSDocs(node) { + var cache = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + function getJSDocsWorker(node) { + var parent = node.parent; // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** // * @param {number} name // * @returns {number} // */ // var x = function(name) { return name.length; } - var isInitializerOfVariableDeclarationInStatement = isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === 200 /* VariableStatement */; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 205 /* VariableStatement */; var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === 200 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + parent.parent.kind === 205 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); - } - if (node.kind === 225 /* ModuleDeclaration */ && - node.parent && node.parent.kind === 225 /* ModuleDeclaration */) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } // Also recognize when the node is the RHS of an assignment expression - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 /* BinaryExpression */ && - parent_4.operatorToken.kind === 56 /* EqualsToken */ && - parent_4.parent.kind === 202 /* ExpressionStatement */; + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 192 /* BinaryExpression */ && + parent.operatorToken.kind === 57 /* EqualsToken */ && + parent.parent.kind === 207 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253 /* PropertyAssignment */; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + var isModuleDeclaration = node.kind === 230 /* ModuleDeclaration */ && + parent && parent.kind === 230 /* ModuleDeclaration */; + var isPropertyAssignmentExpression = parent && parent.kind === 257 /* PropertyAssignment */; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } // Pull parameter comments from declaring function as well - if (node.kind === 142 /* Parameter */) { - var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + if (node.kind === 144 /* Parameter */) { + cache = ts.concatenate(cache, getJSDocParameterTags(node)); } - } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, /*checkParentVariableStatement*/ false, getDocs, getTags)); - } - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); - } - else { - return getDocs(node.jsDocComments); + if (isVariableLike(node) && node.initializer) { + cache = ts.concatenate(cache, node.initializer.jsDoc); } + cache = ts.concatenate(cache, node.jsDoc); } - return result; } - function getJSDocParameterTag(param, checkParentVariableStatement) { + function getJSDocParameterTags(param) { + if (!isParameter(param)) { + return undefined; + } var func = param.parent; - var tags = getJSDocTags(func, checkParentVariableStatement); + var tags = getJSDocTags(func, 281 /* JSDocParameterTag */); if (!param.name) { // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */; }); + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */; }); if (paramTags && 0 <= i && i < paramTags.length) { return [paramTags[i]]; } } - else if (param.name.kind === 69 /* Identifier */) { + else if (param.name.kind === 70 /* Identifier */) { var name_6 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); - if (paramTags) { - return paramTags; - } + return ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */ && tag.parameterName.text === name_6; }); } else { // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines @@ -7280,40 +7867,30 @@ var ts; return undefined; } } - function getJSDocTypeTag(node) { - return getJSDocTag(node, 277 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); + ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 283 /* JSDocTypeTag */); + if (!tag && node.kind === 144 /* Parameter */) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; } - ts.getJSDocTypeTag = getJSDocTypeTag; + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 280 /* JSDocAugmentsTag */); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 276 /* JSDocReturnTag */, /*checkParentVariableStatement*/ true); + return getFirstJSDocTag(node, 282 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 278 /* JSDocTemplateTag */, /*checkParentVariableStatement*/ false); + return getFirstJSDocTag(node, 284 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; - function getCorrespondingJSDocParameterTag(parameter) { - if (parameter.name && parameter.name.kind === 69 /* Identifier */) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - var parameterName = parameter.name.text; - var jsDocTags = getJSDocTags(parameter.parent, /*checkParentVariableStatement*/ true); - if (!jsDocTags) { - return undefined; - } - for (var _i = 0, jsDocTags_2 = jsDocTags; _i < jsDocTags_2.length; _i++) { - var tag = jsDocTags_2[_i]; - if (tag.kind === 275 /* JSDocParameterTag */) { - var parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } - } - } - return undefined; - } - ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -7323,14 +7900,11 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 1048576 /* JavaScriptFile */)) { - if (node.type && node.type.kind === 270 /* JSDocVariadicType */) { + if (node && (node.flags & 65536 /* JavaScriptFile */)) { + if (node.type && node.type.kind === 275 /* JSDocVariadicType */ || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275 /* JSDocVariadicType */; })) { return true; } - var paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 270 /* JSDocVariadicType */; - } } return isDeclaredRestParam(node); } @@ -7339,29 +7913,53 @@ var ts; return node && node.dotDotDotToken !== undefined; } ts.isDeclaredRestParam = isDeclaredRestParam; + var AssignmentKind; + (function (AssignmentKind) { + AssignmentKind[AssignmentKind["None"] = 0] = "None"; + AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; + AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; + })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 192 /* BinaryExpression */: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 57 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + var unaryOperator = parent.operator; + return unaryOperator === 42 /* PlusPlusToken */ || unaryOperator === 43 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 183 /* ParenthesizedExpression */: + case 175 /* ArrayLiteralExpression */: + case 196 /* SpreadElement */: + node = parent; + break; + case 258 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return 0 /* None */; + } + // Fall through + case 257 /* PropertyAssignment */: + node = parent.parent; + break; + default: + return 0 /* None */; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { - while (node.parent.kind === 178 /* ParenthesizedExpression */) { - node = node.parent; - } - while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 /* ArrayLiteralExpression */ || parent_5.kind === 191 /* SpreadElementExpression */) { - node = parent_5; - continue; - } - if (parent_5.kind === 253 /* PropertyAssignment */ || parent_5.kind === 254 /* ShorthandPropertyAssignment */) { - node = parent_5.parent; - continue; - } - return parent_5.kind === 187 /* BinaryExpression */ && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && - parent_5.initializer === node; - } + return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; function isNodeDescendantOf(node, ancestor) { @@ -7375,7 +7973,7 @@ var ts; ts.isNodeDescendantOf = isNodeDescendantOf; function isInAmbientContext(node) { while (node) { - if (hasModifier(node, 2 /* Ambient */) || (node.kind === 256 /* SourceFile */ && node.isDeclarationFile)) { + if (hasModifier(node, 2 /* Ambient */) || (node.kind === 261 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -7385,11 +7983,11 @@ var ts; ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { - if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { + if (name.kind !== 70 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { return false; } var parent = name.parent; - if (parent.kind === 234 /* ImportSpecifier */ || parent.kind === 238 /* ExportSpecifier */) { + if (parent.kind === 239 /* ImportSpecifier */ || parent.kind === 243 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -7402,7 +8000,7 @@ var ts; ts.isDeclarationName = isDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 140 /* ComputedPropertyName */ && + node.parent.kind === 142 /* ComputedPropertyName */ && isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -7410,31 +8008,31 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 255 /* EnumMember */: - case 253 /* PropertyAssignment */: - case 172 /* PropertyAccessExpression */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 260 /* EnumMember */: + case 257 /* PropertyAssignment */: + case 177 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 139 /* QualifiedName */) { + while (parent.kind === 141 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 158 /* TypeQuery */; + return parent.kind === 160 /* TypeQuery */; } return false; - case 169 /* BindingElement */: - case 234 /* ImportSpecifier */: + case 174 /* BindingElement */: + case 239 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -7450,13 +8048,13 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 228 /* NamespaceExportDeclaration */ || - node.kind === 231 /* ImportClause */ && !!node.name || - node.kind === 232 /* NamespaceImport */ || - node.kind === 234 /* ImportSpecifier */ || - node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 234 /* ImportEqualsDeclaration */ || + node.kind === 233 /* NamespaceExportDeclaration */ || + node.kind === 236 /* ImportClause */ && !!node.name || + node.kind === 237 /* NamespaceImport */ || + node.kind === 239 /* ImportSpecifier */ || + node.kind === 243 /* ExportSpecifier */ || + node.kind === 240 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7464,17 +8062,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 106 /* ImplementsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 107 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + var heritageClause = getHeritageClause(node.heritageClauses, 84 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -7542,7 +8140,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 /* FirstKeyword */ <= token && token <= 138 /* LastKeyword */; + return 71 /* FirstKeyword */ <= token && token <= 140 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -7553,8 +8151,10 @@ var ts; return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; - function isStringOrNumericLiteral(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; /** @@ -7569,8 +8169,8 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 140 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression.kind) && + return name.kind === 142 /* ComputedPropertyName */ && + !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -7584,10 +8184,10 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 142 /* Parameter */) { + if (name.kind === 70 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 144 /* Parameter */) { return name.text; } - if (name.kind === 140 /* ComputedPropertyName */) { + if (name.kind === 142 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -7608,22 +8208,26 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 69 /* Identifier */ && node.text === "Symbol"; + return node.kind === 70 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.text === "push" || node.text === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isModifierKind(token) { switch (token) { - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 122 /* DeclareKeyword */: - case 77 /* DefaultKeyword */: - case 82 /* ExportKeyword */: - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 128 /* ReadonlyKeyword */: - case 113 /* StaticKeyword */: + case 116 /* AbstractKeyword */: + case 119 /* AsyncKeyword */: + case 75 /* ConstKeyword */: + case 123 /* DeclareKeyword */: + case 78 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 130 /* ReadonlyKeyword */: + case 114 /* StaticKeyword */: return true; } return false; @@ -7631,11 +8235,11 @@ var ts; ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 142 /* Parameter */; + return root.kind === 144 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 169 /* BindingElement */) { + while (node.kind === 174 /* BindingElement */) { node = node.parent.parent; } return node; @@ -7643,35 +8247,29 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 148 /* Constructor */ - || kind === 179 /* FunctionExpression */ - || kind === 220 /* FunctionDeclaration */ - || kind === 180 /* ArrowFunction */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 225 /* ModuleDeclaration */ - || kind === 256 /* SourceFile */; + return kind === 150 /* Constructor */ + || kind === 184 /* FunctionExpression */ + || kind === 225 /* FunctionDeclaration */ + || kind === 185 /* ArrowFunction */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 230 /* ModuleDeclaration */ + || kind === 261 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - function getOriginalNode(node) { + function getOriginalNode(node, nodeTest) { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; /** @@ -7711,45 +8309,45 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; Associativity[Associativity["Right"] = 1] = "Right"; - })(ts.Associativity || (ts.Associativity = {})); - var Associativity = ts.Associativity; + })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 175 /* NewExpression */: + case 180 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 185 /* PrefixUnaryExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 184 /* AwaitExpression */: - case 188 /* ConditionalExpression */: - case 190 /* YieldExpression */: + case 190 /* PrefixUnaryExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 189 /* AwaitExpression */: + case 193 /* ConditionalExpression */: + case 195 /* YieldExpression */: return 1 /* Right */; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (operator) { - case 38 /* AsteriskAsteriskToken */: - case 56 /* EqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 67 /* BarEqualsToken */: + case 39 /* AsteriskAsteriskToken */: + case 57 /* EqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 68 /* BarEqualsToken */: return 1 /* Right */; } } @@ -7758,15 +8356,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 175 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 187 /* BinaryExpression */) { + if (expression.kind === 192 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 185 /* PrefixUnaryExpression */ || expression.kind === 186 /* PostfixUnaryExpression */) { + else if (expression.kind === 190 /* PrefixUnaryExpression */ || expression.kind === 191 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -7776,106 +8374,107 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 69 /* Identifier */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 70 /* Identifier */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 189 /* TemplateExpression */: - case 178 /* ParenthesizedExpression */: - case 193 /* OmittedExpression */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 197 /* ClassExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 11 /* RegularExpressionLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 194 /* TemplateExpression */: + case 183 /* ParenthesizedExpression */: + case 198 /* OmittedExpression */: + case 297 /* RawExpression */: return 19; - case 176 /* TaggedTemplateExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 181 /* TaggedTemplateExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: return 18; - case 175 /* NewExpression */: + case 180 /* NewExpression */: return hasArguments ? 18 : 17; - case 174 /* CallExpression */: + case 179 /* CallExpression */: return 17; - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return 16; - case 185 /* PrefixUnaryExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 181 /* DeleteExpression */: - case 184 /* AwaitExpression */: + case 190 /* PrefixUnaryExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 186 /* DeleteExpression */: + case 189 /* AwaitExpression */: return 15; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (operatorKind) { - case 49 /* ExclamationToken */: - case 50 /* TildeToken */: + case 50 /* ExclamationToken */: + case 51 /* TildeToken */: return 15; - case 38 /* AsteriskAsteriskToken */: - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: + case 39 /* AsteriskAsteriskToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: return 14; - case 35 /* PlusToken */: - case 36 /* MinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: return 13; - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 25 /* LessThanToken */: - case 28 /* LessThanEqualsToken */: - case 27 /* GreaterThanToken */: - case 29 /* GreaterThanEqualsToken */: - case 90 /* InKeyword */: - case 91 /* InstanceOfKeyword */: + case 26 /* LessThanToken */: + case 29 /* LessThanEqualsToken */: + case 28 /* GreaterThanToken */: + case 30 /* GreaterThanEqualsToken */: + case 91 /* InKeyword */: + case 92 /* InstanceOfKeyword */: return 11; - case 30 /* EqualsEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return 10; - case 46 /* AmpersandToken */: + case 47 /* AmpersandToken */: return 9; - case 48 /* CaretToken */: + case 49 /* CaretToken */: return 8; - case 47 /* BarToken */: + case 48 /* BarToken */: return 7; - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return 6; - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return 5; - case 56 /* EqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 67 /* BarEqualsToken */: + case 57 /* EqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 68 /* BarEqualsToken */: return 3; - case 24 /* CommaToken */: + case 25 /* CommaToken */: return 0; default: return -1; } - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return 4; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return 2; - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return 1; default: return -1; @@ -8125,24 +8724,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,23 +8742,38 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - var sourceFiles = host.getSourceFiles(); + var sourceFiles = getAllEmittableSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, isNonDeclarationFile); + var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); }); + } + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles(); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. */ + function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) { + return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); }); + } + ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory; function isNonDeclarationFile(sourceFile) { return !isDeclarationFile(sourceFile); } + /** + * Whether a file should be emitted in a non-`--outFile` case. + * Don't emit if source file is a declaration file, or was located under node_modules + */ + function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + } function isBundleEmitNonExternalModule(sourceFile) { - return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); + return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } /** * Iterates over each source file to emit. The source files are expected to have been @@ -8184,11 +8786,11 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { @@ -8217,10 +8819,10 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } - function onBundledEmit(host, sourceFiles) { + function onBundledEmit(sourceFiles) { if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -8242,18 +8844,17 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { onBundledEmit(host); } else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { var sourceFile = sourceFiles_3[_i]; - // Don't emit if source file is a declaration file, or was located under node_modules - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) { onSingleFileEmit(host, sourceFile); } } @@ -8275,20 +8876,21 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with // --module or --target es6 specified. Files included by searching under node_modules are also not emitted. - var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8898,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8325,21 +8927,41 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 148 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 150 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 70 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 98 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8347,10 +8969,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 149 /* GetAccessor */) { + if (accessor.kind === 151 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 150 /* SetAccessor */) { + else if (accessor.kind === 152 /* SetAccessor */) { setAccessor = accessor; } else { @@ -8359,7 +8981,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 149 /* GetAccessor */ || member.kind === 150 /* SetAccessor */) + if ((member.kind === 151 /* GetAccessor */ || member.kind === 152 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -8370,10 +8992,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 149 /* GetAccessor */ && !getAccessor) { + if (member.kind === 151 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 150 /* SetAccessor */ && !setAccessor) { + if (member.kind === 152 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -8600,7 +9222,7 @@ var ts; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 /* NestedNamespace */) { + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; @@ -8609,47 +9231,53 @@ var ts; ts.getModifierFlags = getModifierFlags; function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 32 /* Static */; - case 112 /* PublicKeyword */: return 4 /* Public */; - case 111 /* ProtectedKeyword */: return 16 /* Protected */; - case 110 /* PrivateKeyword */: return 8 /* Private */; - case 115 /* AbstractKeyword */: return 128 /* Abstract */; - case 82 /* ExportKeyword */: return 1 /* Export */; - case 122 /* DeclareKeyword */: return 2 /* Ambient */; - case 74 /* ConstKeyword */: return 2048 /* Const */; - case 77 /* DefaultKeyword */: return 512 /* Default */; - case 118 /* AsyncKeyword */: return 256 /* Async */; - case 128 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 114 /* StaticKeyword */: return 32 /* Static */; + case 113 /* PublicKeyword */: return 4 /* Public */; + case 112 /* ProtectedKeyword */: return 16 /* Protected */; + case 111 /* PrivateKeyword */: return 8 /* Private */; + case 116 /* AbstractKeyword */: return 128 /* Abstract */; + case 83 /* ExportKeyword */: return 1 /* Export */; + case 123 /* DeclareKeyword */: return 2 /* Ambient */; + case 75 /* ConstKeyword */: return 2048 /* Const */; + case 78 /* DefaultKeyword */: return 512 /* Default */; + case 119 /* AsyncKeyword */: return 256 /* Async */; + case 130 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 52 /* BarBarToken */ - || token === 51 /* AmpersandAmpersandToken */ - || token === 49 /* ExclamationToken */; + return token === 53 /* BarBarToken */ + || token === 52 /* AmpersandAmpersandToken */ + || token === 50 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; + return token >= 57 /* FirstAssignment */ && token <= 69 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 194 /* ExpressionWithTypeArguments */ && - node.parent.token === 83 /* ExtendsKeyword */ && + if (node.kind === 199 /* ExpressionWithTypeArguments */ && + node.parent.token === 84 /* ExtendsKeyword */ && isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 57 /* EqualsToken */ + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === 56 /* EqualsToken */) { - var kind = node.left.kind; - return kind === 171 /* ObjectLiteralExpression */ - || kind === 170 /* ArrayLiteralExpression */; - } + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + var kind = node.left.kind; + return kind === 176 /* ObjectLiteralExpression */ + || kind === 175 /* ArrayLiteralExpression */; } return false; } @@ -8661,7 +9289,7 @@ var ts; } ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { return true; } else if (isPropertyAccessExpression(node)) { @@ -8676,21 +9304,21 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isEntityNameExpression(node) { - return node.kind === 69 /* Identifier */ || - node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 70 /* Identifier */ || + node.kind === 177 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 171 /* ObjectLiteralExpression */) { + if (kind === 176 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 170 /* ArrayLiteralExpression */) { + if (kind === 175 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -8700,14 +9328,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - 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; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8747,47 +9367,6 @@ var ts; } return output; } - /** - * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph - * as the fallback implementation does not check for circular references by default. - */ - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - /** - * Serialize an object graph into a JSON string. - */ - function stringifyFallback(value) { - // JSON.stringify returns `undefined` here, instead of the string "undefined". - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -8820,12 +9399,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8856,49 +9429,49 @@ var ts; var kind = node.kind; if (kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 10 /* RegularExpressionLiteral */ - || kind === 11 /* NoSubstitutionTemplateLiteral */ - || kind === 69 /* Identifier */ - || kind === 97 /* ThisKeyword */ - || kind === 95 /* SuperKeyword */ - || kind === 99 /* TrueKeyword */ - || kind === 84 /* FalseKeyword */ - || kind === 93 /* NullKeyword */) { + || kind === 11 /* RegularExpressionLiteral */ + || kind === 12 /* NoSubstitutionTemplateLiteral */ + || kind === 70 /* Identifier */ + || kind === 98 /* ThisKeyword */ + || kind === 96 /* SuperKeyword */ + || kind === 100 /* TrueKeyword */ + || kind === 85 /* FalseKeyword */ + || kind === 94 /* NullKeyword */) { return true; } - else if (kind === 172 /* PropertyAccessExpression */) { + else if (kind === 177 /* PropertyAccessExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 173 /* ElementAccessExpression */) { + else if (kind === 178 /* ElementAccessExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1) && isSimpleExpressionWorker(node.argumentExpression, depth + 1); } - else if (kind === 185 /* PrefixUnaryExpression */ - || kind === 186 /* PostfixUnaryExpression */) { + else if (kind === 190 /* PrefixUnaryExpression */ + || kind === 191 /* PostfixUnaryExpression */) { return isSimpleExpressionWorker(node.operand, depth + 1); } - else if (kind === 187 /* BinaryExpression */) { - return node.operatorToken.kind !== 38 /* AsteriskAsteriskToken */ + else if (kind === 192 /* BinaryExpression */) { + return node.operatorToken.kind !== 39 /* AsteriskAsteriskToken */ && isSimpleExpressionWorker(node.left, depth + 1) && isSimpleExpressionWorker(node.right, depth + 1); } - else if (kind === 188 /* ConditionalExpression */) { + else if (kind === 193 /* ConditionalExpression */) { return isSimpleExpressionWorker(node.condition, depth + 1) && isSimpleExpressionWorker(node.whenTrue, depth + 1) && isSimpleExpressionWorker(node.whenFalse, depth + 1); } - else if (kind === 183 /* VoidExpression */ - || kind === 182 /* TypeOfExpression */ - || kind === 181 /* DeleteExpression */) { + else if (kind === 188 /* VoidExpression */ + || kind === 187 /* TypeOfExpression */ + || kind === 186 /* DeleteExpression */) { return isSimpleExpressionWorker(node.expression, depth + 1); } - else if (kind === 170 /* ArrayLiteralExpression */) { + else if (kind === 175 /* ArrayLiteralExpression */) { return node.elements.length === 0; } - else if (kind === 171 /* ObjectLiteralExpression */) { + else if (kind === 176 /* ObjectLiteralExpression */) { return node.properties.length === 0; } - else if (kind === 174 /* CallExpression */) { + else if (kind === 179 /* CallExpression */) { if (!isSimpleExpressionWorker(node.expression, depth + 1)) { return false; } @@ -8938,7 +9511,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,67 +9627,25 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; - function collectExternalModuleInfo(sourceFile, resolver) { - var externalImports = []; - var exportSpecifiers = ts.createMap(); - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 230 /* ImportDeclaration */: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - case 229 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 240 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - case 236 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_8 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_8] || (exportSpecifiers[name_8] = [])).push(specifier); - } - } - break; - case 235 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; } } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues }; + return false; } - ts.collectExternalModuleInfo = collectExternalModuleInfo; + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; function getInitializedVariables(node) { return ts.filter(node.declarations, isInitializedVariable); } @@ -9129,7 +9660,7 @@ var ts; if (node.symbol) { for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 /* ClassDeclaration */ && declaration !== node) { + if (declaration.kind === 226 /* ClassDeclaration */ && declaration !== node) { return true; } } @@ -9159,15 +9690,15 @@ var ts; ts.isNodeArray = isNodeArray; // Literals function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 11 /* NoSubstitutionTemplateLiteral */; + return node.kind === 12 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; + return 8 /* FirstLiteralToken */ <= kind && kind <= 12 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; + return kind === 9 /* StringLiteral */ || kind === 12 /* NoSubstitutionTemplateLiteral */; } ts.isTextualLiteralKind = isTextualLiteralKind; function isLiteralExpression(node) { @@ -9176,21 +9707,22 @@ var ts; ts.isLiteralExpression = isLiteralExpression; // Pseudo-literals function isTemplateLiteralKind(kind) { - return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; + return 12 /* FirstTemplateToken */ <= kind && kind <= 15 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ - || kind === 14 /* TemplateTail */; + function isTemplateHead(node) { + return node.kind === 13 /* TemplateHead */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 14 /* TemplateMiddle */ + || kind === 15 /* TemplateTail */; } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { - return node.kind === 69 /* Identifier */; + return node.kind === 70 /* Identifier */; } ts.isIdentifier = isIdentifier; function isGeneratedIdentifier(node) { @@ -9205,90 +9737,91 @@ var ts; ts.isModifier = isModifier; // Names function isQualifiedName(node) { - return node.kind === 139 /* QualifiedName */; + return node.kind === 141 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 140 /* ComputedPropertyName */; + return node.kind === 142 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; function isEntityName(node) { var kind = node.kind; - return kind === 139 /* QualifiedName */ - || kind === 69 /* Identifier */; + return kind === 141 /* QualifiedName */ + || kind === 70 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ + return kind === 70 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 140 /* ComputedPropertyName */; + || kind === 142 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isModuleName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ + return kind === 70 /* Identifier */ || kind === 9 /* StringLiteral */; } ts.isModuleName = isModuleName; function isBindingName(node) { var kind = node.kind; - return kind === 69 /* Identifier */ - || kind === 167 /* ObjectBindingPattern */ - || kind === 168 /* ArrayBindingPattern */; + return kind === 70 /* Identifier */ + || kind === 172 /* ObjectBindingPattern */ + || kind === 173 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Signature elements function isTypeParameter(node) { - return node.kind === 141 /* TypeParameter */; + return node.kind === 143 /* TypeParameter */; } ts.isTypeParameter = isTypeParameter; function isParameter(node) { - return node.kind === 142 /* Parameter */; + return node.kind === 144 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 143 /* Decorator */; + return node.kind === 145 /* Decorator */; } ts.isDecorator = isDecorator; // Type members function isMethodDeclaration(node) { - return node.kind === 147 /* MethodDeclaration */; + return node.kind === 149 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isClassElement(node) { var kind = node.kind; - return kind === 148 /* Constructor */ - || kind === 145 /* PropertyDeclaration */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 153 /* IndexSignature */ - || kind === 198 /* SemicolonClassElement */; + return kind === 150 /* Constructor */ + || kind === 147 /* PropertyDeclaration */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 155 /* IndexSignature */ + || kind === 203 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 253 /* PropertyAssignment */ - || kind === 254 /* ShorthandPropertyAssignment */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 239 /* MissingDeclaration */; + return kind === 257 /* PropertyAssignment */ + || kind === 258 /* ShorthandPropertyAssignment */ + || kind === 259 /* SpreadAssignment */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 244 /* MissingDeclaration */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) - || kind === 117 /* AnyKeyword */ - || kind === 130 /* NumberKeyword */ - || kind === 120 /* BooleanKeyword */ - || kind === 132 /* StringKeyword */ - || kind === 133 /* SymbolKeyword */ - || kind === 103 /* VoidKeyword */ - || kind === 127 /* NeverKeyword */ - || kind === 194 /* ExpressionWithTypeArguments */; + return (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */) + || kind === 118 /* AnyKeyword */ + || kind === 132 /* NumberKeyword */ + || kind === 121 /* BooleanKeyword */ + || kind === 134 /* StringKeyword */ + || kind === 135 /* SymbolKeyword */ + || kind === 104 /* VoidKeyword */ + || kind === 129 /* NeverKeyword */ + || kind === 199 /* ExpressionWithTypeArguments */; } /** * Node test that determines whether a node is a valid type node. @@ -9300,98 +9833,166 @@ var ts; } ts.isTypeNode = isTypeNode; // Binding patterns + function isArrayBindingPattern(node) { + return node.kind === 173 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isObjectBindingPattern(node) { + return node.kind === 172 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 168 /* ArrayBindingPattern */ - || kind === 167 /* ObjectBindingPattern */; + return kind === 173 /* ArrayBindingPattern */ + || kind === 172 /* ObjectBindingPattern */; } return false; } ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 175 /* ArrayLiteralExpression */ + || kind === 176 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; function isBindingElement(node) { - return node.kind === 169 /* BindingElement */; + return node.kind === 174 /* BindingElement */; } ts.isBindingElement = isBindingElement; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 169 /* BindingElement */ - || kind === 193 /* OmittedExpression */; + return kind === 174 /* BindingElement */ + || kind === 198 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 174 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 172 /* ObjectBindingPattern */: + case 176 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; // Expression + function isArrayLiteralExpression(node) { + return node.kind === 175 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 176 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 172 /* PropertyAccessExpression */; + return node.kind === 177 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 173 /* ElementAccessExpression */; + return node.kind === 178 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isBinaryExpression(node) { - return node.kind === 187 /* BinaryExpression */; + return node.kind === 192 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 188 /* ConditionalExpression */; + return node.kind === 193 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isCallExpression(node) { - return node.kind === 174 /* CallExpression */; + return node.kind === 179 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; - return kind === 189 /* TemplateExpression */ - || kind === 11 /* NoSubstitutionTemplateLiteral */; + return kind === 194 /* TemplateExpression */ + || kind === 12 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; - function isSpreadElementExpression(node) { - return node.kind === 191 /* SpreadElementExpression */; + ts.isTemplateLiteral = isTemplateLiteral; + function isSpreadExpression(node) { + return node.kind === 196 /* SpreadElement */; } - ts.isSpreadElementExpression = isSpreadElementExpression; + ts.isSpreadExpression = isSpreadExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 194 /* ExpressionWithTypeArguments */; + return node.kind === 199 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isLeftHandSideExpressionKind(kind) { - return kind === 172 /* PropertyAccessExpression */ - || kind === 173 /* ElementAccessExpression */ - || kind === 175 /* NewExpression */ - || kind === 174 /* CallExpression */ - || kind === 241 /* JsxElement */ - || kind === 242 /* JsxSelfClosingElement */ - || kind === 176 /* TaggedTemplateExpression */ - || kind === 170 /* ArrayLiteralExpression */ - || kind === 178 /* ParenthesizedExpression */ - || kind === 171 /* ObjectLiteralExpression */ - || kind === 192 /* ClassExpression */ - || kind === 179 /* FunctionExpression */ - || kind === 69 /* Identifier */ - || kind === 10 /* RegularExpressionLiteral */ + return kind === 177 /* PropertyAccessExpression */ + || kind === 178 /* ElementAccessExpression */ + || kind === 180 /* NewExpression */ + || kind === 179 /* CallExpression */ + || kind === 246 /* JsxElement */ + || kind === 247 /* JsxSelfClosingElement */ + || kind === 181 /* TaggedTemplateExpression */ + || kind === 175 /* ArrayLiteralExpression */ + || kind === 183 /* ParenthesizedExpression */ + || kind === 176 /* ObjectLiteralExpression */ + || kind === 197 /* ClassExpression */ + || kind === 184 /* FunctionExpression */ + || kind === 70 /* Identifier */ + || kind === 11 /* RegularExpressionLiteral */ || kind === 8 /* NumericLiteral */ || kind === 9 /* StringLiteral */ - || kind === 11 /* NoSubstitutionTemplateLiteral */ - || kind === 189 /* TemplateExpression */ - || kind === 84 /* FalseKeyword */ - || kind === 93 /* NullKeyword */ - || kind === 97 /* ThisKeyword */ - || kind === 99 /* TrueKeyword */ - || kind === 95 /* SuperKeyword */ - || kind === 196 /* NonNullExpression */; + || kind === 12 /* NoSubstitutionTemplateLiteral */ + || kind === 194 /* TemplateExpression */ + || kind === 85 /* FalseKeyword */ + || kind === 94 /* NullKeyword */ + || kind === 98 /* ThisKeyword */ + || kind === 100 /* TrueKeyword */ + || kind === 96 /* SuperKeyword */ + || kind === 201 /* NonNullExpression */ + || kind === 297 /* RawExpression */; } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isUnaryExpressionKind(kind) { - return kind === 185 /* PrefixUnaryExpression */ - || kind === 186 /* PostfixUnaryExpression */ - || kind === 181 /* DeleteExpression */ - || kind === 182 /* TypeOfExpression */ - || kind === 183 /* VoidExpression */ - || kind === 184 /* AwaitExpression */ - || kind === 177 /* TypeAssertionExpression */ + return kind === 190 /* PrefixUnaryExpression */ + || kind === 191 /* PostfixUnaryExpression */ + || kind === 186 /* DeleteExpression */ + || kind === 187 /* TypeOfExpression */ + || kind === 188 /* VoidExpression */ + || kind === 189 /* AwaitExpression */ + || kind === 182 /* TypeAssertionExpression */ || isLeftHandSideExpressionKind(kind); } function isUnaryExpression(node) { @@ -9399,13 +10000,14 @@ var ts; } ts.isUnaryExpression = isUnaryExpression; function isExpressionKind(kind) { - return kind === 188 /* ConditionalExpression */ - || kind === 190 /* YieldExpression */ - || kind === 180 /* ArrowFunction */ - || kind === 187 /* BinaryExpression */ - || kind === 191 /* SpreadElementExpression */ - || kind === 195 /* AsExpression */ - || kind === 193 /* OmittedExpression */ + return kind === 193 /* ConditionalExpression */ + || kind === 195 /* YieldExpression */ + || kind === 185 /* ArrowFunction */ + || kind === 192 /* BinaryExpression */ + || kind === 196 /* SpreadElement */ + || kind === 200 /* AsExpression */ + || kind === 198 /* OmittedExpression */ + || kind === 297 /* RawExpression */ || isUnaryExpressionKind(kind); } function isExpression(node) { @@ -9414,16 +10016,16 @@ var ts; ts.isExpression = isExpression; function isAssertionExpression(node) { var kind = node.kind; - return kind === 177 /* TypeAssertionExpression */ - || kind === 195 /* AsExpression */; + return kind === 182 /* TypeAssertionExpression */ + || kind === 200 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288 /* PartiallyEmittedExpression */; + return node.kind === 294 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287 /* NotEmittedStatement */; + return node.kind === 293 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -9432,17 +10034,17 @@ var ts; } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isOmittedExpression(node) { - return node.kind === 193 /* OmittedExpression */; + return node.kind === 198 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; // Misc function isTemplateSpan(node) { - return node.kind === 197 /* TemplateSpan */; + return node.kind === 202 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; // Element function isBlock(node) { - return node.kind === 199 /* Block */; + return node.kind === 204 /* Block */; } ts.isBlock = isBlock; function isConciseBody(node) { @@ -9460,119 +10062,121 @@ var ts; } ts.isForInitializer = isForInitializer; function isVariableDeclaration(node) { - return node.kind === 218 /* VariableDeclaration */; + return node.kind === 223 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 219 /* VariableDeclarationList */; + return node.kind === 224 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isCaseBlock(node) { - return node.kind === 227 /* CaseBlock */; + return node.kind === 232 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isModuleBody(node) { var kind = node.kind; - return kind === 226 /* ModuleBlock */ - || kind === 225 /* ModuleDeclaration */; + return kind === 231 /* ModuleBlock */ + || kind === 230 /* ModuleDeclaration */; } ts.isModuleBody = isModuleBody; function isImportEqualsDeclaration(node) { - return node.kind === 229 /* ImportEqualsDeclaration */; + return node.kind === 234 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportClause(node) { - return node.kind === 231 /* ImportClause */; + return node.kind === 236 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 233 /* NamedImports */ - || kind === 232 /* NamespaceImport */; + return kind === 238 /* NamedImports */ + || kind === 237 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; function isImportSpecifier(node) { - return node.kind === 234 /* ImportSpecifier */; + return node.kind === 239 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isNamedExports(node) { - return node.kind === 237 /* NamedExports */; + return node.kind === 242 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 238 /* ExportSpecifier */; + return node.kind === 243 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isModuleOrEnumDeclaration(node) { - return node.kind === 225 /* ModuleDeclaration */ || node.kind === 224 /* EnumDeclaration */; + return node.kind === 230 /* ModuleDeclaration */ || node.kind === 229 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 180 /* ArrowFunction */ - || kind === 169 /* BindingElement */ - || kind === 221 /* ClassDeclaration */ - || kind === 192 /* ClassExpression */ - || kind === 148 /* Constructor */ - || kind === 224 /* EnumDeclaration */ - || kind === 255 /* EnumMember */ - || kind === 238 /* ExportSpecifier */ - || kind === 220 /* FunctionDeclaration */ - || kind === 179 /* FunctionExpression */ - || kind === 149 /* GetAccessor */ - || kind === 231 /* ImportClause */ - || kind === 229 /* ImportEqualsDeclaration */ - || kind === 234 /* ImportSpecifier */ - || kind === 222 /* InterfaceDeclaration */ - || kind === 147 /* MethodDeclaration */ - || kind === 146 /* MethodSignature */ - || kind === 225 /* ModuleDeclaration */ - || kind === 228 /* NamespaceExportDeclaration */ - || kind === 232 /* NamespaceImport */ - || kind === 142 /* Parameter */ - || kind === 253 /* PropertyAssignment */ - || kind === 145 /* PropertyDeclaration */ - || kind === 144 /* PropertySignature */ - || kind === 150 /* SetAccessor */ - || kind === 254 /* ShorthandPropertyAssignment */ - || kind === 223 /* TypeAliasDeclaration */ - || kind === 141 /* TypeParameter */ - || kind === 218 /* VariableDeclaration */ - || kind === 279 /* JSDocTypedefTag */; + return kind === 185 /* ArrowFunction */ + || kind === 174 /* BindingElement */ + || kind === 226 /* ClassDeclaration */ + || kind === 197 /* ClassExpression */ + || kind === 150 /* Constructor */ + || kind === 229 /* EnumDeclaration */ + || kind === 260 /* EnumMember */ + || kind === 243 /* ExportSpecifier */ + || kind === 225 /* FunctionDeclaration */ + || kind === 184 /* FunctionExpression */ + || kind === 151 /* GetAccessor */ + || kind === 236 /* ImportClause */ + || kind === 234 /* ImportEqualsDeclaration */ + || kind === 239 /* ImportSpecifier */ + || kind === 227 /* InterfaceDeclaration */ + || kind === 149 /* MethodDeclaration */ + || kind === 148 /* MethodSignature */ + || kind === 230 /* ModuleDeclaration */ + || kind === 233 /* NamespaceExportDeclaration */ + || kind === 237 /* NamespaceImport */ + || kind === 144 /* Parameter */ + || kind === 257 /* PropertyAssignment */ + || kind === 147 /* PropertyDeclaration */ + || kind === 146 /* PropertySignature */ + || kind === 152 /* SetAccessor */ + || kind === 258 /* ShorthandPropertyAssignment */ + || kind === 228 /* TypeAliasDeclaration */ + || kind === 143 /* TypeParameter */ + || kind === 223 /* VariableDeclaration */ + || kind === 285 /* JSDocTypedefTag */; } function isDeclarationStatementKind(kind) { - return kind === 220 /* FunctionDeclaration */ - || kind === 239 /* MissingDeclaration */ - || kind === 221 /* ClassDeclaration */ - || kind === 222 /* InterfaceDeclaration */ - || kind === 223 /* TypeAliasDeclaration */ - || kind === 224 /* EnumDeclaration */ - || kind === 225 /* ModuleDeclaration */ - || kind === 230 /* ImportDeclaration */ - || kind === 229 /* ImportEqualsDeclaration */ - || kind === 236 /* ExportDeclaration */ - || kind === 235 /* ExportAssignment */ - || kind === 228 /* NamespaceExportDeclaration */; + return kind === 225 /* FunctionDeclaration */ + || kind === 244 /* MissingDeclaration */ + || kind === 226 /* ClassDeclaration */ + || kind === 227 /* InterfaceDeclaration */ + || kind === 228 /* TypeAliasDeclaration */ + || kind === 229 /* EnumDeclaration */ + || kind === 230 /* ModuleDeclaration */ + || kind === 235 /* ImportDeclaration */ + || kind === 234 /* ImportEqualsDeclaration */ + || kind === 241 /* ExportDeclaration */ + || kind === 240 /* ExportAssignment */ + || kind === 233 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 210 /* BreakStatement */ - || kind === 209 /* ContinueStatement */ - || kind === 217 /* DebuggerStatement */ - || kind === 204 /* DoStatement */ - || kind === 202 /* ExpressionStatement */ - || kind === 201 /* EmptyStatement */ - || kind === 207 /* ForInStatement */ - || kind === 208 /* ForOfStatement */ - || kind === 206 /* ForStatement */ - || kind === 203 /* IfStatement */ - || kind === 214 /* LabeledStatement */ - || kind === 211 /* ReturnStatement */ - || kind === 213 /* SwitchStatement */ - || kind === 215 /* ThrowStatement */ - || kind === 216 /* TryStatement */ - || kind === 200 /* VariableStatement */ - || kind === 205 /* WhileStatement */ - || kind === 212 /* WithStatement */ - || kind === 287 /* NotEmittedStatement */; + return kind === 215 /* BreakStatement */ + || kind === 214 /* ContinueStatement */ + || kind === 222 /* DebuggerStatement */ + || kind === 209 /* DoStatement */ + || kind === 207 /* ExpressionStatement */ + || kind === 206 /* EmptyStatement */ + || kind === 212 /* ForInStatement */ + || kind === 213 /* ForOfStatement */ + || kind === 211 /* ForStatement */ + || kind === 208 /* IfStatement */ + || kind === 219 /* LabeledStatement */ + || kind === 216 /* ReturnStatement */ + || kind === 218 /* SwitchStatement */ + || kind === 220 /* ThrowStatement */ + || kind === 221 /* TryStatement */ + || kind === 205 /* VariableStatement */ + || kind === 210 /* WhileStatement */ + || kind === 217 /* WithStatement */ + || kind === 293 /* NotEmittedStatement */ + || kind === 296 /* EndOfDeclarationMarker */ + || kind === 295 /* MergeDeclarationMarker */; } function isDeclaration(node) { return isDeclarationKind(node.kind); @@ -9593,93 +10197,93 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 199 /* Block */; + || kind === 204 /* Block */; } ts.isStatement = isStatement; // Module references function isModuleReference(node) { var kind = node.kind; - return kind === 240 /* ExternalModuleReference */ - || kind === 139 /* QualifiedName */ - || kind === 69 /* Identifier */; + return kind === 245 /* ExternalModuleReference */ + || kind === 141 /* QualifiedName */ + || kind === 70 /* Identifier */; } ts.isModuleReference = isModuleReference; // JSX function isJsxOpeningElement(node) { - return node.kind === 243 /* JsxOpeningElement */; + return node.kind === 248 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 245 /* JsxClosingElement */; + return node.kind === 249 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 97 /* ThisKeyword */ - || kind === 69 /* Identifier */ - || kind === 172 /* PropertyAccessExpression */; + return kind === 98 /* ThisKeyword */ + || kind === 70 /* Identifier */ + || kind === 177 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 241 /* JsxElement */ - || kind === 248 /* JsxExpression */ - || kind === 242 /* JsxSelfClosingElement */ - || kind === 244 /* JsxText */; + return kind === 246 /* JsxElement */ + || kind === 252 /* JsxExpression */ + || kind === 247 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 246 /* JsxAttribute */ - || kind === 247 /* JsxSpreadAttribute */; + return kind === 250 /* JsxAttribute */ + || kind === 251 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; function isJsxSpreadAttribute(node) { - return node.kind === 247 /* JsxSpreadAttribute */; + return node.kind === 251 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxAttribute(node) { - return node.kind === 246 /* JsxAttribute */; + return node.kind === 250 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 248 /* JsxExpression */; + || kind === 252 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 249 /* CaseClause */ - || kind === 250 /* DefaultClause */; + return kind === 253 /* CaseClause */ + || kind === 254 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isHeritageClause(node) { - return node.kind === 251 /* HeritageClause */; + return node.kind === 255 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 252 /* CatchClause */; + return node.kind === 256 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 253 /* PropertyAssignment */; + return node.kind === 257 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 254 /* ShorthandPropertyAssignment */; + return node.kind === 258 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; // Enum function isEnumMember(node) { - return node.kind === 255 /* EnumMember */; + return node.kind === 260 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 256 /* SourceFile */; + return node.kind === 261 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isWatchSet(options) { @@ -9688,10 +10292,19 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { - return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case 5 /* ESNext */: + case 4 /* ES2017 */: + return "lib.es2017.d.ts"; + case 3 /* ES2016 */: + return "lib.es2016.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } } ts.getDefaultLibFileName = getDefaultLibFileName; function textSpanEnd(span) { @@ -9900,9 +10513,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 141 /* TypeParameter */) { + if (d && d.kind === 143 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 222 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227 /* InterfaceDeclaration */) { return current; } } @@ -9910,11 +10523,11 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 150 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 169 /* BindingElement */ || ts.isBindingPattern(node))) { + while (node && (node.kind === 174 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -9922,14 +10535,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 219 /* VariableDeclarationList */) { + if (node && node.kind === 224 /* VariableDeclarationList */) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 200 /* VariableStatement */) { + if (node && node.kind === 205 /* VariableStatement */) { flags |= ts.getModifierFlags(node); } return flags; @@ -9945,19 +10558,73 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 219 /* VariableDeclarationList */) { + if (node && node.kind === 224 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 200 /* VariableStatement */) { + if (node && node.kind === 205 /* VariableStatement */) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + // TODO: Add codePage support for readFile? + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; })(ts || (ts = {})); /// /// @@ -9967,7 +10634,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, location, flags) { - var ConstructorForKind = kind === 256 /* SourceFile */ + var ConstructorForKind = kind === 261 /* SourceFile */ ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor())) : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor())); var node = location @@ -10029,7 +10696,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10057,14 +10724,14 @@ var ts; return node; } else if (typeof value === "boolean") { - return createNode(value ? 99 /* TrueKeyword */ : 84 /* FalseKeyword */, location, /*flags*/ undefined); + return createNode(value ? 100 /* TrueKeyword */ : 85 /* FalseKeyword */, location, /*flags*/ undefined); } else if (typeof value === "string") { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10075,7 +10742,7 @@ var ts; // Identifiers var nextAutoGenerateId = 0; function createIdentifier(text, location) { - var node = createNode(69 /* Identifier */, location); + var node = createNode(70 /* Identifier */, location); node.text = ts.escapeIdentifier(text); node.originalKeywordKind = ts.stringToToken(text); node.autoGenerateKind = 0 /* None */; @@ -10084,7 +10751,7 @@ var ts; } ts.createIdentifier = createIdentifier; function createTempVariable(recordTempVariable, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = ""; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 1 /* Auto */; @@ -10097,7 +10764,7 @@ var ts; } ts.createTempVariable = createTempVariable; function createLoopVariable(location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = ""; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 2 /* Loop */; @@ -10107,7 +10774,7 @@ var ts; } ts.createLoopVariable = createLoopVariable; function createUniqueName(text, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.text = text; name.originalKeywordKind = 0 /* Unknown */; name.autoGenerateKind = 3 /* Unique */; @@ -10117,7 +10784,7 @@ var ts; } ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, location) { - var name = createNode(69 /* Identifier */, location); + var name = createNode(70 /* Identifier */, location); name.original = node; name.text = ""; name.originalKeywordKind = 0 /* Unknown */; @@ -10134,23 +10801,23 @@ var ts; ts.createToken = createToken; // Reserved words function createSuper() { - var node = createNode(95 /* SuperKeyword */); + var node = createNode(96 /* SuperKeyword */); return node; } ts.createSuper = createSuper; function createThis(location) { - var node = createNode(97 /* ThisKeyword */, location); + var node = createNode(98 /* ThisKeyword */, location); return node; } ts.createThis = createThis; function createNull() { - var node = createNode(93 /* NullKeyword */); + var node = createNode(94 /* NullKeyword */); return node; } ts.createNull = createNull; // Names function createComputedPropertyName(expression, location) { - var node = createNode(140 /* ComputedPropertyName */, location); + var node = createNode(142 /* ComputedPropertyName */, location); node.expression = expression; return node; } @@ -10163,17 +10830,8 @@ var ts; } ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements - function createParameter(name, initializer, location) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, name, - /*questionToken*/ undefined, - /*type*/ undefined, initializer, location); - } - ts.createParameter = createParameter; - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { - var node = createNode(142 /* Parameter */, location, flags); + function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) { + var node = createNode(144 /* Parameter */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.dotDotDotToken = dotDotDotToken; @@ -10183,17 +10841,17 @@ var ts; node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined; return node; } - ts.createParameterDeclaration = createParameterDeclaration; - function updateParameterDeclaration(node, decorators, modifiers, name, type, initializer) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); + ts.createParameter = createParameter; + function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); } return node; } - ts.updateParameterDeclaration = updateParameterDeclaration; + ts.updateParameter = updateParameter; // Type members function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) { - var node = createNode(145 /* PropertyDeclaration */, location); + var node = createNode(147 /* PropertyDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10211,7 +10869,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(147 /* MethodDeclaration */, location, flags); + var node = createNode(149 /* MethodDeclaration */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -10231,7 +10889,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body, location, flags) { - var node = createNode(148 /* Constructor */, location, flags); + var node = createNode(150 /* Constructor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = undefined; @@ -10249,7 +10907,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) { - var node = createNode(149 /* GetAccessor */, location, flags); + var node = createNode(151 /* GetAccessor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10268,7 +10926,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) { - var node = createNode(150 /* SetAccessor */, location, flags); + var node = createNode(152 /* SetAccessor */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10287,7 +10945,7 @@ var ts; ts.updateSetAccessor = updateSetAccessor; // Binding Patterns function createObjectBindingPattern(elements, location) { - var node = createNode(167 /* ObjectBindingPattern */, location); + var node = createNode(172 /* ObjectBindingPattern */, location); node.elements = createNodeArray(elements); return node; } @@ -10300,7 +10958,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements, location) { - var node = createNode(168 /* ArrayBindingPattern */, location); + var node = createNode(173 /* ArrayBindingPattern */, location); node.elements = createNodeArray(elements); return node; } @@ -10313,7 +10971,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) { - var node = createNode(169 /* BindingElement */, location); + var node = createNode(174 /* BindingElement */, location); node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; node.dotDotDotToken = dotDotDotToken; node.name = typeof name === "string" ? createIdentifier(name) : name; @@ -10321,16 +10979,16 @@ var ts; return node; } ts.createBindingElement = createBindingElement; - function updateBindingElement(node, propertyName, name, initializer) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, location, multiLine) { - var node = createNode(170 /* ArrayLiteralExpression */, location); + var node = createNode(175 /* ArrayLiteralExpression */, location); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) { node.multiLine = true; @@ -10346,7 +11004,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, location, multiLine) { - var node = createNode(171 /* ObjectLiteralExpression */, location); + var node = createNode(176 /* ObjectLiteralExpression */, location); node.properties = createNodeArray(properties); if (multiLine) { node.multiLine = true; @@ -10362,9 +11020,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name, location, flags) { - var node = createNode(172 /* PropertyAccessExpression */, location, flags); + var node = createNode(177 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 65536 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,14 +11031,14 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index, location) { - var node = createNode(173 /* ElementAccessExpression */, location); + var node = createNode(178 /* ElementAccessExpression */, location); node.expression = parenthesizeForAccess(expression); node.argumentExpression = typeof index === "number" ? createLiteral(index) : index; return node; @@ -10394,7 +11052,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(174 /* CallExpression */, location, flags); + var node = createNode(179 /* CallExpression */, location, flags); node.expression = parenthesizeForAccess(expression); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -10411,7 +11069,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray, location, flags) { - var node = createNode(175 /* NewExpression */, location, flags); + var node = createNode(180 /* NewExpression */, location, flags); node.expression = parenthesizeForNew(expression); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -10426,7 +11084,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template, location) { - var node = createNode(176 /* TaggedTemplateExpression */, location); + var node = createNode(181 /* TaggedTemplateExpression */, location); node.tag = parenthesizeForAccess(tag); node.template = template; return node; @@ -10440,7 +11098,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createParen(expression, location) { - var node = createNode(178 /* ParenthesizedExpression */, location); + var node = createNode(183 /* ParenthesizedExpression */, location); node.expression = expression; return node; } @@ -10452,9 +11110,9 @@ var ts; return node; } ts.updateParen = updateParen; - function createFunctionExpression(asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(179 /* FunctionExpression */, location, flags); - node.modifiers = undefined; + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { + var node = createNode(184 /* FunctionExpression */, location, flags); + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -10464,20 +11122,20 @@ var ts; return node; } ts.createFunctionExpression = createFunctionExpression; - function updateFunctionExpression(node, name, typeParameters, parameters, type, body) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); } return node; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) { - var node = createNode(180 /* ArrowFunction */, location, flags); + var node = createNode(185 /* ArrowFunction */, location, flags); node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10490,7 +11148,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression, location) { - var node = createNode(181 /* DeleteExpression */, location); + var node = createNode(186 /* DeleteExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10503,7 +11161,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression, location) { - var node = createNode(182 /* TypeOfExpression */, location); + var node = createNode(187 /* TypeOfExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10516,7 +11174,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression, location) { - var node = createNode(183 /* VoidExpression */, location); + var node = createNode(188 /* VoidExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10529,7 +11187,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression, location) { - var node = createNode(184 /* AwaitExpression */, location); + var node = createNode(189 /* AwaitExpression */, location); node.expression = parenthesizePrefixOperand(expression); return node; } @@ -10542,7 +11200,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand, location) { - var node = createNode(185 /* PrefixUnaryExpression */, location); + var node = createNode(190 /* PrefixUnaryExpression */, location); node.operator = operator; node.operand = parenthesizePrefixOperand(operand); return node; @@ -10556,7 +11214,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator, location) { - var node = createNode(186 /* PostfixUnaryExpression */, location); + var node = createNode(191 /* PostfixUnaryExpression */, location); node.operand = parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -10570,9 +11228,9 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; - var node = createNode(187 /* BinaryExpression */, location); + var node = createNode(192 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); node.operatorToken = operatorToken; node.right = parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); @@ -10586,13 +11244,23 @@ var ts; return node; } ts.updateBinary = updateBinary; - function createConditional(condition, questionToken, whenTrue, colonToken, whenFalse, location) { - var node = createNode(188 /* ConditionalExpression */, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) { + var node = createNode(193 /* ConditionalExpression */, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + // second overload + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + // first overload + node.questionToken = createToken(54 /* QuestionToken */); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(55 /* ColonToken */); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } ts.createConditional = createConditional; @@ -10604,7 +11272,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans, location) { - var node = createNode(189 /* TemplateExpression */, location); + var node = createNode(194 /* TemplateExpression */, location); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -10618,7 +11286,7 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createYield(asteriskToken, expression, location) { - var node = createNode(190 /* YieldExpression */, location); + var node = createNode(195 /* YieldExpression */, location); node.asteriskToken = asteriskToken; node.expression = expression; return node; @@ -10632,7 +11300,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression, location) { - var node = createNode(191 /* SpreadElementExpression */, location); + var node = createNode(196 /* SpreadElement */, location); node.expression = parenthesizeExpressionForList(expression); return node; } @@ -10645,7 +11313,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(192 /* ClassExpression */, location); + var node = createNode(197 /* ClassExpression */, location); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -10663,12 +11331,12 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression(location) { - var node = createNode(193 /* OmittedExpression */, location); + var node = createNode(198 /* OmittedExpression */, location); return node; } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression, location) { - var node = createNode(194 /* ExpressionWithTypeArguments */, location); + var node = createNode(199 /* ExpressionWithTypeArguments */, location); node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined; node.expression = parenthesizeForAccess(expression); return node; @@ -10683,7 +11351,7 @@ var ts; ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; // Misc function createTemplateSpan(expression, literal, location) { - var node = createNode(197 /* TemplateSpan */, location); + var node = createNode(202 /* TemplateSpan */, location); node.expression = expression; node.literal = literal; return node; @@ -10698,7 +11366,7 @@ var ts; ts.updateTemplateSpan = updateTemplateSpan; // Element function createBlock(statements, location, multiLine, flags) { - var block = createNode(199 /* Block */, location, flags); + var block = createNode(204 /* Block */, location, flags); block.statements = createNodeArray(statements); if (multiLine) { block.multiLine = true; @@ -10714,7 +11382,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList, location, flags) { - var node = createNode(200 /* VariableStatement */, location, flags); + var node = createNode(205 /* VariableStatement */, location, flags); node.decorators = undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -10729,7 +11397,7 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createVariableDeclarationList(declarations, location, flags) { - var node = createNode(219 /* VariableDeclarationList */, location, flags); + var node = createNode(224 /* VariableDeclarationList */, location, flags); node.declarations = createNodeArray(declarations); return node; } @@ -10742,7 +11410,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createVariableDeclaration(name, type, initializer, location, flags) { - var node = createNode(218 /* VariableDeclaration */, location, flags); + var node = createNode(223 /* VariableDeclaration */, location, flags); node.name = typeof name === "string" ? createIdentifier(name) : name; node.type = type; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -10757,11 +11425,11 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createEmptyStatement(location) { - return createNode(201 /* EmptyStatement */, location); + return createNode(206 /* EmptyStatement */, location); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression, location, flags) { - var node = createNode(202 /* ExpressionStatement */, location, flags); + var node = createNode(207 /* ExpressionStatement */, location, flags); node.expression = parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -10774,7 +11442,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement, location) { - var node = createNode(203 /* IfStatement */, location); + var node = createNode(208 /* IfStatement */, location); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -10789,7 +11457,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression, location) { - var node = createNode(204 /* DoStatement */, location); + var node = createNode(209 /* DoStatement */, location); node.statement = statement; node.expression = expression; return node; @@ -10803,7 +11471,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement, location) { - var node = createNode(205 /* WhileStatement */, location); + var node = createNode(210 /* WhileStatement */, location); node.expression = expression; node.statement = statement; return node; @@ -10817,7 +11485,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement, location) { - var node = createNode(206 /* ForStatement */, location, /*flags*/ undefined); + var node = createNode(211 /* ForStatement */, location, /*flags*/ undefined); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -10833,7 +11501,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement, location) { - var node = createNode(207 /* ForInStatement */, location); + var node = createNode(212 /* ForInStatement */, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -10848,7 +11516,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(initializer, expression, statement, location) { - var node = createNode(208 /* ForOfStatement */, location); + var node = createNode(213 /* ForOfStatement */, location); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -10863,7 +11531,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label, location) { - var node = createNode(209 /* ContinueStatement */, location); + var node = createNode(214 /* ContinueStatement */, location); if (label) { node.label = label; } @@ -10878,7 +11546,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label, location) { - var node = createNode(210 /* BreakStatement */, location); + var node = createNode(215 /* BreakStatement */, location); if (label) { node.label = label; } @@ -10893,7 +11561,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression, location) { - var node = createNode(211 /* ReturnStatement */, location); + var node = createNode(216 /* ReturnStatement */, location); node.expression = expression; return node; } @@ -10906,7 +11574,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement, location) { - var node = createNode(212 /* WithStatement */, location); + var node = createNode(217 /* WithStatement */, location); node.expression = expression; node.statement = statement; return node; @@ -10920,7 +11588,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock, location) { - var node = createNode(213 /* SwitchStatement */, location); + var node = createNode(218 /* SwitchStatement */, location); node.expression = parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -10934,7 +11602,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement, location) { - var node = createNode(214 /* LabeledStatement */, location); + var node = createNode(219 /* LabeledStatement */, location); node.label = typeof label === "string" ? createIdentifier(label) : label; node.statement = statement; return node; @@ -10948,7 +11616,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression, location) { - var node = createNode(215 /* ThrowStatement */, location); + var node = createNode(220 /* ThrowStatement */, location); node.expression = expression; return node; } @@ -10961,7 +11629,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock, location) { - var node = createNode(216 /* TryStatement */, location); + var node = createNode(221 /* TryStatement */, location); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -10976,7 +11644,7 @@ var ts; } ts.updateTry = updateTry; function createCaseBlock(clauses, location) { - var node = createNode(227 /* CaseBlock */, location); + var node = createNode(232 /* CaseBlock */, location); node.clauses = createNodeArray(clauses); return node; } @@ -10989,7 +11657,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) { - var node = createNode(220 /* FunctionDeclaration */, location, flags); + var node = createNode(225 /* FunctionDeclaration */, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; @@ -11009,7 +11677,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) { - var node = createNode(221 /* ClassDeclaration */, location); + var node = createNode(226 /* ClassDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.name = name; @@ -11027,7 +11695,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) { - var node = createNode(230 /* ImportDeclaration */, location); + var node = createNode(235 /* ImportDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.importClause = importClause; @@ -11043,7 +11711,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings, location) { - var node = createNode(231 /* ImportClause */, location); + var node = createNode(236 /* ImportClause */, location); node.name = name; node.namedBindings = namedBindings; return node; @@ -11057,7 +11725,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name, location) { - var node = createNode(232 /* NamespaceImport */, location); + var node = createNode(237 /* NamespaceImport */, location); node.name = name; return node; } @@ -11070,7 +11738,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements, location) { - var node = createNode(233 /* NamedImports */, location); + var node = createNode(238 /* NamedImports */, location); node.elements = createNodeArray(elements); return node; } @@ -11083,7 +11751,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name, location) { - var node = createNode(234 /* ImportSpecifier */, location); + var node = createNode(239 /* ImportSpecifier */, location); node.propertyName = propertyName; node.name = name; return node; @@ -11097,7 +11765,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) { - var node = createNode(235 /* ExportAssignment */, location); + var node = createNode(240 /* ExportAssignment */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.isExportEquals = isExportEquals; @@ -11113,7 +11781,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) { - var node = createNode(236 /* ExportDeclaration */, location); + var node = createNode(241 /* ExportDeclaration */, location); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.exportClause = exportClause; @@ -11129,7 +11797,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements, location) { - var node = createNode(237 /* NamedExports */, location); + var node = createNode(242 /* NamedExports */, location); node.elements = createNodeArray(elements); return node; } @@ -11142,7 +11810,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(name, propertyName, location) { - var node = createNode(238 /* ExportSpecifier */, location); + var node = createNode(243 /* ExportSpecifier */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName; return node; @@ -11157,7 +11825,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // JSX function createJsxElement(openingElement, children, closingElement, location) { - var node = createNode(241 /* JsxElement */, location); + var node = createNode(246 /* JsxElement */, location); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -11172,7 +11840,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes, location) { - var node = createNode(242 /* JsxSelfClosingElement */, location); + var node = createNode(247 /* JsxSelfClosingElement */, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -11186,7 +11854,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes, location) { - var node = createNode(243 /* JsxOpeningElement */, location); + var node = createNode(248 /* JsxOpeningElement */, location); node.tagName = tagName; node.attributes = createNodeArray(attributes); return node; @@ -11200,7 +11868,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName, location) { - var node = createNode(245 /* JsxClosingElement */, location); + var node = createNode(249 /* JsxClosingElement */, location); node.tagName = tagName; return node; } @@ -11213,7 +11881,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxAttribute(name, initializer, location) { - var node = createNode(246 /* JsxAttribute */, location); + var node = createNode(250 /* JsxAttribute */, location); node.name = name; node.initializer = initializer; return node; @@ -11227,7 +11895,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxSpreadAttribute(expression, location) { - var node = createNode(247 /* JsxSpreadAttribute */, location); + var node = createNode(251 /* JsxSpreadAttribute */, location); node.expression = expression; return node; } @@ -11240,7 +11908,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(expression, location) { - var node = createNode(248 /* JsxExpression */, location); + var node = createNode(252 /* JsxExpression */, location); node.expression = expression; return node; } @@ -11254,7 +11922,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createHeritageClause(token, types, location) { - var node = createNode(251 /* HeritageClause */, location); + var node = createNode(255 /* HeritageClause */, location); node.token = token; node.types = createNodeArray(types); return node; @@ -11268,7 +11936,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCaseClause(expression, statements, location) { - var node = createNode(249 /* CaseClause */, location); + var node = createNode(253 /* CaseClause */, location); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -11282,7 +11950,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements, location) { - var node = createNode(250 /* DefaultClause */, location); + var node = createNode(254 /* DefaultClause */, location); node.statements = createNodeArray(statements); return node; } @@ -11295,7 +11963,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createCatchClause(variableDeclaration, block, location) { - var node = createNode(252 /* CatchClause */, location); + var node = createNode(256 /* CatchClause */, location); node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -11310,7 +11978,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer, location) { - var node = createNode(253 /* PropertyAssignment */, location); + var node = createNode(257 /* PropertyAssignment */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.questionToken = undefined; node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined; @@ -11325,12 +11993,18 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) { - var node = createNode(254 /* ShorthandPropertyAssignment */, location); + var node = createNode(258 /* ShorthandPropertyAssignment */, location); node.name = typeof name === "string" ? createIdentifier(name) : name; node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; } ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment; + function createSpreadAssignment(expression, location) { + var node = createNode(259 /* SpreadAssignment */, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + ts.createSpreadAssignment = createSpreadAssignment; function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -11338,10 +12012,17 @@ var ts; return node; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; + function updateSpreadAssignment(node, expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + ts.updateSpreadAssignment = updateSpreadAssignment; // Top-level nodes function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createNode(256 /* SourceFile */, /*location*/ node, node.flags); + var updated = createNode(261 /* SourceFile */, /*location*/ node, node.flags); updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; @@ -11395,8 +12076,6 @@ var ts; updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) - updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } return node; @@ -11410,11 +12089,33 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createNode(287 /* NotEmittedStatement */, /*location*/ original); + var node = createNode(293 /* NotEmittedStatement */, /*location*/ original); node.original = original; return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + function createEndOfDeclarationMarker(original) { + var node = createNode(296 /* EndOfDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + function createMergeDeclarationMarker(original) { + var node = createNode(295 /* MergeDeclarationMarker */); + node.emitNode = {}; + node.original = original; + return node; + } + ts.createMergeDeclarationMarker = createMergeDeclarationMarker; /** * Creates a synthetic expression to act as a placeholder for a not-emitted expression in * order to preserve comments or sourcemap positions. @@ -11424,7 +12125,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original, location) { - var node = createNode(288 /* PartiallyEmittedExpression */, /*location*/ location || original); + var node = createNode(294 /* PartiallyEmittedExpression */, /*location*/ location || original); node.expression = expression; node.original = original; return node; @@ -11437,75 +12138,85 @@ var ts; return node; } ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; + /** + * Creates a node that emits a string of raw text in an expression position. Raw text is never + * transformed, should be ES3 compliant, and should have the same precedence as + * PrimaryExpression. + * + * @param text The raw text of the node. + */ + function createRawExpression(text) { + var node = createNode(297 /* RawExpression */); + node.text = text; + return node; + } + ts.createRawExpression = createRawExpression; // Compound nodes function createComma(left, right) { - return createBinary(left, 24 /* CommaToken */, right); + return createBinary(left, 25 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right, location) { - return createBinary(left, 25 /* LessThanToken */, right, location); + return createBinary(left, 26 /* LessThanToken */, right, location); } ts.createLessThan = createLessThan; function createAssignment(left, right, location) { - return createBinary(left, 56 /* EqualsToken */, right, location); + return createBinary(left, 57 /* EqualsToken */, right, location); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 32 /* EqualsEqualsEqualsToken */, right); + return createBinary(left, 33 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 33 /* ExclamationEqualsEqualsToken */, right); + return createBinary(left, 34 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 35 /* PlusToken */, right); + return createBinary(left, 36 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 36 /* MinusToken */, right); + return createBinary(left, 37 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand, location) { - return createPostfix(operand, 41 /* PlusPlusToken */, location); + return createPostfix(operand, 42 /* PlusPlusToken */, location); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 51 /* AmpersandAmpersandToken */, right); + return createBinary(left, 52 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 52 /* BarBarToken */, right); + return createBinary(left, 53 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(49 /* ExclamationToken */, operand); + return createPrefix(50 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { return createVoid(createLiteral(0)); } ts.createVoidZero = createVoidZero; + function createTypeCheck(value, tag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + ts.createTypeCheck = createTypeCheck; function createMemberAccessForPropertyName(target, memberName, location) { if (ts.isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 64 /* NoNestedSourceMaps */; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; - function createRestParameter(name) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, - /*questionToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); - } - ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { return createCall(createPropertyAccess(func, "call"), /*typeArguments*/ undefined, [ @@ -11545,10 +12256,28 @@ var ts; // flag and setting a parent node. var react = createIdentifier(reactNamespace || "React"); react.flags &= ~8 /* Synthesized */; - react.parent = parent; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = ts.getParseTreeNode(parent); return react; } - function createReactCreateElement(reactNamespace, tagName, props, children, parentElement, location) { + function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { + if (ts.isQualifiedName(jsxFactory)) { + var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + var right = createSynthesizedNode(70 /* Identifier */); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement"); + } + function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) { var argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -11568,10 +12297,22 @@ var ts; argumentsList.push(children[0]); } } - return createCall(createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "createElement"), + return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), /*typeArguments*/ undefined, argumentsList, location); } - ts.createReactCreateElement = createReactCreateElement; + ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExportDefault(expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + ts.createExportDefault = createExportDefault; + function createExternalModuleExport(exportName) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(exportName)])); + } + ts.createExternalModuleExport = createExternalModuleExport; + function createLetStatement(name, initializer, location) { + return createVariableStatement(/*modifiers*/ undefined, createLetDeclarationList([createVariableDeclaration(name, /*type*/ undefined, initializer)]), location); + } + ts.createLetStatement = createLetStatement; function createLetDeclarationList(declarations, location) { return createVariableDeclarationList(declarations, location, 1 /* Let */); } @@ -11581,187 +12322,26 @@ var ts; } ts.createConstDeclarationList = createConstDeclarationList; // Helpers - function createHelperName(externalHelpersModuleName, name) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + function getHelperName(name) { + return setEmitFlags(createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); } - ts.createHelperName = createHelperName; - function createExtendsHelper(externalHelpersModuleName, name) { - return createCall(createHelperName(externalHelpersModuleName, "__extends"), - /*typeArguments*/ undefined, [ - name, - createIdentifier("_super") - ]); - } - ts.createExtendsHelper = createExtendsHelper; - function createAssignHelper(externalHelpersModuleName, attributesSegments) { - return createCall(createHelperName(externalHelpersModuleName, "__assign"), - /*typeArguments*/ undefined, attributesSegments); - } - ts.createAssignHelper = createAssignHelper; - function createParamHelper(externalHelpersModuleName, expression, parameterOffset, location) { - return createCall(createHelperName(externalHelpersModuleName, "__param"), - /*typeArguments*/ undefined, [ - createLiteral(parameterOffset), - expression - ], location); - } - ts.createParamHelper = createParamHelper; - function createMetadataHelper(externalHelpersModuleName, metadataKey, metadataValue) { - return createCall(createHelperName(externalHelpersModuleName, "__metadata"), - /*typeArguments*/ undefined, [ - createLiteral(metadataKey), - metadataValue - ]); - } - ts.createMetadataHelper = createMetadataHelper; - function createDecorateHelper(externalHelpersModuleName, decoratorExpressions, target, memberName, descriptor, location) { - var argumentsArray = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), /*typeArguments*/ undefined, argumentsArray, location); - } - ts.createDecorateHelper = createDecorateHelper; - function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, body); - // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; - return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), - /*typeArguments*/ undefined, [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ]); - } - ts.createAwaiterHelper = createAwaiterHelper; - function createHasOwnProperty(target, propertyName) { - return createCall(createPropertyAccess(target, "hasOwnProperty"), - /*typeArguments*/ undefined, [propertyName]); - } - ts.createHasOwnProperty = createHasOwnProperty; - function createObjectCreate(prototype) { - return createCall(createPropertyAccess(createIdentifier("Object"), "create"), - /*typeArguments*/ undefined, [prototype]); - } - function createGeti(target) { - // name => super[name] - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createElementAccess(target, createIdentifier("name"))); - } - function createSeti(target) { - // (name, value) => super[name] = value - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [ - createParameter("name"), - createParameter("value") - ], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createAssignment(createElementAccess(target, createIdentifier("name")), createIdentifier("value"))); - } - function createAdvancedAsyncSuperHelper() { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - // const cache = Object.create(null); - var createCache = createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("cache", - /*type*/ undefined, createObjectCreate(createNull())) - ])); - // get value() { return geti(name); } - var getter = createGetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, "value", - /*parameters*/ [], - /*type*/ undefined, createBlock([ - createReturn(createCall(createIdentifier("geti"), - /*typeArguments*/ undefined, [createIdentifier("name")])) - ])); - // set value(v) { seti(name, v); } - var setter = createSetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, "value", [createParameter("v")], createBlock([ - createStatement(createCall(createIdentifier("seti"), - /*typeArguments*/ undefined, [ - createIdentifier("name"), - createIdentifier("v") - ])) - ])); - // return name => cache[name] || ... - var getOrCreateAccessorsForName = createReturn(createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, createLogicalOr(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createParen(createAssignment(createElementAccess(createIdentifier("cache"), createIdentifier("name")), createObjectLiteral([ - getter, - setter - ])))))); - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - return createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("_super", - /*type*/ undefined, createCall(createParen(createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - createParameter("geti"), - createParameter("seti") - ], - /*type*/ undefined, createBlock([ - createCache, - getOrCreateAccessorsForName - ]))), - /*typeArguments*/ undefined, [ - createGeti(createSuper()), - createSeti(createSuper()) - ])) - ])); - } - ts.createAdvancedAsyncSuperHelper = createAdvancedAsyncSuperHelper; - function createSimpleAsyncSuperHelper() { - return createVariableStatement( - /*modifiers*/ undefined, createConstDeclarationList([ - createVariableDeclaration("_super", - /*type*/ undefined, createGeti(createSuper())) - ])); - } - ts.createSimpleAsyncSuperHelper = createSimpleAsyncSuperHelper; + ts.getHelperName = getHelperName; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return cacheIdentifiers; - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -11775,13 +12355,13 @@ var ts; thisArg = createThis(); target = callee; } - else if (callee.kind === 95 /* SuperKeyword */) { + else if (callee.kind === 96 /* SuperKeyword */) { thisArg = createThis(); - target = languageVersion < 2 /* ES6 */ ? createIdentifier("_super", /*location*/ callee) : callee; + target = languageVersion < 2 /* ES2015 */ ? createIdentifier("_super", /*location*/ callee) : callee; } else { switch (callee.kind) { - case 172 /* PropertyAccessExpression */: { + case 177 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); @@ -11795,7 +12375,7 @@ var ts; } break; } - case 173 /* ElementAccessExpression */: { + case 178 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); @@ -11849,14 +12429,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -11866,7 +12446,7 @@ var ts; if (property === firstAccessor) { var properties_1 = []; if (getAccessor) { - var getterFunction = createFunctionExpression( + var getterFunction = createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, @@ -11877,7 +12457,7 @@ var ts; properties_1.push(getter); } if (setAccessor) { - var setterFunction = createFunctionExpression( + var setterFunction = createFunctionExpression(setAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -11911,7 +12491,7 @@ var ts; /*original*/ property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.asteriskToken, + return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body, @@ -11920,7 +12500,116 @@ var ts; /*location*/ method), /*original*/ method)); } - // Utilities + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getLocalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); + } + ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ + function isLocalName(node) { + return (getEmitFlags(node) & 16384 /* LocalName */) !== 0; + } + ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); + } + ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + function isExportName(node) { + return (getEmitFlags(node) & 8192 /* ExportName */) !== 0; + } + ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + ts.getDeclarationName = getDeclarationName; + function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { + var name_8 = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + setEmitFlags(name_8, emitFlags); + return name_8; + } + return getGeneratedNameForNode(node); + } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), /*location*/ name); + var emitFlags; + if (!allowSourceMaps) + emitFlags |= 48 /* NoSourceMap */; + if (!allowComments) + emitFlags |= 1536 /* NoComments */; + if (emitFlags) + setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + ts.getNamespaceMemberName = getNamespaceMemberName; + function convertToFunctionBody(node, multiLine) { + return ts.isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node, multiLine); + } + ts.convertToFunctionBody = convertToFunctionBody; function isUseStrictPrologue(node) { return node.expression.text === "use strict"; } @@ -11936,7 +12625,7 @@ var ts; * @param visitor: Optional callback used to visit any custom prologue directives. */ function addPrologueDirectives(target, source, ensureUseStrict, visitor) { - ts.Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; var statementOffset = 0; var numStatements = source.length; @@ -11949,22 +12638,60 @@ var ts; target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + var statement = source[statementOffset]; + if (getEmitFlags(statement) & 524288 /* CustomPrologue */) { + target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function startsWithUseStrict(statements) { + var firstStatement = ts.firstOrUndefined(statements); + return firstStatement !== undefined + && ts.isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + function ensureUseStrict(statements) { + var foundUseStrict = false; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))) + ].concat(statements), statements); + } + return statements; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -11977,7 +12704,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 178 /* ParenthesizedExpression */) { + if (skipped.kind === 183 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -12011,8 +12738,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(187 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(192 /* BinaryExpression */, binaryOperator); var emittedOperand = skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -12021,7 +12748,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 190 /* YieldExpression */) { + && operand.kind === 195 /* YieldExpression */) { return false; } return true; @@ -12058,7 +12785,7 @@ var ts; // the same kind (recursively). // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" - if (binaryOperator === 35 /* PlusToken */) { + if (binaryOperator === 36 /* PlusToken */) { var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; @@ -12093,10 +12820,10 @@ var ts; // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === 37 /* AsteriskToken */ - || binaryOperator === 47 /* BarToken */ - || binaryOperator === 46 /* AmpersandToken */ - || binaryOperator === 48 /* CaretToken */; + return binaryOperator === 38 /* AsteriskToken */ + || binaryOperator === 48 /* BarToken */ + || binaryOperator === 47 /* AmpersandToken */ + || binaryOperator === 49 /* CaretToken */; } /** * This function determines whether an expression consists of a homogeneous set of @@ -12109,7 +12836,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 35 /* PlusToken */) { + if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 36 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -12123,6 +12850,24 @@ var ts; } return 0 /* Unknown */; } + function parenthesizeForConditionalHead(condition) { + var conditionalPrecedence = ts.getOperatorPrecedence(193 /* ConditionalExpression */, 54 /* QuestionToken */); + var emittedCondition = skipPartiallyEmittedExpressions(condition); + var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + return createParen(condition); + } + return condition; + } + ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; + function parenthesizeSubexpressionOfConditionalExpression(e) { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + return e.kind === 192 /* BinaryExpression */ && e.operatorToken.kind === 25 /* CommaToken */ + ? createParen(e) + : e; + } /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a NewExpression node. @@ -12132,9 +12877,9 @@ var ts; function parenthesizeForNew(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return createParen(expression); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return emittedExpression.arguments ? expression : createParen(expression); @@ -12159,7 +12904,7 @@ var ts; // var emittedExpression = skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 175 /* NewExpression */ || emittedExpression.arguments) + && (emittedExpression.kind !== 180 /* NewExpression */ || emittedExpression.arguments) && emittedExpression.kind !== 8 /* NumericLiteral */) { return expression; } @@ -12197,7 +12942,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(187 /* BinaryExpression */, 24 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, 25 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : createParen(expression, /*location*/ expression); @@ -12208,7 +12953,7 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === 179 /* FunctionExpression */ || kind === 180 /* ArrowFunction */) { + if (kind === 184 /* FunctionExpression */ || kind === 185 /* ArrowFunction */) { var mutableCall = getMutableClone(emittedExpression); mutableCall.expression = createParen(callee, /*location*/ callee); return recreatePartiallyEmittedExpressions(expression, mutableCall); @@ -12216,7 +12961,7 @@ var ts; } else { var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 171 /* ObjectLiteralExpression */ || leftmostExpressionKind === 179 /* FunctionExpression */) { + if (leftmostExpressionKind === 176 /* ObjectLiteralExpression */ || leftmostExpressionKind === 184 /* FunctionExpression */) { return createParen(expression, /*location*/ expression); } } @@ -12240,21 +12985,21 @@ var ts; function getLeftmostExpression(node) { while (true) { switch (node.kind) { - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: node = node.operand; continue; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: node = node.left; continue; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: node = node.condition; continue; - case 174 /* CallExpression */: - case 173 /* ElementAccessExpression */: - case 172 /* PropertyAccessExpression */: + case 179 /* CallExpression */: + case 178 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: node = node.expression; continue; - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -12263,19 +13008,19 @@ var ts; } function parenthesizeConciseBody(body) { var emittedBody = skipPartiallyEmittedExpressions(body); - if (emittedBody.kind === 171 /* ObjectLiteralExpression */) { + if (emittedBody.kind === 176 /* ObjectLiteralExpression */) { return createParen(body, /*location*/ body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; - })(ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); - var OuterExpressionKinds = ts.OuterExpressionKinds; + })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } var previousNode; @@ -12295,7 +13040,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */) { + while (node.kind === 183 /* ParenthesizedExpression */) { node = node.expression; } return node; @@ -12309,7 +13054,7 @@ var ts; } ts.skipAssertions = skipAssertions; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288 /* PartiallyEmittedExpression */) { + while (node.kind === 294 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12323,17 +13068,297 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + if (!destEmitNode) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) + destEmitNode.constantValue = constantValue; + if (helpers) + destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 261 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + ts.getOrCreateEmitNode = getOrCreateEmitNode; + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; + function getExternalHelpersModuleName(node) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + ts.getExternalHelpersModuleName = getExternalHelpersModuleName; + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { + if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + var externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + var helpers = getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { + var helper = helpers_1[_i]; + if (!helper.scoped) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText)); + } + } + } + } + } + ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelper(node, helper) { + var emitNode = getOrCreateEmitNode(node); + emitNode.helpers = ts.append(emitNode.helpers, helper); + return node; + } + ts.addEmitHelper = addEmitHelper; + /** + * Adds an EmitHelper to a node. + */ + function addEmitHelpers(node, helpers) { + if (ts.some(helpers)) { + var emitNode = getOrCreateEmitNode(node); + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!ts.contains(emitNode.helpers, helper)) { + emitNode.helpers = ts.append(emitNode.helpers, helper); + } + } + } + return node; + } + ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ + function removeEmitHelper(node, helper) { + var emitNode = node.emitNode; + if (emitNode) { + var helpers = emitNode.helpers; + if (helpers) { + return ts.orderedRemoveItem(helpers, helper); + } + } + return false; + } + ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ + function getEmitHelpers(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ + function moveEmitHelpers(source, target, predicate) { + var sourceEmitNode = source.emitNode; + var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!ts.some(sourceEmitHelpers)) + return; + var targetEmitNode = getOrCreateEmitNode(target); + var helpersRemoved = 0; + for (var i = 0; i < sourceEmitHelpers.length; i++) { + var helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!ts.contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + ts.moveEmitHelpers = moveEmitHelpers; + function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === undefined) + return 1 /* GreaterThan */; + if (y.priority === undefined) + return -1 /* LessThan */; + return ts.compareValues(x.priority, y.priority); + } + ts.compareEmitHelpers = compareEmitHelpers; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12366,23 +13391,23 @@ var ts; var name_9 = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } - if (node.kind === 230 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 235 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 236 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 241 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -12426,6 +13451,391 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + if (ts.isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) + ? bindingElement.initializer.right + : undefined; + } + if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + if (ts.isSpreadExpression(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ + function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + if (ts.isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 257 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 258 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + case 259 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // no target + return undefined; + } + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (ts.isSpreadExpression(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 144 /* Parameter */: + case 174 /* BindingElement */: + // `...` in `let [...a] = ...` + return bindingElement.dotDotDotToken; + case 196 /* SpreadElement */: + case 259 /* SpreadAssignment */: + // `...` in `[...a] = ...` + return bindingElement; + } + return undefined; + } + ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ + function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 174 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if (bindingElement.propertyName) { + var propertyName = bindingElement.propertyName; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 257 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if (bindingElement.name) { + var propertyName = bindingElement.name; + return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + break; + case 259 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` + return bindingElement.name; + } + var target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && ts.isPropertyName(target)) { + return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + ts.Debug.fail("Invalid property name for binding element."); + } + ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + case 176 /* ObjectLiteralExpression */: + // `a` in `{a}` + return name.properties; + } + } + ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern; + function convertToArrayAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + var expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + ts.Debug.assertNode(element, ts.isExpression); + return element; + } + ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement; + function convertToObjectAssignmentElement(element) { + if (ts.isBindingElement(element)) { + if (element.dotDotDotToken) { + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + var expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + ts.Debug.assertNode(element.name, ts.isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + ts.Debug.assertNode(element, ts.isObjectLiteralElementLike); + return element; + } + ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 173 /* ArrayBindingPattern */: + case 175 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 172 /* ObjectBindingPattern */: + case 176 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + ts.convertToAssignmentPattern = convertToAssignmentPattern; + function convertToObjectAssignmentPattern(node) { + if (ts.isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isObjectLiteralExpression); + return node; + } + ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern; + function convertToArrayAssignmentPattern(node) { + if (ts.isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node); + } + ts.Debug.assertNode(node, ts.isArrayLiteralExpression); + return node; + } + ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern; + function convertToAssignmentElementTarget(node) { + if (ts.isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + ts.Debug.assertNode(node, ts.isExpression); + return node; + } + ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMap(); + var exportedBindings = ts.createMap(); + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 235 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + break; + case 234 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 245 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 241 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports[specifier.name.text]) { + var name_10 = specifier.propertyName || specifier.name; + ts.multiMapAdd(exportSpecifiers, name_10.text, specifier); + var decl = resolver.getReferencedImportDeclaration(name_10) + || resolver.getReferencedValueDeclaration(name_10); + if (decl) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); + } + uniqueExports[specifier.name.text] = true; + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 240 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 205 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 225 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name_11 = node.name; + if (!uniqueExports[name_11.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_11); + uniqueExports[name_11.text] = true; + exportedNames = ts.append(exportedNames, name_11); + } + } + } + break; + case 226 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name_12 = node.name; + if (!uniqueExports[name_12.text]) { + ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_12); + uniqueExports[name_12.text] = true; + exportedNames = ts.append(exportedNames, name_12); + } + } + } + break; + } + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } })(ts || (ts = {})); /// /// @@ -12437,13 +13847,13 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 256 /* SourceFile */) { + if (kind === 261 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69 /* Identifier */) { + else if (kind === 70 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } - else if (kind < 139 /* FirstNode */) { + else if (kind < 141 /* FirstNode */) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); } else { @@ -12486,26 +13896,28 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: + case 259 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -12514,24 +13926,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -12542,308 +13954,320 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 161 /* TupleType */: + case 163 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return visitNodes(cbNodes, node.types); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: + case 168 /* TypeOperator */: return visitNode(cbNode, node.type); - case 166 /* LiteralType */: + case 169 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 170 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 171 /* LiteralType */: return visitNode(cbNode, node.literal); - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 177 /* TypeAssertionExpression */: + case 182 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 195 /* AsExpression */: + case 200 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 199 /* Block */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: return visitNode(cbNode, node.label); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 249 /* CaseClause */: + case 253 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 143 /* Decorator */: + case 145 /* Decorator */: return visitNode(cbNode, node.expression); - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 233 /* NamedImports */: - case 237 /* NamedExports */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 240 /* ExternalModuleReference */: + case 245 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 257 /* JSDocTypeExpression */: + case 262 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 261 /* JSDocUnionType */: + case 266 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 262 /* JSDocTupleType */: + case 267 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 260 /* JSDocArrayType */: + case 265 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 264 /* JSDocNonNullableType */: + case 269 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 263 /* JSDocNullableType */: + case 268 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 265 /* JSDocRecordType */: + case 270 /* JSDocRecordType */: return visitNode(cbNode, node.literal); - case 267 /* JSDocTypeReference */: + case 272 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 268 /* JSDocOptionalType */: + case 273 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 269 /* JSDocFunctionType */: + case 274 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 270 /* JSDocVariadicType */: + case 275 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 271 /* JSDocConstructorType */: + case 276 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 272 /* JSDocThisType */: + case 277 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 266 /* JSDocRecordMember */: + case 271 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 273 /* JSDocComment */: + case 278 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 275 /* JSDocParameterTag */: + case 281 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 276 /* JSDocReturnTag */: + case 282 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 277 /* JSDocTypeTag */: + case 283 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 278 /* JSDocTemplateTag */: + case 280 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.typeExpression); + case 284 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.jsDocTypeLiteral); - case 281 /* JSDocTypeLiteral */: + case 287 /* JSDocTypeLiteral */: return visitNodes(cbNodes, node.jsDocPropertyTags); - case 280 /* JSDocPropertyTag */: + case 286 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); - case 282 /* JSDocLiteralType */: + case 288 /* JSDocLiteralType */: return visitNode(cbNode, node.literal); } } @@ -12857,6 +14281,10 @@ var ts; return result; } ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } @@ -12898,8 +14326,8 @@ var ts; (function (Parser) { // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 32768 /* DisallowInContext */ | 131072 /* DecoratorContext */; + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; var TokenConstructor; @@ -12989,19 +14417,29 @@ var ts; // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; function getLanguageVariant(scriptKind) { // .tsx and .jsx files are treated as jsx language variant. return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; } - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); TokenConstructor = ts.objectAllocator.getTokenConstructor(); IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); @@ -13013,7 +14451,7 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 1048576 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 65536 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -13052,7 +14490,7 @@ var ts; return sourceFile; } function addJSDocComment(node) { - var comments = ts.getJsDocCommentsFromText(node, sourceFile.text); + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; @@ -13060,10 +14498,10 @@ var ts; if (!jsDoc) { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } return node; @@ -13085,12 +14523,12 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -13101,7 +14539,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(256 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(261 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -13121,16 +14559,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 32768 /* DisallowInContext */); + setContextFlag(val, 2048 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 65536 /* YieldContext */); + setContextFlag(val, 4096 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 131072 /* DecoratorContext */); + setContextFlag(val, 8192 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 262144 /* AwaitContext */); + setContextFlag(val, 16384 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -13171,40 +14609,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(32768 /* DisallowInContext */, func); + return doOutsideOfContext(2048 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(32768 /* DisallowInContext */, func); + return doInsideOfContext(2048 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(65536 /* YieldContext */, func); + return doInsideOfContext(4096 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(131072 /* DecoratorContext */, func); + return doInsideOfContext(8192 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(262144 /* AwaitContext */, func); + return doInsideOfContext(16384 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(262144 /* AwaitContext */, func); + return doOutsideOfContext(16384 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(65536 /* YieldContext */ | 262144 /* AwaitContext */, func); + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(65536 /* YieldContext */); + return inContext(4096 /* YieldContext */); } function inDisallowInContext() { - return inContext(32768 /* DisallowInContext */); + return inContext(2048 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(131072 /* DecoratorContext */); + return inContext(8192 /* DecoratorContext */); } function inAwaitContext() { - return inContext(262144 /* AwaitContext */); + return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -13305,20 +14743,20 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 69 /* Identifier */) { + if (token() === 70 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 114 /* YieldKeyword */ && inYieldContext()) { + if (token() === 115 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token() === 120 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 105 /* LastReservedWord */; + return token() > 106 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -13361,22 +14799,22 @@ var ts; } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 23 /* SemicolonToken */) { + if (token() === 24 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token() === 17 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23 /* SemicolonToken */) { + if (token() === 24 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(23 /* SemicolonToken */); + return parseExpected(24 /* SemicolonToken */); } } // note: this function creates only node @@ -13385,8 +14823,8 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + return kind >= 141 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : + kind === 70 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } function createNodeArray(elements, pos) { @@ -13408,7 +14846,7 @@ var ts; // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 524288 /* ThisNodeHasError */; + node.flags |= 32768 /* ThisNodeHasError */; } return node; } @@ -13433,16 +14871,16 @@ var ts; function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(69 /* Identifier */); + var node = createNode(70 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 69 /* Identifier */) { + if (token() !== 70 /* Identifier */) { node.originalKeywordKind = token(); } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); } - return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + return createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -13459,7 +14897,7 @@ var ts; if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token() === 20 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -13477,13 +14915,13 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(140 /* ComputedPropertyName */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(142 /* ComputedPropertyName */); + parseExpected(20 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -13497,21 +14935,21 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74 /* ConstKeyword */) { + if (token() === 75 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 81 /* EnumKeyword */; + return nextToken() === 82 /* EnumKeyword */; } - if (token() === 82 /* ExportKeyword */) { + if (token() === 83 /* ExportKeyword */) { nextToken(); - if (token() === 77 /* DefaultKeyword */) { + if (token() === 78 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token() !== 38 /* AsteriskToken */ && token() !== 117 /* AsKeyword */ && token() !== 16 /* OpenBraceToken */ && canFollowModifier(); } - if (token() === 77 /* DefaultKeyword */) { + if (token() === 78 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113 /* StaticKeyword */) { + if (token() === 114 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } @@ -13521,16 +14959,16 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 /* OpenBracketToken */ - || token() === 15 /* OpenBraceToken */ - || token() === 37 /* AsteriskToken */ - || token() === 22 /* DotDotDotToken */ + return token() === 20 /* OpenBracketToken */ + || token() === 16 /* OpenBraceToken */ + || token() === 38 /* AsteriskToken */ + || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || - (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 74 /* ClassKeyword */ || token() === 88 /* FunctionKeyword */ || + (token() === 119 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -13548,9 +14986,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token() === 24 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token() === 72 /* CaseKeyword */ || token() === 78 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -13558,19 +14996,21 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token() === 24 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || token() === 38 /* AsteriskToken */ || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); + case 17 /* RestProperties */: + return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token() === 20 /* OpenBracketToken */ || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -13585,37 +15025,37 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 17 /* TypeParameters */: + return token() === 25 /* CommaToken */ || token() === 23 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 18 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token() === 25 /* CommaToken */ || token() === 23 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); - case 18 /* TypeArguments */: - case 19 /* TupleElementTypes */: - return token() === 24 /* CommaToken */ || isStartOfType(); - case 20 /* HeritageClauses */: + case 19 /* TypeArguments */: + case 20 /* TupleElementTypes */: + return token() === 25 /* CommaToken */ || isStartOfType(); + case 21 /* HeritageClauses */: return isHeritageClause(); - case 21 /* ImportOrExportSpecifiers */: + case 22 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 16 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; - case 22 /* JSDocFunctionParameters */: - case 23 /* JSDocTypeArguments */: - case 25 /* JSDocTupleTypes */: + case 23 /* JSDocFunctionParameters */: + case 24 /* JSDocTypeArguments */: + case 26 /* JSDocTupleTypes */: return JSDocParser.isJSDocType(); - case 24 /* JSDocRecordMembers */: + case 25 /* JSDocRecordMembers */: return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15 /* OpenBraceToken */); - if (nextToken() === 16 /* CloseBraceToken */) { + ts.Debug.assert(token() === 16 /* OpenBraceToken */); + if (nextToken() === 17 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // @@ -13624,7 +15064,7 @@ var ts; // extends {} extends // extends {} implements var next = nextToken(); - return next === 24 /* CommaToken */ || next === 15 /* OpenBraceToken */ || next === 83 /* ExtendsKeyword */ || next === 106 /* ImplementsKeyword */; + return next === 25 /* CommaToken */ || next === 16 /* OpenBraceToken */ || next === 84 /* ExtendsKeyword */ || next === 107 /* ImplementsKeyword */; } return true; } @@ -13637,8 +15077,8 @@ var ts; return ts.tokenIsIdentifierOrKeyword(token()); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 /* ImplementsKeyword */ || - token() === 83 /* ExtendsKeyword */) { + if (token() === 107 /* ImplementsKeyword */ || + token() === 84 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -13661,44 +15101,45 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 21 /* ImportOrExportSpecifiers */: - return token() === 16 /* CloseBraceToken */; + case 22 /* ImportOrExportSpecifiers */: + return token() === 17 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token() === 17 /* CloseBraceToken */ || token() === 72 /* CaseKeyword */ || token() === 78 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 16 /* OpenBraceToken */ || token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 17 /* TypeParameters */: + case 18 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 28 /* GreaterThanToken */ || token() === 18 /* OpenParenToken */ || token() === 16 /* OpenBraceToken */ || token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; + return token() === 19 /* CloseParenToken */ || token() === 24 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 19 /* TupleElementTypes */: + case 20 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 20 /* CloseBracketToken */; + return token() === 21 /* CloseBracketToken */; case 16 /* Parameters */: + case 17 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; - case 20 /* HeritageClauses */: - return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; + return token() === 19 /* CloseParenToken */ || token() === 21 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 19 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 25 /* CommaToken */; + case 21 /* HeritageClauses */: + return token() === 16 /* OpenBraceToken */ || token() === 17 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; + return token() === 28 /* GreaterThanToken */ || token() === 40 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); - case 22 /* JSDocFunctionParameters */: - return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; - case 23 /* JSDocTypeArguments */: - return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; - case 25 /* JSDocTupleTypes */: - return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; - case 24 /* JSDocRecordMembers */: - return token() === 16 /* CloseBraceToken */; + return token() === 26 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + case 23 /* JSDocFunctionParameters */: + return token() === 19 /* CloseParenToken */ || token() === 55 /* ColonToken */ || token() === 17 /* CloseBraceToken */; + case 24 /* JSDocTypeArguments */: + return token() === 28 /* GreaterThanToken */ || token() === 17 /* CloseBraceToken */; + case 26 /* JSDocTupleTypes */: + return token() === 21 /* CloseBracketToken */ || token() === 17 /* CloseBraceToken */; + case 25 /* JSDocRecordMembers */: + return token() === 17 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -13716,7 +15157,7 @@ var ts; // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -13724,7 +15165,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 26 /* Count */; kind++) { + for (var kind = 0; kind < 27 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -13799,7 +15240,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 1540096 /* ContextFlags */; + var nodeContextFlags = node.flags & 96256 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -13834,20 +15275,22 @@ var ts; return isReusableVariableDeclaration(node); case 16 /* Parameters */: return isReusableParameter(node); + case 17 /* RestProperties */: + return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 20 /* HeritageClauses */: + case 21 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 17 /* TypeParameters */: + case 18 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 19 /* TupleElementTypes */: + case 20 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -13855,7 +15298,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 18 /* TypeArguments */: + case 19 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -13879,20 +15322,20 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 148 /* Constructor */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 145 /* PropertyDeclaration */: - case 198 /* SemicolonClassElement */: + case 150 /* Constructor */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 203 /* SemicolonClassElement */: return true; - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 69 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 121 /* ConstructorKeyword */; + var nameIsConstructor = methodDeclaration.name.kind === 70 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 122 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -13901,8 +15344,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: return true; } } @@ -13911,58 +15354,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 200 /* VariableStatement */: - case 199 /* Block */: - case 203 /* IfStatement */: - case 202 /* ExpressionStatement */: - case 215 /* ThrowStatement */: - case 211 /* ReturnStatement */: - case 213 /* SwitchStatement */: - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 201 /* EmptyStatement */: - case 216 /* TryStatement */: - case 214 /* LabeledStatement */: - case 204 /* DoStatement */: - case 217 /* DebuggerStatement */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + case 205 /* VariableStatement */: + case 204 /* Block */: + case 208 /* IfStatement */: + case 207 /* ExpressionStatement */: + case 220 /* ThrowStatement */: + case 216 /* ReturnStatement */: + case 218 /* SwitchStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 211 /* ForStatement */: + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + case 206 /* EmptyStatement */: + case 221 /* TryStatement */: + case 219 /* LabeledStatement */: + case 209 /* DoStatement */: + case 222 /* DebuggerStatement */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 228 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 255 /* EnumMember */; + return node.kind === 260 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 152 /* ConstructSignature */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 144 /* PropertySignature */: - case 151 /* CallSignature */: + case 154 /* ConstructSignature */: + case 148 /* MethodSignature */: + case 155 /* IndexSignature */: + case 146 /* PropertySignature */: + case 153 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 218 /* VariableDeclaration */) { + if (node.kind !== 223 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -13983,7 +15426,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 142 /* Parameter */) { + if (node.kind !== 144 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -14005,6 +15448,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; + case 17 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -14016,17 +15460,17 @@ var ts; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 17 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 18 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 19 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 20 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 21 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; - case 22 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 23 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 25 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; - case 24 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; + case 23 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 24 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 26 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; + case 25 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -14040,7 +15484,7 @@ var ts; if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); - if (parseOptional(24 /* CommaToken */)) { + if (parseOptional(25 /* CommaToken */)) { continue; } commaStart = -1; // Back to the state where the last token was not a comma @@ -14049,13 +15493,13 @@ var ts; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(24 /* CommaToken */); + parseExpected(25 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 24 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -14094,8 +15538,8 @@ var ts; // The allowReservedWords parameter controls whether reserved words are permitted after the first dot function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(21 /* DotToken */)) { - var node = createNode(139 /* QualifiedName */, entity.pos); // !!! + while (parseOptional(22 /* DotToken */)) { + var node = createNode(141 /* QualifiedName */, entity.pos); // !!! node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -14128,33 +15572,33 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); - ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + var template = createNode(194 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 13 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 13 /* TemplateMiddle */); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 14 /* TemplateMiddle */); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(197 /* TemplateSpan */); + var span = createNode(202 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16 /* CloseBraceToken */) { + if (token() === 17 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); + literal = parseExpectedToken(15 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(17 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -14162,8 +15606,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 14 /* TemplateMiddle */ || fragment.kind === 15 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14194,35 +15645,35 @@ var ts; // TYPES function parseTypeReference() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - var node = createNode(155 /* TypeReference */, typeName.pos); + var node = createNode(157 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { - node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (!scanner.hasPrecedingLineBreak() && token() === 26 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(154 /* TypePredicate */, lhs.pos); + var node = createNode(156 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(165 /* ThisType */); + var node = createNode(167 /* ThisType */); nextToken(); return finishNode(node); } function parseTypeQuery() { - var node = createNode(158 /* TypeQuery */); - parseExpected(101 /* TypeOfKeyword */); + var node = createNode(160 /* TypeQuery */); + parseExpected(102 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(141 /* TypeParameter */); + var node = createNode(143 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(83 /* ExtendsKeyword */)) { + if (parseOptional(84 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the // user writes a constraint that is an expression and not an actual type, then parse // it out as an expression (so we can recover well), but report that a type is needed @@ -14244,29 +15695,29 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25 /* LessThanToken */) { - return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (token() === 26 /* LessThanToken */) { + return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(54 /* ColonToken */)) { + if (parseOptional(55 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; + return token() === 23 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 /* AtToken */ || token() === 98 /* ThisKeyword */; } function parseParameter() { - var node = createNode(142 /* Parameter */); - if (token() === 97 /* ThisKeyword */) { + var node = createNode(144 /* Parameter */); + if (token() === 98 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); @@ -14281,7 +15732,7 @@ var ts; // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(53 /* QuestionToken */); + node.questionToken = parseOptionalToken(54 /* QuestionToken */); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(/*inParameter*/ true); // Do not check for initializers in an ambient context for parameters. This is not @@ -14301,7 +15752,7 @@ var ts; return parseInitializer(/*inParameter*/ true); } function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 34 /* EqualsGreaterThanToken */; + var returnTokenRequired = returnToken === 35 /* EqualsGreaterThanToken */; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { @@ -14326,7 +15777,7 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(17 /* OpenParenToken */)) { + if (parseExpected(18 /* OpenParenToken */)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); @@ -14334,7 +15785,7 @@ var ts; var result = parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(18 /* CloseParenToken */) && requireCompleteParameterList) { + if (!parseExpected(19 /* CloseParenToken */) && requireCompleteParameterList) { // Caller insisted that we had to end with a ) We didn't. So just return // undefined here. return undefined; @@ -14349,7 +15800,7 @@ var ts; function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. - if (parseOptional(24 /* CommaToken */)) { + if (parseOptional(25 /* CommaToken */)) { return; } // Didn't have a comma. We must have a (possible ASI) semicolon. @@ -14357,15 +15808,15 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 152 /* ConstructSignature */) { - parseExpected(92 /* NewKeyword */); + if (kind === 154 /* ConstructSignature */) { + parseExpected(93 /* NewKeyword */); } - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(node)); } function isIndexSignature() { - if (token() !== 19 /* OpenBracketToken */) { + if (token() !== 20 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -14388,7 +15839,7 @@ var ts; // [] // nextToken(); - if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { + if (token() === 23 /* DotDotDotToken */ || token() === 21 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -14407,49 +15858,49 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { + if (token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 53 /* QuestionToken */) { + if (token() !== 54 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; + return token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */ || token() === 21 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(153 /* IndexSignature */, fullStart); + var node = createNode(155 /* IndexSignature */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { - var method = createNode(146 /* MethodSignature */, fullStart); + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { + var method = createNode(148 /* MethodSignature */, fullStart); method.modifiers = modifiers; method.name = name; method.questionToken = questionToken; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); return addJSDocComment(finishNode(method)); } else { - var property = createNode(144 /* PropertySignature */, fullStart); + var property = createNode(146 /* PropertySignature */, fullStart); property.modifiers = modifiers; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56 /* EqualsToken */) { + if (token() === 57 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -14462,7 +15913,7 @@ var ts; function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier @@ -14471,7 +15922,7 @@ var ts; nextToken(); } // Index signatures and computed property names are type members - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers @@ -14482,21 +15933,21 @@ var ts; // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 17 /* OpenParenToken */ || - token() === 25 /* LessThanToken */ || - token() === 53 /* QuestionToken */ || - token() === 54 /* ColonToken */ || - token() === 24 /* CommaToken */ || + return token() === 18 /* OpenParenToken */ || + token() === 26 /* LessThanToken */ || + token() === 54 /* QuestionToken */ || + token() === 55 /* ColonToken */ || + token() === 25 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { - return parseSignatureMember(151 /* CallSignature */); + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { + return parseSignatureMember(153 /* CallSignature */); } - if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(152 /* ConstructSignature */); + if (token() === 93 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(154 /* ConstructSignature */); } var fullStart = getNodePos(); var modifiers = parseModifiers(); @@ -14507,50 +15958,77 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; + return token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(159 /* TypeLiteral */); + var node = createNode(161 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(15 /* OpenBraceToken */)) { + if (parseExpected(16 /* OpenBraceToken */)) { members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { members = createMissingList(); } return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === 130 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 20 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 91 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(143 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(91 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(170 /* MappedType */); + parseExpected(16 /* OpenBraceToken */); + node.readonlyToken = parseOptionalToken(130 /* ReadonlyKeyword */); + parseExpected(20 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(21 /* CloseBracketToken */); + node.questionToken = parseOptionalToken(54 /* QuestionToken */); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(17 /* CloseBraceToken */); + return finishNode(node); + } function parseTupleType() { - var node = createNode(161 /* TupleType */); - node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + var node = createNode(163 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(164 /* ParenthesizedType */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(166 /* ParenthesizedType */); + parseExpected(18 /* OpenParenToken */); node.type = parseType(); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 157 /* ConstructorType */) { - parseExpected(92 /* NewKeyword */); + if (kind === 159 /* ConstructorType */) { + parseExpected(93 /* NewKeyword */); } - fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(35 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 /* DotToken */ ? undefined : node; + return token() === 22 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode() { - var node = createNode(166 /* LiteralType */); + var node = createNode(171 /* LiteralType */); node.literal = parseSimpleUnaryExpression(); finishNode(node); return node; @@ -14560,42 +16038,42 @@ var ts; } function parseNonArrayType() { switch (token()) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseLiteralTypeNode(); - case 36 /* MinusToken */: + case 37 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: + case 104 /* VoidKeyword */: + case 94 /* NullKeyword */: return parseTokenNode(); - case 97 /* ThisKeyword */: { + case 98 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 101 /* TypeOfKeyword */: + case 102 /* TypeOfKeyword */: return parseTypeQuery(); - case 15 /* OpenBraceToken */: - return parseTypeLiteral(); - case 19 /* OpenBracketToken */: + case 16 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 20 /* OpenBracketToken */: return parseTupleType(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseParenthesizedType(); default: return parseTypeReference(); @@ -14603,29 +16081,31 @@ var ts; } function isStartOfType() { switch (token()) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 97 /* ThisKeyword */: - case 101 /* TypeOfKeyword */: - case 127 /* NeverKeyword */: - case 15 /* OpenBraceToken */: - case 19 /* OpenBracketToken */: - case 25 /* LessThanToken */: - case 92 /* NewKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 98 /* ThisKeyword */: + case 102 /* TypeOfKeyword */: + case 129 /* NeverKeyword */: + case 16 /* OpenBraceToken */: + case 20 /* OpenBracketToken */: + case 26 /* LessThanToken */: + case 48 /* BarToken */: + case 47 /* AmpersandToken */: + case 93 /* NewKeyword */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return true; - case 36 /* MinusToken */: + case 37 /* MinusToken */: return lookAhead(nextTokenIsNumericLiteral); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. return lookAhead(isStartOfParenthesizedOrFunctionType); @@ -14635,19 +16115,43 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 19 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { - parseExpected(20 /* CloseBracketToken */); - var node = createNode(160 /* ArrayType */, type.pos); - node.elementType = type; - type = finishNode(node); + while (!scanner.hasPrecedingLineBreak() && parseOptional(20 /* OpenBracketToken */)) { + if (isStartOfType()) { + var node = createNode(169 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(21 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(162 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(21 /* CloseBracketToken */); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator) { + var node = createNode(168 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 126 /* KeyOfKeyword */: + return parseTypeOperator(126 /* KeyOfKeyword */); + } + return parseArrayTypeOrHigher(); + } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { var types = createNodeArray([type], type.pos); @@ -14662,27 +16166,27 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(163 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + return parseUnionOrIntersectionType(165 /* IntersectionType */, parseTypeOperatorOrHigher, 47 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + return parseUnionOrIntersectionType(164 /* UnionType */, parseIntersectionTypeOrHigher, 48 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { return true; } - return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 18 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 97 /* ThisKeyword */) { + if (isIdentifier() || token() === 98 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { + if (token() === 20 /* OpenBracketToken */ || token() === 16 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -14692,7 +16196,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { + if (token() === 19 /* CloseParenToken */ || token() === 23 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -14700,17 +16204,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || - token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { + if (token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */ || + token() === 54 /* QuestionToken */ || token() === 57 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 18 /* CloseParenToken */) { + if (token() === 19 /* CloseParenToken */) { nextToken(); - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -14722,7 +16226,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(154 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(156 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -14733,7 +16237,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 125 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -14741,41 +16245,41 @@ var ts; function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(327680 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(156 /* FunctionType */); + return parseFunctionOrConstructorType(158 /* FunctionType */); } - if (token() === 92 /* NewKeyword */) { - return parseFunctionOrConstructorType(157 /* ConstructorType */); + if (token() === 93 /* NewKeyword */) { + return parseFunctionOrConstructorType(159 /* ConstructorType */); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(54 /* ColonToken */) ? parseType() : undefined; + return parseOptional(55 /* ColonToken */) ? parseType() : undefined; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 17 /* OpenParenToken */: - case 19 /* OpenBracketToken */: - case 15 /* OpenBraceToken */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 92 /* NewKeyword */: - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - case 69 /* Identifier */: + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 18 /* OpenParenToken */: + case 20 /* OpenBracketToken */: + case 16 /* OpenBraceToken */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 93 /* NewKeyword */: + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + case 70 /* Identifier */: return true; default: return isIdentifier(); @@ -14786,18 +16290,18 @@ var ts; return true; } switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 78 /* DeleteKeyword */: - case 101 /* TypeOfKeyword */: - case 103 /* VoidKeyword */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: - case 25 /* LessThanToken */: - case 119 /* AwaitKeyword */: - case 114 /* YieldKeyword */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 79 /* DeleteKeyword */: + case 102 /* TypeOfKeyword */: + case 104 /* VoidKeyword */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: + case 26 /* LessThanToken */: + case 120 /* AwaitKeyword */: + case 115 /* YieldKeyword */: // Yield/await always starts an expression. Either it is an identifier (in which case // it is definitely an expression). Or it's a keyword (either because we're in // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. @@ -14815,10 +16319,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 15 /* OpenBraceToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && - token() !== 55 /* AtToken */ && + return token() !== 16 /* OpenBraceToken */ && + token() !== 88 /* FunctionKeyword */ && + token() !== 74 /* ClassKeyword */ && + token() !== 56 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -14832,7 +16336,7 @@ var ts; } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(24 /* CommaToken */))) { + while ((operatorToken = parseOptionalToken(25 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { @@ -14841,7 +16345,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56 /* EqualsToken */) { + if (token() !== 57 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -14850,7 +16354,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 16 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -14858,7 +16362,7 @@ var ts; } // Initializer[In, Yield] : // = AssignmentExpression[?In, ?Yield] - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); return parseAssignmentExpressionOrHigher(); } function parseAssignmentExpressionOrHigher() { @@ -14904,7 +16408,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 70 /* Identifier */ && token() === 35 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -14920,7 +16424,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114 /* YieldKeyword */) { + if (token() === 115 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -14949,15 +16453,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(190 /* YieldExpression */); + var node = createNode(195 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + (token() === 38 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -14968,21 +16472,21 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 35 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(180 /* ArrowFunction */, asyncModifier.pos); + node = createNode(185 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(180 /* ArrowFunction */, identifier.pos); + node = createNode(185 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(142 /* Parameter */, identifier.pos); + var parameter = createNode(144 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos); node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(35 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } @@ -15007,8 +16511,8 @@ var ts; // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(35 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 35 /* EqualsGreaterThanToken */ || lastToken === 16 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); return addJSDocComment(finishNode(arrowFunction)); @@ -15018,10 +16522,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { + if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */ || token() === 119 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token() === 35 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -15031,28 +16535,28 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { + if (token() !== 18 /* OpenParenToken */ && token() !== 26 /* LessThanToken */) { return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 17 /* OpenParenToken */) { - if (second === 18 /* CloseParenToken */) { + if (first === 18 /* OpenParenToken */) { + if (second === 19 /* CloseParenToken */) { // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 34 /* EqualsGreaterThanToken */: - case 54 /* ColonToken */: - case 15 /* OpenBraceToken */: + case 35 /* EqualsGreaterThanToken */: + case 55 /* ColonToken */: + case 16 /* OpenBraceToken */: return 1 /* True */; default: return 0 /* False */; @@ -15064,12 +16568,12 @@ var ts; // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === 19 /* OpenBracketToken */ || second === 15 /* OpenBraceToken */) { + if (second === 20 /* OpenBracketToken */ || second === 16 /* OpenBraceToken */) { return 2 /* Unknown */; } // Simple case: "(..." // This is an arrow function with a rest parameter. - if (second === 22 /* DotDotDotToken */) { + if (second === 23 /* DotDotDotToken */) { return 1 /* True */; } // If we had "(" followed by something that's not an identifier, @@ -15082,7 +16586,7 @@ var ts; } // If we have something like "(a:", then we must have a // type-annotated parameter in an arrow function expression. - if (nextToken() === 54 /* ColonToken */) { + if (nextToken() === 55 /* ColonToken */) { return 1 /* True */; } // This *could* be a parenthesized arrow function. @@ -15090,7 +16594,7 @@ var ts; return 2 /* Unknown */; } else { - ts.Debug.assert(first === 25 /* LessThanToken */); + ts.Debug.assert(first === 26 /* LessThanToken */); // If we have "<" not followed by an identifier, // then this definitely is not an arrow function. if (!isIdentifier()) { @@ -15100,17 +16604,17 @@ var ts; if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 83 /* ExtendsKeyword */) { + if (third === 84 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 56 /* EqualsToken */: - case 27 /* GreaterThanToken */: + case 57 /* EqualsToken */: + case 28 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 24 /* CommaToken */) { + else if (third === 25 /* CommaToken */) { return true; } return false; @@ -15129,7 +16633,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -15143,23 +16647,23 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token() === 35 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 70 /* Identifier */ && token() === 35 /* EqualsGreaterThanToken */) { return 1 /* True */; } } return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(180 /* ArrowFunction */); + var node = createNode(185 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); // Arrow functions are never generators. @@ -15169,7 +16673,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; @@ -15182,19 +16686,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token() !== 35 /* EqualsGreaterThanToken */ && token() !== 16 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token() !== 23 /* SemicolonToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && + if (token() !== 24 /* SemicolonToken */ && + token() !== 88 /* FunctionKeyword */ && + token() !== 74 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -15219,17 +16723,17 @@ var ts; } function parseConditionalExpressionRest(leftOperand) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(53 /* QuestionToken */); + var questionToken = parseOptionalToken(54 /* QuestionToken */); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(188 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(193 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(54 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(54 /* ColonToken */)); + node.colonToken = parseExpectedToken(55 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(55 /* ColonToken */)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -15238,7 +16742,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 /* InKeyword */ || t === 138 /* OfKeyword */; + return t === 91 /* InKeyword */ || t === 140 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -15267,16 +16771,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token() === 39 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 /* InKeyword */ && inDisallowInContext()) { + if (token() === 91 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 116 /* AsKeyword */) { + if (token() === 117 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -15297,48 +16801,48 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90 /* InKeyword */) { + if (inDisallowInContext() && token() === 91 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return 1; - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return 2; - case 47 /* BarToken */: + case 48 /* BarToken */: return 3; - case 48 /* CaretToken */: + case 49 /* CaretToken */: return 4; - case 46 /* AmpersandToken */: + case 47 /* AmpersandToken */: return 5; - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return 6; - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: + case 92 /* InstanceOfKeyword */: + case 91 /* InKeyword */: + case 117 /* AsKeyword */: return 7; - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return 8; - case 35 /* PlusToken */: - case 36 /* MinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: return 9; - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: return 10; - case 38 /* AsteriskAsteriskToken */: + case 39 /* AsteriskAsteriskToken */: return 11; } // -1 is lower than all other precedences. Returning it will cause binary expression @@ -15346,45 +16850,45 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(187 /* BinaryExpression */, left.pos); + var node = createNode(192 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(195 /* AsExpression */, left.pos); + var node = createNode(200 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(185 /* PrefixUnaryExpression */); + var node = createNode(190 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(181 /* DeleteExpression */); + var node = createNode(186 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(182 /* TypeOfExpression */); + var node = createNode(187 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(183 /* VoidExpression */); + var node = createNode(188 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 119 /* AwaitKeyword */) { + if (token() === 120 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -15394,7 +16898,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(184 /* AwaitExpression */); + var node = createNode(189 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15418,7 +16922,7 @@ var ts; */ if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 /* AsteriskAsteriskToken */ ? + return token() === 39 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } @@ -15435,9 +16939,9 @@ var ts; */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38 /* AsteriskAsteriskToken */) { + if (token() === 39 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 182 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -15462,23 +16966,23 @@ var ts; */ function parseSimpleUnaryExpression() { switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 78 /* DeleteKeyword */: + case 79 /* DeleteKeyword */: return parseDeleteExpression(); - case 101 /* TypeOfKeyword */: + case 102 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return parseVoidExpression(); - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 119 /* AwaitKeyword */: + case 120 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } @@ -15500,16 +17004,16 @@ var ts; // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly switch (token()) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 78 /* DeleteKeyword */: - case 101 /* TypeOfKeyword */: - case 103 /* VoidKeyword */: - case 119 /* AwaitKeyword */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 79 /* DeleteKeyword */: + case 102 /* TypeOfKeyword */: + case 104 /* VoidKeyword */: + case 120 /* AwaitKeyword */: return false; - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression if (sourceFile.languageVariant !== 1 /* JSX */) { return false; @@ -15532,21 +17036,21 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { - var node = createNode(185 /* PrefixUnaryExpression */); + if (token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) { + var node = createNode(190 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 26 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); + if ((token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(191 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -15585,7 +17089,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token() === 95 /* SuperKeyword */ + var expression = token() === 96 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -15645,14 +17149,14 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { + if (token() === 18 /* OpenParenToken */ || token() === 22 /* DotToken */ || token() === 20 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(172 /* PropertyAccessExpression */, expression.pos); + var node = createNode(177 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(22 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -15660,10 +17164,10 @@ var ts; if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 69 /* Identifier */) { + if (lhs.kind === 70 /* Identifier */) { return lhs.text === rhs.text; } - if (lhs.kind === 97 /* ThisKeyword */) { + if (lhs.kind === 98 /* ThisKeyword */) { return true; } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only @@ -15675,8 +17179,8 @@ var ts; function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 243 /* JsxOpeningElement */) { - var node = createNode(241 /* JsxElement */, opening.pos); + if (opening.kind === 248 /* JsxOpeningElement */) { + var node = createNode(246 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -15686,7 +17190,7 @@ var ts; result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 242 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 247 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -15697,15 +17201,15 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 25 /* LessThanToken */) { + if (inExpressionContext && token() === 26 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(187 /* BinaryExpression */, result.pos); + var badNode = createNode(192 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(24 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(25 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -15713,17 +17217,17 @@ var ts; return result; } function parseJsxText() { - var node = createNode(244 /* JsxText */, scanner.getStartPos()); + var node = createNode(10 /* JsxText */, scanner.getStartPos()); currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 244 /* JsxText */: + case 10 /* JsxText */: return parseJsxText(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); - case 25 /* LessThanToken */: + case 26 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } ts.Debug.fail("Unknown JSX child kind " + token()); @@ -15734,7 +17238,7 @@ var ts; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 26 /* LessThanSlashToken */) { + if (token() === 27 /* LessThanSlashToken */) { // Closing tag break; } @@ -15752,27 +17256,27 @@ var ts; } function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(25 /* LessThanToken */); + parseExpected(26 /* LessThanToken */); var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token() === 27 /* GreaterThanToken */) { + if (token() === 28 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(243 /* JsxOpeningElement */, fullStart); + node = createNode(248 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(39 /* SlashToken */); + parseExpected(40 /* SlashToken */); if (inExpressionContext) { - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(28 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(242 /* JsxSelfClosingElement */, fullStart); + node = createNode(247 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -15785,10 +17289,10 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 97 /* ThisKeyword */ ? + var expression = token() === 98 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(21 /* DotToken */)) { - var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); + while (parseOptional(22 /* DotToken */)) { + var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15796,28 +17300,28 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(248 /* JsxExpression */); - parseExpected(15 /* OpenBraceToken */); - if (token() !== 16 /* CloseBraceToken */) { + var node = createNode(252 /* JsxExpression */); + parseExpected(16 /* OpenBraceToken */); + if (token() !== 17 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + parseExpected(17 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(246 /* JsxAttribute */); + var node = createNode(250 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 56 /* EqualsToken */) { + if (token() === 57 /* EqualsToken */) { switch (scanJsxAttributeValue()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); @@ -15830,72 +17334,72 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(247 /* JsxSpreadAttribute */); - parseExpected(15 /* OpenBraceToken */); - parseExpected(22 /* DotDotDotToken */); + var node = createNode(251 /* JsxSpreadAttribute */); + parseExpected(16 /* OpenBraceToken */); + parseExpected(23 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(245 /* JsxClosingElement */); - parseExpected(26 /* LessThanSlashToken */); + var node = createNode(249 /* JsxClosingElement */); + parseExpected(27 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + parseExpected(28 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(177 /* TypeAssertionExpression */); - parseExpected(25 /* LessThanToken */); + var node = createNode(182 /* TypeAssertionExpression */); + parseExpected(26 /* LessThanToken */); node.type = parseType(); - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(21 /* DotToken */); + var dotToken = parseOptionalToken(22 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 50 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(201 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(173 /* ElementAccessExpression */, expression.pos); + if (!inDecoratorContext() && parseOptional(20 /* OpenBracketToken */)) { + var indexedAccess = createNode(178 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token() !== 20 /* CloseBracketToken */) { + if (token() !== 21 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } - if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { - var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); + if (token() === 12 /* NoSubstitutionTemplateLiteral */ || token() === 13 /* TemplateHead */) { + var tagExpression = createNode(181 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token() === 12 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -15907,7 +17411,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -15916,15 +17420,15 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(174 /* CallExpression */, expression.pos); + var callExpr = createNode(179 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 17 /* OpenParenToken */) { - var callExpr = createNode(174 /* CallExpression */, expression.pos); + else if (token() === 18 /* OpenParenToken */) { + var callExpr = createNode(179 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -15934,17 +17438,17 @@ var ts; } } function parseArgumentList() { - parseExpected(17 /* OpenParenToken */); + parseExpected(18 /* OpenParenToken */); var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(25 /* LessThanToken */)) { + if (!parseOptional(26 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(18 /* TypeArguments */, parseType); - if (!parseExpected(27 /* GreaterThanToken */)) { + var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + if (!parseExpected(28 /* GreaterThanToken */)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; } @@ -15956,32 +17460,32 @@ var ts; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 17 /* OpenParenToken */: // foo( + case 18 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. - case 21 /* DotToken */: // foo. - case 18 /* CloseParenToken */: // foo) - case 20 /* CloseBracketToken */: // foo] - case 54 /* ColonToken */: // foo: - case 23 /* SemicolonToken */: // foo; - case 53 /* QuestionToken */: // foo? - case 30 /* EqualsEqualsToken */: // foo == - case 32 /* EqualsEqualsEqualsToken */: // foo === - case 31 /* ExclamationEqualsToken */: // foo != - case 33 /* ExclamationEqualsEqualsToken */: // foo !== - case 51 /* AmpersandAmpersandToken */: // foo && - case 52 /* BarBarToken */: // foo || - case 48 /* CaretToken */: // foo ^ - case 46 /* AmpersandToken */: // foo & - case 47 /* BarToken */: // foo | - case 16 /* CloseBraceToken */: // foo } + case 22 /* DotToken */: // foo. + case 19 /* CloseParenToken */: // foo) + case 21 /* CloseBracketToken */: // foo] + case 55 /* ColonToken */: // foo: + case 24 /* SemicolonToken */: // foo; + case 54 /* QuestionToken */: // foo? + case 31 /* EqualsEqualsToken */: // foo == + case 33 /* EqualsEqualsEqualsToken */: // foo === + case 32 /* ExclamationEqualsToken */: // foo != + case 34 /* ExclamationEqualsEqualsToken */: // foo !== + case 52 /* AmpersandAmpersandToken */: // foo && + case 53 /* BarBarToken */: // foo || + case 49 /* CaretToken */: // foo ^ + case 47 /* AmpersandToken */: // foo & + case 48 /* BarToken */: // foo | + case 17 /* CloseBraceToken */: // foo } case 1 /* EndOfFileToken */: // these cases can't legally follow a type arg list. However, they're not legal // expressions either. The user is probably in the middle of a generic type. So // treat it as such. return true; - case 24 /* CommaToken */: // foo, - case 15 /* OpenBraceToken */: // foo { + case 25 /* CommaToken */: // foo, + case 16 /* OpenBraceToken */: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. @@ -15994,21 +17498,21 @@ var ts; switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 97 /* ThisKeyword */: - case 95 /* SuperKeyword */: - case 93 /* NullKeyword */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 98 /* ThisKeyword */: + case 96 /* SuperKeyword */: + case 94 /* NullKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseTokenNode(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseParenthesizedExpression(); - case 19 /* OpenBracketToken */: + case 20 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 118 /* AsyncKeyword */: + case 119 /* AsyncKeyword */: // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. @@ -16016,77 +17520,83 @@ var ts; break; } return parseFunctionExpression(); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassExpression(); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionExpression(); - case 92 /* NewKeyword */: + case 93 /* NewKeyword */: return parseNewExpression(); - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - if (reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + if (reScanSlashToken() === 11 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 12 /* TemplateHead */: + case 13 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(178 /* ParenthesizedExpression */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(183 /* ParenthesizedExpression */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(191 /* SpreadElementExpression */); - parseExpected(22 /* DotDotDotToken */); + var node = createNode(196 /* SpreadElement */); + parseExpected(23 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token() === 23 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 25 /* CommaToken */ ? createNode(198 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(170 /* ArrayLiteralExpression */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(175 /* ArrayLiteralExpression */); + parseExpected(20 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(123 /* GetKeyword */)) { - return parseAccessorDeclaration(149 /* GetAccessor */, fullStart, decorators, modifiers); + if (parseContextualModifier(124 /* GetKeyword */)) { + return parseAccessorDeclaration(151 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(131 /* SetKeyword */)) { - return parseAccessorDeclaration(150 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(133 /* SetKeyword */)) { + return parseAccessorDeclaration(152 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); + if (dotDotDotToken) { + var spreadElement = createNode(259 /* SpreadAssignment */, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } var decorators = parseDecorators(); var modifiers = parseModifiers(); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (asteriskToken || token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -16094,12 +17604,12 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 /* CommaToken */ || token() === 17 /* CloseBraceToken */ || token() === 57 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(258 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(56 /* EqualsToken */); + var equalsToken = parseOptionalToken(57 /* EqualsToken */); if (equalsToken) { shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); @@ -16107,23 +17617,23 @@ var ts; return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(253 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(257 /* PropertyAssignment */, fullStart); propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(171 /* ObjectLiteralExpression */); - parseExpected(15 /* OpenBraceToken */); + var node = createNode(176 /* ObjectLiteralExpression */); + parseExpected(16 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { @@ -16136,10 +17646,10 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNode(179 /* FunctionExpression */); + var node = createNode(184 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(87 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + parseExpected(88 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); node.name = @@ -16147,7 +17657,7 @@ var ts; isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -16158,24 +17668,24 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(175 /* NewExpression */); - parseExpected(92 /* NewKeyword */); + var node = createNode(180 /* NewExpression */); + parseExpected(93 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17 /* OpenParenToken */) { + if (node.typeArguments || token() === 18 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(199 /* Block */); - if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(204 /* Block */); + if (parseExpected(16 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -16202,51 +17712,51 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(201 /* EmptyStatement */); - parseExpected(23 /* SemicolonToken */); + var node = createNode(206 /* EmptyStatement */); + parseExpected(24 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(203 /* IfStatement */); - parseExpected(88 /* IfKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(208 /* IfStatement */); + parseExpected(89 /* IfKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(80 /* ElseKeyword */) ? parseStatement() : undefined; + node.elseStatement = parseOptional(81 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(204 /* DoStatement */); - parseExpected(79 /* DoKeyword */); + var node = createNode(209 /* DoStatement */); + parseExpected(80 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(104 /* WhileKeyword */); - parseExpected(17 /* OpenParenToken */); + parseExpected(105 /* WhileKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. - parseOptional(23 /* SemicolonToken */); + parseOptional(24 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(205 /* WhileStatement */); - parseExpected(104 /* WhileKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(210 /* WhileStatement */); + parseExpected(105 /* WhileKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(86 /* ForKeyword */); - parseExpected(17 /* OpenParenToken */); + parseExpected(87 /* ForKeyword */); + parseExpected(18 /* OpenParenToken */); var initializer = undefined; - if (token() !== 23 /* SemicolonToken */) { - if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { + if (token() !== 24 /* SemicolonToken */) { + if (token() === 103 /* VarKeyword */ || token() === 109 /* LetKeyword */ || token() === 75 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -16254,32 +17764,32 @@ var ts; } } var forOrForInOrForOfStatement; - if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(207 /* ForInStatement */, pos); + if (parseOptional(91 /* InKeyword */)) { + var forInStatement = createNode(212 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(138 /* OfKeyword */)) { - var forOfStatement = createNode(208 /* ForOfStatement */, pos); + else if (parseOptional(140 /* OfKeyword */)) { + var forOfStatement = createNode(213 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(206 /* ForStatement */, pos); + var forStatement = createNode(211 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(23 /* SemicolonToken */); - if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { + parseExpected(24 /* SemicolonToken */); + if (token() !== 24 /* SemicolonToken */ && token() !== 19 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(23 /* SemicolonToken */); - if (token() !== 18 /* CloseParenToken */) { + parseExpected(24 /* SemicolonToken */); + if (token() !== 19 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -16287,7 +17797,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 210 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 215 /* BreakStatement */ ? 71 /* BreakKeyword */ : 76 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -16295,8 +17805,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(211 /* ReturnStatement */); - parseExpected(94 /* ReturnKeyword */); + var node = createNode(216 /* ReturnStatement */); + parseExpected(95 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -16304,42 +17814,42 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(212 /* WithStatement */); - parseExpected(105 /* WithKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(217 /* WithStatement */); + parseExpected(106 /* WithKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseCaseClause() { - var node = createNode(249 /* CaseClause */); - parseExpected(71 /* CaseKeyword */); + var node = createNode(253 /* CaseClause */); + parseExpected(72 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(250 /* DefaultClause */); - parseExpected(77 /* DefaultKeyword */); - parseExpected(54 /* ColonToken */); + var node = createNode(254 /* DefaultClause */); + parseExpected(78 /* DefaultKeyword */); + parseExpected(55 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token() === 72 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(213 /* SwitchStatement */); - parseExpected(96 /* SwitchKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(218 /* SwitchStatement */); + parseExpected(97 /* SwitchKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(227 /* CaseBlock */, scanner.getStartPos()); - parseExpected(15 /* OpenBraceToken */); + parseExpected(19 /* CloseParenToken */); + var caseBlock = createNode(232 /* CaseBlock */, scanner.getStartPos()); + parseExpected(16 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } @@ -16351,39 +17861,39 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(215 /* ThrowStatement */); - parseExpected(98 /* ThrowKeyword */); + var node = createNode(220 /* ThrowStatement */); + parseExpected(99 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(216 /* TryStatement */); - parseExpected(100 /* TryKeyword */); + var node = createNode(221 /* TryStatement */); + parseExpected(101 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token() === 73 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 85 /* FinallyKeyword */) { - parseExpected(85 /* FinallyKeyword */); + if (!node.catchClause || token() === 86 /* FinallyKeyword */) { + parseExpected(86 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(252 /* CatchClause */); - parseExpected(72 /* CatchKeyword */); - if (parseExpected(17 /* OpenParenToken */)) { + var result = createNode(256 /* CatchClause */); + parseExpected(73 /* CatchKeyword */); + if (parseExpected(18 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); } - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(217 /* DebuggerStatement */); - parseExpected(76 /* DebuggerKeyword */); + var node = createNode(222 /* DebuggerStatement */); + parseExpected(77 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } @@ -16393,14 +17903,14 @@ var ts; // a colon. var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); - if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(214 /* LabeledStatement */, fullStart); + if (expression.kind === 70 /* Identifier */ && parseOptional(55 /* ColonToken */)) { + var labeledStatement = createNode(219 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(202 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(207 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return addJSDocComment(finishNode(expressionStatement)); @@ -16412,7 +17922,7 @@ var ts; } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token() === 88 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); @@ -16421,12 +17931,12 @@ var ts; function isDeclaration() { while (true) { switch (token()) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: return true; // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; // however, an identifier cannot be followed by another identifier on the same line. This is what we @@ -16449,41 +17959,41 @@ var ts; // I {} // // could be legal, it would add complexity for very little gain. - case 107 /* InterfaceKeyword */: - case 134 /* TypeKeyword */: + case 108 /* InterfaceKeyword */: + case 136 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 122 /* DeclareKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 128 /* ReadonlyKeyword */: + case 116 /* AbstractKeyword */: + case 119 /* AsyncKeyword */: + case 123 /* DeclareKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 130 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 137 /* GlobalKeyword */: + case 139 /* GlobalKeyword */: nextToken(); - return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; - case 89 /* ImportKeyword */: + return token() === 16 /* OpenBraceToken */ || token() === 70 /* Identifier */ || token() === 83 /* ExportKeyword */; + case 90 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 82 /* ExportKeyword */: + return token() === 9 /* StringLiteral */ || token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 83 /* ExportKeyword */: nextToken(); - if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || - token() === 116 /* AsKeyword */) { + if (token() === 57 /* EqualsToken */ || token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */ || token() === 78 /* DefaultKeyword */ || + token() === 117 /* AsKeyword */) { return true; } continue; - case 113 /* StaticKeyword */: + case 114 /* StaticKeyword */: nextToken(); continue; default: @@ -16496,49 +18006,49 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 55 /* AtToken */: - case 23 /* SemicolonToken */: - case 15 /* OpenBraceToken */: - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 87 /* FunctionKeyword */: - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 88 /* IfKeyword */: - case 79 /* DoKeyword */: - case 104 /* WhileKeyword */: - case 86 /* ForKeyword */: - case 75 /* ContinueKeyword */: - case 70 /* BreakKeyword */: - case 94 /* ReturnKeyword */: - case 105 /* WithKeyword */: - case 96 /* SwitchKeyword */: - case 98 /* ThrowKeyword */: - case 100 /* TryKeyword */: - case 76 /* DebuggerKeyword */: + case 56 /* AtToken */: + case 24 /* SemicolonToken */: + case 16 /* OpenBraceToken */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 88 /* FunctionKeyword */: + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: + case 89 /* IfKeyword */: + case 80 /* DoKeyword */: + case 105 /* WhileKeyword */: + case 87 /* ForKeyword */: + case 76 /* ContinueKeyword */: + case 71 /* BreakKeyword */: + case 95 /* ReturnKeyword */: + case 106 /* WithKeyword */: + case 97 /* SwitchKeyword */: + case 99 /* ThrowKeyword */: + case 101 /* TryKeyword */: + case 77 /* DebuggerKeyword */: // 'catch' and 'finally' do not actually indicate that the code is part of a statement, // however, we say they are here so that we may gracefully parse them and error later. - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return true; - case 74 /* ConstKeyword */: - case 82 /* ExportKeyword */: - case 89 /* ImportKeyword */: + case 75 /* ConstKeyword */: + case 83 /* ExportKeyword */: + case 90 /* ImportKeyword */: return isStartOfDeclaration(); - case 118 /* AsyncKeyword */: - case 122 /* DeclareKeyword */: - case 107 /* InterfaceKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: - case 134 /* TypeKeyword */: - case 137 /* GlobalKeyword */: + case 119 /* AsyncKeyword */: + case 123 /* DeclareKeyword */: + case 108 /* InterfaceKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 136 /* TypeKeyword */: + case 139 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); @@ -16548,7 +18058,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; + return isIdentifier() || token() === 16 /* OpenBraceToken */ || token() === 20 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -16557,67 +18067,67 @@ var ts; } function parseStatement() { switch (token()) { - case 23 /* SemicolonToken */: + case 24 /* SemicolonToken */: return parseEmptyStatement(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 102 /* VarKeyword */: + case 103 /* VarKeyword */: return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 108 /* LetKeyword */: + case 109 /* LetKeyword */: if (isLetDeclaration()) { return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); } break; - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 88 /* IfKeyword */: + case 89 /* IfKeyword */: return parseIfStatement(); - case 79 /* DoKeyword */: + case 80 /* DoKeyword */: return parseDoStatement(); - case 104 /* WhileKeyword */: + case 105 /* WhileKeyword */: return parseWhileStatement(); - case 86 /* ForKeyword */: + case 87 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(209 /* ContinueStatement */); - case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(210 /* BreakStatement */); - case 94 /* ReturnKeyword */: + case 76 /* ContinueKeyword */: + return parseBreakOrContinueStatement(214 /* ContinueStatement */); + case 71 /* BreakKeyword */: + return parseBreakOrContinueStatement(215 /* BreakStatement */); + case 95 /* ReturnKeyword */: return parseReturnStatement(); - case 105 /* WithKeyword */: + case 106 /* WithKeyword */: return parseWithStatement(); - case 96 /* SwitchKeyword */: + case 97 /* SwitchKeyword */: return parseSwitchStatement(); - case 98 /* ThrowKeyword */: + case 99 /* ThrowKeyword */: return parseThrowStatement(); - case 100 /* TryKeyword */: + case 101 /* TryKeyword */: // Include 'catch' and 'finally' for error recovery. - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return parseTryStatement(); - case 76 /* DebuggerKeyword */: + case 77 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 55 /* AtToken */: + case 56 /* AtToken */: return parseDeclaration(); - case 118 /* AsyncKeyword */: - case 107 /* InterfaceKeyword */: - case 134 /* TypeKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: - case 122 /* DeclareKeyword */: - case 74 /* ConstKeyword */: - case 81 /* EnumKeyword */: - case 82 /* ExportKeyword */: - case 89 /* ImportKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 115 /* AbstractKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: - case 137 /* GlobalKeyword */: + case 119 /* AsyncKeyword */: + case 108 /* InterfaceKeyword */: + case 136 /* TypeKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 123 /* DeclareKeyword */: + case 75 /* ConstKeyword */: + case 82 /* EnumKeyword */: + case 83 /* ExportKeyword */: + case 90 /* ImportKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 116 /* AbstractKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: + case 139 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -16630,33 +18140,33 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token()) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: return parseVariableStatement(fullStart, decorators, modifiers); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 73 /* ClassKeyword */: + case 74 /* ClassKeyword */: return parseClassDeclaration(fullStart, decorators, modifiers); - case 107 /* InterfaceKeyword */: + case 108 /* InterfaceKeyword */: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 134 /* TypeKeyword */: + case 136 /* TypeKeyword */: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 81 /* EnumKeyword */: + case 82 /* EnumKeyword */: return parseEnumDeclaration(fullStart, decorators, modifiers); - case 137 /* GlobalKeyword */: - case 125 /* ModuleKeyword */: - case 126 /* NamespaceKeyword */: + case 139 /* GlobalKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: return parseModuleDeclaration(fullStart, decorators, modifiers); - case 89 /* ImportKeyword */: + case 90 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 82 /* ExportKeyword */: + case 83 /* ExportKeyword */: nextToken(); switch (token()) { - case 77 /* DefaultKeyword */: - case 56 /* EqualsToken */: + case 78 /* DefaultKeyword */: + case 57 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); - case 116 /* AsKeyword */: + case 117 /* AsKeyword */: return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); @@ -16665,7 +18175,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(239 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(244 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; node.modifiers = modifiers; @@ -16678,7 +18188,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token() !== 16 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -16686,24 +18196,25 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 24 /* CommaToken */) { - return createNode(193 /* OmittedExpression */); + if (token() === 25 /* CommaToken */) { + return createNode(198 /* OmittedExpression */); } - var node = createNode(169 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + var node = createNode(174 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(169 /* BindingElement */); + var node = createNode(174 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token() !== 55 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } @@ -16711,33 +18222,33 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(167 /* ObjectBindingPattern */); - parseExpected(15 /* OpenBraceToken */); + var node = createNode(172 /* ObjectBindingPattern */); + parseExpected(16 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(168 /* ArrayBindingPattern */); - parseExpected(19 /* OpenBracketToken */); + var node = createNode(173 /* ArrayBindingPattern */); + parseExpected(20 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); + return token() === 16 /* OpenBraceToken */ || token() === 20 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(218 /* VariableDeclaration */); + var node = createNode(223 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { @@ -16746,14 +18257,14 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(219 /* VariableDeclarationList */); + var node = createNode(224 /* VariableDeclarationList */); switch (token()) { - case 102 /* VarKeyword */: + case 103 /* VarKeyword */: break; - case 108 /* LetKeyword */: + case 109 /* LetKeyword */: node.flags |= 1 /* Let */; break; - case 74 /* ConstKeyword */: + case 75 /* ConstKeyword */: node.flags |= 2 /* Const */; break; default: @@ -16769,7 +18280,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 140 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -16781,10 +18292,10 @@ var ts; return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; + return nextTokenIsIdentifier() && nextToken() === 19 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(200 /* VariableStatement */, fullStart); + var node = createNode(205 /* VariableStatement */, fullStart); node.decorators = decorators; node.modifiers = modifiers; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -16792,29 +18303,29 @@ var ts; return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(220 /* FunctionDeclaration */, fullStart); + var node = createNode(225 /* FunctionDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(87 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + parseExpected(88 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; var isAsync = ts.hasModifier(node, 256 /* Async */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(148 /* Constructor */, pos); + var node = createNode(150 /* Constructor */, pos); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(121 /* ConstructorKeyword */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + parseExpected(122 /* ConstructorKeyword */); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(147 /* MethodDeclaration */, fullStart); + var method = createNode(149 /* MethodDeclaration */, fullStart); method.decorators = decorators; method.modifiers = modifiers; method.asteriskToken = asteriskToken; @@ -16822,12 +18333,12 @@ var ts; method.questionToken = questionToken; var isGenerator = !!asteriskToken; var isAsync = ts.hasModifier(method, 256 /* Async */); - fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); + fillSignature(55 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(145 /* PropertyDeclaration */, fullStart); + var property = createNode(147 /* PropertyDeclaration */, fullStart); property.decorators = decorators; property.modifiers = modifiers; property.name = name; @@ -16844,17 +18355,17 @@ var ts; // The checker may still error in the static case to explicitly disallow the yield expression. property.initializer = ts.hasModifier(property, 32 /* Static */) ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(65536 /* YieldContext */ | 32768 /* DisallowInContext */, parseNonParameterInitializer); + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); return addJSDocComment(finishNode(property)); } function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var asteriskToken = parseOptionalToken(38 /* AsteriskToken */); var name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + var questionToken = parseOptionalToken(54 /* QuestionToken */); + if (asteriskToken || token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -16869,17 +18380,17 @@ var ts; node.decorators = decorators; node.modifiers = modifiers; node.name = parsePropertyName(); - fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); return addJSDocComment(finishNode(node)); } function isClassMemberModifier(idToken) { switch (idToken) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 113 /* StaticKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 114 /* StaticKeyword */: + case 130 /* ReadonlyKeyword */: return true; default: return false; @@ -16887,7 +18398,7 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55 /* AtToken */) { + if (token() === 56 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. @@ -16904,7 +18415,7 @@ var ts; } nextToken(); } - if (token() === 37 /* AsteriskToken */) { + if (token() === 38 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. @@ -16914,23 +18425,23 @@ var ts; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 19 /* OpenBracketToken */) { + if (token() === 20 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 131 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 133 /* SetKeyword */ || idToken === 124 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case 17 /* OpenParenToken */: // Method declaration - case 25 /* LessThanToken */: // Generic Method declaration - case 54 /* ColonToken */: // Type Annotation for declaration - case 56 /* EqualsToken */: // Initializer for declaration - case 53 /* QuestionToken */: + case 18 /* OpenParenToken */: // Method declaration + case 26 /* LessThanToken */: // Generic Method declaration + case 55 /* ColonToken */: // Type Annotation for declaration + case 57 /* EqualsToken */: // Initializer for declaration + case 54 /* QuestionToken */: return true; default: // Covers @@ -16947,10 +18458,10 @@ var ts; var decorators; while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(55 /* AtToken */)) { + if (!parseOptional(56 /* AtToken */)) { break; } - var decorator = createNode(143 /* Decorator */, decoratorStart); + var decorator = createNode(145 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); if (!decorators) { @@ -16977,7 +18488,7 @@ var ts; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + if (token() === 75 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -17004,7 +18515,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 118 /* AsyncKeyword */) { + if (token() === 119 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -17015,8 +18526,8 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23 /* SemicolonToken */) { - var result = createNode(198 /* SemicolonClassElement */); + if (token() === 24 /* SemicolonToken */) { + var result = createNode(203 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -17027,7 +18538,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121 /* ConstructorKeyword */) { + if (token() === 122 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -17038,14 +18549,14 @@ var ts; if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || - token() === 37 /* AsteriskToken */ || - token() === 19 /* OpenBracketToken */) { + token() === 38 /* AsteriskToken */ || + token() === 20 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_10 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, /*questionToken*/ undefined); + var name_13 = createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, /*questionToken*/ undefined); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); @@ -17054,24 +18565,24 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 192 /* ClassExpression */); + /*modifiers*/ undefined, 197 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 221 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(73 /* ClassKeyword */); + parseExpected(74 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ true); - if (parseExpected(15 /* OpenBraceToken */)) { + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(16 /* OpenBraceToken */)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -17089,19 +18600,19 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 107 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause) { + function parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(20 /* HeritageClauses */, parseHeritageClause); + return parseList(21 /* HeritageClauses */, parseHeritageClause); } return undefined; } function parseHeritageClause() { - if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { - var node = createNode(251 /* HeritageClause */); + if (token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */) { + var node = createNode(255 /* HeritageClause */); node.token = token(); nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -17110,61 +18621,61 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(194 /* ExpressionWithTypeArguments */); + var node = createNode(199 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25 /* LessThanToken */) { - node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + if (token() === 26 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(222 /* InterfaceDeclaration */, fullStart); + var node = createNode(227 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(107 /* InterfaceKeyword */); + parseExpected(108 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(223 /* TypeAliasDeclaration */, fullStart); + var node = createNode(228 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(134 /* TypeKeyword */); + parseExpected(136 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(255 /* EnumMember */, scanner.getStartPos()); + var node = createNode(260 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return addJSDocComment(finishNode(node)); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(224 /* EnumDeclaration */, fullStart); + var node = createNode(229 /* EnumDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - parseExpected(81 /* EnumKeyword */); + parseExpected(82 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(15 /* OpenBraceToken */)) { + if (parseExpected(16 /* OpenBraceToken */)) { node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.members = createMissingList(); @@ -17172,10 +18683,10 @@ var ts; return addJSDocComment(finishNode(node)); } function parseModuleBlock() { - var node = createNode(226 /* ModuleBlock */, scanner.getStartPos()); - if (parseExpected(15 /* OpenBraceToken */)) { + var node = createNode(231 /* ModuleBlock */, scanner.getStartPos()); + if (parseExpected(16 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -17183,7 +18694,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(225 /* ModuleDeclaration */, fullStart); + var node = createNode(230 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; @@ -17191,16 +18702,16 @@ var ts; node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(21 /* DotToken */) + node.body = parseOptional(22 /* DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); return addJSDocComment(finishNode(node)); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(225 /* ModuleDeclaration */, fullStart); + var node = createNode(230 /* ModuleDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (token() === 137 /* GlobalKeyword */) { + if (token() === 139 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -17208,7 +18719,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token() === 15 /* OpenBraceToken */) { + if (token() === 16 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -17218,15 +18729,15 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = 0; - if (token() === 137 /* GlobalKeyword */) { + if (token() === 139 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } - else if (parseOptional(126 /* NamespaceKeyword */)) { + else if (parseOptional(128 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; } else { - parseExpected(125 /* ModuleKeyword */); + parseExpected(127 /* ModuleKeyword */); if (token() === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -17234,57 +18745,57 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 /* RequireKeyword */ && + return token() === 131 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 17 /* OpenParenToken */; + return nextToken() === 18 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 39 /* SlashToken */; + return nextToken() === 40 /* SlashToken */; } function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228 /* NamespaceExportDeclaration */, fullStart); + var exportDeclaration = createNode(233 /* NamespaceExportDeclaration */, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; - parseExpected(116 /* AsKeyword */); - parseExpected(126 /* NamespaceKeyword */); + parseExpected(117 /* AsKeyword */); + parseExpected(128 /* NamespaceKeyword */); exportDeclaration.name = parseIdentifier(); - parseExpected(23 /* SemicolonToken */); + parseSemicolon(); return finishNode(exportDeclaration); } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(89 /* ImportKeyword */); + parseExpected(90 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { + if (token() !== 25 /* CommaToken */ && token() !== 138 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(229 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(234 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; importEqualsDeclaration.modifiers = modifiers; importEqualsDeclaration.name = identifier; - parseExpected(56 /* EqualsToken */); + parseExpected(57 /* EqualsToken */); importEqualsDeclaration.moduleReference = parseModuleReference(); parseSemicolon(); return addJSDocComment(finishNode(importEqualsDeclaration)); } } // Import statement - var importDeclaration = createNode(230 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(235 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; importDeclaration.modifiers = modifiers; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */) { + token() === 38 /* AsteriskToken */ || + token() === 16 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(136 /* FromKeyword */); + parseExpected(138 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -17297,7 +18808,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(231 /* ImportClause */, fullStart); + var importClause = createNode(236 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -17306,8 +18817,8 @@ var ts; // If there was no default import or if there is comma token after default import // parse namespace or named imports if (!importClause.name || - parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + parseOptional(25 /* CommaToken */)) { + importClause.namedBindings = token() === 38 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(238 /* NamedImports */); } return finishNode(importClause); } @@ -17317,11 +18828,11 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(240 /* ExternalModuleReference */); - parseExpected(129 /* RequireKeyword */); - parseExpected(17 /* OpenParenToken */); + var node = createNode(245 /* ExternalModuleReference */); + parseExpected(131 /* RequireKeyword */); + parseExpected(18 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { @@ -17340,9 +18851,9 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(232 /* NamespaceImport */); - parseExpected(37 /* AsteriskToken */); - parseExpected(116 /* AsKeyword */); + var namespaceImport = createNode(237 /* NamespaceImport */); + parseExpected(38 /* AsteriskToken */); + parseExpected(117 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } @@ -17355,14 +18866,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 233 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 238 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 16 /* OpenBraceToken */, 17 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(238 /* ExportSpecifier */); + return parseImportOrExportSpecifier(243 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(234 /* ImportSpecifier */); + return parseImportOrExportSpecifier(239 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -17376,9 +18887,9 @@ var ts; var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116 /* AsKeyword */) { + if (token() === 117 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(116 /* AsKeyword */); + parseExpected(117 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -17387,27 +18898,27 @@ var ts; else { node.name = identifierName; } - if (kind === 234 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 239 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(236 /* ExportDeclaration */, fullStart); + var node = createNode(241 /* ExportDeclaration */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(37 /* AsteriskToken */)) { - parseExpected(136 /* FromKeyword */); + if (parseOptional(38 /* AsteriskToken */)) { + parseExpected(138 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(237 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(242 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(136 /* FromKeyword */); + if (token() === 138 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(138 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -17415,14 +18926,14 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(235 /* ExportAssignment */, fullStart); + var node = createNode(240 /* ExportAssignment */, fullStart); node.decorators = decorators; node.modifiers = modifiers; - if (parseOptional(56 /* EqualsToken */)) { + if (parseOptional(57 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(77 /* DefaultKeyword */); + parseExpected(78 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); @@ -17497,10 +19008,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 229 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 240 /* ExternalModuleReference */ - || node.kind === 230 /* ImportDeclaration */ - || node.kind === 235 /* ExportAssignment */ - || node.kind === 236 /* ExportDeclaration */ + || node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */ + || node.kind === 235 /* ImportDeclaration */ + || node.kind === 240 /* ExportAssignment */ + || node.kind === 241 /* ExportDeclaration */ ? node : undefined; }); @@ -17524,16 +19035,17 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["TypeParameters"] = 17] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 18] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 19] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 20] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 21] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["JSDocFunctionParameters"] = 22] = "JSDocFunctionParameters"; - ParsingContext[ParsingContext["JSDocTypeArguments"] = 23] = "JSDocTypeArguments"; - ParsingContext[ParsingContext["JSDocRecordMembers"] = 24] = "JSDocRecordMembers"; - ParsingContext[ParsingContext["JSDocTupleTypes"] = 25] = "JSDocTupleTypes"; - ParsingContext[ParsingContext["Count"] = 26] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 23] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 24] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 25] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 26] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 27] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -17545,24 +19057,24 @@ var ts; (function (JSDocParser) { function isJSDocType() { switch (token()) { - case 37 /* AsteriskToken */: - case 53 /* QuestionToken */: - case 17 /* OpenParenToken */: - case 19 /* OpenBracketToken */: - case 49 /* ExclamationToken */: - case 15 /* OpenBraceToken */: - case 87 /* FunctionKeyword */: - case 22 /* DotDotDotToken */: - case 92 /* NewKeyword */: - case 97 /* ThisKeyword */: + case 38 /* AsteriskToken */: + case 54 /* QuestionToken */: + case 18 /* OpenParenToken */: + case 20 /* OpenBracketToken */: + case 50 /* ExclamationToken */: + case 16 /* OpenBraceToken */: + case 88 /* FunctionKeyword */: + case 23 /* DotDotDotToken */: + case 93 /* NewKeyword */: + case 98 /* ThisKeyword */: return true; } return ts.tokenIsIdentifierOrKeyword(token()); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = createSourceFile("file.js", 2 /* Latest */, 1 /* JS */); + initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 5 /* Latest */, 1 /* JS */); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -17574,23 +19086,23 @@ var ts; // Parses out a JSDoc type expression. /* @internal */ function parseJSDocTypeExpression() { - var result = createNode(257 /* JSDocTypeExpression */, scanner.getTokenPos()); - parseExpected(15 /* OpenBraceToken */); + var result = createNode(262 /* JSDocTypeExpression */, scanner.getTokenPos()); + parseExpected(16 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); - parseExpected(16 /* CloseBraceToken */); + parseExpected(17 /* CloseBraceToken */); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47 /* BarToken */) { - var unionType = createNode(261 /* JSDocUnionType */, type.pos); + if (token() === 48 /* BarToken */) { + var unionType = createNode(266 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56 /* EqualsToken */) { - var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); + if (token() === 57 /* EqualsToken */) { + var optionalType = createNode(273 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -17600,21 +19112,21 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19 /* OpenBracketToken */) { - var arrayType = createNode(260 /* JSDocArrayType */, type.pos); + if (token() === 20 /* OpenBracketToken */) { + var arrayType = createNode(265 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token() === 53 /* QuestionToken */) { - var nullableType = createNode(263 /* JSDocNullableType */, type.pos); + else if (token() === 54 /* QuestionToken */) { + var nullableType = createNode(268 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49 /* ExclamationToken */) { - var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); + else if (token() === 50 /* ExclamationToken */) { + var nonNullableType = createNode(269 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -17627,94 +19139,95 @@ var ts; } function parseBasicTypeExpression() { switch (token()) { - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: return parseJSDocAllType(); - case 53 /* QuestionToken */: + case 54 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return parseJSDocUnionType(); - case 19 /* OpenBracketToken */: + case 20 /* OpenBracketToken */: return parseJSDocTupleType(); - case 49 /* ExclamationToken */: + case 50 /* ExclamationToken */: return parseJSDocNonNullableType(); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return parseJSDocRecordType(); - case 87 /* FunctionKeyword */: + case 88 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 22 /* DotDotDotToken */: + case 23 /* DotDotDotToken */: return parseJSDocVariadicType(); - case 92 /* NewKeyword */: + case 93 /* NewKeyword */: return parseJSDocConstructorType(); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: return parseJSDocThisType(); - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 94 /* NullKeyword */: + case 137 /* UndefinedKeyword */: + case 129 /* NeverKeyword */: return parseTokenNode(); case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(272 /* JSDocThisType */); + var result = createNode(277 /* JSDocThisType */); nextToken(); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(271 /* JSDocConstructorType */); + var result = createNode(276 /* JSDocConstructorType */); nextToken(); - parseExpected(54 /* ColonToken */); + parseExpected(55 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(270 /* JSDocVariadicType */); + var result = createNode(275 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(269 /* JSDocFunctionType */); + var result = createNode(274 /* JSDocFunctionType */); nextToken(); - parseExpected(17 /* OpenParenToken */); - result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); + parseExpected(18 /* OpenParenToken */); + result.parameters = parseDelimitedList(23 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); - parseExpected(18 /* CloseParenToken */); - if (token() === 54 /* ColonToken */) { + parseExpected(19 /* CloseParenToken */); + if (token() === 55 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(142 /* Parameter */); + var parameter = createNode(144 /* Parameter */); parameter.type = parseJSDocType(); - if (parseOptional(56 /* EqualsToken */)) { - parameter.questionToken = createNode(56 /* EqualsToken */); + if (parseOptional(57 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? + parameter.questionToken = createNode(57 /* EqualsToken */); } return finishNode(parameter); } function parseJSDocTypeReference() { - var result = createNode(267 /* JSDocTypeReference */); + var result = createNode(272 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token() === 25 /* LessThanToken */) { + if (token() === 26 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { - while (parseOptional(21 /* DotToken */)) { - if (token() === 25 /* LessThanToken */) { + while (parseOptional(22 /* DotToken */)) { + if (token() === 26 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -17728,10 +19241,10 @@ var ts; function parseTypeArguments() { // Move past the < nextToken(); - var typeArguments = parseDelimitedList(23 /* JSDocTypeArguments */, parseJSDocType); + var typeArguments = parseDelimitedList(24 /* JSDocTypeArguments */, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); - parseExpected(27 /* GreaterThanToken */); + parseExpected(28 /* GreaterThanToken */); return typeArguments; } function checkForEmptyTypeArgumentList(typeArguments) { @@ -17742,28 +19255,28 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(139 /* QualifiedName */, left.pos); + var result = createNode(141 /* QualifiedName */, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(265 /* JSDocRecordType */); + var result = createNode(270 /* JSDocRecordType */); result.literal = parseTypeLiteral(); return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(264 /* JSDocNonNullableType */); + var result = createNode(269 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(262 /* JSDocTupleType */); + var result = createNode(267 /* JSDocTupleType */); nextToken(); - result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); + result.types = parseDelimitedList(26 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); return finishNode(result); } function checkForTrailingComma(list) { @@ -17773,28 +19286,28 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(261 /* JSDocUnionType */); + var result = createNode(266 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18 /* CloseParenToken */); + parseExpected(19 /* CloseParenToken */); return finishNode(result); } function parseJSDocTypeList(firstType) { ts.Debug.assert(!!firstType); var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(47 /* BarToken */)) { + while (parseOptional(48 /* BarToken */)) { types.push(parseJSDocType()); } types.end = scanner.getStartPos(); return types; } function parseJSDocAllType() { - var result = createNode(258 /* JSDocAllType */); + var result = createNode(263 /* JSDocAllType */); nextToken(); return finishNode(result); } function parseJSDocLiteralType() { - var result = createNode(282 /* JSDocLiteralType */); + var result = createNode(288 /* JSDocLiteralType */); result.literal = parseLiteralTypeNode(); return finishNode(result); } @@ -17811,23 +19324,23 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 24 /* CommaToken */ || - token() === 16 /* CloseBraceToken */ || - token() === 18 /* CloseParenToken */ || - token() === 27 /* GreaterThanToken */ || - token() === 56 /* EqualsToken */ || - token() === 47 /* BarToken */) { - var result = createNode(259 /* JSDocUnknownType */, pos); + if (token() === 25 /* CommaToken */ || + token() === 17 /* CloseBraceToken */ || + token() === 19 /* CloseParenToken */ || + token() === 28 /* GreaterThanToken */ || + token() === 57 /* EqualsToken */ || + token() === 48 /* BarToken */) { + var result = createNode(264 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(263 /* JSDocNullableType */, pos); + var result = createNode(268 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -17892,11 +19405,12 @@ var ts; } if (token() === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; + indent = 0; nextJSDocToken(); } while (token() !== 1 /* EndOfFileToken */) { switch (token()) { - case 55 /* AtToken */: + case 56 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); parseTag(indent); @@ -17917,9 +19431,9 @@ var ts; state = 0 /* BeginningOfLine */; indent = 0; break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */) { + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line state = 2 /* SavingComments */; pushComment(asterisk); @@ -17930,7 +19444,7 @@ var ts; indent += asterisk.length; } break; - case 69 /* Identifier */: + case 70 /* Identifier */: // Anything else is doc comment text. We just save it. Because it // wasn't a tag, we can no longer parse a tag on this line until we hit the next // line break. @@ -17940,7 +19454,10 @@ var ts; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -17948,6 +19465,8 @@ var ts; case 1 /* EndOfFileToken */: break; default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } @@ -17980,7 +19499,7 @@ var ts; content.charCodeAt(start + 3) !== 42 /* asterisk */; } function createJSDocComment() { - var result = createNode(273 /* JSDocComment */, start); + var result = createNode(278 /* JSDocComment */, start); result.tags = tags; result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -17991,8 +19510,8 @@ var ts; } } function parseTag(indent) { - ts.Debug.assert(token() === 55 /* AtToken */); - var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); + ts.Debug.assert(token() === 56 /* AtToken */); + var atToken = createNode(56 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18003,6 +19522,9 @@ var ts; var tag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -18044,7 +19566,7 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 55 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + while (token() !== 56 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { switch (token()) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { @@ -18053,7 +19575,7 @@ var ts; } indent = 0; break; - case 55 /* AtToken */: + case 56 /* AtToken */: // Done break; case 5 /* WhitespaceTrivia */: @@ -18069,7 +19591,7 @@ var ts; indent += whitespace.length; } break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; @@ -18082,7 +19604,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 55 /* AtToken */) { + if (token() === 56 /* AtToken */) { // Done break; } @@ -18093,7 +19615,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(274 /* JSDocTag */, atToken.pos); + var result = createNode(279 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -18111,7 +19633,7 @@ var ts; function tryParseTypeExpression() { return tryParse(function () { skipWhitespace(); - if (token() !== 15 /* OpenBraceToken */) { + if (token() !== 16 /* OpenBraceToken */) { return undefined; } return parseJSDocTypeExpression(); @@ -18123,15 +19645,15 @@ var ts; var name; var isBracketed; // Looking for something like '[foo]' or 'foo' - if (parseOptionalToken(19 /* OpenBracketToken */)) { + if (parseOptionalToken(20 /* OpenBracketToken */)) { name = parseJSDocIdentifierName(); skipWhitespace(); isBracketed = true; // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(56 /* EqualsToken */)) { + if (parseOptionalToken(57 /* EqualsToken */)) { parseExpression(); } - parseExpected(20 /* CloseBracketToken */); + parseExpected(21 /* CloseBracketToken */); } else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); @@ -18150,7 +19672,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(275 /* JSDocParameterTag */, atToken.pos); + var result = createNode(281 /* JSDocParameterTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -18161,20 +19683,20 @@ var ts; return finishNode(result); } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 276 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(276 /* JSDocReturnTag */, atToken.pos); + var result = createNode(282 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 277 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 283 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(277 /* JSDocTypeTag */, atToken.pos); + var result = createNode(283 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -18189,28 +19711,43 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(280 /* JSDocPropertyTag */, atToken.pos); + var result = createNode(286 /* JSDocPropertyTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.name = name; result.typeExpression = typeExpression; return finishNode(result); } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(280 /* JSDocAugmentsTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(279 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(285 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (rightNode.kind !== 70 /* Identifier */) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); if (typeExpression) { - if (typeExpression.type.kind === 267 /* JSDocTypeReference */) { + if (typeExpression.type.kind === 272 /* JSDocTypeReference */) { var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 69 /* Identifier */) { - var name_11 = jsDocTypeReference.name; - if (name_11.text === "Object") { + if (jsDocTypeReference.name.kind === 70 /* Identifier */) { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -18224,7 +19761,7 @@ var ts; } return finishNode(typedefTag); function scanChildTags() { - var jsDocTypeLiteral = createNode(281 /* JSDocTypeLiteral */, scanner.getStartPos()); + var jsDocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, scanner.getStartPos()); var resumePos = scanner.getStartPos(); var canParseTag = true; var seenAsterisk = false; @@ -18232,7 +19769,7 @@ var ts; while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); switch (token()) { - case 55 /* AtToken */: + case 56 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); if (!parentTagTerminated) { @@ -18246,13 +19783,13 @@ var ts; canParseTag = true; seenAsterisk = false; break; - case 37 /* AsteriskToken */: + case 38 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 69 /* Identifier */: + case 70 /* Identifier */: canParseTag = false; case 1 /* EndOfFileToken */: break; @@ -18261,10 +19798,25 @@ var ts; scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(22 /* DotToken */)) { + var jsDocNamespaceNode = createNode(230 /* ModuleDeclaration */, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); + return jsDocNamespaceNode; + } + if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55 /* AtToken */); - var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); + ts.Debug.assert(token() === 56 /* AtToken */); + var atToken = createNode(56 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18282,33 +19834,37 @@ var ts; return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } var propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = []; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + // Error parsing property tag + return false; } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 278 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 284 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } // Type parameter list looks like '@template T,U,V' var typeParameters = createNodeArray(); while (true) { - var name_12 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_12) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141 /* TypeParameter */, name_12.pos); - typeParameter.name = name_12; + var typeParameter = createNode(143 /* TypeParameter */, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24 /* CommaToken */) { + if (token() === 25 /* CommaToken */) { nextJSDocToken(); skipWhitespace(); } @@ -18316,7 +19872,7 @@ var ts; break; } } - var result = createNode(278 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(284 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -18337,7 +19893,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(69 /* Identifier */, pos); + var result = createNode(70 /* Identifier */, pos); result.text = content.substring(pos, end); finishNode(result, end); nextJSDocToken(); @@ -18443,8 +19999,8 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); } @@ -18455,8 +20011,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += 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); } } @@ -18465,7 +20021,7 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 69 /* Identifier */: + case 70 /* Identifier */: return true; } return false; @@ -18593,8 +20149,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_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -18827,25 +20383,25 @@ var ts; /* @internal */ var ts; (function (ts) { + var ModuleInstanceState; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); - var ModuleInstanceState = ts.ModuleInstanceState; + })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 222 /* InterfaceDeclaration */ || node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 228 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { + else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } - else if (node.kind === 226 /* ModuleBlock */) { + else if (node.kind === 231 /* ModuleBlock */) { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -18864,10 +20420,13 @@ var ts; }); return state_1; } - else if (node.kind === 225 /* ModuleDeclaration */) { + else if (node.kind === 230 /* ModuleDeclaration */) { var body = node.body; return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } + else if (node.kind === 70 /* Identifier */ && node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } else { return 1 /* Instantiated */; } @@ -18895,6 +20454,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +20487,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +20502,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +20532,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -18991,7 +20561,7 @@ var ts; if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 225 /* ModuleDeclaration */)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230 /* ModuleDeclaration */)) { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } @@ -19004,10 +20574,10 @@ var ts; if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -19016,21 +20586,21 @@ var ts; return node.name.text; } switch (node.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: return "__constructor"; - case 156 /* FunctionType */: - case 151 /* CallSignature */: + case 158 /* FunctionType */: + case 153 /* CallSignature */: return "__call"; - case 157 /* ConstructorType */: - case 152 /* ConstructSignature */: + case 159 /* ConstructorType */: + case 154 /* ConstructSignature */: return "__new"; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return "__index"; - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return "__export"; - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (ts.getSpecialPropertyAssignmentKind(node)) { case 2 /* ModuleExports */: // module.exports = ... @@ -19045,25 +20615,25 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + case 226 /* ClassDeclaration */: return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; - case 269 /* JSDocFunctionType */: + case 274 /* JSDocFunctionType */: return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 142 /* Parameter */: + case 144 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 269 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 274 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: var parentNode = node.parent && node.parent.parent; var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode && parentNode.kind === 205 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { + if (nameIdentifier.kind === 70 /* Identifier */) { nameFromParentNode = nameIdentifier.text; } } @@ -19134,11 +20704,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 240 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19154,7 +20737,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 238 /* ExportSpecifier */ || (node.kind === 229 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 243 /* ExportSpecifier */ || (node.kind === 234 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -19177,7 +20760,11 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) { + var isJSDocTypedefInJSDocNamespace = node.kind === 285 /* JSDocTypedefTag */ && + node.name && + node.name.kind === 70 /* Identifier */ && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); @@ -19235,15 +20822,15 @@ var ts; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !!ts.getImmediatelyInvokedFunctionExpression(node); - // An IIFE is considered part of the containing control flow. Return statements behave + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19254,14 +20841,13 @@ var ts; hasExplicitReturn = false; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) - // Reset all emit helper flags on node (for incremental scenarios) - node.flags &= ~32128 /* ReachabilityAndEmitFlags */; + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { node.flags |= 128 /* HasImplicitReturn */; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 256 /* SourceFile */) { + if (node.kind === 261 /* SourceFile */) { node.flags |= emitFlags; } if (isIIFE) { @@ -19296,6 +20882,7 @@ var ts; skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { var savedSubtreeTransformFlags = subtreeTransformFlags; @@ -19304,104 +20891,127 @@ var ts; subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); } } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } function bindChildrenWorker(node) { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (ts.isInJavaScriptFile(node) && node.jsDocComments) { - ts.forEach(node.jsDocComments, bind); + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + ts.forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - ts.forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: bindWhileStatement(node); break; - case 204 /* DoStatement */: + case 209 /* DoStatement */: bindDoStatement(node); break; - case 206 /* ForStatement */: + case 211 /* ForStatement */: bindForStatement(node); break; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 203 /* IfStatement */: + case 208 /* IfStatement */: bindIfStatement(node); break; - case 211 /* ReturnStatement */: - case 215 /* ThrowStatement */: + case 216 /* ReturnStatement */: + case 220 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 216 /* TryStatement */: + case 221 /* TryStatement */: bindTryStatement(node); break; - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: bindSwitchStatement(node); break; - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: bindCaseBlock(node); break; - case 249 /* CaseClause */: + case 253 /* CaseClause */: bindCaseClause(node); break; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: bindLabeledStatement(node); break; - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 174 /* CallExpression */: + case 179 /* CallExpression */: bindCallExpressionFlow(node); break; default: - ts.forEachChild(node, bind); + bindEachChild(node); break; } } function isNarrowingExpression(expr) { switch (expr.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: + case 177 /* PropertyAccessExpression */: return isNarrowableReference(expr); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return hasNarrowableArgument(expr); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 185 /* PrefixUnaryExpression */: - return expr.operator === 49 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 190 /* PrefixUnaryExpression */: + return expr.operator === 50 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 70 /* Identifier */ || + expr.kind === 98 /* ThisKeyword */ || + expr.kind === 177 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -19412,41 +21022,41 @@ var ts; } } } - if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + if (expr.expression.kind === 177 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 187 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return isNarrowableReference(expr.left); - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -19466,7 +21076,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -19481,8 +21091,8 @@ var ts; if (!expression) { return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 99 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 84 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + if (expression.kind === 100 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 85 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -19516,6 +21126,14 @@ var ts; node: node }; } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256 /* ArrayMutation */, + antecedent: antecedent, + node: node + }; + } function finishFlowLabel(flow) { var antecedents = flow.antecedents; if (!antecedents) { @@ -19529,34 +21147,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 203 /* IfStatement */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: + case 208 /* IfStatement */: + case 210 /* WhileStatement */: + case 209 /* DoStatement */: return parent.expression === node; - case 206 /* ForStatement */: - case 188 /* ConditionalExpression */: + case 211 /* ForStatement */: + case 193 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 178 /* ParenthesizedExpression */) { + if (node.kind === 183 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 185 /* PrefixUnaryExpression */ && node.operator === 49 /* ExclamationToken */) { + else if (node.kind === 190 /* PrefixUnaryExpression */ && node.operator === 50 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 187 /* BinaryExpression */ && (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 52 /* BarBarToken */); + return node.kind === 192 /* BinaryExpression */ && (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 53 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 178 /* ParenthesizedExpression */ || - node.parent.kind === 185 /* PrefixUnaryExpression */ && - node.parent.operator === 49 /* ExclamationToken */) { + while (node.parent.kind === 183 /* ParenthesizedExpression */ || + node.parent.kind === 190 /* PrefixUnaryExpression */ && + node.parent.operator === 50 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -19597,8 +21215,13 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var preConditionLabel = createBranchLabel(); - var postDoLabel = createBranchLabel(); + var enclosingLabeledStatement = node.parent.kind === 219 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -19629,7 +21252,7 @@ var ts; bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 219 /* VariableDeclarationList */) { + if (node.initializer.kind !== 224 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -19651,7 +21274,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 211 /* ReturnStatement */) { + if (node.kind === 216 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -19670,8 +21293,8 @@ var ts; } return undefined; } - function bindbreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 210 /* BreakStatement */ ? breakTarget : continueTarget; + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 215 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -19683,29 +21306,50 @@ var ts; var activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node) { - var postFinallyLabel = createBranchLabel(); + var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; // TODO: Every statement in try block is potentially an exit point! bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); } - currentFlow = finishFlowLabel(postFinallyLabel); } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19716,7 +21360,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254 /* 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; @@ -19728,6 +21372,8 @@ var ts; currentFlow = finishFlowLabel(postSwitchLabel); } function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; var clauses = node.clauses; var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { @@ -19747,13 +21393,15 @@ var ts; errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { var saveCurrentFlow = currentFlow; currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - ts.forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name, breakTarget, continueTarget) { var activeLabel = { @@ -19779,11 +21427,14 @@ var ts; if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== 209 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node) { - if (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */) { + if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -19794,10 +21445,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 170 /* ArrayLiteralExpression */) { + else if (node.kind === 175 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 191 /* SpreadElementExpression */) { + if (e.kind === 196 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -19805,21 +21456,24 @@ var ts; } } } - else if (node.kind === 171 /* ObjectLiteralExpression */) { + else if (node.kind === 176 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 253 /* PropertyAssignment */) { + if (p.kind === 257 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 254 /* ShorthandPropertyAssignment */) { + else if (p.kind === 258 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } + else if (p.kind === 259 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } } } } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -19830,30 +21484,30 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 49 /* ExclamationToken */) { + if (node.operator === 50 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - ts.forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + bindEachChild(node); + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + bindEachChild(node); + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 51 /* AmpersandAmpersandToken */ || operator === 52 /* BarBarToken */) { + if (operator === 52 /* AmpersandAmpersandToken */ || operator === 53 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -19864,15 +21518,21 @@ var ts; } } else { - ts.forEachChild(node, bind); - if (operator === 56 /* EqualsToken */ && !ts.isAssignmentTarget(node)) { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === 57 /* EqualsToken */ && node.left.kind === 178 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node) { - ts.forEachChild(node, bind); - if (node.expression.kind === 172 /* PropertyAccessExpression */) { + bindEachChild(node); + if (node.expression.kind === 177 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -19882,9 +21542,11 @@ var ts; var postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -19902,8 +21564,8 @@ var ts; } } function bindVariableDeclarationFlow(node) { - ts.forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === 207 /* ForInStatement */ || node.parent.parent.kind === 208 /* ForOfStatement */) { + bindEachChild(node); + if (node.initializer || node.parent.parent.kind === 212 /* ForInStatement */ || node.parent.parent.kind === 213 /* ForOfStatement */) { bindInitializedVariableFlow(node); } } @@ -19912,62 +21574,72 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 178 /* ParenthesizedExpression */) { + while (expr.kind === 183 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 179 /* FunctionExpression */ || expr.kind === 180 /* ArrowFunction */) { - ts.forEach(node.typeArguments, bind); - ts.forEach(node.arguments, bind); + if (expr.kind === 184 /* FunctionExpression */ || expr.kind === 185 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - ts.forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === 177 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } function getContainerFlags(node) { switch (node.kind) { - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 265 /* JSDocRecordType */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 161 /* TypeLiteral */: + case 287 /* JSDocTypeLiteral */: + case 270 /* JSDocRecordType */: return 1 /* IsContainer */; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 269 /* JSDocFunctionType */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 274 /* JSDocFunctionType */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 170 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 256 /* SourceFile */: + case 261 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 148 /* Constructor */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 149 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + case 150 /* Constructor */: + case 225 /* FunctionDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 252 /* CatchClause */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 227 /* CaseBlock */: + case 256 /* CatchClause */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 232 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 199 /* Block */: + case 204 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -20004,41 +21676,42 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 159 /* TypeLiteral */: - case 171 /* ObjectLiteralExpression */: - case 222 /* InterfaceDeclaration */: - case 265 /* JSDocRecordType */: - case 281 /* JSDocTypeLiteral */: + case 161 /* TypeLiteral */: + case 176 /* ObjectLiteralExpression */: + case 227 /* InterfaceDeclaration */: + case 270 /* JSDocRecordType */: + case 287 /* JSDocTypeLiteral */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 269 /* JSDocFunctionType */: - case 223 /* TypeAliasDeclaration */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 274 /* JSDocFunctionType */: + case 228 /* TypeAliasDeclaration */: + case 170 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -20059,11 +21732,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { + var body = node.kind === 261 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 261 /* SourceFile */ || body.kind === 231 /* 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 */) { + if (stat.kind === 241 /* ExportDeclaration */ || stat.kind === 240 /* ExportAssignment */) { return true; } } @@ -20156,7 +21829,7 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.name.kind !== 69 /* Identifier */) { + if (prop.kind === 259 /* SpreadAssignment */ || prop.name.kind !== 70 /* Identifier */) { continue; } var identifier = prop.name; @@ -20168,7 +21841,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */ || prop.kind === 147 /* MethodDeclaration */ + var currentKind = prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */ || prop.kind === 149 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen[identifier.text]; @@ -20190,10 +21863,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -20214,8 +21887,8 @@ var ts; // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && + node.originalKeywordKind >= 107 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 115 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && !ts.isInAmbientContext(node)) { // Report error only if there are no parse errors in file @@ -20251,7 +21924,7 @@ var ts; } function checkStrictModeDeleteExpression(node) { // Grammar checking - if (inStrictMode && node.expression.kind === 69 /* Identifier */) { + if (inStrictMode && node.expression.kind === 70 /* Identifier */) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name var span_2 = ts.getErrorSpanForNode(file, node.expression); @@ -20259,11 +21932,11 @@ var ts; } } function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* Identifier */ && + return node.kind === 70 /* Identifier */ && (node.text === "eval" || node.text === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69 /* Identifier */) { + if (name && name.kind === 70 /* Identifier */) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message @@ -20302,10 +21975,10 @@ var ts; return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; } function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 256 /* SourceFile */ && - blockScopeContainer.kind !== 225 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 261 /* SourceFile */ && + blockScopeContainer.kind !== 230 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -20331,7 +22004,7 @@ var ts; function checkStrictModePrefixUnaryExpression(node) { // Grammar checking if (inStrictMode) { - if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } @@ -20371,7 +22044,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 138 /* LastToken */) { + if (node.kind > 140 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -20390,8 +22063,8 @@ var ts; } function updateStrictModeStatementList(statements) { if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -20412,18 +22085,29 @@ var ts; function bindWorker(node) { switch (node.kind) { /* Strict mode checks */ - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 254 /* ShorthandPropertyAssignment */)) { + case 70 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 285 /* JSDocTypedefTag */) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + break; + } + case 98 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 258 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } break; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: if (ts.isInJavaScriptFile(node)) { var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { @@ -20447,128 +22131,145 @@ var ts; } } return checkStrictModeBinaryExpression(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return checkStrictModeCatchClause(node); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return checkStrictModeWithStatement(node); - case 165 /* ThisType */: + case 167 /* ThisType */: seenThisKeyword = true; return; - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return checkTypePredicate(node); - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 142 /* Parameter */: + case 144 /* Parameter */: return bindParameter(node); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: return bindVariableDeclarationOrBindingElement(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 266 /* JSDocRecordMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 271 /* JSDocRecordMember */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 280 /* JSDocPropertyTag */: + case 286 /* JSDocPropertyTag */: return bindJSDocProperty(node); - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 247 /* JsxSpreadAttribute */: - emitFlags |= 16384 /* HasJsxSpreadAttributes */; + case 259 /* SpreadAssignment */: + case 251 /* JsxSpreadAttribute */: + var root = container; + var hasRest = false; + while (root.parent) { + if (root.kind === 176 /* ObjectLiteralExpression */ && + root.parent.kind === 192 /* BinaryExpression */ && + root.parent.operatorToken.kind === 57 /* EqualsToken */ && + root.parent.left === root) { + hasRest = true; + break; + } + root = root.parent; + } return; - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 269 /* JSDocFunctionType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 274 /* JSDocFunctionType */: return bindFunctionOrConstructorType(node); - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 265 /* JSDocRecordType */: + case 161 /* TypeLiteral */: + case 170 /* MappedType */: + case 287 /* JSDocTypeLiteral */: + case 270 /* JSDocRecordType */: return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return bindFunctionExpression(node); - case 174 /* CallExpression */: + case 179 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 279 /* JSDocTypedefTag */: - case 223 /* TypeAliasDeclaration */: + case 285 /* JSDocTypedefTag */: + if (!node.fullName || node.fullName.kind === 70 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + case 228 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Imports and exports - case 229 /* ImportEqualsDeclaration */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return bindImportClause(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return bindExportDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return bindExportAssignment(node); - case 256 /* SourceFile */: + case 261 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 199 /* Block */: + case 204 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // Fall through - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); } } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 69 /* Identifier */) { + if (parameterName && parameterName.kind === 70 /* Identifier */) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 165 /* ThisType */) { + if (parameterName && parameterName.kind === 167 /* ThisType */) { seenThisKeyword = true; } bind(type); @@ -20588,27 +22289,30 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. + var flags = node.kind === 240 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 256 /* SourceFile */) { + if (node.parent.kind !== 261 /* SourceFile */) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -20634,7 +22338,9 @@ var ts; function setCommonJsModuleIndicator(node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } function bindExportsPropertyAssignment(node) { @@ -20651,12 +22357,12 @@ var ts; function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); // Declare a 'member' if the container is an ES5 class or ES6 constructor - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { + if (container.kind === 225 /* FunctionDeclaration */ || container.kind === 184 /* FunctionExpression */) { container.symbol.members = container.symbol.members || ts.createMap(); // It's acceptable for multiple 'this' assignments of the same identifier to occur declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } - else if (container.kind === 148 /* Constructor */) { + else if (container.kind === 150 /* Constructor */) { // this.foo assignment in a JavaScript class // Bind this property to the containing class var saveContainer = container; @@ -20699,15 +22405,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { - if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= 1024 /* HasClassExtends */; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048 /* HasDecorators */; - } - } - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -20769,11 +22467,6 @@ var ts; } } function bindParameter(node) { - if (!ts.isDeclarationFile(file) && - !ts.isInAmbientContext(node) && - ts.nodeIsDecorated(node)) { - emitFlags |= (2048 /* HasDecorators */ | 4096 /* HasParamDecorators */); - } if (inStrictMode) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -20795,7 +22488,7 @@ var ts; function bindFunctionDeclaration(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } checkStrictModeFunctionName(node); @@ -20810,7 +22503,7 @@ var ts; function bindFunctionExpression(node) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } if (currentFlow) { @@ -20823,12 +22516,12 @@ var ts; function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { if (ts.isAsyncFunctionLike(node)) { - emitFlags |= 8192 /* HasAsyncFunctions */; - } - if (ts.nodeIsDecorated(node)) { - emitFlags |= 2048 /* HasDecorators */; + emitFlags |= 1024 /* HasAsyncFunctions */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20848,13 +22541,13 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 201 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 206 /* EmptyStatement */) || // report error on class declarations - node.kind === 221 /* ClassDeclaration */ || + node.kind === 226 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 225 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 230 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 224 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 229 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; // unreachable code is reported if @@ -20868,7 +22561,7 @@ var ts; // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 200 /* VariableStatement */ || + (node.kind !== 205 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -20888,52 +22581,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 225 /* ModuleDeclaration */: + case 180 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 230 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 142 /* Parameter */: + case 144 /* Parameter */: return computeParameter(node, subtreeFlags); - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 194 /* ExpressionWithTypeArguments */: + case 256 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 199 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 148 /* Constructor */: + case 150 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -20944,44 +22641,63 @@ var ts; var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */ + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537133909 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 95 /* SuperKeyword */: + case 96 /* SuperKeyword */: return true; - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 95 /* SuperKeyword */; + return expressionKind === 96 /* SuperKeyword */; } return false; } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 56 /* EqualsToken */ - && (leftKind === 171 /* ObjectLiteralExpression */ - || leftKind === 170 /* ArrayLiteralExpression */)) { - // Destructuring assignments are ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 256 /* DestructuringAssignment */; + if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 176 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 38 /* AsteriskAsteriskToken */ - || operatorTokenKind === 60 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES7 syntax. - transformFlags |= 48 /* AssertES7 */; + else if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 175 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 39 /* AsteriskAsteriskToken */ + || operatorTokenKind === 61 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20989,26 +22705,29 @@ var ts; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; - // If the parameter has a question token, then it is TypeScript syntax. - if (node.questionToken) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (modifierFlags & 92 /* ParameterPropertyModifier */) { - transformFlags |= 3 /* AssertTypeScript */ | 131072 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES6 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~538968917 /* ParameterExcludes */; + return transformFlags & ~536872257 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21018,17 +22737,17 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (expressionKind === 195 /* AsExpression */ - || expressionKind === 177 /* TypeAssertionExpression */) { + if (expressionKind === 200 /* AsExpression */ + || expressionKind === 182 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 256 /* DestructuringAssignment */) { - transformFlags |= 256 /* DestructuringAssignment */; + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -21039,47 +22758,49 @@ var ts; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES6 */; + transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - // An exported declaration may be TypeScript syntax. - if ((subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) - || (modifierFlags & 1 /* Export */)) { + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537590613 /* ClassExcludes */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 137216 /* TypeScriptClassSyntaxMask */) { + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537590613 /* ClassExcludes */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 83 /* ExtendsKeyword */: + case 84 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 106 /* ImplementsKeyword */: + case 107 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; @@ -21088,65 +22809,85 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537920833 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var body = node.body; - if (body === undefined) { - // An overload constructor is TypeScript syntax. + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* ConstructorExcludes */; + return transformFlags & ~601015617 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - var typeParameters = node.typeParameters; - var asteriskToken = node.asteriskToken; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || typeParameters - || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) - || (subtreeFlags & 2048 /* ContainsDecorators */)) { + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || (modifierFlags & (256 /* Async */ | 128 /* Abstract */)) - || (subtreeFlags & 2048 /* ContainsDecorators */)) { + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550593365 /* MethodOrAccessorExcludes */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -21154,88 +22895,113 @@ var ts; // If the PropertyDeclaration has an initializer, we need to inform its ancestor // so that it handle the transformation. if (node.initializer) { - transformFlags |= 4096 /* ContainsPropertyInitializer */; + transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - var asteriskToken = node.asteriskToken; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & 1 /* Export */) { - transformFlags |= 3 /* AssertTypeScript */ | 192 /* AssertES6 */; - } - // If a FunctionDeclaration is async, then it is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550726485 /* FunctionExcludes */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var asteriskToken = node.asteriskToken; - // An async function expression is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 81920 /* ES6FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { - transformFlags |= 1536 /* AssertGenerator */; + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { + transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550726485 /* FunctionExcludes */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES6 */; - var modifierFlags = ts.getModifierFlags(node); - // An async arrow function is TypeScript syntax. - if (modifierFlags & 256 /* Async */) { + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { transformFlags |= 3 /* AssertTypeScript */; } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~550710101 /* ArrowFunctionExcludes */; + return transformFlags & ~601249089 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21243,21 +23009,25 @@ var ts; var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 95 /* SuperKeyword */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + if (expressionKind === 96 /* SuperKeyword */) { + transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - var nameKind = node.name.kind; - // A VariableDeclaration with a binding pattern is ES6 syntax. - if (nameKind === 167 /* ObjectBindingPattern */ || nameKind === 168 /* ArrayBindingPattern */) { - transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -21269,26 +23039,22 @@ var ts; } else { transformFlags = subtreeFlags; - // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & 1 /* Export */) { - transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; - } - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES6 */; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -21297,18 +23063,18 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // If the expression of an expression statement is a destructuring assignment, // then we treat the statement as ES6 so that we can indicate that we do not // need to hold on to the right-hand side. - if (node.expression.transformFlags & 256 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES6 */; + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536871765 /* NodeExcludes */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -21317,111 +23083,116 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546335573 /* ModuleExcludes */; + return transformFlags & ~574674241 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES6 */; + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES6 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~538968917 /* VariableDeclarationListExcludes */; + return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536871765 /* NodeExcludes */; + var excludeFlags = 536872257 /* NodeExcludes */; switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 115 /* AbstractKeyword */: - case 122 /* DeclareKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 184 /* AwaitExpression */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: - case 196 /* NonNullExpression */: - case 128 /* ReadonlyKeyword */: + case 119 /* AsyncKeyword */: + case 189 /* AwaitExpression */: + // async/await is ES2017 syntax + transformFlags |= 16 /* AssertES2017 */; + break; + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 116 /* AbstractKeyword */: + case 123 /* DeclareKeyword */: + case 75 /* ConstKeyword */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: + case 201 /* NonNullExpression */: + case 130 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 241 /* JsxElement */: - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - case 244 /* JsxText */: - case 245 /* JsxClosingElement */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - case 248 /* JsxExpression */: + case 246 /* JsxElement */: + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 249 /* JsxClosingElement */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: + case 252 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 12 /* AssertJsx */; + transformFlags |= 4 /* AssertJsx */; break; - case 82 /* ExportKeyword */: - // This node is both ES6 and TypeScript syntax. - transformFlags |= 192 /* AssertES6 */ | 3 /* AssertTypeScript */; - break; - case 77 /* DefaultKeyword */: - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - case 189 /* TemplateExpression */: - case 176 /* TaggedTemplateExpression */: - case 254 /* ShorthandPropertyAssignment */: - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: + // for-of might be ESNext if it has a rest destructuring + transformFlags |= 8 /* AssertESNext */; + // FALLTHROUGH + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: + case 194 /* TemplateExpression */: + case 181 /* TaggedTemplateExpression */: + case 258 /* ShorthandPropertyAssignment */: + case 114 /* StaticKeyword */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 4194304 /* ContainsYield */; + transformFlags |= 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; break; - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 141 /* TypeParameter */: - case 144 /* PropertySignature */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 154 /* TypePredicate */: - case 155 /* TypeReference */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 143 /* TypeParameter */: + case 146 /* PropertySignature */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 156 /* TypePredicate */: + case 157 /* TypeReference */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 160 /* TypeQuery */: + case 161 /* TypeLiteral */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 167 /* ThisType */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 171 /* LiteralType */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -21430,76 +23201,877 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 191 /* SpreadElementExpression */: - // This node is ES6 syntax, but is handled by a containing node. - transformFlags |= 262144 /* ContainsSpreadElementExpression */; + case 196 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 95 /* SuperKeyword */: + case 259 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 96 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; break; - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES6 */ | 2097152 /* ContainsBindingPattern */; + case 172 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 143 /* Decorator */: + case 173 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 174 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 145 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 2048 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 171 /* ObjectLiteralExpression */: - excludeFlags = 537430869 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + case 176 /* ObjectLiteralExpression */: + excludeFlags = 540087617 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; } break; - case 170 /* ArrayLiteralExpression */: - case 175 /* NewExpression */: - excludeFlags = 537133909 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 262144 /* ContainsSpreadElementExpression */) { - // If the this node contains a SpreadElementExpression, then it is an ES6 + case 175 /* ArrayLiteralExpression */: + case 180 /* NewExpression */: + excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 // node. - transformFlags |= 192 /* AssertES6 */; + transformFlags |= 192 /* AssertES2015 */; } break; - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES6 */; + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 256 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES6 */; + case 261 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 211 /* ReturnStatement */: - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + case 216 /* ReturnStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 175 /* ArrayLiteralExpression */: + return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + case 230 /* ModuleDeclaration */: + return 574674241 /* ModuleExcludes */; + case 144 /* Parameter */: + return 536872257 /* ParameterExcludes */; + case 185 /* ArrowFunction */: + return 601249089 /* ArrowFunctionExcludes */; + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + return 601281857 /* FunctionExcludes */; + case 224 /* VariableDeclarationList */: + return 546309441 /* VariableDeclarationListExcludes */; + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return 539358529 /* ClassExcludes */; + case 150 /* Constructor */: + return 601015617 /* ConstructorExcludes */; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return 601015617 /* MethodOrAccessorExcludes */; + case 118 /* AnyKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 134 /* StringKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 143 /* TypeParameter */: + case 146 /* PropertySignature */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 176 /* ObjectLiteralExpression */: + return 540087617 /* ObjectLiteralExcludes */; + case 256 /* CatchClause */: + return 537920833 /* CatchClauseExcludes */; + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + return 537396545 /* BindingPatternExcludes */; + default: + return 536872257 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + /** Create Resolved from a file with unknown extension. */ + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2 /* DtsOnly */: + case 0 /* TypeScript */: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1 /* JavaScript */: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @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 + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === 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, typeRoots); + } + } + else { + 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, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2 /* DtsOnly */, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2 /* DtsOnly */, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, 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, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + return path_1 && { path: path_1, extension: tsExtension }; + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; + } + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case 2 /* DtsOnly */: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0 /* TypeScript */: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1 /* JavaScript */: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocations.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + // Note: this would allow a package.json to specify a ".js" file as typings. Maybe that should be forbidden. + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0 /* TypeScript */, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(2 /* DtsOnly */, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== 1 /* JavaScript */) { + return loadModuleFromNodeModulesFolder(2 /* DtsOnly */, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + // Climb up parent directories looking for a module. + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === 0 /* TypeScript */) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2 /* DtsOnly */, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21536,6 +24108,8 @@ var ts; // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if // they no longer need the information (for example, if the user started editing again). var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); @@ -21597,21 +24171,30 @@ var ts; getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + tryGetMemberInModuleExports: tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + } }; var tupleTypes = []; var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var stringLiteralTypes = ts.createMap(); var numericLiteralTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); @@ -21622,12 +24205,15 @@ var ts; var neverType = createIntrinsicType(8192 /* Never */, "never"); var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ | 67108864 /* Transient */, "__type"); + emptyTypeLiteralSymbol.members = ts.createMap(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -21653,6 +24239,7 @@ var ts; var globalBooleanType; var globalRegExpType; var anyArrayType; + var autoArrayType; var anyReadonlyArrayType; // The library files are only loaded when the feature is used. // This allows users to just specify library files they want to used through --lib @@ -21785,6 +24372,8 @@ var ts; "undefined": undefinedType }); var jsxElementType; + var _jsxNamespace; + var _jsxFactoryEntity; /** Things we lazy load from the JSX namespace */ var jsxTypes = ts.createMap(); var JsxNames = { @@ -21814,6 +24403,21 @@ var ts; builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; + function getJsxNamespace() { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. @@ -21897,13 +24501,11 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 225 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 225 /* ModuleDeclaration */))) { + (target.valueDeclaration.kind === 230 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 230 /* ModuleDeclaration */))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } - ts.forEach(source.declarations, function (node) { - target.declarations.push(node); - }); + ts.addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = ts.createMap(); @@ -21959,7 +24561,7 @@ var ts; var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); if (!mainModule) { return; } @@ -22000,8 +24602,11 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type) { + return type.flags & 32768 /* Object */ ? type.objectFlags : 0; + } function isGlobalSourceFile(node) { - return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 261 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -22047,24 +24652,30 @@ var ts; // nodes are in different files and order cannot be determines return true; } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } var sourceFiles = host.getSourceFiles(); return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 218 /* VariableDeclaration */ || + return declaration.kind !== 223 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 200 /* VariableStatement */: - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 205 /* VariableStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -22073,8 +24684,8 @@ var ts; break; } switch (declaration.parent.parent.kind) { - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: // ForIn/ForOf case - use site should not be used in expression part if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { return true; @@ -22082,8 +24693,7 @@ var ts; } return false; } - function isUsedInFunctionOrNonStaticProperty(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage, container) { var current = usage; while (current) { if (current === container) { @@ -22093,7 +24703,7 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 145 /* PropertyDeclaration */ && + current.parent.kind === 147 /* PropertyDeclaration */ && (ts.getModifierFlags(current.parent) & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { @@ -22126,11 +24736,11 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 278 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || - lastLocation.kind === 142 /* Parameter */ || - lastLocation.kind === 141 /* TypeParameter */ + lastLocation.kind === 144 /* Parameter */ || + lastLocation.kind === 143 /* TypeParameter */ : false; } if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { @@ -22139,9 +24749,9 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 142 /* Parameter */ || + lastLocation.kind === 144 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 142 /* Parameter */); + result.valueDeclaration.kind === 144 /* Parameter */); } } if (useResult) { @@ -22153,13 +24763,13 @@ var ts; } } switch (location.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 261 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports["default"]) { @@ -22182,7 +24792,7 @@ var ts; // which is not the desired behavior. if (moduleExports[name] && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 243 /* ExportSpecifier */)) { break; } } @@ -22190,13 +24800,13 @@ var ts; break loop; } break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -22213,9 +24823,9 @@ var ts; } } break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -22226,7 +24836,7 @@ var ts; } break loop; } - if (location.kind === 192 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 197 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -22242,9 +24852,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 227 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -22252,19 +24862,19 @@ var ts; } } break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -22277,7 +24887,7 @@ var ts; } } break; - case 143 /* Decorator */: + case 145 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -22286,7 +24896,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 142 /* Parameter */) { + if (location.parent && location.parent.kind === 144 /* Parameter */) { location = location.parent; } // @@ -22314,6 +24924,7 @@ var ts; if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } @@ -22349,15 +24960,15 @@ var ts; // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + if (decls && decls.length === 1 && decls[0].kind === 233 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 70 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -22402,16 +25013,26 @@ var ts; */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: ts.Debug.assert(ts.isEntityNameExpression(node.expression)); return node.expression; default: return undefined; } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920 /* Namespace */) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); @@ -22427,7 +25048,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -22448,23 +25069,23 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 229 /* ImportEqualsDeclaration */) { + if (node.kind === 234 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 230 /* ImportDeclaration */) { + while (node && node.kind !== 235 /* ImportDeclaration */) { node = node.parent; } return node; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 240 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 245 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -22540,31 +25161,31 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_13 = specifier.propertyName || specifier.name; - if (name_13.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { 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="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -22586,19 +25207,19 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return getTargetOfImportClause(node); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return getTargetOfExportAssignment(node); - case 228 /* NamespaceExportDeclaration */: + case 233 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node); } } @@ -22645,11 +25266,11 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 235 /* ExportAssignment */) { + if (node.kind === 240 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 238 /* ExportSpecifier */) { + else if (node.kind === 243 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -22660,24 +25281,24 @@ var ts; } } // This function is only for imports with entity names - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (entityName.kind === 70 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { + if (entityName.kind === 70 /* Identifier */ || entityName.parent.kind === 141 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 234 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -22690,16 +25311,16 @@ var ts; return undefined; } var symbol; - if (name.kind === 69 /* Identifier */) { + if (name.kind === 70 /* Identifier */) { var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } } - else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { - var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 141 /* QualifiedName */ || name.kind === 177 /* PropertyAccessExpression */) { + var left = name.kind === 141 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 141 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -22724,30 +25345,30 @@ var ts; function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode) { + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReference); if (moduleName === undefined) { return; } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); - if (symbol) { - // merged symbol is module declaration symbol combined with all augmentations - return getMergedSymbol(symbol); - } + var ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; } + var isRelative = ts.isExternalModuleNameRelative(moduleName); var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { // merged symbol is module declaration symbol combined with all augmentations @@ -22765,15 +25386,32 @@ var ts; return getMergedSymbol(pattern.symbol); } } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } if (moduleNotFoundError) { // report errors only if it was requested - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -22800,6 +25438,12 @@ var ts; function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } function getExportsOfSymbol(symbol) { return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -22833,6 +25477,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -22904,7 +25550,7 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 148 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 150 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -22926,8 +25572,9 @@ var ts; type.intrinsicName = "boolean"; return type; } - function createObjectType(kind, symbol) { - var type = createType(kind); + function createObjectType(objectFlags, symbol) { + var type = createType(32768 /* Object */); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -22955,7 +25602,7 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; @@ -22967,7 +25614,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -22979,11 +25626,11 @@ var ts; } } switch (location_1.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } @@ -22998,6 +25645,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { @@ -23016,31 +25673,33 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 /* Alias */ + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -23063,7 +25722,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -23078,10 +25737,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: continue; default: return false; @@ -23112,7 +25771,7 @@ var ts; return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, }; } return hasAccessibleDeclarations; @@ -23149,7 +25808,7 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; @@ -23162,7 +25821,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -23203,12 +25862,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 158 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 160 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 139 /* QualifiedName */ || entityName.kind === 172 /* PropertyAccessExpression */ || - entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 141 /* QualifiedName */ || entityName.kind === 177 /* PropertyAccessExpression */ || + entityName.parent.kind === 234 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -23304,10 +25963,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 164 /* ParenthesizedType */) { + while (node.kind === 166 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 228 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -23315,7 +25974,7 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 226 /* ModuleBlock */ && + node.parent.kind === 231 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { @@ -23329,10 +25988,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return "(Anonymous class)"; - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -23355,17 +26014,17 @@ var ts; var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 19 /* OpenBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } else { - writePunctuation(writer, 21 /* DotToken */); + writePunctuation(writer, 22 /* DotToken */); writer.writeSymbol(symbolName, symbol); } } @@ -23407,9 +26066,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_5) { + walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,59 +26112,69 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072 /* Reference */) { + else if (getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } else if (type.flags & 256 /* EnumLiteral */) { buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 21 /* DotToken */); + writePunctuation(writer, 22 /* DotToken */); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (16 /* Enum */ | 16384 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 196608 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & 2097152 /* Anonymous */) { + else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { writeAnonymousType(type, nextFlags); } else if (type.flags & 96 /* StringOrNumberLiteral */) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & 262144 /* Index */) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 64 /* InElementType */); + } + else if (type.flags & 524288 /* IndexedAccess */) { + writeType(type.objectType, 64 /* InElementType */); + writePunctuation(writer, 20 /* OpenBracketToken */); + writeType(type.indexType, 0 /* None */); + writePunctuation(writer, 21 /* CloseBracketToken */); + } else { // Should never get here // { ... } - writePunctuation(writer, 15 /* OpenBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); writeSpace(writer); - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); writeSpace(writer); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 24 /* CommaToken */) { + if (delimiter !== 25 /* CommaToken */) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 24 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); + writeType(types[i], delimiter === 25 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { @@ -23514,29 +26183,29 @@ var ts; buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } if (pos < end) { - writePunctuation(writer, 25 /* LessThanToken */); + writePunctuation(writer, 26 /* LessThanToken */); writeType(typeArguments[pos], 256 /* InFirstTypeArgument */); pos++; while (pos < end) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); writeType(typeArguments[pos], 0 /* None */); pos++; } - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { writeType(typeArguments[0], 64 /* InElementType */); - writePunctuation(writer, 19 /* OpenBracketToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } - else if (type.target.flags & 262144 /* Tuple */) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); + else if (type.target.objectFlags & 8 /* Tuple */) { + writePunctuation(writer, 20 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 25 /* CommaToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } else { // Write the type reference in the format f
.g.C where A and B are type arguments @@ -23549,15 +26218,15 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); - writePunctuation(writer, 21 /* DotToken */); + writeSymbolTypeReference(parent_6, typeArguments, start, i, flags); + writePunctuation(writer, 22 /* DotToken */); } } } @@ -23567,16 +26236,16 @@ var ts; } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } - if (type.flags & 524288 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); + if (type.flags & 65536 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 48 /* BarToken */); } else { - writeTypeList(type.types, 46 /* AmpersandToken */); + writeTypeList(type.types, 47 /* AmpersandToken */); } if (flags & 64 /* InElementType */) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } } function writeAnonymousType(type, flags) { @@ -23598,7 +26267,7 @@ var ts; } else { // Recursive usage, use any - writeKeyword(writer, 117 /* AnyKeyword */); + writeKeyword(writer, 118 /* AnyKeyword */); } } else { @@ -23622,7 +26291,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 256 /* SourceFile */ || declaration.parent.kind === 226 /* ModuleBlock */; + return declaration.parent.kind === 261 /* SourceFile */ || declaration.parent.kind === 231 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -23632,37 +26301,37 @@ var ts; } } function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 101 /* TypeOfKeyword */); + writeKeyword(writer, 102 /* TypeOfKeyword */); writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); } function writeIndexSignature(info, keyword) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 128 /* ReadonlyKeyword */); + writeKeyword(writer, 130 /* ReadonlyKeyword */); writeSpace(writer); } - writePunctuation(writer, 19 /* OpenBracketToken */); + writePunctuation(writer, 20 /* OpenBracketToken */); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeKeyword(writer, keyword); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeType(info.type, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 128 /* ReadonlyKeyword */); + writeKeyword(writer, 130 /* ReadonlyKeyword */); writeSpace(writer); } buildSymbolDisplay(prop, writer); if (prop.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); + writePunctuation(writer, 54 /* QuestionToken */); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { @@ -23678,56 +26347,68 @@ var ts; return false; } function writeLiteralType(type, flags) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + writeMappedType(type); + return; + } + } var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 15 /* OpenBraceToken */); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { if (flags & 64 /* InElementType */) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); } - writeKeyword(writer, 92 /* NewKeyword */); + writeKeyword(writer, 93 /* NewKeyword */); writeSpace(writer); buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 15 /* OpenBraceToken */); + writePunctuation(writer, 16 /* OpenBraceToken */); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 17 /* CloseBraceToken */); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } - writeIndexSignature(resolved.stringIndexInfo, 132 /* StringKeyword */); - writeIndexSignature(resolved.numberIndexInfo, 130 /* NumberKeyword */); + writeIndexSignature(resolved.stringIndexInfo, 134 /* StringKeyword */); + writeIndexSignature(resolved.numberIndexInfo, 132 /* NumberKeyword */); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -23737,22 +26418,45 @@ var ts; var signature = signatures_1[_f]; writePropertyWithModifiers(p); buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); writeType(t, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); + writePunctuation(writer, 24 /* SemicolonToken */); writer.writeLine(); } } + } + function writeMappedType(type) { + writePunctuation(writer, 16 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 130 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 20 /* OpenBracketToken */); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 91 /* InKeyword */); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 21 /* CloseBracketToken */); + if (type.declaration.questionToken) { + writePunctuation(writer, 54 /* QuestionToken */); + } + writePunctuation(writer, 55 /* ColonToken */); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 24 /* SemicolonToken */); + writer.writeLine(); writer.decreaseIndent(); - writePunctuation(writer, 16 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; + writePunctuation(writer, 17 /* CloseBraceToken */); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { @@ -23766,7 +26470,7 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 83 /* ExtendsKeyword */); + writeKeyword(writer, 84 /* ExtendsKeyword */); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } @@ -23774,7 +26478,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (ts.isRestParameter(parameterNode)) { - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); } if (ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -23783,37 +26487,37 @@ var ts; appendSymbolNameOnly(p, writer); } if (isOptionalParameter(parameterNode)) { - writePunctuation(writer, 53 /* QuestionToken */); + writePunctuation(writer, 54 /* QuestionToken */); } - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 167 /* ObjectBindingPattern */) { - writePunctuation(writer, 15 /* OpenBraceToken */); + if (bindingPattern.kind === 172 /* ObjectBindingPattern */) { + writePunctuation(writer, 16 /* OpenBraceToken */); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 16 /* CloseBraceToken */); + writePunctuation(writer, 17 /* CloseBraceToken */); } - else if (bindingPattern.kind === 168 /* ArrayBindingPattern */) { - writePunctuation(writer, 19 /* OpenBracketToken */); + else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) { + writePunctuation(writer, 20 /* OpenBracketToken */); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); } - writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 21 /* CloseBracketToken */); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 169 /* BindingElement */); + ts.Debug.assert(bindingElement.kind === 174 /* BindingElement */); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); - writePunctuation(writer, 54 /* ColonToken */); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -23821,75 +26525,75 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 22 /* DotDotDotToken */); + writePunctuation(writer, 23 /* DotDotDotToken */); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25 /* LessThanToken */); + writePunctuation(writer, 26 /* LessThanToken */); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); } action(list[i]); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 25 /* LessThanToken */); - var flags_1 = 256 /* InFirstTypeArgument */; + writePunctuation(writer, 26 /* LessThanToken */); + var flags = 256 /* InFirstTypeArgument */; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); - flags_1 = 0 /* None */; + flags = 0 /* None */; } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags_1); + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 27 /* GreaterThanToken */); + writePunctuation(writer, 28 /* GreaterThanToken */); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 17 /* OpenParenToken */); + writePunctuation(writer, 18 /* OpenParenToken */); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 24 /* CommaToken */); + writePunctuation(writer, 25 /* CommaToken */); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 18 /* CloseParenToken */); + writePunctuation(writer, 19 /* CloseParenToken */); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 97 /* ThisKeyword */); + writeKeyword(writer, 98 /* ThisKeyword */); } writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); + writeKeyword(writer, 125 /* IsKeyword */); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); - writePunctuation(writer, 34 /* EqualsGreaterThanToken */); + writePunctuation(writer, 35 /* EqualsGreaterThanToken */); } else { - writePunctuation(writer, 54 /* ColonToken */); + writePunctuation(writer, 55 /* ColonToken */); } writeSpace(writer); if (signature.typePredicate) { @@ -23902,7 +26606,7 @@ var ts; } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { if (kind === 1 /* Construct */) { - writeKeyword(writer, 92 /* NewKeyword */); + writeKeyword(writer, 93 /* NewKeyword */); writeSpace(writer); } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { @@ -23940,75 +26644,75 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 169 /* BindingElement */: + case 174 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 220 /* FunctionDeclaration */: - case 224 /* EnumDeclaration */: - case 229 /* ImportEqualsDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + case 229 /* EnumDeclaration */: + case 234 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_7 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 234 /* ImportEqualsDeclaration */ && parent_7.kind !== 261 /* SourceFile */ && ts.isInAmbientContext(parent_7))) { + return isGlobalSourceFile(parent_7); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + return isDeclarationVisible(parent_7); + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so const it fall into next case statement - case 148 /* Constructor */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 153 /* IndexSignature */: - case 142 /* Parameter */: - case 226 /* ModuleBlock */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 159 /* TypeLiteral */: - case 155 /* TypeReference */: - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: + case 150 /* Constructor */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 155 /* IndexSignature */: + case 144 /* Parameter */: + case 231 /* ModuleBlock */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 161 /* TypeLiteral */: + case 157 /* TypeReference */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: return false; // Type parameters are always visible - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: // Source file and namespace export are always visible - case 256 /* SourceFile */: - case 228 /* NamespaceExportDeclaration */: + case 261 /* SourceFile */: + case 233 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return false; default: return false; @@ -24017,10 +26721,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 240 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 238 /* ExportSpecifier */) { + else if (node.parent.kind === 243 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -24095,7 +26799,6 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 32768 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -24114,12 +26817,12 @@ var ts; node = ts.getRootDeclaration(node); while (node) { switch (node.kind) { - case 218 /* VariableDeclaration */: - case 219 /* VariableDeclarationList */: - case 234 /* ImportSpecifier */: - case 233 /* NamedImports */: - case 232 /* NamespaceImport */: - case 231 /* ImportClause */: + case 223 /* VariableDeclaration */: + case 224 /* VariableDeclarationList */: + case 239 /* ImportSpecifier */: + case 238 /* NamedImports */: + case 237 /* NamespaceImport */: + case 236 /* ImportClause */: node = node.parent; break; default: @@ -24152,22 +26855,36 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function getTextOfPropertyName(name) { - switch (name.kind) { - case 69 /* Identifier */: - return name.text; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - case 140 /* ComputedPropertyName */: - if (ts.isStringOrNumericLiteral(name.expression.kind)) { - return name.expression.text; - } - } - return undefined; - } function isComputedNonLiteralName(name) { - return name.kind === 140 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind); + return name.kind === 142 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (source.flags & 8192 /* Never */) { + return emptyObjectType; + } + if (source.flags & 65536 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createMap(); + var names = ts.createMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name_17 = properties_2[_i]; + names[ts.getTextOfPropertyName(name_17)] = true; + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = prop.name in names; + var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isMethod = prop.flags & 8192 /* Method */; + var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { @@ -24187,25 +26904,41 @@ var ts; return parentType; } var type; - if (pattern.kind === 167 /* ObjectBindingPattern */) { - // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_14 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_14)) { - // computed properties with non-literal names are treated as 'any' - return anyType; + if (pattern.kind === 172 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - var text = getTextOfPropertyName(name_14); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); - return unknownType; + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name_18 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_18)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + var text = ts.getTextOfPropertyName(name_18); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); + if (!type) { + error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); + return unknownType; + } } } else { @@ -24213,7 +26946,11 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + else { // Use specific property type when parent is a tuple or numeric index type when parent is an array var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) @@ -24229,10 +26966,6 @@ var ts; return unknownType; } } - else { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); - } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. @@ -24244,42 +26977,26 @@ var ts; type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); - } - } - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { - // First, see if this node has an @type annotation on it directly. - var typeTag = ts.getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - if (declaration.kind === 218 /* VariableDeclaration */ && - declaration.parent.kind === 219 /* VariableDeclarationList */ && - declaration.parent.parent.kind === 200 /* VariableStatement */) { - // @type annotation might have been on the variable statement, try that instead. - var annotation = ts.getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === 142 /* Parameter */) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } return undefined; } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 94 /* NullKeyword */ || expr.kind === 70 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 175 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. @@ -24288,11 +27005,13 @@ var ts; return type; } } - // A variable declared in a for..in statement is always of type string - if (declaration.parent.parent.kind === 207 /* ForInStatement */) { - return stringType; + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (declaration.parent.parent.kind === 212 /* ForInStatement */) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 208 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 213 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -24306,11 +27025,26 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } - if (declaration.kind === 142 /* Parameter */) { + if ((compilerOptions.noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && + declaration.kind === 223 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 144 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 150 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149 /* GetAccessor */); + if (func.kind === 152 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -24325,8 +27059,7 @@ var ts; // Use contextual parameter type if one is available var type = void 0; if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -24341,7 +27074,7 @@ var ts; return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 258 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -24369,6 +27102,7 @@ var ts; // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createMap(); + var stringIndexInfo; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -24377,19 +27111,23 @@ var ts; hasComputedProperties = true; return; } - var text = getTextOfPropertyName(name); + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; members[symbol.name] = symbol; }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } return result; } @@ -24398,7 +27136,7 @@ var ts; var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); @@ -24417,7 +27155,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 167 /* ObjectBindingPattern */ + return pattern.kind === 172 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -24439,7 +27177,7 @@ var ts; // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - if (declaration.kind === 253 /* PropertyAssignment */) { + if (declaration.kind === 257 /* PropertyAssignment */) { return type; } return getWidenedType(type); @@ -24456,7 +27194,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 142 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 144 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -24468,14 +27206,14 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 252 /* CatchClause */) { + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 235 /* ExportAssignment */) { + if (declaration.kind === 240 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 1048576 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { + if (declaration.flags & 65536 /* JavaScriptFile */ && declaration.kind === 286 /* JSDocPropertyTag */ && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } // Handle variable, parameter or property @@ -24488,16 +27226,16 @@ var ts; // * exports.p = expr // * this.p = expr // * className.prototype.method = expr - if (declaration.kind === 187 /* BinaryExpression */ || - declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { + if (declaration.kind === 192 /* BinaryExpression */ || + declaration.kind === 177 /* PropertyAccessExpression */ && declaration.parent.kind === 192 /* BinaryExpression */) { // Use JS Doc type if present on parent expression statement - if (declaration.flags & 1048576 /* JavaScriptFile */) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + if (declaration.flags & 65536 /* JavaScriptFile */) { + var jsdocType = ts.getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 /* BinaryExpression */ ? checkExpressionCached(decl.right) : checkExpressionCached(decl.parent.right); }); type = getUnionType(declaredTypes, /*subtypeReduction*/ true); @@ -24506,18 +27244,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - // Variable has type annotation that circularly references the variable itself - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -24525,7 +27252,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 149 /* GetAccessor */) { + if (accessor.kind === 151 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -24545,9 +27272,9 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 150 /* SetAccessor */); - if (getter && getter.flags & 1048576 /* JavaScriptFile */) { + var getter = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 152 /* SetAccessor */); + if (getter && getter.flags & 65536 /* JavaScriptFile */) { var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; @@ -24590,7 +27317,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 149 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -24601,11 +27328,11 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(2097152 /* Anonymous */, symbol); + var type = createObjectType(16 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24637,10 +27364,29 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); @@ -24663,7 +27409,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 /* Reference */ ? type.target : type; + return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -24697,9 +27443,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 221 /* ClassDeclaration */ || node.kind === 192 /* ClassExpression */ || - node.kind === 220 /* FunctionDeclaration */ || node.kind === 179 /* FunctionExpression */ || - node.kind === 147 /* MethodDeclaration */ || node.kind === 180 /* ArrowFunction */) { + if (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */ || + node.kind === 225 /* FunctionDeclaration */ || node.kind === 184 /* FunctionExpression */ || + node.kind === 149 /* MethodDeclaration */ || node.kind === 185 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -24709,7 +27455,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 222 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -24718,8 +27464,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 222 /* InterfaceDeclaration */ || node.kind === 221 /* ClassDeclaration */ || - node.kind === 192 /* ClassExpression */ || node.kind === 223 /* TypeAliasDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 226 /* ClassDeclaration */ || + node.kind === 197 /* ClassExpression */ || node.kind === 228 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -24734,7 +27480,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -24746,7 +27492,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; @@ -24766,7 +27512,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 32768 /* Object */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -24785,7 +27531,7 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.flags & 262144 /* Tuple */) { + if (type.objectFlags & 8 /* Tuple */) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -24805,7 +27551,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { + if (!(baseConstructorType.flags & 32768 /* Object */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -24829,15 +27575,23 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } + // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { + if (!(getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } if (type.resolvedBaseTypes === emptyArray) { @@ -24862,12 +27616,12 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 227 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { + if (getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -24894,7 +27648,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 222 /* InterfaceDeclaration */) { + if (declaration.kind === 227 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -24917,7 +27671,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -24926,8 +27680,8 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 131072 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -24935,7 +27689,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -24950,8 +27705,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); + var declaration = ts.getDeclarationOfKind(symbol, 285 /* JSDocTypedefTag */); var type = void 0; if (declaration) { if (declaration.jsDocTypeLiteral) { @@ -24962,16 +27716,17 @@ var ts; } } else { - declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + declaration = ts.getDeclarationOfKind(symbol, 228 /* TypeAliasDeclaration */); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; links.instantiations = ts.createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -24988,14 +27743,14 @@ var ts; return !ts.isInAmbientContext(member); } return expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; + expr.kind === 70 /* Identifier */ && !!symbol.exports[expr.text]; } function enumHasLiteralMembers(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { + if (declaration.kind === 229 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!isLiteralEnumMember(symbol, member)) { @@ -25023,7 +27778,7 @@ var ts; var memberTypes = ts.createMap(); for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { + if (declaration.kind === 229 /* EnumDeclaration */) { computeEnumMemberValues(declaration); for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; @@ -25038,7 +27793,7 @@ var ts; } enumType.memberTypes = memberTypes; if (memberTypeList.length > 1) { - enumType.flags |= 524288 /* Union */; + enumType.flags |= 65536 /* Union */; enumType.types = memberTypeList; unionTypes[getTypeListId(memberTypeList)] = enumType; } @@ -25050,7 +27805,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.declaredType) { var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 /* Union */ ? + links.declaredType = enumType.flags & 65536 /* Union */ ? enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : enumType; } @@ -25061,7 +27816,7 @@ var ts; if (!links.declaredType) { var type = createType(16384 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -25114,20 +27869,20 @@ var ts; // considered independent. function isIndependentType(node) { switch (node.kind) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 127 /* NeverKeyword */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 129 /* NeverKeyword */: + case 171 /* LiteralType */: return true; - case 160 /* ArrayType */: + case 162 /* ArrayType */: return isIndependentType(node.elementType); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return isIndependentTypeReference(node); } return false; @@ -25140,7 +27895,7 @@ var ts; // A function-like declaration is considered independent (free of this references) if it has a return type // annotation that is considered independent and if each parameter is considered independent. function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 148 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 150 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -25161,12 +27916,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return isIndependentVariableLikeDeclaration(declaration); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -25211,7 +27966,7 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072 /* Reference */) { + if (getObjectFlags(type) & 4 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; @@ -25234,8 +27989,8 @@ var ts; else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -25255,7 +28010,7 @@ var ts; numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -25290,14 +28045,14 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -25394,7 +28149,7 @@ var ts; var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); @@ -25402,6 +28157,9 @@ var ts; function intersectIndexInfos(info1, info2) { return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). @@ -25416,17 +28174,17 @@ var ts; stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { var members = symbol.members; @@ -25434,7 +28192,7 @@ var ts; var constructSignatures = getSignaturesOfSymbol(members["__new"]); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module @@ -25450,13 +28208,13 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 32768 /* Object */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are // in the process of resolving (see issue #6072). The temporarily empty signature list @@ -25466,21 +28224,124 @@ var ts; } } } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createMap(); + var stringIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 168 /* TypeOperator */) { + // We have a { [P in keyof T]: X } + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + } + else { + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var iterationMapper = createUnaryTypeMapper(typeParameter, t); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 32 /* StringLiteral */) { + var propName = t.text; + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); + var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & 2 /* String */) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function getErasedTemplateTypeFromMappedType(type) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, 540672 /* TypeVariable */ | 262144 /* Index */); + } + return false; + } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Reference */) { - resolveTypeReferenceMembers(type); + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & 2097152 /* Anonymous */) { - resolveAnonymousTypeMembers(type); - } - else if (type.flags & 524288 /* Union */) { + else if (type.flags & 65536 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576 /* Intersection */) { + else if (type.flags & 131072 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -25488,7 +28349,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -25496,7 +28357,7 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -25509,29 +28370,43 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 196608 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter * as the type argument for the 'this' type. */ - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } @@ -25543,29 +28418,20 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 16384 /* TypeParameter */) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & 34 /* StringLike */) { - type = globalStringType; - } - else if (type.flags & 340 /* NumberLike */) { - type = globalNumberType; - } - else if (type.flags & 136 /* BooleanLike */) { - type = globalBooleanType; - } - else if (type.flags & 512 /* ESSymbol */) { - type = getGlobalESSymbolType(); - } - return type; + var t = type.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & 262178 /* StringLike */ ? globalStringType : + t.flags & 340 /* NumberLike */ ? globalNumberType : + t.flags & 136 /* BooleanLike */ ? globalBooleanType : + t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 131072 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25583,22 +28449,21 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + else if (containingType.flags & 65536 /* Union */) { + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +28474,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 65536 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +28503,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -25645,7 +28518,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -25659,13 +28532,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 196608 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 229376 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -25679,7 +28552,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 229376 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -25714,7 +28587,7 @@ var ts; return undefined; } function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { var templateTag = ts.getJSDocTemplateTag(declaration); if (templateTag) { return getTypeParametersFromDeclaration(templateTag.typeParameters); @@ -25744,21 +28617,32 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (node.flags & 1048576 /* JavaScriptFile */) { - if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { + if (node.flags & 65536 /* JavaScriptFile */) { + if (node.type && node.type.kind === 273 /* JSDocOptionalType */) { return true; } - var paramTag = ts.getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 268 /* JSDocOptionalType */; + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 273 /* JSDocOptionalType */; + } } } } } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } function isOptionalParameter(node) { if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -25773,7 +28657,7 @@ var ts; return false; } function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 69 /* Identifier */) { + if (node.parameterName.kind === 70 /* Identifier */) { var parameterName = node.parameterName; return { kind: 1 /* Identifier */, @@ -25816,7 +28700,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* LiteralType */) { + if (param.type && param.type.kind === 171 /* LiteralType */) { hasLiteralTypes = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { @@ -25830,10 +28714,10 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 149 /* GetAccessor */ || declaration.kind === 150 /* SetAccessor */) && + if ((declaration.kind === 151 /* GetAccessor */ || declaration.kind === 152 /* SetAccessor */) && !ts.hasDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; + var otherKind = declaration.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */; var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); @@ -25845,24 +28729,21 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } - var classType = declaration.kind === 148 /* Constructor */ ? + var classType = declaration.kind === 150 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 156 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); } return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType) { + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -25872,7 +28753,7 @@ var ts; else if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.flags & 1048576 /* JavaScriptFile */) { + if (declaration.flags & 65536 /* JavaScriptFile */) { var type = getReturnTypeFromJSDocComment(declaration); if (type && type !== unknownType) { return type; @@ -25880,8 +28761,8 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 149 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 150 /* SetAccessor */); + if (declaration.kind === 151 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 152 /* SetAccessor */); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -25895,20 +28776,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 269 /* JSDocFunctionType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 274 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -25972,13 +28853,18 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { + if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } return anyType; } function getSignatureInstantiation(signature, typeArguments) { + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + function createSignatureInstantiation(signature, typeArguments) { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { @@ -25995,8 +28881,8 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(2097152 /* Anonymous */); + var isConstructor = signature.declaration.kind === 150 /* Constructor */ || signature.declaration.kind === 154 /* ConstructSignature */; + var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -26009,7 +28895,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 130 /* NumberKeyword */ : 132 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 132 /* NumberKeyword */ : 134 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -26036,11 +28922,11 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 141 /* TypeParameter */).constraint; + return ts.getDeclarationOfKind(type.symbol, 143 /* TypeParameter */).constraint; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26068,8 +28954,13 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 524288 /* IndexedAccess */ ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -26106,22 +28997,23 @@ var ts; result |= type.flags; } } - return result & 234881024 /* PropagatingFlags */; + return result & 14680064 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 131072 /* Reference */ | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(4 /* Reference */, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } return type; } function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -26141,7 +29033,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -26149,21 +29041,26 @@ var ts; } return type; } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. function getTypeFromTypeAliasReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; + var typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNodeNoAlias); - var id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -26181,11 +29078,11 @@ var ts; } function getTypeReferenceName(node) { switch (node.kind) { - case 155 /* TypeReference */: + case 157 /* TypeReference */: return node.typeName; - case 267 /* JSDocTypeReference */: + case 272 /* JSDocTypeReference */: return node.name; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -26195,7 +29092,7 @@ var ts; } return undefined; } - function resolveTypeReferenceName(node, typeReferenceName) { + function resolveTypeReferenceName(typeReferenceName) { if (!typeReferenceName) { return unknownSymbol; } @@ -26211,7 +29108,7 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getTypeFromTypeAliasReference(node, symbol); } - if (symbol.flags & 107455 /* Value */ && node.kind === 267 /* JSDocTypeReference */) { + if (symbol.flags & 107455 /* Value */ && node.kind === 272 /* JSDocTypeReference */) { // A JSDocTypeReference may have resolved to a value (as opposed to a type). In // that case, the type of this reference is just the type of the value we resolved // to. @@ -26224,14 +29121,14 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - if (node.kind === 267 /* JSDocTypeReference */) { + if (node.kind === 272 /* JSDocTypeReference */) { var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ + var typeNameOrExpression = node.kind === 157 /* TypeReference */ ? node.typeName : ts.isEntityNameExpression(node.expression) ? node.expression @@ -26266,9 +29163,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: return declaration; } } @@ -26277,7 +29174,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672 /* ObjectType */)) { + if (!(type.flags & 32768 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -26357,7 +29254,7 @@ var ts; property.type = typeParameter; properties.push(property); } - var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -26365,7 +29262,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26383,7 +29281,7 @@ var ts; function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -26411,7 +29309,7 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 524288 /* Union */) { + if (flags & 65536 /* Union */) { addTypesToUnion(typeSet, type.types); } else if (flags & 1 /* Any */) { @@ -26422,7 +29320,7 @@ var ts; typeSet.containsUndefined = true; if (flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(flags & 33554432 /* ContainsWideningType */)) + if (!(flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } else if (!(flags & 8192 /* Never */)) { @@ -26435,7 +29333,8 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -26466,7 +29365,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -26482,7 +29398,7 @@ var ts; var t = types[i]; var remove = t.flags & 32 /* StringLiteral */ && types.containsString || t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 16777216 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -26532,28 +29448,31 @@ var ts; var type = unionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); + type = unionTypes[id] = createType(65536 /* Union */ | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 131072 /* Intersection */) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1 /* Any */) { typeSet.containsAny = true; } else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -26565,6 +29484,11 @@ var ts; addTypeToIntersection(typeSet, type); } } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. @@ -26582,44 +29506,335 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); + type = intersectionTypes[id] = createType(131072 /* Intersection */ | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(32 /* StringLiteral */, ts.unescapeIdentifier(prop.name)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + // We eagerly compute the constraint of the indexed access type such that circularity + // errors are immediately caught and reported. For example, class C { x: this["x"] } + // becomes an error only when the constraint is eagerly computed. + if (type.objectType.flags & 229376 /* StructuredType */) { + // The constraint of T[K], where T is an object, union, or intersection type, + // is the type of the string index signature of T, if any. + type.constraint = getIndexTypeOfType(type.objectType, 0 /* String */); + } + else if (type.objectType.flags & 540672 /* TypeVariable */) { + // The constraint of T[K], where T is a type variable, is A[K], where A is the + // apparent type of T. + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178 /* StringLike */) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0 /* String */); + } + } + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ? + indexType.text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : + undefined; + if (propName) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + var indexNode = accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType)); + } + else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { + error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 178 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1 /* Any */) { + return objectType; + } + // We first check that the index type is assignable to 'keyof T' for the object type. + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes + // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the + // type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise we defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + // In the following we resolve T[K] to the type of the property in T selected by K. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - var type = createObjectType(2097152 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (ts.isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } } return links.resolvedType; } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 228 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, isFromObjectLiteral) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + left = filterType(left, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (left.flags & 8192 /* Never */) { + return right; + } + right = filterType(right, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (right.flags & 8192 /* Never */) { + return left; + } + if (left.flags & 65536 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, isFromObjectLiteral); }); + } + if (right.flags & 65536 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, isFromObjectLiteral); }); + } + var members = ts.createMap(); + var skippedPrivateMembers = ts.createMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + // we approximate own properties as non-methods plus methods that are inside the object literal + var isOwnProperty = !(rightProp.flags & 8192 /* Method */) || isFromObjectLiteral; + var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + var rightProp = members[leftProp.name]; + var rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 536870912 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | 67108864 /* Transient */ | (leftProp.flags & 536870912 /* Optional */); + var result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } function createLiteralType(flags, text) { var type = createType(flags); type.text = text; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 16777216 /* FreshLiteral */)) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 16777216 /* FreshLiteral */, type.text); + var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.text); freshType.regularType = type; type.freshType = freshType; } @@ -26628,7 +29843,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; } function getLiteralTypeForText(flags, text) { var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; @@ -26652,7 +29867,7 @@ var ts; function getTypeFromJSDocTupleType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNodeNoAlias); + var types = ts.map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -26660,9 +29875,9 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 222 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 227 /* InterfaceDeclaration */)) { if (!(ts.getModifierFlags(container) & 32 /* Static */) && - (container.kind !== 148 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 150 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -26676,87 +29891,90 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type) { - return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); - } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { - case 117 /* AnyKeyword */: - case 258 /* JSDocAllType */: - case 259 /* JSDocUnknownType */: + case 118 /* AnyKeyword */: + case 263 /* JSDocAllType */: + case 264 /* JSDocUnknownType */: return anyType; - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: return stringType; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: return numberType; - case 120 /* BooleanKeyword */: + case 121 /* BooleanKeyword */: return booleanType; - case 133 /* SymbolKeyword */: + case 135 /* SymbolKeyword */: return esSymbolType; - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return voidType; - case 135 /* UndefinedKeyword */: + case 137 /* UndefinedKeyword */: return undefinedType; - case 93 /* NullKeyword */: + case 94 /* NullKeyword */: return nullType; - case 127 /* NeverKeyword */: + case 129 /* NeverKeyword */: return neverType; - case 283 /* JSDocNullKeyword */: + case 289 /* JSDocNullKeyword */: return nullType; - case 284 /* JSDocUndefinedKeyword */: + case 290 /* JSDocUndefinedKeyword */: return undefinedType; - case 285 /* JSDocNeverKeyword */: + case 291 /* JSDocNeverKeyword */: return neverType; - case 165 /* ThisType */: - case 97 /* ThisKeyword */: + case 167 /* ThisType */: + case 98 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* LiteralType */: + case 171 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 282 /* JSDocLiteralType */: + case 288 /* JSDocLiteralType */: return getTypeFromLiteralTypeNode(node.literal); - case 155 /* TypeReference */: - case 267 /* JSDocTypeReference */: + case 157 /* TypeReference */: + case 272 /* JSDocTypeReference */: return getTypeFromTypeReference(node); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return booleanType; - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 160 /* ArrayType */: - case 260 /* JSDocArrayType */: + case 162 /* ArrayType */: + case 265 /* JSDocArrayType */: return getTypeFromArrayTypeNode(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 162 /* UnionType */: - case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); - case 164 /* ParenthesizedType */: - case 263 /* JSDocNullableType */: - case 264 /* JSDocNonNullableType */: - case 271 /* JSDocConstructorType */: - case 272 /* JSDocThisType */: - case 268 /* JSDocOptionalType */: + case 164 /* UnionType */: + case 266 /* JSDocUnionType */: + return getTypeFromUnionTypeNode(node); + case 165 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 166 /* ParenthesizedType */: + case 268 /* JSDocNullableType */: + case 269 /* JSDocNonNullableType */: + case 276 /* JSDocConstructorType */: + case 277 /* JSDocThisType */: + case 273 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); - case 265 /* JSDocRecordType */: + case 270 /* JSDocRecordType */: return getTypeFromTypeNode(node.literal); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 159 /* TypeLiteral */: - case 281 /* JSDocTypeLiteral */: - case 269 /* JSDocFunctionType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 161 /* TypeLiteral */: + case 287 /* JSDocTypeLiteral */: + case 274 /* JSDocFunctionType */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 168 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 169 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 170 /* MappedType */: + return getTypeFromMappedTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode - case 69 /* Identifier */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 141 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 262 /* JSDocTupleType */: + case 267 /* JSDocTupleType */: return getTypeFromJSDocTupleType(node); - case 270 /* JSDocVariadicType */: + case 275 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); default: return unknownType; @@ -26773,6 +29991,16 @@ var ts; } return items; } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } function createUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -26795,7 +30023,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -26893,25 +30120,52 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - if (mapper.instantiations) { - var cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); + result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144 /* Index */) { + var typeVariable_1 = constraintType.type; + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + var replacementMapper = createUnaryTypeMapper(typeVariable_1, t); + var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } var mappedTypes = mapper.mappedTypes; // Starting with the parent of the symbol's declaration, check if the mapper maps any of // the type parameters introduced by enclosing declarations. We just pick the first @@ -26919,23 +30173,23 @@ var ts; var node = symbol.declarations[0].parent; while (node) { switch (node.kind) { - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: var declaration = node; if (declaration.typeParameters) { for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { @@ -26945,27 +30199,63 @@ var ts; } } } - if (ts.isClassLike(node) || node.kind === 222 /* InterfaceDeclaration */) { + if (ts.isClassLike(node) || node.kind === 227 /* InterfaceDeclaration */) { var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; if (thisType && ts.contains(mappedTypes, thisType)) { return true; } } break; - case 225 /* ModuleDeclaration */: - case 256 /* SourceFile */: + case 230 /* ModuleDeclaration */: + case 261 /* SourceFile */: return false; } node = node.parent; } return false; } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 261 /* SourceFile */ || parentKind === 231 /* ModuleBlock */; + } + return false; + } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); + // If we are instantiating a type that has a top-level type alias, obtain the instantiation through + // the type alias instead in order to share instantiations for the same type arguments. This can + // dramatically reduce the number of structurally identical types we generate. Note that we can only + // perform this optimization for top-level type aliases. Consider: + // + // function f1(x: T) { + // type Foo = { x: X, t: T }; + // let obj: Foo = { x: x }; + // return obj; + // } + // function f2(x: U) { return f1(x); } + // let z = f2(42); + // + // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo + // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's + // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been + // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & 2097152 /* Anonymous */) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -26974,19 +30264,28 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & 131072 /* Reference */) { - return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + if (type.objectFlags & 32 /* Mapped */) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & 1048576 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } return type; } function instantiateIndexInfo(info, mapper) { @@ -26995,44 +30294,59 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 187 /* BinaryExpression */: - return node.operatorToken.kind === 52 /* BarBarToken */ && + case 192 /* BinaryExpression */: + return node.operatorToken.kind === 53 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - var areAllParametersUntyped = !ts.forEach(node.parameters, function (p) { return p.type; }); - var isNullaryArrow = node.kind === 180 /* ArrowFunction */ && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.forEach(node.parameters, function (p) { return !p.type; })) { + return true; + } + // For arrow functions we now know we're not context sensitive. + if (node.kind === 185 /* ArrowFunction */) { + return false; + } + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. Otherwise we + // know that all parameters (including 'this') have type annotations and nothing is + // subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152 /* Anonymous */, type.symbol); + var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -27235,7 +30549,7 @@ var ts; } if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { + (source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) { return enumRelation[id] = false; } var targetEnumType = getTypeOfSymbol(target.symbol); @@ -27258,7 +30572,7 @@ var ts; return false; if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) return true; - if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) + if (source.flags & 262178 /* StringLike */ && target.flags & 2 /* String */) return true; if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) return true; @@ -27292,23 +30606,23 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { target = target.regularType; } if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { + if (source.flags & 507904 /* StructuredOrTypeParameter */ || target.flags & 507904 /* StructuredOrTypeParameter */) { return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); } return false; @@ -27355,9 +30669,15 @@ var ts; targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); } if (!message) { - message = relation === comparableRelation ? - ts.Diagnostics.Type_0_is_not_comparable_to_type_1 : - ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); } @@ -27371,16 +30691,35 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source, target, reportErrors, headMessage) { var result; - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 16777216 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { target = target.regularType; } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases @@ -27391,7 +30730,7 @@ var ts; } if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (source.flags & 8388608 /* ObjectLiteral */ && source.flags & 16777216 /* FreshLiteral */) { + if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -27402,13 +30741,15 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 1572864 /* UnionOrIntersection */) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 524288 /* Union */) { + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 65536 /* Union */) { if (relation === comparableRelation) { result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); } @@ -27419,56 +30760,128 @@ var ts; return result; } } - else if (target.flags & 1048576 /* Intersection */) { - result = typeRelatedToEachType(source, target, reportErrors); - if (result) { + else if (target.flags & 65536 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { return result; } } - else { - // It is necessary to try these "some" checks on both sides because there may be nested "each" checks - // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or - // A & B = (A & B) | (C & D). - if (source.flags & 1048576 /* Intersection */) { - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + else if (target.flags & 131072 /* Intersection */) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else if (source.flags & 131072 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + return result; + } + } + else if (target.flags & 16384 /* TypeParameter */) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + // Given a type parameter K with a constraint keyof T, a type S is + // assignable to K if S is assignable to keyof T. + var constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & 262144 /* Index */) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 262144 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } } - if (target.flags & 524288 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { + // Given a type variable T with a constraint C, a type S is assignable to + // keyof T if S is assignable to keyof C. + if (target.type.flags & 540672 /* TypeVariable */) { + var constraint = getConstraintOfTypeVariable(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 524288 /* IndexedAccess */) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. + if (source.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(source); - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + else { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // The constraint may need to be further instantiated with its 'this' type. + constraint = getTypeWithThisArgument(constraint, source); + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -27480,7 +30893,7 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { + if (apparentSource.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { @@ -27490,10 +30903,10 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 2588672 /* ObjectType */ && globalObjectType === source) { + else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -27502,8 +30915,8 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -27511,10 +30924,10 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { - if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { - if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -27526,7 +30939,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -27535,7 +30948,7 @@ var ts; return true; } } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 196608 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -27553,7 +30966,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -27571,7 +30984,7 @@ var ts; } return false; } - function eachTypeRelatedToSomeType(source, target, reportErrors) { + function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { @@ -27586,7 +30999,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } var len = targetTypes.length; @@ -27613,7 +31026,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -27708,6 +31121,9 @@ var ts; if (expandingFlags === 3) { result = 1 /* Maybe */; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -27738,15 +31154,43 @@ var ts; } return result; } + // A type [P in S]: X is related to a type [P in T]: Y if T is related to S and X is related to Y. + function mappedTypeRelatedTo(source, target, reportErrors) { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + var result_2; + if (relation === identityRelation) { + var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken; + var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) { + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) { + return -1 /* True */; + } + return 0 /* False */; + } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); - for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var targetProp = properties_2[_i]; + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -27798,7 +31242,8 @@ var ts; return 0 /* False */; } result &= related; - if (sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -27817,7 +31262,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { + if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -28002,7 +31447,7 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 2097152 /* Anonymous */) { + if (getObjectFlags(type) & 16 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -28020,12 +31465,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { + if (getObjectFlags(type) & (4 /* Reference */ | 64 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { + if (getObjectFlags(t) & (4 /* Reference */ | 64 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -28211,12 +31656,12 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 /* Reference */ && type.target === globalArrayType; + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { @@ -28227,7 +31672,7 @@ var ts; } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 65536 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -28235,15 +31680,15 @@ var ts; type.flags & 64 /* NumberLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfLiteralType)) : + type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 32 /* StringLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 16777216 /* FreshLiteral */ ? numberType : + return type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getWidenedLiteralType)) : + type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } /** @@ -28251,7 +31696,7 @@ var ts; * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); + return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -28265,7 +31710,7 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 /* StringLiteral */ ? type.text === "" ? 32 /* StringLiteral */ : 0 : type.flags & 64 /* NumberLiteral */ ? type.text === "0" ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : @@ -28276,7 +31721,7 @@ var ts; return type; } var types = [type]; - if (flags & 34 /* StringLike */) + if (flags & 262178 /* StringLike */) types.push(emptyStringType); if (flags & 340 /* NumberLike */) types.push(zeroType); @@ -28335,7 +31780,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 8388608 /* ObjectLiteral */ && type.flags & 16777216 /* FreshLiteral */)) { + if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -28345,7 +31790,8 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -28362,18 +31808,18 @@ var ts; return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296 /* RequiresWidening */) { + if (type.flags & 6291456 /* RequiresWidening */) { if (type.flags & 6144 /* Nullable */) { return anyType; } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 65536 /* Union */) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } } return type; @@ -28391,7 +31837,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -28407,11 +31853,11 @@ var ts; } } } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432 /* ContainsWideningType */) { + if (t.flags & 2097152 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -28425,25 +31871,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 142 /* Parameter */: + case 144 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 169 /* BindingElement */: + case 174 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -28456,7 +31902,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -28489,7 +31935,7 @@ var ts; signature: signature, inferUnionTypes: inferUnionTypes, inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length) + inferredTypes: new Array(signature.typeParameters.length), }; } function createTypeInferencesObject() { @@ -28497,29 +31943,79 @@ var ts; primary: undefined, secondary: undefined, topLevel: true, - isFixed: false + isFixed: false, }; } // Return true if the given type could possibly reference a type parameter for which // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 /* TypeParameter */ || - type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 /* TypeVariable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 1572864 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypes(context, originalSource, originalTarget) { - var typeParameters = context.signature.typeParameters; + // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + // an object type with the same set of properties as the source type, where the type of each + // property is computed by inferring from the source property type to X for the type + // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0 /* String */); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var typeVariableArray = [typeVariable]; + var typeInferences = createTypeInferencesObject(); + var typeInferencesArray = [typeInferences]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 536870912 /* Optional */; + var members = createSymbolTable(properties); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 /* Property */ | 67108864 /* Transient */ | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + var inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, /*subtypeReduction*/ true); + } + } + function inferTypesWithContext(context, originalSource, originalTarget) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { var sourceStack; var targetStack; var depth = 0; @@ -28535,11 +32031,21 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { return; } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -28577,19 +32083,19 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 540672 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 134217728 /* ContainsAnyFunctionType */) { + if (source.flags & 8388608 /* ContainsAnyFunctionType */) { return; } - for (var i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - var inferences = context.inferences[i]; + for (var i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + var inferences = typeInferences[i]; if (!inferences.isFixed) { // Any inferences that are made to a type parameter in a union type are inferior // to inferences made to a flat (non-union) type. This is because if we infer to @@ -28603,7 +32109,7 @@ var ts; if (!ts.contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -28611,7 +32117,7 @@ var ts; } } } - else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -28620,31 +32126,31 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864 /* UnionOrIntersection */) { + else if (target.flags & 196608 /* UnionOrIntersection */) { var targetTypes = target.types; - var typeParameterCount = 0; - var typeParameter = void 0; - // First infer to each type in union or intersection that isn't a type parameter + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { var t = targetTypes_2[_d]; - if (t.flags & 16384 /* TypeParameter */ && ts.contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - // Next, if target containings a single naked type parameter, make a secondary inference to that type - // parameter. This gives meaningful results for union types in co-variant positions and intersection + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection // types in contra-variant positions (such as callback parameters). - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } - else if (source.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 196608 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -28654,7 +32160,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 2588672 /* ObjectType */) { + if (source.flags & 32768 /* Object */) { if (isInProcess(source, target)) { return; } @@ -28673,18 +32179,47 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var index = ts.indexOf(typeVariables, constraintType.type); + if (index >= 0 && !typeInferences[index].isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & 16384 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -28754,7 +32289,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -28762,7 +32297,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); } function getInferredType(context, index) { var inferredType = context.inferredTypes[index]; @@ -28778,7 +32313,7 @@ var ts; var widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.map(inferences, getWidenedLiteralType) : inferences; + var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; @@ -28832,10 +32367,10 @@ var ts; // The expression is restricted to a single identifier or a sequence of identifiers separated by periods while (node) { switch (node.kind) { - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return true; - case 69 /* Identifier */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 141 /* QualifiedName */: node = node.parent; continue; default: @@ -28849,14 +32384,14 @@ var ts; // leftmost identifier followed by zero or more property names separated by dots. // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 98 /* ThisKeyword */) { return "0"; } - if (node.kind === 172 /* PropertyAccessExpression */) { + if (node.kind === 177 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + node.name.text; } @@ -28864,31 +32399,31 @@ var ts; } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: return node; - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return getLeftmostIdentifierOrThis(node.expression); } return undefined; } function isMatchingReference(source, target) { switch (source.kind) { - case 69 /* Identifier */: - return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && + case 70 /* Identifier */: + return target.kind === 70 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 223 /* VariableDeclaration */ || target.kind === 174 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97 /* ThisKeyword */: - return target.kind === 97 /* ThisKeyword */; - case 172 /* PropertyAccessExpression */: - return target.kind === 172 /* PropertyAccessExpression */ && + case 98 /* ThisKeyword */: + return target.kind === 98 /* ThisKeyword */; + case 177 /* PropertyAccessExpression */: + return target.kind === 177 /* PropertyAccessExpression */ && source.name.text === target.name.text && isMatchingReference(source.expression, target.expression); } return false; } function containsMatchingReference(source, target) { - while (source.kind === 172 /* PropertyAccessExpression */) { + while (source.kind === 177 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -28901,37 +32436,26 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 /* PropertyAccessExpression */ && + return target.kind === 177 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69 /* Identifier */) { + if (expr.kind === 70 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 172 /* PropertyAccessExpression */) { + if (expr.kind === 177 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.text); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + if (type && type.flags & 65536 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -28950,7 +32474,7 @@ var ts; } } } - if (callExpression.expression.kind === 172 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 177 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -28964,7 +32488,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288 /* Union */)) { + if (!(source.flags & 65536 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -29032,7 +32556,7 @@ var ts; type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 2588672 /* ObjectType */) { + if (flags & 32768 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; @@ -29050,7 +32574,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type); return getTypeFacts(constraint || emptyObjectType); } - if (flags & 1572864 /* UnionOrIntersection */) { + if (flags & 196608 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 8388607 /* All */; @@ -29060,13 +32584,13 @@ var ts; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { - var defaultType = checkExpression(defaultExpression); + var defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { - var text = getTextOfPropertyName(name); + var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || @@ -29077,19 +32601,19 @@ var ts; checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType; } - function getTypeOfDestructuredSpreadElement(type) { + function getTypeOfDestructuredSpreadExpression(type) { return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 170 /* ArrayLiteralExpression */ || node.parent.kind === 253 /* PropertyAssignment */ ? + return node.parent.kind === 175 /* ArrayLiteralExpression */ || node.parent.kind === 257 /* PropertyAssignment */ ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node) { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node) { return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); @@ -29100,21 +32624,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return stringType; - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression) || unknownType; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return undefinedType; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 191 /* SpreadElementExpression */: - return getAssignedTypeOfSpreadElement(parent); - case 253 /* PropertyAssignment */: + case 196 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 257 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -29122,11 +32646,11 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 167 /* ObjectBindingPattern */ ? + var type = pattern.kind === 172 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { @@ -29134,47 +32658,60 @@ var ts; // from its initializer, we'll already have cached the type. Otherwise we compute it now // without caching such that transient types are reflected. var links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node) { if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 207 /* ForInStatement */) { + if (node.parent.parent.kind === 212 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 208 /* ForOfStatement */) { + if (node.parent.parent.kind === 213 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 218 /* VariableDeclaration */ ? + return node.kind === 223 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? + return node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } + function isEmptyArrayAssignment(node) { + return node.kind === 223 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 174 /* BindingElement */ && node.parent.kind === 192 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } function getReferenceCandidate(node) { switch (node.kind) { - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return getReferenceCandidate(node.left); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return getReferenceCandidate(node.right); } } return node; } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 183 /* ParenthesizedExpression */ || + parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 57 /* EqualsToken */ && parent.left === node || + parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 25 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } function getTypeOfSwitchClause(clause) { - if (clause.kind === 249 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(checkExpression(clause.expression)); + if (clause.kind === 253 /* CaseClause */) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -29190,13 +32727,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288 /* Union */) { + if (source.flags & 65536 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -29210,14 +32747,37 @@ var ts; } return containsType(target.types, source); } + function forEachType(type, f) { + return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + } function filterType(type, f) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 65536 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29227,22 +32787,122 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 65536 /* Union */ ? + getUnionType(elementType.types, /*subtypeReduction*/ true) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + if (!(t.flags & 8192 /* Never */)) { + if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 177 /* PropertyAccessExpression */ && (parent.name.text === "length" || + parent.parent.kind === 179 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 178 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 192 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 57 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 340 /* NumberLike */ | 2048 /* Undefined */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 96 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 201 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 512 /* Shared */) { + if (flow.flags & 1024 /* 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. @@ -29275,10 +32935,17 @@ var ts; getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { + if (container && container !== flowContainer && reference.kind !== 177 /* PropertyAccessExpression */) { flow = container.flowNode; continue; } @@ -29287,10 +32954,10 @@ var ts; } else { // Unreachable code errors are reported in the binding phase. Here we - // simply return the declared type to reduce follow-on errors. - type = declaredType; + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); } - if (flow.flags & 512 /* Shared */) { + if (flow.flags & 1024 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -29304,10 +32971,21 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29319,24 +32997,56 @@ var ts; // Assignment doesn't affect reference return undefined; } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 179 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 179 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | 2048 /* Undefined */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (!(type.flags & 8192 /* Never */)) { - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & 8192 /* Never */ && isIncomplete(flowType)) { - type = silentNeverType; - } + if (type.flags & 8192 /* Never */) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); @@ -29378,7 +33088,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at @@ -29393,11 +33103,15 @@ var ts; } // If this flow loop junction and reference are already being processed, return // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -29441,15 +33155,15 @@ var ts; } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - var result = getUnionType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } return cache[key] = result; } function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && - declaredType.flags & 524288 /* Union */ && + return expr.kind === 177 /* PropertyAccessExpression */ && + declaredType.flags & 65536 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(declaredType, expr.name.text); } @@ -29473,19 +33187,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 187 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 187 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29504,9 +33218,9 @@ var ts; return declaredType; } break; - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; @@ -29515,28 +33229,28 @@ var ts; if (type.flags & 1 /* Any */) { return type; } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 32 /* ExclamationEqualsToken */ || operator === 34 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); + var valueType = getTypeOfExpression(value); if (valueType.flags & 6144 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var doubleEquals = operator === 31 /* EqualsEqualsToken */ || operator === 32 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 93 /* NullKeyword */ ? + value.kind === 94 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 33281 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29555,10 +33269,10 @@ var ts; } return type; } - if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 32 /* ExclamationEqualsToken */ || operator === 34 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288 /* Union */)) { + if (assumeTrue && !(type.flags & 65536 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. @@ -29581,7 +33295,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29599,7 +33314,7 @@ var ts; return type; } // Check that right operand is a function type with a prototype property - var rightType = checkExpression(expr.right); + var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -29619,10 +33334,10 @@ var ts; if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 65536 /* Interface */) { + if (getObjectFlags(rightType) & 2 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152 /* Anonymous */) { + else if (getObjectFlags(rightType) & 16 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -29630,18 +33345,18 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type, candidate, assumeTrue) { + function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return filterType(type, function (t) { return !isRelated(t, candidate); }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 524288 /* Union */) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); + if (type.flags & 65536 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); if (!(assignableType.flags & 8192 /* Never */)) { return assignableType; } @@ -29658,7 +33373,7 @@ var ts; getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } var signature = getResolvedSignature(callExpression); @@ -29674,7 +33389,7 @@ var ts; var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -29682,12 +33397,12 @@ var ts; } } else { - var invokedExpression = skipParenthesizedNodes(callExpression.expression); - if (invokedExpression.kind === 173 /* ElementAccessExpression */ || invokedExpression.kind === 172 /* PropertyAccessExpression */) { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 178 /* ElementAccessExpression */ || invokedExpression.kind === 177 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; - var possibleReference = skipParenthesizedNodes(accessExpression.expression); + var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -29700,18 +33415,18 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 69 /* Identifier */: - case 97 /* ThisKeyword */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: + case 177 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 185 /* PrefixUnaryExpression */: - if (expr.operator === 49 /* ExclamationToken */) { + case 190 /* PrefixUnaryExpression */: + if (expr.operator === 50 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -29724,12 +33439,12 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 69 /* Identifier */) { + if (location.kind === 70 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { - var type = checkExpression(location); + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -29742,19 +33457,13 @@ var ts; // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression) { - while (expression.kind === 178 /* ParenthesizedExpression */) { - expression = expression.expression; - } - return expression; - } function getControlFlowContainer(node) { while (true) { node = node.parent; if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 /* ModuleBlock */ || - node.kind === 256 /* SourceFile */ || - node.kind === 145 /* PropertyDeclaration */) { + node.kind === 231 /* ModuleBlock */ || + node.kind === 261 /* SourceFile */ || + node.kind === 147 /* PropertyDeclaration */) { return node; } } @@ -29783,10 +33492,10 @@ var ts; } } function markParameterAssignments(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144 /* Parameter */) { symbol.isAssigned = true; } } @@ -29795,8 +33504,14 @@ var ts; ts.forEachChild(node, markParameterAssignments); } } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects @@ -29805,17 +33520,18 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (languageVersion < 2 /* ES6 */) { - if (container.kind === 180 /* ArrowFunction */) { + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 185 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - if (node.flags & 262144 /* AwaitContext */) { + if (node.flags & 16384 /* AwaitContext */) { getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } + return getTypeOfSymbol(symbol); } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); @@ -29826,8 +33542,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (languageVersion === 2 /* ES6 */ - && declaration_1.kind === 221 /* ClassDeclaration */ + if (declaration_1.kind === 226 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration_1)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -29839,14 +33554,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration_1.kind === 192 /* ClassExpression */) { + else if (declaration_1.kind === 197 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); while (container !== undefined) { if (container.parent === declaration_1) { - if (container.kind === 145 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 147 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -29861,41 +33576,62 @@ var ts; checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); var declaration = localOrExportSymbol.valueDeclaration; + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } // We only narrow variables and parameters occurring in a non-assignment position. For all other // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) || assignmentKind === 1 /* Definite */ || !declaration) { return type; } // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 144 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === 184 /* FunctionExpression */ || + flowContainer.kind === 185 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node, threshold) { var current = node; @@ -29908,9 +33644,9 @@ var ts; return false; } function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 /* ES6 */ || + if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 252 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 256 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -29935,8 +33671,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 206 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 219 /* VariableDeclarationList */).parent === container && + if (container.kind === 211 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 224 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -29950,7 +33686,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { var current = node; // skip parenthesized nodes - while (current.parent.kind === 178 /* ParenthesizedExpression */) { + while (current.parent.kind === 183 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -29958,9 +33694,9 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 185 /* PrefixUnaryExpression */ || current.parent.kind === 186 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 190 /* PrefixUnaryExpression */ || current.parent.kind === 191 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 41 /* PlusPlusToken */ || expr.operator === 42 /* MinusMinusToken */; + isAssigned = expr.operator === 42 /* PlusPlusToken */ || expr.operator === 43 /* MinusMinusToken */; } if (!isAssigned) { return false; @@ -29979,7 +33715,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 145 /* PropertyDeclaration */ || container.kind === 148 /* Constructor */) { + if (container.kind === 147 /* PropertyDeclaration */ || container.kind === 150 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -29988,7 +33724,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30022,58 +33758,61 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 148 /* Constructor */) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + if (container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 180 /* ArrowFunction */) { + if (container.kind === 185 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); + needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 148 /* Constructor */: + case 150 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -30081,11 +33820,11 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 179 /* FunctionExpression */ && + if (container.kind === 184 /* FunctionExpression */ && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') @@ -30098,7 +33837,7 @@ var ts; return getInferredClassType(classSymbol); } } - var thisType = getThisTypeOfDeclaration(container); + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -30121,31 +33860,31 @@ var ts; return anyType; } function getTypeForThisExpressionFromJSDoc(node) { - var typeTag = ts.getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 269 /* JSDocFunctionType */) { - var jsDocFunctionType = typeTag.typeExpression.type; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 272 /* JSDocThisType */) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 274 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277 /* JSDocThisType */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 142 /* Parameter */) { + if (n.kind === 144 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 179 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 180 /* ArrowFunction */) { + while (container && container.kind === 185 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); @@ -30157,16 +33896,16 @@ var ts; // [super.foo()]() {} // } var current = node; - while (current && current !== container && current.kind !== 140 /* ComputedPropertyName */) { + while (current && current !== container && current.kind !== 142 /* ComputedPropertyName */) { current = current.parent; } - if (current && current.kind === 140 /* ComputedPropertyName */) { + if (current && current.kind === 142 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -30174,6 +33913,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } @@ -30237,7 +33979,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 147 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (container.kind === 149 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -30251,8 +33993,8 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 171 /* ObjectLiteralExpression */) { - if (languageVersion < 2 /* ES6 */) { + if (container.parent.kind === 176 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; } @@ -30271,7 +34013,7 @@ var ts; } return unknownType; } - if (container.kind === 148 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 150 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -30286,7 +34028,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 148 /* Constructor */; + return container.kind === 150 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -30294,32 +34036,35 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 171 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */) { if (ts.getModifierFlags(container) & 32 /* Static */) { - return container.kind === 147 /* MethodDeclaration */ || - container.kind === 146 /* MethodSignature */ || - container.kind === 149 /* GetAccessor */ || - container.kind === 150 /* SetAccessor */; + return container.kind === 149 /* MethodDeclaration */ || + container.kind === 148 /* MethodSignature */ || + container.kind === 151 /* GetAccessor */ || + container.kind === 152 /* SetAccessor */; } else { - return container.kind === 147 /* MethodDeclaration */ || - container.kind === 146 /* MethodSignature */ || - container.kind === 149 /* GetAccessor */ || - container.kind === 150 /* SetAccessor */ || - container.kind === 145 /* PropertyDeclaration */ || - container.kind === 144 /* PropertySignature */ || - container.kind === 148 /* Constructor */; + return container.kind === 149 /* MethodDeclaration */ || + container.kind === 148 /* MethodSignature */ || + container.kind === 151 /* GetAccessor */ || + container.kind === 152 /* SetAccessor */ || + container.kind === 147 /* PropertyDeclaration */ || + container.kind === 146 /* PropertySignature */ || + container.kind === 150 /* Constructor */; } } } return false; } } - function getContextualThisParameter(func) { - if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { + function getContextualThisParameterType(func) { + if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } return undefined; @@ -30379,7 +34124,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 142 /* Parameter */) { + if (declaration.kind === 144 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -30390,11 +34135,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_15 = declaration.propertyName || declaration.name; + var name_19 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_15)) { - var text = getTextOfPropertyName(name_15); + !ts.isBindingPattern(name_19)) { + var text = ts.getTextOfPropertyName(name_19); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -30431,7 +34176,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 142 /* Parameter */ && node.parent.initializer === node) { + if (node.parent.kind === 144 /* Parameter */ && node.parent.initializer === node) { return true; } node = node.parent; @@ -30442,8 +34187,8 @@ var ts; // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed if (functionDecl.type || - functionDecl.kind === 148 /* Constructor */ || - functionDecl.kind === 149 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 150 /* SetAccessor */))) { + functionDecl.kind === 150 /* Constructor */ || + functionDecl.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152 /* SetAccessor */))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature @@ -30465,7 +34210,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 176 /* TaggedTemplateExpression */) { + if (template.parent.kind === 181 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -30473,26 +34218,26 @@ var ts; function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; - if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + if (operator >= 57 /* FirstAssignment */ && operator <= 69 /* LastAssignment */) { // Don't do this for special property assignments to avoid circularity if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { return undefined; } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } - else if (operator === 52 /* BarBarToken */) { + else if (operator === 53 /* BarBarToken */) { // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand. var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } - else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + else if (operator === 52 /* AmpersandAmpersandToken */ || operator === 25 /* CommaToken */) { if (node === binaryExpression.right) { return getContextualType(binaryExpression); } @@ -30503,14 +34248,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 65536 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30528,7 +34273,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -30537,7 +34282,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -30580,7 +34325,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1 /* Number */) - || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); + || (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); } return undefined; } @@ -30593,13 +34338,13 @@ var ts; var kind = attribute.kind; var jsxElement = attribute.parent; var attrsType = getJsxElementAttributesType(jsxElement); - if (attribute.kind === 246 /* JsxAttribute */) { + if (attribute.kind === 250 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - else if (attribute.kind === 247 /* JsxSpreadAttribute */) { + else if (attribute.kind === 251 /* JsxSpreadAttribute */) { return attrsType; } ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); @@ -30637,58 +34382,73 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 218 /* VariableDeclaration */: - case 142 /* Parameter */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 169 /* BindingElement */: + case 223 /* VariableDeclaration */: + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 174 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 180 /* ArrowFunction */: - case 211 /* ReturnStatement */: + case 185 /* ArrowFunction */: + case 216 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 197 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 189 /* TemplateExpression */); + case 202 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 194 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return getContextualType(parent); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return getContextualType(parent); - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); } return undefined; } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. - function getNonGenericSignature(type) { + function getNonGenericSignature(type, node) { var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */; + return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -30707,19 +34467,19 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 524288 /* Union */)) { - return getNonGenericSignature(type); + if (!(type.flags & 65536 /* Union */)) { + return getNonGenericSignature(type, node); } var signatureList; var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; - var signature = getNonGenericSignature(current); + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; + var signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -30763,19 +34523,13 @@ var ts; function isInferentialContext(mapper) { return mapper && mapper.context; } - function checkSpreadElementExpression(node, contextualMapper) { - // It is usually not safe to call checkExpressionCached if we can be contextually typing. - // You can tell that we are contextually typing because of the contextualMapper parameter. - // While it is true that a spread element can have a contextual type, it does not do anything - // with this type. It is neither affected by it, nor does it propagate it to its operand. - // So the fact that contextualMapper is passed is not important, because the operand of a spread - // element is not contextually typed. - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node, contextualMapper) { + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 169 /* BindingElement */ && !!node.initializer) || - (node.kind === 187 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 174 /* BindingElement */ && !!node.initializer) || + (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -30784,7 +34538,7 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 191 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 196 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -30799,7 +34553,7 @@ var ts; // if there is no index type / iterated type. var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); + (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -30808,7 +34562,7 @@ var ts; var type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 191 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 196 /* SpreadElement */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -30823,7 +34577,7 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 168 /* ArrayBindingPattern */ || pattern.kind === 170 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 173 /* ArrayBindingPattern */ || pattern.kind === 175 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -30831,7 +34585,7 @@ var ts; elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 193 /* OmittedExpression */) { + if (patternElement.kind !== 198 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -30848,7 +34602,7 @@ var ts; strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { - return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 142 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, @@ -30891,7 +34645,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -30900,10 +34654,10 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(node, properties, kind) { + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 /* String */ || isNumericName(node.properties[i].name)) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -30916,28 +34670,31 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createMap(); var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 167 /* ObjectBindingPattern */ || contextualType.pattern.kind === 171 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 172 /* ObjectBindingPattern */ || contextualType.pattern.kind === 176 /* ObjectLiteralExpression */); var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var memberDecl = _a[_i]; + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; var member = memberDecl.symbol; - if (memberDecl.kind === 253 /* PropertyAssignment */ || - memberDecl.kind === 254 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 257 /* PropertyAssignment */ || + memberDecl.kind === 258 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 253 /* PropertyAssignment */) { + if (memberDecl.kind === 257 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 147 /* MethodDeclaration */) { + else if (memberDecl.kind === 149 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 254 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 258 /* ShorthandPropertyAssignment */); type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -30945,8 +34702,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 253 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 254 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 257 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 258 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } @@ -30954,14 +34711,14 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912 /* Optional */; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -30974,13 +34731,34 @@ var ts; prop.target = member; member = prop; } + else if (memberDecl.kind === 259 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + propertiesArray = []; + propertiesTable = ts.createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, /*isFromObjectLiteral*/ false); + offset = i + 1; + continue; + } else { // TypeScript 1.0 spec (April 2014) // A get accessor declaration is processed in the same manner as // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 149 /* GetAccessor */ || memberDecl.kind === 150 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 151 /* GetAccessor */ || memberDecl.kind === 152 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } if (ts.hasDynamicName(memberDecl)) { @@ -30999,8 +34777,8 @@ var ts; // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { - for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { - var prop = _c[_b]; + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; if (!propertiesTable[prop.name]) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); @@ -31010,15 +34788,41 @@ var ts; } } } - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); - if (inDestructuringPattern) { - result.pattern = node; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + } + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - return result; + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; + result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.objectFlags |= 128 /* ObjectLiteral */; + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144 /* Nullable */)) { + propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */) || + type.flags & 32768 /* Object */ && !isGenericMappedType(type) || + type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); @@ -31038,13 +34842,13 @@ var ts; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: checkJsxExpression(child); break; - case 241 /* JsxElement */: + case 246 /* JsxElement */: checkJsxElement(child); break; - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -31063,7 +34867,7 @@ var ts; */ function isJsxIntrinsicIdentifier(tagName) { // TODO (yuisu): comment - if (tagName.kind === 172 /* PropertyAccessExpression */ || tagName.kind === 97 /* ThisKeyword */) { + if (tagName.kind === 177 /* PropertyAccessExpression */ || tagName.kind === 98 /* ThisKeyword */) { return false; } else { @@ -31081,7 +34885,7 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); + var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); if (attributeType) { correspondingPropType = attributeType; } @@ -31109,6 +34913,9 @@ var ts; return exprType; } function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + if (compilerOptions.jsx === 2 /* React */) { + checkExternalEmitHelpers(node, 2 /* Assign */); + } var type = checkExpression(node.expression); var props = getPropertiesOfType(type); for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { @@ -31174,7 +34981,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); + ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -31190,7 +34997,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -31232,9 +35039,9 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288 /* Union */) { + if (elemType.flags & 65536 /* Union */) { var types = elemType.types; - return getUnionType(types.map(function (type) { + return getUnionType(ts.map(types, function (type) { return getResolvedJsxType(node, type, elemClassType); }), /*subtypeReduction*/ true); } @@ -31306,7 +35113,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 524288 /* Union */) { + else if (attributesType.flags & 65536 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -31395,13 +35202,19 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there - // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactNamespace = getJsxNamespace(); var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = true; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 8388608 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = ts.createMap(); @@ -31410,11 +35223,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 246 /* JsxAttribute */) { + if (node.attributes[i].kind === 250 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 247 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 251 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -31444,7 +35257,7 @@ var ts; // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 145 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 147 /* PropertyDeclaration */; } function getDeclarationModifierFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; @@ -31463,10 +35276,10 @@ var ts; function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); - var errorNode = node.kind === 172 /* PropertyAccessExpression */ || node.kind === 218 /* VariableDeclaration */ ? + var errorNode = node.kind === 177 /* PropertyAccessExpression */ || node.kind === 223 /* VariableDeclaration */ ? node.name : node.right; - if (left.kind === 95 /* SuperKeyword */) { + if (left.kind === 96 /* SuperKeyword */) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -31474,7 +35287,7 @@ var ts; // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 147 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES2015 */ && getDeclarationKindFromSymbol(prop) !== 149 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -31505,7 +35318,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 95 /* SuperKeyword */) { + if (left.kind === 96 /* SuperKeyword */) { return true; } // Get the enclosing class that has the declaring class as its base type @@ -31523,12 +35336,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -31554,6 +35367,33 @@ var ts; function checkQualifiedName(node) { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode, containingType) { + var errorInfo; + if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var subtype = _a[_i]; + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + function markPropertyAsReferenced(prop) { + if (prop && + noUnusedIdentifiers && + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { + if (prop.flags & 16777216 /* Instantiated */) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } + } + } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -31567,51 +35407,36 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (prop.flags & 16777216 /* Instantiated */) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & 32 /* Class */) { checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || + if (node.kind !== 177 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); - function reportNonexistentProperty(propNode, containingType) { - var errorInfo; - if (containingType.flags & 524288 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var subtype = _a[_i]; - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + var flowType = getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 172 /* PropertyAccessExpression */ + var left = node.kind === 177 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -31628,13 +35453,13 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 219 /* VariableDeclarationList */) { + if (initializer.kind === 224 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 69 /* Identifier */) { + else if (initializer.kind === 70 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; @@ -31650,17 +35475,17 @@ var ts; * that references a for-in variable for an object with numeric property names. */ function isForInVariableForNumericPropertyNames(expr) { - var e = skipParenthesizedNodes(expr); - if (e.kind === 69 /* Identifier */) { + var e = ts.skipParentheses(expr); + if (e.kind === 70 /* Identifier */) { var symbol = getResolvedSymbol(e); if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 207 /* ForInStatement */ && + if (node.kind === 212 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression(node.expression))) { + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { return true; } child = node; @@ -31671,10 +35496,11 @@ var ts; return false; } function checkIndexedAccess(node) { - // Grammar checking - if (!node.argumentExpression) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 175 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 180 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -31684,101 +35510,18 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } + return unknownType; } - // Obtain base constraint such that we can bail out if the constraint is an unknown type - var objectType = getApparentType(checkNonNullExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - var isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== 9 /* StringLiteral */)) { - error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - // TypeScript 1.0 spec (April 2014): 4.10 Property Access - // - If IndexExpr is a string literal or a numeric literal and ObjExpr's apparent type has a property with the name - // given by that literal(converted to its string representation in the case of a numeric literal), the property access is of the type of that property. - // - Otherwise, if ObjExpr's apparent type has a numeric index signature and IndexExpr is of type Any, the Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if ObjExpr's apparent type has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. - // See if we can index as a property. - if (node.argumentExpression) { - var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_16 !== undefined) { - var prop = getPropertyOfType(objectType, name_16); - 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_16, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - // Check for compatible indexer types. - var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { - // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - // Try to use string indexing. - var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, 1 /* Number */) ? - ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - return anyType; - } - // REVIEW: Users should know the type that was actually used. - error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - return unknownType; + return getIndexedAccessType(objectType, indexType, node); } - /** - * If indexArgumentExpression is a string literal or number literal, returns its text. - * If indexArgumentExpression is a constant value, returns its string value. - * If indexArgumentExpression is a well known symbol, returns the property name corresponding - * to this symbol, as long as it is a proper symbol reference. - * Otherwise, returns undefined. - */ - function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { - if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { - return indexArgumentExpression.text; - } - if (indexArgumentExpression.kind === 173 /* ElementAccessExpression */ || indexArgumentExpression.kind === 172 /* PropertyAccessExpression */) { - var value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - var rightHandSideName = indexArgumentExpression.name.text; - return ts.getPropertyNameForKnownSymbolName(rightHandSideName); - } - return undefined; - } - /** - * A proper symbol reference requires the following: - * 1. The property access denotes a property that exists - * 2. The expression is of the form Symbol. - * 3. The property access is of the primitive type symbol. - * 4. Symbol in this context resolves to the global Symbol object - */ function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { // There is already an error, so no need to report one. @@ -31815,10 +35558,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 143 /* Decorator */) { + else if (node.kind !== 145 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -31848,13 +35591,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_8 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_8 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_8; index = cutoffIndex; } } @@ -31862,7 +35605,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_8; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -31884,7 +35627,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 191 /* SpreadElementExpression */) { + if (arg && arg.kind === 196 /* SpreadElement */) { return i; } } @@ -31897,13 +35640,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 189 /* TemplateExpression */) { + if (tagExpression.template.kind === 194 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -31916,11 +35659,11 @@ var ts; // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 11 /* NoSubstitutionTemplateLiteral */); + ts.Debug.assert(templateLiteral.kind === 12 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 143 /* Decorator */) { + else if (node.kind === 145 /* Decorator */) { isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); @@ -31929,7 +35672,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 175 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 180 /* NewExpression */); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -31960,7 +35703,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 32768 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -31974,7 +35717,7 @@ var ts; var context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -32005,7 +35748,7 @@ var ts; if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. @@ -32013,9 +35756,9 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 193 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { @@ -32024,7 +35767,7 @@ var ts; var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this @@ -32038,7 +35781,7 @@ var ts; if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -32070,7 +35813,7 @@ var ts; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 175 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 180 /* 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. @@ -32087,10 +35830,10 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 193 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i, arg); + var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { @@ -32109,12 +35852,12 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 174 /* CallExpression */) { + if (node.kind === 179 /* CallExpression */) { var callee = node.expression; - if (callee.kind === 172 /* PropertyAccessExpression */) { + if (callee.kind === 177 /* PropertyAccessExpression */) { return callee.expression; } - else if (callee.kind === 173 /* ElementAccessExpression */) { + else if (callee.kind === 178 /* ElementAccessExpression */) { return callee.expression; } } @@ -32130,16 +35873,16 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 176 /* TaggedTemplateExpression */) { + if (node.kind === 181 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 189 /* TemplateExpression */) { + if (template.kind === 194 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 143 /* Decorator */) { + else if (node.kind === 145 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -32164,19 +35907,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { switch (node.parent.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -32186,7 +35929,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 142 /* Parameter */: + case 144 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -32210,25 +35953,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -32255,32 +35998,32 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { node = node.parent; - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; switch (element.name.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { return nameType; @@ -32306,21 +36049,21 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 226 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 142 /* Parameter */) { + if (node.kind === 144 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 145 /* PropertyDeclaration */) { + if (node.kind === 147 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 147 /* MethodDeclaration */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 149 /* MethodDeclaration */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -32348,14 +36091,14 @@ var ts; /** * Gets the effective argument type for an argument in a call expression. */ - function getEffectiveArgumentType(node, argIndex, arg) { + function getEffectiveArgumentType(node, argIndex) { // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -32367,8 +36110,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 143 /* Decorator */ || - (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */)) { + if (node.kind === 145 /* Decorator */ || + (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -32377,11 +36120,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 143 /* Decorator */) { + if (node.kind === 145 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 176 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -32390,13 +36133,13 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 176 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 143 /* Decorator */; + var isTaggedTemplate = node.kind === 181 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 145 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 95 /* SuperKeyword */) { + if (node.expression.kind !== 96 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -32462,7 +36205,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 174 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -32501,7 +36244,7 @@ var ts; else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -32528,7 +36271,7 @@ var ts; var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -32560,7 +36303,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -32608,7 +36351,7 @@ var ts; } } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (node.expression.kind === 96 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated @@ -32676,7 +36419,7 @@ var ts; if (!numCallSignatures && !numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have // no common signatures. - if (funcType.flags & 524288 /* Union */) { + if (funcType.flags & 65536 /* Union */) { return false; } return isTypeAssignableTo(funcType, globalFunctionType); @@ -32769,12 +36512,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 /* Protected */ && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8 /* Private */) { @@ -32810,16 +36554,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 142 /* Parameter */: + case 144 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -32849,13 +36593,13 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 174 /* CallExpression */: + case 179 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 143 /* Decorator */: + case 145 /* Decorator */: return resolveDecorator(node, candidatesOutArray); } ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); @@ -32901,22 +36645,22 @@ var ts; // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 95 /* SuperKeyword */) { + if (node.expression.kind === 96 /* SuperKeyword */) { return voidType; } - if (node.kind === 175 /* NewExpression */) { + if (node.kind === 180 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 148 /* Constructor */ && - declaration.kind !== 152 /* ConstructSignature */ && - declaration.kind !== 157 /* ConstructorType */ && + declaration.kind !== 150 /* Constructor */ && + declaration.kind !== 154 /* ConstructSignature */ && + declaration.kind !== 159 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // 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 // 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 */ ? + var funcSymbol = node.expression.kind === 70 /* Identifier */ ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { @@ -32929,11 +36673,37 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + // Make sure require is not a local function + var resolvedRequire = resolveName(node.expression, node.expression.text, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require + return true; + } + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & 8388608 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 225 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 223 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return ts.isInAmbientContext(decl); + } + return false; + } function checkTaggedTemplateExpression(node) { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -32969,21 +36739,36 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!parameter.valueDeclaration.type) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push @@ -32993,7 +36778,7 @@ var ts; for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 69 /* Identifier */) { + if (element.name.kind === 70 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } assignBindingElementTypes(element); @@ -33007,8 +36792,8 @@ var ts; links.type = instantiateType(contextualType, mapper); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 167 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 168 /* ArrayBindingPattern */)) { + (parameter.valueDeclaration.name.kind === 172 /* ObjectBindingPattern */ || + parameter.valueDeclaration.name.kind === 173 /* ArrayBindingPattern */)) { links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); } assignBindingElementTypes(parameter.valueDeclaration); @@ -33043,7 +36828,7 @@ var ts; // T in the second overload so that we do not infer Base as a candidate for T // (inferring Base would make type argument inference inconsistent between the two // overloads). - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } function getReturnTypeFromJSDocComment(func) { @@ -33066,7 +36851,7 @@ var ts; 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); + error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } return promiseType; @@ -33078,7 +36863,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 199 /* Block */) { + if (func.body.kind !== 204 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -33121,7 +36906,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33151,7 +36938,7 @@ var ts; if (!node.possiblyExhaustive) { return false; } - var type = checkExpression(node.expression); + var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -33159,14 +36946,14 @@ var ts; if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + if (lastStatement && lastStatement.kind === 218 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { return false; } return true; @@ -33199,7 +36986,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */)) { + func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -33228,7 +37015,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 */ || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; @@ -33261,10 +37048,10 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 179 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 184 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards @@ -33305,14 +37092,14 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 149 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); if (!node.asteriskToken) { @@ -33328,7 +37115,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 199 /* Block */) { + if (node.body.kind === 204 /* Block */) { checkSourceElement(node.body); } else { @@ -33375,11 +37162,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) && - expr.expression.kind === 97 /* ThisKeyword */) { + (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) && + expr.expression.kind === 98 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 148 /* Constructor */)) + if (!(func && func.kind === 150 /* Constructor */)) return true; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, @@ -33391,50 +37178,25 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) { - var node = skipParenthesizedNodes(expr.expression); - if (node.kind === 69 /* Identifier */) { + if (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 70 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 8388608 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 232 /* NamespaceImport */; + return declaration && declaration.kind === 237 /* NamespaceImport */; } } } return false; } - function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. - var node = skipParenthesizedNodes(expr); - if (node.kind !== 69 /* Identifier */ && node.kind !== 172 /* PropertyAccessExpression */ && node.kind !== 173 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr); + if (node.kind !== 70 /* Identifier */ && node.kind !== 177 /* PropertyAccessExpression */ && node.kind !== 178 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } - // Because we get the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - var links = getNodeLinks(node); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - // Only variables (and not functions, classes, namespaces, enum objects, or enum members) - // are considered references when referenced using a simple identifier. - if (node.kind === 69 /* Identifier */ && !(symbol.flags & 3 /* Variable */)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === 173 /* ElementAccessExpression */) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } function checkDeleteExpression(node) { @@ -33452,7 +37214,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 262144 /* AwaitContext */)) { + if (!(node.flags & 16384 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -33467,28 +37229,28 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + if (node.operator === 37 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text)); } switch (node.operator) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 49 /* ExclamationToken */: + case 50 /* ExclamationToken */: var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : booleanType; - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -33502,7 +37264,7 @@ var ts; var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -33512,10 +37274,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33530,20 +37292,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_16 = types; _a < types_16.length; _a++) { - var t = types_16[_a]; + for (var _a = 0, types_17 = types; _a < types_17.length; _a++) { + var t = types_17[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -33552,7 +37314,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -33583,39 +37345,40 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var p = properties_4[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { - if (property.kind === 253 /* PropertyAssignment */ || property.kind === 254 /* ShorthandPropertyAssignment */) { - var name_17 = property.name; - if (name_17.kind === 140 /* ComputedPropertyName */) { - checkComputedPropertyName(name_17); + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 257 /* PropertyAssignment */ || property.kind === 258 /* ShorthandPropertyAssignment */) { + var name_20 = property.name; + if (name_20.kind === 142 /* ComputedPropertyName */) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_17)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_17); + var text = ts.getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 254 /* ShorthandPropertyAssignment */) { + if (property.kind === 258 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -33624,9 +37387,22 @@ var ts; } } else { - error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } + else if (property.kind === 259 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, ts.Diagnostics.Property_assignment_expected); } @@ -33645,8 +37421,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 193 /* OmittedExpression */) { - if (element.kind !== 191 /* SpreadElementExpression */) { + if (element.kind !== 198 /* OmittedExpression */) { + if (element.kind !== 196 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -33670,11 +37446,11 @@ var ts; } else { if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { var restExpression = element.expression; - if (restExpression.kind === 187 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 192 /* BinaryExpression */ && restExpression.operatorToken.kind === 57 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -33687,7 +37463,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 254 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 258 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -33703,21 +37479,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 187 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 192 /* BinaryExpression */ && target.operatorToken.kind === 57 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 171 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + if (target.kind === 176 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 170 /* ArrayLiteralExpression */) { + if (target.kind === 175 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + var error = target.parent.kind === 259 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -33733,52 +37512,52 @@ var ts; function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 176 /* TaggedTemplateExpression */: - case 189 /* TemplateExpression */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 11 /* RegularExpressionLiteral */: + case 181 /* TaggedTemplateExpression */: + case 194 /* TemplateExpression */: + case 12 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 179 /* FunctionExpression */: - case 192 /* ClassExpression */: - case 180 /* ArrowFunction */: - case 170 /* ArrayLiteralExpression */: - case 171 /* ObjectLiteralExpression */: - case 182 /* TypeOfExpression */: - case 196 /* NonNullExpression */: - case 242 /* JsxSelfClosingElement */: - case 241 /* JsxElement */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: + case 94 /* NullKeyword */: + case 137 /* UndefinedKeyword */: + case 184 /* FunctionExpression */: + case 197 /* ClassExpression */: + case 185 /* ArrowFunction */: + case 175 /* ArrayLiteralExpression */: + case 176 /* ObjectLiteralExpression */: + case 187 /* TypeOfExpression */: + case 201 /* NonNullExpression */: + case 247 /* JsxSelfClosingElement */: + case 246 /* JsxElement */: return true; - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { - case 49 /* ExclamationToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: + case 50 /* ExclamationToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: return true; } return false; // Some forms listed here for clarity - case 183 /* VoidExpression */: // Explicit opt-out - case 177 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 195 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 188 /* VoidExpression */: // Explicit opt-out + case 182 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 200 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -33798,34 +37577,34 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 171 /* ObjectLiteralExpression */ || left.kind === 170 /* ArrayLiteralExpression */)) { + if (operator === 57 /* EqualsToken */ && (left.kind === 176 /* ObjectLiteralExpression */ || left.kind === 175 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); var rightType = checkExpression(right, contextualMapper); switch (operator) { - case 37 /* AsteriskToken */: - case 38 /* AsteriskAsteriskToken */: - case 59 /* AsteriskEqualsToken */: - case 60 /* AsteriskAsteriskEqualsToken */: - case 39 /* SlashToken */: - case 61 /* SlashEqualsToken */: - case 40 /* PercentToken */: - case 62 /* PercentEqualsToken */: - case 36 /* MinusToken */: - case 58 /* MinusEqualsToken */: - case 43 /* LessThanLessThanToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* BarToken */: - case 67 /* BarEqualsToken */: - case 48 /* CaretToken */: - case 68 /* CaretEqualsToken */: - case 46 /* AmpersandToken */: - case 66 /* AmpersandEqualsToken */: + case 38 /* AsteriskToken */: + case 39 /* AsteriskAsteriskToken */: + case 60 /* AsteriskEqualsToken */: + case 61 /* AsteriskAsteriskEqualsToken */: + case 40 /* SlashToken */: + case 62 /* SlashEqualsToken */: + case 41 /* PercentToken */: + case 63 /* PercentEqualsToken */: + case 37 /* MinusToken */: + case 59 /* MinusEqualsToken */: + case 44 /* LessThanLessThanToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 48 /* BarToken */: + case 68 /* BarEqualsToken */: + case 49 /* CaretToken */: + case 69 /* CaretEqualsToken */: + case 47 /* AmpersandToken */: + case 67 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -33858,8 +37637,8 @@ var ts; } } return numberType; - case 35 /* PlusToken */: - case 57 /* PlusEqualsToken */: + case 36 /* PlusToken */: + case 58 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } @@ -33880,7 +37659,7 @@ var ts; resultType = numberType; } else { - if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { + if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -33898,24 +37677,26 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 57 /* PlusEqualsToken */) { + if (operator === 58 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } } return booleanType; - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -33926,22 +37707,22 @@ var ts; reportOperatorError(); } return booleanType; - case 91 /* InstanceOfKeyword */: + case 92 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 90 /* InKeyword */: + case 91 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 51 /* AmpersandAmpersandToken */: + case 52 /* AmpersandAmpersandToken */: return getTypeFacts(leftType) & 1048576 /* Truthy */ ? includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; - case 52 /* BarBarToken */: + case 53 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : leftType; - case 56 /* EqualsToken */: + case 57 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 24 /* CommaToken */: + case 25 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } @@ -33960,30 +37741,28 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 47 /* BarToken */: - case 67 /* BarEqualsToken */: - return 52 /* BarBarToken */; - case 48 /* CaretToken */: - case 68 /* CaretEqualsToken */: - return 33 /* ExclamationEqualsEqualsToken */; - case 46 /* AmpersandToken */: - case 66 /* AmpersandEqualsToken */: - return 51 /* AmpersandAmpersandToken */; + case 48 /* BarToken */: + case 68 /* BarEqualsToken */: + return 53 /* BarBarToken */; + case 49 /* CaretToken */: + case 69 /* CaretEqualsToken */: + return 34 /* ExclamationEqualsEqualsToken */; + case 47 /* AmpersandToken */: + case 67 /* AmpersandEqualsToken */: + return 52 /* AmpersandAmpersandToken */; default: return undefined; } } function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + if (produceDiagnostics && operator >= 57 /* FirstAssignment */ && operator <= 69 /* LastAssignment */) { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - // Use default messages - if (ok) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); } @@ -34011,7 +37790,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 65536 /* YieldContext */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -34061,9 +37840,9 @@ var ts; return getFreshTypeOfLiteralType(getLiteralTypeForText(32 /* StringLiteral */, node.text)); case 8 /* NumericLiteral */: return getFreshTypeOfLiteralType(getLiteralTypeForText(64 /* NumberLiteral */, node.text)); - case 99 /* TrueKeyword */: + case 100 /* TrueKeyword */: return trueType; - case 84 /* FalseKeyword */: + case 85 /* FalseKeyword */: return falseType; } } @@ -34099,19 +37878,19 @@ var ts; return links.resolvedType; } function isTypeAssertion(node) { - node = skipParenthesizedNodes(node); - return node.kind === 177 /* TypeAssertionExpression */ || node.kind === 195 /* AsExpression */; + node = ts.skipParentheses(node); + return node.kind === 182 /* TypeAssertionExpression */ || node.kind === 200 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var type = checkExpressionCached(declaration.initializer); return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672 /* TypeVariable */) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); // If the type parameter is constrained to the base primitive type we're checking for, // consider this a literal context. For example, given a type parameter 'T extends string', // this causes us to infer string literal types for T. @@ -34120,7 +37899,7 @@ var ts; } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, 480 /* Literal */); + return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */)); } return false; } @@ -34132,7 +37911,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, contextualMapper); @@ -34143,7 +37922,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -34164,6 +37943,23 @@ var ts; } return type; } + // Returns the type of an expression. Unlike checkExpression, this function is simply concerned + // with computing the type and may not fully check all contained sub-expressions for errors. + function getTypeOfExpression(node) { + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (node.kind === 179 /* CallExpression */ && node.expression.kind !== 96 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -34173,7 +37969,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, contextualMapper) { var type; - if (node.kind === 139 /* QualifiedName */) { + if (node.kind === 141 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -34185,9 +37981,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -34196,79 +37992,79 @@ var ts; } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return checkIdentifier(node); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: return checkThisExpression(node); - case 95 /* SuperKeyword */: + case 96 /* SuperKeyword */: return checkSuperExpression(node); - case 93 /* NullKeyword */: + case 94 /* NullKeyword */: return nullWideningType; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return checkLiteralExpression(node); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: return checkTemplateExpression(node); - case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return stringType; - case 10 /* RegularExpressionLiteral */: + case 11 /* RegularExpressionLiteral */: return globalRegExpType; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: return checkCallExpression(node); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return checkClassExpression(node); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: return checkAssertion(node); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return checkNonNullAssertion(node); - case 181 /* DeleteExpression */: + case 186 /* DeleteExpression */: return checkDeleteExpression(node); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return checkVoidExpression(node); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return checkAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 191 /* SpreadElementExpression */: - return checkSpreadElementExpression(node, contextualMapper); - case 193 /* OmittedExpression */: + case 196 /* SpreadElement */: + return checkSpreadExpression(node, contextualMapper); + case 198 /* OmittedExpression */: return undefinedWideningType; - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return checkYieldExpression(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return checkJsxExpression(node); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return checkJsxElement(node); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -34296,7 +38092,7 @@ var ts; var func = ts.getContainingFunction(node); if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 148 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 150 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -34307,7 +38103,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); } - if (func.kind === 148 /* Constructor */ || func.kind === 152 /* ConstructSignature */ || func.kind === 157 /* ConstructorType */) { + if (func.kind === 150 /* Constructor */ || func.kind === 154 /* ConstructSignature */ || func.kind === 159 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -34321,15 +38117,15 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 147 /* MethodDeclaration */ || - node.kind === 220 /* FunctionDeclaration */ || - node.kind === 179 /* FunctionExpression */; + return node.kind === 149 /* MethodDeclaration */ || + node.kind === 225 /* FunctionDeclaration */ || + node.kind === 184 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 69 /* Identifier */ && + if (param.name.kind === 70 /* Identifier */ && param.name.text === parameter.text) { return i; } @@ -34366,9 +38162,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_18 = _a[_i].name; - if (ts.isBindingPattern(name_18) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -34381,16 +38177,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 180 /* ArrowFunction */: - case 151 /* CallSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 156 /* FunctionType */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + case 185 /* ArrowFunction */: + case 153 /* CallSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 158 /* FunctionType */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + var parent_9 = node.parent; + if (node === parent_9.type) { + return parent_9; } } } @@ -34400,15 +38196,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_19 = element.name; - if (name_19.kind === 69 /* Identifier */ && - name_19.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 70 /* Identifier */ && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_19.kind === 168 /* ArrayBindingPattern */ || - name_19.kind === 167 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 173 /* ArrayBindingPattern */ || + name_22.kind === 172 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -34416,14 +38212,20 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 156 /* FunctionType */ || node.kind === 220 /* FunctionDeclaration */ || node.kind === 157 /* ConstructorType */ || - node.kind === 151 /* CallSignature */ || node.kind === 148 /* Constructor */ || - node.kind === 152 /* ConstructSignature */) { + else if (node.kind === 158 /* FunctionType */ || node.kind === 225 /* FunctionDeclaration */ || node.kind === 159 /* ConstructorType */ || + node.kind === 153 /* CallSignature */ || node.kind === 150 /* Constructor */ || + node.kind === 154 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } + if (ts.isAsyncFunctionLike(node) && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { @@ -34433,16 +38235,16 @@ var ts; checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } if (node.type) { - if (languageVersion >= 2 /* ES6 */ && isSyntacticallyValidGenerator(node)) { + if (languageVersion >= 2 /* ES2015 */ && isSyntacticallyValidGenerator(node)) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34479,7 +38281,7 @@ var ts; var staticNames = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { + if (member.kind === 150 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { @@ -34488,18 +38290,18 @@ var ts; } } else { - var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 113 /* StaticKeyword */; }); + var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114 /* StaticKeyword */; }); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: addName(names, member.name, memberName, 1 /* Getter */); break; - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: addName(names, member.name, memberName, 2 /* Setter */); break; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: addName(names, member.name, memberName, 3 /* Property */); break; } @@ -34525,12 +38327,12 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind == 144 /* PropertySignature */) { + if (member.kind == 146 /* PropertySignature */) { var memberName = void 0; switch (member.name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - case 69 /* Identifier */: + case 70 /* Identifier */: memberName = member.name.text; break; default: @@ -34547,7 +38349,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 222 /* InterfaceDeclaration */) { + if (node.kind === 227 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -34567,7 +38369,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -34575,7 +38377,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -34628,7 +38430,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34640,15 +38442,15 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function markThisReferencesAsErrors(n) { - if (n.kind === 97 /* ThisKeyword */) { + if (n.kind === 98 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 179 /* FunctionExpression */ && n.kind !== 220 /* FunctionDeclaration */) { + else if (n.kind !== 184 /* FunctionExpression */ && n.kind !== 225 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 145 /* PropertyDeclaration */ && + return n.kind === 147 /* PropertyDeclaration */ && !(ts.getModifierFlags(n) & 32 /* Static */) && !!n.initializer; } @@ -34657,6 +38459,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34675,9 +38478,9 @@ var ts; if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -34701,7 +38504,7 @@ var ts; checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 149 /* GetAccessor */) { + if (node.kind === 151 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -34711,13 +38514,13 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 149 /* GetAccessor */ ? 150 /* SetAccessor */ : 149 /* GetAccessor */; + var otherKind = node.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { @@ -34733,11 +38536,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149 /* GetAccessor */) { + if (node.kind === 151 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } - if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { + if (node.parent.kind !== 176 /* ObjectLiteralExpression */) { checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); } @@ -34767,7 +38570,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -34820,6 +38623,17 @@ var ts; function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node) { + getTypeFromIndexedAccessTypeNode(node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } function isPrivateWithinAmbient(node) { return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); } @@ -34827,9 +38641,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 222 /* InterfaceDeclaration */ && - n.parent.kind !== 221 /* ClassDeclaration */ && - n.parent.kind !== 192 /* ClassExpression */ && + if (n.parent.kind !== 227 /* InterfaceDeclaration */ && + n.parent.kind !== 226 /* ClassDeclaration */ && + n.parent.kind !== 197 /* ClassExpression */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported @@ -34917,7 +38731,7 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */) && + var reportError = (node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */) && (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -34956,7 +38770,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 222 /* InterfaceDeclaration */ || node.parent.kind === 159 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 227 /* InterfaceDeclaration */ || node.parent.kind === 161 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -34967,7 +38781,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 220 /* FunctionDeclaration */ || node.kind === 147 /* MethodDeclaration */ || node.kind === 146 /* MethodSignature */ || node.kind === 148 /* Constructor */) { + if (node.kind === 225 /* FunctionDeclaration */ || node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */ || node.kind === 150 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -35089,20 +38903,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 229 /* ImportEqualsDeclaration */: - var result_2 = 0; + case 234 /* ImportEqualsDeclaration */: + var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; default: return 1048576 /* ExportValue */; } @@ -35139,7 +38953,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072 /* Reference */) { + if (getObjectFlags(promise) & 4 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -35157,7 +38971,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -35183,7 +38997,7 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -35262,56 +39076,19 @@ var ts; } } /** - * Checks that the return type provided is an instantiation of the global Promise type - * and returns the awaited type of the return type. + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. * - * @param returnType The return type of a FunctionLikeDeclaration - * @param location The node on which to report the error. + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check */ - function checkCorrectPromiseType(returnType, location, diagnostic, typeName) { - if (returnType === unknownType) { - // The return type already had some other error, so we ignore and return - // the unknown type. - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - // Either we couldn't resolve the global promise type, which would have already - // reported an error, or we could resolve it and the return type is a valid type - // reference to the global type. In either case, we return the awaited type for - // the return type. - return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - // The promise type was not a valid type reference to the global promise type, so we - // report an error and return the unknown type. - error(location, diagnostic, typeName); - return unknownType; - } - /** - * Checks the return type of an async function to ensure it is a compatible - * Promise implementation. - * @param node The signature to check - * @param returnType The return type for the function - * @remarks - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. - */ function checkAsyncFunctionReturnType(node) { - if (languageVersion >= 2 /* ES6 */) { - var returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - // If we couldn't resolve the global PromiseConstructorLike type we cannot verify - // compatibility with __awaiter. - return unknownType; - } // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -35336,39 +39113,56 @@ var ts; // then(...): Promise; // } // - // When we get the type of the `Promise` symbol here, we get the type of the static - // side of the `Promise` class, which would be `{ new (...): Promise }`. - var promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - // If we are compiling with isolatedModules, we may not be able to resolve the - // type as a value. As such, we will just return unknownType; - return unknownType; + var returnType = getTypeFromTypeNode(node.type); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } - var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - // try to fall back to global promise type. - var typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } - // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. - checkReturnTypeAnnotationAsExpression(node); - // Validate the promise constructor type. - var promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } - // Verify there is no local declaration that could collide with the promise constructor. - var promiseName = ts.getEntityNameFromTypeNode(node.type); - var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); - return unknownType; + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(node.type); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.text, 107455 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } } // Get and return the awaited type of the return type. - return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } /** Check a decorator */ function checkDecorator(node) { @@ -35381,22 +39175,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 142 /* Parameter */: + case 144 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -35404,44 +39198,24 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } - /** Checks a type reference node as an expression. */ - function checkTypeNodeAsExpression(node) { - // When we are emitting type metadata for decorators, we need to try to check the type - // as if it were an expression so that we can emit the type in a value position when we - // serialize the type metadata. - if (node && node.kind === 155 /* TypeReference */) { - var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; - // Resolve type so we know which symbol is referenced - var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - // Resolved symbol is alias - if (rootSymbol && rootSymbol.flags & 8388608 /* Alias */) { - var aliasTarget = resolveAlias(rootSymbol); - // If alias has value symbol - mark alias as referenced - if (aliasTarget.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } - } - } /** - * Checks the type annotation of an accessor declaration or property declaration as - * an expression if it is a type reference to a type with a value declaration. - */ - function checkTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - function checkReturnTypeAnnotationAsExpression(node) { - checkTypeNodeAsExpression(node.type); - } - /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ - function checkParameterTypeAnnotationsAsExpressions(node) { - // ensure all type annotations with a value declaration are checked as an expression - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - checkTypeAnnotationAsExpression(parameter); + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + var typeName = node && ts.getEntityNameFromTypeNode(node); + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === 70 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (rootSymbol + && rootSymbol.flags & 8388608 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } /** Check the decorators of a node */ function checkDecorators(node) { if (!node.decorators) { @@ -35455,24 +39229,38 @@ var ts; if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 144 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markTypeNodeAsReferenced(node.type); break; - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: - checkTypeAnnotationAsExpression(node); + case 147 /* PropertyDeclaration */: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + case 144 /* Parameter */: + markTypeNodeAsReferenced(node.type); break; } } @@ -35494,7 +39282,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 142 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -35554,43 +39342,43 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 256 /* SourceFile */: - case 225 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 230 /* ModuleDeclaration */: checkUnusedModuleMembers(node); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: checkUnusedTypeParameters(node); break; - case 199 /* Block */: - case 227 /* CaseBlock */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: checkUnusedLocalsAndParameters(node); break; - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: checkUnusedTypeParameters(node); break; } @@ -35599,46 +39387,66 @@ var ts; } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function (key) { + if (node.parent.kind !== 227 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + var _loop_2 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local.valueDeclaration; + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144 /* Parameter */) { + var parameter = ts.getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !ts.parameterIsThisKeyword(parameter) && + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); } } }; for (var key in node.locals) { - _loop_1(key); + _loop_2(key); } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; } - function parameterNameStartsWithUnderscore(parameter) { - return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 223 /* VariableDeclaration */ && + (declaration.parent.parent.kind === 212 /* ForInStatement */ || + declaration.parent.parent.kind === 213 /* ForOfStatement */)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 70 /* Identifier */ && node.text.charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 145 /* PropertyDeclaration */) { + if (member.kind === 149 /* MethodDeclaration */ || member.kind === 147 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } - else if (member.kind === 148 /* Constructor */) { + else if (member.kind === 150 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { @@ -35686,7 +39494,7 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 199 /* Block */) { + if (node.kind === 204 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -35709,12 +39517,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 145 /* PropertyDeclaration */ || - node.kind === 144 /* PropertySignature */ || - node.kind === 147 /* MethodDeclaration */ || - node.kind === 146 /* MethodSignature */ || - node.kind === 149 /* GetAccessor */ || - node.kind === 150 /* SetAccessor */) { + if (node.kind === 147 /* PropertyDeclaration */ || + node.kind === 146 /* PropertySignature */ || + node.kind === 149 /* MethodDeclaration */ || + node.kind === 148 /* MethodSignature */ || + node.kind === 151 /* GetAccessor */ || + node.kind === 152 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -35723,7 +39531,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 142 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 144 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -35739,7 +39547,7 @@ var ts; var current = node; while (current) { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 69 /* Identifier */; + var isDeclaration_1 = node.kind !== 70 /* Identifier */; if (isDeclaration_1) { error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -35762,7 +39570,7 @@ var ts; return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_2 = node.kind !== 69 /* Identifier */; + var isDeclaration_2 = node.kind !== 70 /* Identifier */; if (isDeclaration_2) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -35772,31 +39580,35 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 225 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 225 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192 /* HasAsyncFunctions */) { + if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -35831,7 +39643,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 218 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 223 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -35841,24 +39653,24 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 219 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 200 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 205 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 199 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 226 /* ModuleBlock */ || - container.kind === 225 /* ModuleDeclaration */ || - container.kind === 256 /* SourceFile */); + (container.kind === 204 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 231 /* ModuleBlock */ || + container.kind === 230 /* ModuleDeclaration */ || + container.kind === 261 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_20 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -35866,7 +39678,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 142 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 144 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -35877,11 +39689,11 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 172 /* PropertyAccessExpression */) { + if (n.kind === 177 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 69 /* Identifier */) { + else if (n.kind === 70 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name var symbol = resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -35896,7 +39708,7 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 142 /* Parameter */) { + if (symbol.valueDeclaration.kind === 144 /* Parameter */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -35910,7 +39722,7 @@ var ts; } // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - if (current.parent.kind === 145 /* PropertyDeclaration */ && + if (current.parent.kind === 147 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)) { return; @@ -35926,6 +39738,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35934,24 +39749,28 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 169 /* BindingElement */) { + if (node.kind === 174 /* BindingElement */) { + if (node.parent.kind === 172 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 140 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 142 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_21 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_10 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_10); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_24)); + markPropertyAsReferenced(property); + if (parent_10.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35959,25 +39778,25 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 142 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 144 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 207 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 207 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -35985,7 +39804,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -35997,10 +39816,10 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */) { + if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) { + if (node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -36010,8 +39829,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 142 /* Parameter */ && right.kind === 218 /* VariableDeclaration */) || - (left.kind === 218 /* VariableDeclaration */ && right.kind === 142 /* Parameter */)) { + if ((left.kind === 144 /* Parameter */ && right.kind === 223 /* VariableDeclaration */) || + (left.kind === 223 /* VariableDeclaration */ && right.kind === 144 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -36041,7 +39860,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 176 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -36062,7 +39881,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 201 /* EmptyStatement */) { + if (node.thenStatement.kind === 206 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -36082,12 +39901,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 224 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -36110,14 +39929,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { + if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -36125,8 +39944,7 @@ var ts; } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); // iteratedType will be undefined if the rightType was missing properties/signatures // required to get its iteratedType (like [Symbol.iterator] or next). This may be // because we accessed properties from anyType, or it may have led to an error inside @@ -36144,12 +39962,13 @@ var ts; function checkForInStatement(node) { // Grammar checking checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 219 /* VariableDeclarationList */) { + if (node.initializer.kind === 224 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -36163,21 +39982,20 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { + if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -36201,7 +40019,7 @@ var ts; if (isTypeAny(inputType)) { return inputType; } - if (languageVersion >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES2015 */) { return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { @@ -36259,7 +40077,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -36300,7 +40118,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -36337,7 +40155,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -36361,14 +40179,18 @@ var ts; * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable). */ function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { - ts.Debug.assert(languageVersion < 2 /* ES6 */); - // After we remove all types that are StringLike, we will know if there was a string constituent - // based on whether the remaining type is the same as the initial type. + ts.Debug.assert(languageVersion < 2 /* ES2015 */); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); + if (arrayOrStringType.flags & 65536 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = arrayOrStringType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + } } - else if (arrayOrStringType.flags & 34 /* StringLike */) { + else if (arrayOrStringType.flags & 262178 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -36400,7 +40222,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 34 /* StringLike */) { + if (arrayElementType.flags & 262178 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); @@ -36413,7 +40235,7 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 149 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 150 /* SetAccessor */))); + return !!(node.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; @@ -36440,12 +40262,12 @@ var ts; // for generators. return; } - if (func.kind === 150 /* SetAccessor */) { + if (func.kind === 152 /* SetAccessor */) { if (node.expression) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 148 /* Constructor */) { + else if (func.kind === 150 /* Constructor */) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -36466,7 +40288,7 @@ var ts; } } } - else if (func.kind !== 148 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 150 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -36475,12 +40297,17 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 262144 /* AwaitContext */) { + if (node.flags & 16384 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -36488,9 +40315,10 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 250 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 254 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -36502,15 +40330,21 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 249 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 253 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. var caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -36527,7 +40361,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 214 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 219 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -36557,22 +40391,20 @@ var ts; if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== 69 /* Identifier */) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = catchClause.variableDeclaration.name.text; - var locals = catchClause.block.locals; - if (locals) { - var localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + var blockLocals = catchClause.block.locals; + if (blockLocals) { + for (var caughtName in catchClause.locals) { + var blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -36594,7 +40426,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -36613,7 +40445,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 65536 /* Interface */)) { + if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -36632,13 +40464,13 @@ var ts; // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (prop.valueDeclaration.name.kind === 140 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 142 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536 /* Interface */) { + else if (getObjectFlags(containingType) & 2 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -36690,7 +40522,7 @@ var ts; var firstDecl; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 221 /* ClassDeclaration */ || declaration.kind === 222 /* InterfaceDeclaration */) { + if (declaration.kind === 226 /* ClassDeclaration */ || declaration.kind === 227 /* InterfaceDeclaration */) { if (!firstDecl) { firstDecl = declaration; } @@ -36736,6 +40568,9 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */ && !ts.isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType_1 = baseTypes[0]; @@ -36753,7 +40588,9 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { + if (baseType_1.symbol.valueDeclaration && + !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) && + baseType_1.symbol.valueDeclaration.kind === 226 /* ClassDeclaration */) { if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -36782,8 +40619,8 @@ var ts; if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; - if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { + var declaredType = getObjectFlags(t) & 4 /* Reference */ ? t.target : t; + if (getObjectFlags(declaredType) & 3 /* ClassOrInterface */) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -36805,7 +40642,7 @@ var ts; if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -36854,7 +40691,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 192 /* ClassExpression */) { + if (derivedClassDecl.kind === 197 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -36902,7 +40739,7 @@ var ts; } } function isAccessor(kind) { - return kind === 149 /* GetAccessor */ || kind === 150 /* SetAccessor */; + return kind === 151 /* GetAccessor */ || kind === 152 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -36943,8 +40780,8 @@ var ts; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { - var prop = properties_5[_a]; + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; var existing = seen[prop.name]; if (!existing) { seen[prop.name] = { prop: prop, containingType: base }; @@ -36974,7 +40811,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(node, symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 222 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -37005,6 +40842,7 @@ var ts; // Grammar checking checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } function computeEnumMemberValues(node) { @@ -37021,7 +40859,7 @@ var ts; error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - var text = getTextOfPropertyName(member.name); + var text = ts.getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -37080,18 +40918,18 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; } switch (e.operator) { - case 35 /* PlusToken */: return value_1; - case 36 /* MinusToken */: return -value_1; - case 50 /* TildeToken */: return ~value_1; + case 36 /* PlusToken */: return value_1; + case 37 /* MinusToken */: return -value_1; + case 51 /* TildeToken */: return ~value_1; } return undefined; - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -37101,31 +40939,31 @@ var ts; return undefined; } switch (e.operatorToken.kind) { - case 47 /* BarToken */: return left | right; - case 46 /* AmpersandToken */: return left & right; - case 44 /* GreaterThanGreaterThanToken */: return left >> right; - case 45 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 43 /* LessThanLessThanToken */: return left << right; - case 48 /* CaretToken */: return left ^ right; - case 37 /* AsteriskToken */: return left * right; - case 39 /* SlashToken */: return left / right; - case 35 /* PlusToken */: return left + right; - case 36 /* MinusToken */: return left - right; - case 40 /* PercentToken */: return left % right; + case 48 /* BarToken */: return left | right; + case 47 /* AmpersandToken */: return left & right; + case 45 /* GreaterThanGreaterThanToken */: return left >> right; + case 46 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 44 /* LessThanLessThanToken */: return left << right; + case 49 /* CaretToken */: return left ^ right; + case 38 /* AsteriskToken */: return left * right; + case 40 /* SlashToken */: return left / right; + case 36 /* PlusToken */: return left + right; + case 37 /* MinusToken */: return left - right; + case 41 /* PercentToken */: return left % right; } return undefined; case 8 /* NumericLiteral */: return +e.text; - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: return evalConstant(e.expression); - case 69 /* Identifier */: - case 173 /* ElementAccessExpression */: - case 172 /* PropertyAccessExpression */: + case 70 /* Identifier */: + case 178 /* ElementAccessExpression */: + case 177 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; var propertyName = void 0; - if (e.kind === 69 /* Identifier */) { + if (e.kind === 70 /* Identifier */) { // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. // instead pick current enum type and later try to fetch member from the type enumType_1 = currentType; @@ -37133,7 +40971,7 @@ var ts; } else { var expression = void 0; - if (e.kind === 173 /* ElementAccessExpression */) { + if (e.kind === 178 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -37148,17 +40986,17 @@ var ts; // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName var current = expression; while (current) { - if (current.kind === 69 /* Identifier */) { + if (current.kind === 70 /* Identifier */) { break; } - else if (current.kind === 172 /* PropertyAccessExpression */) { + else if (current.kind === 177 /* PropertyAccessExpression */) { current = current.expression; } else { return undefined; } } - enumType_1 = checkExpression(expression); + enumType_1 = getTypeOfExpression(expression); // allow references to constant members of other enums if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { return undefined; @@ -37223,7 +41061,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 224 /* EnumDeclaration */) { + if (declaration.kind !== 229 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -37246,8 +41084,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 221 /* ClassDeclaration */ || - (declaration.kind === 220 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 226 /* ClassDeclaration */ || + (declaration.kind === 225 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -37288,9 +41126,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37309,7 +41149,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 221 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 226 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -37360,26 +41200,26 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 241 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 235 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - var name_22 = node.name; - if (ts.isBindingPattern(name_22)) { - for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { + case 174 /* BindingElement */: + case 223 /* VariableDeclaration */: + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); @@ -37387,12 +41227,12 @@ var ts; break; } // fallthrough - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 220 /* FunctionDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 225 /* FunctionDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 228 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -37413,17 +41253,17 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return node; - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 69 /* Identifier */); + } while (node.kind !== 70 /* Identifier */); return node; - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 69 /* Identifier */); + } while (node.kind !== 70 /* Identifier */); return node; } } @@ -37433,9 +41273,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 226 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 236 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 241 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -37468,7 +41308,7 @@ var ts; (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 238 /* ExportSpecifier */ ? + var message = node.kind === 243 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -37496,7 +41336,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 237 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -37533,7 +41373,7 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.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); } @@ -37553,8 +41393,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 226 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 256 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -37568,9 +41408,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 261 /* SourceFile */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 230 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37592,8 +41434,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 256 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 225 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 261 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 230 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -37601,7 +41443,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { markExportAsReferenced(node); } else { @@ -37609,7 +41451,7 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES6) { + if (modulekind === ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -37668,7 +41510,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 225 /* FunctionDeclaration */ && declaration.kind !== 149 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -37680,118 +41523,123 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return checkTypeParameter(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return checkParameter(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return checkPropertyDeclaration(node); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return checkSignatureDeclaration(node); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return checkMethodDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return checkConstructorDeclaration(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return checkAccessorDeclaration(node); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return checkTypeReferenceNode(node); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return checkTypePredicate(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return checkTypeQuery(node); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return checkTypeLiteral(node); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return checkArrayType(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return checkTupleType(node); - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: + case 168 /* TypeOperator */: return checkSourceElement(node.type); - case 220 /* FunctionDeclaration */: + case 169 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 170 /* MappedType */: + return checkMappedType(node); + case 225 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 199 /* Block */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return checkBlock(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return checkVariableStatement(node); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return checkExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return checkIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return checkDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return checkWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return checkForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return checkForInStatement(node); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return checkForOfStatement(node); - case 209 /* ContinueStatement */: - case 210 /* BreakStatement */: + case 214 /* ContinueStatement */: + case 215 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return checkReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return checkWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return checkSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return checkLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return checkThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return checkTryStatement(node); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return checkBindingElement(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return checkClassDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return checkImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return checkExportDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return checkExportAssignment(node); - case 201 /* EmptyStatement */: + case 206 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -37813,17 +41661,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: checkAccessorDeferred(node); break; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: checkClassExpressionDeferred(node); break; } @@ -37885,9 +41733,29 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); } @@ -37904,7 +41772,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 212 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 217 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -37927,25 +41795,25 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -37954,7 +41822,7 @@ var ts; copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); } break; - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -37997,34 +41865,34 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 69 /* Identifier */ && + return name.kind === 70 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 141 /* TypeParameter */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: + case 143 /* TypeParameter */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: return true; } } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 139 /* QualifiedName */) { + while (node.parent && node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } - return node.parent && (node.parent.kind === 155 /* TypeReference */ || node.parent.kind === 267 /* JSDocTypeReference */); + return node.parent && (node.parent.kind === 157 /* TypeReference */ || node.parent.kind === 272 /* JSDocTypeReference */); } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 172 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 177 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 194 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 199 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -38041,13 +41909,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 139 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 141 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 229 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 234 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 235 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 240 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -38059,7 +41927,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 172 /* PropertyAccessExpression */) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177 /* PropertyAccessExpression */) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: @@ -38071,15 +41939,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 240 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + if (entityName.kind !== 177 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 234 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -38087,7 +41955,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 199 /* ExpressionWithTypeArguments */) { meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -38105,20 +41973,20 @@ var ts; // Missing entity name. return undefined; } - if (entityName.kind === 69 /* Identifier */) { + if (entityName.kind === 70 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 172 /* PropertyAccessExpression */) { + else if (entityName.kind === 177 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 139 /* QualifiedName */) { + else if (entityName.kind === 141 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -38127,20 +41995,20 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = (entityName.parent.kind === 157 /* TypeReference */ || entityName.parent.kind === 272 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 246 /* JsxAttribute */) { + else if (entityName.parent.kind === 250 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 154 /* TypePredicate */) { + if (entityName.parent.kind === 156 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 256 /* SourceFile */) { + if (node.kind === 261 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } if (isInsideWithStatementBody(node)) { @@ -38154,12 +42022,12 @@ var ts; else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 169 /* BindingElement */ && - node.parent.parent.kind === 167 /* ObjectBindingPattern */ && + else if (node.parent.kind === 174 /* BindingElement */ && + node.parent.parent.kind === 172 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -38169,11 +42037,11 @@ var ts; } } switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); @@ -38182,15 +42050,15 @@ var ts; } } // fallthrough - case 95 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + case 96 /* SuperKeyword */: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; - case 165 /* ThisType */: + case 167 /* ThisType */: return getTypeFromTypeNode(node).symbol; - case 121 /* ConstructorKeyword */: + case 122 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 148 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 150 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -38198,15 +42066,18 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 230 /* ImportDeclaration */ || node.parent.kind === 236 /* ExportDeclaration */) && + ((node.parent.kind === 235 /* ImportDeclaration */ || node.parent.kind === 241 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 173 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = checkExpression(node.parent.expression); + if (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); if (objectType === unknownType) return undefined; var apparentType = getApparentType(objectType); @@ -38222,7 +42093,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 254 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 258 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); } return undefined; @@ -38242,7 +42113,7 @@ var ts; return getTypeFromTypeNode(node); } if (ts.isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the @@ -38284,28 +42155,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 171 /* ObjectLiteralExpression */ || expr.kind === 170 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 176 /* ObjectLiteralExpression */ || expr.kind === 175 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 208 /* ForOfStatement */) { + if (expr.parent.kind === 213 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 187 /* BinaryExpression */) { - var iteratedType = checkExpression(expr.parent.right); + if (expr.parent.kind === 192 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 253 /* PropertyAssignment */) { + if (expr.parent.kind === 257 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 170 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 175 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false) || unknownType; @@ -38322,11 +42193,11 @@ var ts; var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr) { + function getRegularTypeOfExpression(expr) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } /** * Gets either the static or instance type of a class element, based on @@ -38355,9 +42226,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { var symbols_3 = []; - var name_23 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_23); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -38365,6 +42236,10 @@ var ts; return symbols_3; } else if (symbol.flags & 67108864 /* Transient */) { + if (symbol.leftSpread) { + var links = symbol; + return [links.leftSpread, links.rightSpread]; + } var target = void 0; var next = symbol; while (next = getSymbolLinks(next).target) { @@ -38412,7 +42287,7 @@ var ts; } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; - return ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. @@ -38437,7 +42312,7 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 256 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 261 /* SourceFile */) { var symbolFile = parentSymbol.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -38494,7 +42369,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 199 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 204 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -38540,18 +42415,18 @@ var ts; return true; } switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return node.expression - && node.expression.kind === 69 /* Identifier */ + && node.expression.kind === 70 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -38559,7 +42434,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 256 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 261 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -38625,7 +42500,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 255 /* EnumMember */) { + if (node.kind === 260 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -38638,7 +42513,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -38673,7 +42548,7 @@ var ts; else if (isTypeOfKind(type, 340 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34 /* StringLike */)) { + else if (isTypeOfKind(type, 262178 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { @@ -38705,7 +42580,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getTypeOfExpression(expr)); + var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { @@ -38726,9 +42601,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_11 = reference.parent; + if (ts.isDeclaration(parent_11) && reference === parent_11.name) { + location = getDeclarationContainer(parent_11); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38748,7 +42623,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 16777216 /* FreshLiteral */); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); } return false; } @@ -38802,7 +42677,8 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -38813,7 +42689,7 @@ var ts; // property access can only be used as values // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) + var meaning = (node.kind === 177 /* PropertyAccessExpression */) || (node.kind === 70 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -38839,6 +42715,10 @@ var ts; if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } } } return typeReferenceDirectives; @@ -38852,15 +42732,15 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_12 = getParentOfSymbol(current); + if (parent_12) { + current = parent_12; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 256 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 261 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -38880,7 +42760,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 256 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 261 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -38890,8 +42770,6 @@ var ts; } // Initialize global symbol table var augmentations; - var requestedExternalEmitHelpers = 0; - var firstFileRequestingExternalHelpers; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; if (!ts.isExternalOrCommonJsModule(file)) { @@ -38912,15 +42790,6 @@ var ts; } } } - if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) { - var fileRequestedExternalEmitHelpers = file.flags & 31744 /* EmitHelperFlags */; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { // merge module augmentations. @@ -38962,7 +42831,7 @@ var ts; getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); getGlobalThenableType = ts.memoize(createThenableType); getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); }); - if (languageVersion >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES2015 */) { getGlobalESSymbolType = ts.memoize(function () { return getGlobalType("Symbol"); }); getGlobalIterableType = ts.memoize(function () { return getGlobalType("Iterable", /*arity*/ 1); }); getGlobalIteratorType = ts.memoize(function () { return getGlobalType("Iterator", /*arity*/ 1); }); @@ -38975,49 +42844,50 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - // If we have specified that we are importing helpers, we should report global - // errors if we cannot resolve the helpers external module, or if it does not have - // the necessary helpers exported. - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - // Find the first reference to the helpers module. - var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, - /*errorNode*/ undefined); - // If we found the module, report errors if it does not have the necessary exports. - if (helpersModule) { - var exports = helpersModule.exports; - if (requestedExternalEmitHelpers & 1024 /* HasClassExtends */ && languageVersion < 2 /* ES6 */) { - verifyHelperSymbol(exports, "__extends", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 16384 /* HasJsxSpreadAttributes */ && compilerOptions.jsx !== 1 /* Preserve */) { - verifyHelperSymbol(exports, "__assign", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 2048 /* HasDecorators */) { - verifyHelperSymbol(exports, "__decorate", 107455 /* Value */); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455 /* Value */); - } - } - if (requestedExternalEmitHelpers & 4096 /* HasParamDecorators */) { - verifyHelperSymbol(exports, "__param", 107455 /* Value */); - } - if (requestedExternalEmitHelpers & 8192 /* HasAsyncFunctions */) { - verifyHelperSymbol(exports, "__awaiter", 107455 /* Value */); - if (languageVersion < 2 /* ES6 */) { - verifyHelperSymbol(exports, "__generator", 107455 /* Value */); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 128 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name_27 = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name_27), 107455 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_27); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols, name, meaning) { - var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning); - if (!symbol) { - error(/*location*/ undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; } } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -39029,7 +42899,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152 /* Anonymous */); + var thenableType = createObjectType(16 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -39042,14 +42912,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 147 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 149 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 149 /* GetAccessor */ || node.kind === 150 /* SetAccessor */) { + else if (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -39066,28 +42936,28 @@ var ts; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 128 /* ReadonlyKeyword */) { - if (node.kind === 144 /* PropertySignature */ || node.kind === 146 /* MethodSignature */) { + if (modifier.kind !== 130 /* ReadonlyKeyword */) { + if (node.kind === 146 /* PropertySignature */ || node.kind === 148 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 74 /* ConstKeyword */: - if (node.kind !== 224 /* EnumDeclaration */ && node.parent.kind === 221 /* ClassDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + case 75 /* ConstKeyword */: + if (node.kind !== 229 /* EnumDeclaration */ && node.parent.kind === 226 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75 /* ConstKeyword */)); } break; - case 112 /* PublicKeyword */: - case 111 /* ProtectedKeyword */: - case 110 /* PrivateKeyword */: + case 113 /* PublicKeyword */: + case 112 /* ProtectedKeyword */: + case 111 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 111 /* ProtectedKeyword */) { + if (modifier.kind === 112 /* ProtectedKeyword */) { lastProtected = modifier; } - else if (modifier.kind === 110 /* PrivateKeyword */) { + else if (modifier.kind === 111 /* PrivateKeyword */) { lastPrivate = modifier; } if (flags & 28 /* AccessibilityModifier */) { @@ -39102,11 +42972,11 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { - if (modifier.kind === 110 /* PrivateKeyword */) { + if (modifier.kind === 111 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -39115,7 +42985,7 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 113 /* StaticKeyword */: + case 114 /* StaticKeyword */: if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } @@ -39125,10 +42995,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -39137,18 +43007,18 @@ var ts; flags |= 32 /* Static */; lastStatic = modifier; break; - case 128 /* ReadonlyKeyword */: + case 130 /* ReadonlyKeyword */: if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */ && node.kind !== 153 /* IndexSignature */ && node.kind !== 142 /* Parameter */) { + else if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */ && node.kind !== 155 /* IndexSignature */ && node.kind !== 144 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 82 /* ExportKeyword */: + case 83 /* ExportKeyword */: if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } @@ -39161,45 +43031,45 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; - case 122 /* DeclareKeyword */: + case 123 /* DeclareKeyword */: if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 226 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 115 /* AbstractKeyword */: + case 116 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 221 /* ClassDeclaration */) { - if (node.kind !== 147 /* MethodDeclaration */ && - node.kind !== 145 /* PropertyDeclaration */ && - node.kind !== 149 /* GetAccessor */ && - node.kind !== 150 /* SetAccessor */) { + if (node.kind !== 226 /* ClassDeclaration */) { + if (node.kind !== 149 /* MethodDeclaration */ && + node.kind !== 147 /* PropertyDeclaration */ && + node.kind !== 151 /* GetAccessor */ && + node.kind !== 152 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 221 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + if (!(node.parent.kind === 226 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -39211,14 +43081,14 @@ var ts; } flags |= 128 /* Abstract */; break; - case 118 /* AsyncKeyword */: + case 119 /* AsyncKeyword */: if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 142 /* Parameter */) { + else if (node.kind === 144 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -39226,7 +43096,7 @@ var ts; break; } } - if (node.kind === 148 /* Constructor */) { + if (node.kind === 150 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -39241,13 +43111,13 @@ var ts; } return; } - else if ((node.kind === 230 /* ImportDeclaration */ || node.kind === 229 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { 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)) { + else if (node.kind === 144 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { 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) { + else if (node.kind === 144 /* 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 */) { @@ -39267,38 +43137,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 155 /* IndexSignature */: + case 230 /* ModuleDeclaration */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: + case 240 /* ExportAssignment */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 144 /* Parameter */: return false; default: - if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { return false; } switch (node.kind) { - case 220 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); - case 221 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: + case 225 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 119 /* AsyncKeyword */); + case 226 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 116 /* AbstractKeyword */); + case 227 /* InterfaceDeclaration */: + case 205 /* VariableStatement */: + case 228 /* TypeAliasDeclaration */: return true; - case 224 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); + case 229 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 75 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -39310,10 +43180,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 147 /* MethodDeclaration */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -39329,7 +43199,7 @@ var ts; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); } } - function checkGrammarTypeParameterList(node, typeParameters, file) { + function checkGrammarTypeParameterList(typeParameters, file) { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -39372,11 +43242,11 @@ var ts; function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 180 /* ArrowFunction */) { + if (node.kind === 185 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -39411,7 +43281,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 132 /* StringKeyword */ && parameter.type.kind !== 130 /* NumberKeyword */) { + if (parameter.type.kind !== 134 /* StringKeyword */ && parameter.type.kind !== 132 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -39437,9 +43307,9 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 193 /* OmittedExpression */) { + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; + if (arg.kind === 198 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -39465,7 +43335,7 @@ var ts; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (heritageClause.token === 84 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -39478,7 +43348,7 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 107 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } @@ -39494,14 +43364,14 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (heritageClause.token === 84 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + ts.Debug.assert(heritageClause.token === 107 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } // Grammar checking heritageClause inside class declaration @@ -39512,31 +43382,31 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 140 /* ComputedPropertyName */) { + if (node.kind !== 142 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 187 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 192 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 25 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 220 /* FunctionDeclaration */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 147 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 225 /* FunctionDeclaration */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 149 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); } - if (languageVersion < 2 /* ES6 */) { + if (languageVersion < 2 /* ES2015 */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher); } } } - function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + function checkGrammarForInvalidQuestionMark(questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -39549,13 +43419,15 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { - // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_24); + if (prop.kind === 259 /* SpreadAssignment */) { + continue; } - if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + var name_28 = prop.name; + if (name_28.kind === 142 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name_28); + } + if (prop.kind === 258 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -39564,7 +43436,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 147 /* MethodDeclaration */) { + if (mod.kind !== 119 /* AsyncKeyword */ || prop.kind !== 149 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -39578,27 +43450,27 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 253 /* PropertyAssignment */ || prop.kind === 254 /* ShorthandPropertyAssignment */) { + if (prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_24.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_24); + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_28.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_28); } currentKind = Property; } - else if (prop.kind === 147 /* MethodDeclaration */) { + else if (prop.kind === 149 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 149 /* GetAccessor */) { + else if (prop.kind === 151 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 150 /* SetAccessor */) { + else if (prop.kind === 152 /* SetAccessor */) { currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_28); if (effectiveName === undefined) { continue; } @@ -39608,18 +43480,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); + grammarErrorOnNode(name_28, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_28)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -39628,19 +43500,19 @@ var ts; var seen = ts.createMap(); for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 247 /* JsxSpreadAttribute */) { + if (attr.kind === 251 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_25 = jsxAttr.name; - if (!seen[name_25.text]) { - seen[name_25.text] = true; + var name_29 = jsxAttr.name; + if (!seen[name_29.text]) { + seen[name_29.text] = true; } else { - return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_29, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 248 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 252 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -39649,7 +43521,7 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 219 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 224 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -39664,20 +43536,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 207 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -39697,15 +43569,18 @@ var ts; else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } + else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 149 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 151 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 150 /* SetAccessor */) { + else if (kind === 152 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -39728,20 +43603,11 @@ var ts; A get accessor has no parameters or a single `this` parameter. A set accessor has one parameter or a `this` parameter and one more parameter */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -39755,8 +43621,8 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 171 /* ObjectLiteralExpression */) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (node.parent.kind === 176 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -39776,10 +43642,10 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 222 /* InterfaceDeclaration */) { + else if (node.parent.kind === 227 /* InterfaceDeclaration */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } - else if (node.parent.kind === 159 /* TypeLiteral */) { + else if (node.parent.kind === 161 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -39790,11 +43656,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 209 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 214 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -39802,8 +43668,8 @@ var ts; return false; } break; - case 213 /* SwitchStatement */: - if (node.kind === 210 /* BreakStatement */ && !node.label) { + case 218 /* SwitchStatement */: + if (node.kind === 215 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -39818,13 +43684,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 210 /* BreakStatement */ + var message = node.kind === 215 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 210 /* BreakStatement */ + var message = node.kind === 215 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -39834,24 +43700,24 @@ var ts; if (node.dotDotDotToken) { var elements = node.parent.elements; if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 168 /* ArrayBindingPattern */ || node.name.kind === 167 /* ObjectBindingPattern */) { + if (node.name.kind === 173 /* ArrayBindingPattern */ || node.name.kind === 172 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { - // Error on equals token which immediate precedes the initializer + // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && + expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 207 /* ForInStatement */ && node.parent.parent.kind !== 208 /* ForOfStatement */) { + if (node.parent.parent.kind !== 212 /* ForInStatement */ && node.parent.parent.kind !== 213 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { if (ts.isConst(node) && !node.type) { @@ -39890,8 +43756,8 @@ var ts; return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 69 /* Identifier */) { - if (name.originalKeywordKind === 108 /* LetKeyword */) { + if (name.kind === 70 /* Identifier */) { + if (name.originalKeywordKind === 109 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -39916,15 +43782,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 203 /* IfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: + case 208 /* IfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: return false; - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -39979,7 +43845,7 @@ var ts; return true; } } - else if (node.parent.kind === 222 /* InterfaceDeclaration */) { + else if (node.parent.kind === 227 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -39987,7 +43853,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 159 /* TypeLiteral */) { + else if (node.parent.kind === 161 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -40012,13 +43878,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 222 /* InterfaceDeclaration */ || - node.kind === 223 /* TypeAliasDeclaration */ || - node.kind === 230 /* ImportDeclaration */ || - node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 236 /* ExportDeclaration */ || - node.kind === 235 /* ExportAssignment */ || - node.kind === 228 /* NamespaceExportDeclaration */ || + if (node.kind === 227 /* InterfaceDeclaration */ || + node.kind === 228 /* TypeAliasDeclaration */ || + node.kind === 235 /* ImportDeclaration */ || + node.kind === 234 /* ImportEqualsDeclaration */ || + node.kind === 241 /* ExportDeclaration */ || + node.kind === 240 /* ExportAssignment */ || + node.kind === 233 /* NamespaceExportDeclaration */ || ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -40027,7 +43893,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 200 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 205 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -40053,7 +43919,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 199 /* Block */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 204 /* Block */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -40113,49 +43979,49 @@ var ts; * significantly impacted. */ var nodeEdgeTraversalMap = ts.createMap((_a = {}, - _a[139 /* QualifiedName */] = [ + _a[141 /* QualifiedName */] = [ { name: "left", test: ts.isEntityName }, { name: "right", test: ts.isIdentifier } ], - _a[143 /* Decorator */] = [ + _a[145 /* Decorator */] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[177 /* TypeAssertionExpression */] = [ + _a[182 /* TypeAssertionExpression */] = [ { name: "type", test: ts.isTypeNode }, { name: "expression", test: ts.isUnaryExpression } ], - _a[195 /* AsExpression */] = [ + _a[200 /* AsExpression */] = [ { name: "expression", test: ts.isExpression }, { name: "type", test: ts.isTypeNode } ], - _a[196 /* NonNullExpression */] = [ + _a[201 /* NonNullExpression */] = [ { name: "expression", test: ts.isLeftHandSideExpression } ], - _a[224 /* EnumDeclaration */] = [ + _a[229 /* EnumDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "members", test: ts.isEnumMember } ], - _a[225 /* ModuleDeclaration */] = [ + _a[230 /* ModuleDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isModuleName }, { name: "body", test: ts.isModuleBody } ], - _a[226 /* ModuleBlock */] = [ + _a[231 /* ModuleBlock */] = [ { name: "statements", test: ts.isStatement } ], - _a[229 /* ImportEqualsDeclaration */] = [ + _a[234 /* ImportEqualsDeclaration */] = [ { name: "decorators", test: ts.isDecorator }, { name: "modifiers", test: ts.isModifier }, { name: "name", test: ts.isIdentifier }, { name: "moduleReference", test: ts.isModuleReference } ], - _a[240 /* ExternalModuleReference */] = [ + _a[245 /* ExternalModuleReference */] = [ { name: "expression", test: ts.isExpression, optional: true } ], - _a[255 /* EnumMember */] = [ + _a[260 /* EnumMember */] = [ { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], @@ -40163,355 +44029,363 @@ var ts; function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } + function reduceNodeArray(nodes, f, initial) { + return nodes ? f(initial, nodes) : initial; + } /** * Similar to `reduceLeft`, performs a reduction against each child of a node. * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the * `nodeEdgeTraversalMap` above will be visited. * * @param node The node containing the children to reduce. - * @param f The callback function * @param initial The initial value to supply to the reduction. + * @param f The callback function */ - function reduceEachChild(node, f, initial) { + function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; } + var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; + var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 198 /* SemicolonClassElement */: - case 201 /* EmptyStatement */: - case 193 /* OmittedExpression */: - case 217 /* DebuggerStatement */: - case 287 /* NotEmittedStatement */: + case 203 /* SemicolonClassElement */: + case 206 /* EmptyStatement */: + case 198 /* OmittedExpression */: + case 222 /* DebuggerStatement */: + case 293 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 140 /* ComputedPropertyName */: - result = reduceNode(node.expression, f, result); + case 142 /* ComputedPropertyName */: + result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 142 /* Parameter */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 144 /* Parameter */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 143 /* Decorator */: - result = reduceNode(node.expression, f, result); + case 145 /* Decorator */: + result = reduceNode(node.expression, cbNode, result); break; // Type member - case 145 /* PropertyDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 147 /* PropertyDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 147 /* MethodDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 149 /* MethodDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 148 /* Constructor */: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + case 150 /* Constructor */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; - case 149 /* GetAccessor */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 151 /* GetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 150 /* SetAccessor */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.body, f, result); + case 152 /* SetAccessor */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - result = ts.reduceLeft(node.elements, f, result); + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 169 /* BindingElement */: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 174 /* BindingElement */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 170 /* ArrayLiteralExpression */: - result = ts.reduceLeft(node.elements, f, result); + case 175 /* ArrayLiteralExpression */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 171 /* ObjectLiteralExpression */: - result = ts.reduceLeft(node.properties, f, result); + case 176 /* ObjectLiteralExpression */: + result = reduceNodes(node.properties, cbNodes, result); break; - case 172 /* PropertyAccessExpression */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.name, f, result); + case 177 /* PropertyAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; - case 173 /* ElementAccessExpression */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.argumentExpression, f, result); + case 178 /* ElementAccessExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.argumentExpression, cbNode, result); break; - case 174 /* CallExpression */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + case 179 /* CallExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); break; - case 175 /* NewExpression */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); - result = ts.reduceLeft(node.arguments, f, result); + case 180 /* NewExpression */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); + result = reduceNodes(node.arguments, cbNodes, result); break; - case 176 /* TaggedTemplateExpression */: - result = reduceNode(node.tag, f, result); - result = reduceNode(node.template, f, result); + case 181 /* TaggedTemplateExpression */: + result = reduceNode(node.tag, cbNode, result); + result = reduceNode(node.template, cbNode, result); break; - case 179 /* FunctionExpression */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 184 /* FunctionExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 180 /* ArrowFunction */: - result = ts.reduceLeft(node.modifiers, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 185 /* ArrowFunction */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 178 /* ParenthesizedExpression */: - case 181 /* DeleteExpression */: - case 182 /* TypeOfExpression */: - case 183 /* VoidExpression */: - case 184 /* AwaitExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: - case 196 /* NonNullExpression */: - result = reduceNode(node.expression, f, result); + case 183 /* ParenthesizedExpression */: + case 186 /* DeleteExpression */: + case 187 /* TypeOfExpression */: + case 188 /* VoidExpression */: + case 189 /* AwaitExpression */: + case 195 /* YieldExpression */: + case 196 /* SpreadElement */: + case 201 /* NonNullExpression */: + result = reduceNode(node.expression, cbNode, result); break; - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - result = reduceNode(node.operand, f, result); + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + result = reduceNode(node.operand, cbNode, result); break; - case 187 /* BinaryExpression */: - result = reduceNode(node.left, f, result); - result = reduceNode(node.right, f, result); + case 192 /* BinaryExpression */: + result = reduceNode(node.left, cbNode, result); + result = reduceNode(node.right, cbNode, result); break; - case 188 /* ConditionalExpression */: - result = reduceNode(node.condition, f, result); - result = reduceNode(node.whenTrue, f, result); - result = reduceNode(node.whenFalse, f, result); + case 193 /* ConditionalExpression */: + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.whenTrue, cbNode, result); + result = reduceNode(node.whenFalse, cbNode, result); break; - case 189 /* TemplateExpression */: - result = reduceNode(node.head, f, result); - result = ts.reduceLeft(node.templateSpans, f, result); + case 194 /* TemplateExpression */: + result = reduceNode(node.head, cbNode, result); + result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 192 /* ClassExpression */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + case 197 /* ClassExpression */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; - case 194 /* ExpressionWithTypeArguments */: - result = reduceNode(node.expression, f, result); - result = ts.reduceLeft(node.typeArguments, f, result); + case 199 /* ExpressionWithTypeArguments */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNodes(node.typeArguments, cbNodes, result); break; // Misc - case 197 /* TemplateSpan */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.literal, f, result); + case 202 /* TemplateSpan */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.literal, cbNode, result); break; // Element - case 199 /* Block */: - result = ts.reduceLeft(node.statements, f, result); + case 204 /* Block */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 200 /* VariableStatement */: - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.declarationList, f, result); + case 205 /* VariableStatement */: + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.declarationList, cbNode, result); break; - case 202 /* ExpressionStatement */: - result = reduceNode(node.expression, f, result); + case 207 /* ExpressionStatement */: + result = reduceNode(node.expression, cbNode, result); break; - case 203 /* IfStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.thenStatement, f, result); - result = reduceNode(node.elseStatement, f, result); + case 208 /* IfStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.thenStatement, cbNode, result); + result = reduceNode(node.elseStatement, cbNode, result); break; - case 204 /* DoStatement */: - result = reduceNode(node.statement, f, result); - result = reduceNode(node.expression, f, result); + case 209 /* DoStatement */: + result = reduceNode(node.statement, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; - case 205 /* WhileStatement */: - case 212 /* WithStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + case 210 /* WhileStatement */: + case 217 /* WithStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 206 /* ForStatement */: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.condition, f, result); - result = reduceNode(node.incrementor, f, result); - result = reduceNode(node.statement, f, result); + case 211 /* ForStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.condition, cbNode, result); + result = reduceNode(node.incrementor, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - result = reduceNode(node.initializer, f, result); - result = reduceNode(node.expression, f, result); - result = reduceNode(node.statement, f, result); + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + result = reduceNode(node.initializer, cbNode, result); + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 211 /* ReturnStatement */: - case 215 /* ThrowStatement */: - result = reduceNode(node.expression, f, result); + case 216 /* ReturnStatement */: + case 220 /* ThrowStatement */: + result = reduceNode(node.expression, cbNode, result); break; - case 213 /* SwitchStatement */: - result = reduceNode(node.expression, f, result); - result = reduceNode(node.caseBlock, f, result); + case 218 /* SwitchStatement */: + result = reduceNode(node.expression, cbNode, result); + result = reduceNode(node.caseBlock, cbNode, result); break; - case 214 /* LabeledStatement */: - result = reduceNode(node.label, f, result); - result = reduceNode(node.statement, f, result); + case 219 /* LabeledStatement */: + result = reduceNode(node.label, cbNode, result); + result = reduceNode(node.statement, cbNode, result); break; - case 216 /* TryStatement */: - result = reduceNode(node.tryBlock, f, result); - result = reduceNode(node.catchClause, f, result); - result = reduceNode(node.finallyBlock, f, result); + case 221 /* TryStatement */: + result = reduceNode(node.tryBlock, cbNode, result); + result = reduceNode(node.catchClause, cbNode, result); + result = reduceNode(node.finallyBlock, cbNode, result); break; - case 218 /* VariableDeclaration */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.initializer, f, result); + case 223 /* VariableDeclaration */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 219 /* VariableDeclarationList */: - result = ts.reduceLeft(node.declarations, f, result); + case 224 /* VariableDeclarationList */: + result = reduceNodes(node.declarations, cbNodes, result); break; - case 220 /* FunctionDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.parameters, f, result); - result = reduceNode(node.type, f, result); - result = reduceNode(node.body, f, result); + case 225 /* FunctionDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.parameters, cbNodes, result); + result = reduceNode(node.type, cbNode, result); + result = reduceNode(node.body, cbNode, result); break; - case 221 /* ClassDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.name, f, result); - result = ts.reduceLeft(node.typeParameters, f, result); - result = ts.reduceLeft(node.heritageClauses, f, result); - result = ts.reduceLeft(node.members, f, result); + case 226 /* ClassDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.name, cbNode, result); + result = reduceNodes(node.typeParameters, cbNodes, result); + result = reduceNodes(node.heritageClauses, cbNodes, result); + result = reduceNodes(node.members, cbNodes, result); break; - case 227 /* CaseBlock */: - result = ts.reduceLeft(node.clauses, f, result); + case 232 /* CaseBlock */: + result = reduceNodes(node.clauses, cbNodes, result); break; - case 230 /* ImportDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.importClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 235 /* ImportDeclaration */: + result = reduceNodes(node.decorators, cbNodes, result); + result = reduceNodes(node.modifiers, cbNodes, result); + result = reduceNode(node.importClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 231 /* ImportClause */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.namedBindings, f, result); + case 236 /* ImportClause */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); break; - case 232 /* NamespaceImport */: - result = reduceNode(node.name, f, result); + case 237 /* NamespaceImport */: + result = reduceNode(node.name, cbNode, result); break; - case 233 /* NamedImports */: - case 237 /* NamedExports */: - result = ts.reduceLeft(node.elements, f, result); + case 238 /* NamedImports */: + case 242 /* NamedExports */: + result = reduceNodes(node.elements, cbNodes, result); break; - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - result = reduceNode(node.propertyName, f, result); - result = reduceNode(node.name, f, result); + case 239 /* ImportSpecifier */: + case 243 /* ExportSpecifier */: + result = reduceNode(node.propertyName, cbNode, result); + result = reduceNode(node.name, cbNode, result); break; - case 235 /* ExportAssignment */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.expression, f, result); + case 240 /* ExportAssignment */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.expression, cbNode, result); break; - case 236 /* ExportDeclaration */: - result = ts.reduceLeft(node.decorators, f, result); - result = ts.reduceLeft(node.modifiers, f, result); - result = reduceNode(node.exportClause, f, result); - result = reduceNode(node.moduleSpecifier, f, result); + case 241 /* ExportDeclaration */: + result = ts.reduceLeft(node.decorators, cbNode, result); + result = ts.reduceLeft(node.modifiers, cbNode, result); + result = reduceNode(node.exportClause, cbNode, result); + result = reduceNode(node.moduleSpecifier, cbNode, result); break; // JSX - case 241 /* JsxElement */: - result = reduceNode(node.openingElement, f, result); - result = ts.reduceLeft(node.children, f, result); - result = reduceNode(node.closingElement, f, result); + case 246 /* JsxElement */: + result = reduceNode(node.openingElement, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingElement, cbNode, result); break; - case 242 /* JsxSelfClosingElement */: - case 243 /* JsxOpeningElement */: - result = reduceNode(node.tagName, f, result); - result = ts.reduceLeft(node.attributes, f, result); + case 247 /* JsxSelfClosingElement */: + case 248 /* JsxOpeningElement */: + result = reduceNode(node.tagName, cbNode, result); + result = reduceNodes(node.attributes, cbNodes, result); break; - case 245 /* JsxClosingElement */: - result = reduceNode(node.tagName, f, result); + case 249 /* JsxClosingElement */: + result = reduceNode(node.tagName, cbNode, result); break; - case 246 /* JsxAttribute */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 250 /* JsxAttribute */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 247 /* JsxSpreadAttribute */: - result = reduceNode(node.expression, f, result); + case 251 /* JsxSpreadAttribute */: + result = reduceNode(node.expression, cbNode, result); break; - case 248 /* JsxExpression */: - result = reduceNode(node.expression, f, result); + case 252 /* JsxExpression */: + result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 249 /* CaseClause */: - result = reduceNode(node.expression, f, result); + case 253 /* CaseClause */: + result = reduceNode(node.expression, cbNode, result); // fall-through - case 250 /* DefaultClause */: - result = ts.reduceLeft(node.statements, f, result); + case 254 /* DefaultClause */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 251 /* HeritageClause */: - result = ts.reduceLeft(node.types, f, result); + case 255 /* HeritageClause */: + result = reduceNodes(node.types, cbNodes, result); break; - case 252 /* CatchClause */: - result = reduceNode(node.variableDeclaration, f, result); - result = reduceNode(node.block, f, result); + case 256 /* CatchClause */: + result = reduceNode(node.variableDeclaration, cbNode, result); + result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 253 /* PropertyAssignment */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.initializer, f, result); + case 257 /* PropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.initializer, cbNode, result); break; - case 254 /* ShorthandPropertyAssignment */: - result = reduceNode(node.name, f, result); - result = reduceNode(node.objectAssignmentInitializer, f, result); + case 258 /* ShorthandPropertyAssignment */: + result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.objectAssignmentInitializer, cbNode, result); + break; + case 259 /* SpreadAssignment */: + result = reduceNode(node.expression, cbNode, result); break; // Top-level nodes - case 256 /* SourceFile */: - result = ts.reduceLeft(node.statements, f, result); + case 261 /* SourceFile */: + result = reduceNodes(node.statements, cbNodes, result); break; - case 288 /* PartiallyEmittedExpression */: - result = reduceNode(node.expression, f, result); + case 294 /* PartiallyEmittedExpression */: + result = reduceNode(node.expression, cbNode, result); break; default: var edgeTraversalPath = nodeEdgeTraversalMap[kind]; @@ -40521,8 +44395,8 @@ var ts; var value = node[edge.name]; if (value !== undefined) { result = ts.isArray(value) - ? ts.reduceLeft(value, f, result) - : f(result, value); + ? reduceNodes(value, cbNodes, result) + : cbNode(result, value); } } } @@ -40532,9 +44406,10 @@ var ts; } ts.reduceEachChild = reduceEachChild; function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); var visited = visitor(node); if (visited === node) { return node; @@ -40583,6 +44458,7 @@ var ts; // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; + aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -40615,198 +44491,236 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, ts.isStatement, start); + if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { + statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements); + } + var declarations = context.endLexicalEnvironment(); + return ts.createNodeArray(ts.concatenate(statements, declarations), statements); + } + ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + function visitParameterList(nodes, visitor, context) { + context.startLexicalEnvironment(); + var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + ts.visitParameterList = visitParameterList; + function visitFunctionBody(node, visitor, context) { + context.resumeLexicalEnvironment(); + var updated = visitNode(node, visitor, ts.isConciseBody); + var declarations = context.endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(updated); + var statements = mergeLexicalEnvironment(block.statements, declarations); + return ts.updateBlock(block, statements); + } + return updated; + } + ts.visitFunctionBody = visitFunctionBody; function visitEachChild(node, visitor, context) { if (node === undefined) { return undefined; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 138 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) { return node; } // We do not yet support types. - if ((kind >= 154 /* TypePredicate */ && kind <= 166 /* LiteralType */)) { + if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) { return node; } switch (node.kind) { - case 198 /* SemicolonClassElement */: - case 201 /* EmptyStatement */: - case 193 /* OmittedExpression */: - case 217 /* DebuggerStatement */: + case 203 /* SemicolonClassElement */: + case 206 /* EmptyStatement */: + case 198 /* OmittedExpression */: + case 222 /* DebuggerStatement */: // No need to visit nodes with no children. return node; // Names - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 142 /* Parameter */: - return ts.updateParameterDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 144 /* Parameter */: + return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); // Type member - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); - case 147 /* MethodDeclaration */: - return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 148 /* Constructor */: - return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 149 /* GetAccessor */: - return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 150 /* SetAccessor */: - return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); + case 149 /* MethodDeclaration */: + return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 150 /* Constructor */: + return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); + case 151 /* GetAccessor */: + return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 152 /* SetAccessor */: + return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context)); // Binding patterns - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement)); - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement)); - case 169 /* BindingElement */: - return ts.updateBindingElement(node, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); + case 174 /* BindingElement */: + return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); // Expression - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression)); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); - case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); - case 178 /* ParenthesizedExpression */: + case 181 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 183 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 179 /* FunctionExpression */: - return ts.updateFunctionExpression(node, visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 180 /* ArrowFunction */: - return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isConciseBody, /*optional*/ true), context.endLexicalEnvironment())); - case 181 /* DeleteExpression */: + case 184 /* FunctionExpression */: + return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 185 /* ArrowFunction */: + return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 186 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 182 /* TypeOfExpression */: + case 187 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 183 /* VoidExpression */: + case 188 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 184 /* AwaitExpression */: + case 189 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression)); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 186 /* PostfixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); - case 190 /* YieldExpression */: + case 194 /* TemplateExpression */: + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + case 195 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191 /* SpreadElementExpression */: + case 196 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc - case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + case 202 /* TemplateSpan */: + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 199 /* Block */: + case 204 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, /*optional*/ true, liftToBlock)); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true)); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true)); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock)); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, /*optional*/ true), visitNode(node.finallyBlock, visitor, ts.isBlock, /*optional*/ true)); - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true)); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration)); - case 220 /* FunctionDeclaration */: - return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), (context.startLexicalEnvironment(), visitNodes(node.parameters, visitor, ts.isParameter)), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), mergeFunctionBodyLexicalEnvironment(visitNode(node.body, visitor, ts.isFunctionBody, /*optional*/ true), context.endLexicalEnvironment())); - case 221 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context)); + case 226 /* ClassDeclaration */: return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true)); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 233 /* NamedImports */: + case 238 /* NamedImports */: return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier)); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, /*optional*/ true)); - case 237 /* NamedExports */: + case 242 /* NamedExports */: return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier)); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier)); // JSX - case 241 /* JsxElement */: + case 246 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike)); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 249 /* CaseClause */: + case 253 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement)); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement)); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); + case 259 /* SpreadAssignment */: + return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Top-level nodes - case 256 /* SourceFile */: - context.startLexicalEnvironment(); - return ts.updateSourceFileNode(node, ts.createNodeArray(ts.concatenate(visitNodes(node.statements, visitor, ts.isStatement), context.endLexicalEnvironment()), node.statements)); + case 261 /* SourceFile */: + return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); default: var updated = void 0; @@ -40835,6 +44749,15 @@ var ts; // return node; } ts.visitEachChild = visitEachChild; + function mergeLexicalEnvironment(statements, declarations) { + if (!ts.some(declarations)) { + return statements; + } + return ts.isNodeArray(statements) + ? ts.createNodeArray(ts.concatenate(statements, declarations), statements) + : ts.addRange(statements, declarations); + } + ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function mergeFunctionBodyLexicalEnvironment(body, declarations) { if (body && declarations !== undefined && declarations.length > 0) { if (ts.isBlock(body)) { @@ -40887,13 +44810,25 @@ var ts; if (node === undefined) { return 0 /* None */; } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + if (node.transformFlags & 536870912 /* HasComputedFlags */) { + return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } - else { - var subtreeFlags = aggregateTransformFlagsForSubtree(node); - return ts.computeTransformFlagsForNode(node, subtreeFlags); + var subtreeFlags = aggregateTransformFlagsForSubtree(node); + return ts.computeTransformFlagsForNode(node, subtreeFlags); + } + function aggregateTransformFlagsForNodeArray(nodes) { + if (nodes === undefined) { + return 0 /* None */; } + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + return subtreeFlags; } /** * Aggregates the transform flags for the subtree of a node. @@ -40905,84 +44840,41 @@ var ts; return 0 /* None */; } // Aggregate the transform flags of each child. - return reduceEachChild(node, aggregateTransformFlagsForChildNode, 0 /* None */); + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } /** * Aggregates the TransformFlags of a child node with the TransformFlags of its * siblings. */ - function aggregateTransformFlagsForChildNode(transformFlags, child) { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags, node) { + return transformFlags | aggregateTransformFlagsForNode(node); } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 154 /* FirstTypeNode */ && kind <= 166 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 170 /* ArrayLiteralExpression */: - return 537133909 /* ArrayLiteralOrCallOrNewExcludes */; - case 225 /* ModuleDeclaration */: - return 546335573 /* ModuleExcludes */; - case 142 /* Parameter */: - return 538968917 /* ParameterExcludes */; - case 180 /* ArrowFunction */: - return 550710101 /* ArrowFunctionExcludes */; - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - return 550726485 /* FunctionExcludes */; - case 219 /* VariableDeclarationList */: - return 538968917 /* VariableDeclarationListExcludes */; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - return 537590613 /* ClassExcludes */; - case 148 /* Constructor */: - return 550593365 /* ConstructorExcludes */; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return 550593365 /* MethodOrAccessorExcludes */; - case 117 /* AnyKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 132 /* StringKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 141 /* TypeParameter */: - case 144 /* PropertySignature */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 171 /* ObjectLiteralExpression */: - return 537430869 /* ObjectLiteralExcludes */; - default: - return 536871765 /* NodeExcludes */; - } + function aggregateTransformFlagsForChildNodes(transformFlags, nodes) { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } var Debug; (function (Debug) { Debug.failNotOptional = Debug.shouldAssert(1 /* Normal */) ? function (message) { return Debug.assert(false, message || "Node not optional."); } - : function (message) { }; + : ts.noop; Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } - : function (node, message) { }; + : ts.noop; + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; Debug.assertNode = Debug.shouldAssert(1 /* Normal */) ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } - : function (node, test, message) { }; + : ts.noop; + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + : ts.noop; + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + : ts.noop; + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + : ts.noop; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -41004,334 +44896,348 @@ var ts; /*@internal*/ var ts; (function (ts) { + var FlattenLevel; + (function (FlattenLevel) { + FlattenLevel[FlattenLevel["All"] = 0] = "All"; + FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; + })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); /** - * Flattens a destructuring assignment expression. + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. * - * @param root The destructuring assignment expression. - * @param needsValue Indicates whether the value from the right-hand-side of the - * destructuring assignment is needed as part of a larger expression. - * @param recordTempVariable A callback used to record new temporary variables. - * @param visitor An optional visitor to use to visit expressions. + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. */ - function flattenDestructuringAssignment(context, node, needsValue, recordTempVariable, visitor) { - if (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { - var right = node.right; - if (ts.isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } + function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; - var value = node.right; - var expressions = []; - if (needsValue) { - // If the right-hand value of the destructuring assignment needs to be preserved (as - // is the case when the destructuring assignmen) is part of a larger expression), - // then we need to cache the right-hand value. - // - // The source map location for the assignment should point to the entire binary - // expression. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor); + var value; + if (ts.isDestructuringAssignment(node)) { + value = node.right; + while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (ts.isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - else if (ts.nodeIsSynthesized(node)) { - // Generally, the source map location for a destructuring assignment is the root - // expression. - // - // However, if the root expression is synthesized (as in the case - // of the initializer when transforming a ForOfStatement), then the source map - // location should point to the right-hand value of the expression. - location = value; + var expressions; + var flattenContext = { + context: context, + level: level, + hoistTempVariables: true, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor: visitor + }; + if (value) { + value = ts.visitNode(value, visitor, ts.isExpression); + if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); - if (needsValue) { + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); + if (value && needsValue) { + if (!ts.some(expressions)) { + return value; + } expressions.push(value); } - var expression = ts.inlineExpressions(expressions); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location) { - var expression = ts.createAssignment(name, value, location); + return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); + function emitExpression(expression) { // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); - expressions.push(expression); + expressions = ts.append(expressions, expression); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression); + var expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location); + expression.original = original; + emitExpression(expression); } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; /** - * Flattens binding patterns in a parameter declaration. + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * - * @param node The ParameterDeclaration to flatten. - * @param value The rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. */ - function flattenParameterDestructuring(context, node, value, visitor) { + function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + var pendingExpressions; + var pendingDeclarations = []; var declarations = []; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); + var flattenContext = { + context: context, + level: level, + hoistTempVariables: hoistTempVariables, + emitExpression: emitExpression, + emitBindingOrAssignment: emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor: visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + var value = ts.inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); + ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_30 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name_30, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2); + variable.original = original; + if (ts.isIdentifier(name_30)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); + } + ts.aggregateTransformFlags(variable); + declarations.push(variable); + } return declarations; - function emitAssignment(name, value, location) { - var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); - ts.aggregateTransformFlags(declaration); - declarations.push(declaration); + function emitExpression(value) { + pendingExpressions = ts.append(pendingExpressions, value); } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(/*recordTempVariable*/ undefined); - emitAssignment(name, value, location); - return name; + function emitBindingOrAssignment(target, value, location, original) { + ts.Debug.assertNode(target, ts.isBindingName); + if (pendingExpressions) { + value = ts.inlineExpressions(ts.append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original }); } } - ts.flattenParameterDestructuring = flattenParameterDestructuring; + ts.flattenDestructuringBinding = flattenDestructuringBinding; /** - * Flattens binding patterns in a variable declaration. + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. * - * @param node The VariableDeclaration to flatten. - * @param value An optional rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. */ - function flattenVariableDestructuring(context, node, value, visitor, recordTempVariable) { - var declarations = []; - var pendingAssignments; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - return declarations; - function emitAssignment(name, value, location, original) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = ts.inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); - declaration.original = original; - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); - declarations.push(declaration); - ts.aggregateTransformFlags(declaration); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - if (recordTempVariable) { - var assignment = ts.createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, /*original*/ undefined); - } - return name; - } - } - ts.flattenVariableDestructuring = flattenVariableDestructuring; - /** - * Flattens binding patterns in a variable declaration and transforms them into an expression. - * - * @param node The VariableDeclaration to flatten. - * @param recordTempVariable A callback used to record new temporary variables. - * @param nameSubstitution An optional callback used to substitute binding names. - * @param visitor An optional visitor to use to visit expressions. - */ - function flattenVariableDestructuringToExpression(context, node, recordTempVariable, nameSubstitution, visitor) { - var pendingAssignments = []; - flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - var expression = ts.inlineExpressions(pendingAssignments); - ts.aggregateTransformFlags(expression); - return expression; - function emitAssignment(name, value, location, original) { - var left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - function emitTempVariableAssignment(value, location) { - var name = ts.createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, /*original*/ undefined); - return name; - } - function emitPendingAssignment(name, value, location, original) { - var expression = ts.createAssignment(name, value, location); - expression.original = original; - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); - pendingAssignments.push(expression); - return expression; - } - } - ts.flattenVariableDestructuringToExpression = flattenVariableDestructuringToExpression; - function flattenDestructuring(context, root, value, location, emitAssignment, emitTempVariableAssignment, visitor) { - if (value && visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); - } - if (ts.isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - function emitDestructuringAssignment(bindingTarget, value, location) { - // When emitting target = value use source map node to highlight, including any temporary assignments needed for this - var target; - if (ts.isShorthandPropertyAssignment(bindingTarget)) { - var initializer = visitor - ? ts.visitNode(bindingTarget.objectAssignmentInitializer, visitor, ts.isExpression) - : bindingTarget.objectAssignmentInitializer; - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - target = bindingTarget.name; - } - else if (ts.isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === 56 /* EqualsToken */) { - var initializer = visitor - ? ts.visitNode(bindingTarget.right, visitor, ts.isExpression) - : bindingTarget.right; - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - if (target.kind === 171 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === 170 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value, location); - } - else { - var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); - emitAssignment(name_26, value, location, /*original*/ undefined); - } - } - function emitObjectLiteralAssignment(target, value, location) { - var properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var p = properties_6[_i]; - if (p.kind === 253 /* PropertyAssignment */ || p.kind === 254 /* ShorthandPropertyAssignment */) { - var propName = p.name; - var target_1 = p.kind === 254 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - // Assignment for target = value.propName should highligh whole property, hence use p as source map node - emitDestructuringAssignment(target_1, createDestructuringPropertyAccess(value, propName), p); - } - } - } - function emitArrayLiteralAssignment(target, value, location) { - var elements = target.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var e = elements[i]; - if (e.kind !== 193 /* OmittedExpression */) { - // Assignment for target = value.propName should highligh whole property, hence use e as source map node - if (e.kind !== 191 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, ts.createElementAccess(value, ts.createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment(e.expression, ts.createArraySlice(value, i), e); - } - } - } - } - function emitBindingElement(target, value) { - // Any temporary assignments needed to emit target = value should point to target - var initializer = visitor ? ts.visitNode(target.initializer, visitor, ts.isExpression) : target.initializer; + function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + if (!skipInitializer) { + var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer value = ts.createVoidZero(); } - var name = target.name; - if (ts.isBindingPattern(name)) { - var elements = name.elements; - var numElements = elements.length; - if (numElements !== 1) { - // For anything other than a single-element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. Additionally, if we have zero elements - // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, - // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment); - } - for (var i = 0; i < numElements; i++) { - var element = elements[i]; - if (ts.isOmittedExpression(element)) { - continue; - } - else if (name.kind === 167 /* ObjectBindingPattern */) { - // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, ts.createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, ts.createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - function createDefaultValueCheck(value, defaultValue, location) { - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - return ts.createConditional(ts.createStrictEquality(value, ts.createVoidZero()), ts.createToken(53 /* QuestionToken */), defaultValue, ts.createToken(54 /* ColonToken */), value); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } - /** - * Creates either a PropertyAccessExpression or an ElementAccessExpression for the - * right-hand side of a transformed destructuring assignment. - * - * @param expression The right-hand expression that is the source of the property. - * @param propertyName The destructuring property name. - */ - function createDestructuringPropertyAccess(expression, propertyName) { - if (ts.isComputedPropertyName(propertyName)) { - return ts.createElementAccess(expression, ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)); - } - else if (ts.isLiteralExpression(propertyName)) { - var clone_2 = ts.getSynthesizedClone(propertyName); - clone_2.text = ts.unescapeIdentifier(clone_2.text); - return ts.createElementAccess(expression, clone_2); - } - else { - if (ts.isGeneratedIdentifier(propertyName)) { - var clone_3 = ts.getSynthesizedClone(propertyName); - clone_3.text = ts.unescapeIdentifier(clone_3.text); - return ts.createPropertyAccess(expression, clone_3); + else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var computedTempVariables; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !ts.isComputedPropertyName(propertyName)) { + bindingElements = ts.append(bindingElements, element); } else { - return ts.createPropertyAccess(expression, ts.createIdentifier(ts.unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (ts.isComputedPropertyName(propertyName)) { + computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + var numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + var bindingElements; + var restContainingElements; + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = ts.append(restContainingElements, [temp, element]); + bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = ts.append(bindingElements, element); + } + } + else if (ts.isOmittedExpression(element)) { + continue; + } + else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { + var rhsValue = ts.createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + var rhsValue = ts.createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) { + var _a = restContainingElements_1[_i], id = _a[0], element = _a[1]; + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); + } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return ts.createElementAccess(value, argumentExpression); + } + else if (ts.isStringOrNumericLiteral(propertyName)) { + var argumentExpression = ts.getSynthesizedClone(propertyName); + argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + return ts.createElementAccess(value, argumentExpression); + } + else { + var name_31 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + return ts.createPropertyAccess(value, name_31); } } /** @@ -41339,24 +45245,75 @@ var ts; * This function is useful to ensure that the expression's value can be read from in subsequent expressions. * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. * + * @param flattenContext Options used to control flattening. * @param value the expression whose value needs to be bound. * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; - * false if it is necessary to always emit an identifier. + * false if it is necessary to always emit an identifier. * @param location The location to use for source maps and comments. - * @param emitTempVariableAssignment A callback used to emit a temporary variable. - * @param visitor An optional callback used to visit the value. */ - function ensureIdentifier(value, reuseIdentifierExpressions, location, emitTempVariableAssignment, visitor) { + function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = ts.visitNode(value, visitor, ts.isExpression); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(ts.createAssignment(temp, value, location)); } - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; } } + function makeArrayBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isArrayBindingElement); + return ts.createArrayBindingPattern(elements); + } + function makeArrayAssignmentPattern(elements) { + return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement)); + } + function makeObjectBindingPattern(elements) { + ts.Debug.assertEachNode(elements, ts.isBindingElement); + return ts.createObjectBindingPattern(elements); + } + function makeObjectAssignmentPattern(elements) { + return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); + } + function makeBindingElement(name) { + return ts.createBindingElement(/*propertyName*/ undefined, /*dotDotDotToken*/ undefined, name); + } + function makeAssignmentElement(name) { + return name; + } + var restHelper = { + name: "typescript:rest", + scoped: false, + text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" + }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/ + function createRestCall(context, value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + var propertyNames = []; + var computedTempVariableOffset = 0; + for (var i = 0; i < elements.length - 1; i++) { + var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (ts.isComputedPropertyName(propertyName)) { + var temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); + } + else { + propertyNames.push(ts.createLiteral(propertyName)); + } + } + } + return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]); + } })(ts || (ts = {})); /// /// @@ -41374,13 +45331,11 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; - /** Enables substitutions for async methods with `super` calls. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["AsyncMethodsWithSuper"] = 4] = "AsyncMethodsWithSuper"; /* Enables substitutions for unqualified enum members */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,12 +45346,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(178 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; - var currentSourceFileExternalHelpersModuleName; + var currentScopeFirstDeclarationsOfName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. * They are persisted between each SourceFile transformation and should not be reset. @@ -41412,11 +45370,6 @@ var ts; * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; - /** - * This keeps track of containers where `super` is valid, for use with - * just-in-time substitution for `super` expressions inside of async methods. - */ - var currentSuperContainer; return transformSourceFile; /** * Transform TypeScript-specific syntax in a SourceFile. @@ -41424,7 +45377,14 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { - return ts.visitNode(node, visitor, ts.isSourceFile); + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } /** * Visits a node, saving and restoring state variables on the stack. @@ -41434,13 +45394,40 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node) { + switch (node.kind) { + case 261 /* SourceFile */: + case 232 /* CaseBlock */: + case 231 /* ModuleBlock */: + case 204 /* Block */: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 226 /* ClassDeclaration */: + case 225 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); + break; + } + } /** * General-purpose node visitor. * @@ -41455,10 +45442,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.kind === 256 /* SourceFile */) { - return visitSourceFile(node); - } - else if (node.transformFlags & 1 /* TypeScript */) { + if (node.transformFlags & 1 /* TypeScript */) { // This node is explicitly marked as TypeScript, so we should transform the node. return visitTypeScript(node); } @@ -41468,6 +45452,33 @@ var ts; } return node; } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + case 241 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } /** * Specialized visitor that visits the immediate children of a namespace. * @@ -41482,11 +45493,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 236 /* ExportDeclaration */ || - node.kind === 230 /* ImportDeclaration */ || - node.kind === 231 /* ImportClause */ || - (node.kind === 229 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 240 /* ExternalModuleReference */)) { + if (node.kind === 241 /* ExportDeclaration */ || + node.kind === 235 /* ImportDeclaration */ || + node.kind === 236 /* ImportClause */ || + (node.kind === 234 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 245 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -41516,25 +45527,34 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 145 /* PropertyDeclaration */: - case 153 /* IndexSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 147 /* MethodDeclaration */: + case 147 /* PropertyDeclaration */: + case 155 /* IndexSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 149 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 198 /* SemicolonClassElement */: + case 203 /* SemicolonClassElement */: return node; default: ts.Debug.failBadSyntaxKind(node); return undefined; } } + function modifierVisitor(node) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + return undefined; + } + else if (currentNamespace && node.kind === 83 /* ExportKeyword */) { + return undefined; + } + return node; + } /** * Branching visitor, visits a TypeScript syntax node. * @@ -41547,57 +45567,59 @@ var ts; return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 82 /* ExportKeyword */: - case 77 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 115 /* AbstractKeyword */: - case 118 /* AsyncKeyword */: - case 74 /* ConstKeyword */: - case 122 /* DeclareKeyword */: - case 128 /* ReadonlyKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 116 /* AbstractKeyword */: + case 75 /* ConstKeyword */: + case 123 /* DeclareKeyword */: + case 130 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 160 /* ArrayType */: - case 161 /* TupleType */: - case 159 /* TypeLiteral */: - case 154 /* TypePredicate */: - case 141 /* TypeParameter */: - case 117 /* AnyKeyword */: - case 120 /* BooleanKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 127 /* NeverKeyword */: - case 103 /* VoidKeyword */: - case 133 /* SymbolKeyword */: - case 157 /* ConstructorType */: - case 156 /* FunctionType */: - case 158 /* TypeQuery */: - case 155 /* TypeReference */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 164 /* ParenthesizedType */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 162 /* ArrayType */: + case 163 /* TupleType */: + case 161 /* TypeLiteral */: + case 156 /* TypePredicate */: + case 143 /* TypeParameter */: + case 118 /* AnyKeyword */: + case 121 /* BooleanKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 129 /* NeverKeyword */: + case 104 /* VoidKeyword */: + case 135 /* SymbolKeyword */: + case 159 /* ConstructorType */: + case 158 /* FunctionType */: + case 160 /* TypeQuery */: + case 157 /* TypeReference */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: + case 166 /* ParenthesizedType */: + case 167 /* ThisType */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 171 /* LiteralType */: // TypeScript type nodes are elided. - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: // TypeScript index signatures are elided. - case 143 /* Decorator */: + case 145 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. - case 145 /* PropertyDeclaration */: - // TypeScript property declarations are elided. - case 148 /* Constructor */: - // TypeScript constructors are transformed in `visitClassDeclaration`. + case 147 /* PropertyDeclaration */: + // TypeScript property declarations are elided. return undefined; - case 222 /* InterfaceDeclaration */: + case 150 /* Constructor */: + return visitConstructor(node); + case 227 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -41607,9 +45629,8 @@ var ts; // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassDeclaration(node); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -41619,37 +45640,36 @@ var ts; // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassExpression(node); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 147 /* MethodDeclaration */: - // TypeScript method declarations may be 'async', and may have decorators, modifiers + case 149 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 149 /* GetAccessor */: + case 151 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 150 /* SetAccessor */: - // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + case 152 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 220 /* FunctionDeclaration */: - // TypeScript function declarations may be 'async' + case 225 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: - // TypeScript function expressions may be 'async' + case 184 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 180 /* ArrowFunction */: - // TypeScript arrow functions may be 'async' + case 185 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 142 /* Parameter */: + case 144 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -41659,30 +45679,33 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 178 /* ParenthesizedExpression */: + case 183 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 177 /* TypeAssertionExpression */: - case 195 /* AsExpression */: + case 182 /* TypeAssertionExpression */: + case 200 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 196 /* NonNullExpression */: + case 179 /* CallExpression */: + return visitCallExpression(node); + case 180 /* NewExpression */: + return visitNewExpression(node); + case 201 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 184 /* AwaitExpression */: - // TypeScript 'await' expressions must be transformed. - return visitAwaitExpression(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 225 /* ModuleDeclaration */: + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 230 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -41690,51 +45713,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } } - /** - * Performs actions that should always occur immediately before visiting a node. - * - * @param node The node to visit. - */ - function onBeforeVisitNode(node) { - switch (node.kind) { - case 256 /* SourceFile */: - case 227 /* CaseBlock */: - case 226 /* ModuleBlock */: - case 199 /* Block */: - currentScope = node; - break; - } - } function visitSourceFile(node) { - currentSourceFile = node; - // If the source file requires any helpers and is an external module, and - // the importHelpers compiler option is enabled, emit a synthesized import - // statement for the helpers library. - if (node.flags & 31744 /* EmitHelperFlags */ - && compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); - var externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText); - var externalHelpersModuleImport = ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~8 /* Synthesized */; - statements.push(externalHelpersModuleImport); - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - node = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = ts.visitEachChild(node, visitor, context); - } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); - return node; + var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** * Tests whether we should emit a __decorate call for a class declaration. @@ -41770,7 +45751,6 @@ var ts; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var classAlias; // emit name if // - node has a name // - node has static initializers @@ -41779,38 +45759,22 @@ var ts; if (!name && staticProperties.length > 0) { name = ts.getGeneratedNameForNode(node); } - var statements = []; - if (!isDecoratedClass) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - var classDeclaration = ts.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), - /*location*/ node); - ts.setOriginalNode(classDeclaration, node); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); - } - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + var classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var statements = [classStatement]; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, /*noSourceMaps*/ true)); + addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); } // Write any decorators of the node. addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); // If the class is exported as part of a TypeScript namespace, emit the namespace export. // Otherwise, if the class was exported at the top level and was decorated, emit an export // declaration or export default for the class. @@ -41819,26 +45783,54 @@ var ts; } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(ts.createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, getLocalName(node))); + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } - return statements; + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param hasStaticProperties A value indicating whether the class has static properties. + */ + function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); + var emitFlags = ts.getEmitFlags(node); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + if (hasStaticProperties) { + emitFlags |= 32 /* NoTrailingSourceMap */; + } + ts.setOriginalNode(classDeclaration, node); + ts.setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; } /** * Transforms a decorated class declaration and appends the resulting statements. If * the class requires an alias to avoid issues with double-binding, the alias is returned. * + * @param statements A statement list to which to add the declaration. * @param node A ClassDeclaration node. * @param name The name of the class. - * @param hasExtendsClause A value indicating whether + * @param hasExtendsClause A value indicating whether the class has an extends clause. */ - function addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { // When we emit an ES6 class that has a class decorator, we must tailor the // emit to certain specific cases. // @@ -41873,20 +45865,20 @@ var ts; // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = C_1 = class C { // class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export { C }; + // | var C_1; // --------------------------------------------------------------------- // // If a class declaration is the default export of a module, we instead emit @@ -41915,59 +45907,31 @@ var ts; // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export default class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export default C; + // | var C_1; // --------------------------------------------------------------------- // var location = ts.moveRangePastDecorators(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // ... = class ${name} ${heritageClauses} { // ${members} // } - var classExpression = ts.setOriginalNode(ts.createClassExpression( - /*modifiers*/ undefined, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), - /*location*/ location), node); - if (!name) { - name = ts.getGeneratedNameForNode(node); - } - // Record an alias to avoid class double-binding. - var classAlias; - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - } - var declaredName = getDeclarationName(node, /*allowComments*/ true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = transformClassMembers(node, hasExtendsClause); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members, location); + ts.setOriginalNode(classExpression, node); // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference // or decoratedClassAlias if the class contain self-reference. - var transformedClassExpression = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(classAlias || declaredName, - /*type*/ undefined, classExpression) - ]), - /*location*/ location); - setCommentRange(transformedClassExpression, node); - statements.push(ts.setOriginalNode( - /*node*/ transformedClassExpression, - /*original*/ node)); - if (classAlias) { - // We emit the class alias as a `let` declaration here so that it has the same - // TDZ as the class. - // let ${declaredName} = ${decoratedClassAlias} - statements.push(ts.setOriginalNode(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createLetDeclarationList([ - ts.createVariableDeclaration(declaredName, - /*type*/ undefined, classAlias) - ]), - /*location*/ location), - /*original*/ node)); - } - return classAlias; + var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location); + ts.setOriginalNode(statement, node); + ts.setCommentRange(statement, node); + return statement; } /** * Transforms a class expression with TypeScript syntax into compatible ES6. @@ -41981,7 +45945,7 @@ var ts; function visitClassExpression(node) { var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, heritageClauses !== undefined); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84 /* ExtendsKeyword */; })); var classExpression = ts.setOriginalNode(ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members, @@ -41996,9 +45960,9 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 32768 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); - ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } @@ -42030,7 +45994,7 @@ var ts; // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 131072 /* ContainsParameterPropertyAssignments */; + var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -42038,7 +46002,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + var body = transformConstructorBody(node, constructor, hasExtendsClause); // constructor(${parameters}) { // ${body} // } @@ -42070,9 +46034,8 @@ var ts; // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. // Instead, we'll avoid using a rest parameter and spread into the super call as // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". - return constructor - ? ts.visitNodes(constructor.parameters, visitor, ts.isParameter) - : []; + return ts.visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } /** * Transforms (or creates) a constructor body for a class with parameter property @@ -42081,13 +46044,11 @@ var ts; * @param node The current class. * @param constructor The current class constructor. * @param hasExtendsClause A value indicating whether the class has an extends clause. - * @param parameters The transformed parameters for the constructor. */ - function transformConstructorBody(node, constructor, hasExtendsClause, parameters) { + function transformConstructorBody(node, constructor, hasExtendsClause) { var statements = []; var indexOfFirstStatement = 0; - // The body of a constructor is a new lexical environment - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); // Add parameters with property assignments. Transforms this: @@ -42124,16 +46085,17 @@ var ts; // } // var properties = getInitializedProperties(node, /*isStatic*/ false); - addInitializedPropertyStatements(statements, node, properties, ts.createThis()); + addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { // The class already had a constructor, so we should add the existing statements, skipping the initial super call. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } // End the lexical environment. ts.addRange(statements, endLexicalEnvironment()); - return ts.setMultiLine(ts.createBlock(ts.createNodeArray(statements, + return ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), - /*location*/ constructor ? constructor.body : undefined), true); + /*location*/ constructor ? constructor.body : undefined, + /*multiLine*/ true); } /** * Adds super call and preceding prologue directives into the list of statements. @@ -42151,7 +46113,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +46147,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 1536 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42224,41 +46186,39 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 145 /* PropertyDeclaration */ + return member.kind === 147 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } /** * Generates assignment statements for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function addInitializedPropertyStatements(statements, node, properties, receiver) { - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; - var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + function addInitializedPropertyStatements(statements, properties, receiver) { + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; + var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } /** * Generates assignment expressions for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function generateInitializedPropertyExpressions(node, properties, receiver) { + function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { - var property = properties_8[_i]; - var expression = transformInitializedProperty(node, property, receiver); + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; + var expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42266,11 +46226,10 @@ var ts; /** * Transforms a property initializer into an assignment statement. * - * @param node The class containing the property. * @param property The property declaration. * @param receiver The object receiving the property assignment. */ - function transformInitializedProperty(node, property, receiver) { + function transformInitializedProperty(property, receiver) { var propertyName = visitPropertyNameOfClassElement(property); var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -42362,12 +46321,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -42384,10 +46343,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -42428,14 +46388,14 @@ var ts; * @param node The declaration node. * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } /** @@ -42482,7 +46442,7 @@ var ts; */ function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -42502,13 +46462,13 @@ var ts; // __metadata("design:type", Function), // __metadata("design:paramtypes", [Object]), // __metadata("design:returntype", void 0) - // ], C.prototype, "method", undefined); + // ], C.prototype, "method", null); // // The emit for an accessor is: // // __decorate([ // dec - // ], C.prototype, "accessor", undefined); + // ], C.prototype, "accessor", null); // // The emit for a property is: // @@ -42519,12 +46479,12 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 145 /* PropertyDeclaration */ + ? member.kind === 147 /* PropertyDeclaration */ ? ts.createVoidZero() : ts.createNull() : undefined; - var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); + ts.setEmitFlags(helper, 1536 /* NoComments */); return helper; } /** @@ -42532,8 +46492,8 @@ var ts; * * @param node The class node. */ - function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { - var expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } @@ -42543,33 +46503,19 @@ var ts; * * @param node The class node. */ - function generateConstructorDecorationExpression(node, decoratedClassAlias) { + function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = C_1 = __decorate([dec], C); - // - if (decoratedClassAlias) { - var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); - var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); - return result; - } - else { - var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); - return result; - } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = createDecorateHelper(context, decoratorExpressions, localName); + var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); + return expression; } /** * Transforms a decorator into an expression. @@ -42591,9 +46537,9 @@ var ts; expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 1536 /* NoComments */); expressions.push(helper); } } @@ -42605,41 +46551,41 @@ var ts; * @param node The declaration node. * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(ts.createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); } } } @@ -42652,10 +46598,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */ - || kind === 145 /* PropertyDeclaration */; + return kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */ + || kind === 147 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -42665,7 +46611,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 147 /* MethodDeclaration */; + return node.kind === 149 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -42675,12 +46621,16 @@ var ts; * @param node The node to test. */ function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 221 /* ClassDeclaration */ - || kind === 192 /* ClassExpression */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */; + switch (node.kind) { + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return true; + } + return false; } /** * Serializes the type of a node for use with decorator type metadata. @@ -42689,43 +46639,26 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: - case 149 /* GetAccessor */: + case 147 /* PropertyDeclaration */: + case 144 /* Parameter */: + case 151 /* GetAccessor */: return serializeTypeNode(node.type); - case 150 /* SetAccessor */: + case 152 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 147 /* MethodDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 149 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node) { - if (node && node.kind === 160 /* ArrayType */) { - return node.elementType; - } - else if (node && node.kind === 155 /* TypeReference */) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } /** * Serializes the types of the parameters of a node for use with decorator type metadata. * * @param node The node that should have its parameter types serialized. */ - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -42733,7 +46666,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -42741,7 +46674,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -42750,6 +46683,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } /** * Serializes the return type of a node for use with decorator type metadata. * @@ -42787,49 +46729,80 @@ var ts; return ts.createIdentifier("Object"); } switch (node.kind) { - case 103 /* VoidKeyword */: + case 104 /* VoidKeyword */: return ts.createVoidZero(); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return ts.createIdentifier("Function"); - case 160 /* ArrayType */: - case 161 /* TupleType */: + case 162 /* ArrayType */: + case 163 /* TupleType */: return ts.createIdentifier("Array"); - case 154 /* TypePredicate */: - case 120 /* BooleanKeyword */: + case 156 /* TypePredicate */: + case 121 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 132 /* StringKeyword */: + case 134 /* StringKeyword */: return ts.createIdentifier("String"); - case 166 /* LiteralType */: + case 171 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 85 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 130 /* NumberKeyword */: + case 132 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 133 /* SymbolKeyword */: - return languageVersion < 2 /* ES6 */ + case 135 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return serializeTypeReferenceNode(node); - case 158 /* TypeQuery */: - case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: - case 117 /* AnyKeyword */: - case 165 /* ThisType */: + case 165 /* IntersectionType */: + case 164 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 70 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough + case 160 /* TypeQuery */: + case 168 /* TypeOperator */: + case 169 /* IndexedAccessType */: + case 170 /* MappedType */: + case 161 /* TypeLiteral */: + case 118 /* AnyKeyword */: + case 167 /* ThisType */: break; default: ts.Debug.failBadSyntaxKind(node); @@ -42848,7 +46821,7 @@ var ts; case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictEquality(ts.createTypeOf(ts.createAssignment(temp, serialized)), ts.createLiteral("function")), temp), ts.createIdentifier("Object")); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: @@ -42862,7 +46835,7 @@ var ts; case ts.TypeReferenceSerializationKind.ArrayLikeType: return ts.createIdentifier("Array"); case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ES6 */ + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); case ts.TypeReferenceSerializationKind.TypeWithCallSignature: @@ -42883,18 +46856,18 @@ var ts; */ function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. - var name_27 = ts.getMutableClone(node); - name_27.flags &= ~8 /* Synthesized */; - name_27.original = undefined; - name_27.parent = currentScope; + var name_32 = ts.getMutableClone(node); + name_32.flags &= ~8 /* Synthesized */; + name_32.original = undefined; + name_32.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_27), ts.createLiteral("undefined")), name_27); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_32), ts.createLiteral("undefined")), name_32); } - return name_27; - case 139 /* QualifiedName */: + return name_32; + case 141 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -42907,7 +46880,7 @@ var ts; */ function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 69 /* Identifier */) { + if (node.left.kind === 70 /* Identifier */) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { @@ -42924,7 +46897,7 @@ var ts; * available. */ function getGlobalSymbolNameWithFallback() { - return ts.createConditional(ts.createStrictEquality(ts.createTypeOf(ts.createIdentifier("Symbol")), ts.createLiteral("function")), ts.createToken(53 /* QuestionToken */), ts.createIdentifier("Symbol"), ts.createToken(54 /* ColonToken */), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } /** * Gets an expression that represents a property name. For a computed property, a @@ -42940,7 +46913,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeIdentifier(name.text)); } else { return ts.getSynthesizedClone(name); @@ -42978,9 +46951,9 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 83 /* ExtendsKeyword */) { + if (node.token === 84 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.createHeritageClause(83 /* ExtendsKeyword */, types, node); + return ts.createHeritageClause(84 /* ExtendsKeyword */, types, node); } return undefined; } @@ -43006,12 +46979,18 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + return ts.visitEachChild(node, visitor, context); + } /** * Visits a method declaration of a class. * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node is marked as abstract, public, private, protected, or readonly * - The node has both a decorator and a computed property name * * @param node The method node. @@ -43020,17 +46999,17 @@ var ts; if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var method = ts.createMethod( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(method, node); - return method; + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -43054,16 +47033,16 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createGetAccessor( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Visits a set accessor declaration of a class. @@ -43078,23 +47057,23 @@ var ts; if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var accessor = ts.createSetAccessor( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), - /*location*/ node); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); - ts.setOriginalNode(accessor, node); - return accessor; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + } + return updated; } /** * Visits a function declaration. * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked async * - The node is exported from a TypeScript namespace + * - The node has decorators * * @param node The function node. */ @@ -43102,24 +47081,22 @@ var ts; if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var func = ts.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isNamespaceExport(node)) { - var statements = [func]; + var statements = [updated]; addExportMemberAssignment(statements, node); return statements; } - return func; + return updated; } /** * Visits a function expression node. * * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations * * @param node The function expression node. */ @@ -43127,111 +47104,21 @@ var ts; if (ts.nodeIsMissing(node.body)) { return ts.createOmittedExpression(); } - var func = ts.createFunctionExpression(node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); - return func; + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } /** * @remarks * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations */ function visitArrowFunction(node) { - var func = ts.createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, node.equalsGreaterThanToken, transformConciseBody(node), - /*location*/ node); - ts.setOriginalNode(func, node); - return func; - } - function transformFunctionBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformFunctionBodyWorker(node.body); - } - function transformFunctionBodyWorker(body, start) { - if (start === void 0) { start = 0; } - var savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - var statements = ts.visitNodes(body.statements, visitor, ts.isStatement, start); - var visited = ts.updateBlock(body, statements); - var declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - function transformConciseBody(node) { - if (ts.isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); - } - function transformConciseBodyWorker(body, forceBlockFunctionBody) { - if (ts.isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - var visited = ts.visitNode(body, visitor, ts.isConciseBody); - var declarations = endLexicalEnvironment(); - var merged = ts.mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !ts.isBlock(merged)) { - return ts.createBlock([ - ts.createReturn(merged) - ]); - } - else { - return merged; - } - } - } - function getPromiseConstructor(type) { - var typeName = ts.getEntityNameFromTypeNode(type); - if (typeName && ts.isEntityName(typeName)) { - var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - return undefined; - } - function transformAsyncFunctionBody(node) { - var promiseConstructor = languageVersion < 2 /* ES6 */ ? getPromiseConstructor(node.type) : undefined; - var isArrowFunction = node.kind === 180 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - if (!isArrowFunction) { - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); - var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES6 */) { - if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); - } - else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); - } - } - return block; - } - else { - return ts.createAwaiterHelper(currentSourceFileExternalHelpersModuleName, hasLexicalArguments, promiseConstructor, transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)); - } + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + return updated; } /** * Visits a parameter declaration node. @@ -43244,10 +47131,10 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameterDeclaration( + var parameter = ts.createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, @@ -43256,9 +47143,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); return parameter; } /** @@ -43284,24 +47171,17 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getNamespaceMemberNameWithSourceMapsAndWithoutComments, visitor); + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); } else { return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression), /*location*/ node); } } - /** - * Visits an await expression. - * - * This function will be called any time a TypeScript await expression is encountered. - * - * @param node The await expression node. - */ - function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.createYield( - /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), - /*location*/ node), node); + function visitVariableDeclaration(node) { + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } /** * Visits a parenthesized expression that contains either a type assertion or an `as` @@ -43340,6 +47220,14 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression); return ts.createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node) { + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + function visitNewExpression(node) { + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } /** * Determines whether to emit an enum declaration. * @@ -43350,20 +47238,6 @@ var ts; || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); - } - /* - * Adds a trailing VariableStatement for an enum or module declaration. - */ - function addVarForEnumExportedFromNamespace(statements, node) { - var statement = ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), - /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); - statements.push(statement); - } /** * Visits an enum declaration. * @@ -43378,15 +47252,14 @@ var ts; var statements = []; // We request to be advised when the printer is about to print this node. This allows // us to set up the correct state for later substitutions. - var emitFlags = 64 /* AdviseOnEmitNode */; + var emitFlags = 2 /* AdviseOnEmitNode */; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384 /* NoLeadingComments */; + emitFlags |= 512 /* NoLeadingComments */; } } // `parameterName` is the declaration name used inside of the enum. @@ -43394,24 +47267,36 @@ var ts; // `containerName` is the expression used inside of the enum for assignments. var containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) + var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) + moduleArg = ts.createAssignment(localName, moduleArg); + } // (function (x) { // x[x["y"] = 0] = "y"; // ... // })(x || (x = {})); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), - /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), + /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); - } + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } /** @@ -43473,58 +47358,98 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.System); } - function isES6ExportedDeclaration(node) { - return isExternalModuleExport(node) - && moduleKind === ts.ModuleKind.ES6; + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } } - function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_33 = node.symbol && node.symbol.name; + if (name_33) { + return currentScopeFirstDeclarationsOfName[name_33] === node; + } + } + return false; } /** * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements, node) { // Emit a variable statement for the module. - var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) - ? ts.visitNodes(node.modifiers, visitor, ts.isModifier) - : undefined, [ - ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), [ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) ]); - ts.setOriginalNode(statement, /*original*/ node); - // Adjust the source map emit to match the old emitter. - if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 229 /* EnumDeclaration */) { + ts.setSourceMapRange(statement.declarationList, node); + } + else { + ts.setSourceMapRange(statement, node); + } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 2097152 /* HasEndOfDeclarationMarker */); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + var mergeMarker = ts.createMergeDeclarationMarker(statement); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 2097152 /* HasEndOfDeclarationMarker */); + statements.push(mergeMarker); + return false; } - // Trailing comments for module declaration should be emitted after the function closure - // instead of the variable statement: - // - // /** Module comment*/ - // module m1 { - // function foo4Export() { - // } - // } // trailing comment module - // - // Should emit: - // - // /** Module comment*/ - // var m1; - // (function (m1) { - // function foo4Export() { - // } - // })(m1 || (m1 = {})); // trailing comment module - // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); - statements.push(statement); } /** * Visits a module declaration node. @@ -43542,15 +47467,14 @@ var ts; var statements = []; // We request to be advised when the printer is about to print this node. This allows // us to set up the correct state for later substitutions. - var emitFlags = 64 /* AdviseOnEmitNode */; + var emitFlags = 2 /* AdviseOnEmitNode */; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 16384 /* NoLeadingComments */; + emitFlags |= 512 /* NoLeadingComments */; } } // `parameterName` is the declaration name used inside of the namespace. @@ -43558,13 +47482,15 @@ var ts; // `containerName` is the expression used inside of the namespace for exports. var containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - var exportName = getExportName(node); + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x || (x = {}) // exports.x || (exports.x = {}) var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); - if (ts.hasModifier(node, 1 /* Export */) && !isES6ExportedDeclaration(node)) { + if (hasNamespaceQualifiedExportName(node)) { // `localName` is the expression used within this node's containing scope for any local references. - var localName = getLocalName(node); + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x = (exports.x || (exports.x = {})) moduleArg = ts.createAssignment(localName, moduleArg); } @@ -43572,15 +47498,19 @@ var ts; // x_1.y = ...; // })(x || (x = {})); var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } /** @@ -43591,14 +47521,16 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 226 /* ModuleBlock */) { + if (body.kind === 231 /* ModuleBlock */) { ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); statementsLocation = body.statements; blockLocation = body; @@ -43619,6 +47551,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43643,17 +47576,127 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + if (body.kind !== 231 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node) { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + // Elide the declaration if the import clause was elided. + var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, /*optional*/ true); + return importClause + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. + var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, /*optional*/ true); + return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; + } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node) { + if (node.kind === 237 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); + return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; + } + } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; + } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node) { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + // Elide the export declaration if all of its named exports are elided. + var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, /*optional*/ true); + return exportClause + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) + : undefined; + } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. + var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); + return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; + } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } /** * Determines whether to emit an import equals declaration. * @@ -43674,19 +47717,22 @@ var ts; */ function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { - return ts.visitEachChild(node, visitor, context); + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? ts.visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; - return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(node.name, - /*type*/ undefined, moduleReference) + return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) ]), node), node); } else { @@ -43735,45 +47781,27 @@ var ts; return ts.createStatement(expression, /*location*/ undefined); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.createStatement(ts.createAssignment(getNamespaceMemberName(exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); + return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location); } - function createExternalModuleExport(exportName) { - return ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports([ - ts.createExportSpecifier(exportName) - ])); - } - function getNamespaceMemberName(name, allowComments, allowSourceMaps) { - var qualifiedName = ts.createPropertyAccess(currentNamespaceContainerName, ts.getSynthesizedClone(name), /*location*/ name); - var emitFlags; - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; - } - if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName, exportValue, location) { + return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return getNamespaceMemberName(name, /*allowComments*/ false, /*allowSourceMaps*/ true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); } /** * Gets the declaration name used inside of a namespace or enum. */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43784,89 +47812,31 @@ var ts; return ts.getGeneratedNameForNode(node); } /** - * Gets the local name for a declaration for use in expressions. - * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. */ - function getLocalName(node, noSourceMaps, allowComments) { - return getDeclarationName(node, allowComments, !noSourceMaps, 262144 /* LocalName */); - } - /** - * Gets the export name for a declaration for use in expressions. - * - * An export name will *always* be prefixed with an module or namespace export modifier - * like "exports." if one is required. - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. - */ - function getExportName(node, noSourceMaps, allowComments) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - return getDeclarationName(node, allowComments, !noSourceMaps, 131072 /* ExportName */); - } - /** - * Gets the name for a declaration for use in declarations. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - * @param emitFlags Additional NodeEmitFlags to specify for the name. - */ - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; - } - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); - } - return name_28; - } - else { - return ts.getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } function getClassPrototype(node) { - return ts.createPropertyAccess(getDeclarationName(node), "prototype"); + return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { return ts.hasModifier(member, 32 /* Static */) - ? getDeclarationName(node) + ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; - context.enableSubstitution(69 /* Identifier */); - } - } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) === 0) { - enabledSubstitutions |= 4 /* AsyncMethodsWithSuper */; - // We need to enable substitutions for call, property access, and element access - // if we need to rewrite super calls. - context.enableSubstitution(174 /* CallExpression */); - context.enableSubstitution(172 /* PropertyAccessExpression */); - context.enableSubstitution(173 /* ElementAccessExpression */); - // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(221 /* ClassDeclaration */); - context.enableEmitNotification(147 /* MethodDeclaration */); - context.enableEmitNotification(149 /* GetAccessor */); - context.enableEmitNotification(150 /* SetAccessor */); - context.enableEmitNotification(148 /* Constructor */); + context.enableSubstitution(70 /* Identifier */); } } function enableSubstitutionForClassAliases() { @@ -43874,7 +47844,7 @@ var ts; enabledSubstitutions |= 1 /* ClassAliases */; // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. - context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(70 /* Identifier */); // Keep track of class aliases. classAliases = ts.createMap(); } @@ -43884,60 +47854,45 @@ var ts; enabledSubstitutions |= 2 /* NamespaceExports */; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(254 /* ShorthandPropertyAssignment */); + context.enableSubstitution(70 /* Identifier */); + context.enableSubstitution(258 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(225 /* ModuleDeclaration */); + context.enableEmitNotification(230 /* ModuleDeclaration */); } } - function isSuperContainer(node) { - var kind = node.kind; - return kind === 221 /* ClassDeclaration */ - || kind === 148 /* Constructor */ - || kind === 147 /* MethodDeclaration */ - || kind === 149 /* GetAccessor */ - || kind === 150 /* SetAccessor */; - } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 225 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 230 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 224 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 229 /* EnumDeclaration */; } /** * Hook for node emit. * + * @param emitContext A context hint for the emitter. * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; - var savedCurrentSuperContainer = currentSuperContainer; - // If we need to support substitutions for `super` in an async method, - // we should track it here. - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2 /* NamespaceExports */; } if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } /** * Hooks node substitutions. * + * @param emitContext A context hint for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,34 +47902,28 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_34 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_34); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_34, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_34, exportedName, /*location*/ node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: - return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + case 177 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); } return node; } @@ -43995,10 +47944,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); - return clone_4; + var clone_2 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -44007,13 +47956,13 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 225 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 224 /* EnumDeclaration */); + if (container && container.kind !== 261 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 230 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 229 /* EnumDeclaration */); if (substitute) { return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, /*location*/ node); } @@ -44021,2073 +47970,368 @@ var ts; } return undefined; } - function substituteCallExpression(node) { - var expression = node.expression; - if (ts.isSuperProperty(expression)) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - var argumentExpression = ts.isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), - /*typeArguments*/ undefined, [ - ts.createThis() - ].concat(node.arguments)); - } - } - return node; - } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); - } - } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { - var flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; } + ts.setConstantValue(node, constantValue); + return substitute; } return node; } - function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { - if (flags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), - /*typeArguments*/ undefined, [argumentExpression]), "value", location); + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; } - else { - return ts.createCall(ts.createIdentifier("_super"), - /*typeArguments*/ undefined, [argumentExpression], location); - } - } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; } } ts.transformTypeScript = transformTypeScript; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformES6Module(context) { - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var currentSourceFile; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return ts.visitEachChild(node, visitor, context); - } - return node; - } - function visitor(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 231 /* ImportClause */: - return visitImportClause(node); - case 233 /* NamedImports */: - case 232 /* NamespaceImport */: - return visitNamedBindings(node); - case 234 /* ImportSpecifier */: - return visitImportSpecifier(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 237 /* NamedExports */: - return visitNamedExports(node); - case 238 /* ExportSpecifier */: - return visitExportSpecifier(node); - } - return node; - } - function visitExportAssignment(node) { - if (node.isExportEquals) { - return undefined; // do not emit export equals for ES6 - } - var original = ts.getOriginalNode(node); - return ts.nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; - } - function visitExportDeclaration(node) { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; - } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; - } - var newExportClause = ts.visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true); - if (node.exportClause === newExportClause) { - return node; - } - return newExportClause - ? ts.createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, newExportClause, node.moduleSpecifier) - : undefined; - } - function visitNamedExports(node) { - var newExports = ts.visitNodes(node.elements, visitor, ts.isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? ts.createNamedExports(newExports) : undefined; - } - function visitExportSpecifier(node) { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - function visitImportEqualsDeclaration(node) { - return !ts.isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - function visitImportDeclaration(node) { - if (node.importClause) { - var newImportClause = ts.visitNode(node.importClause, visitor, ts.isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, newImportClause, node.moduleSpecifier); - } - } - return node; - } - function visitImportClause(node) { - var newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - var newNamedBindings = ts.visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? ts.createImportClause(newDefaultImport, newNamedBindings) - : node; - } - function visitNamedBindings(node) { - if (node.kind === 232 /* NamespaceImport */) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - var newNamedImportElements = ts.visitNodes(node.elements, visitor, ts.isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === node.elements) { - return node; - } - return ts.createNamedImports(newNamedImportElements); - } - } - function visitImportSpecifier(node) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } + var paramHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" + }; + function createParamHelper(context, expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ + ts.createLiteral(parameterOffset), + expression + ], location); } - ts.transformES6Module = transformES6Module; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(187 /* BinaryExpression */); - context.enableSubstitution(185 /* PrefixUnaryExpression */); - context.enableSubstitution(186 /* PostfixUnaryExpression */); - context.enableEmitNotification(256 /* SourceFile */); - var exportFunctionForFileMap = []; - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStarsToExportValues; - var exportFunctionForFile; - var contextObjectForFile; - var exportedLocalNames; - var exportedFunctionDeclarations; - var enclosingBlockScopedContainer; - var currentParent; - var currentNode; - return transformSourceFile; - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; - // Perform the transformation. - var updated = transformSystemModuleWorker(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - return node; - } - function transformSystemModuleWorker(node) { - // System modules have the following shape: - // - // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) - // - // The parameter 'exports' here is a callback '(name: string, value: T) => T' that - // is used to publish exported values. 'exports' returns its 'value' argument so in - // most cases expressions that mutate exported values can be rewritten as: - // - // expr -> exports('name', expr) - // - // The only exception in this rule is postfix unary operators, - // see comment to 'substitutePostfixUnaryExpression' for more details - ts.Debug.assert(!exportFunctionForFile); - // Collect information about the external module and dependency groups. - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - // Make sure that the name of the 'exports' function does not conflict with - // existing identifiers. - exportFunctionForFile = ts.createUniqueName("exports"); - contextObjectForFile = ts.createUniqueName("context"); - exportFunctionForFileMap[ts.getOriginalNodeId(node)] = exportFunctionForFile; - var dependencyGroups = collectDependencyGroups(externalImports); - var statements = []; - // Add the body of the module. - addSystemModuleBody(statements, node, dependencyGroups); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, getNameOfDependencyGroup)); - var body = ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(exportFunctionForFile), - ts.createParameter(contextObjectForFile) - ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); - // Write the call to `System.register` - // Clear the emit-helpers flag for later passes since we'll have already used it in the module body - // So the helper will be emit at the correct position instead of at the top of the source-file - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), - /*typeArguments*/ undefined, moduleName - ? [moduleName, dependencies, body] - : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); - var _a; - } - /** - * Adds the statements for the module body function for the source file. - * - * @param statements The output statements for the module body. - * @param node The source file for the module. - * @param statementOffset The offset at which to begin visiting the statements of the SourceFile. - */ - function addSystemModuleBody(statements, node, dependencyGroups) { - // Shape of the body in system modules: - // - // function (exports) { - // - // - // - // return { - // setters: [ - // - // ], - // execute: function() { - // - // } - // } - // - // } - // - // i.e: - // - // import {x} from 'file1' - // var y = 1; - // export function foo() { return y + x(); } - // console.log(y); - // - // Will be transformed to: - // - // function(exports) { - // var file_1; // local alias - // var y; - // function foo() { return y + file_1.x(); } - // exports("foo", foo); - // return { - // setters: [ - // function(v) { file_1 = v } - // ], - // execute(): function() { - // y = 1; - // console.log(y); - // } - // }; - // } - // We start a new lexical environment in this function body, but *not* in the - // body of the execute function. This allows us to emit temporary declarations - // only in the outer module body and not in the inner one. - startLexicalEnvironment(); - // Add any prologue directives. - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitSourceElement); - // var __moduleName = context_1 && context_1.id; - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", - /*type*/ undefined, ts.createLogicalAnd(contextObjectForFile, ts.createPropertyAccess(contextObjectForFile, "id"))) - ]))); - // Visit the statements of the source file, emitting any transformations into - // the `executeStatements` array. We do this *before* we fill the `setters` array - // as we both emit transformations as well as aggregate some data used when creating - // setters. This allows us to reduce the number of times we need to loop through the - // statements of the source file. - var executeStatements = ts.visitNodes(node.statements, visitSourceElement, ts.isStatement, statementOffset); - // We emit the lexical environment (hoisted variables and function declarations) - // early to align roughly with our previous emit output. - // Two key differences in this approach are: - // - Temporary variables will appear at the top rather than at the bottom of the file - // - Calls to the exporter for exported function declarations are grouped after - // the declarations. - ts.addRange(statements, endLexicalEnvironment()); - // Emit early exports for function declarations. - ts.addRange(statements, exportedFunctionDeclarations); - var exportStarFunction = addExportStarIfNeeded(statements); - statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ - ts.createPropertyAssignment("setters", generateSetters(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, ts.createBlock(executeStatements, - /*location*/ undefined, - /*multiLine*/ true))) - ]), - /*multiLine*/ true))); - } - function addExportStarIfNeeded(statements) { - if (!hasExportStarsToExportValues) { - return; - } - // when resolving exports local exported entries/indirect exported entries in the module - // should always win over entries with similar names that were added via star exports - // to support this we store names of local/indirect exported entries in a set. - // this set is used to filter names brought by star expors. - // local names set should only be added if we have anything exported - if (!exportedLocalNames && ts.isEmpty(exportSpecifiers)) { - // no exported declarations (export var ...) or export specifiers (export {x}) - // check if we have any non star export declarations. - var hasExportDeclarationWithExportClause = false; - for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { - var externalImport = externalImports_1[_i]; - if (externalImport.kind === 236 /* ExportDeclaration */ && externalImport.exportClause) { - hasExportDeclarationWithExportClause = true; - break; - } - } - if (!hasExportDeclarationWithExportClause) { - // we still need to emit exportStar helper - return addExportStarFunction(statements, /*localNames*/ undefined); - } - } - var exportedNames = []; - if (exportedLocalNames) { - for (var _a = 0, exportedLocalNames_1 = exportedLocalNames; _a < exportedLocalNames_1.length; _a++) { - var exportedLocalName = exportedLocalNames_1[_a]; - // write name of exported declaration, i.e 'export var x...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName.text), ts.createLiteral(true))); - } - } - for (var _b = 0, externalImports_2 = externalImports; _b < externalImports_2.length; _b++) { - var externalImport = externalImports_2[_b]; - if (externalImport.kind !== 236 /* ExportDeclaration */) { - continue; - } - var exportDecl = externalImport; - if (!exportDecl.exportClause) { - // export * from ... - continue; - } - for (var _c = 0, _d = exportDecl.exportClause.elements; _c < _d.length; _c++) { - var element = _d[_c]; - // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); - } - } - var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, - /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) - ]))); - return addExportStarFunction(statements, exportedNamesStorageRef); - } - /** - * Emits a setter callback for each dependency group. - * @param write The callback used to write each callback. - */ - function generateSetters(exportStarFunction, dependencyGroups) { - var setters = []; - for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group = dependencyGroups_1[_i]; - // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); - var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); - var statements = []; - for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { - var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); - switch (entry.kind) { - case 230 /* ImportDeclaration */: - if (!entry.importClause) { - // 'import "..."' case - // module is imported only for side-effects, no emit required - break; - } - // fall-through - case 229 /* ImportEqualsDeclaration */: - ts.Debug.assert(importVariableName !== undefined); - // save import into the local - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); - break; - case 236 /* ExportDeclaration */: - ts.Debug.assert(importVariableName !== undefined); - if (entry.exportClause) { - // export {a, b as c} from 'foo' - // - // emit as: - // - // exports_({ - // "a": _["a"], - // "c": _["b"] - // }); - var properties = []; - for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { - var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); - } - statements.push(ts.createStatement(ts.createCall(exportFunctionForFile, - /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); - } - else { - // export * from 'foo' - // - // emit as: - // - // exportStar(foo_1_1); - statements.push(ts.createStatement(ts.createCall(exportStarFunction, - /*typeArguments*/ undefined, [parameterName]))); - } - break; - } - } - setters.push(ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(parameterName)], - /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); - } - return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); - } - function visitSourceElement(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - default: - return visitNestedNode(node); - } - } - function visitNestedNode(node) { - var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - if (currentParent && ts.isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; - } - var result = visitNestedNodeWorker(node); - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return result; - } - function visitNestedNodeWorker(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 206 /* ForStatement */: - return visitForStatement(node); - case 207 /* ForInStatement */: - return visitForInStatement(node); - case 208 /* ForOfStatement */: - return visitForOfStatement(node); - case 204 /* DoStatement */: - return visitDoStatement(node); - case 205 /* WhileStatement */: - return visitWhileStatement(node); - case 214 /* LabeledStatement */: - return visitLabeledStatement(node); - case 212 /* WithStatement */: - return visitWithStatement(node); - case 213 /* SwitchStatement */: - return visitSwitchStatement(node); - case 227 /* CaseBlock */: - return visitCaseBlock(node); - case 249 /* CaseClause */: - return visitCaseClause(node); - case 250 /* DefaultClause */: - return visitDefaultClause(node); - case 216 /* TryStatement */: - return visitTryStatement(node); - case 252 /* CatchClause */: - return visitCatchClause(node); - case 199 /* Block */: - return visitBlock(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - default: - return node; - } - } - function visitImportDeclaration(node) { - if (node.importClause && ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - return undefined; - } - function visitImportEqualsDeclaration(node) { - if (ts.contains(externalImports, node)) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); - } - // NOTE(rbuckton): Do we support export import = require('') in System? - return undefined; - } - function visitExportDeclaration(node) { - if (!node.moduleSpecifier) { - var statements = []; - ts.addRange(statements, ts.map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - return undefined; - } - function visitExportSpecifier(specifier) { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement(specifier.name, specifier.propertyName || specifier.name); - } - return undefined; - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement(ts.createLiteral("default"), node.expression); - } - } - return undefined; - } - /** - * Visits a variable statement, hoisting declared names to the top-level module body. - * Each declaration is rewritten into an assignment expression. - * - * @param node The variable statement to visit. - */ - function visitVariableStatement(node) { - // hoist only non-block scoped declarations or block scoped declarations parented by source file - var shouldHoist = ((ts.getCombinedNodeFlags(ts.getOriginalNode(node.declarationList)) & 3 /* BlockScoped */) == 0) || - enclosingBlockScopedContainer.kind === 256 /* SourceFile */; - if (!shouldHoist) { - return node; - } - var isExported = ts.hasModifier(node, 1 /* Export */); - var expressions = []; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } - } - if (expressions.length) { - return ts.createStatement(ts.inlineExpressions(expressions), node); - } - return undefined; - } - /** - * Transforms a VariableDeclaration into one or more assignment expressions. - * - * @param node The VariableDeclaration to transform. - * @param isExported A value used to indicate whether the containing statement was exported. - */ - function transformVariable(node, isExported) { - // Hoist any bound names within the declaration. - hoistBindingElement(node, isExported); - if (!node.initializer) { - // If the variable has no initializer, ignore it. - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - // If the variable has an IdentifierName, write out an assignment expression in its place. - return ts.createAssignment(name, node.initializer); - } - else { - // If the variable has a BindingPattern, flatten the variable into multiple assignment expressions. - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - /** - * Visits a FunctionDeclaration, hoisting it to the outer module body function. - * - * @param node The function declaration to visit. - */ - function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1 /* Export */)) { - // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body, - /*location*/ node); - // Record a declaration export in the outer module body function. - recordExportedFunctionDeclaration(node); - if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); - } - ts.setOriginalNode(newNode, node); - node = newNode; - } - // Hoist the function declaration to the outer module body function. - hoistFunctionDeclaration(node); - return undefined; - } - function visitExpressionStatement(node) { - var originalNode = ts.getOriginalNode(node); - if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); - // We only need to hoistVariableDeclaration for EnumDeclaration - // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement - // which then call transformsVariable for each declaration in declarationList - if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); - } - return [ - node, - createExportStatement(name_31, name_31) - ]; - } - return node; - } - /** - * Visits a ClassDeclaration, hoisting its name to the outer module body function. - * - * @param node The class declaration to visit. - */ - function visitClassDeclaration(node) { - // Hoist the name of the class declaration to the outer module body function. - var name = getDeclarationName(node); - hoistVariableDeclaration(name); - var statements = []; - // Rewrite the class declaration into an assignment of a class expression. - statements.push(ts.createStatement(ts.createAssignment(name, ts.createClassExpression( - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, node.heritageClauses, node.members, - /*location*/ node)), - /*location*/ node)); - // If the class was exported, write a declaration export to the inner module body function. - if (ts.hasModifier(node, 1 /* Export */)) { - if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name); - } - statements.push(createDeclarationExport(node)); - } - return statements; - } - function shouldHoistLoopInitializer(node) { - return ts.isVariableDeclarationList(node) && (ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) === 0; - } - /** - * Visits the body of a ForStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var expressions = []; - for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { - var variable = _a[_i]; - var visited = transformVariable(variable, /*isExported*/ false); - if (visited) { - expressions.push(visited); - } - } - ; - return ts.createFor(expressions.length - ? ts.inlineExpressions(expressions) - : ts.createSynthesizedNode(193 /* OmittedExpression */), node.condition, node.incrementor, ts.visitNode(node.statement, visitNestedNode, ts.isStatement), - /*location*/ node); - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Transforms and hoists the declaration list of a ForInStatement or ForOfStatement into an expression. - * - * @param node The decalaration list to transform. - */ - function transformForBinding(node) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, /*isExported*/ false); - var name = firstDeclaration.name; - return ts.isIdentifier(name) - ? name - : ts.flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); - } - /** - * Visits the body of a ForInStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForInStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Visits the body of a ForOfStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitForOfStatement(node) { - var initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - var updated = ts.getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - return updated; - } - else { - return ts.visitEachChild(node, visitNestedNode, context); - } - } - /** - * Visits the body of a DoStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitDoStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a WhileStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitWhileStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a LabeledStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitLabeledStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a WithStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitWithStatement(node) { - var statement = ts.visitNode(node.statement, visitNestedNode, ts.isStatement, /*optional*/ false, ts.liftToBlock); - if (statement !== node.statement) { - var updated = ts.getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; - } - /** - * Visits the body of a SwitchStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitSwitchStatement(node) { - var caseBlock = ts.visitNode(node.caseBlock, visitNestedNode, ts.isCaseBlock); - if (caseBlock !== node.caseBlock) { - var updated = ts.getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; - } - /** - * Visits the body of a CaseBlock to hoist declarations. - * - * @param node The node to visit. - */ - function visitCaseBlock(node) { - var clauses = ts.visitNodes(node.clauses, visitNestedNode, ts.isCaseOrDefaultClause); - if (clauses !== node.clauses) { - var updated = ts.getMutableClone(node); - updated.clauses = clauses; - return updated; - } - return node; - } - /** - * Visits the body of a CaseClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitCaseClause(node) { - var statements = ts.visitNodes(node.statements, visitNestedNode, ts.isStatement); - if (statements !== node.statements) { - var updated = ts.getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; - } - /** - * Visits the body of a DefaultClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitDefaultClause(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - /** - * Visits the body of a TryStatement to hoist declarations. - * - * @param node The statement to visit. - */ - function visitTryStatement(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - /** - * Visits the body of a CatchClause to hoist declarations. - * - * @param node The clause to visit. - */ - function visitCatchClause(node) { - var block = ts.visitNode(node.block, visitNestedNode, ts.isBlock); - if (block !== node.block) { - var updated = ts.getMutableClone(node); - updated.block = block; - return updated; - } - return node; - } - /** - * Visits the body of a Block to hoist declarations. - * - * @param node The block to visit. - */ - function visitBlock(node) { - return ts.visitEachChild(node, visitNestedNode, context); - } - // - // Substitutions - // - function onEmitNode(node, emit) { - if (node.kind === 256 /* SourceFile */) { - exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - exportFunctionForFile = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - /** - * Hooks node substitutions. - * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. - */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - return node; - } - /** - * Substitute the expression, if necessary. - * - * @param node The node to substitute. - */ - function substituteExpression(node) { - switch (node.kind) { - case 69 /* Identifier */: - return substituteExpressionIdentifier(node); - case 187 /* BinaryExpression */: - return substituteBinaryExpression(node); - case 185 /* PrefixUnaryExpression */: - case 186 /* PostfixUnaryExpression */: - return substituteUnaryExpression(node); - } - return node; - } - /** - * Substitution for identifiers exported at the top level of a module. - */ - function substituteExpressionIdentifier(node) { - var importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - var importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; - } - } - return node; - } - function substituteBinaryExpression(node) { - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); - } - return node; - } - function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var left = node.left; - switch (left.kind) { - case 69 /* Identifier */: - var exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); - } - break; - case 171 /* ObjectLiteralExpression */: - case 170 /* ArrayLiteralExpression */: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - return node; - } - function isExportedBinding(name) { - var container = resolver.getReferencedExportContainer(name); - return container && container.kind === 256 /* SourceFile */; - } - function hasExportedReferenceInDestructuringPattern(node) { - switch (node.kind) { - case 69 /* Identifier */: - return isExportedBinding(node); - case 171 /* ObjectLiteralExpression */: - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var property = _a[_i]; - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - break; - case 170 /* ArrayLiteralExpression */: - for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - break; - } - return false; - } - function hasExportedReferenceInObjectDestructuringElement(node) { - if (ts.isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (ts.isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - function hasExportedReferenceInArrayDestructuringElement(node) { - if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - function hasExportedReferenceInDestructuringElement(node) { - if (ts.isBinaryExpression(node)) { - var left = node.left; - return node.operatorToken.kind === 56 /* EqualsToken */ - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (ts.isIdentifier(node)) { - return isExportedBinding(node); - } - else if (ts.isSpreadElementExpression(node)) { - var expression = node.expression; - return ts.isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - function isDestructuringPattern(node) { - var kind = node.kind; - return kind === 69 /* Identifier */ - || kind === 171 /* ObjectLiteralExpression */ - || kind === 170 /* ArrayLiteralExpression */; - } - function substituteDestructuring(node) { - return ts.flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration); - } - function substituteUnaryExpression(node) { - var operand = node.operand; - var operator = node.operator; - var substitute = ts.isIdentifier(operand) && - (node.kind === 186 /* PostfixUnaryExpression */ || - (node.kind === 185 /* PrefixUnaryExpression */ && (operator === 41 /* PlusPlusToken */ || operator === 42 /* MinusMinusToken */))); - if (substitute) { - var exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); - var call = createExportExpression(operand, expr); - if (node.kind === 185 /* PrefixUnaryExpression */) { - return call; - } - else { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - return operator === 41 /* PlusPlusToken */ - ? ts.createSubtract(call, ts.createLiteral(1)) - : ts.createAdd(call, ts.createLiteral(1)); - } - } - } - return node; - } - /** - * Gets a name to use for a DeclarationStatement. - * @param node The declaration statement. - */ - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function addExportStarFunction(statements, localNames) { - var exportStarFunction = ts.createUniqueName("exportStar"); - var m = ts.createIdentifier("m"); - var n = ts.createIdentifier("n"); - var exports = ts.createIdentifier("exports"); - var condition = ts.createStrictInequality(n, ts.createLiteral("default")); - if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createHasOwnProperty(localNames, n))); - } - statements.push(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [ts.createParameter(m)], - /*type*/ undefined, ts.createBlock([ - ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, - /*type*/ undefined, ts.createObjectLiteral([])) - ])), - ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, /*type*/ undefined) - ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) - ])), - ts.createStatement(ts.createCall(exportFunctionForFile, - /*typeArguments*/ undefined, [exports])) - ], - /*location*/ undefined, - /*multiline*/ true))); - return exportStarFunction; - } - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportExpression(name, value) { - var exportName = ts.isIdentifier(name) ? ts.createLiteral(name.text) : name; - return ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exportName, value]); - } - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportStatement(name, value) { - return ts.createStatement(createExportExpression(name, value)); - } - /** - * Creates a call to the current file's export function to export a declaration. - * @param node The declaration to export. - */ - function createDeclarationExport(node) { - var declarationName = getDeclarationName(node); - var exportName = ts.hasModifier(node, 512 /* Default */) ? ts.createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - function createImportBinding(importDeclaration) { - var importAlias; - var name; - if (ts.isImportClause(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent); - name = ts.createIdentifier("default"); - } - else if (ts.isImportSpecifier(importDeclaration)) { - importAlias = ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - if (name.originalKeywordKind && languageVersion === 0 /* ES3 */) { - return ts.createElementAccess(importAlias, ts.createLiteral(name.text)); - } - else { - return ts.createPropertyAccess(importAlias, ts.getSynthesizedClone(name)); - } - } - function collectDependencyGroups(externalImports) { - var groupIndices = ts.createMap(); - var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; - var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); - var text = externalModuleName.text; - if (ts.hasProperty(groupIndices, text)) { - // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[text]; - dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; - } - else { - groupIndices[text] = dependencyGroups.length; - dependencyGroups.push({ - name: externalModuleName, - externalImports: [externalImport] - }); - } - } - return dependencyGroups; - } - function getNameOfDependencyGroup(dependencyGroup) { - return dependencyGroup.name; - } - function recordExportName(name) { - if (!exportedLocalNames) { - exportedLocalNames = []; - } - exportedLocalNames.push(name); - } - function recordExportedFunctionDeclaration(node) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; - } - exportedFunctionDeclarations.push(createDeclarationExport(node)); - } - function hoistBindingElement(node, isExported) { - if (ts.isOmittedExpression(node)) { - return; - } - var name = node.name; - if (ts.isIdentifier(name)) { - hoistVariableDeclaration(ts.getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); - } - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); - } - } - function hoistExportedBindingElement(node) { - hoistBindingElement(node, /*isExported*/ true); - } - function hoistNonExportedBindingElement(node) { - hoistBindingElement(node, /*isExported*/ false); - } - function updateSourceFile(node, statements, nodeEmitFlags) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); - return updated; - } + var metadataHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" + }; + function createMetadataHelper(context, metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ + ts.createLiteral(metadataKey), + metadataValue + ]); } - ts.transformSystemModule = transformSystemModule; -})(ts || (ts = {})); -/// -/// -/*@internal*/ -var ts; -(function (ts) { - function transformModule(context) { - var transformModuleDelegates = ts.createMap((_a = {}, - _a[ts.ModuleKind.None] = transformCommonJSModule, - _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, - _a[ts.ModuleKind.AMD] = transformAMDModule, - _a[ts.ModuleKind.UMD] = transformUMDModule, - _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; - var compilerOptions = context.getCompilerOptions(); - var resolver = context.getEmitResolver(); - var host = context.getEmitHost(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var moduleKind = ts.getEmitModuleKind(compilerOptions); - var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onSubstituteNode = onSubstituteNode; - context.onEmitNode = onEmitNode; - context.enableSubstitution(69 /* Identifier */); - context.enableSubstitution(187 /* BinaryExpression */); - context.enableSubstitution(185 /* PrefixUnaryExpression */); - context.enableSubstitution(186 /* PostfixUnaryExpression */); - context.enableSubstitution(254 /* ShorthandPropertyAssignment */); - context.enableEmitNotification(256 /* SourceFile */); - var currentSourceFile; - var externalImports; - var exportSpecifiers; - var exportEquals; - var bindingNameExportSpecifiersMap; - // Subset of exportSpecifiers that is a binding-name. - // This is to reduce amount of memory we have to keep around even after we done with module-transformer - var bindingNameExportSpecifiersForFileMap = ts.createMap(); - var hasExportStarsToExportValues; - return transformSourceFile; - /** - * Transforms the module aspects of a SourceFile. - * - * @param node The SourceFile node. - */ - function transformSourceFile(node) { - if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - // Collect information about the external module. - (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); - // Perform the transformation. - var transformModule_1 = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; - var updated = transformModule_1(node); - ts.aggregateTransformFlags(updated); - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; - } - return node; - var _a; - } - /** - * Transforms a SourceFile into a CommonJS module. - * - * @param node The SourceFile node. - */ - function transformCommonJSModule(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - ts.addRange(statements, endLexicalEnvironment()); - addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - var updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); - } - return updated; - } - /** - * Transforms a SourceFile into an AMD module. - * - * @param node The SourceFile node. - */ - function transformAMDModule(node) { - var define = ts.createIdentifier("define"); - var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); - } - /** - * Transforms a SourceFile into a UMD module. - * - * @param node The SourceFile node. - */ - function transformUMDModule(node) { - var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); - return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); - } - /** - * Transforms a SourceFile into an AMD or UMD module. - * - * @param node The SourceFile node. - * @param define The expression used to define the module. - * @param moduleName An expression for the module name, if available. - * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. - */ - function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { - // An AMD define function has the following shape: - // - // define(id?, dependencies?, factory); - // - // This has the shape of the following: - // - // define(name, ["module1", "module2"], function (module1Alias) { ... } - // - // The location of the alias in the parameter list in the factory function needs to - // match the position of the module name in the dependency list. - // - // To ensure this is true in cases of modules with no aliases, e.g.: - // - // import "module" - // - // or - // - // /// - // - // we need to add modules without alias names to the end of the dependencies list - var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - // Create an updated SourceFile: - // - // define(moduleName?, ["module1", "module2"], function ... - return updateSourceFile(node, [ - ts.createStatement(ts.createCall(define, - /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ - // Add the dependency array argument: - // - // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ - ts.createLiteral("require"), - ts.createLiteral("exports") - ].concat(aliasedModuleNames, unaliasedModuleNames)), - // Add the module body function argument: - // - // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter("require"), - ts.createParameter("exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) - ]))) - ]); - } - /** - * Transforms a SourceFile into an AMD or UMD module body. - * - * @param node The SourceFile node. - */ - function transformAsynchronousModuleBody(node) { - startLexicalEnvironment(); - var statements = []; - var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); - // Visit each statement of the module body. - ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); - // End the lexical environment for the module body - // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); - // Append the 'export =' statement if provided. - addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); - var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); - if (hasExportStarsToExportValues) { - // If we have any `export * from ...` declarations - // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); - } - return body; - } - function addExportEqualsIfNeeded(statements, emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - if (emitAsReturn) { - var statement = ts.createReturn(exportEquals.expression, - /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), - /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); - statements.push(statement); - } + var decorateHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" + }; + function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { + context.requestEmitHelper(decorateHelper); + var argumentsArray = []; + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); } } - /** - * Visits a node at the top level of the source file. - * - * @param node The node. - */ - function visitor(node) { - switch (node.kind) { - case 230 /* ImportDeclaration */: - return visitImportDeclaration(node); - case 229 /* ImportEqualsDeclaration */: - return visitImportEqualsDeclaration(node); - case 236 /* ExportDeclaration */: - return visitExportDeclaration(node); - case 235 /* ExportAssignment */: - return visitExportAssignment(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - default: - // This visitor does not descend into the tree, as export/import statements - // are only transformed at the top level of a file. - return node; - } - } - /** - * Visits an ImportDeclaration node. - * - * @param node The ImportDeclaration node. - */ - function visitImportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var statements = []; - var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); - if (moduleKind !== ts.ModuleKind.AMD) { - if (!node.importClause) { - // import "mod"; - statements.push(ts.createStatement(createRequireCall(node), - /*location*/ node)); - } - else { - var variables = []; - if (namespaceDeclaration && !ts.isDefaultImport(node)) { - // import * as n from "mod"; - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); - } - else { - // import d from "mod"; - // import { x, y } from "mod"; - // import d, { x, y } from "mod"; - // import d, * as n from "mod"; - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); - if (namespaceDeclaration && ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, ts.getGeneratedNameForNode(node))); - } - } - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createConstDeclarationList(variables), - /*location*/ node)); - } - } - else if (namespaceDeclaration && ts.isDefaultImport(node)) { - // import d, * as n from "mod"; - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, ts.getGeneratedNameForNode(node), - /*location*/ node) - ]))); - } - addExportImportAssignments(statements, node); - return ts.singleOrMany(statements); - } - function visitImportEqualsDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - // Set emitFlags on the name of the importEqualsDeclaration - // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); - var statements = []; - if (moduleKind !== ts.ModuleKind.AMD) { - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.createStatement(createExportAssignment(node.name, createRequireCall(node)), - /*location*/ node)); - } - else { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), - /*type*/ undefined, createRequireCall(node)) - ], - /*location*/ undefined, - /*flags*/ languageVersion >= 2 /* ES6 */ ? 2 /* Const */ : 0 /* None */), - /*location*/ node)); - } - } - else { - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.createStatement(createExportAssignment(node.name, node.name), - /*location*/ node)); - } - } - addExportImportAssignments(statements, node); - return statements; - } - function visitExportDeclaration(node) { - if (!ts.contains(externalImports, node)) { - return undefined; - } - var generatedName = ts.getGeneratedNameForNode(node); - if (node.exportClause) { - var statements = []; - // export { x, y } from "mod"; - if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(generatedName, - /*type*/ undefined, createRequireCall(node)) - ]), - /*location*/ node)); - } - for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { - var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.createStatement(createExportAssignment(specifier.name, exportedValue), - /*location*/ specifier)); - } - } - return ts.singleOrMany(statements); - } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { - // export * from "mod"; - return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), - /*typeArguments*/ undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ]), - /*location*/ node); - } - } - function visitExportAssignment(node) { - if (!node.isExportEquals) { - if (ts.nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - var statements = []; - addExportDefault(statements, node.expression, /*location*/ node); - return statements; - } - } - return undefined; - } - function addExportDefault(statements, expression, location) { - tryAddExportDefaultCompat(statements); - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("default"), expression), location)); - } - function tryAddExportDefaultCompat(statements) { - var original = ts.getOriginalNode(currentSourceFile); - ts.Debug.assert(original.kind === 256 /* SourceFile */); - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === 0 /* ES3 */) { - statements.push(ts.createStatement(createExportAssignment(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); - } - else { - statements.push(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) - ]) - ]))); - } - } - } - function addExportImportAssignments(statements, node) { - if (ts.isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); - } - else { - var names = ts.reduceEachChild(node, collectExportMembers, []); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); - } - } - } - function collectExportMembers(names, node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); - } - } - return ts.reduceEachChild(node, collectExportMembers, names); - } - function addExportMemberAssignments(statements, name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - statements.push(ts.startOnNewLine(ts.createStatement(createExportAssignment(specifier.name, name), - /*location*/ specifier.name))); - } - } - } - function addExportMemberAssignment(statements, node) { - if (ts.hasModifier(node, 512 /* Default */)) { - addExportDefault(statements, getDeclarationName(node), /*location*/ node); - } - else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); - } - } - function visitVariableStatement(node) { - // If the variable is for a generated declaration, - // we should maintain it and just strip off the 'export' modifier if necessary. - var originalKind = ts.getOriginalNode(node).kind; - if (originalKind === 225 /* ModuleDeclaration */ || - originalKind === 224 /* EnumDeclaration */ || - originalKind === 221 /* ClassDeclaration */) { - if (!ts.hasModifier(node, 1 /* Export */)) { - return node; - } - return ts.setOriginalNode(ts.createVariableStatement( - /*modifiers*/ undefined, node.declarationList), node); - } - var resultStatements = []; - // If we're exporting these variables, then these just become assignments to 'exports.blah'. - // We only want to emit assignments for variables with initializers. - if (ts.hasModifier(node, 1 /* Export */)) { - var variables = ts.getInitializedVariables(node.declarationList); - if (variables.length > 0) { - var inlineAssignments = ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)), node); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - // While we might not have been exported here, each variable might have been exported - // later on in an export specifier (e.g. `export {foo as blah, bar}`). - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - return resultStatements; - } - /** - * Creates appropriate assignments for each binding identifier that is exported in an export specifier, - * and inserts it into 'resultStatements'. - */ - function addExportMemberAssignmentsForBindingName(resultStatements, name) { - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - var sourceFileId = ts.getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = ts.createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - function transformInitializedVariable(node) { - var name = node.name; - if (ts.isBindingPattern(name)) { - return ts.flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, getModuleMemberName, visitor); - } - else { - return ts.createAssignment(getModuleMemberName(name), ts.visitNode(node.initializer, visitor, ts.isExpression)); - } - } - function visitFunctionDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name, - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body, - /*location*/ node), - /*original*/ node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - if (node.name) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitClassDeclaration(node) { - var statements = []; - var name = node.name || ts.getGeneratedNameForNode(node); - if (ts.hasModifier(node, 1 /* Export */)) { - statements.push(ts.setOriginalNode(ts.createClassDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, name, - /*typeParameters*/ undefined, node.heritageClauses, node.members, - /*location*/ node), - /*original*/ node)); - addExportMemberAssignment(statements, node); - } - else { - statements.push(node); - } - // Decorators end up creating a series of assignment expressions which overwrite - // the local binding that we export, so we need to defer from exporting decorated classes - // until the decoration assignments take place. We do this when visiting expression-statements. - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); - } - return ts.singleOrMany(statements); - } - function visitExpressionStatement(node) { - var original = ts.getOriginalNode(node); - var origKind = original.kind; - if (origKind === 224 /* EnumDeclaration */ || origKind === 225 /* ModuleDeclaration */) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === 221 /* ClassDeclaration */) { - // The decorated assignment for a class name may need to be transformed. - var classDecl = original; - if (classDecl.name) { - var statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; - } - } - return node; - } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node, original) { - var statements = [node]; - // Preserve old behavior for enums in which a variable statement is emitted after the body itself. - if (ts.hasModifier(original, 1 /* Export */) && - original.kind === 224 /* EnumDeclaration */ && - ts.isFirstDeclarationOfKind(original, 224 /* EnumDeclaration */)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); - } - addExportMemberAssignments(statements, original.name); - return statements; - } - /** - * Adds a trailing VariableStatement for an enum or module declaration. - */ - function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { - var transformedStatement = ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), - /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], - /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); - statements.push(transformedStatement); - } - function getDeclarationName(node) { - return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); - } - function onEmitNode(node, emit) { - if (node.kind === 256 /* SourceFile */) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); - bindingNameExportSpecifiersMap = undefined; - } - else { - previousOnEmitNode(node, emit); - } - } - /** - * Hooks node substitutions. - * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. - */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); - } - else if (ts.isShorthandPropertyAssignment(node)) { - return substituteShorthandPropertyAssignment(node); - } - return node; - } - function substituteShorthandPropertyAssignment(node) { - var name = node.name; - var exportedOrImportedName = substituteExpressionIdentifier(name); - if (exportedOrImportedName !== name) { - // A shorthand property with an assignment initializer is probably part of a - // destructuring assignment - if (node.objectAssignmentInitializer) { - var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name, initializer, /*location*/ node); - } - return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); - } - return node; - } - function substituteExpression(node) { - switch (node.kind) { - case 69 /* Identifier */: - return substituteExpressionIdentifier(node); - case 187 /* BinaryExpression */: - return substituteBinaryExpression(node); - case 186 /* PostfixUnaryExpression */: - case 185 /* PrefixUnaryExpression */: - return substituteUnaryExpression(node); - } - return node; - } - function substituteExpressionIdentifier(node) { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; - } - function substituteBinaryExpression(node) { - var left = node.left; - // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier - if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); - } - return nestedExportAssignment; - } - } - return node; - } - function substituteUnaryExpression(node) { - // Because how the compiler only parse plusplus and minusminus to be either prefixUnaryExpression or postFixUnaryExpression depended on where they are - // We don't need to check that the operator has SyntaxKind.plusplus or SyntaxKind.minusminus - var operator = node.operator; - var operand = node.operand; - if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); - var transformedUnaryExpression = void 0; - if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), - /*location*/ node); - // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); - } - var nestedExportAssignment = void 0; - for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; - } - } - return node; - } - function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); - if ((emitFlags & 262144 /* LocalName */) === 0) { - var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); - if (container) { - if (container.kind === 256 /* SourceFile */) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), - /*location*/ node); - } - } - } - return undefined; - } - function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { - var declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (ts.isImportClause(declaration)) { - if (languageVersion >= 1 /* ES5 */) { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createIdentifier("default"), - /*location*/ node); - } - else { - // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent), ts.createLiteral("default"), - /*location*/ node); - } - } - else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { - // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), - /*location*/ node); - } - else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), - /*location*/ node); - } - } - } - } - return undefined; - } - function getModuleMemberName(name) { - return ts.createPropertyAccess(ts.createIdentifier("exports"), name, - /*location*/ name); - } - function createRequireCall(importNode) { - var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - var args = []; - if (ts.isDefined(moduleName)) { - args.push(moduleName); - } - return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); - } - function createExportStatement(name, value, location) { - var statement = ts.createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - return statement; - } - function createExportAssignment(name, value) { - return ts.createAssignment(name.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion === 0 /* ES3 */ - ? ts.createElementAccess(ts.createIdentifier("exports"), ts.createLiteral(name.text)) - : ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value); - } - function collectAsynchronousDependencies(node, includeNonAmdDependencies) { - // names of modules with corresponding parameter in the factory function - var aliasedModuleNames = []; - // names of modules with no corresponding parameters in factory function - var unaliasedModuleNames = []; - // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - var importAliasNames = []; - // Fill in amd-dependency tags - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - } - } - for (var _b = 0, externalImports_3 = externalImports; _b < externalImports_3.length; _b++) { - var importNode = externalImports_3[_b]; - // Find the name of the external module - var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - // Find the name of the module alias, if there is one - var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - // Set emitFlags on the name of the classDeclaration - // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; - } - function updateSourceFile(node, statements) { - var updated = ts.getMutableClone(node); - updated.statements = ts.createNodeArray(statements, node.statements); - return updated; - } - var _a; + return ts.createCall(ts.getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray, location); } - ts.transformModule = transformModule; })(ts || (ts = {})); /// /// /*@internal*/ var ts; (function (ts) { - var entities = createEntitiesMap(); + function transformESNext(context) { + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + function visitorNoDestructuringValue(node) { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + function visitorWorker(node, noDestructuringValue) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 176 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 192 /* BinaryExpression */: + return visitBinaryExpression(node, noDestructuringValue); + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 188 /* VoidExpression */: + return visitVoidExpression(node); + case 150 /* Constructor */: + return visitConstructorDeclaration(node); + case 149 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 151 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 152 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 184 /* FunctionExpression */: + return visitFunctionExpression(node); + case 185 /* ArrowFunction */: + return visitArrowFunction(node); + case 144 /* Parameter */: + return visitParameter(node); + case 207 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 183 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, noDestructuringValue); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function chunkObjectLiteralElements(elements) { + var chunkObject; + var objects = []; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; + if (e.kind === 259 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + var target = e.expression; + objects.push(ts.visitNode(target, visitor, ts.isExpression)); + } + else { + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === 257 /* PropertyAssignment */) { + var p = e; + chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); + } + else { + chunkObject.push(e); + } + } + } + if (chunkObject) { + objects.push(ts.createObjectLiteral(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + var objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 176 /* ObjectLiteralExpression */) { + objects.unshift(ts.createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return ts.visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + function visitParenthesizedExpression(node, noDestructuringValue) { + return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node, noDestructuringValue) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); + } + else if (node.operatorToken.kind === 25 /* CommaToken */) { + return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); + } + return ts.visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + } + function visitVoidExpression(node) { + return ts.visitEachChild(node, visitorNoDestructuringValue, context); + } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + var leadingStatements; + var temp; + var initializer = ts.skipParentheses(node.initializer); + if (initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isVariableDeclarationList(initializer)) { + temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var firstDeclaration = ts.firstOrUndefined(initializer.declarations); + var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(initializer, declarations), + /*location*/ initializer); + leadingStatements = ts.append(leadingStatements, statement); + } + } + else if (ts.isAssignmentPattern(initializer)) { + temp = ts.createTempVariable(/*recordTempVariable*/ undefined); + var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, /*location*/ node.initializer)), visitor, context, 1 /* ObjectRest */); + leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, /*location*/ node.initializer)); + } + } + if (temp) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var block = ts.isBlock(statement) + ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements)) + : ts.createBlock(ts.append(leadingStatements, statement), statement, /*multiLine*/ true); + return ts.updateForOf(node, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer) + ], node.initializer, 1 /* Let */), expression, block); + } + return ts.visitEachChild(node, visitor, context); + } + function visitParameter(node) { + if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + return ts.visitEachChild(node, visitor, context); + } + function visitConstructorDeclaration(node) { + return ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitGetAccessorDeclaration(node) { + return ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitSetAccessorDeclaration(node) { + return ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + } + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + var leadingStatements; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + var temp = ts.getGeneratedNameForNode(parameter); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); + if (ts.some(declarations)) { + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + leadingStatements = ts.append(leadingStatements, statement); + } + } + } + var body = ts.visitNode(node.body, visitor, ts.isConciseBody); + var trailingStatements = endLexicalEnvironment(); + if (ts.some(leadingStatements) || ts.some(trailingStatements)) { + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); + } + return body; + } + } + ts.transformESNext = transformESNext; + var assignHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + }; + function createAssignHelper(context, attributesSegments) { + context.requestEmitHelper(assignHelper); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); + } + ts.createAssignHelper = createAssignHelper; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; @@ -46098,44 +48342,44 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; - return node; + return visited; } function visitor(node) { - if (node.transformFlags & 4 /* Jsx */) { + if (node.transformFlags & 4 /* ContainsJsx */) { return visitorWorker(node); } - else if (node.transformFlags & 8 /* ContainsJsx */) { - return ts.visitEachChild(node, visitor, context); - } else { return node; } } function visitorWorker(node) { switch (node.kind) { - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitJsxExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.visitEachChild(node, visitor, context); } } function transformJsxChildToExpression(node) { switch (node.kind) { - case 244 /* JsxText */: + case 10 /* JsxText */: return visitJsxText(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return visitJsxExpression(node); - case 241 /* JsxElement */: + case 246 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); default: ts.Debug.failBadSyntaxKind(node); @@ -46169,10 +48413,12 @@ var ts; } // Either emit one big object literal (no spread attribs), or // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) - || ts.createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = ts.createAssignHelper(context, segments); + } } - var element = ts.createReactCreateElement(compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.filter(ts.map(children, transformJsxChildToExpression), ts.isDefined), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -46194,7 +48440,7 @@ var ts; var decoded = tryDecodeEntities(node.text); return decoded ? ts.createLiteral(decoded, /*location*/ node) : node; } - else if (node.kind === 248 /* JsxExpression */) { + else if (node.kind === 252 /* JsxExpression */) { return visitJsxExpression(node); } else { @@ -46276,7 +48522,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 241 /* JsxElement */) { + if (node.kind === 246 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -46308,337 +48554,3217 @@ var ts; } } ts.transformJsx = transformJsx; - function createEntitiesMap() { - return ts.createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + var entities = ts.createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); })(ts || (ts = {})); /// /// /*@internal*/ var ts; (function (ts) { - function transformES7(context) { + var ES2017SubstitutionFlags; + (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ + ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; + })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); + function transformES2017(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // These variables contain state that changes as we descend into the tree. + var currentSourceFile; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + var currentSuperContainer; + // Save the previous transformation hooks. + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + return node; + } + switch (node.kind) { + case 119 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + case 189 /* AwaitExpression */: + // ES2017 'await' expressions must be transformed for targets < ES2017. + return visitAwaitExpression(node); + case 149 /* MethodDeclaration */: + // ES2017 method declarations may be 'async' + return visitMethodDeclaration(node); + case 225 /* FunctionDeclaration */: + // ES2017 function declarations may be 'async' + return visitFunctionDeclaration(node); + case 184 /* FunctionExpression */: + // ES2017 function expressions may be 'async' + return visitFunctionExpression(node); + case 185 /* ArrowFunction */: + // ES2017 arrow functions may be 'async' + return visitArrowFunction(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node) { + return ts.setOriginalNode(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node) { + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node) { + if (ts.nodeIsMissing(node.body)) { + return ts.createOmittedExpression(); + } + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node) { + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + function transformAsyncFunctionBody(node) { + resumeLexicalEnvironment(); + var original = ts.getOriginalNode(node, ts.isFunctionLike); + var nodeType = original.type; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 185 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + if (!isArrowFunction) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES2015 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + enableSubstitutionForAsyncMethodsWithSuper(); + ts.addEmitHelper(block, asyncSuperHelper); + } + } + return block; + } + else { + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var declarations = endLexicalEnvironment(); + if (ts.some(declarations)) { + var block = ts.convertToFunctionBody(expression); + return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements)); + } + return expression; + } + } + function transformFunctionBodyWorker(body, start) { + if (ts.isBlock(body)) { + return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); + var declarations = endLexicalEnvironment(); + return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements)); + } + } + function getPromiseConstructor(type) { + var typeName = type && ts.getEntityNameFromTypeNode(type); + if (typeName && ts.isEntityName(typeName)) { + var serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === ts.TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + return undefined; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(179 /* CallExpression */); + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(178 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(226 /* ClassDeclaration */); + context.enableEmitNotification(149 /* MethodDeclaration */); + context.enableEmitNotification(151 /* GetAccessor */); + context.enableEmitNotification(152 /* SetAccessor */); + context.enableEmitNotification(150 /* Constructor */); + } + } + function substituteExpression(node) { + switch (node.kind) { + case 177 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 179 /* CallExpression */: + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) { + return substituteCallExpression(node); + } + break; + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); + } + } + return node; + } + function substituteElementAccessExpression(node) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); + } + } + return node; + } + function substituteCallExpression(node) { + var expression = node.expression; + if (ts.isSuperProperty(expression)) { + var flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + var argumentExpression = ts.isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ + ts.createThis() + ].concat(node.arguments)); + } + } + return node; + } + function isSuperContainer(node) { + var kind = node.kind; + return kind === 226 /* ClassDeclaration */ + || kind === 150 /* Constructor */ + || kind === 149 /* MethodDeclaration */ + || kind === 151 /* GetAccessor */ + || kind === 152 /* SetAccessor */; + } + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { + if (flags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value", location); + } + else { + return ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression], location); + } + } + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); + } + } + ts.transformES2017 = transformES2017; + function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { + context.requestEmitHelper(awaiterHelper); + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(38 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ + ts.createThis(), + hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), + promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), + generatorFunc + ]); + } + var awaiterHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" + }; + var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: "\n const _super = name => super[name];" + }; + var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);" + }; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if (node.transformFlags & 16 /* ES7 */) { - return visitorWorker(node); + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + return node; } - else if (node.transformFlags & 32 /* ContainsES7 */) { + switch (node.kind) { + case 192 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 61 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 39 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + var target; + var value; + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), + /*location*/ left); + value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, + /*location*/ left); + } + else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); + target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, + /*location*/ left); + value = ts.createPropertyAccess(expressionTemp, left.name, + /*location*/ left); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + } + function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` + var left = ts.visitNode(node.left, visitor, ts.isExpression); + var right = ts.visitNode(node.right, visitor, ts.isExpression); + return ts.createMathPow(left, right, /*location*/ node); + } + } + ts.transformES2016 = transformES2016; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var ES2015SubstitutionFlags; + (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ + ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; + })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); + function transformES2015(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + var currentSourceFile; + var currentText; + var currentParent; + var currentNode; + var enclosingVariableStatement; + var enclosingBlockScopeContainer; + var enclosingBlockScopeContainerParent; + var enclosingFunction; + var enclosingNonArrowFunction; + var enclosingNonAsyncFunctionBody; + var isInConstructorWithCapturedSuper; + /** + * Used to track if we are emitting body of the converted loop + */ + var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ + var enabledSubstitutions; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + currentSourceFile = node; + currentText = node.text; + var visited = saveStateAndInvoke(node, visitSourceFile); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + currentText = undefined; + return visited; + } + function visitor(node) { + return saveStateAndInvoke(node, dispatcher); + } + function dispatcher(node) { + return convertedLoopState + ? visitorForConvertedLoopWorker(node) + : visitorWorker(node); + } + function saveStateAndInvoke(node, f) { + var savedEnclosingFunction = enclosingFunction; + var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; + var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; + var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; + var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; + var savedEnclosingVariableStatement = enclosingVariableStatement; + var savedCurrentParent = currentParent; + var savedCurrentNode = currentNode; + var savedConvertedLoopState = convertedLoopState; + var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; + if (ts.nodeStartsNewLexicalEnvironment(node)) { + // don't treat content of nodes that start new lexical environment as part of converted loop copy or constructor body + isInConstructorWithCapturedSuper = false; + convertedLoopState = undefined; + } + onBeforeVisitNode(node); + var visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; + convertedLoopState = savedConvertedLoopState; + enclosingFunction = savedEnclosingFunction; + enclosingNonArrowFunction = savedEnclosingNonArrowFunction; + enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; + enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; + enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; + enclosingVariableStatement = savedEnclosingVariableStatement; + currentParent = savedCurrentParent; + currentNode = savedCurrentNode; + return visited; + } + function onBeforeVisitNode(node) { + if (currentNode) { + if (ts.isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + if (ts.isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== 185 /* ArrowFunction */) { + enclosingNonArrowFunction = currentNode; + if (!(ts.getEmitFlags(currentNode) & 131072 /* AsyncFunctionBody */)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + // keep track of the enclosing variable statement when in the context of + // variable statements, variable declarations, binding elements, and binding + // patterns. + switch (currentNode.kind) { + case 205 /* VariableStatement */: + enclosingVariableStatement = currentNode; + break; + case 224 /* VariableDeclarationList */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: + break; + default: + enclosingVariableStatement = undefined; + } + } + currentParent = currentNode; + currentNode = node; + } + function returnCapturedThis(node) { + return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return isInConstructorWithCapturedSuper && node.kind === 216 /* ReturnStatement */ && !node.expression; + } + function shouldCheckNode(node) { + return (node.transformFlags & 64 /* ES2015 */) !== 0 || + node.kind === 219 /* LabeledStatement */ || + (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + } + function visitorWorker(node) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { + return visitJavaScript(node); + } + else if (node.transformFlags & 128 /* ContainsES2015 */ || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) { + // we want to dive in this branch either if node has children with ES2015 specific syntax + // or we are inside constructor that captures result of the super call so all returns without expression should be + // rewritten. Note: we skip expressions since returns should never appear there return ts.visitEachChild(node, visitor, context); } else { return node; } } - function visitorWorker(node) { + function visitorForConvertedLoopWorker(node) { + var result; + if (shouldCheckNode(node)) { + result = visitJavaScript(node); + } + else { + result = visitNodesInConvertedLoop(node); + } + return result; + } + function visitNodesInConvertedLoop(node) { switch (node.kind) { - case 187 /* BinaryExpression */: - return visitBinaryExpression(node); + case 216 /* ReturnStatement */: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; + return visitReturnStatement(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 218 /* SwitchStatement */: + return visitSwitchStatement(node); + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 98 /* ThisKeyword */: + return visitThisKeyword(node); + case 70 /* Identifier */: + return visitIdentifier(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitJavaScript(node) { + switch (node.kind) { + case 114 /* StaticKeyword */: + return undefined; // elide static keyword + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 197 /* ClassExpression */: + return visitClassExpression(node); + case 144 /* Parameter */: + return visitParameter(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 185 /* ArrowFunction */: + return visitArrowFunction(node); + case 184 /* FunctionExpression */: + return visitFunctionExpression(node); + case 223 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 70 /* Identifier */: + return visitIdentifier(node); + case 224 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 219 /* LabeledStatement */: + return visitLabeledStatement(node); + case 209 /* DoStatement */: + return visitDoStatement(node); + case 210 /* WhileStatement */: + return visitWhileStatement(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 212 /* ForInStatement */: + return visitForInStatement(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 207 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 176 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 256 /* CatchClause */: + return visitCatchClause(node); + case 258 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 175 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 179 /* CallExpression */: + return visitCallExpression(node); + case 180 /* NewExpression */: + return visitNewExpression(node); + case 183 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 192 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 12 /* NoSubstitutionTemplateLiteral */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: + return visitTemplateLiteral(node); + case 181 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 194 /* TemplateExpression */: + return visitTemplateExpression(node); + case 195 /* YieldExpression */: + return visitYieldExpression(node); + case 196 /* SpreadElement */: + return visitSpreadElement(node); + case 96 /* SuperKeyword */: + return visitSuperKeyword(); + case 195 /* YieldExpression */: + // `yield` will be handled by a generators transform. + return ts.visitEachChild(node, visitor, context); + case 149 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } - function visitBinaryExpression(node) { - // We are here because ES7 adds support for the exponentiation operator. - var left = ts.visitNode(node.left, visitor, ts.isExpression); - var right = ts.visitNode(node.right, visitor, ts.isExpression); - if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var target = void 0; - var value = void 0; - if (ts.isElementAccessExpression(left)) { - // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), - /*location*/ left); - value = ts.createElementAccess(expressionTemp, argumentExpressionTemp, - /*location*/ left); - } - else if (ts.isPropertyAccessExpression(left)) { - // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` - var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); - target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name, - /*location*/ left); - value = ts.createPropertyAccess(expressionTemp, left.name, - /*location*/ left); - } - else { - // Transforms `a **= b` into `a = Math.pow(a, b)` - target = left; - value = left; - } - return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node); + function visitSourceFile(node) { + var statements = []; + startLexicalEnvironment(); + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + function visitSwitchStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + var result = ts.visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + function visitReturnStatement(node) { + ts.Debug.assert(convertedLoopState !== undefined); + convertedLoopState.nonLocalJumps |= 8 /* Return */; + return ts.createReturn(ts.createObjectLiteral([ + ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero()) + ])); + } + function visitThisKeyword(node) { + ts.Debug.assert(convertedLoopState !== undefined); + if (enclosingFunction && enclosingFunction.kind === 185 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. + convertedLoopState.containsLexicalThis = true; + return node; } - else if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */) { - // Transforms `a ** b` into `Math.pow(a, b)` - return ts.createMathPow(left, right, /*location*/ node); + return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); + } + function visitIdentifier(node) { + if (!convertedLoopState) { + return node; } - else { - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + if (ts.isGeneratedIdentifier(node)) { + return node; + } + if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { + return node; + } + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 215 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + var labelMarker = void 0; + if (!node.label) { + if (node.kind === 215 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. + labelMarker = "continue"; + } + } + else { + if (node.kind === 215 /* BreakStatement */) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + } + } + var returnExpression = ts.createLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + var outParams = convertedLoopState.loopOutParameters; + var expr = void 0; + for (var i = 0; i < outParams.length; i++) { + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } + else { + expr = ts.createBinary(expr, 25 /* CommaToken */, copyExpr); + } + } + returnExpression = ts.createBinary(expr, 25 /* CommaToken */, returnExpression); + } + return ts.createReturn(returnExpression); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ + function visitClassDeclaration(node) { + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); + ts.setOriginalNode(variable, node); + var statements = []; + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]), /*location*/ node); + ts.setOriginalNode(statement, node); + ts.startOnNewLine(statement); + statements.push(statement); + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) + ? ts.createExportDefault(ts.getLocalName(node)) + : ts.createExternalModuleExport(ts.getLocalName(node)); + ts.setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + var emitFlags = ts.getEmitFlags(node); + if ((emitFlags & 2097152 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(ts.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statement, emitFlags | 2097152 /* HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ + function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) + return transformClassLikeDeclarationToExpression(node); + } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ + function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + if (ts.getEmitFlags(node) & 32768 /* Indented */) { + ts.setEmitFlags(classFunction, 32768 /* Indented */); + } + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter + var inner = ts.createPartiallyEmittedExpression(classFunction); + inner.end = node.end; + ts.setEmitFlags(inner, 1536 /* NoComments */); + var outer = ts.createPartiallyEmittedExpression(inner); + outer.end = ts.skipTrivia(currentText, node.pos); + ts.setEmitFlags(outer, 1536 /* NoComments */); + return ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement + ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] + : [])); + } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function transformClassBody(node, extendsClauseElement) { + var statements = []; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, extendsClauseElement); + addClassMembers(statements, node); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 17 /* CloseBraceToken */); + var localName = ts.getLocalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)), + /*location*/ extendsClauseElement)); } } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ + function addConstructor(statements, node, extendsClauseElement) { + var constructor = ts.getFirstConstructorWithBody(node); + var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getDeclarationName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); + } + statements.push(constructorFunction); + } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. + return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; + } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 0; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } + if (constructor) { + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; + } + if (constructor) { + var body = saveStateAndInvoke(constructor, function (constructor) { + isInConstructorWithCapturedSuper = superCaptureStatus === 1 /* ReplaceSuperCapture */; + return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); + }); + ts.addRange(statements, body); + } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } + ts.addRange(statements, endLexicalEnvironment()); + var block = ts.createBlock(ts.createNodeArray(statements, + /*location*/ constructor ? constructor.body.statements : node.members), + /*location*/ constructor ? constructor.body : node, + /*multiLine*/ true); + if (!constructor) { + ts.setEmitFlags(block, 1536 /* NoComments */); + } + return block; + } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 216 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 208 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 204 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; + } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + var returnStatement = ts.createReturn(superCallExpression); + if (superCallExpression.kind !== 192 /* BinaryExpression */ + || superCallExpression.left.kind !== 179 /* CallExpression */) { + ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); + statements.push(returnStatement); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); + } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ + function visitParameter(node) { + if (node.dotDotDotToken) { + // rest parameters are elided + return undefined; + } + else if (ts.isBindingPattern(node.name)) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else if (node.initializer) { + // Initializers are elided + return ts.setOriginalNode(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + /*location*/ node), + /*original*/ node); + } + else { + return node; + } + } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ + function shouldAddDefaultValueAssignments(node) { + return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ + function addDefaultValueAssignmentsIfNeeded(statements, node) { + if (!shouldAddDefaultValueAssignments(node)) { + return; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + var name_36 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (dotDotDotToken) { + continue; + } + if (ts.isBindingPattern(name_36)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_36, initializer); + } + else if (initializer) { + addDefaultValueAssignmentForInitializer(statements, parameter, name_36, initializer); + } + } + } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + if (name.elements.length > 0) { + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 524288 /* CustomPrologue */)); + } + else if (initializer) { + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288 /* CustomPrologue */)); + } + } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ + function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = ts.visitNode(initializer, visitor, ts.isExpression); + var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer)), + /*location*/ parameter)) + ], /*location*/ parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */), + /*elseStatement*/ undefined, + /*location*/ parameter); + statement.startsOnNewLine = true; + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 524288 /* CustomPrologue */); + statements.push(statement); + } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return node && node.dotDotDotToken && node.name.kind === 70 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var parameter = ts.lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return; + } + // `declarationName` is the name of the local declaration for the parameter. + var declarationName = ts.getMutableClone(parameter.name); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. + var expressionName = ts.getSynthesizedClone(parameter.name); + var restIndex = node.parameters.length - 1; + var temp = ts.createLoopVariable(); + // var param = []; + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ]), + /*location*/ parameter), 524288 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } + var forStatement = ts.createFor(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) + ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), + /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ + ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ? temp + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), + /*location*/ parameter)) + ])); + ts.setEmitFlags(forStatement, 524288 /* CustomPrologue */); + ts.startOnNewLine(forStatement); + statements.push(forStatement); + } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ + function addCaptureThisForNodeIfNeeded(statements, node) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 185 /* ArrowFunction */) { + captureThisForNode(statements, node, ts.createThis()); + } + } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 524288 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ + function addClassMembers(statements, node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 203 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 149 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); + break; + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); + } + break; + case 150 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ + function transformSemicolonClassElementToStatement(member) { + return ts.createEmptyStatement(/*location*/ member); + } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ + function transformClassMethodDeclarationToStatement(receiver, member) { + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); + ts.setSourceMapRange(memberFunction, sourceMapRange); + var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction), + /*location*/ member); + ts.setOriginalNode(statement, member); + ts.setCommentRange(statement, commentRange); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + return statement; + } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ + function transformAccessorsToStatement(receiver, accessors) { + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); + return statement; + } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ + function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { + var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. + var target = ts.getMutableClone(receiver); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); + var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); + var properties = []; + if (getAccessor) { + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); + var getter = ts.createPropertyAssignment("get", getterFunction); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); + var setter = ts.createPropertyAssignment("set", setterFunction); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + target, + propertyName, + ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) + ]); + if (startsOnNewLine) { + call.startsOnNewLine = true; + } + return call; + } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ + function visitArrowFunction(node) { + if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node), node); + ts.setOriginalNode(func, node); + ts.setEmitFlags(func, 8 /* CapturesThis */); + return func; + } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ + function visitFunctionExpression(node) { + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ + function visitFunctionDeclaration(node) { + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, node.modifiers, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.transformFlags & 64 /* ES2015 */ + ? transformFunctionBody(node) + : ts.visitFunctionBody(node.body, visitor, context)); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ + function transformFunctionLikeToExpression(node, location, name) { + var savedContainingNonArrowFunction = enclosingNonArrowFunction; + if (node.kind !== 185 /* ArrowFunction */) { + enclosingNonArrowFunction = node; + } + var expression = ts.setOriginalNode(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), + /*original*/ node); + enclosingNonArrowFunction = savedContainingNonArrowFunction; + return expression; + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ + function transformFunctionBody(node) { + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line + var statementsLocation; + var closeBraceLocation; + var statements = []; + var body = node.body; + var statementOffset; + resumeLexicalEnvironment(); + if (ts.isBlock(body)) { + // ensureUseStrict is false because no new prologue-directive should be added. + // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); + } + addCaptureThisForNodeIfNeeded(statements, node); + addDefaultValueAssignmentsIfNeeded(statements, node); + addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); + // If we added any generated statements, this must be a multi-line block. + if (!multiLine && statements.length > 0) { + multiLine = true; + } + if (ts.isBlock(body)) { + statementsLocation = body.statements; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. + if (!multiLine && body.multiLine) { + multiLine = true; + } + } + else { + ts.Debug.assert(node.kind === 185 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. + statementsLocation = ts.moveRangeEnd(body, -1); + var equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { + if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } + else { + multiLine = true; + } + } + var expression = ts.visitNode(body, visitor, ts.isExpression); + var returnStatement = ts.createReturn(expression, /*location*/ body); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); + statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. + closeBraceLocation = body; + } + var lexicalEnvironment = context.endLexicalEnvironment(); + ts.addRange(statements, lexicalEnvironment); + // If we added any final generated statements, this must be a multi-line block + if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + multiLine = true; + } + var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); + if (!multiLine && singleLine) { + ts.setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + ts.setTokenSourceMapRange(block, 17 /* CloseBraceToken */, closeBraceLocation); + } + ts.setOriginalNode(block, node.body); + return block; + } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ + function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. + switch (node.expression.kind) { + case 183 /* ParenthesizedExpression */: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 192 /* BinaryExpression */: + return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. + if (!needsDestructuringValue) { + switch (node.expression.kind) { + case 183 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 192 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ + function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. + if (ts.isDestructuringAssignment(node)) { + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); + } + } + function visitVariableStatement(node) { + if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { + // we are inside a converted loop - hoist variable declarations + var assignments = void 0; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + var assignment = void 0; + if (ts.isBindingPattern(decl.name)) { + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); + } + else { + assignment = ts.createBinary(decl.name, 57 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + } + (assignments || (assignments = [])).push(assignment); + } + } + if (assignments) { + return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25 /* CommaToken */, acc); }), node); + } + else { + // none of declarations has initializer - the entire variable statement can be deleted + return undefined; + } + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ + function visitVariableDeclarationList(node) { + if (node.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration)); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); + ts.setOriginalNode(declarationList, node); + ts.setCommentRange(declarationList, node); + if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + && (ts.isBindingPattern(node.declarations[0].name) + || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + var firstDeclaration = ts.firstOrUndefined(declarations); + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + } + return declarationList; + } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) + || (isCapturedInFunction + && isDeclaredInLoop + && ts.isBlock(enclosingBlockScopeContainer) + && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); + var emitExplicitInitializer = !emittedAsTopLevel + && enclosingBlockScopeContainer.kind !== 212 /* ForInStatement */ + && enclosingBlockScopeContainer.kind !== 213 /* ForOfStatement */ + && (!resolver.isDeclarationWithCollidingName(node) + || (isDeclaredInLoop + && !isCapturedInFunction + && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); + return emitExplicitInitializer; + } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized + var name = node.name; + if (ts.isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + var clone_3 = ts.getMutableClone(node); + clone_3.initializer = ts.createVoidZero(); + return clone_3; + } + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node) { + // If we are here it is because the name contains a binding pattern. + if (ts.isBindingPattern(node.name)) { + var hoistTempVariables = enclosingVariableStatement + && ts.hasModifier(enclosingVariableStatement, 1 /* Export */); + return ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, hoistTempVariables); + } + return ts.visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = ts.createMap(); + } + convertedLoopState.labels[node.label.text] = node.label.text; + } + var result; + if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { + result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); + } + else { + result = ts.visitEachChild(node, visitor, context); + } + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } + return result; + } + function visitDoStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitWhileStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + function visitForInStatement(node) { + return convertIterationStatementBodyIfNecessary(node); + } + /** + * Visits a ForOfStatement and converts it into a compatible ForStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node) { + return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); + } + function convertForOfToFor(node, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + var initializer = node.initializer; + var statements = []; + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var counter = ts.createLoopVariable(); + var rhsReference = expression.kind === 70 /* Identifier */ + ? ts.createUniqueName(expression.text) + : ts.createTempVariable(/*recordTempVariable*/ undefined); + var elementAccess = ts.createElementAccess(rhsReference, counter); + // Initialize LHS + // var v = _a[_i]; + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.flags & 3 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, elementAccess); + var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); + ts.setOriginalNode(declarationList, initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. + var firstDeclaration = declarations[0]; + var lastDeclaration = ts.lastOrUndefined(declarations); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) + ], /*location*/ ts.moveRangePos(initializer, -1)), initializer), + /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignment = ts.createAssignment(initializer, elementAccess); + if (ts.isDestructuringAssignment(assignment)) { + // This is a destructuring pattern, so we flatten the destructuring instead. + statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0 /* All */))); + } + else { + // Currently there is not way to check that assignment is binary expression of destructing assignment + // so we have to cast never type to binaryExpression + assignment.end = initializer.end; + statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); + } + } + var bodyLocation; + var statementsLocation; + if (convertedLoopBodyStatements) { + ts.addRange(statements, convertedLoopBodyStatements); + } + else { + var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } + else { + statements.push(statement); + } + } + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + // The old emitter does not emit source maps for the block. + // We add the location to preserve comments. + var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), + /*location*/ bodyLocation); + ts.setEmitFlags(body, 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), + ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) + ], /*location*/ node.expression), 1048576 /* NoHoisting */), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), + /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); + return forStatement; + } + /** + * Visits an ObjectLiteralExpression with computed propety names. + * + * @param node An ObjectLiteralExpression node. + */ + function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. + var properties = node.properties; + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialProperties = numProperties; + for (var i = 0; i < numProperties; i++) { + var property = properties[i]; + if (property.transformFlags & 16777216 /* ContainsYield */ + || property.name.kind === 142 /* ComputedPropertyName */) { + numInitialProperties = i; + break; + } + } + ts.Debug.assert(numInitialProperties !== numProperties); + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. + var expressions = []; + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + /*location*/ undefined, node.multiLine), 32768 /* Indented */)); + if (node.multiLine) { + assignment.startsOnNewLine = true; + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line + expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); + return ts.inlineExpressions(expressions); + } + function shouldConvertIterationStatementBody(node) { + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node) { + if (node.kind === 70 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, convert) { + if (!shouldConvertIterationStatementBody(node)) { + var saveAllowedNonLabeledJumps = void 0; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + var functionName = ts.createUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 224 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + // variables that will be passed to the loop as parameters + var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop + var loopOutParameters = []; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + } + } + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (outerConvertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (outerConvertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + } + if (outerConvertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = outerConvertedLoopState.thisName; + } + if (outerConvertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + } + } + startLexicalEnvironment(); + var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); + var currentState = convertedLoopState; + convertedLoopState = outerConvertedLoopState; + if (loopOutParameters.length || lexicalEnvironment) { + var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); + loopBody = ts.createBlock(statements_4, /*location*/ undefined, /*multiline*/ true); + } + if (!ts.isBlock(loopBody)) { + loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); + } + var isAsyncBlockContainingAwait = enclosingNonArrowFunction + && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072 /* AsyncFunctionBody */) !== 0 + && (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; + var loopBodyFlags = 0; + if (currentState.containsLexicalThis) { + loopBodyFlags |= 8 /* CapturesThis */; + } + if (isAsyncBlockContainingAwait) { + loopBodyFlags |= 131072 /* AsyncFunctionBody */; + } + var convertedLoopVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, isAsyncBlockContainingAwait ? ts.createToken(38 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, loopParameters, + /*type*/ undefined, loopBody), loopBodyFlags)) + ]), 1048576 /* NoHoisting */)); + var statements = [convertedLoopVariable]; + var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary + if (currentState.argumentsName) { + // if alias for arguments is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.argumentsName = currentState.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); + } + } + if (currentState.thisName) { + // if alias for this is set + if (outerConvertedLoopState) { + // pass it to outer converted loop + outerConvertedLoopState.thisName = currentState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); + } + } + if (currentState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (outerConvertedLoopState) { + // pass them to outer converted loop + outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + } + else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + // hoist collected variable declarations + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; + extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); + } + } + } + // add extra variables to hold out parameters if necessary + if (loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; + extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); + } + } + // create variable statement to hold all introduced variable declarations + if (extraVariableDeclarations) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + } + var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); + var loop; + if (convert) { + loop = convert(node, convertedLoopBodyStatements); + } + else { + loop = ts.getMutableClone(node); + // clean statement part + loop.statement = undefined; + // visit childnodes to transform initializer/condition/incrementor parts + loop = ts.visitEachChild(loop, visitor, context); + // set loop statement + loop.statement = ts.createBlock(convertedLoopBodyStatements, + /*location*/ undefined, + /*multiline*/ true); + // reset and re-aggregate the transform flags + loop.transformFlags = 0; + ts.aggregateTransformFlags(loop); + } + statements.push(currentParent.kind === 219 /* LabeledStatement */ + ? ts.createLabel(currentParent.label, loop) + : loop); + return statements; + } + function copyOutParameter(outParam, copyDirection) { + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 57 /* EqualsToken */, source); + } + function copyOutParameters(outParams, copyDirection, statements) { + for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { + var outParam = outParams_1[_i]; + statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + } + } + function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { + var outerConvertedLoopState = convertedLoopState; + var statements = []; + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && + !state.labeledNonLocalBreaks && + !state.labeledNonLocalContinues; + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); + var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38 /* AsteriskToken */), call) : call; + if (isSimpleLoop) { + statements.push(ts.createStatement(callResult)); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + } + else { + var loopResultName = ts.createUniqueName("state"); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + var returnStatement = void 0; + if (outerConvertedLoopState) { + outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + returnStatement = ts.createReturn(loopResultName); + } + else { + returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); + } + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 33 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 33 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + var caseClauses = []; + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = ts.createMap(); + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = ts.createMap(); + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + var label = ts.createIdentifier(labelText); + statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(ts.createReturn(loopResultName)); + } + caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); + } + } + function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + var name = decl.name; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + } + } + } + else { + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var outParamName = ts.createUniqueName("out_" + name.text); + loopOutParameters.push({ originalName: name, outParamName: outParamName }); + } + } + } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ + function addObjectLiteralMembers(expressions, node, receiver, start) { + var properties = node.properties; + var numProperties = properties.length; + for (var i = start; i < numProperties; i++) { + var property = properties[i]; + switch (property.kind) { + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); + } + break; + case 257 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 258 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 149 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); + break; + default: + ts.Debug.failBadSyntaxKind(node); + break; + } + } + } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), + /*location*/ property); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) { + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), + /*location*/ method); + if (startsOnNewLine) { + expression.startsOnNewLine = true; + } + return expression; + } + function visitCatchClause(node) { + ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name)); + var temp = ts.createTempVariable(undefined); + var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); + var list = ts.createVariableDeclarationList(vars, /*location*/ node.variableDeclaration, /*flags*/ node.variableDeclaration.flags); + var destructure = ts.createVariableStatement(undefined, list); + return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + function addStatementToStartOfBlock(block, statement) { + var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); + return ts.updateBlock(block, [statement].concat(transformedStatements)); + } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ + function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. + ts.Debug.assert(!ts.isComputedPropertyName(node.name)); + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.createPropertyAssignment(node.name, functionExpression, + /*location*/ node); + } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ + function visitShorthandPropertyAssignment(node) { + return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), + /*location*/ node); + } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ + function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. + return ts.visitEachChild(node, visitor, context); + } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ + function visitArrayLiteralExpression(node) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ + function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 96 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall; + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 96 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; + } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ + function visitNewExpression(node) { + // We are here because we contain a SpreadElementExpression. + ts.Debug.assert((node.transformFlags & 524288 /* ContainsSpread */) !== 0); + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() + var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); + } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ + function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. + var numElements = elements.length; + var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { + return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); + })); + if (segments.length === 1) { + var firstElement = elements[0]; + return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 /* ArrayLiteralExpression */ + ? ts.createArraySlice(segments[0]) + : segments[0]; + } + // Rewrite using the pattern .concat(, , ...) + return ts.createArrayConcat(segments.shift(), segments); + } + function partitionSpread(node) { + return ts.isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return ts.map(chunk, visitExpressionOfSpread); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), + /*location*/ undefined, multiLine); + } + function visitSpreadElement(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ + function visitExpressionOfSpread(node) { + return ts.visitNode(node.expression, visitor, ts.isExpression); + } + /** + * Visits a template literal. + * + * @param node A template literal. + */ + function visitTemplateLiteral(node) { + return ts.createLiteral(node.text, /*location*/ node); + } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ + function visitTaggedTemplateExpression(node) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Allocate storage for the template site object + var temp = ts.createTempVariable(hoistVariableDeclaration); + // Build up the template arguments and the raw and cooked strings for the template. + var templateArguments = [temp]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(ts.createLiteral(template.text)); + rawStrings.push(getRawLiteral(template)); + } + else { + cookedStrings.push(ts.createLiteral(template.head.text)); + rawStrings.push(getRawLiteral(template.head)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); + rawStrings.push(getRawLiteral(templateSpan.literal)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + // NOTE: The parentheses here is entirely optional as we are now able to auto- + // parenthesize when rebuilding the tree. This should be removed in a + // future version. It is here for now to match our existing emit. + return ts.createParen(ts.inlineExpressions([ + ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), + ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), + ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) + ])); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 12 /* NoSubstitutionTemplateLiteral */ || node.kind === 15 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.createLiteral(text, /*location*/ node); + } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ + function visitTemplateExpression(node) { + var expressions = []; + addTemplateHead(expressions, node); + addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var expression = ts.reduceLeft(expressions, ts.createAdd); + if (ts.nodeIsSynthesized(expression)) { + ts.setTextRange(expression, node); + } + return expression; + } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ + function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateHead(expressions, node) { + if (!shouldAddTemplateHead(node)) { + return; + } + expressions.push(ts.createLiteral(node.head.text)); + } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ + function addTemplateSpans(expressions, node) { + for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { + var span_6 = _a[_i]; + expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (span_6.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span_6.literal.text)); + } + } + } + /** + * Visits the `super` keyword + */ + function visitSuperKeyword() { + return enclosingNonAsyncFunctionBody + && ts.isClassElement(enclosingNonAsyncFunctionBody) + && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) + && currentParent.kind !== 179 /* CallExpression */ + ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") + : ts.createIdentifier("_super"); + } + /** + * Called by the printer just before a node is printed. + * + * @param node The node to be printed. + */ + function onEmitNode(emitContext, node, emitCallback) { + var savedEnclosingFunction = enclosingFunction; + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + enclosingFunction = node; + } + previousOnEmitNode(emitContext, node, emitCallback); + enclosingFunction = savedEnclosingFunction; + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(70 /* Identifier */); + } + } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(98 /* ThisKeyword */); + context.enableEmitNotification(150 /* Constructor */); + context.enableEmitNotification(149 /* MethodDeclaration */); + context.enableEmitNotification(151 /* GetAccessor */); + context.enableEmitNotification(152 /* SetAccessor */); + context.enableEmitNotification(185 /* ArrowFunction */); + context.enableEmitNotification(184 /* FunctionExpression */); + context.enableEmitNotification(225 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param emitContext The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + if (ts.isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + /** + * Hooks substitutions for non-expression identifiers. + */ + function substituteIdentifier(node) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var original = ts.getParseTreeNode(node, ts.isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return ts.getGeneratedNameForNode(original); + } + } + return node; + } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ + function isNameOfDeclarationWithCollidingName(node) { + var parent = node.parent; + switch (parent.kind) { + case 174 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 223 /* VariableDeclaration */: + return parent.name === node + && resolver.isDeclarationWithCollidingName(parent); + } + return false; + } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ + function substituteExpression(node) { + switch (node.kind) { + case 70 /* Identifier */: + return substituteExpressionIdentifier(node); + case 98 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration) { + return ts.getGeneratedNameForNode(declaration.name); + } + } + return node; + } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && enclosingFunction + && ts.getEmitFlags(enclosingFunction) & 8 /* CapturesThis */) { + return ts.createIdentifier("_this", /*location*/ node); + } + return node; + } + function getClassMemberPrefix(node, member) { + var expression = ts.getLocalName(node); + return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (ts.some(constructor.parameters)) { + return false; + } + var statement = ts.firstOrUndefined(constructor.body.statements); + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207 /* ExpressionStatement */) { + return false; + } + var statementExpression = statement.expression; + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179 /* CallExpression */) { + return false; + } + var callTarget = statementExpression.expression; + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 96 /* SuperKeyword */) { + return false; + } + var callArgument = ts.singleOrUndefined(statementExpression.arguments); + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196 /* SpreadElement */) { + return false; + } + var expression = callArgument.expression; + return ts.isIdentifier(expression) && expression.text === "arguments"; + } } - ts.transformES7 = transformES7; + ts.transformES2015 = transformES2015; + function createExtendsHelper(context, name) { + context.requestEmitHelper(extendsHelper); + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ + name, + ts.createIdentifier("_super") + ]); + } + var extendsHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };" + }; })(ts || (ts = {})); /// /// @@ -46820,7 +51946,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,12 +51996,15 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (node.transformFlags & 1024 /* ContainsGenerator */) { - currentSourceFile = node; - node = ts.visitEachChild(node, visitor, context); - currentSourceFile = undefined; + if (ts.isDeclarationFile(node) + || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + return node; } - return node; + currentSourceFile = node; + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + return visited; } /** * Visits a node. @@ -46890,10 +52019,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 512 /* Generator */) { + else if (transformFlags & 256 /* Generator */) { return visitGenerator(node); } - else if (transformFlags & 1024 /* ContainsGenerator */) { + else if (transformFlags & 512 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -46907,13 +52036,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 204 /* DoStatement */: + case 209 /* DoStatement */: return visitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return visitWhileStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return visitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -46926,30 +52055,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return visitFunctionExpression(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return visitAccessorDeclaration(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return visitVariableStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return visitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return visitForInStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return visitBreakStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return visitContinueStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 16777216 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -46964,21 +52093,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return visitBinaryExpression(node); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return visitConditionalExpression(node); - case 190 /* YieldExpression */: + case 195 /* YieldExpression */: return visitYieldExpression(node); - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 174 /* CallExpression */: + case 179 /* CallExpression */: return visitCallExpression(node); - case 175 /* NewExpression */: + case 180 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -46991,9 +52120,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 179 /* FunctionExpression */: + case 184 /* FunctionExpression */: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -47011,12 +52140,11 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, + /*decorators*/ undefined, node.modifiers, /*asteriskToken*/ undefined, node.name, - /*typeParameters*/ undefined, node.parameters, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node), node); } @@ -47050,10 +52178,11 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, node.name, - /*typeParameters*/ undefined, node.parameters, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node), node); } @@ -47099,6 +52228,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +52242,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47120,7 +52251,7 @@ var ts; operationLocations = undefined; state = ts.createTempVariable(/*recordTempVariable*/ undefined); // Build the generator - startLexicalEnvironment(); + resumeLexicalEnvironment(); var statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); @@ -47132,6 +52263,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47150,13 +52282,13 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 16777216 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 524288 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -47189,23 +52321,23 @@ var ts; } } function isCompoundAssignment(kind) { - return kind >= 57 /* FirstCompoundAssignment */ - && kind <= 68 /* LastCompoundAssignment */; + return kind >= 58 /* FirstCompoundAssignment */ + && kind <= 69 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 57 /* PlusEqualsToken */: return 35 /* PlusToken */; - case 58 /* MinusEqualsToken */: return 36 /* MinusToken */; - case 59 /* AsteriskEqualsToken */: return 37 /* AsteriskToken */; - case 60 /* AsteriskAsteriskEqualsToken */: return 38 /* AsteriskAsteriskToken */; - case 61 /* SlashEqualsToken */: return 39 /* SlashToken */; - case 62 /* PercentEqualsToken */: return 40 /* PercentToken */; - case 63 /* LessThanLessThanEqualsToken */: return 43 /* LessThanLessThanToken */; - case 64 /* GreaterThanGreaterThanEqualsToken */: return 44 /* GreaterThanGreaterThanToken */; - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanGreaterThanToken */; - case 66 /* AmpersandEqualsToken */: return 46 /* AmpersandToken */; - case 67 /* BarEqualsToken */: return 47 /* BarToken */; - case 68 /* CaretEqualsToken */: return 48 /* CaretToken */; + case 58 /* PlusEqualsToken */: return 36 /* PlusToken */; + case 59 /* MinusEqualsToken */: return 37 /* MinusToken */; + case 60 /* AsteriskEqualsToken */: return 38 /* AsteriskToken */; + case 61 /* AsteriskAsteriskEqualsToken */: return 39 /* AsteriskAsteriskToken */; + case 62 /* SlashEqualsToken */: return 40 /* SlashToken */; + case 63 /* PercentEqualsToken */: return 41 /* PercentToken */; + case 64 /* LessThanLessThanEqualsToken */: return 44 /* LessThanLessThanToken */; + case 65 /* GreaterThanGreaterThanEqualsToken */: return 45 /* GreaterThanGreaterThanToken */; + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanGreaterThanToken */; + case 67 /* AmpersandEqualsToken */: return 47 /* AmpersandToken */; + case 68 /* BarEqualsToken */: return 48 /* BarToken */; + case 69 /* CaretEqualsToken */: return 49 /* CaretToken */; } } /** @@ -47218,7 +52350,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 172 /* PropertyAccessExpression */: + case 177 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -47230,7 +52362,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -47249,7 +52381,7 @@ var ts; } var operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return ts.createBinary(target, 56 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); + return ts.createBinary(target, 57 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node); } else { return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression)); @@ -47262,7 +52394,7 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 24 /* CommaToken */) { + else if (node.operatorToken.kind === 25 /* CommaToken */) { return visitCommaExpression(node); } // [source] @@ -47273,10 +52405,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -47317,7 +52449,7 @@ var ts; var resultLabel = defineLabel(); var resultLocal = declareLocal(); emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + if (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */) { // Logical `&&` shortcuts when the left-hand operand is falsey. emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } @@ -47348,7 +52480,7 @@ var ts; visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 24 /* CommaToken */) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 25 /* CommaToken */) { visit(node.left); visit(node.right); } @@ -47429,7 +52561,7 @@ var ts; * @param node The node to visit. */ function visitArrayLiteralExpression(node) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); } /** * Visits an array of expressions containing one or more YieldExpression nodes @@ -47438,7 +52570,7 @@ var ts; * @param elements The elements to visit. * @param multiLine Whether array literals created should be emitted on multiple lines. */ - function visitElements(elements, multiLine) { + function visitElements(elements, leadingElement, location, multiLine) { // [source] // ar = [1, yield, 2]; // @@ -47452,19 +52584,24 @@ var ts; var temp = declareLocal(); var hasAssignedTemp = false; if (numInitialElements > 0) { - emitAssignment(temp, ts.createArrayLiteral(ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements))); + var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements); + emitAssignment(temp, ts.createArrayLiteral(leadingElement + ? [leadingElement].concat(initialElements) : initialElements)); + leadingElement = undefined; hasAssignedTemp = true; } var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine); function reduceElement(expressions, element) { if (containsYield(element) && expressions.length > 0) { emitAssignment(temp, hasAssignedTemp - ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions)]) - : ts.createArrayLiteral(expressions)); + ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)]) + : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, + /*location*/ undefined, multiLine)); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } expressions.push(ts.visitNode(element, visitor, ts.isExpression)); @@ -47530,10 +52667,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -47550,7 +52687,7 @@ var ts; // .mark resumeLabel // _b.apply(_a, _c.concat([%sent%, 2])); var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false), + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); @@ -47568,7 +52705,8 @@ var ts; // .mark resumeLabel // new (_b.apply(_a, _c.concat([%sent%, 2]))); var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, /*multiLine*/ false)), + return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), /*typeArguments*/ undefined, [], /*location*/ node), node); } @@ -47599,35 +52737,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 199 /* Block */: + case 204 /* Block */: return transformAndEmitBlock(node); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return transformAndEmitIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return transformAndEmitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return transformAndEmitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return transformAndEmitWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement, /*optional*/ true)); @@ -48047,7 +53185,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 250 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 254 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -48060,7 +53198,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 249 /* CaseClause */) { + if (clause.kind === 253 /* CaseClause */) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -48191,7 +53329,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -48202,9 +53340,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,12 +53359,12 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); - return clone_7; + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_6 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -48368,7 +53506,7 @@ var ts; if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = ts.createMap(); - context.enableSubstitution(69 /* Identifier */); + context.enableSubstitution(70 /* Identifier */); } renamedCatchVariables[text] = true; renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; @@ -48625,7 +53763,7 @@ var ts; if (labelExpressions === undefined) { labelExpressions = []; } - var expression = ts.createSynthesizedNode(8 /* NumericLiteral */); + var expression = ts.createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -48634,7 +53772,7 @@ var ts; } return expression; } - return ts.createNode(193 /* OmittedExpression */); + return ts.createOmittedExpression(); } /** * Creates a numeric literal for the provided instruction. @@ -48812,17 +53950,14 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), - /*typeArguments*/ undefined, [ - ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(state)], - /*type*/ undefined, ts.createBlock(buildResult, - /*location*/ undefined, - /*multiLine*/ buildResult.length > 0)), 4194304 /* ReuseTempVariableScope */) - ]); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*location*/ undefined, + /*multiLine*/ buildResult.length > 0)), 262144 /* ReuseTempVariableScope */)); } /** * Builds the statements for the generator function body. @@ -49193,6 +54328,76 @@ var ts; } } ts.transformGenerators = transformGenerators; + function createGeneratorHelper(context, body) { + context.requestEmitHelper(generatorHelper); + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + var generatorHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + }; var _a; })(ts || (ts = {})); /// @@ -49200,2329 +54405,2634 @@ var ts; /*@internal*/ var ts; (function (ts) { - var ES6SubstitutionFlags; - (function (ES6SubstitutionFlags) { - /** Enables substitutions for captured `this` */ - ES6SubstitutionFlags[ES6SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; - /** Enables substitutions for block-scoped bindings. */ - ES6SubstitutionFlags[ES6SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; - })(ES6SubstitutionFlags || (ES6SubstitutionFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; - var resolver = context.getEmitResolver(); + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + function transformES5(context) { var previousOnSubstituteNode = context.onSubstituteNode; - var previousOnEmitNode = context.onEmitNode; - context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; - var currentText; - var currentParent; - var currentNode; - var enclosingVariableStatement; - var enclosingBlockScopeContainer; - var enclosingBlockScopeContainerParent; - var enclosingFunction; - var enclosingNonArrowFunction; - var enclosingNonAsyncFunctionBody; - /** - * Used to track if we are emitting body of the converted loop - */ - var convertedLoopState; - /** - * Keeps track of whether substitutions have been enabled for specific cases. - * They are persisted between each SourceFile transformation and should not - * be reset. - */ - var enabledSubstitutions; + context.enableSubstitution(177 /* PropertyAccessExpression */); + context.enableSubstitution(257 /* PropertyAssignment */); return transformSourceFile; + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ function transformSourceFile(node) { - currentSourceFile = node; - currentText = node.text; - return ts.visitNode(node, visitor, ts.isSourceFile); - } - function visitor(node) { - return saveStateAndInvoke(node, dispatcher); - } - function dispatcher(node) { - return convertedLoopState - ? visitorForConvertedLoopWorker(node) - : visitorWorker(node); - } - function saveStateAndInvoke(node, f) { - var savedEnclosingFunction = enclosingFunction; - var savedEnclosingNonArrowFunction = enclosingNonArrowFunction; - var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody; - var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer; - var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent; - var savedEnclosingVariableStatement = enclosingVariableStatement; - var savedCurrentParent = currentParent; - var savedCurrentNode = currentNode; - var savedConvertedLoopState = convertedLoopState; - if (ts.nodeStartsNewLexicalEnvironment(node)) { - // don't treat content of nodes that start new lexical environment as part of converted loop copy - convertedLoopState = undefined; - } - onBeforeVisitNode(node); - var visited = f(node); - convertedLoopState = savedConvertedLoopState; - enclosingFunction = savedEnclosingFunction; - enclosingNonArrowFunction = savedEnclosingNonArrowFunction; - enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody; - enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer; - enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent; - enclosingVariableStatement = savedEnclosingVariableStatement; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - return visited; - } - function shouldCheckNode(node) { - return (node.transformFlags & 64 /* ES6 */) !== 0 || - node.kind === 214 /* LabeledStatement */ || - (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); - } - function visitorWorker(node) { - if (shouldCheckNode(node)) { - return visitJavaScript(node); - } - else if (node.transformFlags & 128 /* ContainsES6 */) { - return ts.visitEachChild(node, visitor, context); - } - else { - return node; - } - } - function visitorForConvertedLoopWorker(node) { - var result; - if (shouldCheckNode(node)) { - result = visitJavaScript(node); - } - else { - result = visitNodesInConvertedLoop(node); - } - return result; - } - function visitNodesInConvertedLoop(node) { - switch (node.kind) { - case 211 /* ReturnStatement */: - return visitReturnStatement(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - case 213 /* SwitchStatement */: - return visitSwitchStatement(node); - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: - return visitBreakOrContinueStatement(node); - case 97 /* ThisKeyword */: - return visitThisKeyword(node); - case 69 /* Identifier */: - return visitIdentifier(node); - default: - return ts.visitEachChild(node, visitor, context); - } - } - function visitJavaScript(node) { - switch (node.kind) { - case 82 /* ExportKeyword */: - return node; - case 221 /* ClassDeclaration */: - return visitClassDeclaration(node); - case 192 /* ClassExpression */: - return visitClassExpression(node); - case 142 /* Parameter */: - return visitParameter(node); - case 220 /* FunctionDeclaration */: - return visitFunctionDeclaration(node); - case 180 /* ArrowFunction */: - return visitArrowFunction(node); - case 179 /* FunctionExpression */: - return visitFunctionExpression(node); - case 218 /* VariableDeclaration */: - return visitVariableDeclaration(node); - case 69 /* Identifier */: - return visitIdentifier(node); - case 219 /* VariableDeclarationList */: - return visitVariableDeclarationList(node); - case 214 /* LabeledStatement */: - return visitLabeledStatement(node); - case 204 /* DoStatement */: - return visitDoStatement(node); - case 205 /* WhileStatement */: - return visitWhileStatement(node); - case 206 /* ForStatement */: - return visitForStatement(node); - case 207 /* ForInStatement */: - return visitForInStatement(node); - case 208 /* ForOfStatement */: - return visitForOfStatement(node); - case 202 /* ExpressionStatement */: - return visitExpressionStatement(node); - case 171 /* ObjectLiteralExpression */: - return visitObjectLiteralExpression(node); - case 254 /* ShorthandPropertyAssignment */: - return visitShorthandPropertyAssignment(node); - case 170 /* ArrayLiteralExpression */: - return visitArrayLiteralExpression(node); - case 174 /* CallExpression */: - return visitCallExpression(node); - case 175 /* NewExpression */: - return visitNewExpression(node); - case 178 /* ParenthesizedExpression */: - return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 187 /* BinaryExpression */: - return visitBinaryExpression(node, /*needsDestructuringValue*/ true); - case 11 /* NoSubstitutionTemplateLiteral */: - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: - return visitTemplateLiteral(node); - case 176 /* TaggedTemplateExpression */: - return visitTaggedTemplateExpression(node); - case 189 /* TemplateExpression */: - return visitTemplateExpression(node); - case 190 /* YieldExpression */: - return visitYieldExpression(node); - case 95 /* SuperKeyword */: - return visitSuperKeyword(node); - case 190 /* YieldExpression */: - // `yield` will be handled by a generators transform. - return ts.visitEachChild(node, visitor, context); - case 147 /* MethodDeclaration */: - return visitMethodDeclaration(node); - case 256 /* SourceFile */: - return visitSourceFileNode(node); - case 200 /* VariableStatement */: - return visitVariableStatement(node); - default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); - } - } - function onBeforeVisitNode(node) { - if (currentNode) { - if (ts.isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - if (ts.isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== 180 /* ArrowFunction */) { - enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - // keep track of the enclosing variable statement when in the context of - // variable statements, variable declarations, binding elements, and binding - // patterns. - switch (currentNode.kind) { - case 200 /* VariableStatement */: - enclosingVariableStatement = currentNode; - break; - case 219 /* VariableDeclarationList */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - break; - default: - enclosingVariableStatement = undefined; - } - } - currentParent = currentNode; - currentNode = node; - } - function visitSwitchStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - // for switch statement allow only non-labeled break - convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; - var result = ts.visitEachChild(node, visitor, context); - convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; - return result; - } - function visitReturnStatement(node) { - ts.Debug.assert(convertedLoopState !== undefined); - convertedLoopState.nonLocalJumps |= 8 /* Return */; - return ts.createReturn(ts.createObjectLiteral([ - ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression - ? ts.visitNode(node.expression, visitor, ts.isExpression) - : ts.createVoidZero()) - ])); - } - function visitThisKeyword(node) { - ts.Debug.assert(convertedLoopState !== undefined); - if (enclosingFunction && enclosingFunction.kind === 180 /* ArrowFunction */) { - // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword. - convertedLoopState.containsLexicalThis = true; - return node; - } - return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this")); - } - function visitIdentifier(node) { - if (!convertedLoopState) { - return node; - } - if (ts.isGeneratedIdentifier(node)) { - return node; - } - if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) { - return node; - } - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); - } - function visitBreakOrContinueStatement(node) { - if (convertedLoopState) { - // check if we can emit break/continue as is - // it is possible if either - // - break/continue is labeled and label is located inside the converted loop - // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 210 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || - (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); - if (!canUseBreakOrContinue) { - var labelMarker = void 0; - if (!node.label) { - if (node.kind === 210 /* BreakStatement */) { - convertedLoopState.nonLocalJumps |= 2 /* Break */; - labelMarker = "break"; - } - else { - convertedLoopState.nonLocalJumps |= 4 /* Continue */; - // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. - labelMarker = "continue"; - } - } - else { - if (node.kind === 210 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); - } - else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); - } - } - var returnExpression = ts.createLiteral(labelMarker); - if (convertedLoopState.loopOutParameters.length) { - var outParams = convertedLoopState.loopOutParameters; - var expr = void 0; - for (var i = 0; i < outParams.length; i++) { - var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); - if (i === 0) { - expr = copyExpr; - } - else { - expr = ts.createBinary(expr, 24 /* CommaToken */, copyExpr); - } - } - returnExpression = ts.createBinary(expr, 24 /* CommaToken */, returnExpression); - } - return ts.createReturn(returnExpression); - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a ClassDeclaration and transforms it into a variable statement. - * - * @param node A ClassDeclaration node. - */ - function visitClassDeclaration(node) { - // [source] - // class C { } - // - // [output] - // var C = (function () { - // function C() { - // } - // return C; - // }()); - var modifierFlags = ts.getModifierFlags(node); - var isExported = modifierFlags & 1 /* Export */; - var isDefault = modifierFlags & 512 /* Default */; - // Add an `export` modifier to the statement if needed (for `--target es5 --module es6`) - var modifiers = isExported && !isDefault - ? ts.filter(node.modifiers, isExportModifier) - : undefined; - var statement = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(getDeclarationName(node, /*allowComments*/ true), - /*type*/ undefined, transformClassLikeDeclarationToExpression(node)) - ]), - /*location*/ node); - ts.setOriginalNode(statement, node); - ts.startOnNewLine(statement); - // Add an `export default` statement for default exports (for `--target es5 --module es6`) - if (isExported && isDefault) { - var statements = [statement]; - statements.push(ts.createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, getDeclarationName(node, /*allowComments*/ false))); - return statements; - } - return statement; - } - function isExportModifier(node) { - return node.kind === 82 /* ExportKeyword */; - } - /** - * Visits a ClassExpression and transforms it into an expression. - * - * @param node A ClassExpression node. - */ - function visitClassExpression(node) { - // [source] - // C = class { } - // - // [output] - // C = (function () { - // function class_1() { - // } - // return class_1; - // }()) - return transformClassLikeDeclarationToExpression(node); - } - /** - * Transforms a ClassExpression or ClassDeclaration into an expression. - * - * @param node A ClassExpression or ClassDeclaration node. - */ - function transformClassLikeDeclarationToExpression(node) { - // [source] - // class C extends D { - // constructor() {} - // method() {} - // get prop() {} - // set prop(v) {} - // } - // - // [output] - // (function (_super) { - // __extends(C, _super); - // function C() { - // } - // C.prototype.method = function () {} - // Object.defineProperty(C.prototype, "prop", { - // get: function() {}, - // set: function() {}, - // enumerable: true, - // configurable: true - // }); - // return C; - // }(D)) - if (node.name) { - enableSubstitutionsForBlockScopedBindings(); - } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], - /*type*/ undefined, transformClassBody(node, extendsClauseElement)); - // To preserve the behavior of the old emitter, we explicitly indent - // the body of the function here if it was requested in an earlier - // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); - } - // "inner" and "outer" below are added purely to preserve source map locations from - // the old emitter - var inner = ts.createPartiallyEmittedExpression(classFunction); - inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); - var outer = ts.createPartiallyEmittedExpression(inner); - outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); - return ts.createParen(ts.createCall(outer, - /*typeArguments*/ undefined, extendsClauseElement - ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] - : [])); - } - /** - * Transforms a ClassExpression or ClassDeclaration into a function body. - * - * @param node A ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function transformClassBody(node, extendsClauseElement) { - var statements = []; - startLexicalEnvironment(); - addExtendsHelperIfNeeded(statements, node, extendsClauseElement); - addConstructor(statements, node, extendsClauseElement); - addClassMembers(statements, node); - // Create a synthetic text range for the return statement. - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 16 /* CloseBraceToken */); - var localName = getLocalName(node); - // The following partially-emitted expression exists purely to align our sourcemap - // emit with the original emitter. - var outer = ts.createPartiallyEmittedExpression(localName); - outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); - var statement = ts.createReturn(outer); - statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); - statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); - return block; - } - /** - * Adds a call to the `__extends` helper if needed for a class. - * - * @param statements The statements of the class body function. - * @param node The ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { - if (extendsClauseElement) { - statements.push(ts.createStatement(ts.createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), - /*location*/ extendsClauseElement)); - } - } - /** - * Adds the constructor of the class to a class body function. - * - * @param statements The statements of the class body function. - * @param node The ClassExpression or ClassDeclaration node. - * @param extendsClauseElement The expression for the class `extends` clause. - */ - function addConstructor(statements, node, extendsClauseElement) { - var constructor = ts.getFirstConstructorWithBody(node); - var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, getDeclarationName(node), - /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), - /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); - } - /** - * Transforms the parameters of the constructor declaration of a class. - * - * @param constructor The constructor for the class. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function transformConstructorParameters(constructor, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, we do not include the synthetic `...args` parameter and - // will instead use the `arguments` object in ES5/3. - if (constructor && !hasSynthesizedSuper) { - return ts.visitNodes(constructor.parameters, visitor, ts.isParameter); - } - return []; - } - /** - * Transforms the body of a constructor declaration of a class. - * - * @param constructor The constructor for the class. - * @param node The node which contains the constructor. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - startLexicalEnvironment(); - if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); - if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); - ts.addRange(statements, body); - } - ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.createNodeArray(statements, - /*location*/ constructor ? constructor.body.statements : node.members), - /*location*/ constructor ? constructor.body : node, - /*multiLine*/ true); - if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); - } - return block; - } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - /** - * Adds a synthesized call to `_super` if it is needed. - * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. - */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); - } - } - /** - * Visits a parameter declaration. - * - * @param node A ParameterDeclaration node. - */ - function visitParameter(node) { - if (node.dotDotDotToken) { - // rest parameters are elided - return undefined; - } - else if (ts.isBindingPattern(node.name)) { - // Binding patterns are converted into a generated name and are - // evaluated inside the function body. - return ts.setOriginalNode(ts.createParameter(ts.getGeneratedNameForNode(node), - /*initializer*/ undefined, - /*location*/ node), - /*original*/ node); - } - else if (node.initializer) { - // Initializers are elided - return ts.setOriginalNode(ts.createParameter(node.name, - /*initializer*/ undefined, - /*location*/ node), - /*original*/ node); - } - else { - return node; - } - } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; - } - /** - * Adds statements to the body of a function-like node if it contains parameters with - * binding patterns or initializers. - * - * @param statements The statements for the new function body. - * @param node A function-like node. - */ - function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; - // A rest parameter cannot have a binding pattern or an initializer, - // so let's just ignore it. - if (dotDotDotToken) { - continue; - } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); - } - else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); - } - } - } - /** - * Adds statements to the body of a function-like node for parameters with binding patterns - * - * @param statements The statements for the new function body. - * @param parameter The parameter for the function. - * @param name The name of the parameter. - * @param initializer The initializer for the parameter. - */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); - // In cases where a binding pattern is simply '[]' or '{}', - // we usually don't want to emit a var declaration; however, in the presence - // of an initializer, we must emit that expression to preserve side effects. - if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); - } - else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); - } - } - /** - * Adds statements to the body of a function-like node for parameters with initializers. - * - * @param statements The statements for the new function body. - * @param parameter The parameter for the function. - * @param name The name of the parameter. - * @param initializer The initializer for the parameter. - */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { - initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), - /*location*/ parameter)) - ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), - /*elseStatement*/ undefined, - /*location*/ parameter); - statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); - statements.push(statement); - } - /** - * Gets a value indicating whether we need to add statements to handle a rest parameter. - * - * @param node A ParameterDeclaration node. - * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is - * part of a constructor declaration with a - * synthesized call to `super` - */ - function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 69 /* Identifier */ && !inConstructorWithSynthesizedSuper; - } - /** - * Adds statements to the body of a function-like node if it contains a rest parameter. - * - * @param statements The statements for the new function body. - * @param node A function-like node. - * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is - * part of a constructor declaration with a - * synthesized call to `super` - */ - function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { - var parameter = ts.lastOrUndefined(node.parameters); - if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; - } - // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); - // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); - var restIndex = node.parameters.length - 1; - var temp = ts.createLoopVariable(); - // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(declarationName, - /*type*/ undefined, ts.createArrayLiteral([])) - ]), - /*location*/ parameter), 8388608 /* CustomPrologue */)); - // for (var _i = restIndex; _i < arguments.length; _i++) { - // param[_i - restIndex] = arguments[_i]; - // } - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) - ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), - /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([ - ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), - /*location*/ parameter)) - ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); - ts.startOnNewLine(forStatement); - statements.push(forStatement); - } - /** - * Adds a statement to capture the `this` of a function declaration if it is needed. - * - * @param statements The statements for the new function body. - * @param node A node. - */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); - } - } - /** - * Adds statements to the class body function for a class to define the members of the - * class. - * - * @param statements The statements for the class body function. - * @param node The ClassExpression or ClassDeclaration node. - */ - function addClassMembers(statements, node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 198 /* SemicolonClassElement */: - statements.push(transformSemicolonClassElementToStatement(member)); - break; - case 147 /* MethodDeclaration */: - statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member)); - break; - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors)); - } - break; - case 148 /* Constructor */: - // Constructors are handled in visitClassExpression/visitClassDeclaration - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - /** - * Transforms a SemicolonClassElement into a statement for a class body function. - * - * @param member The SemicolonClassElement node. - */ - function transformSemicolonClassElementToStatement(member) { - return ts.createEmptyStatement(/*location*/ member); - } - /** - * Transforms a MethodDeclaration into a statement for a class body function. - * - * @param receiver The receiver for the member. - * @param member The MethodDeclaration node. - */ - function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); - var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); - var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), - /*location*/ member.name), func), - /*location*/ member); - ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - // The location for the statement is used to emit comments only. - // No source map should be emitted for this statement to align with the - // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); - return statement; - } - /** - * Transforms a set of related of get/set accessors into a statement for a class body function. - * - * @param receiver The receiver for the member. - * @param accessors The set of related get/set accessors. - */ - function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); - // The location for the statement is used to emit source maps only. - // No comments should be emitted for this statement to align with the - // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); - return statement; - } - /** - * Transforms a set of related get/set accessors into an expression for either a class - * body function or an ObjectLiteralExpression with computed properties. - * - * @param receiver The receiver for the member. - */ - function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { - var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - // To align with source maps in the old emitter, the receiver and property name - // arguments are both mapped contiguously to the accessor name. - var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); - var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); - var properties = []; - if (getAccessor) { - var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); - var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); - properties.push(getter); - } - if (setAccessor) { - var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); - var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); - properties.push(setter); - } - properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); - var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - target, - propertyName, - ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true) - ]); - if (startsOnNewLine) { - call.startsOnNewLine = true; - } - return call; - } - /** - * Visits an ArrowFunction and transforms it into a FunctionExpression. - * - * @param node An ArrowFunction node. - */ - function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); - } - var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); - return func; - } - /** - * Visits a FunctionExpression node. - * - * @param node a FunctionExpression node. - */ - function visitFunctionExpression(node) { - return transformFunctionLikeToExpression(node, /*location*/ node, node.name); - } - /** - * Visits a FunctionDeclaration node. - * - * @param node a FunctionDeclaration node. - */ - function visitFunctionDeclaration(node) { - return ts.setOriginalNode(ts.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, transformFunctionBody(node), - /*location*/ node), - /*original*/ node); - } - /** - * Transforms a function-like node into a FunctionExpression. - * - * @param node The function-like node to transform. - * @param location The source-map location for the new FunctionExpression. - * @param name The name of the new FunctionExpression. - */ - function transformFunctionLikeToExpression(node, location, name) { - var savedContainingNonArrowFunction = enclosingNonArrowFunction; - if (node.kind !== 180 /* ArrowFunction */) { - enclosingNonArrowFunction = node; - } - var expression = ts.setOriginalNode(ts.createFunctionExpression(node.asteriskToken, name, - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), - /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location), - /*original*/ node); - enclosingNonArrowFunction = savedContainingNonArrowFunction; - return expression; - } - /** - * Transforms the body of a function-like node. - * - * @param node A function-like node. - */ - function transformFunctionBody(node) { - var multiLine = false; // indicates whether the block *must* be emitted as multiple lines - var singleLine = false; // indicates whether the block *may* be emitted as a single line - var statementsLocation; - var closeBraceLocation; - var statements = []; - var body = node.body; - var statementOffset; - startLexicalEnvironment(); - if (ts.isBlock(body)) { - // ensureUseStrict is false because no new prologue-directive should be added. - // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; - } - if (ts.isBlock(body)) { - statementsLocation = body.statements; - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); - // If the original body was a multi-line block, this must be a multi-line block. - if (!multiLine && body.multiLine) { - multiLine = true; - } - } - else { - ts.Debug.assert(node.kind === 180 /* ArrowFunction */); - // To align with the old emitter, we use a synthetic end position on the location - // for the statement list we synthesize when we down-level an arrow function with - // an expression function body. This prevents both comments and source maps from - // being emitted for the end position only. - statementsLocation = ts.moveRangeEnd(body, -1); - var equalsGreaterThanToken = node.equalsGreaterThanToken; - if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { - if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { - singleLine = true; - } - else { - multiLine = true; - } - } - var expression = ts.visitNode(body, visitor, ts.isExpression); - var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); - statements.push(returnStatement); - // To align with the source map emit for the old emitter, we set a custom - // source map location for the close brace. - closeBraceLocation = body; - } - var lexicalEnvironment = endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); - // If we added any final generated statements, this must be a multi-line block - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { - multiLine = true; - } - var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); - if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); - } - if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); - } - ts.setOriginalNode(block, node.body); - return block; - } - /** - * Visits an ExpressionStatement that contains a destructuring assignment. - * - * @param node An ExpressionStatement node. - */ - function visitExpressionStatement(node) { - // If we are here it is most likely because our expression is a destructuring assignment. - switch (node.expression.kind) { - case 178 /* ParenthesizedExpression */: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 187 /* BinaryExpression */: - return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a ParenthesizedExpression that may contain a destructuring assignment. - * - * @param node A ParenthesizedExpression node. - * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs - * of a destructuring assignment. - */ - function visitParenthesizedExpression(node, needsDestructuringValue) { - // If we are here it is most likely because our expression is a destructuring assignment. - if (needsDestructuringValue) { - switch (node.expression.kind) { - case 178 /* ParenthesizedExpression */: - return ts.createParen(visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node); - case 187 /* BinaryExpression */: - return ts.createParen(visitBinaryExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node); - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a BinaryExpression that contains a destructuring assignment. - * - * @param node A BinaryExpression node. - * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs - * of a destructuring assignment. - */ - function visitBinaryExpression(node, needsDestructuringValue) { - // If we are here it is because this is a destructuring assignment. - ts.Debug.assert(ts.isDestructuringAssignment(node)); - return ts.flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); - } - function visitVariableStatement(node) { - if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) { - // we are inside a converted loop - hoist variable declarations - var assignments = void 0; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); - if (decl.initializer) { - var assignment = void 0; - if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); - } - else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); - } - (assignments || (assignments = [])).push(assignment); - } - } - if (assignments) { - return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 24 /* CommaToken */, acc); }), node); - } - else { - // none of declarations has initializer - the entire variable statement can be deleted - return undefined; - } - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). - * - * @param node A VariableDeclarationList node. - */ - function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */) { - enableSubstitutionsForBlockScopedBindings(); - } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ - ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); - var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); - ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) - || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - } - return declarationList; - } - /** - * Gets a value indicating whether we should emit an explicit initializer for a variable - * declaration in a `let` declaration list. - * - * @param node A VariableDeclaration node. - */ - function shouldEmitExplicitInitializerForLetDeclaration(node) { - // Nested let bindings might need to be initialized explicitly to preserve - // ES6 semantic: - // - // { let x = 1; } - // { let x; } // x here should be undefined. not 1 - // - // Top level bindings never collide with anything and thus don't require - // explicit initialization. As for nested let bindings there are two cases: - // - // - Nested let bindings that were not renamed definitely should be - // initialized explicitly: - // - // { let x = 1; } - // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } - // - // Without explicit initialization code in /*1*/ can be executed even if - // some-condition is evaluated to false. - // - // - Renaming introduces fresh name that should not collide with any - // existing names, however renamed bindings sometimes also should be - // explicitly initialized. One particular case: non-captured binding - // declared inside loop body (but not in loop initializer): - // - // let x; - // for (;;) { - // let x; - // } - // - // In downlevel codegen inner 'x' will be renamed so it won't collide - // with outer 'x' however it will should be reset on every iteration as - // if it was declared anew. - // - // * Why non-captured binding? - // - Because if loop contains block scoped binding captured in some - // function then loop body will be rewritten to have a fresh scope - // on every iteration so everything will just work. - // - // * Why loop initializer is excluded? - // - Since we've introduced a fresh name it already will be undefined. - var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; - var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer) - || (isCapturedInFunction - && isDeclaredInLoop - && ts.isBlock(enclosingBlockScopeContainer) - && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false)); - var emitExplicitInitializer = !emittedAsTopLevel - && enclosingBlockScopeContainer.kind !== 207 /* ForInStatement */ - && enclosingBlockScopeContainer.kind !== 208 /* ForOfStatement */ - && (!resolver.isDeclarationWithCollidingName(node) - || (isDeclaredInLoop - && !isCapturedInFunction - && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false))); - return emitExplicitInitializer; - } - /** - * Visits a VariableDeclaration in a `let` declaration list. - * - * @param node A VariableDeclaration node. - */ - function visitVariableDeclarationInLetDeclarationList(node) { - // For binding pattern names that lack initializers there is no point to emit - // explicit initializer since downlevel codegen for destructuring will fail - // in the absence of initializer so all binding elements will say uninitialized - var name = node.name; - if (ts.isBindingPattern(name)) { - return visitVariableDeclaration(node); - } - if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_8 = ts.getMutableClone(node); - clone_8.initializer = ts.createVoidZero(); - return clone_8; - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits a VariableDeclaration node with a binding pattern. - * - * @param node A VariableDeclaration node. - */ - function visitVariableDeclaration(node) { - // If we are here it is because the name contains a binding pattern. - if (ts.isBindingPattern(node.name)) { - var recordTempVariablesInLine = !enclosingVariableStatement - || !ts.hasModifier(enclosingVariableStatement, 1 /* Export */); - return ts.flattenVariableDestructuring(context, node, /*value*/ undefined, visitor, recordTempVariablesInLine ? undefined : hoistVariableDeclaration); - } - return ts.visitEachChild(node, visitor, context); - } - function visitLabeledStatement(node) { - if (convertedLoopState) { - if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); - } - convertedLoopState.labels[node.label.text] = node.label.text; - } - var result; - if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) { - result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement); - } - else { - result = ts.visitEachChild(node, visitor, context); - } - if (convertedLoopState) { - convertedLoopState.labels[node.label.text] = undefined; - } - return result; - } - function visitDoStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitWhileStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - function visitForInStatement(node) { - return convertIterationStatementBodyIfNecessary(node); - } - /** - * Visits a ForOfStatement and converts it into a compatible ForStatement. - * - * @param node A ForOfStatement. - */ - function visitForOfStatement(node) { - return convertIterationStatementBodyIfNecessary(node, convertForOfToFor); - } - function convertForOfToFor(node, convertedLoopBodyStatements) { - // The following ES6 code: - // - // for (let v of expr) { } - // - // should be emitted as - // - // for (var _i = 0, _a = expr; _i < _a.length; _i++) { - // var v = _a[_i]; - // } - // - // where _a and _i are temps emitted to capture the RHS and the counter, - // respectively. - // When the left hand side is an expression instead of a let declaration, - // the "let v" is not emitted. - // When the left hand side is a let/const, the v is renamed if there is - // another v in scope. - // Note that all assignments to the LHS are emitted in the body, including - // all destructuring. - // Note also that because an extra statement is needed to assign to the LHS, - // for-of bodies are always emitted as blocks. - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - var initializer = node.initializer; - var statements = []; - // In the case where the user wrote an identifier as the RHS, like this: - // - // for (let v of arr) { } - // - // we don't want to emit a temporary variable for the RHS, just use it directly. - var counter = ts.createLoopVariable(); - var rhsReference = expression.kind === 69 /* Identifier */ - ? ts.createUniqueName(expression.text) - : ts.createTempVariable(/*recordTempVariable*/ undefined); - // Initialize LHS - // var v = _a[_i]; - if (ts.isVariableDeclarationList(initializer)) { - if (initializer.flags & 3 /* BlockScoped */) { - enableSubstitutionsForBlockScopedBindings(); - } - var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); - if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - // This works whether the declaration is a var, let, or const. - // It will use rhsIterationValue _a[_i] as the initializer. - var declarations = ts.flattenVariableDestructuring(context, firstOriginalDeclaration, ts.createElementAccess(rhsReference, counter), visitor); - var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer); - ts.setOriginalNode(declarationList, initializer); - // Adjust the source map range for the first declaration to align with the old - // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, declarationList)); - } - else { - // The following call does not include the initializer, so we have - // to emit it separately. - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), - /*type*/ undefined, ts.createElementAccess(rhsReference, counter)) - ], /*location*/ ts.moveRangePos(initializer, -1)), - /*location*/ ts.moveRangeEnd(initializer, -1))); - } - } - else { - // Initializer is an expression. Emit the expression in the body, so that it's - // evaluated on every iteration. - var assignment = ts.createAssignment(initializer, ts.createElementAccess(rhsReference, counter)); - if (ts.isDestructuringAssignment(assignment)) { - // This is a destructuring pattern, so we flatten the destructuring instead. - statements.push(ts.createStatement(ts.flattenDestructuringAssignment(context, assignment, - /*needsValue*/ false, hoistVariableDeclaration, visitor))); - } - else { - // Currently there is not way to check that assignment is binary expression of destructing assignment - // so we have to cast never type to binaryExpression - assignment.end = initializer.end; - statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1))); - } - } - var bodyLocation; - var statementsLocation; - if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); - } - else { - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); - if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; - } - else { - statements.push(statement); - } - } - // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); - // The old emitter does not emit source maps for the block. - // We add the location to preserve comments. - var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), - /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); - var forStatement = ts.createFor(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), - ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) - ], /*location*/ node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), - /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, - /*location*/ node); - // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); - return forStatement; - } - /** - * Visits an ObjectLiteralExpression with computed propety names. - * - * @param node An ObjectLiteralExpression node. - */ - function visitObjectLiteralExpression(node) { - // We are here because a ComputedPropertyName was used somewhere in the expression. - var properties = node.properties; - var numProperties = properties.length; - // Find the first computed property. - // Everything until that point can be emitted as part of the initial object literal. - var numInitialProperties = numProperties; - for (var i = 0; i < numProperties; i++) { - var property = properties[i]; - if (property.transformFlags & 4194304 /* ContainsYield */ - || property.name.kind === 140 /* ComputedPropertyName */) { - numInitialProperties = i; - break; - } - } - ts.Debug.assert(numInitialProperties !== numProperties); - // For computed properties, we need to create a unique handle to the object - // literal so we can modify it without risking internal assignments tainting the object. - var temp = ts.createTempVariable(hoistVariableDeclaration); - // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. - var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), - /*location*/ undefined, node.multiLine), 524288 /* Indented */)); - if (node.multiLine) { - assignment.startsOnNewLine = true; - } - expressions.push(assignment); - addObjectLiteralMembers(expressions, node, temp, numInitialProperties); - // We need to clone the temporary identifier so that we can write it on a - // new line - expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); - return ts.inlineExpressions(expressions); - } - function shouldConvertIterationStatementBody(node) { - return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; - } - /** - * Records constituents of name for the given variable to be hoisted in the outer scope. - */ - function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { - if (!state.hoistedLocalVariables) { - state.hoistedLocalVariables = []; - } - visit(node.name); - function visit(node) { - if (node.kind === 69 /* Identifier */) { - state.hoistedLocalVariables.push(node); - } - else { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - visit(element.name); - } - } - } - } - } - function convertIterationStatementBodyIfNecessary(node, convert) { - if (!shouldConvertIterationStatementBody(node)) { - var saveAllowedNonLabeledJumps = void 0; - if (convertedLoopState) { - // we get here if we are trying to emit normal loop loop inside converted loop - // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is - saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; - } - var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context); - if (convertedLoopState) { - convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; - } - return result; - } - var functionName = ts.createUniqueName("_loop"); - var loopInitializer; - switch (node.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - var initializer = node.initializer; - if (initializer && initializer.kind === 219 /* VariableDeclarationList */) { - loopInitializer = initializer; - } - break; - } - // variables that will be passed to the loop as parameters - var loopParameters = []; - // variables declared in the loop initializer that will be changed inside the loop - var loopOutParameters = []; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { - for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); - } - } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. - // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { - // outer loop has already used 'arguments' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; - } - if (outerConvertedLoopState.thisName) { - // outer loop has already used 'this' so we've already have some name to alias it - // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; - } - if (outerConvertedLoopState.hoistedLocalVariables) { - // we've already collected some non-block scoped variable declarations in enclosing loop - // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; - } - } - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { - var statements_3 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_3); - loopBody = ts.createBlock(statements_3, /*location*/ undefined, /*multiline*/ true); - } - if (!ts.isBlock(loopBody)) { - loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); - } - var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 - && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 256 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 2097152 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ])); - var statements = [convertedLoopVariable]; - var extraVariableDeclarations; - // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { - // if alias for arguments is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; - } - else { - // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, - /*type*/ undefined, ts.createIdentifier("arguments"))); - } - } - if (currentState.thisName) { - // if alias for this is set - if (outerConvertedLoopState) { - // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; - } - else { - // this is top level converted loop so we need to create an alias for 'this' here - // NOTE: - // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. - // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, - /*type*/ undefined, ts.createIdentifier("this"))); - } - } - if (currentState.hoistedLocalVariables) { - // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { - // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; - } - else { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; - extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); - } - } - } - // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { - if (!extraVariableDeclarations) { - extraVariableDeclarations = []; - } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; - extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); - } - } - // create variable statement to hold all introduced variable declarations - if (extraVariableDeclarations) { - statements.push(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); - } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait); - var loop; - if (convert) { - loop = convert(node, convertedLoopBodyStatements); - } - else { - loop = ts.getMutableClone(node); - // clean statement part - loop.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - loop = ts.visitEachChild(loop, visitor, context); - // set loop statement - loop.statement = ts.createBlock(convertedLoopBodyStatements, - /*location*/ undefined, - /*multiline*/ true); - // reset and re-aggregate the transform flags - loop.transformFlags = 0; - ts.aggregateTransformFlags(loop); - } - statements.push(currentParent.kind === 214 /* LabeledStatement */ - ? ts.createLabel(currentParent.label, loop) - : loop); - return statements; - } - function copyOutParameter(outParam, copyDirection) { - var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; - var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 56 /* EqualsToken */, source); - } - function copyOutParameters(outParams, copyDirection, statements) { - for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { - var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); - } - } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; - var statements = []; - // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop - // simple loops are emitted as just 'loop()'; - // NOTE: if loop uses only 'continue' it still will be emitted as simple loop - var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && - !state.labeledNonLocalBreaks && - !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(37 /* AsteriskToken */), call) : call; - if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); - } - else { - var loopResultName = ts.createUniqueName("state"); - var stateVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); - statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); - if (state.nonLocalJumps & 8 /* Return */) { - var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; - returnStatement = ts.createReturn(loopResultName); - } - else { - returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); - } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); - } - if (state.nonLocalJumps & 2 /* Break */) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 32 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); - } - if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { - var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); - statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); - } - } - return statements; - } - function setLabeledJump(state, isBreak, labelText, labelMarker) { - if (isBreak) { - if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); - } - state.labeledNonLocalBreaks[labelText] = labelMarker; - } - else { - if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); - } - state.labeledNonLocalContinues[labelText] = labelMarker; - } - } - function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { - if (!table) { - return; - } - for (var labelText in table) { - var labelMarker = table[labelText]; - var statements = []; - // if there are no outer converted loop or outer label in question is located inside outer converted loop - // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do - if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { - var label = ts.createIdentifier(labelText); - statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); - } - else { - setLabeledJump(outerLoop, isBreak, labelText, labelMarker); - statements.push(ts.createReturn(loopResultName)); - } - caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); - } - } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { - var name = decl.name; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); - } - } - } - else { - loopParameters.push(ts.createParameter(name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + name.text); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); - } - } - } - /** - * Adds the members of an object literal to an array of expressions. - * - * @param expressions An array of expressions. - * @param node An ObjectLiteralExpression node. - * @param receiver The receiver for members of the ObjectLiteralExpression. - * @param numInitialNonComputedProperties The number of initial properties without - * computed property names. - */ - function addObjectLiteralMembers(expressions, node, receiver, start) { - var properties = node.properties; - var numProperties = properties.length; - for (var i = start; i < numProperties; i++) { - var property = properties[i]; - switch (property.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine)); - } - break; - case 253 /* PropertyAssignment */: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 254 /* ShorthandPropertyAssignment */: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); - break; - case 147 /* MethodDeclaration */: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); - break; - default: - ts.Debug.failBadSyntaxKind(node); - break; - } - } - } - /** - * Transforms a PropertyAssignment node into an expression. - * - * @param node The ObjectLiteralExpression that contains the PropertyAssignment. - * @param property The PropertyAssignment node. - * @param receiver The receiver for the assignment. - */ - function transformPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression), - /*location*/ property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Transforms a ShorthandPropertyAssignment node into an expression. - * - * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. - * @param property The ShorthandPropertyAssignment node. - * @param receiver The receiver for the assignment. - */ - function transformShorthandPropertyAssignmentToExpression(node, property, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name), - /*location*/ property); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. - * - * @param node The ObjectLiteralExpression that contains the MethodDeclaration. - * @param method The MethodDeclaration node. - * @param receiver The receiver for the assignment. - */ - function transformObjectLiteralMethodDeclarationToExpression(node, method, receiver, startsOnNewLine) { - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined), - /*location*/ method); - if (startsOnNewLine) { - expression.startsOnNewLine = true; - } - return expression; - } - /** - * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a - * PropertyAssignment. - * - * @param node A MethodDeclaration node. - */ - function visitMethodDeclaration(node) { - // We should only get here for methods on an object literal with regular identifier names. - // Methods on classes are handled in visitClassDeclaration/visitClassExpression. - // Methods with computed property names are handled in visitObjectLiteralExpression. - ts.Debug.assert(!ts.isComputedPropertyName(node.name)); - var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); - return ts.createPropertyAssignment(node.name, functionExpression, - /*location*/ node); - } - /** - * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. - * - * @param node A ShorthandPropertyAssignment node. - */ - function visitShorthandPropertyAssignment(node) { - return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name), - /*location*/ node); - } - /** - * Visits a YieldExpression node. - * - * @param node A YieldExpression node. - */ - function visitYieldExpression(node) { - // `yield` expressions are transformed using the generators transformer. - return ts.visitEachChild(node, visitor, context); - } - /** - * Visits an ArrayLiteralExpression that contains a spread element. - * - * @param node An ArrayLiteralExpression node. - */ - function visitArrayLiteralExpression(node) { - // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); - } - /** - * Visits a CallExpression that contains either a spread element or `super`. - * - * @param node a CallExpression. - */ - function visitCallExpression(node) { - // We are here either because SuperKeyword was used somewhere in the expression, or - // because we contain a SpreadElementExpression. - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { - // [source] - // f(...a, b) - // x.m(...a, b) - // super(...a, b) - // super.m(...a, b) // in static - // super.m(...a, b) // in instance - // - // [output] - // f.apply(void 0, a.concat([b])) - // (_a = x).m.apply(_a, a.concat([b])) - // _super.apply(this, a.concat([b])) - // _super.m.apply(this, a.concat([b])) - // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); - } - else { - // [source] - // super(a) - // super.m(a) // in static - // super.m(a) // in instance - // - // [output] - // _super.call(this, a) - // _super.m.call(this, a) - // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), - /*location*/ node); - } - } - /** - * Visits a NewExpression that contains a spread element. - * - * @param node A NewExpression node. - */ - function visitNewExpression(node) { - // We are here because we contain a SpreadElementExpression. - ts.Debug.assert((node.transformFlags & 262144 /* ContainsSpreadElementExpression */) !== 0); - // [source] - // new C(...a) - // - // [output] - // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() - var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), - /*typeArguments*/ undefined, []); - } - /** - * Transforms an array of Expression nodes that contains a SpreadElementExpression. - * - * @param elements The array of Expression nodes. - * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. - * @param multiLine A value indicating whether the result should be emitted on multiple lines. - */ - function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { - // [source] - // [a, ...b, c] - // - // [output] - // [a].concat(b, [c]) - // Map spans of spread expressions into their expressions and spans of other - // expressions into an array literal. - var numElements = elements.length; - var segments = ts.flatten(ts.spanMap(elements, partitionSpreadElement, function (partition, visitPartition, start, end) { - return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); - })); - if (segments.length === 1) { - var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElementExpression(firstElement) && firstElement.expression.kind !== 170 /* ArrayLiteralExpression */ - ? ts.createArraySlice(segments[0]) - : segments[0]; - } - // Rewrite using the pattern .concat(, , ...) - return ts.createArrayConcat(segments.shift(), segments); - } - function partitionSpreadElement(node) { - return ts.isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; - } - function visitSpanOfSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.map(chunk, visitExpressionOfSpreadElement); - } - function visitSpanOfNonSpreadElements(chunk, multiLine, hasTrailingComma) { - return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression), - /*location*/ undefined, multiLine); - } - /** - * Transforms the expression of a SpreadElementExpression node. - * - * @param node A SpreadElementExpression node. - */ - function visitExpressionOfSpreadElement(node) { - return ts.visitNode(node.expression, visitor, ts.isExpression); - } - /** - * Visits a template literal. - * - * @param node A template literal. - */ - function visitTemplateLiteral(node) { - return ts.createLiteral(node.text, /*location*/ node); - } - /** - * Visits a TaggedTemplateExpression node. - * - * @param node A TaggedTemplateExpression node. - */ - function visitTaggedTemplateExpression(node) { - // Visit the tag expression - var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - // Allocate storage for the template site object - var temp = ts.createTempVariable(hoistVariableDeclaration); - // Build up the template arguments and the raw and cooked strings for the template. - var templateArguments = [temp]; - var cookedStrings = []; - var rawStrings = []; - var template = node.template; - if (ts.isNoSubstitutionTemplateLiteral(template)) { - cookedStrings.push(ts.createLiteral(template.text)); - rawStrings.push(getRawLiteral(template)); - } - else { - cookedStrings.push(ts.createLiteral(template.head.text)); - rawStrings.push(getRawLiteral(template.head)); - for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { - var templateSpan = _a[_i]; - cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); - rawStrings.push(getRawLiteral(templateSpan.literal)); - templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); - } - } - // NOTE: The parentheses here is entirely optional as we are now able to auto- - // parenthesize when rebuilding the tree. This should be removed in a - // future version. It is here for now to match our existing emit. - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) - ])); - } - /** - * Creates an ES5 compatible literal from an ES6 template literal. - * - * @param node The ES6 template literal. - */ - function getRawLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - return ts.createLiteral(text, /*location*/ node); - } - /** - * Visits a TemplateExpression node. - * - * @param node A TemplateExpression node. - */ - function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, ts.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(ts.createLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { - for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { - var span_6 = _a[_i]; - expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); - } - } - } - /** - * Visits the `super` keyword - */ - function visitSuperKeyword(node) { - return enclosingNonAsyncFunctionBody - && ts.isClassElement(enclosingNonAsyncFunctionBody) - && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */) - && currentParent.kind !== 174 /* CallExpression */ - ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") - : ts.createIdentifier("_super"); - } - function visitSourceFileNode(node) { - var _a = ts.span(node.statements, ts.isPrologueDirective), prologue = _a[0], remaining = _a[1]; - var statements = []; - startLexicalEnvironment(); - ts.addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - ts.addRange(statements, ts.visitNodes(ts.createNodeArray(remaining), visitor, ts.isStatement)); - ts.addRange(statements, endLexicalEnvironment()); - var clone = ts.getMutableClone(node); - clone.statements = ts.createNodeArray(statements, /*location*/ node.statements); - return clone; - } - /** - * Called by the printer just before a node is printed. - * - * @param node The node to be printed. - */ - function onEmitNode(node, emit) { - var savedEnclosingFunction = enclosingFunction; - if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { - // If we are tracking a captured `this`, keep track of the enclosing function. - enclosingFunction = node; - } - previousOnEmitNode(node, emit); - enclosingFunction = savedEnclosingFunction; - } - /** - * Enables a more costly code path for substitutions when we determine a source file - * contains block-scoped bindings (e.g. `let` or `const`). - */ - function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { - enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(69 /* Identifier */); - } - } - /** - * Enables a more costly code path for substitutions when we determine a source file - * contains a captured `this`. - */ - function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { - enabledSubstitutions |= 1 /* CapturedThis */; - context.enableSubstitution(97 /* ThisKeyword */); - context.enableEmitNotification(148 /* Constructor */); - context.enableEmitNotification(147 /* MethodDeclaration */); - context.enableEmitNotification(149 /* GetAccessor */); - context.enableEmitNotification(150 /* SetAccessor */); - context.enableEmitNotification(180 /* ArrowFunction */); - context.enableEmitNotification(179 /* FunctionExpression */); - context.enableEmitNotification(220 /* FunctionDeclaration */); - } + return node; } /** * Hooks node substitutions. * + * @param emitContext The context for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { - return substituteExpression(node); + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); } - if (ts.isIdentifier(node)) { - return substituteIdentifier(node); + else if (ts.isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); } return node; } /** - * Hooks substitutions for non-expression identifiers. + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression */ - function substituteIdentifier(node) { - // Only substitute the identifier if we have enabled substitutions for block-scoped - // bindings. - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { - var original = ts.getParseTreeNode(node, ts.isIdentifier); - if (original && isNameOfDeclarationWithCollidingName(original)) { - return ts.getGeneratedNameForNode(original); + function substitutePropertyAccessExpression(node) { + var literalName = trySubstituteReservedName(node.name); + if (literalName) { + return ts.createElementAccess(node.expression, literalName, /*location*/ node); + } + return node; + } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node) { + var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return ts.updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + if (token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */) { + return ts.createLiteral(name, /*location*/ name); + } + return undefined; + } + } + ts.transformES5 = transformES5; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformES2015Module(context) { + var compilerOptions = context.getCompilerOptions(); + var previousOnEmitNode = context.onEmitNode; + var previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(261 /* SourceFile */); + context.enableSubstitution(70 /* Identifier */); + var currentSourceFile; + return transformSourceFile; + function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements); + ts.append(statements, ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + } + else { + return ts.visitEachChild(node, visitor, context); } } return node; } - /** - * Determines whether a name is the name of a declaration with a colliding name. - * NOTE: This function expects to be called with an original source tree node. - * - * @param node An original source tree node. - */ - function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { - case 169 /* BindingElement */: - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 218 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + function visitor(node) { + switch (node.kind) { + case 234 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case 240 /* ExportAssignment */: + return visitExportAssignment(node); } - return false; + return node; + } + function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (ts.isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (ts.isIdentifier(node) && emitContext === 1 /* Expression */) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } + ts.transformES2015Module = transformES2015Module; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformSystemModule(context) { + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file. + var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = ts.createMap(); // The export function associated with a source file. + var noSubstitutionMap = ts.createMap(); // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. + var hoistedStatements; + var enclosingBlockScopedContainer; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. + moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. + exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports"); + contextObject = ts.createUniqueName("context"); + // Add the body of the module. + var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction])) + ], node.statements)), 1024 /* NoTrailingComments */); + if (!(compilerOptions.outFile || compilerOptions.out)) { + ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + return ts.aggregateTransformFlags(updated); } /** - * Substitutes an expression. + * Collects the dependency groups for this files imports. * - * @param node An Expression node. + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports) { + var groupIndices = ts.createMap(); + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; i++) { + var externalImport = externalImports[i]; + var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + var text = externalModuleName.text; + if (ts.hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + return dependencyGroups; + } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ + function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. + startLexicalEnvironment(); + // Add any prologue directives. + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + ]))); + // Visit the synthetic external helpers import declaration if present + ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. + var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. + ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + ts.addRange(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); + statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([ + ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, + /*location*/ undefined, + /*multiLine*/ true))) + ]), + /*multiLine*/ true))); + return ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported + if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { + var externalImport = _a[_i]; + if (externalImport.kind === 241 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction_1); + return exportStarFunction_1.name; + } + } + var exportedNames = []; + if (moduleInfo.exportedNames) { + for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { + var exportedLocalName = _c[_b]; + if (exportedLocalName.text === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true))); + } + } + for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { + var externalImport = _e[_d]; + if (externalImport.kind !== 241 /* ExportDeclaration */) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + // export * from ... + continue; + } + for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { + var element = _g[_f]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true))); + } + } + var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)) + ]))); + var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ + function createExportStarFunction(localNames) { + var exportStarFunction = ts.createUniqueName("exportStar"); + var m = ts.createIdentifier("m"); + var n = ts.createIdentifier("n"); + var exports = ts.createIdentifier("exports"); + var condition = ts.createStrictInequality(n, ts.createLiteral("default")); + if (localNames) { + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) + ])), + ts.createForIn(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(n, /*type*/ undefined) + ]), m, ts.createBlock([ + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ])), + ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], + /*location*/ undefined, + /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction, dependencyGroups) { + var setters = []; + for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { + var group = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group + var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); + var statements = []; + for (var _a = 0, _b = group.externalImports; _a < _b.length; _a++) { + var entry = _b[_a]; + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + switch (entry.kind) { + case 235 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // fall-through + case 234 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + // save import into the local + statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + break; + case 241 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== undefined); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + var properties = []; + for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { + var e = _d[_c]; + properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + } + statements.push(ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]))); + } + else { + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); + } + break; + } + } + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true))); + } + return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); + } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 241 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return nestedElementVisitor(node); + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + if (node.importClause) { + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); + } + } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + } + else { + hoistedStatements = ts.append(hoistedStatements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + return undefined; + } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + // Hoist the name of the class declaration to the outer module body function. + var name = ts.getLocalName(node); + hoistVariableDeclaration(name); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement), + /*location*/ node)), + /*location*/ node)); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return ts.visitNode(node, destructuringVisitor, ts.isStatement); + } + var expressions; + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); + var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + var statements; + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node)); + } + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + return ts.singleOrMany(statements); + } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); + } + } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 1048576 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 261 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node, isExportedDeclaration) { + var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return ts.isBindingPattern(node.name) + ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(ts.getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location))) + : preventSubstitution(ts.createAssignment(name, value, location)); + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + var excludeName = void 0; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); + excludeName = decl.name.text; + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + var excludeName; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); + excludeName = exportName.text; + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + var name = ts.getDeclarationName(decl); + var exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { + var exportSpecifier = exportSpecifiers_1[_i]; + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value)); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name, value) { + var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; + return ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node) { + switch (node.kind) { + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 211 /* ForStatement */: + return visitForStatement(node); + case 212 /* ForInStatement */: + return visitForInStatement(node); + case 213 /* ForOfStatement */: + return visitForOfStatement(node); + case 209 /* DoStatement */: + return visitDoStatement(node); + case 210 /* WhileStatement */: + return visitWhileStatement(node); + case 219 /* LabeledStatement */: + return visitLabeledStatement(node); + case 217 /* WithStatement */: + return visitWithStatement(node); + case 218 /* SwitchStatement */: + return visitSwitchStatement(node); + case 232 /* CaseBlock */: + return visitCaseBlock(node); + case 253 /* CaseClause */: + return visitCaseClause(node); + case 254 /* DefaultClause */: + return visitDefaultClause(node); + case 221 /* TryStatement */: + return visitTryStatement(node); + case 256 /* CatchClause */: + return visitCatchClause(node); + case 204 /* Block */: + return visitBlock(node); + case 295 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 296 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + return destructuringVisitor(node); + } + } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForInStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitForOfStatement(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node) { + return ts.isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + var expressions = void 0; + for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + } + return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); + } + else { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitDoStatement(node) { + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWhileStatement(node) { + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitLabeledStatement(node) { + return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitWithStatement(node) { + return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock)); + } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitSwitchStatement(node) { + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCaseClause(node) { + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitDefaultClause(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ + function visitTryStatement(node) { + return ts.visitEachChild(node, nestedElementVisitor, context); + } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ + function visitCatchClause(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock)); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ + function visitBlock(node) { + var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = ts.visitEachChild(node, nestedElementVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringVisitor(node) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 192 /* BinaryExpression */) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & 2048 /* ContainsDestructuringAssignment */) { + return ts.visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + /*needsValue*/ true); + } + return ts.visitEachChild(node, destructuringVisitor, context); + } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node) { + if (ts.isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (ts.isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (ts.isObjectLiteralExpression(node)) { + return ts.some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isArrayLiteralExpression(node)) { + return ts.some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (ts.isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (ts.isIdentifier(node)) { + var container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === 261 /* SourceFile */; + } + else { + return false; + } + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + switch (node.kind) { + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261 /* SourceFile */) { + var id = ts.getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. */ function substituteExpression(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return substituteExpressionIdentifier(node); - case 97 /* ThisKeyword */: - return substituteThisKeyword(node); + case 192 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 190 /* PrefixUnaryExpression */: + case 191 /* PostfixUnaryExpression */: + return substituteUnaryExpression(node); } return node; } /** - * Substitutes an expression identifier. + * Substitution for an Identifier expression that may contain an imported or exported symbol. * - * @param node An Identifier node. + * @param node The node to substitute. */ function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { - var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.getGeneratedNameForNode(declaration.name); + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), + /*location*/ node); + } } } return node; } /** - * Substitutes `this` when contained within an arrow function. + * Substitution for a BinaryExpression that may contain an imported or exported symbol. * - * @param node The ThisKeyword node. + * @param node The node to substitute. */ - function substituteThisKeyword(node) { - if (enabledSubstitutions & 1 /* CapturedThis */ - && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { - return ts.createIdentifier("_this", /*location*/ node); + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } } return node; } /** - * Gets the local name for a declaration for use in expressions. + * Substitution for a UnaryExpression that may contain an imported or exported symbol. * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + * @param node The node to substitute. */ - function getLocalName(node, allowComments, allowSourceMaps) { - return getDeclarationName(node, allowComments, allowSourceMaps, 262144 /* LocalName */); + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 /* PostfixUnaryExpression */ + ? ts.createPrefix(node.operator, node.operand, + /*location*/ node) + : node; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (node.kind === 191 /* PostfixUnaryExpression */) { + expression = node.operator === 42 /* PlusPlusToken */ + ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) + : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); + } + return expression; + } + } + return node; } /** - * Gets the name of a declaration, without source map or comments. + * Gets the exports of a name. * - * @param node The declaration. - * @param allowComments Allow comments for the name. + * @param name The name. */ - function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= 1536 /* NoSourceMap */; + function getExports(name) { + var exportedNames; + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 261 /* SourceFile */) { + exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); + } + exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); } - if (!allowComments) { - emitFlags |= 49152 /* NoComments */; - } - if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); - } - return name_39; } - return ts.getGeneratedNameForNode(node); + return exportedNames; } - function getClassMemberPrefix(node, member) { - var expression = getLocalName(node); - return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node) { + if (noSubstitution === undefined) + noSubstitution = ts.createMap(); + noSubstitution[ts.getNodeId(node)] = true; + return node; } - function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { - if (!constructor || !hasExtendsClause) { - return false; - } - var parameter = ts.singleOrUndefined(constructor.parameters); - if (!parameter || !ts.nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { - return false; - } - var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 202 /* ExpressionStatement */) { - return false; - } - var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 174 /* CallExpression */) { - return false; - } - var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 95 /* SuperKeyword */) { - return false; - } - var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 191 /* SpreadElementExpression */) { - return false; - } - var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression === parameter.name; + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; } } - ts.transformES6 = transformES6; + ts.transformSystemModule = transformSystemModule; +})(ts || (ts = {})); +/// +/// +/*@internal*/ +var ts; +(function (ts) { + function transformModule(context) { + var transformModuleDelegates = ts.createMap((_a = {}, + _a[ts.ModuleKind.None] = transformCommonJSModule, + _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, + _a[ts.ModuleKind.AMD] = transformAMDModule, + _a[ts.ModuleKind.UMD] = transformUMDModule, + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var compilerOptions = context.getCompilerOptions(); + var resolver = context.getEmitResolver(); + var host = context.getEmitHost(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + var previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(258 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file. + var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. + return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ + function transformSourceFile(node) { + if (ts.isDeclarationFile(node) + || !(ts.isExternalModule(node) + || compilerOptions.isolatedModules)) { + return node; + } + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Perform the transformation. + var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None]; + var updated = transformModule(node); + currentSourceFile = undefined; + currentModuleInfo = undefined; + return ts.aggregateTransformFlags(updated); + } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ + function transformCommonJSModule(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + ts.addRange(statements, endLexicalEnvironment()); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); + var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + ts.addEmitHelper(updated, exportStarHelper); + } + return updated; + } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ + function transformAMDModule(node) { + var define = ts.createIdentifier("define"); + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true); + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ + function transformUMDModule(node) { + var define = ts.createRawExpression(umdHelper); + return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); + } + /** + * Transforms a SourceFile into an AMD or UMD module. + * + * @param node The SourceFile node. + * @param define The expression used to define the module. + * @param moduleName An expression for the module name, if available. + * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies. + */ + function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... + return ts.updateSourceFileNode(node, ts.createNodeArray([ + ts.createStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + ts.createArrayLiteral([ + ts.createLiteral("require"), + ts.createLiteral("exports") + ].concat(aliasedModuleNames, unaliasedModuleNames)), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) + ]))) + ], + /*location*/ node.statements)); + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + var importAliasNames = []; + // Fill in amd-dependency tags + for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { + var amdDependency = _a[_i]; + if (amdDependency.name) { + aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); + } + } + for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { + var importNode = _c[_b]; + // Find the name of the external module + var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one + var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + var statements = []; + var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + // Visit each statement of the module body. + ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); + ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); + // End the lexical environment for the module body + // and merge any new lexical declarations. + ts.addRange(statements, endLexicalEnvironment()); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true); + if (currentModuleInfo.hasExportStarsToExportValues) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. + ts.addEmitHelper(body, exportStarHelper); + } + return body; + } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + if (emitAsReturn) { + var statement = ts.createReturn(currentModuleInfo.exportEquals.expression, + /*location*/ currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression), + /*location*/ currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } + } + } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node) { + switch (node.kind) { + case 235 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 234 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 241 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 240 /* ExportAssignment */: + return visitExportAssignment(node); + case 205 /* VariableStatement */: + return visitVariableStatement(node); + case 225 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 226 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 295 /* MergeDeclarationMarker */: + return visitMergeDeclarationMarker(node); + case 296 /* EndOfDeclarationMarker */: + return visitEndOfDeclarationMarker(node); + default: + // This visitor does not descend into the tree, as export/import statements + // are only transformed at the top level of a file. + return node; + } + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node) { + var statements; + var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); + if (moduleKind !== ts.ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; + return ts.createStatement(createRequireCall(node), /*location*/ node); + } + else { + var variables = []; + if (namespaceDeclaration && !ts.isDefaultImport(node)) { + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, createRequireCall(node))); + } + else { + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, createRequireCall(node))); + if (namespaceDeclaration && ts.isDefaultImport(node)) { + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); + } + } + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, + /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else if (namespaceDeclaration && ts.isDefaultImport(node)) { + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node), + /*location*/ node) + ], + /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode) { + var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + var args = []; + if (moduleName) { + args.push(moduleName); + } + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); + } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node) { + ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + var statements; + if (moduleKind !== ts.ModuleKind.AMD) { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)), + /*location*/ node)); + } + else { + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*location*/ undefined, + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */), + /*location*/ node)); + } + } + else { + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)), + /*location*/ node)); + } + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ + function visitExportDeclaration(node) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. + return undefined; + } + var generatedName = ts.getGeneratedNameForNode(node); + if (node.exportClause) { + var statements = []; + // export { x, y } from "mod"; + if (moduleKind !== ts.ModuleKind.AMD) { + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ]), + /*location*/ node)); + } + for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { + var specifier = _a[_i]; + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue), + /*location*/ specifier)); + } + return ts.singleOrMany(statements); + } + else { + // export * from "mod"; + return ts.createStatement(ts.createCall(ts.createIdentifier("__export"), + /*typeArguments*/ undefined, [ + moduleKind !== ts.ModuleKind.AMD + ? createRequireCall(node) + : generatedName + ]), + /*location*/ node); + } + } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node) { + if (node.isExportEquals) { + return undefined; + } + var statements; + var original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + } + else { + statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + } + return ts.singleOrMany(statements); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, node.parameters, + /*type*/ undefined, node.body, + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node) { + var statements; + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, node.heritageClauses, node.members, + /*location*/ node), + /*original*/ node)); + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node) { + var statements; + var variables; + var expressions; + if (ts.hasModifier(node, 1 /* Export */)) { + var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var variable = _a[_i]; + if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { + if (!modifiers) { + modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + } + variables = ts.append(variables, variable); + } + else if (variable.initializer) { + expressions = ts.append(expressions, transformInitializedVariable(variable)); + } + } + if (variables) { + statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node)); + } + } + else { + statements = ts.append(statements, node); + } + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + return ts.singleOrMany(statements); + } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node) { + if (ts.isBindingPattern(node.name)) { + return ts.flattenDestructuringAssignment(node, + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createExportExpression); + } + else { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name, + /*location*/ node.name), node.initializer); + } + } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) { + var id = ts.getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); + } + return node; + } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node) { + return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + var id = ts.getOriginalNodeId(node); + var statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return ts.append(statements, node); + } + return node; + } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + var importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 237 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 238 /* NamedImports */: + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var importBinding = _a[_i]; + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements, node) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + statements = appendExportsOfBindingElement(statements, decl); + } + return statements; + } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + return statements; + } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements, decl) { + var name = ts.getDeclarationName(decl); + var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { + var exportSpecifier = exportSpecifiers_2[_i]; + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements, exportName, expression, location, allowComments) { + if (exportName.text === "default") { + var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 0 /* ES3 */) { + statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true)))); + } + else { + statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ]))); + } + } + } + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name, value, location, allowComments) { + var statement = ts.createStatement(createExportExpression(name, value), location); + ts.startOnNewLine(statement); + if (!allowComments) { + ts.setEmitFlags(statement, 1536 /* NoComments */); + } + return statement; + } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name, value, location) { + return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location); + } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node) { + // Elide module-specific modifiers. + switch (node.kind) { + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: + return undefined; + } + return node; + } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext, node, emitCallback) { + if (node.kind === 261 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; + noSubstitution = ts.createMap(); + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === 1 /* Expression */) { + return substituteExpression(node); + } + else if (ts.isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + var exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment + if (node.objectAssignmentInitializer) { + var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return ts.createPropertyAssignment(name, initializer, /*location*/ node); + } + return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node); + } + return node; + } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteExpression(node) { + switch (node.kind) { + case 70 /* Identifier */: + return substituteExpressionIdentifier(node); + case 192 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 191 /* PostfixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: + return substituteUnaryExpression(node); + } + return node; + } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ + function substituteExpressionIdentifier(node) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { + var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return ts.createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { + var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); + if (exportContainer && exportContainer.kind === 261 /* SourceFile */) { + return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node), + /*location*/ node); + } + var importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + var name_38 = importDeclaration.propertyName || importDeclaration.name; + return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_38), + /*location*/ node); + } + } + } + return node; + } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (ts.isAssignmentOperator(node.operatorToken.kind) + && ts.isIdentifier(node.left) + && !ts.isGeneratedIdentifier(node.left) + && !ts.isLocalName(node.left) + && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { + var exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = node; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); + } + return expression; + } + } + return node; + } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node) { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */) + && ts.isIdentifier(node.operand) + && !ts.isGeneratedIdentifier(node.operand) + && !ts.isLocalName(node.operand) + && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { + var exportedNames = getExports(node.operand); + if (exportedNames) { + var expression = node.kind === 191 /* PostfixUnaryExpression */ + ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 /* PlusPlusToken */ ? 58 /* PlusEqualsToken */ : 59 /* MinusEqualsToken */), ts.createLiteral(1), + /*location*/ node) + : node; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; + // Mark the node to prevent triggering this rule again. + noSubstitution[ts.getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + } + return expression; + } + } + return node; + } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name) { + if (!ts.isGeneratedIdentifier(name)) { + var valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]; + } + } + } + var _a; + } + ts.transformModule = transformModule; + // emit output for the __export helper function + var exportStarHelper = { + name: "typescript:export-star", + scoped: true, + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + }; + // emit output for the UMD helper function. + var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })"; })(ts || (ts = {})); /// /// /// -/// -/// +/// +/// +/// +/// /// +/// /// /// -/// +/// /* @internal */ var ts; (function (ts) { var moduleTransformerMap = ts.createMap((_a = {}, - _a[ts.ModuleKind.ES6] = ts.transformES6Module, + _a[ts.ModuleKind.ES2015] = ts.transformES2015Module, _a[ts.ModuleKind.System] = ts.transformSystemModule, _a[ts.ModuleKind.AMD] = ts.transformModule, _a[ts.ModuleKind.CommonJS] = ts.transformModule, @@ -51540,25 +57050,31 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var transformers = []; transformers.push(ts.transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - transformers.push(ts.transformES7); - if (languageVersion < 2 /* ES6 */) { - transformers.push(ts.transformES6); + if (languageVersion < 5 /* ESNext */) { + transformers.push(ts.transformESNext); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(ts.transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(ts.transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]); + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { + transformers.push(ts.transformES5); + } return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,76 +57084,46 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); + var enabledSyntaxKindFeatures = new Array(298 /* Count */); + var lexicalEnvironmentDisabled = false; + var lexicalEnvironmentVariableDeclarations; + var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; - var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; - var hoistedVariableDeclarations; - var hoistedFunctionDeclarations; - var lexicalEnvironmentDisabled; + var lexicalEnvironmentSuspended = false; + var emitHelpers; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, + startLexicalEnvironment: startLexicalEnvironment, + suspendLexicalEnvironment: suspendLexicalEnvironment, + resumeLexicalEnvironment: resumeLexicalEnvironment, + endLexicalEnvironment: endLexicalEnvironment, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, - startLexicalEnvironment: startLexicalEnvironment, - endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + requestEmitHelper: requestEmitHelper, + readEmitHelpers: readEmitHelpers, + onSubstituteNode: function (_emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +57146,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +57180,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51826,11 +57205,11 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); var decl = ts.createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } /** @@ -51838,11 +57217,11 @@ var ts; */ function hoistFunctionDeclaration(func) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } /** @@ -51851,15 +57230,28 @@ var ts; */ function startLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); // Save the current lexical environment. Rather than resizing the array we adjust the // stack size variable. This allows us to reuse existing array slots we've // already allocated between transformations to avoid allocation and GC overhead during // transformation. - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } /** * Ends a lexical environment. The previous set of hoisted declarations are restored and @@ -51867,14 +57259,15 @@ var ts; */ function endLexicalEnvironment() { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = hoistedFunctionDeclarations.slice(); + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = lexicalEnvironmentFunctionDeclarations.slice(); } - if (hoistedVariableDeclarations) { + if (lexicalEnvironmentVariableDeclarations) { var statement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(hoistedVariableDeclarations)); + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -51885,101 +57278,33 @@ var ts; } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + function requestEmitHelper(helper) { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = ts.append(emitHelpers, helper); + } + function readEmitHelpers() { + ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + var helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +57313,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,26 +57327,17 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, - getSourceMappingURL: getSourceMappingURL + getSourceMappingURL: getSourceMappingURL, }; /** * Initialize the SourceMapWriter for a new output file. @@ -52034,12 +57348,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +57409,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +57419,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +57466,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +57495,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 293 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 64 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 293 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +57574,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,21 +57600,27 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, sources: sourceMapData.sourceMapSources, names: sourceMapData.sourceMapNames, mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent + sourcesContent: sourceMapData.sourceMapSourcesContent, }); } /** * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +57631,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52455,32 +57688,34 @@ var ts; setSourceFile: setSourceFile, emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, - emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition + emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; - var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + var isEmittedNode = node.kind !== 293 /* NotEmittedStatement */; + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { @@ -52497,18 +57732,20 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 219 /* VariableDeclarationList */) { + if (node.kind === 224 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitNodeWithComment"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,17 +57770,19 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; - var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; + var emitFlags = ts.getEmitFlags(node); + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52553,6 +57792,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -52580,7 +57822,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -52599,7 +57841,7 @@ var ts; function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -52623,7 +57865,7 @@ var ts; ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); } } - function emitTrailingCommentOfPosition(commentPos, commentEnd, kind, hasTrailingNewLine) { + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); @@ -52664,16 +57906,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +57967,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52757,7 +57989,7 @@ var ts; var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; var noDeclare; var moduleElementDeclarationEmitInfo = []; @@ -52786,7 +58018,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52813,7 +58045,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 230 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 235 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -52847,7 +58079,7 @@ var ts; reportedDeclarationError: reportedDeclarationError, moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput + referencesOutput: referencesOutput, }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); @@ -52872,6 +58104,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -52887,10 +58120,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 218 /* VariableDeclaration */) { + if (declaration.kind === 223 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 233 /* NamedImports */ || declaration.kind === 234 /* ImportSpecifier */ || declaration.kind === 231 /* ImportClause */) { + else if (declaration.kind === 238 /* NamedImports */ || declaration.kind === 239 /* ImportSpecifier */ || declaration.kind === 236 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -52908,7 +58141,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 230 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 235 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -52918,12 +58151,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 225 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 230 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 225 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 230 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -52987,7 +58220,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,20 +58233,20 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } function emitLines(nodes) { - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -53028,7 +58261,7 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); @@ -53040,53 +58273,59 @@ var ts; } function emitType(type) { switch (type.kind) { - case 117 /* AnyKeyword */: - case 132 /* StringKeyword */: - case 130 /* NumberKeyword */: - case 120 /* BooleanKeyword */: - case 133 /* SymbolKeyword */: - case 103 /* VoidKeyword */: - case 135 /* UndefinedKeyword */: - case 93 /* NullKeyword */: - case 127 /* NeverKeyword */: - case 165 /* ThisType */: - case 166 /* LiteralType */: + case 118 /* AnyKeyword */: + case 134 /* StringKeyword */: + case 132 /* NumberKeyword */: + case 121 /* BooleanKeyword */: + case 135 /* SymbolKeyword */: + case 104 /* VoidKeyword */: + case 137 /* UndefinedKeyword */: + case 94 /* NullKeyword */: + case 129 /* NeverKeyword */: + case 167 /* ThisType */: + case 171 /* LiteralType */: return writeTextOfNode(currentText, type); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return emitTypeReference(type); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return emitTypeQuery(type); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return emitArrayType(type); - case 161 /* TupleType */: + case 163 /* TupleType */: return emitTupleType(type); - case 162 /* UnionType */: + case 164 /* UnionType */: return emitUnionType(type); - case 163 /* IntersectionType */: + case 165 /* IntersectionType */: return emitIntersectionType(type); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return emitParenType(type); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 168 /* TypeOperator */: + return emitTypeOperator(type); + case 169 /* IndexedAccessType */: + return emitIndexedAccessType(type); + case 170 /* MappedType */: + return emitMappedType(type); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return emitTypeLiteral(type); - case 69 /* Identifier */: + case 70 /* Identifier */: return emitEntityName(type); - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return emitEntityName(type); - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 69 /* Identifier */) { + if (entityName.kind === 70 /* Identifier */) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 139 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 139 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 141 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 141 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); @@ -53095,14 +58334,14 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 229 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 234 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 70 /* Identifier */ || node.expression.kind === 177 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -53148,6 +58387,42 @@ var ts; emitType(type.type); write(")"); } + function emitTypeOperator(type) { + write(ts.tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + function emitIndexedAccessType(node) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + function emitMappedType(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } function emitTypeLiteral(type) { write("{"); if (type.members.length) { @@ -53181,14 +58456,14 @@ var ts; var count = 0; while (true) { count++; - var name_40 = baseName + "_" + count; - if (!(name_40 in currentIdentifiers)) { - return name_40; + var name_39 = baseName + "_" + count; + if (!(name_39 in currentIdentifiers)) { + return name_39; } } } function emitExportAssignment(node) { - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -53202,7 +58477,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53211,12 +58486,12 @@ var ts; write(";"); writeLine(); // Make all the declarations visible for the export name - if (node.expression.kind === 69 /* Identifier */) { + if (node.expression.kind === 70 /* Identifier */) { var nodes = resolver.collectLinkedAliases(node.expression); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic) { + function getDefaultExportAccessibilityDiagnostic() { return { diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -53230,10 +58505,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 229 /* ImportEqualsDeclaration */ || - (node.parent.kind === 256 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 234 /* ImportEqualsDeclaration */ || + (node.parent.kind === 261 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 256 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -53243,7 +58518,7 @@ var ts; }); } else { - if (node.kind === 230 /* ImportDeclaration */) { + if (node.kind === 235 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -53261,23 +58536,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return writeVariableStatement(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return writeClassDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -53285,7 +58560,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 256 /* SourceFile */) { + if (node.parent.kind === 261 /* SourceFile */) { var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { @@ -53294,7 +58569,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 222 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 227 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } @@ -53336,7 +58611,7 @@ var ts; write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult) { + function getImportEntityNameVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -53346,7 +58621,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 232 /* NamespaceImport */) { + if (namedBindings.kind === 237 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -53370,7 +58645,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 237 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -53391,13 +58666,13 @@ var ts; // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 225 /* ModuleDeclaration */; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230 /* ModuleDeclaration */; var moduleSpecifier; - if (parent.kind === 229 /* ImportEqualsDeclaration */) { + if (parent.kind === 234 /* ImportEqualsDeclaration */) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 225 /* ModuleDeclaration */) { + else if (parent.kind === 230 /* ModuleDeclaration */) { moduleSpecifier = parent.name; } else { @@ -53467,7 +58742,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 231 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -53501,7 +58776,7 @@ var ts; write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + function getTypeAliasDeclarationVisibilityError() { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -53537,7 +58812,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 147 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 149 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -53548,52 +58823,55 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 159 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 147 /* MethodDeclaration */ || - node.parent.kind === 146 /* MethodSignature */ || - node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - node.parent.kind === 151 /* CallSignature */ || - node.parent.kind === 152 /* ConstructSignature */); + if (node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 161 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 149 /* MethodDeclaration */ || + node.parent.kind === 148 /* MethodSignature */ || + node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + node.parent.kind === 153 /* CallSignature */ || + node.parent.kind === 154 /* ConstructSignature */); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { + function getTypeParameterConstraintVisibilityError() { // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 226 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case 228 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; default: ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -53619,17 +58897,17 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { + else if (!isImplementsList && node.expression.kind === 94 /* NullKeyword */) { write("null"); } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult) { + function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + if (node.parent.parent.kind === 226 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -53690,7 +58968,10 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); + var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); + } write(" {"); writeLine(); increaseIndent(); @@ -53713,7 +58994,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 218 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 223 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -53724,11 +59005,11 @@ var ts; writeTextOfNode(currentText, node.name); // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor // we don't want to emit property declaration with "?" - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || - (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */ || + (node.kind === 144 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { + if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) && node.parent.kind === 161 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -53741,14 +59022,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 218 /* VariableDeclaration */) { + if (node.kind === 223 /* VariableDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) { + else if (node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -53757,7 +59038,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -53789,7 +59070,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 193 /* OmittedExpression */) { + if (element.kind !== 198 /* OmittedExpression */) { elements.push(element); } } @@ -53859,7 +59140,7 @@ var ts; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 149 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 151 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -53872,7 +59153,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 149 /* GetAccessor */ + return accessor.kind === 151 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -53881,7 +59162,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 150 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 152 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? @@ -53931,17 +59212,17 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 220 /* FunctionDeclaration */) { + if (node.kind === 225 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 147 /* MethodDeclaration */ || node.kind === 148 /* Constructor */) { + else if (node.kind === 149 /* MethodDeclaration */ || node.kind === 150 /* Constructor */) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 220 /* FunctionDeclaration */) { + if (node.kind === 225 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 148 /* Constructor */) { + else if (node.kind === 150 /* Constructor */) { write("constructor"); } else { @@ -53961,17 +59242,17 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { // Index signature can have readonly modifier emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { // Construct signature or constructor type write new Signature - if (node.kind === 152 /* ConstructSignature */ || node.kind === 157 /* ConstructorType */) { + if (node.kind === 154 /* ConstructSignature */ || node.kind === 159 /* ConstructorType */) { write("new "); } - else if (node.kind === 156 /* FunctionType */) { + else if (node.kind === 158 /* FunctionType */) { var currentOutput = writer.getText(); // Do not generate incorrect type when function type with type parameters is type argument // This could happen if user used space between two '<' making it error free @@ -53986,22 +59267,22 @@ var ts; } // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 153 /* IndexSignature */) { + if (node.kind === 155 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 156 /* FunctionType */ || node.kind === 157 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 159 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 158 /* FunctionType */ || node.kind === 159 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 161 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 148 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { + else if (node.kind !== 150 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -54015,26 +59296,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151 /* CallSignature */: + case 153 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -54042,7 +59323,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.kind === 226 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54056,7 +59337,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54091,9 +59372,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 156 /* FunctionType */ || - node.parent.kind === 157 /* ConstructorType */ || - node.parent.parent.kind === 159 /* TypeLiteral */) { + if (node.parent.kind === 158 /* FunctionType */ || + node.parent.kind === 159 /* ConstructorType */ || + node.parent.parent.kind === 161 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8 /* Private */)) { @@ -54109,24 +59390,29 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 148 /* Constructor */: + case 150 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151 /* CallSignature */: + case 153 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 155 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -54134,7 +59420,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 221 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 226 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54147,7 +59433,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54159,12 +59445,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 167 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 172 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 168 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -54175,7 +59461,7 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 193 /* OmittedExpression */) { + if (bindingElement.kind === 198 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -54184,7 +59470,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 169 /* BindingElement */) { + else if (bindingElement.kind === 174 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -54207,7 +59493,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 69 /* Identifier */); + ts.Debug.assert(bindingElement.name.kind === 70 /* Identifier */); // If the node is just an identifier, we will simply emit the text associated with the node's name // Example: // original: function foo({y = 10, x}) {} @@ -54223,40 +59509,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 225 /* ModuleDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 222 /* InterfaceDeclaration */: - case 221 /* ClassDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: + case 225 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 227 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return emitExportDeclaration(node); - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return writeFunctionDeclaration(node); - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 153 /* IndexSignature */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 155 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return emitAccessorDeclaration(node); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return emitPropertyDeclaration(node); - case 255 /* EnumMember */: + case 260 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return emitExportAssignment(node); - case 256 /* SourceFile */: + case 261 /* SourceFile */: return emitSourceFile(node); } } @@ -54265,7 +59551,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +59560,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54282,7 +59568,7 @@ var ts; referencesOutput += "/// " + newLine; } return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) { // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path if (isBundledEmit && !addBundledFileReference) { return; @@ -54294,8 +59580,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,90 +59621,12 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (_) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); - // emit output for the __extends helper function - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; - // Emit output for the __assign helper function. - // This is typically used for JSX spread attributes, - // and can be used for object literal spread properties. - var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; - // emit output for the __decorate helper function - var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; - // emit output for the __metadata helper function - var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; - // emit output for the __param helper function - var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; - // The __generator helper is used by down-level transformations to emulate the runtime - // semantics of an ES2015 generator function. When called, this helper returns an - // object that implements the Iterator protocol, in that it has `next`, `return`, and - // `throw` methods that step through the generator when invoked. - // - // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. - // - // variables: - // _ Persistent state for the generator that is shared between the helper and the - // generator body. The state object has the following members: - // sent() - A method that returns or throws the current completion value. - // label - The next point at which to resume evaluation of the generator body. - // trys - A stack of protected regions (try/catch/finally blocks). - // ops - A stack of pending instructions when inside of a finally block. - // f A value indicating whether the generator is executing. - // y An iterator to delegate for a yield*. - // t A temporary variable that holds one of the following values (note that these - // cases do not overlap): - // - The completion value when resuming from a `yield` or `yield*`. - // - The error value for a catch block. - // - The current protected region (array of try/catch/finally/end labels). - // - The verb (`next`, `throw`, or `return` method) to delegate to the expression - // of a `yield*`. - // - The result of evaluating the verb delegated to the expression of a `yield*`. - // - // functions: - // verb(n) Creates a bound callback to the `step` function for opcode `n`. - // step(op) Evaluates opcodes in a generator body until execution is suspended or - // completed. - // - // The __generator helper understands a limited set of instructions: - // 0: next(value?) - Start or resume the generator with the specified value. - // 1: throw(error) - Resume the generator with an exception. If the generator is - // suspended inside of one or more protected regions, evaluates - // any intervening finally blocks between the current label and - // the nearest catch block or function boundary. If uncaught, the - // exception is thrown to the caller. - // 2: return(value?) - Resume the generator as if with a return. If the generator is - // suspended inside of one or more protected regions, evaluates any - // intervening finally blocks. - // 3: break(label) - Jump to the specified label. If the label is outside of the - // current protected region, evaluates any intervening finally - // blocks. - // 4: yield(value?) - Yield execution to the caller with an optional value. When - // resumed, the generator will continue at the next label. - // 5: yield*(value) - Delegates evaluation to the supplied iterator. When - // delegation completes, the generator will continue at the next - // label. - // 6: catch(error) - Handles an exception thrown from within the generator body. If - // the current label is inside of one or more protected regions, - // evaluates any intervening finally blocks between the current - // label and the nearest catch block or function boundary. If - // uncaught, the exception is thrown to the caller. - // 7: endfinally - Ends a finally block, resuming the last instruction prior to - // entering a finally block. - // - // For examples of how these are used, see the comments in ./transformers/generators.ts - var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; - // emit output for the __export helper function - var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; - // emit output for the UMD helper function. - var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; - var superHelper = "\nconst _super = name => super[name];"; - var advancedSuperHelper = "\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -54426,11 +59634,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54440,25 +59648,23 @@ var ts; var currentSourceFile; var currentText; var currentFileIdentifiers; - var extendsEmitted; - var assignEmitted; - var decorateEmitted; - var paramEmitted; - var awaiterEmitted; + var bundledHelpers; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +59674,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54491,12 +59701,13 @@ var ts; nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = ts.createMap(); + bundledHelpers = isBundledEmit ? ts.createMap() : undefined; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; - emitEmitHelpers(sourceFile); + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; + emitHelpers(sourceFile, /*isBundle*/ true); } } // Print each transformed source file. @@ -54508,14 +59719,14 @@ var ts; } // Write the source map if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Record source map data for the test harness. if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); comments.reset(); @@ -54523,11 +59734,6 @@ var ts; tempFlags = 0 /* Auto */; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } function printSourceFile(node) { @@ -54536,448 +59742,465 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 261 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 70 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals - case 12 /* TemplateHead */: - case 13 /* TemplateMiddle */: - case 14 /* TemplateTail */: + case 13 /* TemplateHead */: + case 14 /* TemplateMiddle */: + case 15 /* TemplateTail */: return emitLiteral(node); // Identifiers - case 69 /* Identifier */: + case 70 /* Identifier */: return emitIdentifier(node); // Reserved words - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 82 /* ExportKeyword */: - case 103 /* VoidKeyword */: + case 75 /* ConstKeyword */: + case 78 /* DefaultKeyword */: + case 83 /* ExportKeyword */: + case 104 /* VoidKeyword */: // Strict mode reserved words - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 112 /* PublicKeyword */: - case 113 /* StaticKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 114 /* StaticKeyword */: // Contextual keywords - case 115 /* AbstractKeyword */: - case 117 /* AnyKeyword */: - case 118 /* AsyncKeyword */: - case 120 /* BooleanKeyword */: - case 122 /* DeclareKeyword */: - case 130 /* NumberKeyword */: - case 128 /* ReadonlyKeyword */: - case 132 /* StringKeyword */: - case 133 /* SymbolKeyword */: - case 137 /* GlobalKeyword */: - return writeTokenNode(node); + case 116 /* AbstractKeyword */: + case 117 /* AsKeyword */: + case 118 /* AnyKeyword */: + case 119 /* AsyncKeyword */: + case 120 /* AwaitKeyword */: + case 121 /* BooleanKeyword */: + case 122 /* ConstructorKeyword */: + case 123 /* DeclareKeyword */: + case 124 /* GetKeyword */: + case 125 /* IsKeyword */: + case 127 /* ModuleKeyword */: + case 128 /* NamespaceKeyword */: + case 129 /* NeverKeyword */: + case 130 /* ReadonlyKeyword */: + case 131 /* RequireKeyword */: + case 132 /* NumberKeyword */: + case 133 /* SetKeyword */: + case 134 /* StringKeyword */: + case 135 /* SymbolKeyword */: + case 136 /* TypeKeyword */: + case 137 /* UndefinedKeyword */: + case 138 /* FromKeyword */: + case 139 /* GlobalKeyword */: + case 140 /* OfKeyword */: + writeTokenText(kind); + return; // Parse tree nodes // Names - case 139 /* QualifiedName */: + case 141 /* QualifiedName */: return emitQualifiedName(node); - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: return emitTypeParameter(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return emitParameter(node); - case 143 /* Decorator */: + case 145 /* Decorator */: return emitDecorator(node); // Type members - case 144 /* PropertySignature */: + case 146 /* PropertySignature */: return emitPropertySignature(node); - case 145 /* PropertyDeclaration */: + case 147 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 146 /* MethodSignature */: + case 148 /* MethodSignature */: return emitMethodSignature(node); - case 147 /* MethodDeclaration */: + case 149 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return emitConstructor(node); - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return emitAccessorDeclaration(node); - case 151 /* CallSignature */: + case 153 /* CallSignature */: return emitCallSignature(node); - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: return emitConstructSignature(node); - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return emitIndexSignature(node); // Types - case 154 /* TypePredicate */: + case 156 /* TypePredicate */: return emitTypePredicate(node); - case 155 /* TypeReference */: + case 157 /* TypeReference */: return emitTypeReference(node); - case 156 /* FunctionType */: + case 158 /* FunctionType */: return emitFunctionType(node); - case 157 /* ConstructorType */: + case 159 /* ConstructorType */: return emitConstructorType(node); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return emitTypeQuery(node); - case 159 /* TypeLiteral */: + case 161 /* TypeLiteral */: return emitTypeLiteral(node); - case 160 /* ArrayType */: + case 162 /* ArrayType */: return emitArrayType(node); - case 161 /* TupleType */: + case 163 /* TupleType */: return emitTupleType(node); - case 162 /* UnionType */: + case 164 /* UnionType */: return emitUnionType(node); - case 163 /* IntersectionType */: + case 165 /* IntersectionType */: return emitIntersectionType(node); - case 164 /* ParenthesizedType */: + case 166 /* ParenthesizedType */: return emitParenthesizedType(node); - case 194 /* ExpressionWithTypeArguments */: + case 199 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 165 /* ThisType */: - return emitThisType(node); - case 166 /* LiteralType */: + case 167 /* ThisType */: + return emitThisType(); + case 168 /* TypeOperator */: + return emitTypeOperator(node); + case 169 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 170 /* MappedType */: + return emitMappedType(node); + case 171 /* LiteralType */: return emitLiteralType(node); // Binding patterns - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return emitBindingElement(node); // Misc - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return emitTemplateSpan(node); - case 198 /* SemicolonClassElement */: - return emitSemicolonClassElement(node); + case 203 /* SemicolonClassElement */: + return emitSemicolonClassElement(); // Statements - case 199 /* Block */: + case 204 /* Block */: return emitBlock(node); - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: return emitVariableStatement(node); - case 201 /* EmptyStatement */: - return emitEmptyStatement(node); - case 202 /* ExpressionStatement */: + case 206 /* EmptyStatement */: + return emitEmptyStatement(); + case 207 /* ExpressionStatement */: return emitExpressionStatement(node); - case 203 /* IfStatement */: + case 208 /* IfStatement */: return emitIfStatement(node); - case 204 /* DoStatement */: + case 209 /* DoStatement */: return emitDoStatement(node); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: return emitWhileStatement(node); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return emitForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: return emitForInStatement(node); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: return emitForOfStatement(node); - case 209 /* ContinueStatement */: + case 214 /* ContinueStatement */: return emitContinueStatement(node); - case 210 /* BreakStatement */: + case 215 /* BreakStatement */: return emitBreakStatement(node); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: return emitReturnStatement(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: return emitWithStatement(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return emitSwitchStatement(node); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: return emitLabeledStatement(node); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: return emitThrowStatement(node); - case 216 /* TryStatement */: + case 221 /* TryStatement */: return emitTryStatement(node); - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 219 /* VariableDeclarationList */: + case 224 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 220 /* FunctionDeclaration */: + case 225 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: return emitClassDeclaration(node); - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return emitModuleBlock(node); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return emitCaseBlock(node); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: return emitImportDeclaration(node); - case 231 /* ImportClause */: + case 236 /* ImportClause */: return emitImportClause(node); - case 232 /* NamespaceImport */: + case 237 /* NamespaceImport */: return emitNamespaceImport(node); - case 233 /* NamedImports */: + case 238 /* NamedImports */: return emitNamedImports(node); - case 234 /* ImportSpecifier */: + case 239 /* ImportSpecifier */: return emitImportSpecifier(node); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: return emitExportAssignment(node); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: return emitExportDeclaration(node); - case 237 /* NamedExports */: + case 242 /* NamedExports */: return emitNamedExports(node); - case 238 /* ExportSpecifier */: + case 243 /* ExportSpecifier */: return emitExportSpecifier(node); - case 239 /* MissingDeclaration */: + case 244 /* MissingDeclaration */: return; // Module references - case 240 /* ExternalModuleReference */: + case 245 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) - case 244 /* JsxText */: + case 10 /* JsxText */: return emitJsxText(node); - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: return emitJsxOpeningElement(node); - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: return emitJsxClosingElement(node); - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: return emitJsxAttribute(node); - case 247 /* JsxSpreadAttribute */: + case 251 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 248 /* JsxExpression */: + case 252 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 249 /* CaseClause */: + case 253 /* CaseClause */: return emitCaseClause(node); - case 250 /* DefaultClause */: + case 254 /* DefaultClause */: return emitDefaultClause(node); - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: return emitHeritageClause(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 253 /* PropertyAssignment */: + case 257 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 254 /* ShorthandPropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); + case 259 /* SpreadAssignment */: + return emitSpreadAssignment(node); // Enum - case 255 /* EnumMember */: + case 260 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals case 8 /* NumericLiteral */: return emitNumericLiteral(node); case 9 /* StringLiteral */: - case 10 /* RegularExpressionLiteral */: - case 11 /* NoSubstitutionTemplateLiteral */: + case 11 /* RegularExpressionLiteral */: + case 12 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); // Identifiers - case 69 /* Identifier */: + case 70 /* Identifier */: return emitIdentifier(node); // Reserved words - case 84 /* FalseKeyword */: - case 93 /* NullKeyword */: - case 95 /* SuperKeyword */: - case 99 /* TrueKeyword */: - case 97 /* ThisKeyword */: - return writeTokenNode(node); - // Expressions - case 170 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 171 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 172 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 174 /* CallExpression */: - return emitCallExpression(node); - case 175 /* NewExpression */: - return emitNewExpression(node); - case 176 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 177 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 178 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 179 /* FunctionExpression */: - return emitFunctionExpression(node); - case 180 /* ArrowFunction */: - return emitArrowFunction(node); - case 181 /* DeleteExpression */: - return emitDeleteExpression(node); - case 182 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 183 /* VoidExpression */: - return emitVoidExpression(node); - case 184 /* AwaitExpression */: - return emitAwaitExpression(node); - case 185 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 186 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 187 /* BinaryExpression */: - return emitBinaryExpression(node); - case 188 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 189 /* TemplateExpression */: - return emitTemplateExpression(node); - case 190 /* YieldExpression */: - return emitYieldExpression(node); - case 191 /* SpreadElementExpression */: - return emitSpreadElementExpression(node); - case 192 /* ClassExpression */: - return emitClassExpression(node); - case 193 /* OmittedExpression */: + case 85 /* FalseKeyword */: + case 94 /* NullKeyword */: + case 96 /* SuperKeyword */: + case 100 /* TrueKeyword */: + case 98 /* ThisKeyword */: + writeTokenText(kind); return; - case 195 /* AsExpression */: + // Expressions + case 175 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 176 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 177 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 178 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 179 /* CallExpression */: + return emitCallExpression(node); + case 180 /* NewExpression */: + return emitNewExpression(node); + case 181 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 182 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 183 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 184 /* FunctionExpression */: + return emitFunctionExpression(node); + case 185 /* ArrowFunction */: + return emitArrowFunction(node); + case 186 /* DeleteExpression */: + return emitDeleteExpression(node); + case 187 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 188 /* VoidExpression */: + return emitVoidExpression(node); + case 189 /* AwaitExpression */: + return emitAwaitExpression(node); + case 190 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 191 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 192 /* BinaryExpression */: + return emitBinaryExpression(node); + case 193 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 194 /* TemplateExpression */: + return emitTemplateExpression(node); + case 195 /* YieldExpression */: + return emitYieldExpression(node); + case 196 /* SpreadElement */: + return emitSpreadExpression(node); + case 197 /* ClassExpression */: + return emitClassExpression(node); + case 198 /* OmittedExpression */: + return; + case 200 /* AsExpression */: return emitAsExpression(node); - case 196 /* NonNullExpression */: + case 201 /* NonNullExpression */: return emitNonNullExpression(node); // JSX - case 241 /* JsxElement */: + case 246 /* JsxElement */: return emitJsxElement(node); - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 294 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); + case 297 /* RawExpression */: + return writeLines(node.text); } } // @@ -55010,12 +60233,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, /*includeTrivia*/ false)); - } + write(getTextOfNode(node, /*includeTrivia*/ false)); } // // Names @@ -55026,7 +60244,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -55102,7 +60320,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 149 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 151 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55130,7 +60348,7 @@ var ts; emitWithPrefix(": ", node.type); write(";"); } - function emitSemicolonClassElement(node) { + function emitSemicolonClassElement() { write(";"); } // @@ -55187,9 +60405,42 @@ var ts; emit(node.type); write(")"); } - function emitThisType(node) { + function emitThisType() { write("this"); } + function emitTypeOperator(node) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + function emitIndexedAccessType(node) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + function emitMappedType(node) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } function emitLiteralType(node) { emitExpression(node.literal); } @@ -55243,7 +60494,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +60507,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 65536 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; - var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; + var dotToken = { kind: 22 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55282,19 +60530,18 @@ var ts; if (expression.kind === 8 /* NumericLiteral */) { // check if numeric literal was originally written with a dot var text = getLiteralTextOfNode(expression); - return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; + return text.indexOf(ts.tokenToString(22 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55302,11 +60549,13 @@ var ts; } function emitCallExpression(node) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { @@ -55378,16 +60627,16 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 185 /* PrefixUnaryExpression */ - && ((node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) - || (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */))); + return operand.kind === 190 /* PrefixUnaryExpression */ + && ((node.operator === 36 /* PlusToken */ && (operand.operator === 36 /* PlusToken */ || operand.operator === 42 /* PlusPlusToken */)) + || (node.operator === 37 /* MinusToken */ && (operand.operator === 37 /* MinusToken */ || operand.operator === 43 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 24 /* CommaToken */; + var isCommaOperator = node.operatorToken.kind !== 25 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); @@ -55422,7 +60671,7 @@ var ts; write(node.asteriskToken ? "yield*" : "yield"); emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node) { + function emitSpreadExpression(node) { write("..."); emitExpression(node.expression); } @@ -55454,20 +60703,20 @@ var ts; // // Statements // - function emitBlock(node, format) { + function emitBlock(node) { if (isSingleLineEmptyBlock(node)) { - writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); write(" "); - writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } else { - writeToken(15 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); emitBlockStatements(node); - writeToken(16 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55479,7 +60728,7 @@ var ts; emit(node.declarationList); write(";"); } - function emitEmptyStatement(node) { + function emitEmptyStatement() { write(";"); } function emitExpressionStatement(node) { @@ -55487,16 +60736,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(88 /* IfKeyword */, node.pos, node); + var openParenPos = writeToken(89 /* IfKeyword */, node.pos, node); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos, node); + writeToken(18 /* OpenParenToken */, openParenPos, node); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end, node); + writeToken(19 /* CloseParenToken */, node.expression.end, node); emitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { writeLine(); - writeToken(80 /* ElseKeyword */, node.thenStatement.end, node); - if (node.elseStatement.kind === 203 /* IfStatement */) { + writeToken(81 /* ElseKeyword */, node.thenStatement.end, node); + if (node.elseStatement.kind === 208 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -55525,9 +60774,9 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + writeToken(18 /* OpenParenToken */, openParenPos, /*contextNode*/ node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -55537,28 +60786,28 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(86 /* ForKeyword */, node.pos); + var openParenPos = writeToken(87 /* ForKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 219 /* VariableDeclarationList */) { + if (node.kind === 224 /* VariableDeclarationList */) { emit(node); } else { @@ -55567,17 +60816,17 @@ var ts; } } function emitContinueStatement(node) { - writeToken(75 /* ContinueKeyword */, node.pos); + writeToken(76 /* ContinueKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(70 /* BreakKeyword */, node.pos); + writeToken(71 /* BreakKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitReturnStatement(node) { - writeToken(94 /* ReturnKeyword */, node.pos, /*contextNode*/ node); + writeToken(95 /* ReturnKeyword */, node.pos, /*contextNode*/ node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -55588,11 +60837,11 @@ var ts; emitEmbeddedStatement(node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(96 /* SwitchKeyword */, node.pos); + var openParenPos = writeToken(97 /* SwitchKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emitExpression(node.expression); - writeToken(18 /* CloseParenToken */, node.expression.end); + writeToken(19 /* CloseParenToken */, node.expression.end); write(" "); emit(node.caseBlock); } @@ -55617,7 +60866,7 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(76 /* DebuggerKeyword */, node.pos); + writeToken(77 /* DebuggerKeyword */, node.pos); write(";"); } // @@ -55625,6 +60874,7 @@ var ts; // function emitVariableDeclaration(node) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } function emitVariableDeclarationList(node) { @@ -55645,19 +60895,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 262144 /* ReuseTempVariableScope */) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { var savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } if (indentedFlag) { @@ -55680,14 +60930,14 @@ var ts; emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { + function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: // * The body has NodeEmitFlags.SingleLine specified. // We must emit a function body as a multi-line body in the following cases: // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55710,14 +60960,14 @@ var ts; } return true; } - function emitBlockFunctionBody(parentNode, body) { + function emitBlockFunctionBody(body) { write(" {"); increaseIndent(); - emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); decreaseIndent(); - writeToken(16 /* CloseBraceToken */, body.statements.end, body); + writeToken(17 /* CloseBraceToken */, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -55743,7 +60993,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55796,7 +61046,7 @@ var ts; write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); emit(node.name); var body = node.body; - while (body.kind === 225 /* ModuleDeclaration */) { + while (body.kind === 230 /* ModuleDeclaration */) { write("."); emit(body.name); body = body.body; @@ -55805,7 +61055,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -55819,9 +61069,9 @@ var ts; } } function emitCaseBlock(node) { - writeToken(15 /* OpenBraceToken */, node.pos); + writeToken(16 /* OpenBraceToken */, node.pos); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(16 /* CloseBraceToken */, node.clauses.end); + writeToken(17 /* CloseBraceToken */, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -55832,7 +61082,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -55958,7 +61208,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 69 /* Identifier */) { + if (node.kind === 70 /* Identifier */) { emitExpression(node); } else { @@ -56001,11 +61251,11 @@ var ts; } function emitCatchClause(node) { writeLine(); - var openParenPos = writeToken(72 /* CatchKeyword */, node.pos); + var openParenPos = writeToken(73 /* CatchKeyword */, node.pos); write(" "); - writeToken(17 /* OpenParenToken */, openParenPos); + writeToken(18 /* OpenParenToken */, openParenPos); emit(node.variableDeclaration); - writeToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + writeToken(19 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); write(" "); emit(node.block); } @@ -56023,8 +61273,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56036,6 +61286,12 @@ var ts; emitExpression(node.objectAssignmentInitializer); } } + function emitSpreadAssignment(node) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } // // Enum // @@ -56083,68 +61339,37 @@ var ts; } return statements.length; } - function emitHelpers(node) { - var emitFlags = node.emitFlags; + function emitHelpers(node, isBundle) { + var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile; + var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit; var helpersEmitted = false; - if (emitFlags & 1 /* EmitEmitHelpers */) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - if (emitFlags & 2 /* EmitExportStar */) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - if (emitFlags & 4 /* EmitSuperHelper */) { - writeLines(superHelper); - helpersEmitted = true; - } - if (emitFlags & 8 /* EmitAdvancedSuperHelper */) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - return helpersEmitted; - } - function emitEmitHelpers(node) { - // Only emit helpers if the user did not say otherwise. - if (compilerOptions.noEmitHelpers) { - return false; - } - // Don't emit helpers if we can import them. - if (compilerOptions.importHelpers - && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } - var helpersEmitted = false; - // Only Emit __extends function when target ES5. - // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 1024 /* HasClassExtends */)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } - if (compilerOptions.jsx !== 1 /* Preserve */ && !assignEmitted && (node.flags & 16384 /* HasJsxSpreadAttributes */)) { - writeLines(assignHelper); - assignEmitted = true; - } - if (!decorateEmitted && node.flags & 2048 /* HasDecorators */) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + writeLines(helper.text); + helpersEmitted = true; } - decorateEmitted = true; - helpersEmitted = true; - } - if (!paramEmitted && node.flags & 4096 /* HasParamDecorators */) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - if (!awaiterEmitted && node.flags & 8192 /* HasAsyncFunctions */) { - writeLines(awaiterHelper); - if (languageVersion < 2 /* ES6 */) { - writeLines(generatorHelper); - } - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { writeLine(); @@ -56152,9 +61377,10 @@ var ts; return helpersEmitted; } function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); + var lines = text.split(/\r\n?|\n/g); + var indentation = guessIndentation(lines); for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + var line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -56163,6 +61389,21 @@ var ts; } } } + function guessIndentation(lines) { + var indentation; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var line = lines_1[_a]; + for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!ts.isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } // // Helpers // @@ -56197,31 +61438,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +61545,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +61591,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56507,7 +61708,7 @@ var ts; && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 178 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 183 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -56539,17 +61740,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56575,10 +61771,10 @@ var ts; */ function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_41 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_41)) { + var name_40 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_40)) { tempFlags |= flags; - return name_41; + return name_40; } } while (true) { @@ -56586,11 +61782,11 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_42 = count < 26 + var name_41 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_42)) { - return name_42; + if (isUniqueName(name_41)) { + return name_41; } } } @@ -56637,19 +61833,19 @@ var ts; */ function generateNameForNode(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return makeUniqueName(getTextOfNode(node)); - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 230 /* ImportDeclaration */: - case 236 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: + case 241 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 235 /* ExportAssignment */: + case 225 /* FunctionDeclaration */: + case 226 /* ClassDeclaration */: + case 240 /* ExportAssignment */: return generateNameForExportDefault(); - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: return generateNameForClassExpression(); default: return makeTempVariableName(0 /* Auto */); @@ -56815,8 +62011,6 @@ var ts; /// var ts; (function (ts) { - /** The version of the TypeScript compiler release */ - ts.version = "2.1.0"; var emptyArray = []; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -56878,695 +62072,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @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 - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === 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, typeRoots); - } - } - else { - 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, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +62177,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); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57731,54 +62236,15 @@ var ts; } var resolutions = []; var cache = ts.createMap(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var result = name_43 in cache - ? cache[name_43] - : cache[name_43] = loader(name_43, containingFile); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_42 = names_1[_i]; + var result = name_42 in cache + ? cache[name_42] + : cache[name_42] = loader(name_42, containingFile); resolutions.push(result); } return resolutions; } - /** - * Given a set of options, 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, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57795,7 +62261,7 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. @@ -57812,10 +62278,18 @@ var ts; var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +62297,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,10 +62307,11 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -57884,20 +62359,23 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { // Make sure directory path ends with directory separator so this string can directly @@ -57920,6 +62398,112 @@ var ts; } return classifiableNames; } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + // if old program state is not supplied and file does not contain locally defined ambient modules + // then the best we can do is fallback to the default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + // at this point we know that either + // - file has local declarations for ambient modules + // OR + // - old program state is available + // OR + // - both of items above + // With this it is possible that we can tell how some module names from the initial list will be resolved + // without doing actual resolution (in particular if some name was resolved to ambient module). + // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` + // since we don't want to resolve them again. + // this is a list of modules for which we cannot predict resolution so they should be actually resolved + var unknownModuleNames; + // this is a list of combined results assembles from predicted and resolved results. + // Order in this list matches the order in the original list of module names `moduleNames` which is important + // so later we can split results to resolutions of modules and resolutions of module augmentations. + var result; + // a transient placeholder that is used to mark predicted resolution in the result list + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // module name is known to be resolved to ambient module if + // - module name is contained in the list of ambient modules that are locally declared in the file + // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // (so the same module declaration will land in the new program) + var isKnownToResolveToAmbientModule = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + // found a first module name for which result can be prediced + // this means that this module name should not be passed to `resolveModuleNamesWorker`. + // We'll use a separate list for module names that are definitely unknown. + result = new Array(moduleNames.length); + // copy all module names that appear before the current one in the list + // since they are known to be unknown + unknownModuleNames = moduleNames.slice(0, i); + } + // mark prediced resolution in the result list + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + // found unknown module name and we are already using separate list for those - add it to the list + unknownModuleNames.push(moduleName); + } + } + if (!unknownModuleNames) { + // we've looked throught the list but have not seen any predicted resolution + // use default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + // combine results of resolutions and predicted results + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState) { + return false; + } + var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + // module used to be resolved to file - ignore it + return false; + } + var ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + // at least one of declarations should come from non-modified source file + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } function tryReuseStructureFromOldProgram() { if (!oldProgram) { return false; @@ -57927,20 +62511,7 @@ var ts; // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + if (ts.changesAffectModuleResolution(oldOptions, options)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -57991,29 +62562,8 @@ var ts; // 'types' references has changed return false; } - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - // ensure that module resolution results are still correct - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - // ensure that types resolutions are still correct - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { // file has no changes - use it as is @@ -58022,15 +62572,42 @@ var ts; // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } + var modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + // try to verify results of module resolution + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var _c = modifiedSourceFiles_1[_b], oldSourceFile = _c.oldFile, newSourceFile = _c.newFile; + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths: modifiedFilePaths }); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + // pass the cache of module/types resolutions from the old source file + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } // update fileName -> file mapping for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { - var modifiedFile = modifiedSourceFiles_1[_b]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { + var modifiedFile = modifiedSourceFiles_2[_d]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -58046,24 +62623,30 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked + isEmitBlocked: isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file) { + return sourceFilesFoundSearchingNodeModules[file.path]; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +62678,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58135,7 +62718,15 @@ var ts; return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } } - function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } function runWithCancellationToken(func) { @@ -58164,179 +62755,180 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report semantic errors. + // Instead, we'll report errors for using TypeScript-only constructs from within a + // JavaScript file when we get syntactic diagnostics for the file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; + var parent = sourceFile; walk(sourceFile); return diagnostics; function walk(node) { - if (!node) { - return false; + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 144 /* Parameter */: + case 147 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // Pass through + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 223 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } } switch (node.kind) { - case 229 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 235 /* ExportAssignment */: + case 234 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 240 /* ExportAssignment */: if (node.isExportEquals) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; } break; - case 221 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 251 /* HeritageClause */: + case 255 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; + if (heritageClause.token === 107 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; } break; - case 222 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 225 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 223 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; + case 227 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 230 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 228 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 229 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 182 /* TypeAssertionExpression */: + var typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 226 /* ClassDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // pass through + case 205 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 205 /* VariableStatement */); } break; - case 200 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 218 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 174 /* CallExpression */: - case 175 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 142 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 145 /* PropertyDeclaration */: - var propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + case 147 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _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 (modifier.kind !== 114 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } - } - if (checkTypeAnnotation(node.type)) { - return true; + return; } break; - case 224 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 177 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* Decorator */: - if (!options.experimentalDecorators) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + case 144 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 128 /* ReadonlyKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: + break; + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 199 /* ExpressionWithTypeArguments */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 75 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // Fallthrough to report error + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + case 130 /* ReadonlyKeyword */: + case 123 /* DeclareKeyword */: + case 116 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 114 /* StaticKeyword */: + case 83 /* ExportKeyword */: + case 78 /* DefaultKeyword */: } } - return false; + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } @@ -58344,8 +62936,7 @@ var ts; return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - var writeFile = function () { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { @@ -58362,11 +62953,8 @@ var ts; ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName) { - return ts.getBaseFileName(fileName).indexOf(".") >= 0; - } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*isReference*/ true); + processSourceFile(ts.normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -58383,16 +62971,21 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + var isDtsFile = ts.isDeclarationFile(file); var imports; var moduleAugmentations; + var ambientModules; // If we are importing helpers, we need to add a synthetic reference to resolve the // helpers library. if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - var externalHelpersModuleReference = ts.createNode(9 /* StringLiteral */); + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createSynthesizedNode(9 /* StringLiteral */); externalHelpersModuleReference.text = ts.externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + var importDecl = ts.createSynthesizedNode(235 /* ImportDeclaration */); + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { @@ -58404,12 +62997,13 @@ var ts; } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 241 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -58424,7 +63018,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) { var moduleName = node.name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. @@ -58436,6 +63030,10 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(moduleName.text); + } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. @@ -58461,18 +63059,15 @@ var ts; } } } - /** - * 'isReference' indicates whether the file was brought in via a reference directive (rather than an import declaration) - */ - function processSourceFile(fileName, isDefaultLib, isReference, refFile, refPos, refEnd) { + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { var diagnosticArgument; var diagnostic; - if (hasExtension(fileName)) { + if (ts.hasExtension(fileName)) { if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -58482,13 +63077,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -58513,7 +63108,7 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, path, isDefaultLib, isReference, refFile, refPos, refEnd) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { if (filesByName.contains(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -58526,16 +63121,16 @@ var ts; if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); + processImportedModules(file_1); } } return file_1; @@ -58564,13 +63159,12 @@ var ts; } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - var basePath = ts.getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } // always process imported modules to record module name resolutions - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); } @@ -58580,10 +63174,10 @@ var ts; } return file; } - function processReferencedFiles(file, basePath, isDefaultLib) { + function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, /*isReference*/ true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -58609,22 +63203,25 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents // for sameness and possibly issue an error if (previousResolution) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } } // don't overwrite previous resolution result saveResolution = false; } else { // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } } } @@ -58650,34 +63247,43 @@ var ts; function getCanonicalFileName(fileName) { return host.getCanonicalFileName(fileName); } - function processImportedModules(file, basePath) { + function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = ts.createMap(); - var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); + var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name comes from the list of imports // - it's not a top level JavaScript module that exceeded the search max - var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); - if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; - } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, - /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -58688,12 +63294,11 @@ var ts; // no imports - drop cached module resolutions file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +63309,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +63353,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +63364,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,11 +63404,14 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (options.isolatedModules) { - if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58812,7 +63420,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); @@ -58846,14 +63454,22 @@ var ts; !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); - ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); @@ -58864,12 +63480,18 @@ var ts; var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + var chain_1; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error - createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -58877,12 +63499,40 @@ var ts; } } } - function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); } } ts.createProgram = createProgram; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ts.Extension.Ts: + case ts.Extension.Dts: + // These are always allowed. + return undefined; + case ts.Extension.Tsx: + return needJsx(); + case ts.Extension.Jsx: + return needJsx() || needAllowJs(); + case ts.Extension.Js: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; })(ts || (ts = {})); /// /// @@ -58891,27 +63541,30 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -58926,7 +63579,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -58936,15 +63589,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -58953,27 +63606,32 @@ var ts; "react": 2 /* React */ }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -58984,11 +63642,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -58997,12 +63655,12 @@ var ts; "lf": 1 /* LineFeed */ }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -59011,7 +63669,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -59020,60 +63678,60 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, // for correct behaviour, please use outFile - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -59096,30 +63754,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -59130,7 +63788,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -59144,23 +63802,26 @@ var ts; type: ts.createMap({ "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, - "es6": 2 /* ES6 */, - "es2015": 2 /* ES2015 */ + "es6": 2 /* ES2015 */, + "es2015": 2 /* ES2015 */, + "es2016": 3 /* ES2016 */, + "es2017": 4 /* ES2017 */, + "esnext": 5 /* ESNext */, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -59177,10 +63838,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -59309,8 +63970,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -59327,13 +63989,25 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -59357,10 +64031,24 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -59379,23 +64067,13 @@ var ts; ts.getOptionNameMap = getOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; /* @internal */ function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ @@ -59419,7 +64097,6 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - /* @internal */ function parseCommandLine(commandLine, readFile) { var options = {}; var fileNames = []; @@ -59461,7 +64138,13 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -59547,10 +64230,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59597,11 +64281,11 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_44 in options) { - if (ts.hasProperty(options, name_44)) { + for (var name_43 in options) { + if (ts.hasProperty(options, name_43)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean - switch (name_44) { + switch (name_43) { case "init": case "watch": case "version": @@ -59609,14 +64293,14 @@ var ts; case "project": break; default: - var value = options[name_44]; - var optionDefinition = optionsNameMap[name_44.toLowerCase()]; + var value = options[name_43]; + var optionDefinition = optionsNameMap[name_43.toLowerCase()]; if (optionDefinition) { var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result[name_44] = value; + result[name_43] = value; } else { if (optionDefinition.type === "list") { @@ -59625,11 +64309,11 @@ var ts; var element = _a[_i]; convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); } - result[name_44] = convertedValue; + result[name_43] = convertedValue; } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name_44] = getNameOfCompilerOptionValue(value, customTypeMap); + result[name_43] = getNameOfCompilerOptionValue(value, customTypeMap); } } } @@ -59672,9 +64356,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -59682,14 +64367,17 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -59712,18 +64400,20 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); @@ -59757,6 +64447,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -59784,8 +64477,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders and the outDir - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + // If no includes were specified, exclude common package folders and the outDir + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -59794,33 +64487,49 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -59955,7 +64664,7 @@ var ts; * @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) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { 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 @@ -59982,7 +64691,7 @@ var ts; 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); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (fileNames) { @@ -60051,6 +64760,7 @@ var ts; // // /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 + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler // // We watch a directory without recursion if it contains a wildcard in the file segment of // the pattern: @@ -60064,14 +64774,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_45 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_45)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_45); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_45) ? 1 /* Recursive */ : 0 /* None */; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -60093,6 +64802,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } /** * Determines whether a literal or wildcard file has already been included that has a higher * extension priority. @@ -60166,12 +64888,14 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; }; - StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + StringScriptSnapshot.prototype.getChangeRange = function () { // Text-based snapshots do not support incremental parsing. Return undefined // to signal that to the caller. return undefined; @@ -60196,12 +64920,13 @@ var ts; HighlightSpanKind.reference = "reference"; HighlightSpanKind.writtenReference = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + var IndentStyle; (function (IndentStyle) { IndentStyle[IndentStyle["None"] = 0] = "None"; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; - })(ts.IndentStyle || (ts.IndentStyle = {})); - var IndentStyle = ts.IndentStyle; + })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -60225,14 +64950,14 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; - })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); - var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; - })(ts.OutputFileType || (ts.OutputFileType = {})); - var OutputFileType = ts.OutputFileType; + })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {})); + var EndOfLineState; (function (EndOfLineState) { EndOfLineState[EndOfLineState["None"] = 0] = "None"; EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; @@ -60241,8 +64966,8 @@ var ts; EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; - })(ts.EndOfLineState || (ts.EndOfLineState = {})); - var EndOfLineState = ts.EndOfLineState; + })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {})); + var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -60253,8 +64978,7 @@ var ts; TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; - })(ts.TokenClass || (ts.TokenClass = {})); - var TokenClass = ts.TokenClass; + })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); // TODO: move these to enums var ScriptElementKind; (function (ScriptElementKind) { @@ -60361,6 +65085,7 @@ var ts; ClassificationTypeNames.jsxText = "jsx text"; ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; @@ -60386,52 +65111,51 @@ var ts; ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; - })(ts.ClassificationType || (ts.ClassificationType = {})); - var ClassificationType = ts.ClassificationType; + })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); // These utilities are common to multiple language service features. /* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); ts.emptyArray = []; + var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; - })(ts.SemanticMeaning || (ts.SemanticMeaning = {})); - var SemanticMeaning = ts.SemanticMeaning; + })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 142 /* Parameter */: - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 252 /* CatchClause */: + case 144 /* Parameter */: + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: + case 260 /* EnumMember */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 256 /* CatchClause */: return 1 /* Value */; - case 141 /* TypeParameter */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 159 /* TypeLiteral */: + case 143 /* TypeParameter */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 161 /* TypeLiteral */: return 2 /* Type */; - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -60441,22 +65165,22 @@ var ts; else { return 4 /* Namespace */; } - case 233 /* NamedImports */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 230 /* ImportDeclaration */: - case 235 /* ExportAssignment */: - case 236 /* ExportDeclaration */: + case 238 /* NamedImports */: + case 239 /* ImportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 235 /* ImportDeclaration */: + case 240 /* ExportAssignment */: + case 241 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 256 /* SourceFile */: + case 261 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.parent.kind === 235 /* ExportAssignment */) { + if (node.parent.kind === 240 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -60477,19 +65201,19 @@ var ts; } ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 69 /* Identifier */); + ts.Debug.assert(node.kind === 70 /* Identifier */); // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 139 /* QualifiedName */ && + if (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 229 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 234 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function isInRightSideOfImport(node) { - while (node.parent.kind === 139 /* QualifiedName */) { + while (node.parent.kind === 141 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -60500,27 +65224,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 139 /* QualifiedName */) { - while (root.parent && root.parent.kind === 139 /* QualifiedName */) { + if (root.parent.kind === 141 /* QualifiedName */) { + while (root.parent && root.parent.kind === 141 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 155 /* TypeReference */ && !isLastClause; + return root.parent.kind === 157 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 172 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 172 /* PropertyAccessExpression */) { + if (root.parent.kind === 177 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 177 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 194 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 251 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 199 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 255 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 221 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 222 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 226 /* ClassDeclaration */ && root.parent.parent.token === 107 /* ImplementsKeyword */) || + (decl.kind === 227 /* InterfaceDeclaration */ && root.parent.parent.token === 84 /* ExtendsKeyword */); } return false; } @@ -60528,17 +65252,17 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 155 /* TypeReference */ || - (node.parent.kind === 194 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 97 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || - node.kind === 165 /* ThisType */; + return node.parent.kind === 157 /* TypeReference */ || + (node.parent.kind === 199 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 98 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || + node.kind === 167 /* ThisType */; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 174 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 179 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 175 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 180 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -60551,7 +65275,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 214 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 219 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -60560,14 +65284,14 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 69 /* Identifier */ && - (node.parent.kind === 210 /* BreakStatement */ || node.parent.kind === 209 /* ContinueStatement */) && + return node.kind === 70 /* Identifier */ && + (node.parent.kind === 215 /* BreakStatement */ || node.parent.kind === 214 /* ContinueStatement */) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 69 /* Identifier */ && - node.parent.kind === 214 /* LabeledStatement */ && + return node.kind === 70 /* Identifier */ && + node.parent.kind === 219 /* LabeledStatement */ && node.parent.label === node; } function isLabelName(node) { @@ -60575,38 +65299,38 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 225 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 230 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 69 /* Identifier */ && + return node.kind === 70 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 253 /* PropertyAssignment */: - case 255 /* EnumMember */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 225 /* ModuleDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 257 /* PropertyAssignment */: + case 260 /* EnumMember */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 230 /* ModuleDeclaration */: return node.parent.name === node; - case 173 /* ElementAccessExpression */: + case 178 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 140 /* ComputedPropertyName */: + case 142 /* ComputedPropertyName */: return true; } } @@ -60655,17 +65379,17 @@ var ts; return undefined; } switch (node.kind) { - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: return node; } } @@ -60673,46 +65397,46 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* SourceFile */: return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: return ts.ScriptElementKind.moduleElement; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: return ts.ScriptElementKind.classElement; - case 222 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; - case 223 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; - case 224 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; - case 218 /* VariableDeclaration */: + case 227 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; + case 228 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; + case 229 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + case 223 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 169 /* BindingElement */: + case 174 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return ts.ScriptElementKind.functionElement; - case 149 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 151 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; + case 152 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: return ts.ScriptElementKind.memberFunctionElement; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return ts.ScriptElementKind.memberVariableElement; - case 153 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; - case 152 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; - case 151 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; - case 148 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; - case 141 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; - case 255 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; - case 142 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 231 /* ImportClause */: - case 238 /* ExportSpecifier */: - case 232 /* NamespaceImport */: + case 155 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; + case 154 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; + case 153 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; + case 150 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; + case 143 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; + case 260 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; + case 144 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + case 234 /* ImportEqualsDeclaration */: + case 239 /* ImportSpecifier */: + case 236 /* ImportClause */: + case 243 /* ExportSpecifier */: + case 237 /* NamespaceImport */: return ts.ScriptElementKind.alias; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return ts.ScriptElementKind.typeElement; default: return ts.ScriptElementKind.unknown; @@ -60727,7 +65451,7 @@ var ts; } ts.getNodeKind = getNodeKind; function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 171 /* LiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); if (type && type.flags & 32 /* StringLiteral */) { return type; @@ -60737,12 +65461,12 @@ var ts; ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode; function isThis(node) { switch (node.kind) { - case 97 /* ThisKeyword */: + case 98 /* ThisKeyword */: // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 69 /* Identifier */: + case 70 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 144 /* Parameter */; default: return false; } @@ -60787,42 +65511,42 @@ var ts; return false; } switch (n.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 167 /* ObjectBindingPattern */: - case 159 /* TypeLiteral */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 227 /* CaseBlock */: - case 233 /* NamedImports */: - case 237 /* NamedExports */: - return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 252 /* CatchClause */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 172 /* ObjectBindingPattern */: + case 161 /* TypeLiteral */: + case 204 /* Block */: + case 231 /* ModuleBlock */: + case 232 /* CaseBlock */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: + return nodeEndsWith(n, 17 /* CloseBraceToken */, sourceFile); + case 256 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 175 /* NewExpression */: + case 180 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 174 /* CallExpression */: - case 178 /* ParenthesizedExpression */: - case 164 /* ParenthesizedType */: - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 156 /* FunctionType */: - case 157 /* ConstructorType */: + case 179 /* CallExpression */: + case 183 /* ParenthesizedExpression */: + case 166 /* ParenthesizedType */: + return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile); + case 158 /* FunctionType */: + case 159 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 152 /* ConstructSignature */: - case 151 /* CallSignature */: - case 180 /* ArrowFunction */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 154 /* ConstructSignature */: + case 153 /* CallSignature */: + case 185 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -60831,68 +65555,68 @@ var ts; } // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. - return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 225 /* ModuleDeclaration */: + return hasChildOfKind(n, 19 /* CloseParenToken */, sourceFile); + case 230 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 203 /* IfStatement */: + case 208 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 23 /* SemicolonToken */); - case 170 /* ArrayLiteralExpression */: - case 168 /* ArrayBindingPattern */: - case 173 /* ElementAccessExpression */: - case 140 /* ComputedPropertyName */: - case 161 /* TupleType */: - return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 153 /* IndexSignature */: + hasChildOfKind(n, 24 /* SemicolonToken */); + case 175 /* ArrayLiteralExpression */: + case 173 /* ArrayBindingPattern */: + case 178 /* ElementAccessExpression */: + case 142 /* ComputedPropertyName */: + case 163 /* TupleType */: + return nodeEndsWith(n, 21 /* CloseBracketToken */, sourceFile); + case 155 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + return hasChildOfKind(n, 21 /* CloseBracketToken */, sourceFile); + case 253 /* CaseClause */: + case 254 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 210 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 204 /* DoStatement */: + case 209 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); + var hasWhileKeyword = findChildOfKind(n, 105 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { - return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 158 /* TypeQuery */: + case 160 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 182 /* TypeOfExpression */: - case 181 /* DeleteExpression */: - case 183 /* VoidExpression */: - case 190 /* YieldExpression */: - case 191 /* SpreadElementExpression */: + case 187 /* TypeOfExpression */: + case 186 /* DeleteExpression */: + case 188 /* VoidExpression */: + case 195 /* YieldExpression */: + case 196 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 176 /* TaggedTemplateExpression */: + case 181 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 189 /* TemplateExpression */: + case 194 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 197 /* TemplateSpan */: + case 202 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 236 /* ExportDeclaration */: - case 230 /* ImportDeclaration */: + case 241 /* ExportDeclaration */: + case 235 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 185 /* PrefixUnaryExpression */: + case 190 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 187 /* BinaryExpression */: + case 192 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 188 /* ConditionalExpression */: + case 193 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -60910,7 +65634,7 @@ var ts; if (last.kind === expectedLastToken) { return true; } - else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { + else if (last.kind === 24 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -60948,7 +65672,7 @@ var ts; // for the position of the relevant node (or comma). var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { // find syntax list that covers the span of the node - if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 292 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -61083,7 +65807,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -61091,7 +65815,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 244 /* JsxText */) { + if (isToken(n)) { return n; } var children = n.getChildren(); @@ -61105,10 +65829,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 244 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 244 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -61120,7 +65844,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 256 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 261 /* SourceFile */); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -61171,25 +65895,25 @@ var ts; if (!token) { return false; } - if (token.kind === 244 /* JsxText */) { + if (token.kind === 10 /* JsxText */) { return true; } //
Hello |
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 244 /* JsxText */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { return true; } //
{ |
or
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 248 /* JsxExpression */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 252 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 16 /* CloseBraceToken */ && token.parent.kind === 248 /* JsxExpression */) { + if (token && token.kind === 17 /* CloseBraceToken */ && token.parent.kind === 252 /* JsxExpression */) { return true; } //
|
- if (token.kind === 25 /* LessThanToken */ && token.parent.kind === 245 /* JsxClosingElement */) { + if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 249 /* JsxClosingElement */) { return true; } return false; @@ -61246,9 +65970,9 @@ var ts; var node = ts.getTokenAtPosition(sourceFile, position); if (isToken(node)) { switch (node.kind) { - case 102 /* VarKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: + case 103 /* VarKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: // if the current token is var, let or const, skip the VariableDeclarationList node = node.parent === undefined ? undefined : node.parent.parent; break; @@ -61258,11 +65982,11 @@ var ts; } } if (node) { - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - if (jsDocComment.tags) { - for (var _b = 0, _c = jsDocComment.tags; _b < _c.length; _b++) { + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (jsDoc.tags) { + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; if (tag.pos <= position && position <= tag.end) { return tag; @@ -61301,21 +66025,21 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 155 /* TypeReference */ || node.kind === 174 /* CallExpression */) { + if (node.kind === 157 /* TypeReference */ || node.kind === 179 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 221 /* ClassDeclaration */ || node.kind === 222 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 226 /* ClassDeclaration */ || node.kind === 227 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 138 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 140 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { - return kind === 69 /* Identifier */ || ts.isKeyword(kind); + return kind === 70 /* Identifier */ || ts.isKeyword(kind); } ts.isWord = isWord; function isPropertyName(kind) { @@ -61327,7 +66051,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ - || kind === 10 /* RegularExpressionLiteral */ + || kind === 11 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -61335,7 +66059,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; + return 16 /* FirstPunctuation */ <= kind && kind <= 69 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position) { @@ -61345,9 +66069,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: return true; } return false; @@ -61370,18 +66094,18 @@ var ts; } ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 170 /* ArrayLiteralExpression */ || - node.kind === 171 /* ObjectLiteralExpression */) { + if (node.kind === 175 /* ArrayLiteralExpression */ || + node.kind === 176 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 187 /* BinaryExpression */ && + if (node.parent.kind === 192 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 56 /* EqualsToken */) { + node.parent.operatorToken.kind === 57 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 208 /* ForOfStatement */ && + if (node.parent.kind === 213 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -61389,7 +66113,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 253 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 257 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -61420,10 +66144,9 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 144 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -61440,13 +66163,14 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, - trackSymbol: function () { }, - reportInaccessibleThisError: function () { } + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop }; function writeIndent() { if (lineStart) { @@ -61476,7 +66200,7 @@ var ts; } } function symbolPart(text, symbol) { - return displayPart(text, displayPartKind(symbol), symbol); + return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol) { var flags = symbol.flags; if (flags & 3 /* Variable */) { @@ -61525,7 +66249,7 @@ var ts; } } ts.symbolPart = symbolPart; - function displayPart(text, kind, symbol) { + function displayPart(text, kind) { return { text: text, kind: ts.SymbolDisplayPartKind[kind] @@ -61602,8 +66326,8 @@ var ts; if (isImportOrExportSpecifierName(location)) { return location.getText(); } - else if (ts.isStringOrNumericLiteral(location.kind) && - location.parent.kind === 140 /* ComputedPropertyName */) { + else if (ts.isStringOrNumericLiteral(location) && + location.parent.kind === 142 /* ComputedPropertyName */) { return location.text; } // Try to get the local symbol if we're dealing with an 'export default' @@ -61615,7 +66339,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 234 /* ImportSpecifier */ || location.parent.kind === 238 /* ExportSpecifier */) && + (location.parent.kind === 239 /* ImportSpecifier */ || location.parent.kind === 243 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -61657,11 +66381,11 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { - target: 2 /* ES6 */, + target: 2 /* ES2015 */, removeComments: true }, reportDiagnostics: true @@ -61671,37 +66395,40 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { /// Classifier function createClassifier() { - var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false); /// We do not have a full parser support to know when we should parse a regex or not /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. var noRegexTable = []; - noRegexTable[69 /* Identifier */] = true; + noRegexTable[70 /* Identifier */] = true; noRegexTable[9 /* StringLiteral */] = true; noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[10 /* RegularExpressionLiteral */] = true; - noRegexTable[97 /* ThisKeyword */] = true; - noRegexTable[41 /* PlusPlusToken */] = true; - noRegexTable[42 /* MinusMinusToken */] = true; - noRegexTable[18 /* CloseParenToken */] = true; - noRegexTable[20 /* CloseBracketToken */] = true; - noRegexTable[16 /* CloseBraceToken */] = true; - noRegexTable[99 /* TrueKeyword */] = true; - noRegexTable[84 /* FalseKeyword */] = true; + noRegexTable[11 /* RegularExpressionLiteral */] = true; + noRegexTable[98 /* ThisKeyword */] = true; + noRegexTable[42 /* PlusPlusToken */] = true; + noRegexTable[43 /* MinusMinusToken */] = true; + noRegexTable[19 /* CloseParenToken */] = true; + noRegexTable[21 /* CloseBracketToken */] = true; + noRegexTable[17 /* CloseBraceToken */] = true; + noRegexTable[100 /* TrueKeyword */] = true; + noRegexTable[85 /* FalseKeyword */] = true; // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) // classification on template strings. Because of the context free nature of templates, // the only precise way to classify a template portion would be by propagating the stack across @@ -61726,10 +66453,10 @@ var ts; /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 131 /* SetKeyword */ || - keyword2 === 121 /* ConstructorKeyword */ || - keyword2 === 113 /* StaticKeyword */) { + if (keyword2 === 124 /* GetKeyword */ || + keyword2 === 133 /* SetKeyword */ || + keyword2 === 122 /* ConstructorKeyword */ || + keyword2 === 114 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; @@ -61828,7 +66555,7 @@ var ts; offset = 2; // fallthrough case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(12 /* TemplateHead */); + templateStack.push(13 /* TemplateHead */); break; } scanner.setText(text); @@ -61859,71 +66586,71 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { - token = 10 /* RegularExpressionLiteral */; + if ((token === 40 /* SlashToken */ || token === 62 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 11 /* RegularExpressionLiteral */) { + token = 11 /* RegularExpressionLiteral */; } } - else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { - token = 69 /* Identifier */; + else if (lastNonTriviaToken === 22 /* DotToken */ && isKeyword(token)) { + token = 70 /* Identifier */; } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { // We have two keywords in a row. Only treat the second as a keyword if // it's a sequence that could legally occur in the language. Otherwise // treat it as an identifier. This way, if someone writes "private var" // we recognize that 'var' is actually an identifier here. - token = 69 /* Identifier */; + token = 70 /* Identifier */; } - else if (lastNonTriviaToken === 69 /* Identifier */ && - token === 25 /* LessThanToken */) { + else if (lastNonTriviaToken === 70 /* Identifier */ && + token === 26 /* LessThanToken */) { // Could be the start of something generic. Keep track of that by bumping // up the current count of generic contexts we may be in. angleBracketStack++; } - else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { + else if (token === 28 /* GreaterThanToken */ && angleBracketStack > 0) { // If we think we're currently in something generic, then mark that that // generic entity is complete. angleBracketStack--; } - else if (token === 117 /* AnyKeyword */ || - token === 132 /* StringKeyword */ || - token === 130 /* NumberKeyword */ || - token === 120 /* BooleanKeyword */ || - token === 133 /* SymbolKeyword */) { + else if (token === 118 /* AnyKeyword */ || + token === 134 /* StringKeyword */ || + token === 132 /* NumberKeyword */ || + token === 121 /* BooleanKeyword */ || + token === 135 /* SymbolKeyword */) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, // causing a noisy experience for the user. - token = 69 /* Identifier */; + token = 70 /* Identifier */; } } - else if (token === 12 /* TemplateHead */) { + else if (token === 13 /* TemplateHead */) { templateStack.push(token); } - else if (token === 15 /* OpenBraceToken */) { + else if (token === 16 /* OpenBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } } - else if (token === 16 /* CloseBraceToken */) { + else if (token === 17 /* CloseBraceToken */) { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 12 /* TemplateHead */) { + if (lastTemplateStackToken === 13 /* TemplateHead */) { token = scanner.reScanTemplateToken(); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. - if (token === 14 /* TemplateTail */) { + if (token === 15 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + ts.Debug.assert(token === 14 /* TemplateMiddle */, "Should have been a template middle. Was " + token); } } else { - ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + ts.Debug.assert(lastTemplateStackToken === 16 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); templateStack.pop(); } } @@ -61964,10 +66691,10 @@ var ts; } else if (ts.isTemplateLiteralKind(token)) { if (scanner.isUnterminated()) { - if (token === 14 /* TemplateTail */) { + if (token === 15 /* TemplateTail */) { result.endOfLineState = 5 /* InTemplateMiddleOrTail */; } - else if (token === 11 /* NoSubstitutionTemplateLiteral */) { + else if (token === 12 /* NoSubstitutionTemplateLiteral */) { result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; } else { @@ -61975,7 +66702,7 @@ var ts; } } } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 13 /* TemplateHead */) { result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; } } @@ -62005,43 +66732,43 @@ var ts; } function isBinaryExpressionOperatorToken(token) { switch (token) { - case 37 /* AsteriskToken */: - case 39 /* SlashToken */: - case 40 /* PercentToken */: - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 43 /* LessThanLessThanToken */: - case 44 /* GreaterThanGreaterThanToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 25 /* LessThanToken */: - case 27 /* GreaterThanToken */: - case 28 /* LessThanEqualsToken */: - case 29 /* GreaterThanEqualsToken */: - case 91 /* InstanceOfKeyword */: - case 90 /* InKeyword */: - case 116 /* AsKeyword */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 46 /* AmpersandToken */: - case 48 /* CaretToken */: - case 47 /* BarToken */: - case 51 /* AmpersandAmpersandToken */: - case 52 /* BarBarToken */: - case 67 /* BarEqualsToken */: - case 66 /* AmpersandEqualsToken */: - case 68 /* CaretEqualsToken */: - case 63 /* LessThanLessThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 57 /* PlusEqualsToken */: - case 58 /* MinusEqualsToken */: - case 59 /* AsteriskEqualsToken */: - case 61 /* SlashEqualsToken */: - case 62 /* PercentEqualsToken */: - case 56 /* EqualsToken */: - case 24 /* CommaToken */: + case 38 /* AsteriskToken */: + case 40 /* SlashToken */: + case 41 /* PercentToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 44 /* LessThanLessThanToken */: + case 45 /* GreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 26 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 29 /* LessThanEqualsToken */: + case 30 /* GreaterThanEqualsToken */: + case 92 /* InstanceOfKeyword */: + case 91 /* InKeyword */: + case 117 /* AsKeyword */: + case 31 /* EqualsEqualsToken */: + case 32 /* ExclamationEqualsToken */: + case 33 /* EqualsEqualsEqualsToken */: + case 34 /* ExclamationEqualsEqualsToken */: + case 47 /* AmpersandToken */: + case 49 /* CaretToken */: + case 48 /* BarToken */: + case 52 /* AmpersandAmpersandToken */: + case 53 /* BarBarToken */: + case 68 /* BarEqualsToken */: + case 67 /* AmpersandEqualsToken */: + case 69 /* CaretEqualsToken */: + case 64 /* LessThanLessThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 58 /* PlusEqualsToken */: + case 59 /* MinusEqualsToken */: + case 60 /* AsteriskEqualsToken */: + case 62 /* SlashEqualsToken */: + case 63 /* PercentEqualsToken */: + case 57 /* EqualsToken */: + case 25 /* CommaToken */: return true; default: return false; @@ -62049,19 +66776,19 @@ var ts; } function isPrefixUnaryExpressionOperatorToken(token) { switch (token) { - case 35 /* PlusToken */: - case 36 /* MinusToken */: - case 50 /* TildeToken */: - case 49 /* ExclamationToken */: - case 41 /* PlusPlusToken */: - case 42 /* MinusMinusToken */: + case 36 /* PlusToken */: + case 37 /* MinusToken */: + case 51 /* TildeToken */: + case 50 /* ExclamationToken */: + case 42 /* PlusPlusToken */: + case 43 /* MinusMinusToken */: return true; default: return false; } } function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 138 /* LastKeyword */; + return token >= 71 /* FirstKeyword */ && token <= 140 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -62070,7 +66797,7 @@ var ts; else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { return 5 /* operator */; } - else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { + else if (token >= 16 /* FirstPunctuation */ && token <= 69 /* LastPunctuation */) { return 10 /* punctuation */; } switch (token) { @@ -62078,7 +66805,7 @@ var ts; return 4 /* numericLiteral */; case 9 /* StringLiteral */: return 6 /* stringLiteral */; - case 10 /* RegularExpressionLiteral */: + case 11 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; case 7 /* ConflictMarkerTrivia */: case 3 /* MultiLineCommentTrivia */: @@ -62087,7 +66814,7 @@ var ts; case 5 /* WhitespaceTrivia */: case 4 /* NewLineTrivia */: return 8 /* whiteSpace */; - case 69 /* Identifier */: + case 70 /* Identifier */: default: if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; @@ -62118,10 +66845,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 225 /* ModuleDeclaration */: - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: + case 230 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -62172,7 +66899,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 225 /* ModuleDeclaration */ && + return declaration.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -62182,7 +66909,7 @@ var ts; if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { var kind = node.kind; checkForClassificationCancellation(cancellationToken, kind); - if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { + if (kind === 70 /* Identifier */ && !ts.nodeIsMissing(node)) { var identifier = node; // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run @@ -62251,8 +66978,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -62336,16 +67063,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 275 /* JSDocParameterTag */: + case 281 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 278 /* JSDocTemplateTag */: + case 284 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 277 /* JSDocTypeTag */: + case 283 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 276 /* JSDocReturnTag */: + case 282 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -62416,10 +67143,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -62432,22 +67159,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 243 /* JsxOpeningElement */: + case 248 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 245 /* JsxClosingElement */: + case 249 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 242 /* JsxSelfClosingElement */: + case 247 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 246 /* JsxAttribute */: + case 250 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -62464,7 +67191,7 @@ var ts; } // Special case < and > If they appear in a generic context they are punctuation, // not operators. - if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { + if (tokenKind === 26 /* LessThanToken */ || tokenKind === 28 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { @@ -62473,19 +67200,19 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { - if (tokenKind === 56 /* EqualsToken */) { + if (tokenKind === 57 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 218 /* VariableDeclaration */ || - token.parent.kind === 145 /* PropertyDeclaration */ || - token.parent.kind === 142 /* Parameter */ || - token.parent.kind === 246 /* JsxAttribute */) { + if (token.parent.kind === 223 /* VariableDeclaration */ || + token.parent.kind === 147 /* PropertyDeclaration */ || + token.parent.kind === 144 /* Parameter */ || + token.parent.kind === 250 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 187 /* BinaryExpression */ || - token.parent.kind === 185 /* PrefixUnaryExpression */ || - token.parent.kind === 186 /* PostfixUnaryExpression */ || - token.parent.kind === 188 /* ConditionalExpression */) { + if (token.parent.kind === 192 /* BinaryExpression */ || + token.parent.kind === 190 /* PrefixUnaryExpression */ || + token.parent.kind === 191 /* PostfixUnaryExpression */ || + token.parent.kind === 193 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -62495,9 +67222,9 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token.parent.kind === 250 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } - else if (tokenKind === 10 /* RegularExpressionLiteral */) { + else if (tokenKind === 11 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } @@ -62505,41 +67232,40 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } - else if (tokenKind === 244 /* JsxText */) { + else if (tokenKind === 10 /* JsxText */) { return 23 /* jsxText */; } - else if (tokenKind === 69 /* Identifier */) { + else if (tokenKind === 70 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 141 /* TypeParameter */: + case 143 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 142 /* Parameter */: + case 144 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62567,6 +67293,7 @@ var ts; } ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; })(ts || (ts = {})); +/// /* @internal */ var ts; (function (ts) { @@ -62583,20 +67310,20 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 245 /* JsxClosingElement */) { + location.parent && location.parent.kind === 249 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: @@ -62606,7 +67333,7 @@ var ts; name: tagName.text, kind: undefined, kindModifiers: undefined, - sortText: "0" + sortText: "0", }); } else { @@ -62619,18 +67346,18 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { + for (var name_44 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_46] === position) { + if (nameTable[name_44] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_44]) { + uniqueNames[name_44] = name_44; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_44), compilerOptions.target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -62663,7 +67390,7 @@ var ts; name: displayName, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - sortText: "0" + sortText: "0", }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { @@ -62690,7 +67417,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 257 /* PropertyAssignment */ && + node.parent.parent.kind === 176 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62714,7 +67443,7 @@ var ts; // a['/*completion position*/'] return getStringLiteralCompletionEntriesFromElementAccess(node.parent); } - else if (node.parent.kind === 230 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { + else if (node.parent.kind === 235 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // import x = require("/*completion position*/"); @@ -62727,7 +67456,7 @@ var ts; // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); } // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" @@ -62740,11 +67469,11 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, location) { + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { var candidates = []; var entries = []; typeChecker.getResolvedSignature(argumentInfo.invocation, candidates); @@ -62756,7 +67485,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +67495,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +67506,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62786,7 +67515,7 @@ var ts; if (!type) { return; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 65536 /* Union */) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { @@ -62819,6 +67548,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +67584,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +67609,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +67784,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +67804,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63084,7 +67836,7 @@ var ts; if (typeRoots) { for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); + getCompletionEntriesFromDirectories(host, root, span, result); } } } @@ -63093,12 +67845,12 @@ var ts; for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { var packageJson = _d[_c]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + getCompletionEntriesFromDirectories(host, typesDir, span, result); } } return result; } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { + function getCompletionEntriesFromDirectories(host, directory, span, result) { if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { @@ -63118,11 +67870,11 @@ var ts; if (currentConfigPath) { paths.push(currentConfigPath); currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_16 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_16) { + var parent_13 = ts.getDirectoryPath(currentDir); + if (currentDir === parent_13) { break; } - currentDir = parent_16; + currentDir = parent_13; } else { break; @@ -63203,14 +67955,14 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; + var symbols = completionData.symbols, location_3 = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -63238,12 +67990,12 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location; + var symbols = completionData.symbols, location_4 = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_4) === entryName ? s : undefined; }); } return undefined; } @@ -63274,9 +68026,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 277 /* JSDocTypeTag */: - case 275 /* JSDocParameterTag */: - case 276 /* JSDocReturnTag */: + case 283 /* JSDocTypeTag */: + case 281 /* JSDocParameterTag */: + case 282 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -63285,7 +68037,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63321,13 +68073,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_17 = contextToken.parent, kind = contextToken.kind; - if (kind === 21 /* DotToken */) { - if (parent_17.kind === 172 /* PropertyAccessExpression */) { + var parent_14 = contextToken.parent, kind = contextToken.kind; + if (kind === 22 /* DotToken */) { + if (parent_14.kind === 177 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_17.kind === 139 /* QualifiedName */) { + else if (parent_14.kind === 141 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -63338,17 +68090,18 @@ var ts; } } else if (sourceFile.languageVariant === 1 /* JSX */) { - if (kind === 25 /* LessThanToken */) { + if (kind === 26 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 245 /* JsxClosingElement */) { + else if (kind === 40 /* SlashToken */ && contextToken.parent.kind === 249 /* JsxClosingElement */) { isStartingCloseTag = true; location = contextToken; } } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63384,12 +68137,13 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { + if (node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -63417,7 +68171,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 524288 /* Union */) { + if (isJavaScriptFile && type.flags & 65536 /* Union */) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that // each individual type has. This is because we're going to add all identifiers @@ -63445,7 +68199,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 247 /* JsxSelfClosingElement */) || (jsxContainer.kind === 248 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -63491,6 +68245,13 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + if (scopeNode) { + isGlobalCompletion = + scopeNode.kind === 261 /* SourceFile */ || + scopeNode.kind === 194 /* TemplateExpression */ || + scopeNode.kind === 252 /* JsxExpression */ || + ts.isStatement(scopeNode); + } /// TODO filter meaning based on the current context var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -63517,15 +68278,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 244 /* JsxText */) { + if (contextToken.kind === 10 /* JsxText */) { return true; } - if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 243 /* JsxOpeningElement */) { + if (contextToken.kind === 28 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 248 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 245 /* JsxClosingElement */ || contextToken.parent.kind === 242 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 241 /* JsxElement */; + if (contextToken.parent.kind === 249 /* JsxClosingElement */ || contextToken.parent.kind === 247 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 246 /* JsxElement */; } } return false; @@ -63534,41 +68295,41 @@ var ts; if (previousToken) { var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 174 /* CallExpression */ // func( a, | - || containingNodeKind === 148 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 175 /* NewExpression */ // new C(a, | - || containingNodeKind === 170 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 187 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 156 /* FunctionType */; // var x: (s: string, list| - case 17 /* OpenParenToken */: - return containingNodeKind === 174 /* CallExpression */ // func( | - || containingNodeKind === 148 /* Constructor */ // constructor( | - || containingNodeKind === 175 /* NewExpression */ // new C(a| - || containingNodeKind === 178 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 164 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ - case 19 /* OpenBracketToken */: - return containingNodeKind === 170 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 153 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 140 /* ComputedPropertyName */; // [ | /* this can become an index signature */ - case 125 /* ModuleKeyword */: // module | - case 126 /* NamespaceKeyword */: + case 25 /* CommaToken */: + return containingNodeKind === 179 /* CallExpression */ // func( a, | + || containingNodeKind === 150 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 180 /* NewExpression */ // new C(a, | + || containingNodeKind === 175 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 192 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 158 /* FunctionType */; // var x: (s: string, list| + case 18 /* OpenParenToken */: + return containingNodeKind === 179 /* CallExpression */ // func( | + || containingNodeKind === 150 /* Constructor */ // constructor( | + || containingNodeKind === 180 /* NewExpression */ // new C(a| + || containingNodeKind === 183 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 166 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 20 /* OpenBracketToken */: + return containingNodeKind === 175 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 155 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 142 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 127 /* ModuleKeyword */: // module | + case 128 /* NamespaceKeyword */: return true; - case 21 /* DotToken */: - return containingNodeKind === 225 /* ModuleDeclaration */; // module A.| - case 15 /* OpenBraceToken */: - return containingNodeKind === 221 /* ClassDeclaration */; // class A{ | - case 56 /* EqualsToken */: - return containingNodeKind === 218 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 187 /* BinaryExpression */; // x = a| - case 12 /* TemplateHead */: - return containingNodeKind === 189 /* TemplateExpression */; // `aa ${| - case 13 /* TemplateMiddle */: - return containingNodeKind === 197 /* TemplateSpan */; // `aa ${10} dd ${| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; // class A{ public | + case 22 /* DotToken */: + return containingNodeKind === 230 /* ModuleDeclaration */; // module A.| + case 16 /* OpenBraceToken */: + return containingNodeKind === 226 /* ClassDeclaration */; // class A{ | + case 57 /* EqualsToken */: + return containingNodeKind === 223 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 192 /* BinaryExpression */; // x = a| + case 13 /* TemplateHead */: + return containingNodeKind === 194 /* TemplateExpression */; // `aa ${| + case 14 /* TemplateMiddle */: + return containingNodeKind === 202 /* TemplateSpan */; // `aa ${10} dd ${| + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + return containingNodeKind === 147 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -63582,7 +68343,7 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ - || contextToken.kind === 10 /* RegularExpressionLiteral */ + || contextToken.kind === 11 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); @@ -63595,7 +68356,7 @@ var ts; } if (position === end) { return !!contextToken.isUnterminated - || contextToken.kind === 10 /* RegularExpressionLiteral */; + || contextToken.kind === 11 /* RegularExpressionLiteral */; } } return false; @@ -63611,7 +68372,7 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 176 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; @@ -63621,7 +68382,7 @@ var ts; typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 172 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -63632,11 +68393,11 @@ var ts; // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { + if (!canGetType && rootDeclaration.kind === 144 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 149 /* MethodDeclaration */ || rootDeclaration.parent.kind === 152 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -63678,9 +68439,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 233 /* NamedImports */ ? - 230 /* ImportDeclaration */ : - 236 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 238 /* NamedImports */ ? + 235 /* ImportDeclaration */ : + 241 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -63703,11 +68464,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // const x = { | - case 24 /* CommaToken */: - var parent_18 = contextToken.parent; - if (parent_18 && (parent_18.kind === 171 /* ObjectLiteralExpression */ || parent_18.kind === 167 /* ObjectBindingPattern */)) { - return parent_18; + case 16 /* OpenBraceToken */: // const x = { | + case 25 /* CommaToken */: + var parent_15 = contextToken.parent; + if (parent_15 && (parent_15.kind === 176 /* ObjectLiteralExpression */ || parent_15.kind === 172 /* ObjectBindingPattern */)) { + return parent_15; } break; } @@ -63721,11 +68482,11 @@ var ts; function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // import { | - case 24 /* CommaToken */: + case 16 /* OpenBraceToken */: // import { | + case 25 /* CommaToken */: switch (contextToken.parent.kind) { - case 233 /* NamedImports */: - case 237 /* NamedExports */: + case 238 /* NamedImports */: + case 242 /* NamedExports */: return contextToken.parent; } } @@ -63734,37 +68495,37 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_19 = contextToken.parent; + var parent_16 = contextToken.parent; switch (contextToken.kind) { - case 26 /* LessThanSlashToken */: - case 39 /* SlashToken */: - case 69 /* Identifier */: - case 246 /* JsxAttribute */: - case 247 /* JsxSpreadAttribute */: - if (parent_19 && (parent_19.kind === 242 /* JsxSelfClosingElement */ || parent_19.kind === 243 /* JsxOpeningElement */)) { - return parent_19; + case 27 /* LessThanSlashToken */: + case 40 /* SlashToken */: + case 70 /* Identifier */: + case 250 /* JsxAttribute */: + case 251 /* JsxSpreadAttribute */: + if (parent_16 && (parent_16.kind === 247 /* JsxSelfClosingElement */ || parent_16.kind === 248 /* JsxOpeningElement */)) { + return parent_16; } - else if (parent_19.kind === 246 /* JsxAttribute */) { - return parent_19.parent; + else if (parent_16.kind === 250 /* JsxAttribute */) { + return parent_16.parent; } break; // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_19 && ((parent_19.kind === 246 /* JsxAttribute */) || (parent_19.kind === 247 /* JsxSpreadAttribute */))) { - return parent_19.parent; + if (parent_16 && ((parent_16.kind === 250 /* JsxAttribute */) || (parent_16.kind === 251 /* JsxSpreadAttribute */))) { + return parent_16.parent; } break; - case 16 /* CloseBraceToken */: - if (parent_19 && - parent_19.kind === 248 /* JsxExpression */ && - parent_19.parent && - (parent_19.parent.kind === 246 /* JsxAttribute */)) { - return parent_19.parent.parent; + case 17 /* CloseBraceToken */: + if (parent_16 && + parent_16.kind === 252 /* JsxExpression */ && + parent_16.parent && + (parent_16.parent.kind === 250 /* JsxAttribute */)) { + return parent_16.parent.parent; } - if (parent_19 && parent_19.kind === 247 /* JsxSpreadAttribute */) { - return parent_19.parent; + if (parent_16 && parent_16.kind === 251 /* JsxSpreadAttribute */) { + return parent_16.parent; } break; } @@ -63773,16 +68534,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 153 /* IndexSignature */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 155 /* IndexSignature */: return true; } return false; @@ -63793,67 +68554,67 @@ var ts; function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { - case 24 /* CommaToken */: - return containingNodeKind === 218 /* VariableDeclaration */ || - containingNodeKind === 219 /* VariableDeclarationList */ || - containingNodeKind === 200 /* VariableStatement */ || - containingNodeKind === 224 /* EnumDeclaration */ || + case 25 /* CommaToken */: + return containingNodeKind === 223 /* VariableDeclaration */ || + containingNodeKind === 224 /* VariableDeclarationList */ || + containingNodeKind === 205 /* VariableStatement */ || + containingNodeKind === 229 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 168 /* ArrayBindingPattern */ || - containingNodeKind === 223 /* TypeAliasDeclaration */; // type Map, K, | - case 21 /* DotToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [.| - case 54 /* ColonToken */: - return containingNodeKind === 169 /* BindingElement */; // var {x :html| - case 19 /* OpenBracketToken */: - return containingNodeKind === 168 /* ArrayBindingPattern */; // var [x| - case 17 /* OpenParenToken */: - return containingNodeKind === 252 /* CatchClause */ || + containingNodeKind === 226 /* ClassDeclaration */ || + containingNodeKind === 197 /* ClassExpression */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 173 /* ArrayBindingPattern */ || + containingNodeKind === 228 /* TypeAliasDeclaration */; // type Map, K, | + case 22 /* DotToken */: + return containingNodeKind === 173 /* ArrayBindingPattern */; // var [.| + case 55 /* ColonToken */: + return containingNodeKind === 174 /* BindingElement */; // var {x :html| + case 20 /* OpenBracketToken */: + return containingNodeKind === 173 /* ArrayBindingPattern */; // var [x| + case 18 /* OpenParenToken */: + return containingNodeKind === 256 /* CatchClause */ || isFunction(containingNodeKind); - case 15 /* OpenBraceToken */: - return containingNodeKind === 224 /* EnumDeclaration */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 159 /* TypeLiteral */; // const x : { | - case 23 /* SemicolonToken */: - return containingNodeKind === 144 /* PropertySignature */ && + case 16 /* OpenBraceToken */: + return containingNodeKind === 229 /* EnumDeclaration */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 161 /* TypeLiteral */; // const x : { | + case 24 /* SemicolonToken */: + return containingNodeKind === 146 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 222 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 159 /* TypeLiteral */); // const x : { a; | - case 25 /* LessThanToken */: - return containingNodeKind === 221 /* ClassDeclaration */ || - containingNodeKind === 192 /* ClassExpression */ || - containingNodeKind === 222 /* InterfaceDeclaration */ || - containingNodeKind === 223 /* TypeAliasDeclaration */ || + (contextToken.parent.parent.kind === 227 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 161 /* TypeLiteral */); // const x : { a; | + case 26 /* LessThanToken */: + return containingNodeKind === 226 /* ClassDeclaration */ || + containingNodeKind === 197 /* ClassExpression */ || + containingNodeKind === 227 /* InterfaceDeclaration */ || + containingNodeKind === 228 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); - case 113 /* StaticKeyword */: - return containingNodeKind === 145 /* PropertyDeclaration */; - case 22 /* DotDotDotToken */: - return containingNodeKind === 142 /* Parameter */ || + case 114 /* StaticKeyword */: + return containingNodeKind === 147 /* PropertyDeclaration */; + case 23 /* DotDotDotToken */: + return containingNodeKind === 144 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 168 /* ArrayBindingPattern */); // var [...z| - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - return containingNodeKind === 142 /* Parameter */; - case 116 /* AsKeyword */: - return containingNodeKind === 234 /* ImportSpecifier */ || - containingNodeKind === 238 /* ExportSpecifier */ || - containingNodeKind === 232 /* NamespaceImport */; - case 73 /* ClassKeyword */: - case 81 /* EnumKeyword */: - case 107 /* InterfaceKeyword */: - case 87 /* FunctionKeyword */: - case 102 /* VarKeyword */: - case 123 /* GetKeyword */: - case 131 /* SetKeyword */: - case 89 /* ImportKeyword */: - case 108 /* LetKeyword */: - case 74 /* ConstKeyword */: - case 114 /* YieldKeyword */: - case 134 /* TypeKeyword */: + contextToken.parent.parent.kind === 173 /* ArrayBindingPattern */); // var [...z| + case 113 /* PublicKeyword */: + case 111 /* PrivateKeyword */: + case 112 /* ProtectedKeyword */: + return containingNodeKind === 144 /* Parameter */; + case 117 /* AsKeyword */: + return containingNodeKind === 239 /* ImportSpecifier */ || + containingNodeKind === 243 /* ExportSpecifier */ || + containingNodeKind === 237 /* NamespaceImport */; + case 74 /* ClassKeyword */: + case 82 /* EnumKeyword */: + case 108 /* InterfaceKeyword */: + case 88 /* FunctionKeyword */: + case 103 /* VarKeyword */: + case 124 /* GetKeyword */: + case 133 /* SetKeyword */: + case 90 /* ImportKeyword */: + case 109 /* LetKeyword */: + case 75 /* ConstKeyword */: + case 115 /* YieldKeyword */: + case 136 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -63901,8 +68662,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_45 = element.propertyName || element.name; + existingImportsOrExports[name_45.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -63923,10 +68684,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 253 /* PropertyAssignment */ && - m.kind !== 254 /* ShorthandPropertyAssignment */ && - m.kind !== 169 /* BindingElement */ && - m.kind !== 147 /* MethodDeclaration */) { + if (m.kind !== 257 /* PropertyAssignment */ && + m.kind !== 258 /* ShorthandPropertyAssignment */ && + m.kind !== 174 /* BindingElement */ && + m.kind !== 149 /* MethodDeclaration */ && + m.kind !== 151 /* GetAccessor */ && + m.kind !== 152 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -63934,9 +68697,9 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 169 /* BindingElement */ && m.propertyName) { + if (m.kind === 174 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list - if (m.propertyName.kind === 69 /* Identifier */) { + if (m.propertyName.kind === 70 /* Identifier */) { existingName = m.propertyName.text; } } @@ -63964,7 +68727,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 246 /* JsxAttribute */) { + if (attr.kind === 250 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -64014,7 +68777,7 @@ var ts; } // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 138 /* LastKeyword */; i++) { + for (var i = 71 /* FirstKeyword */; i <= 140 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ts.ScriptElementKind.keyword, @@ -64026,9 +68789,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// = 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { + if (pushKeywordIf(keywords, loopTokens[i], 105 /* WhileKeyword */)) { break; } } @@ -64455,7 +69224,7 @@ var ts; var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */, 76 /* ContinueKeyword */); } }); return ts.map(keywords, getHighlightSpanForNode); @@ -64464,13 +69233,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 204 /* DoStatement */: - case 205 /* WhileStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 209 /* DoStatement */: + case 210 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -64478,14 +69247,14 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 97 /* SwitchKeyword */); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); + pushKeywordIf(keywords, clause.getFirstToken(), 72 /* CaseKeyword */, 78 /* DefaultKeyword */); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); + pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */); } }); }); @@ -64493,13 +69262,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 101 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 86 /* FinallyKeyword */); } return ts.map(keywords, getHighlightSpanForNode); } @@ -64510,13 +69279,13 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */); }); // If the "owner" is a function, then we equate 'return' and 'throw' statements in their // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */); }); } return ts.map(keywords, getHighlightSpanForNode); @@ -64524,36 +69293,36 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 199 /* Block */))) { + if (!(func && hasKind(func.body, 204 /* Block */))) { return undefined; } var keywords = []; ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */); }); // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */); }); return ts.map(keywords, getHighlightSpanForNode); } function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 203 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 208 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (ifStatement) { var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); + pushKeywordIf(keywords, children[0], 89 /* IfKeyword */); // Generally the 'else' keyword is second-to-last, so we traverse backwards. for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { + if (pushKeywordIf(keywords, children[i], 81 /* ElseKeyword */)) { break; } } - if (!hasKind(ifStatement.elseStatement, 203 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 208 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -64562,7 +69331,7 @@ var ts; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { + if (keywords[i].kind === 81 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. var shouldCombindElseAndIf = true; @@ -64596,7 +69365,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 214 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 219 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -64734,10 +69503,10 @@ var ts; break; } // Fallthrough - case 69 /* Identifier */: - case 97 /* ThisKeyword */: + case 70 /* Identifier */: + case 98 /* ThisKeyword */: // case SyntaxKind.SuperKeyword: TODO:GH#9268 - case 121 /* ConstructorKeyword */: + case 122 /* ConstructorKeyword */: case 9 /* StringLiteral */: return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, /*implementations*/ false); } @@ -64762,7 +69531,7 @@ var ts; if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } - if (node.kind === 95 /* SuperKeyword */) { + if (node.kind === 96 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } } @@ -64798,9 +69567,9 @@ var ts; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } else { - var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + var internedName = getInternedName(symbol, node); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = ts.getNameTable(sourceFile); if (nameTable[internedName] !== undefined) { @@ -64830,12 +69599,12 @@ var ts; function getAliasSymbolForPropertyNameSymbol(symbol, location) { if (symbol.flags & 8388608 /* Alias */) { // Default import get alias - var defaultImport = ts.getDeclarationOfKind(symbol, 231 /* ImportClause */); + var defaultImport = ts.getDeclarationOfKind(symbol, 236 /* ImportClause */); if (defaultImport) { return typeChecker.getAliasedSymbol(symbol); } - var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 234 /* ImportSpecifier */ || - declaration.kind === 238 /* ExportSpecifier */) ? declaration : undefined; }); + var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 239 /* ImportSpecifier */ || + declaration.kind === 243 /* ExportSpecifier */) ? declaration : undefined; }); if (importOrExportSpecifier && // export { a } (!importOrExportSpecifier.propertyName || @@ -64843,7 +69612,7 @@ var ts; importOrExportSpecifier.propertyName === location)) { // If Import specifier -> get alias // else Export specifier -> get local target - return importOrExportSpecifier.kind === 234 /* ImportSpecifier */ ? + return importOrExportSpecifier.kind === 239 /* ImportSpecifier */ ? typeChecker.getAliasedSymbol(symbol) : typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier); } @@ -64858,20 +69627,20 @@ var ts; typeChecker.getPropertySymbolOfDestructuringAssignment(location); } function isObjectBindingPatternElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */); return bindingElement && - bindingElement.parent.kind === 167 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 172 /* ObjectBindingPattern */ && !bindingElement.propertyName; } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) { if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 169 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */); var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } return undefined; } - function getInternedName(symbol, location, declarations) { + function getInternedName(symbol, location) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever under the cursor. if (ts.isImportOrExportSpecifierName(location)) { @@ -64895,14 +69664,14 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 184 /* FunctionExpression */ || valueDeclaration.kind === 197 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 226 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -64933,7 +69702,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -64964,8 +69733,8 @@ var ts; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } @@ -65005,7 +69774,7 @@ var ts; if (node) { // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: return node.getWidth() === searchSymbolName.length; case 9 /* StringLiteral */: if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || @@ -65069,14 +69838,14 @@ var ts; var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation, - /*searchLocationIsConstructor*/ searchLocation.kind === 121 /* ConstructorKeyword */, parents, inheritsFromCache); + /*searchLocationIsConstructor*/ searchLocation.kind === 122 /* ConstructorKeyword */, parents, inheritsFromCache); if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } - else if (searchLocation.kind === 121 /* ConstructorKeyword */) { + else if (searchLocation.kind === 122 /* ConstructorKeyword */) { findAdditionalConstructorReferences(referenceSymbol, referenceLocation); } } @@ -65097,7 +69866,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== searchSymbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 1572864 /* UnionOrIntersection */) { + else if (localParentType.flags & 196608 /* UnionOrIntersection */) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -65137,17 +69906,17 @@ var ts; var result = []; for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148 /* Constructor */); + ts.Debug.assert(decl.kind === 150 /* Constructor */); var ctrKeyword = decl.getChildAt(0); - ts.Debug.assert(ctrKeyword.kind === 121 /* ConstructorKeyword */); + ts.Debug.assert(ctrKeyword.kind === 122 /* ConstructorKeyword */); result.push(ctrKeyword); } ts.forEachProperty(classSymbol.exports, function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 147 /* MethodDeclaration */) { + if (decl && decl.kind === 149 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97 /* ThisKeyword */, function (thisKeyword) { + forEachDescendantOfKind(body, 98 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { result.push(thisKeyword); } @@ -65167,10 +69936,10 @@ var ts; var result = []; for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 148 /* Constructor */); + ts.Debug.assert(decl.kind === 150 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 95 /* SuperKeyword */, function (node) { + forEachDescendantOfKind(body, 96 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { result.push(node); } @@ -65208,8 +69977,8 @@ var ts; if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { result.push(getReferenceEntryFromNode(refNode.parent)); } - else if (refNode.kind === 69 /* Identifier */) { - if (refNode.parent.kind === 254 /* ShorthandPropertyAssignment */) { + else if (refNode.kind === 70 /* Identifier */) { + if (refNode.parent.kind === 258 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result); } @@ -65222,24 +69991,24 @@ var ts; // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference) { - var parent_21 = containingTypeReference.parent; - if (ts.isVariableLike(parent_21) && parent_21.type === containingTypeReference && parent_21.initializer && isImplementationExpression(parent_21.initializer)) { - maybeAdd(getReferenceEntryFromNode(parent_21.initializer)); + var parent_18 = containingTypeReference.parent; + if (ts.isVariableLike(parent_18) && parent_18.type === containingTypeReference && parent_18.initializer && isImplementationExpression(parent_18.initializer)) { + maybeAdd(getReferenceEntryFromNode(parent_18.initializer)); } - else if (ts.isFunctionLike(parent_21) && parent_21.type === containingTypeReference && parent_21.body) { - if (parent_21.body.kind === 199 /* Block */) { - ts.forEachReturnStatement(parent_21.body, function (returnStatement) { + else if (ts.isFunctionLike(parent_18) && parent_18.type === containingTypeReference && parent_18.body) { + if (parent_18.body.kind === 204 /* Block */) { + ts.forEachReturnStatement(parent_18.body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { maybeAdd(getReferenceEntryFromNode(returnStatement.expression)); } }); } - else if (isImplementationExpression(parent_21.body)) { - maybeAdd(getReferenceEntryFromNode(parent_21.body)); + else if (isImplementationExpression(parent_18.body)) { + maybeAdd(getReferenceEntryFromNode(parent_18.body)); } } - else if (ts.isAssertionExpression(parent_21) && isImplementationExpression(parent_21.expression)) { - maybeAdd(getReferenceEntryFromNode(parent_21.expression)); + else if (ts.isAssertionExpression(parent_18) && isImplementationExpression(parent_18.expression)) { + maybeAdd(getReferenceEntryFromNode(parent_18.expression)); } } } @@ -65261,7 +70030,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 1572864 /* UnionOrIntersection */) { + if (componentType.getFlags() & 196608 /* UnionOrIntersection */) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -65279,12 +70048,12 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 194 /* ExpressionWithTypeArguments */ - && node.parent.kind === 251 /* HeritageClause */ + if (node.kind === 199 /* ExpressionWithTypeArguments */ + && node.parent.kind === 255 /* HeritageClause */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 69 /* Identifier */ || node.kind === 172 /* PropertyAccessExpression */) { + else if (node.kind === 70 /* Identifier */ || node.kind === 177 /* PropertyAccessExpression */) { return getContainingClassIfInHeritageClause(node.parent); } } @@ -65295,14 +70064,14 @@ var ts; */ function isImplementationExpression(node) { // Unwrap parentheses - if (node.kind === 178 /* ParenthesizedExpression */) { + if (node.kind === 183 /* ParenthesizedExpression */) { return isImplementationExpression(node.expression); } - return node.kind === 180 /* ArrowFunction */ || - node.kind === 179 /* FunctionExpression */ || - node.kind === 171 /* ObjectLiteralExpression */ || - node.kind === 192 /* ClassExpression */ || - node.kind === 170 /* ArrayLiteralExpression */; + return node.kind === 185 /* ArrowFunction */ || + node.kind === 184 /* FunctionExpression */ || + node.kind === 176 /* ObjectLiteralExpression */ || + node.kind === 197 /* ClassExpression */ || + node.kind === 175 /* ArrayLiteralExpression */; } /** * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol @@ -65351,7 +70120,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { + else if (declaration.kind === 227 /* InterfaceDeclaration */) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -65379,13 +70148,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -65398,7 +70167,7 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 95 /* SuperKeyword */) { + if (!node || node.kind !== 96 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -65417,27 +70186,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 256 /* SourceFile */: + case 261 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -65446,7 +70215,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 256 /* SourceFile */) { + if (searchSpaceNode.kind === 261 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -65480,28 +70249,28 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 192 /* ClassExpression */: - case 221 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 226 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 256 /* SourceFile */: - if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { + case 261 /* SourceFile */: + if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -65516,8 +70285,8 @@ var ts; return undefined; } var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var sourceFile = sourceFiles_9[_i]; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd()); getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references); } @@ -65555,7 +70324,7 @@ var ts; // Search the property symbol // for ( { property: p2 } of elems) { } var containingObjectLiteralElement = getContainingObjectLiteralElement(location); - if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 254 /* ShorthandPropertyAssignment */) { + if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 258 /* ShorthandPropertyAssignment */) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location); if (propertySymbol) { result.push(propertySymbol); @@ -65603,7 +70372,7 @@ var ts; // we should include both parameter declaration symbol and property declaration symbol // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 142 /* Parameter */ && + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 144 /* Parameter */ && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); } @@ -65658,7 +70427,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 222 /* InterfaceDeclaration */) { + else if (declaration.kind === 227 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -65734,18 +70503,18 @@ var ts; return undefined; } } - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3, /*previousIterationSymbolsCache*/ ts.createMap()); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 140 /* ComputedPropertyName */) { + if (node.name.kind === 142 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } return undefined; @@ -65757,20 +70526,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_4 = []; + var result_5 = []; var symbol_2 = contextualType.getProperty(name); if (symbol_2) { - result_4.push(symbol_2); + result_5.push(symbol_2); } - if (contextualType.flags & 524288 /* Union */) { + if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); } - return result_4; + return result_5; } return undefined; } @@ -65824,7 +70593,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 218 /* VariableDeclaration */) { + else if (node.kind === 223 /* VariableDeclaration */) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } @@ -65834,18 +70603,18 @@ var ts; } else { switch (node.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 200 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 219 /* VariableDeclarationList */); + if (node.parent && node.parent.parent && node.parent.parent.kind === 205 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 224 /* VariableDeclarationList */); return node.parent.parent; } } @@ -65879,17 +70648,17 @@ var ts; FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode; /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node) { - if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { + if (node.kind === 70 /* Identifier */ && ts.isDeclarationName(node)) { return true; } var parent = node.parent; if (parent) { - if (parent.kind === 186 /* PostfixUnaryExpression */ || parent.kind === 185 /* PrefixUnaryExpression */) { + if (parent.kind === 191 /* PostfixUnaryExpression */ || parent.kind === 190 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 187 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 192 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; - return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; + return 57 /* FirstAssignment */ <= operator && operator <= 69 /* LastAssignment */; } } return false; @@ -65909,22 +70678,22 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 140 /* ComputedPropertyName */) { + if (node.parent.kind === 142 /* ComputedPropertyName */) { return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined; } // intential fall through - case 69 /* Identifier */: + case 70 /* Identifier */: return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined; } return undefined; } function isObjectLiteralPropertyDeclaration(node) { switch (node.kind) { - case 253 /* PropertyAssignment */: - case 254 /* ShorthandPropertyAssignment */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 257 /* PropertyAssignment */: + case 258 /* ShorthandPropertyAssignment */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: return true; } return false; @@ -65997,9 +70766,9 @@ var ts; // (1) when the aliased symbol was declared in the location(parent). // (2) when the aliased symbol is originating from a named import. // - if (node.kind === 69 /* Identifier */ && + if (node.kind === 70 /* Identifier */ && (node.parent === declaration || - (declaration.kind === 234 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 233 /* NamedImports */))) { + (declaration.kind === 239 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 238 /* NamedImports */))) { symbol = typeChecker.getAliasedSymbol(symbol); } } @@ -66008,7 +70777,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -66036,14 +70805,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_5 = []; + if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_5; + return result_6; } if (!type.symbol) { return undefined; @@ -66066,7 +70835,7 @@ var ts; function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 121 /* ConstructorKeyword */) { + if (ts.isNewExpressionTarget(location) || location.kind === 122 /* ConstructorKeyword */) { if (symbol.flags & 32 /* Class */) { // Find the first class-like declaration and try to get the construct signature. for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { @@ -66091,8 +70860,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 148 /* Constructor */) || - (!selectConstructors && (d.kind === 220 /* FunctionDeclaration */ || d.kind === 147 /* MethodDeclaration */ || d.kind === 146 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 150 /* Constructor */) || + (!selectConstructors && (d.kind === 225 /* FunctionDeclaration */ || d.kind === 149 /* MethodDeclaration */ || d.kind === 148 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -66172,12 +70941,12 @@ var ts; function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) { // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 254 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) { var result = []; ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); return result.length > 0 ? result : undefined; } - else if (node.kind === 95 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + else if (node.kind === 96 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no // need to "Find all References" var symbol = typeChecker.getSymbolAtLocation(node); @@ -66226,6 +70995,7 @@ var ts; "lends", "link", "memberOf", + "method", "name", "namespace", "param", @@ -66245,7 +71015,7 @@ var ts; "version" ]; var jsDocCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + function getJsDocCommentsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -66254,7 +71024,7 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getJSDocComments(declaration, /*checkParentVariableStatement*/ true); + var comments = ts.getCommentsFromJSDoc(declaration); if (!comments) { return; } @@ -66295,7 +71065,7 @@ var ts; name: tagName, kind: ts.ScriptElementKind.keyword, kindModifiers: "", - sortText: "0" + sortText: "0", }; })); } @@ -66338,19 +71108,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - case 221 /* ClassDeclaration */: - case 200 /* VariableStatement */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 150 /* Constructor */: + case 226 /* ClassDeclaration */: + case 205 /* VariableStatement */: break findOwner; - case 256 /* SourceFile */: + case 261 /* SourceFile */: return undefined; - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 225 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 230 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -66363,13 +71133,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; - var paramName = currentName.kind === 69 /* Identifier */ ? + var paramName = currentName.kind === 70 /* Identifier */ ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } // A doc comment consists of the following // * The opening comment line @@ -66391,7 +71167,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 200 /* VariableStatement */) { + if (commentOwner.kind === 205 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -66409,17 +71185,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 178 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 183 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return rightHandSide.parameters; - case 192 /* ClassExpression */: + case 197 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* Constructor */) { + if (member.kind === 150 /* Constructor */) { return member.parameters; } } @@ -66431,7 +71207,9 @@ var ts; })(ts || (ts = {})); // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. -/// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,35 +71220,49 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); + /* @internal */ + JsTyping.nodeCoreModuleList = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console" + ]; + var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project * @param projectRootPath is the path to the project root directory * @param safeListPath is the path used to retrieve the safe list * @param packageNameToTypingLocation is the map of package names to their cached typing locations - * @param typingOptions are used to customize the typing inference process + * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { // A typing name to typing file path mapping var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { + if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information var searchDirs = []; var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { + if (projectRootPath) { possibleSearchDirs.push(projectRootPath); } searchDirs = ts.deduplicate(possibleSearchDirs); @@ -66484,15 +71276,25 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { + var moduleId = unresolvedImports_1[_a]; + var typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } + } + } // Add the cached typing locations for inferred typings that are already installed - for (var name_48 in packageNameToTypingLocation) { - if (name_48 in inferredTypings && !inferredTypings[name_48]) { - inferredTypings[name_48] = packageNameToTypingLocation[name_48]; + for (var name_46 in packageNameToTypingLocation) { + if (name_46 in inferredTypings && !inferredTypings[name_46]) { + inferredTypings[name_46] = packageNameToTypingLocation[name_46]; } } // Remove typings that the user has added to the exclude list - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; + for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { + var excludeTypingName = exclude_1[_b]; delete inferredTypings[excludeTypingName]; } var newTypingNames = []; @@ -66524,10 +71326,12 @@ var ts; * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -66552,13 +71356,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +71374,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + 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); @@ -66616,21 +71417,22 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_49 in nameToDeclarations) { - var declarations = nameToDeclarations[name_49]; + for (var name_47 in nameToDeclarations) { + var declarations = nameToDeclarations[name_47]; 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_49); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_47); if (!matches) { continue; } @@ -66643,14 +71445,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_49); + matches = patternMatcher.getMatches(containers, name_47); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_49, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_47, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -66658,7 +71460,7 @@ var ts; // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; - if (decl.kind === 231 /* ImportClause */ || decl.kind === 234 /* ImportSpecifier */ || decl.kind === 229 /* ImportEqualsDeclaration */) { + if (decl.kind === 236 /* ImportClause */ || decl.kind === 239 /* ImportSpecifier */ || decl.kind === 234 /* ImportEqualsDeclaration */) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; @@ -66686,7 +71488,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { return node.text; @@ -66700,7 +71502,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 140 /* ComputedPropertyName */) { + else if (declaration.name.kind === 142 /* ComputedPropertyName */) { return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { @@ -66721,7 +71523,7 @@ var ts; } return true; } - if (expression.kind === 172 /* PropertyAccessExpression */) { + if (expression.kind === 177 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -66734,7 +71536,7 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 140 /* ComputedPropertyName */) { + if (declaration.name.kind === 142 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } @@ -66767,8 +71569,8 @@ var ts; // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -66803,6 +71605,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -66880,7 +71689,7 @@ var ts; return; } switch (node.kind) { - case 148 /* Constructor */: + case 150 /* 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); @@ -66892,21 +71701,21 @@ var ts; } } break; - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 146 /* MethodSignature */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 148 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 231 /* ImportClause */: + case 236 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -66918,7 +71727,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 232 /* NamespaceImport */) { + if (namedBindings.kind === 237 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -66929,12 +71738,12 @@ var ts; } } break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: + case 174 /* BindingElement */: + case 223 /* VariableDeclaration */: var decl = node; - var name_50 = decl.name; - if (ts.isBindingPattern(name_50)) { - addChildrenRecursively(name_50); + var name_48 = decl.name; + if (ts.isBindingPattern(name_48)) { + addChildrenRecursively(name_48); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -66944,12 +71753,12 @@ var ts; addNodeWithRecursiveChild(decl, decl.initializer); } break; - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: startNode(node); for (var _d = 0, _e = node.members; _d < _e.length; _d++) { var member = _e[_d]; @@ -66959,9 +71768,9 @@ var ts; } endNode(); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: startNode(node); for (var _f = 0, _g = node.members; _f < _g.length; _f++) { var member = _g[_f]; @@ -66969,21 +71778,21 @@ var ts; } endNode(); break; - case 225 /* ModuleDeclaration */: + case 230 /* 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 */: + case 243 /* ExportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 155 /* IndexSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 228 /* TypeAliasDeclaration */: addLeafNode(node); break; default: - ts.forEach(node.jsDocComments, function (jsDocComment) { - ts.forEach(jsDocComment.tags, function (tag) { - if (tag.kind === 279 /* JSDocTypedefTag */) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 285 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -67034,14 +71843,14 @@ var ts; }); /** 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)); + return a.kind === b.kind && (a.kind !== 230 /* 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; } - if (a.body.kind !== 225 /* ModuleDeclaration */) { + if (a.body.kind !== 230 /* ModuleDeclaration */) { return true; } return areSameModule(a.body, b.body); @@ -67076,11 +71885,9 @@ var ts; 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) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.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); @@ -67090,7 +71897,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -67103,7 +71910,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 225 /* ModuleDeclaration */) { + if (node.kind === 230 /* ModuleDeclaration */) { return getModuleName(node); } var decl = node; @@ -67111,18 +71918,18 @@ var ts; return ts.getPropertyNameForPropertyNameNode(decl.name); } switch (node.kind) { - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 197 /* ClassExpression */: return getFunctionOrClassName(node); - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 225 /* ModuleDeclaration */) { + if (node.kind === 230 /* ModuleDeclaration */) { return getModuleName(node); } var name = node.name; @@ -67133,29 +71940,32 @@ var ts; } } switch (node.kind) { - case 256 /* SourceFile */: + case 261 /* 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 */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. return getFunctionOrClassName(node); - case 148 /* Constructor */: + case 150 /* Constructor */: return "constructor"; - case 152 /* ConstructSignature */: + case 154 /* ConstructSignature */: return "new()"; - case 151 /* CallSignature */: + case 153 /* CallSignature */: return "()"; - case 153 /* IndexSignature */: + case 155 /* IndexSignature */: return "[]"; - case 279 /* JSDocTypedefTag */: + case 285 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -67167,10 +71977,10 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode && parentNode.kind === 205 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { + if (nameIdentifier.kind === 70 /* Identifier */) { return nameIdentifier.text; } } @@ -67196,24 +72006,24 @@ var ts; 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 */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 229 /* EnumDeclaration */: + case 227 /* InterfaceDeclaration */: + case 230 /* ModuleDeclaration */: + case 261 /* SourceFile */: + case 228 /* TypeAliasDeclaration */: + case 285 /* JSDocTypedefTag */: return true; - case 148 /* Constructor */: - case 147 /* MethodDeclaration */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 218 /* VariableDeclaration */: + case 150 /* Constructor */: + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 223 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 180 /* ArrowFunction */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -67223,10 +72033,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 226 /* ModuleBlock */: - case 256 /* SourceFile */: - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: + case 231 /* ModuleBlock */: + case 261 /* SourceFile */: + case 149 /* MethodDeclaration */: + case 150 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -67235,13 +72045,22 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + return childKind !== 223 /* VariableDeclaration */ && childKind !== 174 /* BindingElement */; }); } } } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +72084,16 @@ var ts; grayed: false }; } - 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)); - } + } + 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 spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -67284,7 +72103,7 @@ var ts; // 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 */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -67295,13 +72114,13 @@ var ts; * 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; + return decl.body.kind === 230 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + return !member.name || member.name.kind === 142 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ + return node.kind === 261 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); } @@ -67309,14 +72128,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 218 /* VariableDeclaration */) { + else if (node.parent.kind === 223 /* 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 === 192 /* BinaryExpression */ && + node.parent.operatorToken.kind === 57 /* EqualsToken */) { + return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 257 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512 /* Default */) { @@ -67327,8 +72146,22 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */ || node.kind === 197 /* ClassExpression */; } + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + var whiteSpaceRegex = /\s+/g; })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -67403,7 +72236,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 180 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 185 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -67415,34 +72248,34 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 199 /* Block */: + case 204 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_22 = n.parent; - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + var parent_19 = n.parent; + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. - if (parent_22.kind === 204 /* DoStatement */ || - parent_22.kind === 207 /* ForInStatement */ || - parent_22.kind === 208 /* ForOfStatement */ || - parent_22.kind === 206 /* ForStatement */ || - parent_22.kind === 203 /* IfStatement */ || - parent_22.kind === 205 /* WhileStatement */ || - parent_22.kind === 212 /* WithStatement */ || - parent_22.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + if (parent_19.kind === 209 /* DoStatement */ || + parent_19.kind === 212 /* ForInStatement */ || + parent_19.kind === 213 /* ForOfStatement */ || + parent_19.kind === 211 /* ForStatement */ || + parent_19.kind === 208 /* IfStatement */ || + parent_19.kind === 210 /* WhileStatement */ || + parent_19.kind === 217 /* WithStatement */ || + parent_19.kind === 256 /* CatchClause */) { + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_22.kind === 216 /* TryStatement */) { + if (parent_19.kind === 221 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_22; + var tryStatement = parent_19; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_22, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile); if (finallyKeyword) { addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); break; @@ -67461,25 +72294,25 @@ var ts; break; } // Fallthrough. - case 226 /* ModuleBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + case 231 /* ModuleBlock */: { + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 171 /* ObjectLiteralExpression */: - case 227 /* CaseBlock */: { - var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 176 /* ObjectLiteralExpression */: + case 232 /* CaseBlock */: { + var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 170 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + case 175 /* ArrayLiteralExpression */: + var openBracket = ts.findChildOfKind(n, 20 /* OpenBracketToken */, sourceFile); + var closeBracket = ts.findChildOfKind(n, 21 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); break; } @@ -67497,13 +72330,13 @@ var ts; var ts; (function (ts) { // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + var PatternMatchKind; (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; - })(ts.PatternMatchKind || (ts.PatternMatchKind = {})); - var PatternMatchKind = ts.PatternMatchKind; + })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { return { kind: kind, @@ -67834,7 +72667,7 @@ var ts; if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -67847,7 +72680,7 @@ var ts; if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -68068,10 +72901,10 @@ var ts; var externalModule = false; function nextToken() { var token = ts.scanner.scan(); - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { braceNesting++; } - else if (token === 16 /* CloseBraceToken */) { + else if (token === 17 /* CloseBraceToken */) { braceNesting--; } return token; @@ -68122,10 +72955,10 @@ var ts; */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 122 /* DeclareKeyword */) { + if (token === 123 /* DeclareKeyword */) { // declare module "mod" token = nextToken(); - if (token === 125 /* ModuleKeyword */) { + if (token === 127 /* ModuleKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { recordAmbientExternalModule(); @@ -68140,7 +72973,7 @@ var ts; */ function tryConsumeImport() { var token = ts.scanner.getToken(); - if (token === 89 /* ImportKeyword */) { + if (token === 90 /* ImportKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import "mod"; @@ -68148,9 +72981,9 @@ var ts; return true; } else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -68158,12 +72991,12 @@ var ts; return true; } } - else if (token === 56 /* EqualsToken */) { + else if (token === 57 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 24 /* CommaToken */) { + else if (token === 25 /* CommaToken */) { // consume comma and keep going token = nextToken(); } @@ -68172,16 +73005,16 @@ var ts; return true; } } - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure that it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 17 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 16 /* CloseBraceToken */) { + if (token === 17 /* CloseBraceToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -68191,13 +73024,13 @@ var ts; } } } - else if (token === 37 /* AsteriskToken */) { + else if (token === 38 /* AsteriskToken */) { token = nextToken(); - if (token === 116 /* AsKeyword */) { + if (token === 117 /* AsKeyword */) { token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -68215,19 +73048,19 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 82 /* ExportKeyword */) { + if (token === 83 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 15 /* OpenBraceToken */) { + if (token === 16 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses // make sure it stops on EOF - while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 17 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 16 /* CloseBraceToken */) { + if (token === 17 /* CloseBraceToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -68237,9 +73070,9 @@ var ts; } } } - else if (token === 37 /* AsteriskToken */) { + else if (token === 38 /* AsteriskToken */) { token = nextToken(); - if (token === 136 /* FromKeyword */) { + if (token === 138 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -68247,11 +73080,11 @@ var ts; } } } - else if (token === 89 /* ImportKeyword */) { + else if (token === 90 /* ImportKeyword */) { token = nextToken(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + if (token === 70 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 56 /* EqualsToken */) { + if (token === 57 /* EqualsToken */) { if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } @@ -68264,9 +73097,9 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 129 /* RequireKeyword */) { + if (token === 131 /* RequireKeyword */) { token = nextToken(); - if (token === 17 /* OpenParenToken */) { + if (token === 18 /* OpenParenToken */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // require("mod"); @@ -68279,16 +73112,16 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 69 /* Identifier */ && ts.scanner.getTokenValue() === "define") { + if (token === 70 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 17 /* OpenParenToken */) { + if (token !== 18 /* OpenParenToken */) { return true; } token = nextToken(); if (token === 9 /* StringLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 24 /* CommaToken */) { + if (token === 25 /* CommaToken */) { token = nextToken(); } else { @@ -68297,14 +73130,14 @@ var ts; } } // should be start of dependency list - if (token !== 19 /* OpenBracketToken */) { + if (token !== 20 /* OpenBracketToken */) { return true; } // skip open bracket token = nextToken(); var i = 0; // scan until ']' or EOF - while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + while (token !== 21 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names if (token === 9 /* StringLiteral */) { recordModuleName(); @@ -68394,7 +73227,7 @@ var ts; var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || ts.isThis(node)) { @@ -68619,12 +73452,12 @@ var ts; // return null; // } var emptyArray = []; + var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - })(SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); - var ArgumentListKind = SignatureHelp.ArgumentListKind; + })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help @@ -68655,15 +73488,15 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 174 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 179 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. var callExpression = argumentInfo.invocation; var expression = callExpression.expression; - var name = expression.kind === 69 /* Identifier */ + var name = expression.kind === 70 /* Identifier */ ? expression - : expression.kind === 172 /* PropertyAccessExpression */ + : expression.kind === 177 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -68696,7 +73529,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (node.parent.kind === 174 /* CallExpression */ || node.parent.kind === 175 /* NewExpression */) { + if (node.parent.kind === 179 /* CallExpression */ || node.parent.kind === 180 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -68712,8 +73545,8 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give sig help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 25 /* LessThanToken */ || - node.kind === 17 /* OpenParenToken */) { + if (node.kind === 26 /* LessThanToken */ || + node.kind === 18 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); @@ -68750,27 +73583,27 @@ var ts; } return undefined; } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 181 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.kind === 13 /* TemplateHead */ && node.parent.parent.kind === 181 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 197 /* TemplateSpan */ && node.parent.parent.parent.kind === 176 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 202 /* TemplateSpan */ && node.parent.parent.parent.kind === 181 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 189 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. - if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { + if (node.kind === 15 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); @@ -68798,7 +73631,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 24 /* CommaToken */) { + if (child.kind !== 25 /* CommaToken */) { argumentIndex++; } } @@ -68817,8 +73650,8 @@ var ts; // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 24 /* CommaToken */; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 24 /* CommaToken */) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 25 /* CommaToken */; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 25 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -68848,7 +73681,7 @@ var ts; } function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. - var argumentCount = tagExpression.template.kind === 11 /* NoSubstitutionTemplateLiteral */ + var argumentCount = tagExpression.template.kind === 12 /* NoSubstitutionTemplateLiteral */ ? 1 : tagExpression.template.templateSpans.length + 1; ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); @@ -68886,7 +73719,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 189 /* TemplateExpression */) { + if (template.kind === 194 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -68895,7 +73728,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 256 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 261 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -68955,35 +73788,38 @@ var ts; if (callTargetDisplayParts) { ts.addRange(prefixDisplayParts, callTargetDisplayParts); } + var isVariadic; if (isTypeParameterList) { - prefixDisplayParts.push(ts.punctuationPart(25 /* LessThanToken */)); + isVariadic = false; // type parameter lists are not variadic + prefixDisplayParts.push(ts.punctuationPart(26 /* LessThanToken */)); var typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(27 /* GreaterThanToken */)); + suffixDisplayParts.push(ts.punctuationPart(28 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); }); ts.addRange(suffixDisplayParts, parameterParts); } else { + isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); }); ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + prefixDisplayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); var parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; - suffixDisplayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + suffixDisplayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); }); ts.addRange(suffixDisplayParts, returnTypeParts); return { - isVariadic: candidateSignature.hasRestParameter, + isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(24 /* CommaToken */), ts.spacePart()], + separatorDisplayParts: [ts.punctuationPart(25 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, documentation: candidateSignature.getDocumentationComment() }; @@ -69037,7 +73873,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */) ? ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ts.ScriptElementKind.enumElement; @@ -69068,7 +73904,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return ts.ScriptElementKind.localVariableElement; } - if (location.kind === 97 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 98 /* ThisKeyword */ && ts.isExpression(location)) { return ts.ScriptElementKind.parameterElement; } if (flags & 3 /* Variable */) { @@ -69132,7 +73968,7 @@ var ts; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; - var isThisExpression = location.kind === 97 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 98 /* ThisKeyword */ && ts.isExpression(location); var type; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { @@ -69143,7 +73979,7 @@ var ts; var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 172 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 177 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -69152,7 +73988,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression = void 0; - if (location.kind === 174 /* CallExpression */ || location.kind === 175 /* NewExpression */) { + if (location.kind === 179 /* CallExpression */ || location.kind === 180 /* NewExpression */) { callExpression = location; } else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) { @@ -69165,7 +74001,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 175 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 180 /* NewExpression */ || callExpression.expression.kind === 96 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -69183,7 +74019,7 @@ var ts; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -69199,13 +74035,13 @@ var ts; case ts.ScriptElementKind.parameterElement: case ts.ScriptElementKind.localVariableElement: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.punctuationPart(55 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); @@ -69218,24 +74054,24 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 148 /* Constructor */)) { + (location.kind === 122 /* ConstructorKeyword */ && location.parent.kind === 150 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 148 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration.kind === 150 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 148 /* Constructor */) { + if (functionDeclaration.kind === 150 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ts.ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 151 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 153 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -69244,7 +74080,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 192 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -69252,7 +74088,7 @@ var ts; } else { // Class declaration has name which is not local. - displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); + displayParts.push(ts.keywordPart(74 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -69260,77 +74096,77 @@ var ts; } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); + displayParts.push(ts.keywordPart(108 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(136 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); + displayParts.push(ts.keywordPart(75 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); + displayParts.push(ts.keywordPart(82 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 225 /* ModuleDeclaration */); - var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 230 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 70 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 128 /* NamespaceKeyword */ : 127 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(90 /* InKeyword */)); - displayParts.push(ts.spacePart()); if (symbol.parent) { // Class/Interface type parameter + addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { // Method/function type parameter - var declaration = ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */); + var declaration = ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */); ts.Debug.assert(declaration !== undefined); declaration = declaration.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { + addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 152 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + if (declaration.kind === 154 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(93 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 151 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 153 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else { + else if (declaration.kind === 228 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path - displayParts.push(ts.keywordPart(134 /* TypeKeyword */)); + addInPrefix(); + displayParts.push(ts.keywordPart(136 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -69341,11 +74177,11 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 255 /* EnumMember */) { + if (declaration.kind === 260 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(constantValue.toString(), ts.SymbolDisplayPartKind.numericLiteral)); } @@ -69353,33 +74189,33 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); + if (symbol.declarations[0].kind === 233 /* NamespaceExportDeclaration */) { + displayParts.push(ts.keywordPart(83 /* ExportKeyword */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); + displayParts.push(ts.keywordPart(128 /* NamespaceKeyword */)); } else { - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + displayParts.push(ts.keywordPart(90 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 229 /* ImportEqualsDeclaration */) { + if (declaration.kind === 234 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* RequireKeyword */)); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.keywordPart(131 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.operatorPart(57 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -69393,7 +74229,7 @@ var ts; if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(97 /* ThisKeyword */)); + displayParts.push(ts.keywordPart(98 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); @@ -69403,7 +74239,7 @@ var ts; symbolFlags & 3 /* Variable */ || symbolKind === ts.ScriptElementKind.localVariableElement || isThisExpression) { - displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.punctuationPart(55 /* ColonToken */)); displayParts.push(ts.spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { @@ -69437,10 +74273,10 @@ var ts; // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 192 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -69461,6 +74297,11 @@ var ts; displayParts.push(ts.lineBreakPart()); } } + function addInPrefix() { + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(91 /* InKeyword */)); + displayParts.push(ts.spacePart()); + } function addFullSymbolName(symbol, enclosingDeclaration) { var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); @@ -69483,9 +74324,9 @@ var ts; displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); return; } } @@ -69493,12 +74334,12 @@ var ts; ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); - displayParts.push(ts.operatorPart(35 /* PlusToken */)); + displayParts.push(ts.punctuationPart(18 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(36 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } documentation = signature.getDocumentationComment(); } @@ -69516,16 +74357,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 179 /* FunctionExpression */) { + if (declaration.kind === 184 /* FunctionExpression */) { return true; } - if (declaration.kind !== 218 /* VariableDeclaration */ && declaration.kind !== 220 /* FunctionDeclaration */) { + if (declaration.kind !== 223 /* VariableDeclaration */ && declaration.kind !== 225 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_23 = declaration.parent; !ts.isFunctionBlock(parent_23); parent_23 = parent_23.parent) { + for (var parent_20 = declaration.parent; !ts.isFunctionBlock(parent_20); parent_20 = parent_20.parent) { // Reached source file or module block - if (parent_23.kind === 256 /* SourceFile */ || parent_23.kind === 226 /* ModuleBlock */) { + if (parent_20.kind === 261 /* SourceFile */ || parent_20.kind === 231 /* ModuleBlock */) { return false; } } @@ -69586,8 +74427,8 @@ var ts; var sourceMapText; // Create a compilerHost object to allow the compiler to read and write files var compilerHost = { - getSourceFile: function (fileName, target) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, - writeFile: function (name, text, writeByteOrderMark) { + getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text) { if (ts.fileExtensionIs(name, ".map")) { ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); sourceMapText = text; @@ -69603,9 +74444,9 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; }, - getDirectories: function (path) { return []; } + readFile: function () { return ""; }, + directoryExists: function () { return true; }, + getDirectories: function () { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -69636,7 +74477,7 @@ var ts; return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_2 = function (opt) { + var _loop_3 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -69655,7 +74496,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_2(opt); + _loop_3(opt); } return options; } @@ -69667,8 +74508,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); - var jsxScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); /** * Scanner that is currently used for formatting */ @@ -69683,7 +74524,7 @@ var ts; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { - ts.Debug.assert(scanner === undefined); + ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; scanner.setText(sourceFile.text); scanner.setTextPos(startPos); @@ -69708,7 +74549,7 @@ var ts; } }; function advance() { - ts.Debug.assert(scanner !== undefined); + ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { @@ -69750,11 +74591,11 @@ var ts; function shouldRescanGreaterThanToken(node) { if (node) { switch (node.kind) { - case 29 /* GreaterThanEqualsToken */: - case 64 /* GreaterThanGreaterThanEqualsToken */: - case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 45 /* GreaterThanGreaterThanGreaterThanToken */: - case 44 /* GreaterThanGreaterThanToken */: + case 30 /* GreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 46 /* GreaterThanGreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanToken */: return true; } } @@ -69763,27 +74604,27 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 246 /* JsxAttribute */: - case 243 /* JsxOpeningElement */: - case 245 /* JsxClosingElement */: - case 242 /* JsxSelfClosingElement */: - return node.kind === 69 /* Identifier */; + case 250 /* JsxAttribute */: + case 248 /* JsxOpeningElement */: + case 249 /* JsxClosingElement */: + case 247 /* JsxSelfClosingElement */: + return node.kind === 70 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 244 /* JsxText */; + return node && node.kind === 10 /* JsxText */; } function shouldRescanSlashToken(container) { - return container.kind === 10 /* RegularExpressionLiteral */; + return container.kind === 11 /* RegularExpressionLiteral */; } function shouldRescanTemplateToken(container) { - return container.kind === 13 /* TemplateMiddle */ || - container.kind === 14 /* TemplateTail */; + return container.kind === 14 /* TemplateMiddle */ || + container.kind === 15 /* TemplateTail */; } function startsWithSlashToken(t) { - return t === 39 /* SlashToken */ || t === 61 /* SlashEqualsToken */; + return t === 40 /* SlashToken */ || t === 62 /* SlashEqualsToken */; } function readTokenInfo(n) { ts.Debug.assert(scanner !== undefined); @@ -69824,7 +74665,7 @@ var ts; scanner.scan(); } var currentToken = scanner.getToken(); - if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 27 /* GreaterThanToken */) { + if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 28 /* GreaterThanToken */) { currentToken = scanner.reScanGreaterToken(); ts.Debug.assert(n.kind === currentToken); lastScanAction = 1 /* RescanGreaterThanToken */; @@ -69834,11 +74675,11 @@ var ts; ts.Debug.assert(n.kind === currentToken); lastScanAction = 2 /* RescanSlashToken */; } - else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 16 /* CloseBraceToken */) { + else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 17 /* CloseBraceToken */) { currentToken = scanner.reScanTemplateToken(); lastScanAction = 3 /* RescanTemplateToken */; } - else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 69 /* Identifier */) { + else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 70 /* Identifier */) { currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } @@ -69981,8 +74822,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 15 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 16 /* CloseBraceToken */, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 16 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 17 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -70001,14 +74842,14 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var FormattingRequestKind; (function (FormattingRequestKind) { FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; - })(formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - var FormattingRequestKind = formatting.FormattingRequestKind; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70040,13 +74881,13 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; RuleAction[RuleAction["Space"] = 2] = "Space"; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; - })(formatting.RuleAction || (formatting.RuleAction = {})); - var RuleAction = formatting.RuleAction; + })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70087,11 +74928,11 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; - })(formatting.RuleFlags || (formatting.RuleFlags = {})); - var RuleFlags = formatting.RuleFlags; + })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// @@ -70130,7 +74971,7 @@ var ts; function RuleOperationContext() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i - 0] = arguments[_i]; + funcs[_i] = arguments[_i]; } this.customContextChecks = funcs; } @@ -70170,125 +75011,125 @@ var ts; this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 3 /* MultiLineCommentTrivia */, 73 /* ClassKeyword */, 82 /* ExportKeyword */, 89 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([70 /* Identifier */, 3 /* MultiLineCommentTrivia */, 74 /* ClassKeyword */, 83 /* ExportKeyword */, 90 /* ImportKeyword */]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a control flow construct - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 79 /* DoKeyword */, 100 /* TryKeyword */, 85 /* FinallyKeyword */, 80 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 80 /* DoKeyword */, 101 /* TryKeyword */, 86 /* FinallyKeyword */, 81 /* ElseKeyword */]); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* OpenBraceToken */, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // For functions and control block place } on a new line [multi-line rule] - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 42 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 43 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* PlusPlusToken */, 36 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* PlusToken */, 36 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* PlusToken */, 42 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(43 /* MinusMinusToken */, 37 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* MinusToken */, 37 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* MinusToken */, 43 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([103 /* VarKeyword */, 99 /* ThrowKeyword */, 93 /* NewKeyword */, 79 /* DeleteKeyword */, 95 /* ReturnKeyword */, 102 /* TypeOfKeyword */, 120 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([109 /* LetKeyword */, 75 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); + this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(88 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(104 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(95 /* ReturnKeyword */, 24 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 80 /* DoKeyword */, 81 /* ElseKeyword */, 72 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([101 /* TryKeyword */, 86 /* FinallyKeyword */]), 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 131 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124 /* GetKeyword */, 133 /* SetKeyword */]), 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); // TypeScript-specific higher priority rules // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122 /* ConstructorKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 129 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([127 /* ModuleKeyword */, 131 /* RequireKeyword */]), 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 131 /* SetKeyword */, 113 /* StaticKeyword */, 134 /* TypeKeyword */, 136 /* FromKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */, 136 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 74 /* ClassKeyword */, 123 /* DeclareKeyword */, 78 /* DefaultKeyword */, 82 /* EnumKeyword */, 83 /* ExportKeyword */, 84 /* ExtendsKeyword */, 124 /* GetKeyword */, 107 /* ImplementsKeyword */, 90 /* ImportKeyword */, 108 /* InterfaceKeyword */, 127 /* ModuleKeyword */, 128 /* NamespaceKeyword */, 111 /* PrivateKeyword */, 113 /* PublicKeyword */, 112 /* ProtectedKeyword */, 133 /* SetKeyword */, 114 /* StaticKeyword */, 136 /* TypeKeyword */, 138 /* FromKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84 /* ExtendsKeyword */, 107 /* ImplementsKeyword */, 138 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); + this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 35 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(35 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(23 /* DotDotDotToken */, 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 25 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 26 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* CloseParenToken */, 26 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 28 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([18 /* OpenParenToken */, 20 /* OpenBracketToken */, 28 /* GreaterThanToken */, 25 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* OpenBraceToken */, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 131 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 70 /* Identifier */, 83 /* ExportKeyword */, 78 /* DefaultKeyword */, 74 /* ClassKeyword */, 114 /* StaticKeyword */, 113 /* PublicKeyword */, 111 /* PrivateKeyword */, 112 /* ProtectedKeyword */, 124 /* GetKeyword */, 133 /* SetKeyword */, 20 /* OpenBracketToken */, 38 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(38 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(115 /* YieldKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* YieldKeyword */, 38 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(119 /* AsyncKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(119 /* AsyncKeyword */, 88 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(70 /* Identifier */, formatting.Shared.TokenRange.FromTokens([12 /* NoSubstitutionTemplateLiteral */, 13 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 40 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(40 /* SlashToken */, 28 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(57 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -70350,60 +75191,60 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); // Insert space after keywords in control flow statements - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); // Open Brace braces after function // TypeScript: Function can have return types, which can be made of tons of different token kinds - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after TypeScript module/class/interface - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after control block - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* OpenParenToken */, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(20 /* OpenBracketToken */, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing template string braces - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13 /* TemplateHead */, 14 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([13 /* TemplateHead */, 14 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14 /* TemplateMiddle */, 15 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([14 /* TemplateMiddle */, 15 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); // No space after type assertion - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(28 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_51 in o) { - if (o[name_51] === rule) { - return name_51; + for (var name_49 in o) { + if (o[name_49] === rule) { + return name_49; } } throw new Error("Unknown rule"); @@ -70412,42 +75253,42 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 206 /* ForStatement */; + return context.contextNode.kind === 211 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 187 /* BinaryExpression */: - case 188 /* ConditionalExpression */: - case 195 /* AsExpression */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 154 /* TypePredicate */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: + case 192 /* BinaryExpression */: + case 193 /* ConditionalExpression */: + case 200 /* AsExpression */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 156 /* TypePredicate */: + case 164 /* UnionType */: + case 165 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 169 /* BindingElement */: + case 174 /* BindingElement */: // equals in type X = ... - case 223 /* TypeAliasDeclaration */: + case 228 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 218 /* VariableDeclaration */: + case 223 /* VariableDeclaration */: // equal in p = 0; - case 142 /* Parameter */: - case 255 /* EnumMember */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; + case 144 /* Parameter */: + case 260 /* EnumMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: + return context.currentTokenSpan.kind === 57 /* EqualsToken */ || context.nextTokenSpan.kind === 57 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 207 /* ForInStatement */: - return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; + case 212 /* ForInStatement */: + return context.currentTokenSpan.kind === 91 /* InKeyword */ || context.nextTokenSpan.kind === 91 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 208 /* ForOfStatement */: - return context.currentTokenSpan.kind === 138 /* OfKeyword */ || context.nextTokenSpan.kind === 138 /* OfKeyword */; + case 213 /* ForOfStatement */: + return context.currentTokenSpan.kind === 140 /* OfKeyword */ || context.nextTokenSpan.kind === 140 /* OfKeyword */; } return false; }; @@ -70455,7 +75296,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 188 /* ConditionalExpression */; + return context.contextNode.kind === 193 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -70499,127 +75340,127 @@ var ts; return true; } switch (node.kind) { - case 199 /* Block */: - case 227 /* CaseBlock */: - case 171 /* ObjectLiteralExpression */: - case 226 /* ModuleBlock */: + case 204 /* Block */: + case 232 /* CaseBlock */: + case 176 /* ObjectLiteralExpression */: + case 231 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 151 /* CallSignature */: - case 179 /* FunctionExpression */: - case 148 /* Constructor */: - case 180 /* ArrowFunction */: + case 153 /* CallSignature */: + case 184 /* FunctionExpression */: + case 150 /* Constructor */: + case 185 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 222 /* InterfaceDeclaration */: + case 227 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 220 /* FunctionDeclaration */ || context.contextNode.kind === 179 /* FunctionExpression */; + return context.contextNode.kind === 225 /* FunctionDeclaration */ || context.contextNode.kind === 184 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 159 /* TypeLiteral */: - case 225 /* ModuleDeclaration */: - case 236 /* ExportDeclaration */: - case 237 /* NamedExports */: - case 230 /* ImportDeclaration */: - case 233 /* NamedImports */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 161 /* TypeLiteral */: + case 230 /* ModuleDeclaration */: + case 241 /* ExportDeclaration */: + case 242 /* NamedExports */: + case 235 /* ImportDeclaration */: + case 238 /* NamedImports */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 221 /* ClassDeclaration */: - case 225 /* ModuleDeclaration */: - case 224 /* EnumDeclaration */: - case 199 /* Block */: - case 252 /* CatchClause */: - case 226 /* ModuleBlock */: - case 213 /* SwitchStatement */: + case 226 /* ClassDeclaration */: + case 230 /* ModuleDeclaration */: + case 229 /* EnumDeclaration */: + case 204 /* Block */: + case 256 /* CatchClause */: + case 231 /* ModuleBlock */: + case 218 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 203 /* IfStatement */: - case 213 /* SwitchStatement */: - case 206 /* ForStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 205 /* WhileStatement */: - case 216 /* TryStatement */: - case 204 /* DoStatement */: - case 212 /* WithStatement */: + case 208 /* IfStatement */: + case 218 /* SwitchStatement */: + case 211 /* ForStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 210 /* WhileStatement */: + case 221 /* TryStatement */: + case 209 /* DoStatement */: + case 217 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 252 /* CatchClause */: + case 256 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 171 /* ObjectLiteralExpression */; + return context.contextNode.kind === 176 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 174 /* CallExpression */; + return context.contextNode.kind === 179 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 175 /* NewExpression */; + return context.contextNode.kind === 180 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); }; Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 24 /* CommaToken */; + return context.currentTokenSpan.kind !== 25 /* CommaToken */; }; Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; + return context.nextTokenSpan.kind !== 21 /* CloseBracketToken */; }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 180 /* ArrowFunction */; + return context.contextNode.kind === 185 /* ArrowFunction */; }; Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; }; Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 241 /* JsxElement */; + return context.contextNode.kind !== 246 /* JsxElement */; }; Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 248 /* JsxExpression */; + return context.contextNode.kind === 252 /* JsxExpression */; }; Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246 /* JsxAttribute */; + return context.nextTokenParent.kind === 250 /* JsxAttribute */; }; Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246 /* JsxAttribute */; + return context.contextNode.kind === 250 /* JsxAttribute */; }; Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242 /* JsxSelfClosingElement */; + return context.contextNode.kind === 247 /* JsxSelfClosingElement */; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -70634,41 +75475,41 @@ var ts; while (ts.isPartOfExpression(node)) { node = node.parent; } - return node.kind === 143 /* Decorator */; + return node.kind === 145 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 219 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 224 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 225 /* ModuleDeclaration */; + return context.contextNode.kind === 230 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 159 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 161 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 25 /* LessThanToken */ && token.kind !== 27 /* GreaterThanToken */) { + if (token.kind !== 26 /* LessThanToken */ && token.kind !== 28 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 155 /* TypeReference */: - case 177 /* TypeAssertionExpression */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 194 /* ExpressionWithTypeArguments */: + case 157 /* TypeReference */: + case 182 /* TypeAssertionExpression */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 199 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -70679,13 +75520,13 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 177 /* TypeAssertionExpression */; + return context.contextNode.kind === 182 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 183 /* VoidExpression */; + return context.currentTokenSpan.kind === 104 /* VoidKeyword */ && context.currentTokenParent.kind === 188 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 190 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 195 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; }()); @@ -70709,7 +75550,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 138 /* LastToken */ + 1; + this.mapRowLength = 140 /* LastToken */ + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); @@ -70723,8 +75564,8 @@ var ts; }); }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + ts.Debug.assert(row <= 140 /* LastKeyword */ && column <= 140 /* LastKeyword */, "Must compute formatting context from tokens"); var rulesBucketIndex = (row * this.mapRowLength) + column; - // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { @@ -70760,6 +75601,7 @@ var ts; formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; + var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; @@ -70767,8 +75609,7 @@ var ts; RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesPosition = formatting.RulesPosition; + })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); var RulesBucketConstructionState = (function () { function RulesBucketConstructionState() { //// The Rules list contains all the inserted rules into a rulebucket in the following order: @@ -70904,12 +75745,12 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 138 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 140 /* LastToken */; token++) { result.push(token); } return result; }; - TokenAllAccess.prototype.Contains = function (tokenValue) { + TokenAllAccess.prototype.Contains = function () { return true; }; TokenAllAccess.prototype.toString = function () { @@ -70948,17 +75789,17 @@ var ts; }()); TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 138 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 138 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.Keywords = TokenRange.FromRange(71 /* FirstKeyword */, 140 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(26 /* FirstBinaryOperator */, 69 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91 /* InKeyword */, 92 /* InstanceOfKeyword */, 140 /* OfKeyword */, 117 /* AsKeyword */, 125 /* IsKeyword */]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([42 /* PlusPlusToken */, 43 /* MinusMinusToken */, 51 /* TildeToken */, 50 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 70 /* Identifier */, 18 /* OpenParenToken */, 20 /* OpenBracketToken */, 16 /* OpenBraceToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 19 /* CloseParenToken */, 21 /* CloseBracketToken */, 93 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 19 /* CloseParenToken */, 21 /* CloseBracketToken */, 93 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 130 /* NumberKeyword */, 132 /* StringKeyword */, 120 /* BooleanKeyword */, 133 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([70 /* Identifier */, 132 /* NumberKeyword */, 134 /* StringKeyword */, 121 /* BooleanKeyword */, 135 /* SymbolKeyword */, 104 /* VoidKeyword */, 118 /* AnyKeyword */]); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -71005,25 +75846,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +75874,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +75886,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +75896,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +75904,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +75912,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +75926,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71149,11 +75990,11 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 23 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + return formatOutermostParent(position, 24 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 16 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); + return formatOutermostParent(position, 17 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -71217,17 +76058,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 221 /* ClassDeclaration */: - case 222 /* InterfaceDeclaration */: + case 226 /* ClassDeclaration */: + case 227 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 256 /* SourceFile */: - case 199 /* Block */: - case 226 /* ModuleBlock */: + return body && body.kind === 231 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 261 /* SourceFile */: + case 204 /* Block */: + case 231 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -71282,7 +76123,7 @@ var ts; index++; } }; - function rangeHasNoErrors(r) { + function rangeHasNoErrors() { return false; } } @@ -71332,7 +76173,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +76245,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +76253,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71432,20 +76273,20 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 221 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 222 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 220 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 224 /* EnumDeclaration */: return 224 /* EnumDeclaration */; - case 149 /* GetAccessor */: return 123 /* GetKeyword */; - case 150 /* SetAccessor */: return 131 /* SetKeyword */; - case 147 /* MethodDeclaration */: + case 226 /* ClassDeclaration */: return 74 /* ClassKeyword */; + case 227 /* InterfaceDeclaration */: return 108 /* InterfaceKeyword */; + case 225 /* FunctionDeclaration */: return 88 /* FunctionKeyword */; + case 229 /* EnumDeclaration */: return 229 /* EnumDeclaration */; + case 151 /* GetAccessor */: return 124 /* GetKeyword */; + case 152 /* SetAccessor */: return 133 /* SetKeyword */; + case 149 /* MethodDeclaration */: if (node.asteriskToken) { - return 37 /* AsteriskToken */; + return 38 /* AsteriskToken */; } /* fall-through */ - case 145 /* PropertyDeclaration */: - case 142 /* Parameter */: + case 147 /* PropertyDeclaration */: + case 144 /* Parameter */: return node.name.kind; } } @@ -71457,9 +76298,9 @@ var ts; // .. { // // comment // } - case 16 /* CloseBraceToken */: - case 20 /* CloseBracketToken */: - case 18 /* CloseParenToken */: + case 17 /* CloseBraceToken */: + case 21 /* CloseBracketToken */: + case 19 /* CloseParenToken */: return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; @@ -71473,15 +76314,15 @@ var ts; } switch (kind) { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 15 /* OpenBraceToken */: - case 16 /* CloseBraceToken */: - case 19 /* OpenBracketToken */: - case 20 /* CloseBracketToken */: - case 17 /* OpenParenToken */: - case 18 /* CloseParenToken */: - case 80 /* ElseKeyword */: - case 104 /* WhileKeyword */: - case 55 /* AtToken */: + case 16 /* OpenBraceToken */: + case 17 /* CloseBraceToken */: + case 20 /* OpenBracketToken */: + case 21 /* CloseBracketToken */: + case 18 /* OpenParenToken */: + case 19 /* CloseParenToken */: + case 81 /* ElseKeyword */: + case 105 /* WhileKeyword */: + case 56 /* AtToken */: return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation @@ -71493,13 +76334,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71581,18 +76422,19 @@ var ts; if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (ts.isToken(child)) { + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); - ts.Debug.assert(tokenInfo.token.end === child.end); + ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 143 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 145 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; - if (isFirstListItem && parent.kind === 170 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 175 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -71790,11 +76632,23 @@ var ts; else { var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); - if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } } } + function characterToColumn(startLinePosition, characterInLine) { + var column = 0; + for (var i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } @@ -71919,7 +76773,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71937,41 +76791,41 @@ var ts; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 148 /* Constructor */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 180 /* ArrowFunction */: + case 150 /* Constructor */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 185 /* ArrowFunction */: if (node.typeParameters === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } else if (node.parameters === list) { - return 17 /* OpenParenToken */; + return 18 /* OpenParenToken */; } break; - case 174 /* CallExpression */: - case 175 /* NewExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: if (node.typeArguments === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } else if (node.arguments === list) { - return 17 /* OpenParenToken */; + return 18 /* OpenParenToken */; } break; - case 155 /* TypeReference */: + case 157 /* TypeReference */: if (node.typeArguments === list) { - return 25 /* LessThanToken */; + return 26 /* LessThanToken */; } } return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 17 /* OpenParenToken */: - return 18 /* CloseParenToken */; - case 25 /* LessThanToken */: - return 27 /* GreaterThanToken */; + case 18 /* OpenParenToken */: + return 19 /* CloseParenToken */; + case 26 /* LessThanToken */: + return 28 /* GreaterThanToken */; } return 0 /* Unknown */; } @@ -71980,14 +76834,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +76856,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +76899,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +76915,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72075,7 +76929,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 187 /* BinaryExpression */) { + if (precedingToken.kind === 25 /* CommaToken */ && precedingToken.parent.kind !== 192 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -72095,7 +76949,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +76960,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +76972,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +77015,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72198,7 +77052,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 256 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 261 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -72209,11 +77063,11 @@ var ts; if (!nextToken) { return false; } - if (nextToken.kind === 15 /* OpenBraceToken */) { + if (nextToken.kind === 16 /* OpenBraceToken */) { // open braces are always indented at the parent level return true; } - else if (nextToken.kind === 16 /* CloseBraceToken */) { + else if (nextToken.kind === 17 /* CloseBraceToken */) { // close braces are indented at the parent level if they are located on the same line with cursor // this means that if new line will be added at $ position, this case will be indented // class A { @@ -72231,8 +77085,8 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 203 /* IfStatement */ && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); + if (parent.kind === 208 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 81 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -72243,23 +77097,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 155 /* TypeReference */: + case 157 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 171 /* ObjectLiteralExpression */: + case 176 /* ObjectLiteralExpression */: return node.parent.properties; - case 170 /* ArrayLiteralExpression */: + case 175 /* ArrayLiteralExpression */: return node.parent.elements; - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: { + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -72270,8 +77124,8 @@ var ts; } break; } - case 175 /* NewExpression */: - case 174 /* CallExpression */: { + case 180 /* NewExpression */: + case 179 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -72298,11 +77152,11 @@ var ts; function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: // - node is close parenthesis - this is the end of the expression - if (node.kind === 18 /* CloseParenToken */) { + if (node.kind === 19 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 174 /* CallExpression */ || - node.parent.kind === 175 /* NewExpression */) && + if (node.parent && (node.parent.kind === 179 /* CallExpression */ || + node.parent.kind === 180 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -72320,10 +77174,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 172 /* PropertyAccessExpression */: - case 173 /* ElementAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 177 /* PropertyAccessExpression */: + case 178 /* ElementAccessExpression */: node = node.expression; break; default: @@ -72339,7 +77193,7 @@ var ts; // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 24 /* CommaToken */) { + if (list[i].kind === 25 /* CommaToken */) { continue; } // skip list items that ends on the same line with the current list element @@ -72371,7 +77225,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72387,48 +77241,48 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202 /* ExpressionStatement */: - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 224 /* EnumDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 170 /* ArrayLiteralExpression */: - case 199 /* Block */: - case 226 /* ModuleBlock */: - case 171 /* ObjectLiteralExpression */: - case 159 /* TypeLiteral */: - case 161 /* TupleType */: - case 227 /* CaseBlock */: - case 250 /* DefaultClause */: - case 249 /* CaseClause */: - case 178 /* ParenthesizedExpression */: - case 172 /* PropertyAccessExpression */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 200 /* VariableStatement */: - case 218 /* VariableDeclaration */: - case 235 /* ExportAssignment */: - case 211 /* ReturnStatement */: - case 188 /* ConditionalExpression */: - case 168 /* ArrayBindingPattern */: - case 167 /* ObjectBindingPattern */: - case 243 /* JsxOpeningElement */: - case 242 /* JsxSelfClosingElement */: - case 248 /* JsxExpression */: - case 146 /* MethodSignature */: - case 151 /* CallSignature */: - case 152 /* ConstructSignature */: - case 142 /* Parameter */: - case 156 /* FunctionType */: - case 157 /* ConstructorType */: - case 164 /* ParenthesizedType */: - case 176 /* TaggedTemplateExpression */: - case 184 /* AwaitExpression */: - case 237 /* NamedExports */: - case 233 /* NamedImports */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: + case 207 /* ExpressionStatement */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 229 /* EnumDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 175 /* ArrayLiteralExpression */: + case 204 /* Block */: + case 231 /* ModuleBlock */: + case 176 /* ObjectLiteralExpression */: + case 161 /* TypeLiteral */: + case 163 /* TupleType */: + case 232 /* CaseBlock */: + case 254 /* DefaultClause */: + case 253 /* CaseClause */: + case 183 /* ParenthesizedExpression */: + case 177 /* PropertyAccessExpression */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 205 /* VariableStatement */: + case 223 /* VariableDeclaration */: + case 240 /* ExportAssignment */: + case 216 /* ReturnStatement */: + case 193 /* ConditionalExpression */: + case 173 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 248 /* JsxOpeningElement */: + case 247 /* JsxSelfClosingElement */: + case 252 /* JsxExpression */: + case 148 /* MethodSignature */: + case 153 /* CallSignature */: + case 154 /* ConstructSignature */: + case 144 /* Parameter */: + case 158 /* FunctionType */: + case 159 /* ConstructorType */: + case 166 /* ParenthesizedType */: + case 181 /* TaggedTemplateExpression */: + case 189 /* AwaitExpression */: + case 242 /* NamedExports */: + case 238 /* NamedImports */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: return true; } return false; @@ -72437,27 +77291,27 @@ var ts; function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 204 /* DoStatement */: - case 205 /* WhileStatement */: - case 207 /* ForInStatement */: - case 208 /* ForOfStatement */: - case 206 /* ForStatement */: - case 203 /* IfStatement */: - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 180 /* ArrowFunction */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - return childKind !== 199 /* Block */; - case 236 /* ExportDeclaration */: - return childKind !== 237 /* NamedExports */; - case 230 /* ImportDeclaration */: - return childKind !== 231 /* ImportClause */ || - (child.namedBindings && child.namedBindings.kind !== 233 /* NamedImports */); - case 241 /* JsxElement */: - return childKind !== 245 /* JsxClosingElement */; + case 209 /* DoStatement */: + case 210 /* WhileStatement */: + case 212 /* ForInStatement */: + case 213 /* ForOfStatement */: + case 211 /* ForStatement */: + case 208 /* IfStatement */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 185 /* ArrowFunction */: + case 150 /* Constructor */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return childKind !== 204 /* Block */; + case 241 /* ExportDeclaration */: + return childKind !== 242 /* NamedExports */; + case 235 /* ImportDeclaration */: + return childKind !== 236 /* ImportClause */ || + (child.namedBindings && child.namedBindings.kind !== 238 /* NamedImports */); + case 246 /* JsxElement */: + return childKind !== 249 /* JsxClosingElement */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -72473,6 +77327,776 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 122 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 98 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 179 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var ModuleSpecifierComparison; + (function (ModuleSpecifierComparison) { + ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; + ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; + })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); + var ImportCodeActionMap = (function () { + function ImportCodeActionMap() { + this.symbolIdToActionMap = ts.createMap(); + } + ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { + if (!newAction) { + return; + } + if (!this.symbolIdToActionMap[symbolId]) { + this.symbolIdToActionMap[symbolId] = [newAction]; + return; + } + if (newAction.kind === "CodeChange") { + this.symbolIdToActionMap[symbolId].push(newAction); + return; + } + var updatedNewImports = []; + for (var _i = 0, _a = this.symbolIdToActionMap[symbolId]; _i < _a.length; _i++) { + var existingAction = _a[_i]; + if (existingAction.kind === "CodeChange") { + // only import actions should compare + updatedNewImports.push(existingAction); + continue; + } + switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { + case ModuleSpecifierComparison.Better: + // the new one is not worth considering if it is a new improt. + // However if it is instead a insertion into existing import, the user might want to use + // the module specifier even it is worse by our standards. So keep it. + if (newAction.kind === "NewImport") { + return; + } + case ModuleSpecifierComparison.Equal: + // the current one is safe. But it is still possible that the new one is worse + // than another existing one. For example, you may have new imports from "./foo/bar" + // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new + // one and the current one are not comparable (one relative path and one absolute path), + // but the new one is worse than the other one, so should not add to the list. + updatedNewImports.push(existingAction); + break; + case ModuleSpecifierComparison.Worse: + // the existing one is worse, remove from the list. + continue; + } + } + // if we reach here, it means the new one is better or equal to all of the existing ones. + updatedNewImports.push(newAction); + this.symbolIdToActionMap[symbolId] = updatedNewImports; + }; + ImportCodeActionMap.prototype.addActions = function (symbolId, newActions) { + for (var _i = 0, newActions_1 = newActions; _i < newActions_1.length; _i++) { + var newAction = newActions_1[_i]; + this.addAction(symbolId, newAction); + } + }; + ImportCodeActionMap.prototype.getAllActions = function () { + var result = []; + for (var symbolId in this.symbolIdToActionMap) { + result = ts.concatenate(result, this.symbolIdToActionMap[symbolId]); + } + return result; + }; + ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { + if (moduleSpecifier1 === moduleSpecifier2) { + return ModuleSpecifierComparison.Equal; + } + // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better + if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { + return ModuleSpecifierComparison.Better; + } + if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { + return ModuleSpecifierComparison.Worse; + } + // if both are relative paths, and ms1 has fewer levels, then it is better + if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { + var regex = new RegExp(ts.directorySeparator, "g"); + var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; + var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; + return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Better + : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Equal + : ModuleSpecifierComparison.Worse; + } + // the equal cases include when the two specifiers are not comparable. + return ModuleSpecifierComparison.Equal; + }; + return ImportCodeActionMap; + }()); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var allSourceFiles = context.program.getSourceFiles(); + var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var name = token.getText(); + var symbolIdActionMap = new ImportCodeActionMap(); + // this is a module id -> module import declaration map + var cachedImportDeclarations = ts.createMap(); + var cachedNewImportInsertPosition; + var allPotentialModules = checker.getAmbientModules(); + for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { + var otherSourceFile = allSourceFiles_1[_i]; + if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { + allPotentialModules.push(otherSourceFile.symbol); + } + } + var currentTokenMeaning = ts.getMeaningFromLocation(token); + for (var _a = 0, allPotentialModules_1 = allPotentialModules; _a < allPotentialModules_1.length; _a++) { + var moduleSymbol = allPotentialModules_1[_a]; + context.cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + return symbolIdActionMap.getAllActions(); + function getImportDeclarations(moduleSymbol) { + var moduleSymbolId = getUniqueSymbolId(moduleSymbol); + if (cachedImportDeclarations[moduleSymbolId]) { + return cachedImportDeclarations[moduleSymbolId]; + } + var existingDeclarations = []; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importModuleSpecifier = _a[_i]; + var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + function getImportDeclaration(moduleSpecifier) { + var node = moduleSpecifier; + while (node) { + if (node.kind === 235 /* ImportDeclaration */) { + return node; + } + if (node.kind === 234 /* ImportEqualsDeclaration */) { + return node; + } + node = node.parent; + } + return undefined; + } + } + function getUniqueSymbolId(symbol) { + if (symbol.flags & 8388608 /* Alias */) { + return ts.getSymbolId(checker.getAliasedSymbol(symbol)); + } + return ts.getSymbolId(symbol); + } + function checkSymbolHasMeaning(symbol, meaning) { + var declarations = symbol.getDeclarations(); + return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + } + function getCodeActionForImport(moduleSymbol, isDefault) { + var existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + function getCodeActionsForExistingImport(declarations) { + var actions = []; + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + var namespaceImportDeclaration; + var namedImportDeclaration; + var existingModuleSpecifier; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (declaration.kind === 235 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === 237 /* NamespaceImport */) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; + } + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; + } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + } + } + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + if (namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + var textChange = getTextChangeForImportClause(namedImportDeclaration.importClause); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], textChange.newText, textChange.span, sourceFile.fileName, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + } + else { + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + function getModuleSpecifierFromImportEqualsDeclaration(declaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === 245 /* ExternalModuleReference */) { + return declaration.moduleReference.expression.getText(); + } + return declaration.moduleReference.getText(); + } + function getTextChangeForImportClause(importClause) { + var newImportText = isDefault ? "default as " + name : name; + var importList = importClause.namedBindings; + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + if (!importList && importClause.name) { + var start = importClause.name.getEnd(); + return { + newText: ", { " + newImportText + " }", + span: { start: start, length: 0 } + }; + } + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (importList.elements.length === 0) { + var start = importList.getStart(); + return { + newText: "{ " + newImportText + " }", + span: { start: start, length: importList.getEnd() - start } + }; + } + // case 3: + // original text: import { foo, bar } from "module" + // change to: import { foo, bar, name } from "module" + var insertPoint = importList.elements[importList.elements.length - 1].getEnd(); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + var startLine = ts.getLineOfLocalPosition(sourceFile, importList.getStart()); + var endLine = ts.getLineOfLocalPosition(sourceFile, importList.getEnd()); + var oneImportPerLine = endLine - startLine > importList.elements.length; + return { + newText: "," + (oneImportPerLine ? context.newLineCharacter : " ") + newImportText, + span: { start: insertPoint, length: 0 } + }; + } + function getCodeActionForNamespaceImport(declaration) { + var namespacePrefix; + if (declaration.kind === 235 /* ImportDeclaration */) { + namespacePrefix = declaration.importClause.namedBindings.name.getText(); + } + else { + namespacePrefix = declaration.name.getText(); + } + namespacePrefix = ts.stripQuotes(namespacePrefix); + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], namespacePrefix + ".", { start: token.getStart(), length: 0 }, sourceFile.fileName, "CodeChange"); + } + } + function getCodeActionForNewImport(moduleSpecifier) { + if (!cachedNewImportInsertPosition) { + // insert after any existing imports + var lastModuleSpecifierEnd = -1; + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var moduleSpecifier_1 = _a[_i]; + var end = moduleSpecifier_1.getEnd(); + if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) { + lastModuleSpecifierEnd = end; + } + } + cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart(); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + var importStatementText = isDefault + ? "import " + name + " from \"" + moduleSpecifierWithoutQuotes + "\"" + : "import { " + name + " } from \"" + moduleSpecifierWithoutQuotes + "\""; + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + var newText = cachedNewImportInsertPosition === sourceFile.getStart() + ? importStatementText + ";" + context.newLineCharacter + context.newLineCharacter + : "" + context.newLineCharacter + importStatementText + ";"; + return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], newText, { start: cachedNewImportInsertPosition, length: 0 }, sourceFile.fileName, "NewImport", moduleSpecifierWithoutQuotes); + function getModuleSpecifierForNewImport() { + var fileName = sourceFile.path; + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path; + var sourceDirectory = ts.getDirectoryPath(fileName); + var options = context.program.getCompilerOptions(); + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + function tryGetModuleNameFromAmbientModule() { + if (moduleSymbol.valueDeclaration.kind !== 261 /* SourceFile */) { + return moduleSymbol.name; + } + } + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { + return undefined; + } + var normalizedBaseUrl = ts.toPath(options.baseUrl, ts.getDirectoryPath(options.baseUrl), getCanonicalFileName); + var relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl); + if (!relativeName) { + return undefined; + } + relativeName = removeExtensionAndIndexPostFix(relativeName); + if (options.paths) { + for (var key in options.paths) { + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName) { + return key; + } + } + } + } + return relativeName; + } + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + var normalizedRootDirs = ts.map(options.rootDirs, function (rootDir) { return ts.toPath(rootDir, /*basePath*/ undefined, getCanonicalFileName); }); + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs); + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs); + if (normalizedTargetPath !== undefined) { + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + } + return undefined; + } + function tryGetModuleNameFromTypeRoots() { + var typeRoots = ts.getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); + for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { + var typeRoot = normalizedTypeRoots_1[_i]; + if (ts.startsWith(moduleFileName, typeRoot)) { + var relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } + } + } + function tryGetModuleNameAsNodeModule() { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + var relativeFileName; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + relativeFileName = ts.removeFileExtension(relativeFileName); + if (ts.endsWith(relativeFileName, "/index")) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + else { + try { + var moduleDirectory = ts.getDirectoryPath(moduleFileName); + var packageJsonContent = JSON.parse(context.host.readFile(ts.combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + var mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + var mainExportFile = ts.toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(moduleFileName)) { + relativeFileName = ts.getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + return relativeFileName; + } + } + function getPathRelativeToRootDirs(path, rootDirs) { + for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { + var rootDir = rootDirs_2[_i]; + var relativeName = tryRemoveParentDirectoryName(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePath(path, directoryPath) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } + function tryRemoveParentDirectoryName(path, parentDirectory) { + var index = path.indexOf(parentDirectory); + if (index === 0) { + return ts.endsWith(parentDirectory, ts.directorySeparator) + ? path.substring(parentDirectory.length) + : path.substring(parentDirectory.length + 1); + } + return undefined; + } + } + } + function createCodeAction(description, diagnosticArgs, newText, span, fileName, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: [{ fileName: fileName, textChanges: [{ newText: newText, span: span }] }], + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics._0_is_declared_but_never_used.code, + ts.Diagnostics.Property_0_is_declared_but_never_used.code + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start); + // this handles var ["computed"] = 12; + if (token.kind === 20 /* OpenBracketToken */) { + token = ts.getTokenAtPosition(sourceFile, start + 1); + } + switch (token.kind) { + case 70 /* Identifier */: + switch (token.parent.kind) { + case 223 /* VariableDeclaration */: + switch (token.parent.parent.parent.kind) { + case 211 /* ForStatement */: + var forStatement = token.parent.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos); + } + else { + return removeSingleItem(forInitializer.declarations, token); + } + case 213 /* ForOfStatement */: + var forOfStatement = token.parent.parent.parent; + if (forOfStatement.initializer.kind === 224 /* VariableDeclarationList */) { + var forOfInitializer = forOfStatement.initializer; + return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos); + } + break; + case 212 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in + return undefined; + case 256 /* CatchClause */: + var catchClause = token.parent.parent; + var parameter = catchClause.variableDeclaration.getChildren()[0]; + return createCodeFix("", parameter.pos, parameter.end - parameter.pos); + default: + var variableStatement = token.parent.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos); + } + else { + var declarations = variableStatement.declarationList.declarations; + return removeSingleItem(declarations, token); + } + } + case 143 /* TypeParameter */: + var typeParameters = token.parent.parent.typeParameters; + if (typeParameters.length === 1) { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2); + } + else { + return removeSingleItem(typeParameters, token); + } + case 144 /* Parameter */: + var functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else { + return removeSingleItem(functionDeclaration.parameters, token); + } + // handle case where 'import a = A;' + case 234 /* ImportEqualsDeclaration */: + var importEquals = findImportDeclaration(token); + return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos); + case 239 /* ImportSpecifier */: + var namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + var importSpec = findImportDeclaration(token); + return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos); + } + else { + return removeSingleItem(namedImports.elements, token); + } + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case 236 /* ImportClause */: + var importClause = token.parent; + if (!importClause.namedBindings) { + var importDecl = findImportDeclaration(importClause); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos); + } + case 237 /* NamespaceImport */: + var namespaceImport = token.parent; + if (namespaceImport.name == token && !namespaceImport.parent.name) { + var importDecl = findImportDeclaration(namespaceImport); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + var start_4 = namespaceImport.parent.name.end; + return createCodeFix("", start_4, namespaceImport.parent.namedBindings.end - start_4); + } + } + break; + case 147 /* PropertyDeclaration */: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + case 237 /* NamespaceImport */: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + if (ts.isDeclarationName(token)) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos); + } + else { + return undefined; + } + function findImportDeclaration(token) { + var importDecl = token; + while (importDecl.kind != 235 /* ImportDeclaration */ && importDecl.parent) { + importDecl = importDecl.parent; + } + return importDecl; + } + function createCodeFix(newText, start, length) { + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_unused_identifiers), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ newText: newText, span: { start: start, length: length } }] + }] + }]; + } + function removeSingleItem(elements, token) { + if (elements[0] === token.parent) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1); + } + else { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1); + } + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// +/// +/// /// /// /// @@ -72498,13 +78122,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { - var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + var node = kind >= 141 /* FirstNode */ ? new NodeObject(kind, pos, end) : + kind === 70 /* Identifier */ ? new IdentifierObject(70 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72515,7 +78141,6 @@ var ts; this.end = end; this.flags = 0 /* None */; this.transformFlags = undefined; - this.excludeTransformFlags = undefined; this.parent = undefined; this.kind = kind; } @@ -72562,11 +78187,11 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(292 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -72581,11 +78206,11 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 139 /* FirstNode */) { + if (this.kind >= 141 /* FirstNode */) { ts.scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 278 /* FirstJSDocTagNode */ && this.kind <= 291 /* LastJSDocTagNode */; var processNode = function (node) { var isJSDocTagNode = ts.isJSDocTag(node); if (!isJSDocTagNode && pos_3 < node.pos) { @@ -72604,8 +78229,8 @@ var ts; pos_3 = nodes.end; }; // jsDocComments need to be the first children - if (this.jsDocComments) { - for (var _i = 0, _a = this.jsDocComments; _i < _a.length; _i++) { + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; processNode(jsDocComment); } @@ -72643,7 +78268,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 139 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + return child.kind < 141 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -72651,7 +78276,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 139 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 141 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; }()); @@ -72690,19 +78315,19 @@ var ts; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { + TokenOrIdentifierObject.prototype.getChildAt = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { + TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { + TokenOrIdentifierObject.prototype.getLastToken = function () { return undefined; }; return TokenOrIdentifierObject; @@ -72723,7 +78348,7 @@ var ts; }; SymbolObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); } return this.documentationComment; }; @@ -72732,19 +78357,20 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + function IdentifierObject(_kind, pos, end) { + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69 /* Identifier */; + IdentifierObject.prototype.kind = 70 /* Identifier */; var TypeObject = (function () { function TypeObject(checker, flags) { this.checker = checker; @@ -72778,7 +78404,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 /* Class */ | 65536 /* Interface */) + return this.flags & 32768 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -72805,9 +78431,7 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration], - /*name*/ undefined, - /*canUseParsedParamTagComments*/ false) : []; + this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; } return this.documentationComment; }; @@ -72816,7 +78440,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72830,6 +78454,20 @@ var ts; SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { return ts.getPositionOfLineAndCharacter(this, line, character); }; + SourceFileObject.prototype.getLineEndOfPosition = function (pos) { + var line = this.getLineAndCharacterOfPosition(pos).line; + var lineStarts = this.getLineStarts(); + var lastCharPos; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); @@ -72851,13 +78489,13 @@ var ts; } function getDeclarationName(declaration) { if (declaration.name) { - var result_6 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_6 !== undefined) { - return result_6; + var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_7 !== undefined) { + return result_7; } - if (declaration.name.kind === 140 /* ComputedPropertyName */) { + if (declaration.name.kind === 142 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 172 /* PropertyAccessExpression */) { + if (expr.kind === 177 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -72867,7 +78505,7 @@ var ts; } function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 69 /* Identifier */ || + if (node.kind === 70 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { return node.text; @@ -72877,10 +78515,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 220 /* FunctionDeclaration */: - case 179 /* FunctionExpression */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: + case 225 /* FunctionDeclaration */: + case 184 /* FunctionExpression */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -72897,35 +78535,35 @@ var ts; else { declarations.push(functionDeclaration); } - ts.forEachChild(node, visit); } + ts.forEachChild(node, visit); break; - case 221 /* ClassDeclaration */: - case 192 /* ClassExpression */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - case 224 /* EnumDeclaration */: - case 225 /* ModuleDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 159 /* TypeLiteral */: + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: + case 229 /* EnumDeclaration */: + case 230 /* ModuleDeclaration */: + case 234 /* ImportEqualsDeclaration */: + case 243 /* ExportSpecifier */: + case 239 /* ImportSpecifier */: + case 234 /* ImportEqualsDeclaration */: + case 236 /* ImportClause */: + case 237 /* NamespaceImport */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 161 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 142 /* Parameter */: + case 144 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // fall through - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: { + case 223 /* VariableDeclaration */: + case 174 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -72934,19 +78572,19 @@ var ts; if (decl.initializer) visit(decl.initializer); } - case 255 /* EnumMember */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 260 /* EnumMember */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: addDeclaration(node); break; - case 236 /* ExportDeclaration */: + case 241 /* 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 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -72958,7 +78596,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 237 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -72982,9 +78620,33 @@ var ts; getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, - getSignatureConstructor: function () { return SignatureObject; } + getSignatureConstructor: function () { return SignatureObject; }, }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +78662,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73053,7 +78719,7 @@ var ts; }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (path, value) { + this.fileNameToEntry.forEachValue(function (_path, value) { if (value) { fileNames.push(value.hostFileName); } @@ -73085,7 +78751,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -73185,7 +78851,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +78891,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73256,7 +78929,7 @@ var ts; useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: function (fileName, data, writeByteOrderMark) { }, + writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality @@ -73390,7 +79063,7 @@ var ts; return program; } function cleanupSemanticCache() { - // TODO: Should we jettison the program (or it's type checker) here? + program = undefined; } function dispose() { if (program) { @@ -73452,12 +79125,12 @@ var ts; if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: - case 97 /* ThisKeyword */: - case 165 /* ThisType */: - case 95 /* SuperKeyword */: + case 70 /* Identifier */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: + case 98 /* ThisKeyword */: + case 167 /* ThisType */: + case 96 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); if (type) { @@ -73553,12 +79226,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +79242,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73591,7 +79264,7 @@ var ts; function getSourceFile(fileName) { return getNonBoundSourceFile(fileName); } - function getNameOrDottedNameSpan(fileName, startPos, endPos) { + function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location var node = ts.getTouchingPropertyName(sourceFile, startPos); @@ -73599,16 +79272,16 @@ var ts; return; } switch (node.kind) { - case 172 /* PropertyAccessExpression */: - case 139 /* QualifiedName */: + case 177 /* PropertyAccessExpression */: + case 141 /* QualifiedName */: case 9 /* StringLiteral */: - case 84 /* FalseKeyword */: - case 99 /* TrueKeyword */: - case 93 /* NullKeyword */: - case 95 /* SuperKeyword */: - case 97 /* ThisKeyword */: - case 165 /* ThisType */: - case 69 /* Identifier */: + case 85 /* FalseKeyword */: + case 100 /* TrueKeyword */: + case 94 /* NullKeyword */: + case 96 /* SuperKeyword */: + case 98 /* ThisKeyword */: + case 167 /* ThisType */: + case 70 /* Identifier */: break; // Cant create the text span default: @@ -73624,7 +79297,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 225 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 230 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -73647,14 +79320,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73701,48 +79388,76 @@ var ts; return result; function getMatchingTokenKind(token) { switch (token.kind) { - case 15 /* OpenBraceToken */: return 16 /* CloseBraceToken */; - case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; - case 19 /* OpenBracketToken */: return 20 /* CloseBracketToken */; - case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; - case 16 /* CloseBraceToken */: return 15 /* OpenBraceToken */; - case 18 /* CloseParenToken */: return 17 /* OpenParenToken */; - case 20 /* CloseBracketToken */: return 19 /* OpenBracketToken */; - case 27 /* GreaterThanToken */: return 25 /* LessThanToken */; + case 16 /* OpenBraceToken */: return 17 /* CloseBraceToken */; + case 18 /* OpenParenToken */: return 19 /* CloseParenToken */; + case 20 /* OpenBracketToken */: return 21 /* CloseBracketToken */; + case 26 /* LessThanToken */: return 28 /* GreaterThanToken */; + case 17 /* CloseBraceToken */: return 16 /* OpenBraceToken */; + case 19 /* CloseParenToken */: return 18 /* OpenParenToken */; + case 21 /* CloseBracketToken */: return 20 /* OpenBracketToken */; + case 28 /* GreaterThanToken */: return 26 /* LessThanToken */; } return undefined; } } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar, + host: host, + cancellationToken: cancellationToken + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73758,7 +79473,7 @@ var ts; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -73926,6 +79641,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +79651,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -73956,7 +79673,7 @@ var ts; sourceFile.nameTable = nameTable; function walk(node) { switch (node.kind) { - case 69 /* Identifier */: + case 70 /* Identifier */: nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9 /* StringLiteral */: @@ -73966,7 +79683,7 @@ var ts; // then we want 'something' to be in the name table. Similarly, if we have // "a['propname']" then we want to store "propname" in the name table. if (ts.isDeclarationName(node) || - node.parent.kind === 240 /* ExternalModuleReference */ || + node.parent.kind === 245 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node)) { nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; @@ -73974,10 +79691,10 @@ var ts; break; default: ts.forEachChild(node, walk); - if (node.jsDocComments) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - ts.forEachChild(jsDocComment, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); } } } @@ -73986,7 +79703,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 173 /* ElementAccessExpression */ && + node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -74070,143 +79787,143 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 200 /* VariableStatement */: + case 205 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 218 /* VariableDeclaration */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: + case 223 /* VariableDeclaration */: + case 147 /* PropertyDeclaration */: + case 146 /* PropertySignature */: return spanInVariableDeclaration(node); - case 142 /* Parameter */: + case 144 /* Parameter */: return spanInParameterDeclaration(node); - case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: + case 225 /* FunctionDeclaration */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 184 /* FunctionExpression */: + case 185 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 199 /* Block */: + case 204 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: return spanInBlock(node); - case 252 /* CatchClause */: + case 256 /* CatchClause */: return spanInBlock(node.block); - case 202 /* ExpressionStatement */: + case 207 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 211 /* ReturnStatement */: + case 216 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 205 /* WhileStatement */: + case 210 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 204 /* DoStatement */: + case 209 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 217 /* DebuggerStatement */: + case 222 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 203 /* IfStatement */: + case 208 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 214 /* LabeledStatement */: + case 219 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 210 /* BreakStatement */: - case 209 /* ContinueStatement */: + case 215 /* BreakStatement */: + case 214 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 206 /* ForStatement */: + case 211 /* ForStatement */: return spanInForStatement(node); - case 207 /* ForInStatement */: + case 212 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 208 /* ForOfStatement */: + case 213 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 213 /* SwitchStatement */: + case 218 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 249 /* CaseClause */: - case 250 /* DefaultClause */: + case 253 /* CaseClause */: + case 254 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 216 /* TryStatement */: + case 221 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 215 /* ThrowStatement */: + case 220 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 235 /* ExportAssignment */: + case 240 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 229 /* ImportEqualsDeclaration */: + case 234 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 230 /* ImportDeclaration */: + case 235 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 236 /* ExportDeclaration */: + case 241 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 255 /* EnumMember */: - case 169 /* BindingElement */: + case 226 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 260 /* EnumMember */: + case 174 /* BindingElement */: // span on complete node return textSpan(node); - case 212 /* WithStatement */: + case 217 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 143 /* Decorator */: + case 145 /* Decorator */: return spanInNodeArray(node.parent.decorators); - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: + case 172 /* ObjectBindingPattern */: + case 173 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: + case 227 /* InterfaceDeclaration */: + case 228 /* TypeAliasDeclaration */: return undefined; // Tokens: - case 23 /* SemicolonToken */: + case 24 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 24 /* CommaToken */: + case 25 /* CommaToken */: return spanInPreviousNode(node); - case 15 /* OpenBraceToken */: + case 16 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 16 /* CloseBraceToken */: + case 17 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 20 /* CloseBracketToken */: + case 21 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 17 /* OpenParenToken */: + case 18 /* OpenParenToken */: return spanInOpenParenToken(node); - case 18 /* CloseParenToken */: + case 19 /* CloseParenToken */: return spanInCloseParenToken(node); - case 54 /* ColonToken */: + case 55 /* ColonToken */: return spanInColonToken(node); - case 27 /* GreaterThanToken */: - case 25 /* LessThanToken */: + case 28 /* GreaterThanToken */: + case 26 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); // Keywords: - case 104 /* WhileKeyword */: + case 105 /* WhileKeyword */: return spanInWhileKeyword(node); - case 80 /* ElseKeyword */: - case 72 /* CatchKeyword */: - case 85 /* FinallyKeyword */: + case 81 /* ElseKeyword */: + case 73 /* CatchKeyword */: + case 86 /* FinallyKeyword */: return spanInNextNode(node); - case 138 /* OfKeyword */: + case 140 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -74218,14 +79935,14 @@ var ts; // Set breakpoint on identifier element of destructuring pattern // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern - if ((node.kind === 69 /* Identifier */ || - node.kind == 191 /* SpreadElementExpression */ || - node.kind === 253 /* PropertyAssignment */ || - node.kind === 254 /* ShorthandPropertyAssignment */) && + if ((node.kind === 70 /* Identifier */ || + node.kind == 196 /* SpreadElement */ || + node.kind === 257 /* PropertyAssignment */ || + node.kind === 258 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 187 /* BinaryExpression */) { + if (node.kind === 192 /* BinaryExpression */) { var binaryExpression = node; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -74234,7 +79951,7 @@ var ts; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); } - if (binaryExpression.operatorToken.kind === 56 /* EqualsToken */ && + if (binaryExpression.operatorToken.kind === 57 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { // Set breakpoint on assignment expression element of destructuring pattern // a = expression of @@ -74242,28 +79959,28 @@ var ts; // { a = expression, b, c } = someExpression return textSpan(node); } - if (binaryExpression.operatorToken.kind === 24 /* CommaToken */) { + if (binaryExpression.operatorToken.kind === 25 /* CommaToken */) { return spanInNode(binaryExpression.left); } } if (ts.isPartOfExpression(node)) { switch (node.parent.kind) { - case 204 /* DoStatement */: + case 209 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 143 /* Decorator */: + case 145 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: return textSpan(node); - case 187 /* BinaryExpression */: - if (node.parent.operatorToken.kind === 24 /* CommaToken */) { + case 192 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 25 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 180 /* ArrowFunction */: + case 185 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -74272,13 +79989,13 @@ var ts; } } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 253 /* PropertyAssignment */ && + if (node.parent.kind === 257 /* PropertyAssignment */ && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 177 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 182 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNextNode(node.parent.type); } // return type of function go to previous token @@ -74286,8 +80003,8 @@ var ts; return spanInPreviousNode(node); } // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 218 /* VariableDeclaration */ || - node.parent.kind === 142 /* Parameter */)) { + if ((node.parent.kind === 223 /* VariableDeclaration */ || + node.parent.kind === 144 /* Parameter */)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -74295,7 +80012,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 187 /* BinaryExpression */) { + if (node.parent.kind === 192 /* BinaryExpression */) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -74321,7 +80038,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 207 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 212 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } // If this is a destructuring pattern, set breakpoint in binding pattern @@ -74332,7 +80049,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 208 /* ForOfStatement */) { + variableDeclaration.parent.parent.kind === 213 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } var declarations = variableDeclaration.parent.declarations; @@ -74372,7 +80089,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 221 /* ClassDeclaration */ && functionDeclaration.kind !== 148 /* Constructor */); + (functionDeclaration.parent.kind === 226 /* ClassDeclaration */ && functionDeclaration.kind !== 150 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -74395,25 +80112,25 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 225 /* ModuleDeclaration */: + case 230 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 205 /* WhileStatement */: - case 203 /* IfStatement */: - case 207 /* ForInStatement */: + case 210 /* WhileStatement */: + case 208 /* IfStatement */: + case 212 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 219 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 224 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -74438,23 +80155,23 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 193 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 169 /* BindingElement */) { + if (bindingPattern.parent.kind === 174 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 168 /* ArrayBindingPattern */ && node.kind !== 167 /* ObjectBindingPattern */); - var elements = node.kind === 170 /* ArrayLiteralExpression */ ? + ts.Debug.assert(node.kind !== 173 /* ArrayBindingPattern */ && node.kind !== 172 /* ObjectBindingPattern */); + var elements = node.kind === 175 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 193 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -74462,18 +80179,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 187 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 192 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 224 /* EnumDeclaration */: + case 229 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 221 /* ClassDeclaration */: + case 226 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -74481,24 +80198,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 226 /* ModuleBlock */: + case 231 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 224 /* EnumDeclaration */: - case 221 /* ClassDeclaration */: + case 229 /* EnumDeclaration */: + case 226 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 199 /* Block */: + case 204 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through - case 252 /* CatchClause */: + case 256 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 227 /* CaseBlock */: + case 232 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -74506,7 +80223,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 167 /* ObjectBindingPattern */: + case 172 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -74522,7 +80239,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 168 /* ArrayBindingPattern */: + case 173 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -74537,12 +80254,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 204 /* DoStatement */ || - node.parent.kind === 174 /* CallExpression */ || - node.parent.kind === 175 /* NewExpression */) { + if (node.parent.kind === 209 /* DoStatement */ || + node.parent.kind === 179 /* CallExpression */ || + node.parent.kind === 180 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 178 /* ParenthesizedExpression */) { + if (node.parent.kind === 183 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -74551,21 +80268,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 179 /* FunctionExpression */: - case 220 /* FunctionDeclaration */: - case 180 /* ArrowFunction */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 205 /* WhileStatement */: - case 204 /* DoStatement */: - case 206 /* ForStatement */: - case 208 /* ForOfStatement */: - case 174 /* CallExpression */: - case 175 /* NewExpression */: - case 178 /* ParenthesizedExpression */: + case 184 /* FunctionExpression */: + case 225 /* FunctionDeclaration */: + case 185 /* ArrowFunction */: + case 149 /* MethodDeclaration */: + case 148 /* MethodSignature */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + case 150 /* Constructor */: + case 210 /* WhileStatement */: + case 209 /* DoStatement */: + case 211 /* ForStatement */: + case 213 /* ForOfStatement */: + case 179 /* CallExpression */: + case 180 /* NewExpression */: + case 183 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -74575,20 +80292,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 253 /* PropertyAssignment */ || - node.parent.kind === 142 /* Parameter */) { + node.parent.kind === 257 /* PropertyAssignment */ || + node.parent.kind === 144 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 177 /* TypeAssertionExpression */) { + if (node.parent.kind === 182 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 204 /* DoStatement */) { + if (node.parent.kind === 209 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -74596,7 +80313,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 208 /* ForOfStatement */) { + if (node.parent.kind === 213 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -74624,7 +80341,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74678,7 +80395,7 @@ var ts; var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -74712,6 +80429,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74769,7 +80492,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -74818,7 +80541,7 @@ var ts; // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. try { - var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, 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) { @@ -74892,7 +80615,7 @@ var ts; this.factory = factory; factory.registerShim(this); } - ShimBase.prototype.dispose = function (dummy) { + ShimBase.prototype.dispose = function (_dummy) { this.factory.unregisterShim(this); }; return ShimBase; @@ -74914,11 +80637,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +80880,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +80910,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +80937,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75221,8 +80951,15 @@ var ts; return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (resolvedFileName && !compilerOptions.allowJs && ts.fileExtensionIs(resolvedFileName, ".js")) { + return { + resolvedFileName: undefined, + failedLookupLocations: [] + }; + } return { - resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations }; }); @@ -75283,7 +81020,7 @@ var ts; if (result.error) { return { options: {}, - typingOptions: {}, + typeAcquisition: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] @@ -75293,7 +81030,7 @@ var ts; var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, - typingOptions: configFile.typingOptions, + typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") @@ -75308,7 +81045,7 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typingOptions, info.compilerOptions); + return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -75391,9 +81128,7 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -/* tslint:disable:no-unused-variable */ // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.1"; -/* tslint:enable:no-unused-variable */ +var toolsVersion = "2.2"; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index b1248c700fa..d8cd324a8d2 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -1,18 +1,18 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -26,12 +26,13 @@ var ts; return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; - })(ts.ExitStatus || (ts.ExitStatus = {})); - var ExitStatus = ts.ExitStatus; + })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; @@ -44,41 +45,47 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; - })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; - })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); - var DiagnosticCategory = ts.DiagnosticCategory; + })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var ModuleResolutionKind; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); - var ModuleResolutionKind = ts.ModuleResolutionKind; + })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleKind; (function (ModuleKind) { ModuleKind[ModuleKind["None"] = 0] = "None"; ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; - ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; - })(ts.ModuleKind || (ts.ModuleKind = {})); - var ModuleKind = ts.ModuleKind; + })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); + var Extension; + (function (Extension) { + Extension[Extension["Ts"] = 0] = "Ts"; + Extension[Extension["Tsx"] = 1] = "Tsx"; + Extension[Extension["Dts"] = 2] = "Dts"; + Extension[Extension["Js"] = 3] = "Js"; + Extension[Extension["Jsx"] = 4] = "Jsx"; + Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + })(Extension = ts.Extension || (ts.Extension = {})); })(ts || (ts = {})); var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : function (markName) { }; + : function (_markName) { }; var enabled = false; var profilerStart = 0; var counts; @@ -129,8 +136,12 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + ts.version = "2.2.0"; +})(ts || (ts = {})); (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -151,7 +162,7 @@ var ts; remove: remove, forEachValue: forEachValueInMap, getKeys: getKeys, - clear: clear + clear: clear, }; function forEachValueInMap(f) { for (var key in files) { @@ -205,6 +216,13 @@ var ts; return undefined; } ts.forEach = forEach; + function zipWith(arrayA, arrayB, callback) { + Debug.assert(arrayA.length === arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + ts.zipWith = zipWith; function every(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -336,13 +354,32 @@ var ts; if (array) { result = []; for (var i = 0; i < array.length; i++) { - var v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } ts.map = map; + function sameMap(array, f) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameMap = sameMap; function flatten(array) { var result; if (array) { @@ -443,10 +480,27 @@ var ts; return result; } ts.mapObject = mapObject; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; function concatenate(array1, array2) { - if (!array2 || !array2.length) + if (!some(array2)) return array1; - if (!array1 || !array1.length) + if (!some(array1)) return array2; return array1.concat(array2); } @@ -455,8 +509,8 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { var res = result_1[_a]; if (areEqual ? areEqual(res, item) : res === item) { @@ -469,6 +523,41 @@ var ts; return result; } ts.deduplicate = deduplicate; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; function compact(array) { var result; if (array) { @@ -487,26 +576,62 @@ var ts; return result || array; } ts.compact = compact; + function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { + if (comparer === void 0) { comparer = compareValues; } + if (offsetA === void 0) { offsetA = 0; } + if (offsetB === void 0) { offsetB = 0; } + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1: break inner; + case 0: continue outer; + case 1: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + ts.relativeComplement = relativeComplement; 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; } ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; function addRange(to, from) { - if (to && from) { - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - if (v !== undefined) { - to.push(v); - } - } + if (from === undefined) + return to; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; + to = append(to, v); } + return to; } ts.addRange = addRange; + function stableSort(array, comparer) { + if (comparer === void 0) { comparer = compareValues; } + return array + .map(function (_, i) { return i; }) + .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) + .map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -523,6 +648,12 @@ var ts; : undefined; } ts.firstOrUndefined = firstOrUndefined; + function lastOrUndefined(array) { + return array && array.length > 0 + ? array[array.length - 1] + : undefined; + } + ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -535,17 +666,17 @@ var ts; : array; } ts.singleOrMany = singleOrMany; - function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; } - ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value, comparer) { + ts.replaceElement = replaceElement; + function binarySearch(array, value, comparer, offset) { if (!array || array.length === 0) { return -1; } - var low = 0; + var low = offset || 0; var high = array.length - 1; comparer = comparer !== undefined ? comparer @@ -655,6 +786,15 @@ var ts; } } ts.copyProperties = copyProperties; + function appendProperty(map, key, value) { + if (key === undefined || value === undefined) + return map; + if (map === undefined) + map = createMap(); + map[key] = value; + return map; + } + ts.appendProperty = appendProperty; function assign(t) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -678,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -709,8 +840,8 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; result[makeKey(value)] = makeValue ? makeValue(value) : value; } return result; @@ -779,6 +910,12 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function noop() { } + ts.noop = noop; + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; function memoize(callback) { var value; return function () { @@ -790,9 +927,59 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { @@ -817,11 +1004,11 @@ var ts; length: length, messageText: text, category: message.category, - code: message.code + code: message.code, }; } ts.createFileDiagnostic = createFileDiagnostic; - function formatMessage(dummy, message) { + function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -844,6 +1031,17 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; function chainDiagnosticMessages(details, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -884,7 +1082,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1037,9 +1235,17 @@ var ts; function getEmitModuleKind(compilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -1236,6 +1442,10 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function hasExtension(fileName) { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); } @@ -1263,68 +1473,83 @@ var ts; var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; - spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + 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 += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - subpattern += ts.directorySeparator; - } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } if (!pattern) { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter) { + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + var lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + if (usage !== "exclude") { + if (component.charCodeAt(0) === 42) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } function replaceWildCardCharacterFiles(match) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); } @@ -1334,7 +1559,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); @@ -1349,7 +1574,7 @@ var ts; 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 patterns = getFileMatcherPatterns(path, 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); @@ -1391,25 +1616,30 @@ var ts; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - var includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } 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; - } + var _loop_1 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); } - basePaths.push(includeBasePath); + }; + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_1(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute) { + var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -1434,8 +1664,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1446,11 +1687,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -1509,10 +1750,6 @@ var ts; return path.substring(0, path.length - extension.length); } ts.removeExtension = removeExtension; - function isJsxOrTsxExtension(ext) { - return ext === ".jsx" || ext === ".tsx"; - } - ts.isJsxOrTsxExtension = isJsxOrTsxExtension; function changeExtension(path, newExtension) { return (removeFileExtension(path) + newExtension); } @@ -1522,10 +1759,10 @@ var ts; this.name = name; this.declarations = undefined; } - function Type(checker, flags) { + function Type(_checker, flags) { this.flags = flags; } - function Signature(checker) { + function Signature() { } function Node(kind, pos, end) { this.id = 0; @@ -1537,7 +1774,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1550,9 +1786,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1570,30 +1806,17 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; + return false; } - ts.getEnvironmentVariable = getEnvironmentVariable; + ts.orderedRemoveItem = orderedRemoveItem; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1624,10 +1847,94 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; function positionIsSynthesized(pos) { return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; + function extensionIsTypeScript(ext) { + return ext <= ts.Extension.LastTypeScriptExtension; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function tryGetExtensionFromPath(path) { + if (fileExtensionIs(path, ".d.ts")) { + return ts.Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return ts.Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return ts.Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return ts.Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return ts.Extension.Jsx; + } + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; })(ts || (ts = {})); var ts; (function (ts) { @@ -1821,9 +2128,15 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; - function readFile(fileName, encoding) { + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; } @@ -1916,6 +2229,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } + var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -1925,7 +2239,7 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (fileName, callback, pollingInterval) { if (useNonPollingWatchers) { var watchedFile_1 = watchedFileSet.addFile(fileName, callback); return { @@ -1933,7 +2247,7 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: function () { return _fs.unwatchFile(fileName, fileChanged); } }; @@ -1947,6 +2261,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -2022,7 +2339,9 @@ var ts; } catch (e) { } - } + }, + setTimeout: setTimeout, + clearTimeout: clearTimeout }; return nodeSystem; } @@ -2033,7 +2352,7 @@ var ts; args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile: function (path, encoding) { + readFile: function (path, _encoding) { return ChakraHost.readFile(path); }, writeFile: function (path, data, writeByteOrderMark) { @@ -2049,9 +2368,9 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function (name) { return ""; }), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), readDirectory: function (path, extensions, excludes, includes) { - var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, @@ -2090,6 +2409,11 @@ var ts; } return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2135,7 +2459,7 @@ var ts; A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_1055", message: "Type '{0}' is not a valid async function return type." }, + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." }, @@ -2245,7 +2569,6 @@ var ts; Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_name_must_be_an_identifier_1195", message: "Catch clause variable name must be an identifier." }, Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, @@ -2308,6 +2631,7 @@ var ts; 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." }, + An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, 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." }, @@ -2351,6 +2675,7 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." }, @@ -2361,16 +2686,17 @@ var ts; Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_of_assignment_expression_2364", message: "Invalid left-hand side of assignment expression." }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" }, @@ -2410,11 +2736,11 @@ var ts; Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_in_statement_2406", message: "Invalid left-hand side in 'for...in' statement." }, + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2448,8 +2774,6 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2461,7 +2785,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_an_array_destructuring_pattern_2462", message: "A rest element must be last in an array destructuring pattern" }, + A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" }, A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, @@ -2483,9 +2807,7 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, - Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, @@ -2532,6 +2854,13 @@ var ts; Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, + Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, + Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, + Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, + Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, + Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2555,6 +2884,7 @@ var ts; Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, @@ -2575,7 +2905,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, 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" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, 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'?" }, @@ -2586,6 +2916,11 @@ var ts; Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, + Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, + Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, 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}'." }, @@ -2656,7 +2991,10 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, 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}'." }, @@ -2685,6 +3023,7 @@ var ts; Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2697,7 +3036,7 @@ var ts; Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, @@ -2768,7 +3107,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_types_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_types_field_6100", message: "'package.json' does not have 'types' field." }, + package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -2805,10 +3144,16 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, + No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, + Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, + Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2817,7 +3162,8 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, @@ -2833,6 +3179,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2850,6 +3197,7 @@ var ts; 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." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, + Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, @@ -2860,141 +3208,157 @@ var ts; A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, + Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, + The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }, + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" }, + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, + Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" }, + Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" }, + Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" }, }; })(ts || (ts = {})); var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { - return token >= 69; + return token >= 70; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; var textToToken = ts.createMap({ - "abstract": 115, - "any": 117, - "as": 116, - "boolean": 120, - "break": 70, - "case": 71, - "catch": 72, - "class": 73, - "continue": 75, - "const": 74, - "constructor": 121, - "debugger": 76, - "declare": 122, - "default": 77, - "delete": 78, - "do": 79, - "else": 80, - "enum": 81, - "export": 82, - "extends": 83, - "false": 84, - "finally": 85, - "for": 86, - "from": 136, - "function": 87, - "get": 123, - "if": 88, - "implements": 106, - "import": 89, - "in": 90, - "instanceof": 91, - "interface": 107, - "is": 124, - "let": 108, - "module": 125, - "namespace": 126, - "never": 127, - "new": 92, - "null": 93, - "number": 130, - "package": 109, - "private": 110, - "protected": 111, - "public": 112, - "readonly": 128, - "require": 129, - "global": 137, - "return": 94, - "set": 131, - "static": 113, - "string": 132, - "super": 95, - "switch": 96, - "symbol": 133, - "this": 97, - "throw": 98, - "true": 99, - "try": 100, - "type": 134, - "typeof": 101, - "undefined": 135, - "var": 102, - "void": 103, - "while": 104, - "with": 105, - "yield": 114, - "async": 118, - "await": 119, - "of": 138, - "{": 15, - "}": 16, - "(": 17, - ")": 18, - "[": 19, - "]": 20, - ".": 21, - "...": 22, - ";": 23, - ",": 24, - "<": 25, - ">": 27, - "<=": 28, - ">=": 29, - "==": 30, - "!=": 31, - "===": 32, - "!==": 33, - "=>": 34, - "+": 35, - "-": 36, - "**": 38, - "*": 37, - "/": 39, - "%": 40, - "++": 41, - "--": 42, - "<<": 43, - ">": 44, - ">>>": 45, - "&": 46, - "|": 47, - "^": 48, - "!": 49, - "~": 50, - "&&": 51, - "||": 52, - "?": 53, - ":": 54, - "=": 56, - "+=": 57, - "-=": 58, - "*=": 59, - "**=": 60, - "/=": 61, - "%=": 62, - "<<=": 63, - ">>=": 64, - ">>>=": 65, - "&=": 66, - "|=": 67, - "^=": 68, - "@": 55 + "abstract": 116, + "any": 118, + "as": 117, + "boolean": 121, + "break": 71, + "case": 72, + "catch": 73, + "class": 74, + "continue": 76, + "const": 75, + "constructor": 122, + "debugger": 77, + "declare": 123, + "default": 78, + "delete": 79, + "do": 80, + "else": 81, + "enum": 82, + "export": 83, + "extends": 84, + "false": 85, + "finally": 86, + "for": 87, + "from": 138, + "function": 88, + "get": 124, + "if": 89, + "implements": 107, + "import": 90, + "in": 91, + "instanceof": 92, + "interface": 108, + "is": 125, + "keyof": 126, + "let": 109, + "module": 127, + "namespace": 128, + "never": 129, + "new": 93, + "null": 94, + "number": 132, + "package": 110, + "private": 111, + "protected": 112, + "public": 113, + "readonly": 130, + "require": 131, + "global": 139, + "return": 95, + "set": 133, + "static": 114, + "string": 134, + "super": 96, + "switch": 97, + "symbol": 135, + "this": 98, + "throw": 99, + "true": 100, + "try": 101, + "type": 136, + "typeof": 102, + "undefined": 137, + "var": 103, + "void": 104, + "while": 105, + "with": 106, + "yield": 115, + "async": 119, + "await": 120, + "of": 140, + "{": 16, + "}": 17, + "(": 18, + ")": 19, + "[": 20, + "]": 21, + ".": 22, + "...": 23, + ";": 24, + ",": 25, + "<": 26, + ">": 28, + "<=": 29, + ">=": 30, + "==": 31, + "!=": 32, + "===": 33, + "!==": 34, + "=>": 35, + "+": 36, + "-": 37, + "**": 39, + "*": 38, + "/": 40, + "%": 41, + "++": 42, + "--": 43, + "<<": 44, + ">": 45, + ">>>": 46, + "&": 47, + "|": 48, + "^": 49, + "!": 50, + "~": 51, + "&&": 52, + "||": 53, + "?": 54, + ":": 55, + "=": 57, + "+=": 58, + "-=": 59, + "*=": 60, + "**=": 61, + "/=": 62, + "%=": 63, + "<<=": 64, + ">>=": 65, + ">>>=": 66, + "&=": 67, + "|=": 68, + "^=": 69, + "@": 56, }); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -3391,7 +3755,7 @@ var ts; return iterateCommentRanges(true, text, pos, true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; - function appendCommentRange(pos, end, kind, hasTrailingNewLine, state, comments) { + function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { if (!comments) { comments = []; } @@ -3457,8 +3821,8 @@ var ts; getTokenValue: function () { return tokenValue; }, hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 69 || token > 105; }, - isReservedWord: function () { return token >= 70 && token <= 105; }, + isIdentifier: function () { return token === 70 || token > 106; }, + isReservedWord: function () { return token >= 71 && token <= 106; }, isUnterminated: function () { return tokenIsUnterminated; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, @@ -3477,7 +3841,7 @@ var ts; setTextPos: setTextPos, tryScan: tryScan, lookAhead: lookAhead, - scanRange: scanRange + scanRange: scanRange, }; function error(message, length) { if (onError) { @@ -3594,20 +3958,20 @@ var ts; contents += text.substring(start, pos); tokenIsUnterminated = true; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } var currChar = text.charCodeAt(pos); if (currChar === 96) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 11 : 14; + resultingToken = startedWithBacktick ? 12 : 15; break; } if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 12 : 13; + resultingToken = startedWithBacktick ? 13 : 14; break; } if (currChar === 92) { @@ -3769,10 +4133,10 @@ var ts; return token = textToToken[tokenValue]; } } - return token = 69; + return token = 70; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -3844,12 +4208,12 @@ var ts; case 33: if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 33; + return pos += 3, token = 34; } - return pos += 2, token = 31; + return pos += 2, token = 32; } pos++; - return token = 49; + return token = 50; case 34: case 39: tokenValue = scanString(); @@ -3858,51 +4222,39 @@ var ts; return token = scanTemplateAndSetTokenValue(); case 37: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 62; + return pos += 2, token = 63; } pos++; - return token = 40; + return token = 41; case 38: if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 51; + return pos += 2, token = 52; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + return pos += 2, token = 67; } pos++; - return token = 46; + return token = 47; case 40: pos++; - return token = 17; + return token = 18; case 41: pos++; - return token = 18; + return token = 19; case 42: if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; + return pos += 2, token = 60; } if (text.charCodeAt(pos + 1) === 42) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 60; + return pos += 3, token = 61; } - return pos += 2, token = 38; + return pos += 2, token = 39; } pos++; - return token = 37; + return token = 38; case 43: if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 41; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 57; - } - pos++; - return token = 35; - case 44: - pos++; - return token = 24; - case 45: - if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; } if (text.charCodeAt(pos + 1) === 61) { @@ -3910,16 +4262,28 @@ var ts; } pos++; return token = 36; + case 44: + pos++; + return token = 25; + case 45: + if (text.charCodeAt(pos + 1) === 45) { + return pos += 2, token = 43; + } + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 59; + } + pos++; + return token = 37; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 22; + return pos += 3, token = 23; } pos++; - return token = 21; + return token = 22; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -3963,10 +4327,10 @@ var ts; } } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; + return pos += 2, token = 62; } pos++; - return token = 39; + return token = 40; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -4015,10 +4379,10 @@ var ts; return token = 8; case 58: pos++; - return token = 54; + return token = 55; case 59: pos++; - return token = 23; + return token = 24; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -4031,20 +4395,20 @@ var ts; } if (text.charCodeAt(pos + 1) === 60) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 63; + return pos += 3, token = 64; } - return pos += 2, token = 43; + return pos += 2, token = 44; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 28; + return pos += 2, token = 29; } if (languageVariant === 1 && text.charCodeAt(pos + 1) === 47 && text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 26; + return pos += 2, token = 27; } pos++; - return token = 25; + return token = 26; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -4057,15 +4421,15 @@ var ts; } if (text.charCodeAt(pos + 1) === 61) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 32; + return pos += 3, token = 33; } - return pos += 2, token = 30; + return pos += 2, token = 31; } if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 34; + return pos += 2, token = 35; } pos++; - return token = 56; + return token = 57; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -4077,43 +4441,43 @@ var ts; } } pos++; - return token = 27; + return token = 28; case 63: pos++; - return token = 53; + return token = 54; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 94: + if (text.charCodeAt(pos + 1) === 61) { + return pos += 2, token = 69; + } + pos++; + return token = 49; + case 123: + pos++; + return token = 16; + case 124: + if (text.charCodeAt(pos + 1) === 124) { + return pos += 2, token = 53; + } if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } pos++; return token = 48; - case 123: - pos++; - return token = 15; - case 124: - if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 52; - } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 67; - } - pos++; - return token = 47; case 125: pos++; - return token = 16; + return token = 17; case 126: pos++; - return token = 50; + return token = 51; case 64: pos++; - return token = 55; + return token = 56; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -4151,29 +4515,29 @@ var ts; } } function reScanGreaterToken() { - if (token === 27) { + if (token === 28) { if (text.charCodeAt(pos) === 62) { if (text.charCodeAt(pos + 1) === 62) { if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + return pos += 3, token = 66; } - return pos += 2, token = 45; + return pos += 2, token = 46; } if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + return pos += 2, token = 65; } pos++; - return token = 44; + return token = 45; } if (text.charCodeAt(pos) === 61) { pos++; - return token = 29; + return token = 30; } } return token; } function reScanSlashToken() { - if (token === 39 || token === 61) { + if (token === 40 || token === 62) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; @@ -4212,12 +4576,12 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 10; + token = 11; } return token; } function reScanTemplateToken() { - ts.Debug.assert(token === 16, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 17, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -4234,14 +4598,14 @@ var ts; if (char === 60) { if (text.charCodeAt(pos + 1) === 47) { pos += 2; - return token = 26; + return token = 27; } pos++; - return token = 25; + return token = 26; } if (char === 123) { pos++; - return token = 15; + return token = 16; } while (pos < end) { pos++; @@ -4250,7 +4614,7 @@ var ts; break; } } - return token = 244; + return token = 10; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -4297,39 +4661,42 @@ var ts; return token = 5; case 64: pos++; - return token = 55; + return token = 56; case 10: case 13: pos++; return token = 4; case 42: pos++; - return token = 37; + return token = 38; case 123: pos++; - return token = 15; + return token = 16; case 125: pos++; - return token = 16; + return token = 17; case 91: pos++; - return token = 19; + return token = 20; case 93: pos++; - return token = 20; + return token = 21; case 61: pos++; - return token = 56; + return token = 57; case 44: pos++; - return token = 24; + return token = 25; + case 46: + pos++; + return token = 22; } - if (isIdentifierStart(ch, 2)) { + if (isIdentifierStart(ch, 5)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { pos++; } - return token = 69; + return token = 70; } else { return pos += 1, token = 0; @@ -4419,24 +4786,24 @@ var ts; ts.optionDeclarations = [ { name: "charset", - type: "string" + type: "string", }, ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_d_ts_file + description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, { name: "declarationDir", type: "string", isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "diagnostics", - type: "boolean" + type: "boolean", }, { name: "extendedDiagnostics", @@ -4451,7 +4818,7 @@ var ts; name: "help", shortName: "h", type: "boolean", - description: ts.Diagnostics.Print_this_message + description: ts.Diagnostics.Print_this_message, }, { name: "help", @@ -4461,15 +4828,15 @@ var ts; { name: "init", type: "boolean", - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, }, { name: "inlineSourceMap", - type: "boolean" + type: "boolean", }, { name: "inlineSources", - type: "boolean" + type: "boolean", }, { name: "jsx", @@ -4478,27 +4845,32 @@ var ts; "react": 2 }), paramType: ts.Diagnostics.KIND, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, }, { name: "reactNamespace", type: "string", description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", - type: "boolean" + type: "boolean", }, { name: "locale", - type: "string" + type: "string", }, { name: "mapRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "module", @@ -4509,11 +4881,11 @@ var ts; "amd": ts.ModuleKind.AMD, "system": ts.ModuleKind.System, "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES6, - "es2015": ts.ModuleKind.ES2015 + "es6": ts.ModuleKind.ES2015, + "es2015": ts.ModuleKind.ES2015, }), description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, - paramType: ts.Diagnostics.KIND + paramType: ts.Diagnostics.KIND, }, { name: "newLine", @@ -4522,12 +4894,12 @@ var ts; "lf": 1 }), description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - paramType: ts.Diagnostics.NEWLINE + paramType: ts.Diagnostics.NEWLINE, }, { name: "noEmit", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs + description: ts.Diagnostics.Do_not_emit_outputs, }, { name: "noEmitHelpers", @@ -4536,7 +4908,7 @@ var ts; { name: "noEmitOnError", type: "boolean", - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, }, { name: "noErrorTruncation", @@ -4545,59 +4917,59 @@ var ts; { name: "noImplicitAny", type: "boolean", - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, { name: "noImplicitThis", type: "boolean", - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_errors_on_unused_locals, }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_errors_on_unused_parameters, }, { name: "noLib", - type: "boolean" + type: "boolean", }, { name: "noResolve", - type: "boolean" + type: "boolean", }, { name: "skipDefaultLibCheck", - type: "boolean" + type: "boolean", }, { name: "skipLibCheck", type: "boolean", - description: ts.Diagnostics.Skip_type_checking_of_declaration_files + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, }, { name: "out", type: "string", isFilePath: false, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outFile", type: "string", isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - paramType: ts.Diagnostics.FILE + paramType: ts.Diagnostics.FILE, }, { name: "outDir", type: "string", isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - paramType: ts.Diagnostics.DIRECTORY + paramType: ts.Diagnostics.DIRECTORY, }, { name: "preserveConstEnums", @@ -4620,30 +4992,30 @@ var ts; { name: "removeComments", type: "boolean", - description: ts.Diagnostics.Do_not_emit_comments_to_output + description: ts.Diagnostics.Do_not_emit_comments_to_output, }, { name: "rootDir", type: "string", isFilePath: true, paramType: ts.Diagnostics.LOCATION, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", - type: "boolean" + type: "boolean", }, { name: "sourceMap", type: "boolean", - description: ts.Diagnostics.Generates_corresponding_map_file + description: ts.Diagnostics.Generates_corresponding_map_file, }, { name: "sourceRoot", type: "string", isFilePath: true, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - paramType: ts.Diagnostics.LOCATION + paramType: ts.Diagnostics.LOCATION, }, { name: "suppressExcessPropertyErrors", @@ -4654,7 +5026,7 @@ var ts; { name: "suppressImplicitAnyIndexErrors", type: "boolean", - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, { name: "stripInternal", @@ -4669,22 +5041,25 @@ var ts; "es3": 0, "es5": 1, "es6": 2, - "es2015": 2 + "es2015": 2, + "es2016": 3, + "es2017": 4, + "esnext": 5, }), - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, - paramType: ts.Diagnostics.VERSION + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + paramType: ts.Diagnostics.VERSION, }, { name: "version", shortName: "v", type: "boolean", - description: ts.Diagnostics.Print_the_compiler_s_version + description: ts.Diagnostics.Print_the_compiler_s_version, }, { name: "watch", shortName: "w", type: "boolean", - description: ts.Diagnostics.Watch_input_files + description: ts.Diagnostics.Watch_input_files, }, { name: "experimentalDecorators", @@ -4701,10 +5076,10 @@ var ts; name: "moduleResolution", type: ts.createMap({ "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic + "classic": ts.ModuleResolutionKind.Classic, }), description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - paramType: ts.Diagnostics.STRATEGY + paramType: ts.Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -4826,8 +5201,9 @@ var ts; "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", + }), }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4844,12 +5220,21 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; - ts.typingOptionDeclarations = [ + ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", - type: "boolean" + type: "boolean", + }, + { + name: "enable", + type: "boolean", }, { name: "include", @@ -4872,9 +5257,21 @@ var ts; module: ts.ModuleKind.CommonJS, target: 1, noImplicitAny: false, - sourceMap: false + sourceMap: false, }; var optionNameMapCache; + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + var result = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -4892,22 +5289,12 @@ var ts; } ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = []; - for (var key in opt.type) { - namesOfType.push(" '" + key + "'"); - } + var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", "); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -4969,7 +5356,11 @@ var ts; i++; break; case "boolean": - options[opt.name] = true; + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -5143,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5153,14 +5545,15 @@ var ts; return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))], wildcardDirectories: {} }; } var options = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { var _a = [undefined, undefined, undefined, {}], include = _a[0], exclude = _a[1], files = _a[2], baseOptions = _a[3]; if (typeof json["extends"] === "string") { @@ -5187,7 +5580,7 @@ var ts; return { options: options, fileNames: fileNames, - typingOptions: typingOptions, + typeAcquisition: typeAcquisition, raw: json, errors: errors, wildcardDirectories: wildcardDirectories, @@ -5195,7 +5588,7 @@ var ts; }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); @@ -5228,6 +5621,9 @@ var ts; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -5255,7 +5651,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { excludeSpecs.push(outDir); @@ -5264,7 +5660,11 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + } + return result; } var _b; } @@ -5286,24 +5686,23 @@ var ts; return { options: options, errors: errors }; } ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypingOptionsFromJson(jsonOptions, basePath, configFileName) { + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { var errors = []; - var options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options: options, errors: errors }; } - ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true } + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(ts.typingOptionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_typing_option_0, errors); + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { @@ -5365,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5377,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -5433,14 +5832,13 @@ var ts; var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_6 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_6)) { + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - var match = wildcardDirectoryPattern.exec(name_6); + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_6) ? 1 : 0; + var key = match.key, flags = match.flags; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -5461,6 +5859,19 @@ var ts; } return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 : 0 + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 }; + } + return undefined; + } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); @@ -5501,9 +5912,18 @@ var ts; ; var safeList; var EmptySafeList = ts.createMap(); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + JsTyping.nodeCoreModuleList = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console" + ]; + var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { + if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { @@ -5517,10 +5937,10 @@ var ts; var filesToWatch = []; var searchDirs = []; var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { + if (projectRootPath) { possibleSearchDirs.push(projectRootPath); } searchDirs = ts.deduplicate(possibleSearchDirs); @@ -5534,13 +5954,22 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); - for (var name_7 in packageNameToTypingLocation) { - if (name_7 in inferredTypings && !inferredTypings[name_7]) { - inferredTypings[name_7] = packageNameToTypingLocation[name_7]; + if (unresolvedImports) { + for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { + var moduleId = unresolvedImports_1[_a]; + var typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } } } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; + for (var name_6 in packageNameToTypingLocation) { + if (name_6 in inferredTypings && !inferredTypings[name_6]) { + inferredTypings[name_6] = packageNameToTypingLocation[name_6]; + } + } + for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { + var excludeTypingName = exclude_1[_b]; delete inferredTypings[excludeTypingName]; } var newTypingNames = []; @@ -5566,10 +5995,12 @@ var ts; } } function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -5636,7 +6067,34 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function trace(host, message) { + var server; + (function (server) { + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { host.trace(ts.formatMessage.apply(undefined, arguments)); } ts.trace = trace; @@ -5644,24 +6102,51 @@ var ts; return compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function resolvedFromAnyFile(path) { + return { path: path, extension: ts.extensionFromPath(path) }; + } + function resolvedModuleFromResolved(_a, isExternalLibraryImport) { + var path = _a.path, extension = _a.extension; + return { resolvedFileName: path, extension: extension, isExternalLibraryImport: isExternalLibraryImport }; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations: failedLookupLocations }; } - ts.createResolvedModule = createResolvedModule; function moduleHasNonRelativeName(moduleName) { return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; + function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case 2: + case 0: + return tryReadFromField("typings") || tryReadFromField("types"); + case 1: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } function tryReadFromField(fieldName) { if (ts.hasProperty(jsonContent, fieldName)) { var typesFile = jsonContent[fieldName]; if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); } - return typesFilePath_1; + return typesFilePath; } else { if (state.traceEnabled) { @@ -5670,18 +6155,6 @@ var ts; } } } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; } function readJson(path, host) { try { @@ -5692,7 +6165,6 @@ var ts; return {}; } } - var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -5704,7 +6176,9 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } } ts.getEffectiveTypeRoots = getEffectiveTypeRoots; function getDefaultTypeRoots(currentDirectory, host) { @@ -5712,17 +6186,12 @@ var ts; return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; } var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + forEachAncestorDirectory(currentDirectory, function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); } - var parent_1 = ts.getDirectoryPath(currentDirectory); - if (parent_1 === currentDirectory) { - break; - } - currentDirectory = parent_1; - } + }); return typeRoots; } var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); @@ -5731,7 +6200,6 @@ var ts; var moduleResolutionState = { compilerOptions: options, host: host, - skipTsx: true, traceEnabled: traceEnabled }; var typeRoots = getEffectiveTypeRoots(options, host); @@ -5754,62 +6222,57 @@ var ts; } } var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); } - 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) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - else { + resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState)); + if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } } } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; function getAutomaticTypeDirectiveNames(options, host) { @@ -5876,15 +6339,15 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); } else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); } } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -5918,7 +6381,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -5935,7 +6398,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -5946,7 +6409,7 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { if (!state.compilerOptions.baseUrl) { return undefined; } @@ -5958,131 +6421,90 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; + var tsExtension = ts.tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, false, state); + return path_1 && { path: path_1, extension: tsExtension }; } - } - return undefined; + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); } else { var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var result = tryResolve(0) || tryResolve(1); + if (result) { + var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return { resolved: resolved, isExternalLibraryImport: false }; + } if (moduleHasNonRelativeName(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); - isExternalLibraryImport = resolvedFileName !== undefined; + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state); + return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true }; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false }; } } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } @@ -6092,21 +6514,30 @@ var ts; var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); } } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); + switch (extensions) { + case 2: + return tryExtension(".d.ts", ts.Extension.Dts); + case 0: + return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + case 1: + return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + } + function tryExtension(ext, extension) { + var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); @@ -6117,29 +6548,32 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); } - failedLookupLocation.push(fileName); + failedLookupLocations.push(fileName); return undefined; } } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { var packageJsonPath = pathToPackageJson(candidate); var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state); if (typesFile) { var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; + var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state); + if (fromFile) { + return resolvedFromAnyFile(fromFile); + } + var x = tryAddingExtensions(typesFile, 0, failedLookupLocations, onlyRecordFailures_1, state); + if (x) { + return x; } } else { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); } } } @@ -6147,86 +6581,98 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } - failedLookupLocation.push(packageJsonPath); + failedLookupLocations.push(packageJsonPath); } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } function pathToPackageJson(directory) { return ts.combinePaths(directory, "package.json"); } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(2, moduleName, directory, failedLookupLocations, state, true); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly); + } + }); + } + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; + if (extensions !== 1) { + return loadModuleFromNodeModulesFolder(2, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); } } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(0) || tryResolve(1); + return createResolvedModuleWithFailedLookupLocations(resolved, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return resolvedUsingSettings; + } + if (moduleHasNonRelativeName(moduleName)) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state); + }); + if (resolved_3) { + return resolved_3; } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } + if (extensions === 0) { + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); } } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(2, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; + if (parentPath === directory) { + return undefined; } directory = parentPath; } - return undefined; } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; })(ts || (ts = {})); var ts; (function (ts) { @@ -6236,19 +6682,58 @@ var ts; (function (typingsInstaller) { var nullLog = { isEnabled: function () { return false; }, - writeLine: function () { } + writeLine: ts.noop }; - function typingToFileName(cachePath, packageName, installTypingHost) { - var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost); - return result.resolvedModule && result.resolvedModule.resolvedFileName; + function typingToFileName(cachePath, packageName, installTypingHost, log) { + try { + var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost); + return result.resolvedModule && result.resolvedModule.resolvedFileName; + } + catch (e) { + if (log.isEnabled()) { + log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message); + } + return undefined; + } } - typingsInstaller.NpmViewRequest = "npm view"; - typingsInstaller.NpmInstallRequest = "npm install"; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {})); + typingsInstaller.MaxPackageNameLength = 214; + function validatePackageName(packageName) { + if (!packageName) { + return PackageNameValidationResult.EmptyName; + } + if (packageName.length > typingsInstaller.MaxPackageNameLength) { + return PackageNameValidationResult.NameTooLong; + } + if (packageName.charCodeAt(0) === 46) { + return PackageNameValidationResult.NameStartsWithDot; + } + if (packageName.charCodeAt(0) === 95) { + return PackageNameValidationResult.NameStartsWithUnderscore; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return PackageNameValidationResult.ScopedPackagesNotSupported; + } + if (encodeURIComponent(packageName) !== packageName) { + return PackageNameValidationResult.NameContainsNonURISafeCharacters; + } + return PackageNameValidationResult.Ok; + } + typingsInstaller.validatePackageName = validatePackageName; var TypingsInstaller = (function () { - function TypingsInstaller(globalCachePath, npmPath, safeListPath, throttleLimit, log) { + function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, throttleLimit, log) { if (log === void 0) { log = nullLog; } + this.installTypingHost = installTypingHost; this.globalCachePath = globalCachePath; - this.npmPath = npmPath; this.safeListPath = safeListPath; this.throttleLimit = throttleLimit; this.log = log; @@ -6262,10 +6747,8 @@ var ts; if (this.log.isEnabled()) { this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "'"); } - } - TypingsInstaller.prototype.init = function () { this.processCacheLocation(this.globalCachePath); - }; + } TypingsInstaller.prototype.closeProject = function (req) { this.closeWatchers(req.projectName); }; @@ -6299,7 +6782,7 @@ var ts; } this.processCacheLocation(req.cachePath); } - var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, req.fileNames, req.projectRootPath, this.safeListPath, this.packageNameToTypingLocation, req.typingOptions, req.compilerOptions); + var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, req.fileNames, req.projectRootPath, this.safeListPath, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); if (this.log.isEnabled()) { this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult)); } @@ -6339,8 +6822,9 @@ var ts; if (!packageName) { continue; } - var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost); + var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log); if (!typingFile) { + this.missingTypingsSet[packageName] = true; continue; } var existingTypingFile = this.packageNameToTypingLocation[packageName]; @@ -6364,19 +6848,57 @@ var ts; } this.knownCachesSet[cacheLocation] = true; }; - TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { - var _this = this; - if (this.log.isEnabled()) { - this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall)); - } - typingsToInstall = ts.filter(typingsToInstall, function (x) { return !_this.missingTypingsSet[x]; }); + TypingsInstaller.prototype.filterTypings = function (typingsToInstall) { if (typingsToInstall.length === 0) { - if (this.log.isEnabled()) { - this.log.writeLine("All typings are known to be missing - no need to go any further"); - } - return; + return typingsToInstall; } - var npmConfigPath = ts.combinePaths(cachePath, "package.json"); + var result = []; + for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) { + var typing = typingsToInstall_1[_i]; + if (this.missingTypingsSet[typing] || this.packageNameToTypingLocation[typing]) { + continue; + } + var validationResult = validatePackageName(typing); + if (validationResult === PackageNameValidationResult.Ok) { + if (typing in this.typesRegistry) { + result.push(typing); + } + else { + if (this.log.isEnabled()) { + this.log.writeLine("Entry for package '" + typing + "' does not exist in local types registry - skipping..."); + } + } + } + else { + this.missingTypingsSet[typing] = true; + if (this.log.isEnabled()) { + switch (validationResult) { + case PackageNameValidationResult.EmptyName: + this.log.writeLine("Package name '" + typing + "' cannot be empty"); + break; + case PackageNameValidationResult.NameTooLong: + this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters"); + break; + case PackageNameValidationResult.NameStartsWithDot: + this.log.writeLine("Package name '" + typing + "' cannot start with '.'"); + break; + case PackageNameValidationResult.NameStartsWithUnderscore: + this.log.writeLine("Package name '" + typing + "' cannot start with '_'"); + break; + case PackageNameValidationResult.ScopedPackagesNotSupported: + this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported"); + break; + case PackageNameValidationResult.NameContainsNonURISafeCharacters: + this.log.writeLine("Package name '" + typing + "' contains non URI safe characters"); + break; + } + } + } + } + return result; + }; + TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) { + var npmConfigPath = ts.combinePaths(directory, "package.json"); if (this.log.isEnabled()) { this.log.writeLine("Npm config file: " + npmConfigPath); } @@ -6384,78 +6906,76 @@ var ts; if (this.log.isEnabled()) { this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one..."); } - this.ensureDirectoryExists(cachePath, this.installTypingHost); + this.ensureDirectoryExists(directory, this.installTypingHost); this.installTypingHost.writeFile(npmConfigPath, "{}"); } - this.runInstall(cachePath, typingsToInstall, function (installedTypings) { - if (_this.log.isEnabled()) { - _this.log.writeLine("Requested to install typings " + JSON.stringify(typingsToInstall) + ", installed typings " + JSON.stringify(installedTypings)); - } - var installedPackages = ts.createMap(); - var installedTypingFiles = []; - for (var _i = 0, installedTypings_1 = installedTypings; _i < installedTypings_1.length; _i++) { - var t = installedTypings_1[_i]; - var packageName = ts.getBaseFileName(t); - if (!packageName) { - continue; - } - installedPackages[packageName] = true; - var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost); - if (!typingFile) { - continue; - } - if (!_this.packageNameToTypingLocation[packageName]) { - _this.packageNameToTypingLocation[packageName] = typingFile; - } - installedTypingFiles.push(typingFile); - } - if (_this.log.isEnabled()) { - _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles)); - } - for (var _a = 0, typingsToInstall_1 = typingsToInstall; _a < typingsToInstall_1.length; _a++) { - var toInstall = typingsToInstall_1[_a]; - if (!installedPackages[toInstall]) { - if (_this.log.isEnabled()) { - _this.log.writeLine("New missing typing package '" + toInstall + "'"); - } - _this.missingTypingsSet[toInstall] = true; - } - } - _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); - }); }; - TypingsInstaller.prototype.runInstall = function (cachePath, typingsToInstall, postInstallAction) { + TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { + var _this = this; + if (this.log.isEnabled()) { + this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall)); + } + var filteredTypings = this.filterTypings(typingsToInstall); + var scopedTypings = filteredTypings.map(function (x) { return "@types/" + x; }); + if (scopedTypings.length === 0) { + if (this.log.isEnabled()) { + this.log.writeLine("All typings are known to be missing or invalid - no need to go any further"); + } + return; + } + this.ensurePackageDirectoryExists(cachePath); var requestId = this.installRunCount; this.installRunCount++; - var execInstallCmdCount = 0; - var filteredTypings = []; - for (var _i = 0, typingsToInstall_2 = typingsToInstall; _i < typingsToInstall_2.length; _i++) { - var typing = typingsToInstall_2[_i]; - execNpmViewTyping(this, typing); - } - function execNpmViewTyping(self, typing) { - var command = self.npmPath + " view @types/" + typing + " --silent name"; - self.execAsync(typingsInstaller.NpmViewRequest, requestId, command, cachePath, function (err, stdout, stderr) { - if (stdout) { - filteredTypings.push(typing); + this.sendResponse({ + kind: server.EventBeginInstallTypes, + eventId: requestId, + typingsInstallerVersion: ts.version, + projectName: req.projectName + }); + this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) { + try { + if (!ok) { + if (_this.log.isEnabled()) { + _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings)); + } + for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) { + var typing = filteredTypings_1[_i]; + _this.missingTypingsSet[typing] = true; + } + return; } - execInstallCmdCount++; - if (execInstallCmdCount === typingsToInstall.length) { - installFilteredTypings(self, filteredTypings); + if (_this.log.isEnabled()) { + _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings)); } - }); - } - function installFilteredTypings(self, filteredTypings) { - if (filteredTypings.length === 0) { - postInstallAction([]); - return; + var installedTypingFiles = []; + for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) { + var packageName = filteredTypings_2[_a]; + var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log); + if (!typingFile) { + _this.missingTypingsSet[packageName] = true; + continue; + } + if (!_this.packageNameToTypingLocation[packageName]) { + _this.packageNameToTypingLocation[packageName] = typingFile; + } + installedTypingFiles.push(typingFile); + } + if (_this.log.isEnabled()) { + _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles)); + } + _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); } - var scopedTypings = filteredTypings.map(function (t) { return "@types/" + t; }); - var command = self.npmPath + " install " + scopedTypings.join(" ") + " --save-dev"; - self.execAsync(typingsInstaller.NpmInstallRequest, requestId, command, cachePath, function (err, stdout, stderr) { - postInstallAction(stdout ? scopedTypings : []); - }); - } + finally { + _this.sendResponse({ + kind: server.EventEndInstallTypes, + eventId: requestId, + projectName: req.projectName, + packagesToInstall: scopedTypings, + installSuccess: ok, + typingsInstallerVersion: ts.version + }); + } + }); }; TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) { var directoryName = ts.getDirectoryPath(directory); @@ -6480,9 +7000,11 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Got FS notification for " + f + ", handler is already invoked '" + isInvoked + "'"); } - _this.sendResponse({ projectName: projectName, kind: "invalidate" }); - isInvoked = true; - }); + if (!isInvoked) { + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + isInvoked = true; + } + }, 2000); watchers.push(w); } this.projectWatchers[projectName] = watchers; @@ -6490,30 +7012,31 @@ var ts; TypingsInstaller.prototype.createSetTypings = function (request, typings) { return { projectName: request.projectName, - typingOptions: request.typingOptions, + typeAcquisition: request.typeAcquisition, compilerOptions: request.compilerOptions, typings: typings, - kind: "set" + unresolvedImports: request.unresolvedImports, + kind: server.ActionSet }; }; - TypingsInstaller.prototype.execAsync = function (requestKind, requestId, command, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestKind: requestKind, requestId: requestId, command: command, cwd: cwd, onRequestCompleted: onRequestCompleted }); + TypingsInstaller.prototype.installTypingsAsync = function (requestId, args, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestId: requestId, args: args, cwd: cwd, onRequestCompleted: onRequestCompleted }); this.executeWithThrottling(); }; TypingsInstaller.prototype.executeWithThrottling = function () { var _this = this; - var _loop_1 = function () { + var _loop_2 = function () { this_1.inFlightRequestCount++; var request = this_1.pendingRunRequests.pop(); - this_1.runCommand(request.requestKind, request.requestId, request.command, request.cwd, function (err, stdout, stderr) { + this_1.installWorker(request.requestId, request.args, request.cwd, function (ok) { _this.inFlightRequestCount--; - request.onRequestCompleted(err, stdout, stderr); + request.onRequestCompleted(ok); _this.executeWithThrottling(); }); }; var this_1 = this; while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { - _loop_1(); + _loop_2(); } }; return TypingsInstaller; @@ -6550,20 +7073,54 @@ var ts; return "npm"; } } + function loadTypesRegistryFile(typesRegistryFilePath, host, log) { + if (!host.fileExists(typesRegistryFilePath)) { + if (log.isEnabled()) { + log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist"); + } + return ts.createMap(); + } + try { + var content = JSON.parse(host.readFile(typesRegistryFilePath)); + return ts.createMap(content.entries); + } + catch (e) { + if (log.isEnabled()) { + log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack); + } + return ts.createMap(); + } + } + var TypesRegistryPackageName = "types-registry"; + function getTypesRegistryFileLocation(globalTypingsCacheLocation) { + return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + TypesRegistryPackageName + "/index.json"); + } var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) { - _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log); - this.installTypingHost = ts.sys; - if (this.log.isEnabled()) { - this.log.writeLine("Process id: " + process.pid); + var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + if (_this.log.isEnabled()) { + _this.log.writeLine("Process id: " + process.pid); } - var exec = require("child_process").exec; - this.exec = exec; + _this.npmPath = getNPMLocation(process.argv[0]); + (_this.execSync = require("child_process").execSync); + _this.ensurePackageDirectoryExists(globalTypingsCacheLocation); + try { + if (_this.log.isEnabled()) { + _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); + } + _this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + } + catch (e) { + if (_this.log.isEnabled()) { + _this.log.writeLine("Error updating " + TypesRegistryPackageName + " package: " + e.message); + } + } + _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log); + return _this; } - NodeTypingsInstaller.prototype.init = function () { + NodeTypingsInstaller.prototype.listen = function () { var _this = this; - _super.prototype.init.call(this); process.on("message", function (req) { switch (req.kind) { case "discover": @@ -6583,30 +7140,33 @@ var ts; this.log.writeLine("Response has been sent."); } }; - NodeTypingsInstaller.prototype.runCommand = function (requestKind, requestId, command, cwd, onRequestCompleted) { - var _this = this; + NodeTypingsInstaller.prototype.installWorker = function (requestId, args, cwd, onRequestCompleted) { if (this.log.isEnabled()) { - this.log.writeLine("#" + requestId + " running command '" + command + "'."); + this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(args) + "'."); } - this.exec(command, { cwd: cwd }, function (err, stdout, stderr) { - if (_this.log.isEnabled()) { - _this.log.writeLine(requestKind + " #" + requestId + " stdout: " + stdout); - _this.log.writeLine(requestKind + " #" + requestId + " stderr: " + stderr); - } - onRequestCompleted(err, stdout, stderr); - }); + var command = this.npmPath + " install " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; + var start = Date.now(); + var stdout; + var stderr; + var hasError = false; + try { + stdout = this.execSync(command, { cwd: cwd }); + } + catch (e) { + stdout = e.stdout; + stderr = e.stderr; + hasError = true; + } + if (this.log.isEnabled()) { + this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms" + ts.sys.newLine + "stdout: " + (stdout && stdout.toString()) + ts.sys.newLine + "stderr: " + (stderr && stderr.toString())); + } + onRequestCompleted(!hasError); }; return NodeTypingsInstaller; }(typingsInstaller.TypingsInstaller)); typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller; - function findArgument(argumentName) { - var index = ts.sys.args.indexOf(argumentName); - return index >= 0 && index < ts.sys.args.length - 1 - ? ts.sys.args[index + 1] - : undefined; - } - var logFilePath = findArgument("--logFile"); - var globalTypingsCacheLocation = findArgument("--globalTypingsCacheLocation"); + var logFilePath = server.findArgument(server.Arguments.LogFile); + var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); var log = new FileLog(logFilePath); if (log.isEnabled()) { process.on("uncaughtException", function (e) { @@ -6620,7 +7180,7 @@ var ts; process.exit(0); }); var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, 5, log); - installer.init(); + installer.listen(); })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); diff --git a/netci.groovy b/netci.groovy new file mode 100644 index 00000000000..bc512f6b245 --- /dev/null +++ b/netci.groovy @@ -0,0 +1,22 @@ +// Import the utility functionality. +import jobs.generation.Utilities; + +// Defines a the new of the repo, used elsewhere in the file +def project = GithubProject +def branch = GithubBranchName + +def nodeVersions = ['stable', '6', '4'] + +nodeVersions.each { nodeVer -> + + def newJobName = "typescript_node.${nodeVer}" + def newJob = job(Utilities.getFullJobName(project, newJobName, true)) { + steps { + shell("./jenkins.sh ${nodeVer}") + } + } + + Utilities.standardJobSetup(newJob, project, true, "*/${branch}") + Utilities.setMachineAffinity(newJob, 'Ubuntu', '20161020') + Utilities.addGithubPRTriggerForBranch(newJob, branch, "TypeScript Test Run ${newJobName}") +} diff --git a/package.json b/package.json index 1f943f89788..2de37b712ab 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "2.1.0", + "version": "2.2.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -26,7 +26,7 @@ "tsserver": "./bin/tsserver" }, "engines": { - "node": ">=0.8.0" + "node": ">=4.2.0" }, "devDependencies": { "@types/browserify": "latest", @@ -75,8 +75,7 @@ "through2": "latest", "travis-fold": "latest", "ts-node": "latest", - "tsd": "latest", - "tslint": "next", + "tslint": "4.0.0-dev.3", "typescript": "next" }, "scripts": { diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts new file mode 100644 index 00000000000..66f29f577d9 --- /dev/null +++ b/scripts/buildProtocol.ts @@ -0,0 +1,185 @@ +/// + +import * as ts from "../lib/typescript"; +import * as path from "path"; + +function endsWith(s: string, suffix: string) { + return s.lastIndexOf(suffix, s.length - suffix.length) !== -1; +} + +class DeclarationsWalker { + private visitedTypes: ts.Type[] = []; + private text = ""; + private removedTypes: ts.Type[] = []; + + private constructor(private typeChecker: ts.TypeChecker, private protocolFile: ts.SourceFile) { + } + + static getExtraDeclarations(typeChecker: ts.TypeChecker, protocolFile: ts.SourceFile): string { + let text = "declare namespace ts.server.protocol {\n"; + var walker = new DeclarationsWalker(typeChecker, protocolFile); + walker.visitTypeNodes(protocolFile); + text = walker.text + ? `declare namespace ts.server.protocol {\n${walker.text}}` + : ""; + if (walker.removedTypes) { + text += "\ndeclare namespace ts {\n"; + text += " // these types are empty stubs for types from services and should not be used directly\n" + for (const type of walker.removedTypes) { + text += ` export type ${type.symbol.name} = never;\n`; + } + text += "}" + } + return text; + } + + private processType(type: ts.Type): void { + if (this.visitedTypes.indexOf(type) >= 0) { + return; + } + this.visitedTypes.push(type); + let s = type.aliasSymbol || type.getSymbol(); + if (!s) { + return; + } + if (s.name === "Array") { + // we should process type argument instead + return this.processType((type).typeArguments[0]); + } + else { + for (const decl of s.getDeclarations()) { + const sourceFile = decl.getSourceFile(); + if (sourceFile === this.protocolFile || path.basename(sourceFile.fileName) === "lib.d.ts") { + return; + } + if (decl.kind === ts.SyntaxKind.EnumDeclaration) { + this.removedTypes.push(type); + return; + } + else { + // splice declaration in final d.ts file + let text = decl.getFullText(); + this.text += `${text}\n`; + // recursively pull all dependencies into result dts file + + this.visitTypeNodes(decl); + } + } + } + } + + private visitTypeNodes(node: ts.Node) { + if (node.parent) { + switch (node.parent.kind) { + case ts.SyntaxKind.VariableDeclaration: + case ts.SyntaxKind.MethodDeclaration: + case ts.SyntaxKind.MethodSignature: + case ts.SyntaxKind.PropertyDeclaration: + case ts.SyntaxKind.PropertySignature: + case ts.SyntaxKind.Parameter: + case ts.SyntaxKind.IndexSignature: + if (((node.parent).type) === node) { + this.processTypeOfNode(node); + } + break; + case ts.SyntaxKind.InterfaceDeclaration: + const heritageClauses = (node.parent).heritageClauses; + if (heritageClauses) { + if (heritageClauses[0].token !== ts.SyntaxKind.ExtendsKeyword) { + throw new Error(`Unexpected kind of heritage clause: ${ts.SyntaxKind[heritageClauses[0].kind]}`); + } + for (const type of heritageClauses[0].types) { + this.processTypeOfNode(type); + } + } + break; + } + } + ts.forEachChild(node, n => this.visitTypeNodes(n)); + } + + private processTypeOfNode(node: ts.Node): void { + if (node.kind === ts.SyntaxKind.UnionType) { + for (const t of (node).types) { + this.processTypeOfNode(t); + } + } + else { + const type = this.typeChecker.getTypeAtLocation(node); + if (type && !(type.flags & (ts.TypeFlags.TypeParameter))) { + this.processType(type); + } + } + } +} + +function generateProtocolFile(protocolTs: string, typeScriptServicesDts: string): string { + const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: true, types: [], stripInternal: true }; + + /** + * 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped + * @return text of protocol.d.t.s + */ + function getInitialDtsFileForProtocol() { + const program = ts.createProgram([protocolTs, typeScriptServicesDts], options); + + let protocolDts: string; + program.emit(program.getSourceFile(protocolTs), (file, content) => { + if (endsWith(file, ".d.ts")) { + protocolDts = content; + } + }); + if (protocolDts === undefined) { + throw new Error(`Declaration file for protocol.ts is not generated`) + } + return protocolDts; + } + + const protocolFileName = "protocol.d.ts"; + /** + * Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts + */ + function getProgramWithProtocolText(protocolDts: string, includeTypeScriptServices: boolean) { + const host = ts.createCompilerHost(options); + const originalGetSourceFile = host.getSourceFile; + host.getSourceFile = (fileName) => { + if (fileName === protocolFileName) { + return ts.createSourceFile(fileName, protocolDts, options.target); + } + return originalGetSourceFile.apply(host, [fileName]); + } + const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName]; + return ts.createProgram(rootFiles, options, host); + } + + let protocolDts = getInitialDtsFileForProtocol(); + const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true); + + const protocolFile = program.getSourceFile("protocol.d.ts"); + const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile); + if (extraDeclarations) { + protocolDts += extraDeclarations; + } + protocolDts += "\nimport protocol = ts.server.protocol;"; + protocolDts += "\nexport = protocol;"; + protocolDts += "\nexport as namespace protocol;"; + // do sanity check and try to compile generated text as standalone program + const sanityCheckProgram = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ false); + const diagnostics = [...sanityCheckProgram.getSyntacticDiagnostics(), ...sanityCheckProgram.getSemanticDiagnostics(), ...sanityCheckProgram.getGlobalDiagnostics()]; + if (diagnostics.length) { + const flattenedDiagnostics = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, "\n")).join("\n"); + throw new Error(`Unexpected errors during sanity check: ${flattenedDiagnostics}`); + } + return protocolDts; +} + +if (process.argv.length < 5) { + console.log(`Expected 3 arguments: path to 'protocol.ts', path to 'typescriptservices.d.ts' and path to output file`); + process.exit(1); +} + +const protocolTs = process.argv[2]; +const typeScriptServicesDts = process.argv[3]; +const outputFile = process.argv[4]; +const generatedProtocolDts = generateProtocolFile(protocolTs, typeScriptServicesDts); +ts.sys.writeFile(outputFile, generatedProtocolDts); diff --git a/scripts/parallel-lint.js b/scripts/parallel-lint.js index a9aec06c2df..aec9960ce47 100644 --- a/scripts/parallel-lint.js +++ b/scripts/parallel-lint.js @@ -1,26 +1,29 @@ -var Linter = require("tslint"); +var tslint = require("tslint"); var fs = require("fs"); function getLinterOptions() { return { - configuration: require("../tslint.json"), formatter: "prose", formattersDirectory: undefined, rulesDirectory: "built/local/tslint" }; } - -function lintFileContents(options, path, contents) { - var ll = new Linter(path, contents, options); - return ll.lint(); +function getLinterConfiguration() { + return require("../tslint.json"); } -function lintFileAsync(options, path, cb) { +function lintFileContents(options, configuration, path, contents) { + var ll = new tslint.Linter(options); + ll.lint(path, contents, configuration); + return ll.getResult(); +} + +function lintFileAsync(options, configuration, path, cb) { fs.readFile(path, "utf8", function (err, contents) { if (err) { return cb(err); } - var result = lintFileContents(options, path, contents); + var result = lintFileContents(options, configuration, path, contents); cb(undefined, result); }); } @@ -30,7 +33,8 @@ process.on("message", function (data) { case "file": var target = data.name; var lintOptions = getLinterOptions(); - lintFileAsync(lintOptions, target, function (err, result) { + var lintConfiguration = getLinterConfiguration(); + lintFileAsync(lintOptions, lintConfiguration, target, function (err, result) { if (err) { process.send({ kind: "error", error: err.toString() }); return; diff --git a/scripts/tslint/booleanTriviaRule.ts b/scripts/tslint/booleanTriviaRule.ts index b626b7560a6..db6abcbf17b 100644 --- a/scripts/tslint/booleanTriviaRule.ts +++ b/scripts/tslint/booleanTriviaRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { diff --git a/scripts/tslint/nextLineRule.ts b/scripts/tslint/nextLineRule.ts index d25652f7bce..2dee393bd84 100644 --- a/scripts/tslint/nextLineRule.ts +++ b/scripts/tslint/nextLineRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; const OPTION_CATCH = "check-catch"; diff --git a/scripts/tslint/noInOperatorRule.ts b/scripts/tslint/noInOperatorRule.ts index 527e8c1b895..307f0dffd6a 100644 --- a/scripts/tslint/noInOperatorRule.ts +++ b/scripts/tslint/noInOperatorRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; diff --git a/scripts/tslint/noIncrementDecrementRule.ts b/scripts/tslint/noIncrementDecrementRule.ts index f5c90abe893..2a957b36af5 100644 --- a/scripts/tslint/noIncrementDecrementRule.ts +++ b/scripts/tslint/noIncrementDecrementRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; diff --git a/scripts/tslint/noTypeAssertionWhitespaceRule.ts b/scripts/tslint/noTypeAssertionWhitespaceRule.ts index e75964b9e7e..5368dcf74ba 100644 --- a/scripts/tslint/noTypeAssertionWhitespaceRule.ts +++ b/scripts/tslint/noTypeAssertionWhitespaceRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; diff --git a/scripts/tslint/objectLiteralSurroundingSpaceRule.ts b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts index b527746bf51..a705e56c969 100644 --- a/scripts/tslint/objectLiteralSurroundingSpaceRule.ts +++ b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts index 445fbe2e72a..28d7446b290 100644 --- a/scripts/tslint/preferConstRule.ts +++ b/scripts/tslint/preferConstRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { diff --git a/scripts/tslint/typeOperatorSpacingRule.ts b/scripts/tslint/typeOperatorSpacingRule.ts index 559d1b34937..50f2971a0ee 100644 --- a/scripts/tslint/typeOperatorSpacingRule.ts +++ b/scripts/tslint/typeOperatorSpacingRule.ts @@ -1,4 +1,4 @@ -import * as Lint from "tslint/lib/lint"; +import * as Lint from "tslint/lib"; import * as ts from "typescript"; diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index b17fe546f58..a6f5993f6c8 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -54,6 +54,11 @@ namespace ts { const body = (node).body; return body ? getModuleInstanceState(body) : ModuleInstanceState.Instantiated; } + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + else if (node.kind === SyntaxKind.Identifier && (node).isInJSDocNamespace) { + return ModuleInstanceState.NonInstantiated; + } else { return ModuleInstanceState.Instantiated; } @@ -84,6 +89,7 @@ namespace ts { IsFunctionExpression = 1 << 4, HasLocals = 1 << 5, IsInterface = 1 << 6, + IsObjectLiteralOrClassExpressionMethod = 1 << 7, } const binder = createBinder(); @@ -121,7 +127,8 @@ namespace ts { // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. let inStrictMode: boolean; let symbolCount = 0; @@ -139,7 +146,7 @@ namespace ts { file = f; options = opts; languageVersion = getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = createMap(); symbolCount = 0; skipTransformFlagAggregation = isDeclarationFile(file); @@ -174,6 +181,16 @@ namespace ts { return bindSourceFile; + function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean { + if (opts.alwaysStrict && !isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags: SymbolFlags, name: string): Symbol { symbolCount++; return new Symbol(flags, name); @@ -217,8 +234,8 @@ namespace ts { if (node.name.kind === SyntaxKind.ComputedPropertyName) { const nameExpression = (node.name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (isStringOrNumericLiteral(nameExpression.kind)) { - return (nameExpression).text; + if (isStringOrNumericLiteral(nameExpression)) { + return nameExpression.text; } Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); @@ -417,7 +434,11 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) { + const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && + node.name && + node.name.kind === SyntaxKind.Identifier && + (node.name).isInJSDocNamespace; + if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) { const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | @@ -478,16 +499,16 @@ namespace ts { const saveReturnTarget = currentReturnTarget; const saveActiveLabels = activeLabels; const saveHasExplicitReturn = hasExplicitReturn; - const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !!getImmediatelyInvokedFunctionExpression(node); - // An IIFE is considered part of the containing control flow. Return statements behave + const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !hasModifier(node, ModifierFlags.Async) && !!getImmediatelyInvokedFunctionExpression(node); + // A non-async IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: FlowFlags.Start }; - if (containerFlags & ContainerFlags.IsFunctionExpression) { - (currentFlow).container = node; + if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { + (currentFlow).container = node; } currentReturnTarget = undefined; } @@ -497,7 +518,6 @@ namespace ts { hasExplicitReturn = false; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) - // Reset all emit helper flags on node (for incremental scenarios) node.flags &= ~NodeFlags.ReachabilityAndEmitFlags; if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((node).body)) { node.flags |= NodeFlags.HasImplicitReturn; @@ -539,6 +559,7 @@ namespace ts { skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } else { const savedSubtreeTransformFlags = subtreeTransformFlags; @@ -548,15 +569,40 @@ namespace ts { } } + function bindEach(nodes: NodeArray) { + if (nodes === undefined) { + return; + } + + if (skipTransformFlagAggregation) { + forEach(nodes, bind); + } + else { + const savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = TransformFlags.None; + let nodeArrayFlags = TransformFlags.None; + for (const node of nodes) { + bind(node); + nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags; + } + nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + + function bindEachChild(node: Node) { + forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node: Node): void { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (isInJavaScriptFile(node) && node.jsDocComments) { - forEach(node.jsDocComments, bind); + if (isInJavaScriptFile(node) && node.jsDoc) { + forEach(node.jsDoc, bind); } if (checkUnreachable(node)) { - forEachChild(node, bind); + bindEachChild(node); return; } switch (node.kind) { @@ -621,7 +667,7 @@ namespace ts { bindCallExpressionFlow(node); break; default: - forEachChild(node, bind); + bindEachChild(node); break; } } @@ -773,6 +819,15 @@ namespace ts { }; } + function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode { + setFlowNodeReferenced(antecedent); + return { + flags: FlowFlags.ArrayMutation, + antecedent, + node + }; + } + function finishFlowLabel(flow: FlowLabel): FlowNode { const antecedents = flow.antecedents; if (!antecedents) { @@ -862,8 +917,13 @@ namespace ts { function bindDoStatement(node: DoStatement): void { const preDoLabel = createLoopLabel(); - const preConditionLabel = createBranchLabel(); - const postDoLabel = createBranchLabel(); + const enclosingLabeledStatement = node.parent.kind === SyntaxKind.LabeledStatement + ? lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + const preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + const postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); currentFlow = preDoLabel; bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); @@ -940,7 +1000,7 @@ namespace ts { return undefined; } - function bindbreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) { + function bindBreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) { const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); @@ -954,33 +1014,53 @@ namespace ts { const activeLabel = findActiveLabel(node.label.text); if (activeLabel) { activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); } } else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); } } function bindTryStatement(node: TryStatement): void { - const postFinallyLabel = createBranchLabel(); + const preFinallyLabel = createBranchLabel(); const preTryFlow = currentFlow; // TODO: Every statement in try block is potentially an exit point! bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + + const flowAfterTry = currentFlow; + let flowAfterCatch = unreachableFlow; + if (node.catchClause) { currentFlow = preTryFlow; bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); + addAntecedent(preFinallyLabel, currentFlow); + + flowAfterCatch = currentFlow; } if (node.finallyBlock) { - currentFlow = preTryFlow; + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + addAntecedent(preFinallyLabel, preTryFlow); + currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & FlowFlags.Unreachable)) { + if ((flowAfterTry.flags & FlowFlags.Unreachable) && (flowAfterCatch.flags & FlowFlags.Unreachable)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } } - // if try statement has finally block and flow after finally block is unreachable - keep it - // otherwise use whatever flow was accumulated at postFinallyLabel - if (!node.finallyBlock || !(currentFlow.flags & FlowFlags.Unreachable)) { - currentFlow = finishFlowLabel(postFinallyLabel); + else { + currentFlow = finishFlowLabel(preFinallyLabel); } } @@ -1006,6 +1086,8 @@ namespace ts { } function bindCaseBlock(node: CaseBlock): void { + const savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; const clauses = node.clauses; let fallthroughFlow = unreachableFlow; for (let i = 0; i < clauses.length; i++) { @@ -1025,6 +1107,8 @@ namespace ts { errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch); } } + clauses.transformFlags = subtreeTransformFlags | TransformFlags.HasComputedFlags; + subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node: CaseClause): void { @@ -1032,7 +1116,7 @@ namespace ts { currentFlow = preSwitchCaseFlow; bind(node.expression); currentFlow = saveCurrentFlow; - forEach(node.statements, bind); + bindEach(node.statements); } function pushActiveLabel(name: string, breakTarget: FlowLabel, continueTarget: FlowLabel): ActiveLabel { @@ -1061,8 +1145,11 @@ namespace ts { if (!activeLabel.referenced && !options.allowUnusedLabels) { file.bindDiagnostics.push(createDiagnosticForNode(node.label, Diagnostics.Unused_label)); } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); + if (!node.statement || node.statement.kind !== SyntaxKind.DoStatement) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } } function bindDestructuringTargetFlow(node: Expression) { @@ -1080,8 +1167,8 @@ namespace ts { } else if (node.kind === SyntaxKind.ArrayLiteralExpression) { for (const e of (node).elements) { - if (e.kind === SyntaxKind.SpreadElementExpression) { - bindAssignmentTargetFlow((e).expression); + if (e.kind === SyntaxKind.SpreadElement) { + bindAssignmentTargetFlow((e).expression); } else { bindDestructuringTargetFlow(e); @@ -1096,6 +1183,9 @@ namespace ts { else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) { bindAssignmentTargetFlow((p).name); } + else if (p.kind === SyntaxKind.SpreadAssignment) { + bindAssignmentTargetFlow((p).expression); + } } } } @@ -1118,12 +1208,12 @@ namespace ts { const saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; - forEachChild(node, bind); + bindEachChild(node); currentFalseTarget = currentTrueTarget; currentTrueTarget = saveTrueTarget; } else { - forEachChild(node, bind); + bindEachChild(node); if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { bindAssignmentTargetFlow(node.operand); } @@ -1131,7 +1221,7 @@ namespace ts { } function bindPostfixUnaryExpressionFlow(node: PostfixUnaryExpression) { - forEachChild(node, bind); + bindEachChild(node); if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { bindAssignmentTargetFlow(node.operand); } @@ -1150,15 +1240,21 @@ namespace ts { } } else { - forEachChild(node, bind); - if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) { + bindEachChild(node); + if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) { + const elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } } } } function bindDeleteExpressionFlow(node: DeleteExpression) { - forEachChild(node, bind); + bindEachChild(node); if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { bindAssignmentTargetFlow(node.expression); } @@ -1170,9 +1266,11 @@ namespace ts { const postExpressionLabel = createBranchLabel(); bindCondition(node.condition, trueLabel, falseLabel); currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); bind(node.whenTrue); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); bind(node.whenFalse); addAntecedent(postExpressionLabel, currentFlow); currentFlow = finishFlowLabel(postExpressionLabel); @@ -1181,7 +1279,7 @@ namespace ts { function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) { const name = !isOmittedExpression(node) ? node.name : undefined; if (isBindingPattern(name)) { - for (const child of name.elements) { + for (const child of name.elements) { bindInitializedVariableFlow(child); } } @@ -1191,7 +1289,7 @@ namespace ts { } function bindVariableDeclarationFlow(node: VariableDeclaration) { - forEachChild(node, bind); + bindEachChild(node); if (node.initializer || node.parent.parent.kind === SyntaxKind.ForInStatement || node.parent.parent.kind === SyntaxKind.ForOfStatement) { bindInitializedVariableFlow(node); } @@ -1206,12 +1304,18 @@ namespace ts { expr = (expr).expression; } if (expr.kind === SyntaxKind.FunctionExpression || expr.kind === SyntaxKind.ArrowFunction) { - forEach(node.typeArguments, bind); - forEach(node.arguments, bind); + bindEach(node.typeArguments); + bindEach(node.arguments); bind(node.expression); } else { - forEachChild(node, bind); + bindEachChild(node); + } + if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { + const propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } } } @@ -1232,14 +1336,18 @@ namespace ts { case SyntaxKind.JSDocFunctionType: case SyntaxKind.ModuleDeclaration: case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.MappedType: return ContainerFlags.IsContainer | ContainerFlags.HasLocals; case SyntaxKind.SourceFile: return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals; + case SyntaxKind.MethodDeclaration: + if (isObjectLiteralOrClassExpressionMethod(node)) { + return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod; + } case SyntaxKind.Constructor: case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: @@ -1348,6 +1456,7 @@ namespace ts { case SyntaxKind.ArrowFunction: case SyntaxKind.JSDocFunctionType: case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.MappedType: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -1474,7 +1583,7 @@ namespace ts { const seen = createMap(); for (const prop of node.properties) { - if (prop.name.kind !== SyntaxKind.Identifier) { + if (prop.kind === SyntaxKind.SpreadAssignment || prop.name.kind !== SyntaxKind.Identifier) { continue; } @@ -1649,7 +1758,7 @@ namespace ts { } function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) { - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { // Report error if function is not top level function declaration if (blockScopeContainer.kind !== SyntaxKind.SourceFile && blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration && @@ -1772,6 +1881,17 @@ namespace ts { switch (node.kind) { /* Strict mode checks */ case SyntaxKind.Identifier: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if ((node).isInJSDocNamespace) { + let parentNode = node.parent; + while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + break; + } case SyntaxKind.ThisKeyword: if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) { node.flowNode = currentFlow; @@ -1842,8 +1962,20 @@ namespace ts { case SyntaxKind.EnumMember: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); + case SyntaxKind.SpreadAssignment: case SyntaxKind.JsxSpreadAttribute: - emitFlags |= NodeFlags.HasJsxSpreadAttributes; + let root = container; + let hasRest = false; + while (root.parent) { + if (root.kind === SyntaxKind.ObjectLiteralExpression && + root.parent.kind === SyntaxKind.BinaryExpression && + (root.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && + (root.parent as BinaryExpression).left === root) { + hasRest = true; + break; + } + root = root.parent; + } return; case SyntaxKind.CallSignature: @@ -1871,9 +2003,10 @@ namespace ts { case SyntaxKind.JSDocFunctionType: return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: + case SyntaxKind.MappedType: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.JSDocRecordType: - return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); + return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: @@ -1895,6 +2028,10 @@ namespace ts { case SyntaxKind.InterfaceDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); case SyntaxKind.JSDocTypedefTag: + if (!(node).fullName || (node).fullName.kind === SyntaxKind.Identifier) { + return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + } + break; case SyntaxKind.TypeAliasDeclaration: return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: @@ -2016,7 +2153,9 @@ namespace ts { function setCommonJsModuleIndicator(node: Node) { if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } } @@ -2092,15 +2231,6 @@ namespace ts { } function bindClassLikeDeclaration(node: ClassLikeDeclaration) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= NodeFlags.HasClassExtends; - } - if (nodeIsDecorated(node)) { - emitFlags |= NodeFlags.HasDecorators; - } - } - if (node.kind === SyntaxKind.ClassDeclaration) { bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); } @@ -2170,12 +2300,6 @@ namespace ts { } function bindParameter(node: ParameterDeclaration) { - if (!isDeclarationFile(file) && - !isInAmbientContext(node) && - nodeIsDecorated(node)) { - emitFlags |= (NodeFlags.HasDecorators | NodeFlags.HasParamDecorators); - } - if (inStrictMode) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) @@ -2233,9 +2357,10 @@ namespace ts { if (isAsyncFunctionLike(node)) { emitFlags |= NodeFlags.HasAsyncFunctions; } - if (nodeIsDecorated(node)) { - emitFlags |= NodeFlags.HasDecorators; - } + } + + if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; } return hasDynamicName(node) @@ -2311,6 +2436,9 @@ namespace ts { case SyntaxKind.CallExpression: return computeCallExpression(node, subtreeFlags); + case SyntaxKind.NewExpression: + return computeNewExpression(node, subtreeFlags); + case SyntaxKind.ModuleDeclaration: return computeModuleDeclaration(node, subtreeFlags); @@ -2356,6 +2484,9 @@ namespace ts { case SyntaxKind.HeritageClause: return computeHeritageClause(node, subtreeFlags); + case SyntaxKind.CatchClause: + return computeCatchClause(node, subtreeFlags); + case SyntaxKind.ExpressionWithTypeArguments: return computeExpressionWithTypeArguments(node, subtreeFlags); @@ -2388,11 +2519,15 @@ namespace ts { const expression = node.expression; const expressionKind = expression.kind; - if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression + if (node.typeArguments) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + if (subtreeFlags & TransformFlags.ContainsSpread || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2414,21 +2549,38 @@ namespace ts { return false; } + function computeNewExpression(node: NewExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= TransformFlags.AssertTypeScript; + } + if (subtreeFlags & TransformFlags.ContainsSpread) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= TransformFlags.AssertES2015; + } + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; + } + function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; const operatorTokenKind = node.operatorToken.kind; const leftKind = node.left.kind; - if (operatorTokenKind === SyntaxKind.EqualsToken - && (leftKind === SyntaxKind.ObjectLiteralExpression - || leftKind === SyntaxKind.ArrayLiteralExpression)) { - // Destructuring assignments are ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment; + if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ObjectLiteralExpression) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment; + } + else if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ArrayLiteralExpression) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment; } else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken || operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) { - // Exponentiation is ES7 syntax. - transformFlags |= TransformFlags.AssertES7; + // Exponentiation is ES2016 syntax. + transformFlags |= TransformFlags.AssertES2016; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2442,13 +2594,12 @@ namespace ts { const initializer = node.initializer; const dotDotDotToken = node.dotDotDotToken; - // If the parameter has a question token, then it is TypeScript syntax. - if (node.questionToken) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & TransformFlags.ContainsDecorators || isThisIdentifier(name)) { + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & TransformFlags.ContainsDecorators + || isThisIdentifier(name)) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2457,10 +2608,15 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments; } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2501,13 +2657,14 @@ namespace ts { } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | TransformFlags.AssertES6; + transformFlags = subtreeFlags | TransformFlags.AssertES2015; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - // An exported declaration may be TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) - || (modifierFlags & ModifierFlags.Export)) { + || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2524,11 +2681,12 @@ namespace ts { function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) { // A ClassExpression is ES6 syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) { + if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask + || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2548,7 +2706,7 @@ namespace ts { switch (node.token) { case SyntaxKind.ExtendsKeyword: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.ImplementsKeyword: @@ -2565,10 +2723,21 @@ namespace ts { return transformFlags & ~TransformFlags.NodeExcludes; } + function computeCatchClause(node: CatchClause, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + + if (node.variableDeclaration && isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= TransformFlags.AssertES2015; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.CatchClauseExcludes; + } + function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. @@ -2582,36 +2751,48 @@ namespace ts { function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const body = node.body; - if (body === undefined) { - // An overload constructor is TypeScript syntax. + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; return transformFlags & ~TransformFlags.ConstructorExcludes; } function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) { // A MethodDeclaration is ES6 syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; - const modifierFlags = getModifierFlags(node); - const body = node.body; - const typeParameters = node.typeParameters; - const asteriskToken = node.asteriskToken; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || typeParameters - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + + // An async method declaration is ES2017 syntax. + if (hasModifier(node, ModifierFlags.Async)) { + transformFlags |= TransformFlags.AssertES2017; + } + // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } @@ -2621,17 +2802,21 @@ namespace ts { function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const modifierFlags = getModifierFlags(node); - const body = node.body; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.type + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; return transformFlags & ~TransformFlags.MethodOrAccessorExcludes; } @@ -2654,7 +2839,6 @@ namespace ts { let transformFlags: TransformFlags; const modifierFlags = getModifierFlags(node); const body = node.body; - const asteriskToken = node.asteriskToken; if (!body || (modifierFlags & ModifierFlags.Ambient)) { // An ambient declaration is TypeScript syntax. @@ -2664,21 +2848,29 @@ namespace ts { else { transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; - // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & ModifierFlags.TypeScriptModifier + || node.typeParameters + || node.type) { + transformFlags |= TransformFlags.AssertTypeScript; } - // If a FunctionDeclaration is async, then it is TypeScript syntax. + // An async function declaration is ES2017 syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertES2017; + } + + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES6; + if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES2015; } // If a FunctionDeclaration is generator function and is the body of a @@ -2686,7 +2878,7 @@ namespace ts { // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } } @@ -2697,19 +2889,31 @@ namespace ts { function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const modifierFlags = getModifierFlags(node); - const asteriskToken = node.asteriskToken; - // An async function expression is TypeScript syntax. - if (modifierFlags & ModifierFlags.Async) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type) { transformFlags |= TransformFlags.AssertTypeScript; } + // An async function expression is ES2017 syntax. + if (hasModifier(node, ModifierFlags.Async)) { + transformFlags |= TransformFlags.AssertES2017; + } + + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + + // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES6; + if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES2015; } // If a FunctionExpression is generator function and is the body of a @@ -2717,7 +2921,7 @@ namespace ts { // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } @@ -2727,14 +2931,26 @@ namespace ts { function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; - const modifierFlags = getModifierFlags(node); + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - // An async arrow function is TypeScript syntax. - if (modifierFlags & ModifierFlags.Async) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type) { transformFlags |= TransformFlags.AssertTypeScript; } + // An async arrow function is ES2017 syntax. + if (hasModifier(node, ModifierFlags.Async)) { + transformFlags |= TransformFlags.AssertES2017; + } + + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. if (subtreeFlags & TransformFlags.ContainsLexicalThis) { transformFlags |= TransformFlags.ContainsCapturedLexicalThis; @@ -2761,11 +2977,16 @@ namespace ts { function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const nameKind = node.name.kind; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; - // A VariableDeclaration with a binding pattern is ES6 syntax. - if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & TransformFlags.ContainsObjectRest) { + transformFlags |= TransformFlags.AssertESNext; + } + + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= TransformFlags.AssertTypeScript; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2784,13 +3005,8 @@ namespace ts { else { transformFlags = subtreeFlags; - // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; - } - if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } } @@ -2804,7 +3020,7 @@ namespace ts { // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding && isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2830,7 +3046,7 @@ namespace ts { // then we treat the statement as ES6 so that we can indicate that we do not // need to hold on to the right-hand side. if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2853,12 +3069,12 @@ namespace ts { let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; if (subtreeFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & NodeFlags.BlockScoped) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBlockScopedBinding; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2871,14 +3087,18 @@ namespace ts { let excludeFlags = TransformFlags.NodeExcludes; switch (kind) { + case SyntaxKind.AsyncKeyword: + case SyntaxKind.AwaitExpression: + // async/await is ES2017 syntax + transformFlags |= TransformFlags.AssertES2017; + break; + case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.DeclareKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ConstKeyword: - case SyntaxKind.AwaitExpression: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMember: case SyntaxKind.TypeAssertionExpression: @@ -2901,12 +3121,10 @@ namespace ts { transformFlags |= TransformFlags.AssertJsx; break; - case SyntaxKind.ExportKeyword: - // This node is both ES6 and TypeScript syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; - break; - - case SyntaxKind.DefaultKeyword: + case SyntaxKind.ForOfStatement: + // for-of might be ESNext if it has a rest destructuring + transformFlags |= TransformFlags.AssertESNext; + // FALLTHROUGH case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: @@ -2914,14 +3132,14 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.TaggedTemplateExpression: case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.ForOfStatement: + case SyntaxKind.StaticKeyword: // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.YieldExpression: // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsYield; break; case SyntaxKind.AnyKeyword: @@ -2951,6 +3169,9 @@ namespace ts { case SyntaxKind.InterfaceDeclaration: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.ThisType: + case SyntaxKind.TypeOperator: + case SyntaxKind.IndexedAccessType: + case SyntaxKind.MappedType: case SyntaxKind.LiteralType: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = TransformFlags.AssertTypeScript; @@ -2975,14 +3196,17 @@ namespace ts { } break; - case SyntaxKind.SpreadElementExpression: - // This node is ES6 syntax, but is handled by a containing node. - transformFlags |= TransformFlags.ContainsSpreadElementExpression; + case SyntaxKind.SpreadElement: + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsSpread; + break; + + case SyntaxKind.SpreadAssignment: + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectSpread; break; case SyntaxKind.SuperKeyword: // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.ThisKeyword: @@ -2991,9 +3215,23 @@ namespace ts { break; case SyntaxKind.ObjectBindingPattern: + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; + if (subtreeFlags & TransformFlags.ContainsRest) { + transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRest; + } + excludeFlags = TransformFlags.BindingPatternExcludes; + break; + case SyntaxKind.ArrayBindingPattern: - // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; + excludeFlags = TransformFlags.BindingPatternExcludes; + break; + + case SyntaxKind.BindingElement: + transformFlags |= TransformFlags.AssertES2015; + if ((node).dotDotDotToken) { + transformFlags |= TransformFlags.ContainsRest; + } break; case SyntaxKind.Decorator: @@ -3006,7 +3244,7 @@ namespace ts { if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { @@ -3015,15 +3253,21 @@ namespace ts { transformFlags |= TransformFlags.ContainsLexicalThis; } + if (subtreeFlags & TransformFlags.ContainsObjectSpread) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= TransformFlags.AssertESNext; + } + break; case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.NewExpression: excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes; - if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { - // If the this node contains a SpreadElementExpression, then it is an ES6 + if (subtreeFlags & TransformFlags.ContainsSpread) { + // If the this node contains a SpreadExpression, then it is an ES6 // node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; @@ -3034,14 +3278,14 @@ namespace ts { case SyntaxKind.ForInStatement: // A loop containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; case SyntaxKind.SourceFile: if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; @@ -3056,4 +3300,70 @@ namespace ts { node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; return transformFlags & ~excludeFlags; } + + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + export function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) { + if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) { + return TransformFlags.TypeExcludes; + } + + switch (kind) { + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + case SyntaxKind.ArrayLiteralExpression: + return TransformFlags.ArrayLiteralOrCallOrNewExcludes; + case SyntaxKind.ModuleDeclaration: + return TransformFlags.ModuleExcludes; + case SyntaxKind.Parameter: + return TransformFlags.ParameterExcludes; + case SyntaxKind.ArrowFunction: + return TransformFlags.ArrowFunctionExcludes; + case SyntaxKind.FunctionExpression: + case SyntaxKind.FunctionDeclaration: + return TransformFlags.FunctionExcludes; + case SyntaxKind.VariableDeclarationList: + return TransformFlags.VariableDeclarationListExcludes; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + return TransformFlags.ClassExcludes; + case SyntaxKind.Constructor: + return TransformFlags.ConstructorExcludes; + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return TransformFlags.MethodOrAccessorExcludes; + case SyntaxKind.AnyKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.NeverKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.BooleanKeyword: + case SyntaxKind.SymbolKeyword: + case SyntaxKind.VoidKeyword: + case SyntaxKind.TypeParameter: + case SyntaxKind.PropertySignature: + case SyntaxKind.MethodSignature: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.TypeAliasDeclaration: + return TransformFlags.TypeExcludes; + case SyntaxKind.ObjectLiteralExpression: + return TransformFlags.ObjectLiteralExcludes; + case SyntaxKind.CatchClause: + return TransformFlags.CatchClauseExcludes; + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + return TransformFlags.BindingPatternExcludes; + default: + return TransformFlags.NodeExcludes; + } + } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 78481c17d1f..c3a3f2b6416 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -38,6 +38,8 @@ namespace ts { // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if // they no longer need the information (for example, if the user started editing again). let cancellationToken: CancellationToken; + let requestedExternalEmitHelpers: ExternalEmitHelpers; + let externalHelpersModule: Symbol; const Symbol = objectAllocator.getSymbolConstructor(); const Type = objectAllocator.getTypeConstructor(); @@ -104,10 +106,15 @@ namespace ts { getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getAmbientModules, - getJsxElementAttributesType, getJsxIntrinsicTagNames, - isOptionalParameter + isOptionalParameter, + tryGetMemberInModuleExports, + tryFindAmbientModuleWithoutAugmentations: moduleName => { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + } }; const tupleTypes: GenericType[] = []; @@ -115,6 +122,8 @@ namespace ts { const intersectionTypes = createMap(); const stringLiteralTypes = createMap(); const numericLiteralTypes = createMap(); + const indexedAccessTypes = createMap(); + const evolvingArrayTypes: EvolvingArrayType[] = []; const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); @@ -137,6 +146,11 @@ namespace ts { const silentNeverType = createIntrinsicType(TypeFlags.Never, "never"); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + + const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral | SymbolFlags.Transient, "__type"); + emptyTypeLiteralSymbol.members = createMap(); + const emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = createMap(); @@ -176,6 +190,7 @@ namespace ts { let globalBooleanType: ObjectType; let globalRegExpType: ObjectType; let anyArrayType: Type; + let autoArrayType: Type; let anyReadonlyArrayType: Type; // The library files are only loaded when the feature is used. @@ -321,9 +336,12 @@ namespace ts { "undefined": undefinedType }); - let jsxElementType: ObjectType; + let jsxElementType: Type; + let _jsxNamespace: string; + let _jsxFactoryEntity: EntityName; + /** Things we lazy load from the JSX namespace */ - const jsxTypes = createMap(); + const jsxTypes = createMap(); const JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -359,6 +377,22 @@ namespace ts { return checker; + function getJsxNamespace(): string { + if (_jsxNamespace === undefined) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = compilerOptions.reactNamespace; + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile: SourceFile, cancellationToken: CancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. @@ -366,7 +400,7 @@ namespace ts { return emitResolver; } - function error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void { + function error(location: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): void { const diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2) : createCompilerDiagnostic(message, arg0, arg1, arg2); @@ -432,9 +466,7 @@ namespace ts { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } - forEach(source.declarations, node => { - target.declarations.push(node); - }); + addRange(target.declarations, source.declarations); if (source.members) { if (!target.members) target.members = createMap(); mergeSymbolTable(target.members, source.members); @@ -491,7 +523,7 @@ namespace ts { const moduleNotFoundError = !isInAmbientContext(moduleName.parent.parent) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError); + let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); if (!mainModule) { return; } @@ -536,6 +568,10 @@ namespace ts { return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } + function getObjectFlags(type: Type): ObjectFlags { + return type.flags & TypeFlags.Object ? (type).objectFlags : 0; + } + function isGlobalSourceFile(node: Node) { return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } @@ -589,21 +625,39 @@ namespace ts { // nodes are in different files and order cannot be determines return true; } - + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrNonStaticProperty(usage)) { + return true; + } const sourceFiles = host.getSourceFiles(); return indexOf(sourceFiles, declarationFile) <= indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage - // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== SyntaxKind.VariableDeclaration || - !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + if (declaration.kind === SyntaxKind.BindingElement) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + const errorBindingElement = getAncestor(usage, SyntaxKind.BindingElement) as BindingElement; + if (errorBindingElement) { + return getAncestorBindingPattern(errorBindingElement) !== getAncestorBindingPattern(declaration) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, SyntaxKind.VariableDeclaration) as Declaration, usage); + } + else if (declaration.kind === SyntaxKind.VariableDeclaration) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration as VariableDeclaration, usage); + } + return true; } + // declaration is after usage // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) - return isUsedInFunctionOrNonStaticProperty(declaration, usage); + const container = getEnclosingBlockScopeContainer(declaration); + return isUsedInFunctionOrNonStaticProperty(usage, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration: VariableDeclaration, usage: Node): boolean { const container = getEnclosingBlockScopeContainer(declaration); @@ -632,8 +686,7 @@ namespace ts { return false; } - function isUsedInFunctionOrNonStaticProperty(declaration: Declaration, usage: Node): boolean { - const container = getEnclosingBlockScopeContainer(declaration); + function isUsedInFunctionOrNonStaticProperty(usage: Node, container?: Node): boolean { let current = usage; while (current) { if (current === container) { @@ -657,6 +710,16 @@ namespace ts { } return false; } + + function getAncestorBindingPattern(node: Node): BindingPattern { + while (node) { + if (isBindingPattern(node)) { + return node; + } + node = node.parent; + } + return undefined; + } } // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and @@ -882,6 +945,7 @@ namespace ts { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); } @@ -922,7 +986,7 @@ namespace ts { if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { const decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) { - error(errorLocation, Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -992,6 +1056,18 @@ namespace ts { } } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { + if (meaning === SymbolFlags.Namespace) { + const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); + return true; + } + } + + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); @@ -1010,7 +1086,7 @@ namespace ts { Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, SyntaxKind.VariableDeclaration), errorLocation)) { + if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name)); } } @@ -1045,14 +1121,14 @@ namespace ts { } function getDeclarationOfAliasSymbol(symbol: Symbol): Declaration | undefined { - return forEach(symbol.declarations, d => isAliasSymbolDeclaration(d) ? d : undefined); + return find(symbol.declarations, isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node: ImportEqualsDeclaration): Symbol { if (node.moduleReference.kind === SyntaxKind.ExternalModuleReference) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference); } function getTargetOfImportClause(node: ImportClause): Symbol { @@ -1265,7 +1341,7 @@ namespace ts { } // This function is only for imports with entity names - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName: EntityName, importDeclaration: ImportEqualsDeclaration, dontResolveAlias?: boolean): Symbol { + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName: EntityName, dontResolveAlias?: boolean): Symbol { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // @@ -1336,16 +1412,16 @@ namespace ts { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, Diagnostics.Cannot_find_module_0); } - function resolveExternalModuleNameWorker(location: Node, moduleReferenceExpression: Expression, moduleNotFoundError: DiagnosticMessage): Symbol { + function resolveExternalModuleNameWorker(location: Node, moduleReferenceExpression: Expression, moduleNotFoundError: DiagnosticMessage, isForAugmentation = false): Symbol { if (moduleReferenceExpression.kind !== SyntaxKind.StringLiteral) { return; } const moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); } - function resolveExternalModule(location: Node, moduleReference: string, moduleNotFoundError: DiagnosticMessage, errorNode: Node): Symbol { + function resolveExternalModule(location: Node, moduleReference: string, moduleNotFoundError: DiagnosticMessage, errorNode: Node, isForAugmentation = false): Symbol { // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. const moduleName = escapeIdentifier(moduleReference); @@ -1354,17 +1430,14 @@ namespace ts { return; } - const isRelative = isExternalModuleNameRelative(moduleName); - if (!isRelative) { - const symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule); - if (symbol) { - // merged symbol is module declaration symbol combined with all augmentations - return getMergedSymbol(symbol); - } + const ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; } - + const isRelative = isExternalModuleNameRelative(moduleName); const resolvedModule = getResolvedModule(getSourceFileOfNode(location), moduleReference); - const sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule); + const sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { // merged symbol is module declaration symbol combined with all augmentations @@ -1384,15 +1457,36 @@ namespace ts { } } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (!isRelative && resolvedModule && !extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (compilerOptions.noImplicitAny && moduleNotFoundError) { + error(errorNode, + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, + moduleReference, + resolvedModule.resolvedFileName); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { // report errors only if it was requested - const tsExtension = tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, removeExtension(moduleName, tsExtension)); + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); } else { - error(errorNode, moduleNotFoundError, moduleName); + const tsExtension = tryExtractTypeScriptExtension(moduleName); + if (tsExtension) { + const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, removeExtension(moduleName, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleName); + } } } return undefined; @@ -1424,6 +1518,13 @@ namespace ts { return symbolsToArray(getExportsOfModule(moduleSymbol)); } + function tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined { + const symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable[memberName]; + } + } + function getExportsOfSymbol(symbol: Symbol): SymbolTable { return symbol.flags & SymbolFlags.Module ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -1583,8 +1684,9 @@ namespace ts { return type; } - function createObjectType(kind: TypeFlags, symbol?: Symbol): ObjectType { - const type = createType(kind); + function createObjectType(objectFlags: ObjectFlags, symbol?: Symbol): ObjectType { + const type = createType(TypeFlags.Object); + type.objectFlags = objectFlags; type.symbol = symbol; return type; } @@ -1614,7 +1716,7 @@ namespace ts { return result || emptyArray; } - function setObjectTypeMembers(type: ObjectType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType { + function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType { (type).members = members; (type).properties = getNamedMembers(members); (type).callSignatures = callSignatures; @@ -1625,7 +1727,7 @@ namespace ts { } function createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType { - return setObjectTypeMembers(createObjectType(TypeFlags.Anonymous, symbol), + return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -1660,7 +1762,19 @@ namespace ts { } function getAccessibleSymbolChain(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, useOnlyExternalAliasing: boolean): Symbol[] { - function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable): Symbol[] { + function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + + function getAccessibleSymbolChainFromSymbolTableWorker(symbols: SymbolTable, visitedSymbolTables: SymbolTable[]): Symbol[] { + if (contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + const result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable: Symbol, meaning: SymbolFlags) { // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { @@ -1682,34 +1796,36 @@ namespace ts { } } - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } + function trySymbolTable(symbols: SymbolTable) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } - // Check if symbol is any of the alias - return forEachProperty(symbols, symbolFromSymbolTable => { - if (symbolFromSymbolTable.flags & SymbolFlags.Alias - && symbolFromSymbolTable.name !== "export=" - && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) { - if (!useOnlyExternalAliasing || // We can use any type of alias to get the name - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { + // Check if symbol is any of the alias + return forEachProperty(symbols, symbolFromSymbolTable => { + if (symbolFromSymbolTable.flags & SymbolFlags.Alias + && symbolFromSymbolTable.name !== "export=" + && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) { + if (!useOnlyExternalAliasing || // We can use any type of alias to get the name + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { - const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } + const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - const accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + const accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { @@ -2176,7 +2292,7 @@ namespace ts { } writer.writeKeyword("this"); } - else if (type.flags & TypeFlags.Reference) { + else if (getObjectFlags(type) & ObjectFlags.Reference) { writeTypeReference(type, nextFlags); } else if (type.flags & TypeFlags.EnumLiteral) { @@ -2184,30 +2300,35 @@ namespace ts { writePunctuation(writer, SyntaxKind.DotToken); appendSymbolNameOnly(type.symbol, writer); } - else if (type.flags & (TypeFlags.Class | TypeFlags.Interface | TypeFlags.Enum | TypeFlags.TypeParameter)) { + else if (getObjectFlags(type) & ObjectFlags.ClassOrInterface || type.flags & (TypeFlags.Enum | TypeFlags.TypeParameter)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); } - else if (!(flags & TypeFormatFlags.InTypeAlias) && ((type.flags & TypeFlags.Anonymous && !(type).target) || type.flags & TypeFlags.UnionOrIntersection) && type.aliasSymbol && + else if (!(flags & TypeFormatFlags.InTypeAlias) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { - // We emit inferred type as type-alias at the current localtion if all the following is true - // the input type is has alias symbol that is accessible - // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) - // e.g.: export type Bar = () => [X, Y]; - // export type Foo = Bar; - // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) const typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & TypeFlags.UnionOrIntersection) { writeUnionOrIntersectionType(type, nextFlags); } - else if (type.flags & TypeFlags.Anonymous) { + else if (getObjectFlags(type) & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { writeAnonymousType(type, nextFlags); } else if (type.flags & TypeFlags.StringOrNumberLiteral) { writer.writeStringLiteral(literalTypeToString(type)); } + else if (type.flags & TypeFlags.Index) { + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType((type).type, TypeFormatFlags.InElementType); + } + else if (type.flags & TypeFlags.IndexedAccess) { + writeType((type).objectType, TypeFormatFlags.InElementType); + writePunctuation(writer, SyntaxKind.OpenBracketToken); + writeType((type).indexType, TypeFormatFlags.None); + writePunctuation(writer, SyntaxKind.CloseBracketToken); + } else { // Should never get here // { ... } @@ -2258,7 +2379,7 @@ namespace ts { writePunctuation(writer, SyntaxKind.OpenBracketToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } - else if (type.target.flags & TypeFlags.Tuple) { + else if (type.target.objectFlags & ObjectFlags.Tuple) { writePunctuation(writer, SyntaxKind.OpenBracketToken); writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); @@ -2410,6 +2531,13 @@ namespace ts { } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { + if (type.objectFlags & ObjectFlags.Mapped) { + if (getConstraintTypeFromMappedType(type).flags & (TypeFlags.TypeParameter | TypeFlags.Index)) { + writeMappedType(type); + return; + } + } + const resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { @@ -2448,6 +2576,13 @@ namespace ts { writePunctuation(writer, SyntaxKind.OpenBraceToken); writer.writeLine(); writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, SyntaxKind.CloseBraceToken); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + + function writeObjectLiteralType(resolved: ResolvedType) { for (const signature of resolved.callSignatures) { buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); @@ -2480,9 +2615,33 @@ namespace ts { writer.writeLine(); } } + } + + function writeMappedType(type: MappedType) { + writePunctuation(writer, SyntaxKind.OpenBraceToken); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, SyntaxKind.ReadonlyKeyword); + writeSpace(writer); + } + writePunctuation(writer, SyntaxKind.OpenBracketToken); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, SyntaxKind.InKeyword); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), TypeFormatFlags.None); + writePunctuation(writer, SyntaxKind.CloseBracketToken); + if (type.declaration.questionToken) { + writePunctuation(writer, SyntaxKind.QuestionToken); + } + writePunctuation(writer, SyntaxKind.ColonToken); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), TypeFormatFlags.None); + writePunctuation(writer, SyntaxKind.SemicolonToken); + writer.writeLine(); writer.decreaseIndent(); writePunctuation(writer, SyntaxKind.CloseBraceToken); - inObjectTypeLiteral = saveInObjectTypeLiteral; } } @@ -2548,7 +2707,7 @@ namespace ts { } Debug.assert(bindingElement.kind === SyntaxKind.BindingElement); if (bindingElement.propertyName) { - writer.writeSymbol(getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); } @@ -2581,7 +2740,7 @@ namespace ts { } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); let flags = TypeFormatFlags.InFirstTypeArgument; @@ -2860,7 +3019,6 @@ namespace ts { return getSymbolLinks(target).declaredType; } if (propertyName === TypeSystemPropertyName.ResolvedBaseConstructorType) { - Debug.assert(!!((target).flags & TypeFlags.Class)); return (target).resolvedBaseConstructorType; } if (propertyName === TypeSystemPropertyName.ResolvedReturnType) { @@ -2927,24 +3085,37 @@ namespace ts { return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function getTextOfPropertyName(name: PropertyName): string { - switch (name.kind) { - case SyntaxKind.Identifier: - return (name).text; - case SyntaxKind.StringLiteral: - case SyntaxKind.NumericLiteral: - return (name).text; - case SyntaxKind.ComputedPropertyName: - if (isStringOrNumericLiteral((name).expression.kind)) { - return ((name).expression).text; - } - } - - return undefined; + function isComputedNonLiteralName(name: PropertyName): boolean { + return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((name).expression); } - function isComputedNonLiteralName(name: PropertyName): boolean { - return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((name).expression.kind); + function getRestType(source: Type, properties: PropertyName[], symbol: Symbol): Type { + source = filterType(source, t => !(t.flags & TypeFlags.Nullable)); + if (source.flags & TypeFlags.Never) { + return emptyObjectType; + } + + if (source.flags & TypeFlags.Union) { + return mapType(source, t => getRestType(t, properties, symbol)); + } + + const members = createMap(); + const names = createMap(); + for (const name of properties) { + names[getTextOfPropertyName(name)] = true; + } + for (const prop of getPropertiesOfType(source)) { + const inNamesToRemove = prop.name in names; + const isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected); + const isMethod = prop.flags & SymbolFlags.Method; + const isSetOnlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor); + if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) { + members[prop.name] = prop; + } + } + const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); + const numberIndexInfo = getIndexInfoOfType(source, IndexKind.Number); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } /** Return the inferred type for a binding element */ @@ -2967,26 +3138,41 @@ namespace ts { let type: Type; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { - // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - const name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - // computed properties with non-literal names are treated as 'any' - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + const literalMembers: PropertyName[] = []; + for (const element of pattern.elements) { + if (!(element as BindingElement).dotDotDotToken) { + literalMembers.push(element.propertyName || element.name as Identifier); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + const name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - const text = getTextOfPropertyName(name); + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + const text = getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) || - getIndexTypeOfType(parentType, IndexKind.String); - if (!type) { - error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name)); - return unknownType; + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) || + getIndexTypeOfType(parentType, IndexKind.String); + if (!type) { + error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name)); + return unknownType; + } } } else { @@ -2994,7 +3180,11 @@ namespace ts { // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); - if (!declaration.dotDotDotToken) { + if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + else { // Use specific property type when parent is a tuple or numeric index type when parent is an array const propName = "" + indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) @@ -3010,10 +3200,6 @@ namespace ts { return unknownType; } } - else { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); - } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. @@ -3026,44 +3212,21 @@ namespace ts { } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration) { - const jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); - if (jsDocType) { - return getTypeFromTypeNode(jsDocType); + const jsdocType = getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); } - } - - function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration): JSDocType { - // First, see if this node has an @type annotation on it directly. - const typeTag = getJSDocTypeTag(declaration); - if (typeTag && typeTag.typeExpression) { - return typeTag.typeExpression.type; - } - - if (declaration.kind === SyntaxKind.VariableDeclaration && - declaration.parent.kind === SyntaxKind.VariableDeclarationList && - declaration.parent.parent.kind === SyntaxKind.VariableStatement) { - - // @type annotation might have been on the variable statement, try that instead. - const annotation = getJSDocTypeTag(declaration.parent.parent); - if (annotation && annotation.typeExpression) { - return annotation.typeExpression.type; - } - } - else if (declaration.kind === SyntaxKind.Parameter) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - const paramTag = getCorrespondingJSDocParameterTag(declaration); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type; - } - } - return undefined; } - function isAutoVariableInitializer(initializer: Expression) { - const expr = initializer && skipParentheses(initializer); - return !expr || expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; + function isNullOrUndefined(node: Expression) { + const expr = skipParentheses(node); + return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; + } + + function isEmptyArrayLiteral(node: Expression) { + const expr = skipParentheses(node); + return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr).elements.length === 0; } function addOptionality(type: Type, optional: boolean): Type { @@ -3082,9 +3245,11 @@ namespace ts { } } - // A variable declared in a for..in statement is always of type string + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. if (declaration.parent.parent.kind === SyntaxKind.ForInStatement) { - return stringType; + const indexType = getIndexType(checkNonNullExpression((declaration.parent.parent).expression)); + return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? indexType : stringType; } if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement) { @@ -3104,12 +3269,20 @@ namespace ts { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } - // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer - // or a 'null' or 'undefined' initializer. - if (declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && - !(getCombinedNodeFlags(declaration) & NodeFlags.Const) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && - !isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { - return autoType; + if ((compilerOptions.noImplicitAny || declaration.flags & NodeFlags.JavaScriptFile) && + declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && + !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !isInAmbientContext(declaration)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } } if (declaration.kind === SyntaxKind.Parameter) { @@ -3131,8 +3304,7 @@ namespace ts { // Use contextual parameter type if one is available let type: Type; if (declaration.symbol.name === "this") { - const thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + type = getContextualThisParameterType(func); } else { type = getContextuallyTypedParameterType(declaration); @@ -3181,6 +3353,7 @@ namespace ts { // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern: ObjectBindingPattern, includePatternInType: boolean, reportErrors: boolean): Type { const members = createMap(); + let stringIndexInfo: IndexInfo; let hasComputedProperties = false; forEach(pattern.elements, e => { const name = e.propertyName || e.name; @@ -3189,6 +3362,10 @@ namespace ts { hasComputedProperties = true; return; } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } const text = getTextOfPropertyName(name); const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); @@ -3197,12 +3374,12 @@ namespace ts { symbol.bindingElement = e; members[symbol.name] = symbol; }); - const result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + const result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { result.pattern = pattern; } if (hasComputedProperties) { - result.isObjectLiteralPatternWithComputedProperties = true; + result.objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties; } return result; } @@ -3212,7 +3389,7 @@ namespace ts { const elements = pattern.elements; const lastElement = lastOrUndefined(elements); if (elements.length === 0 || (!isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType; + return languageVersion >= ScriptTarget.ES2015 ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); @@ -3288,7 +3465,7 @@ namespace ts { } // Handle catch clause variables const declaration = symbol.valueDeclaration; - if (declaration.parent.kind === SyntaxKind.CatchClause) { + if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } // Handle export default expressions @@ -3313,9 +3490,9 @@ namespace ts { declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { // Use JS Doc type if present on parent expression statement if (declaration.flags & NodeFlags.JavaScriptFile) { - const typeTag = getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); + const jsdocType = getJSDocType(declaration.parent); + if (jsdocType) { + return links.type = getTypeFromTypeNode(jsdocType); } } const declaredTypes = map(symbol.declarations, @@ -3329,20 +3506,7 @@ namespace ts { } if (!popTypeResolution()) { - if ((symbol.valueDeclaration).type) { - // Variable has type annotation that circularly references the variable itself - type = unknownType; - error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, - symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, - symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -3436,11 +3600,11 @@ namespace ts { function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === SyntaxKind.ModuleDeclaration && isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & SymbolFlags.Module && isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - const type = createObjectType(TypeFlags.Anonymous, symbol); + const type = createObjectType(ObjectFlags.Anonymous, symbol); links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type; } @@ -3476,11 +3640,33 @@ namespace ts { function getTypeOfInstantiatedSymbol(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { + return unknownType; + } + let type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol: Symbol) { + // Check if variable has type annotation that circularly references the variable itself + if ((symbol.valueDeclaration).type) { + error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, + symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, + symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol: Symbol): Type { if (symbol.flags & SymbolFlags.Instantiated) { return getTypeOfInstantiatedSymbol(symbol); @@ -3503,8 +3689,8 @@ namespace ts { return unknownType; } - function getTargetType(type: ObjectType): Type { - return type.flags & TypeFlags.Reference ? (type).target : type; + function getTargetType(type: Type): Type { + return getObjectFlags(type) & ObjectFlags.Reference ? (type).target : type; } function hasBaseType(type: InterfaceType, checkBase: InterfaceType) { @@ -3580,23 +3766,23 @@ namespace ts { } function isConstructorType(type: Type): boolean { - return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Construct).length > 0; + return type.flags & TypeFlags.Object && getSignaturesOfType(type, SignatureKind.Construct).length > 0; } function getBaseTypeNodeOfClass(type: InterfaceType): ExpressionWithTypeArguments { return getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); } - function getConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { + function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[]): Signature[] { const typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount); } - function getInstantiatedConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { + function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[]): Signature[] { let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - const typeArguments = map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments)); } return signatures; @@ -3607,7 +3793,7 @@ namespace ts { // unknownType if an error occurred during resolution of the extends expression, // nullType if the extends expression is the null value, or // an object type with at least one construct signature. - function getBaseConstructorTypeOfClass(type: InterfaceType): ObjectType { + function getBaseConstructorTypeOfClass(type: InterfaceType): Type { if (!type.resolvedBaseConstructorType) { const baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { @@ -3617,10 +3803,10 @@ namespace ts { return unknownType; } const baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & TypeFlags.ObjectType) { + if (baseConstructorType.flags & TypeFlags.Object) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. - resolveStructuredTypeMembers(baseConstructorType); + resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); @@ -3637,7 +3823,7 @@ namespace ts { function getBaseTypes(type: InterfaceType): ObjectType[] { if (!type.resolvedBaseTypes) { - if (type.flags & TypeFlags.Tuple) { + if (type.objectFlags & ObjectFlags.Tuple) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } else if (type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { @@ -3657,8 +3843,8 @@ namespace ts { function resolveBaseTypesOfClass(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - const baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & TypeFlags.ObjectType)) { + const baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & TypeFlags.Object)) { return; } const baseTypeNode = getBaseTypeNodeOfClass(type); @@ -3682,23 +3868,33 @@ namespace ts { } baseType = getReturnTypeOfSignature(constructors[0]); } + + // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters + const valueDecl = type.symbol.valueDeclaration; + if (valueDecl && isInJavaScriptFile(valueDecl)) { + const augTag = getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface))) { + if (!(getObjectFlags(getTargetType(baseType)) & ObjectFlags.ClassOrInterface)) { error(baseTypeNode.expression, Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, + error(valueDecl, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); return; } if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; + type.resolvedBaseTypes = [baseType]; } else { - type.resolvedBaseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } } @@ -3721,13 +3917,13 @@ namespace ts { for (const node of getInterfaceBaseTypeNodes(declaration)) { const baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) { + if (getObjectFlags(getTargetType(baseType)) & ObjectFlags.ClassOrInterface) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; + type.resolvedBaseTypes = [baseType]; } else { - type.resolvedBaseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } } else { @@ -3771,7 +3967,7 @@ namespace ts { function getDeclaredTypeOfClassOrInterface(symbol: Symbol): InterfaceType { const links = getSymbolLinks(symbol); if (!links.declaredType) { - const kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; + const kind = symbol.flags & SymbolFlags.Class ? ObjectFlags.Class : ObjectFlags.Interface; const type = links.declaredType = createObjectType(kind, symbol); const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -3780,8 +3976,8 @@ namespace ts { // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === TypeFlags.Class || !isIndependentInterface(symbol)) { - type.flags |= TypeFlags.Reference; + if (outerTypeParameters || localTypeParameters || kind === ObjectFlags.Class || !isIndependentInterface(symbol)) { + type.objectFlags |= ObjectFlags.Reference; type.typeParameters = concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -3807,7 +4003,6 @@ namespace ts { return unknownType; } - const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); let type: Type; if (declaration) { @@ -3820,16 +4015,17 @@ namespace ts { } else { declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; + const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; links.instantiations = createMap(); - links.instantiations[getTypeListId(links.typeParameters)] = type; + links.instantiations[getTypeListId(typeParameters)] = type; } } else { @@ -4077,8 +4273,8 @@ namespace ts { return type; } - function getTypeWithThisArgument(type: ObjectType, thisArgument?: Type) { - if (type.flags & TypeFlags.Reference) { + function getTypeWithThisArgument(type: Type, thisArgument?: Type) { + if (getObjectFlags(type) & ObjectFlags.Reference) { return createTypeReference((type).target, concatenate((type).typeArguments, [thisArgument || (type).target.thisType])); } @@ -4103,8 +4299,8 @@ namespace ts { else { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); - callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); - constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } @@ -4115,7 +4311,7 @@ namespace ts { } const thisArgument = lastOrUndefined(typeArguments); for (const baseType of baseTypes) { - const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct)); @@ -4123,7 +4319,7 @@ namespace ts { numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, IndexKind.Number); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type: InterfaceType): void { @@ -4165,13 +4361,13 @@ namespace ts { return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } const baseTypeNode = getBaseTypeNodeOfClass(classType); - const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); + const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); const typeArgCount = typeArguments ? typeArguments.length : 0; const result: Signature[] = []; for (const baseSig of baseSignatures) { const typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - const sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + const sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -4270,7 +4466,7 @@ namespace ts { const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); const stringIndexInfo = getUnionIndexInfo(type.types, IndexKind.String); const numberIndexInfo = getUnionIndexInfo(type.types, IndexKind.Number); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1: Type, type2: Type): Type { @@ -4282,6 +4478,11 @@ namespace ts { getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); } + function unionSpreadIndexInfos(info1: IndexInfo, info2: IndexInfo): IndexInfo { + return info1 && info2 && createIndexInfo( + getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function resolveIntersectionTypeMembers(type: IntersectionType) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). @@ -4295,18 +4496,18 @@ namespace ts { stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, IndexKind.String)); numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, IndexKind.Number)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type: AnonymousType) { const symbol = type.symbol; if (type.target) { const members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - const callSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Call), type.mapper, instantiateSignature); - const constructSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper, instantiateSignature); + const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, SignatureKind.Call), type.mapper); + const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper); const stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.String), type.mapper); const numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.Number), type.mapper); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & SymbolFlags.TypeLiteral) { const members = symbol.members; @@ -4314,7 +4515,7 @@ namespace ts { const constructSignatures = getSignaturesOfSymbol(members["__new"]); const stringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String); const numberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number); - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module @@ -4330,13 +4531,13 @@ namespace ts { constructSignatures = getDefaultConstructSignatures(classType); } const baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & TypeFlags.ObjectType) { + if (baseConstructorType.flags & TypeFlags.Object) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } const numberIndexInfo = symbol.flags & SymbolFlags.Enum ? enumNumberIndexInfo : undefined; - setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are // in the process of resolving (see issue #6072). The temporarily empty signature list @@ -4347,16 +4548,127 @@ namespace ts { } } - function resolveStructuredTypeMembers(type: ObjectType): ResolvedType { + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type: MappedType) { + const members: SymbolTable = createMap(); + let stringIndexInfo: IndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + const typeParameter = getTypeParameterFromMappedType(type); + const constraintType = getConstraintTypeFromMappedType(type); + const templateType = getTemplateTypeFromMappedType(type); + const modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + const templateReadonly = !!type.declaration.readonlyToken; + const templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === SyntaxKind.TypeOperator) { + // We have a { [P in keyof T]: X } + forEachType(getLiteralTypeFromPropertyNames(modifiersType), addMemberForKeyType); + if (getIndexInfoOfType(modifiersType, IndexKind.String)) { + addMemberForKeyType(stringType); + } + } + else { + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + const keyType = constraintType.flags & TypeFlags.TypeVariable ? getApparentType(constraintType) : constraintType; + const iterationType = keyType.flags & TypeFlags.Index ? getIndexType(getApparentType((keyType).type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + + function addMemberForKeyType(t: Type) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + const iterationMapper = createUnaryTypeMapper(typeParameter, t); + const templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + const propType = instantiateType(templateType, templateMapper); + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & TypeFlags.StringLiteral) { + const propName = (t).text; + const modifiersProp = getPropertyOfType(modifiersType, propName); + const isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & SymbolFlags.Optional); + const prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | (isOptional ? SymbolFlags.Optional : 0), propName); + prop.type = propType; + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); + members[propName] = prop; + } + else if (t.flags & TypeFlags.String) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + + function getTypeParameterFromMappedType(type: MappedType) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + + function getConstraintTypeFromMappedType(type: MappedType) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + + function getTemplateTypeFromMappedType(type: MappedType) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + + function getModifiersTypeFromMappedType(type: MappedType) { + if (!type.modifiersType) { + const constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === SyntaxKind.TypeOperator) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode((constraintDeclaration).type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + const declaredType = getTypeFromMappedTypeNode(type.declaration); + const constraint = getConstraintTypeFromMappedType(declaredType); + const extendedConstraint = constraint && constraint.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & TypeFlags.Index ? instantiateType((extendedConstraint).type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + + function getErasedTemplateTypeFromMappedType(type: MappedType) { + return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); + } + + function isGenericMappedType(type: Type) { + if (getObjectFlags(type) & ObjectFlags.Mapped) { + const constraintType = getConstraintTypeFromMappedType(type); + return maybeTypeOfKind(constraintType, TypeFlags.TypeVariable | TypeFlags.Index); + } + return false; + } + + function resolveStructuredTypeMembers(type: StructuredType): ResolvedType { if (!(type).members) { - if (type.flags & TypeFlags.Reference) { - resolveTypeReferenceMembers(type); - } - else if (type.flags & (TypeFlags.Class | TypeFlags.Interface)) { - resolveClassOrInterfaceMembers(type); - } - else if (type.flags & TypeFlags.Anonymous) { - resolveAnonymousTypeMembers(type); + if (type.flags & TypeFlags.Object) { + if ((type).objectFlags & ObjectFlags.Reference) { + resolveTypeReferenceMembers(type); + } + else if ((type).objectFlags & ObjectFlags.ClassOrInterface) { + resolveClassOrInterfaceMembers(type); + } + else if ((type).objectFlags & ObjectFlags.Anonymous) { + resolveAnonymousTypeMembers(type); + } + else if ((type).objectFlags & ObjectFlags.Mapped) { + resolveMappedTypeMembers(type); + } } else if (type.flags & TypeFlags.Union) { resolveUnionTypeMembers(type); @@ -4370,7 +4682,7 @@ namespace ts { /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type: Type): Symbol[] { - if (type.flags & TypeFlags.ObjectType) { + if (type.flags & TypeFlags.Object) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -4379,7 +4691,7 @@ namespace ts { /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type: Type, name: string): Symbol { - if (type.flags & TypeFlags.ObjectType) { + if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); const symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { @@ -4416,18 +4728,20 @@ namespace ts { function getPropertiesOfType(type: Type): Symbol[] { type = getApparentType(type); - return type.flags & TypeFlags.UnionOrIntersection ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & TypeFlags.UnionOrIntersection ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter * as the type argument for the 'this' type. */ - function getApparentTypeOfTypeParameter(type: TypeParameter) { + function getApparentTypeOfTypeVariable(type: TypeVariable) { if (!type.resolvedApparentType) { - let constraintType = getConstraintOfTypeParameter(type); + let constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & TypeFlags.TypeParameter) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } @@ -4440,22 +4754,12 @@ namespace ts { * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type: Type): Type { - if (type.flags & TypeFlags.TypeParameter) { - type = getApparentTypeOfTypeParameter(type); - } - if (type.flags & TypeFlags.StringLike) { - type = globalStringType; - } - else if (type.flags & TypeFlags.NumberLike) { - type = globalNumberType; - } - else if (type.flags & TypeFlags.BooleanLike) { - type = globalBooleanType; - } - else if (type.flags & TypeFlags.ESSymbol) { - type = getGlobalESSymbolType(); - } - return type; + const t = type.flags & TypeFlags.TypeVariable ? getApparentTypeOfTypeVariable(type) : type; + return t.flags & TypeFlags.StringLike ? globalStringType : + t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BooleanLike ? globalBooleanType : + t.flags & TypeFlags.ESSymbol ? getGlobalESSymbolType() : + t; } function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { @@ -4480,6 +4784,7 @@ namespace ts { if (isReadonlySymbol(prop)) { isReadonly = true; } + } else if (containingType.flags & TypeFlags.Union) { isPartial = true; @@ -4552,8 +4857,8 @@ namespace ts { */ function getPropertyOfType(type: Type, name: string): Symbol { type = getApparentType(type); - if (type.flags & TypeFlags.ObjectType) { - const resolved = resolveStructuredTypeMembers(type); + if (type.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(type); const symbol = resolved.members[name]; if (symbol && symbolIsValue(symbol)) { return symbol; @@ -4666,20 +4971,30 @@ namespace ts { if (node.type && node.type.kind === SyntaxKind.JSDocOptionalType) { return true; } + const paramTags = getJSDocParameterTags(node); + if (paramTags) { + for (const paramTag of paramTags) { + if (paramTag.isBracketed) { + return true; + } - const paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag) { - if (paramTag.isBracketed) { - return true; - } - - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === SyntaxKind.JSDocOptionalType; + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === SyntaxKind.JSDocOptionalType; + } } } } } + function tryFindAmbientModule(moduleName: string, withAugmentations: boolean) { + if (isExternalModuleNameRelative(moduleName)) { + return undefined; + } + const symbol = getSymbol(globals, `"${moduleName}"`, SymbolFlags.ValueModule); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node: ParameterDeclaration) { if (hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; @@ -4776,9 +5091,6 @@ namespace ts { if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } const classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) @@ -4786,7 +5098,7 @@ namespace ts { const typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : getTypeParametersFromJSDocTemplate(declaration); - const returnType = getSignatureReturnTypeFromDeclaration(declaration, minArgumentCount, isJSConstructSignature, classType); + const returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); const typePredicate = declaration.type && declaration.type.kind === SyntaxKind.TypePredicate ? createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode) : undefined; @@ -4796,7 +5108,7 @@ namespace ts { return links.resolvedSignature; } - function getSignatureReturnTypeFromDeclaration(declaration: SignatureDeclaration, minArgumentCount: number, isJSConstructSignature: boolean, classType: Type) { + function getSignatureReturnTypeFromDeclaration(declaration: SignatureDeclaration, isJSConstructSignature: boolean, classType: Type) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); } @@ -4914,7 +5226,7 @@ namespace ts { function getRestTypeOfSignature(signature: Signature): Type { if (signature.hasRestParameter) { const type = getTypeOfSymbol(lastOrUndefined(signature.parameters)); - if (type.flags & TypeFlags.Reference && (type).target === globalArrayType) { + if (getObjectFlags(type) & ObjectFlags.Reference && (type).target === globalArrayType) { return (type).typeArguments[0]; } } @@ -4922,6 +5234,12 @@ namespace ts { } function getSignatureInstantiation(signature: Signature, typeArguments: Type[]): Signature { + const instantiations = signature.instantiations || (signature.instantiations = createMap()); + const id = getTypeListId(typeArguments); + return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments)); + } + + function createSignatureInstantiation(signature: Signature, typeArguments: Type[]): Signature { return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } @@ -4940,7 +5258,7 @@ namespace ts { // will result in a different declaration kind. if (!signature.isolatedSignatureType) { const isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; - const type = createObjectType(TypeFlags.Anonymous); + const type = createObjectType(ObjectFlags.Anonymous); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -5022,6 +5340,12 @@ namespace ts { return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type: TypeVariable): Type { + return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type) : + type.flags & TypeFlags.IndexedAccess ? (type).constraint : + undefined; + } + function getParentSymbolOfTypeParameter(typeParameter: TypeParameter): Symbol { return getSymbolOfNode(getDeclarationOfKind(typeParameter.symbol, SyntaxKind.TypeParameter).parent); } @@ -5068,9 +5392,8 @@ namespace ts { const id = getTypeListId(typeArguments); let type = target.instantiations[id]; if (!type) { - const propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - const flags = TypeFlags.Reference | propagatedFlags; - type = target.instantiations[id] = createObjectType(flags, target.symbol); + type = target.instantiations[id] = createObjectType(ObjectFlags.Reference, target.symbol); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } @@ -5078,7 +5401,9 @@ namespace ts { } function cloneTypeReference(source: TypeReference): TypeReference { - const type = createObjectType(source.flags, source.symbol); + const type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; type.target = source.target; type.typeArguments = source.typeArguments; return type; @@ -5100,7 +5425,7 @@ namespace ts { // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, concatenate(type.outerTypeParameters, map(node.typeArguments, getTypeFromTypeNodeNoAlias))); + return createTypeReference(type, concatenate(type.outerTypeParameters, map(node.typeArguments, getTypeFromTypeNode))); } if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -5109,21 +5434,27 @@ namespace ts { return type; } + function getTypeAliasInstantiation(symbol: Symbol, typeArguments: Type[]): Type { + const type = getDeclaredTypeOfSymbol(symbol); + const links = getSymbolLinks(symbol); + const typeParameters = links.typeParameters; + const id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments))); + } + // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { const type = getDeclaredTypeOfSymbol(symbol); - const links = getSymbolLinks(symbol); - const typeParameters = links.typeParameters; + const typeParameters = getSymbolLinks(symbol).typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - const typeArguments = map(node.typeArguments, getTypeFromTypeNodeNoAlias); - const id = getTypeListId(typeArguments); - return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + const typeArguments = map(node.typeArguments, getTypeFromTypeNode); + return getTypeAliasInstantiation(symbol, typeArguments); } if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); @@ -5161,10 +5492,7 @@ namespace ts { return undefined; } - function resolveTypeReferenceName( - node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, - typeReferenceName: EntityNameExpression | EntityName) { - + function resolveTypeReferenceName(typeReferenceName: EntityNameExpression | EntityName) { if (!typeReferenceName) { return unknownSymbol; } @@ -5202,7 +5530,7 @@ namespace ts { let type: Type; if (node.kind === SyntaxKind.JSDocTypeReference) { const typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(node, typeReferenceName); + symbol = resolveTypeReferenceName(typeReferenceName); type = getTypeReferenceType(node, symbol); } else { @@ -5256,7 +5584,7 @@ namespace ts { return arity ? emptyGenericType : emptyObjectType; } const type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & TypeFlags.ObjectType)) { + if (!(type.flags & TypeFlags.Object)) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -5306,7 +5634,7 @@ namespace ts { /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ - function createTypeFromGenericGlobalType(genericGlobalType: GenericType, typeArguments: Type[]): Type { + function createTypeFromGenericGlobalType(genericGlobalType: GenericType, typeArguments: Type[]): ObjectType { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -5318,7 +5646,7 @@ namespace ts { return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(), [elementType]); } - function createArrayType(elementType: Type): Type { + function createArrayType(elementType: Type): ObjectType { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } @@ -5347,7 +5675,7 @@ namespace ts { property.type = typeParameter; properties.push(property); } - const type = createObjectType(TypeFlags.Tuple | TypeFlags.Reference); + const type = createObjectType(ObjectFlags.Tuple | ObjectFlags.Reference); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -5377,7 +5705,7 @@ namespace ts { function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNodeNoAlias)); + links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNode)); } return links.resolvedType; } @@ -5390,6 +5718,7 @@ namespace ts { containsString?: boolean; containsNumber?: boolean; containsStringOrNumberLiteral?: boolean; + unionIndex?: number; } function binarySearchTypes(types: Type[], type: Type): number { @@ -5436,7 +5765,8 @@ namespace ts { const len = typeSet.length; const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); if (index < 0) { - if (!(flags & TypeFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) { + if (!(flags & TypeFlags.Object && (type).objectFlags & ObjectFlags.Anonymous && + type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } @@ -5558,7 +5888,7 @@ namespace ts { let type = unionTypes[id]; if (!type) { const propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); - type = unionTypes[id] = createObjectType(TypeFlags.Union | propagatedFlags); + type = unionTypes[id] = createType(TypeFlags.Union | propagatedFlags); type.types = types; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; @@ -5566,10 +5896,11 @@ namespace ts { return type; } - function getTypeFromUnionTypeNode(node: UnionTypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { + function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, + getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -5582,6 +5913,9 @@ namespace ts { typeSet.containsAny = true; } else if (!(type.flags & TypeFlags.Never) && (strictNullChecks || !(type.flags & TypeFlags.Nullable)) && !contains(typeSet, type)) { + if (type.flags & TypeFlags.Union && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } typeSet.push(type); } } @@ -5594,6 +5928,11 @@ namespace ts { } } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. @@ -5611,11 +5950,19 @@ namespace ts { if (typeSet.length === 1) { return typeSet[0]; } + const unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + const unionType = typeSet[unionIndex]; + return getUnionType(map(unionType.types, t => getIntersectionType(replaceElement(typeSet, unionIndex, t))), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + } const id = getTypeListId(typeSet); let type = intersectionTypes[id]; if (!type) { const propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable); - type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | propagatedFlags); + type = intersectionTypes[id] = createType(TypeFlags.Intersection | propagatedFlags); type.types = typeSet; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; @@ -5623,26 +5970,324 @@ namespace ts { return type; } - function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { + function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNode), + getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node: Node, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { + function getIndexTypeForGenericType(type: TypeVariable | UnionOrIntersectionType) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(TypeFlags.Index); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + + function getLiteralTypeFromPropertyName(prop: Symbol) { + return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.name, "__@") ? + neverType : + getLiteralTypeForText(TypeFlags.StringLiteral, unescapeIdentifier(prop.name)); + } + + function getLiteralTypeFromPropertyNames(type: Type) { + return getUnionType(map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + + function getIndexType(type: Type): Type { + return maybeTypeOfKind(type, TypeFlags.TypeVariable) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & ObjectFlags.Mapped ? getConstraintTypeFromMappedType(type) : + type.flags & TypeFlags.Any || getIndexInfoOfType(type, IndexKind.String) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + + function getIndexTypeOrString(type: Type): Type { + const indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + + function getTypeFromTypeOperatorNode(node: TypeOperatorNode) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + + function createIndexedAccessType(objectType: Type, indexType: Type) { + const type = createType(TypeFlags.IndexedAccess); + type.objectType = objectType; + type.indexType = indexType; + // We eagerly compute the constraint of the indexed access type such that circularity + // errors are immediately caught and reported. For example, class C { x: this["x"] } + // becomes an error only when the constraint is eagerly computed. + if (type.objectType.flags & TypeFlags.StructuredType) { + // The constraint of T[K], where T is an object, union, or intersection type, + // is the type of the string index signature of T, if any. + type.constraint = getIndexTypeOfType(type.objectType, IndexKind.String); + } + else if (type.objectType.flags & TypeFlags.TypeVariable) { + // The constraint of T[K], where T is a type variable, is A[K], where A is the + // apparent type of T. + const apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind((type).indexType, TypeFlags.StringLike) ? + getIndexedAccessType(apparentType, (type).indexType) : + getIndexTypeOfType(apparentType, IndexKind.String); + } + } + return type; + } + + function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode, cacheSymbol: boolean) { + const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; + const propName = indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral | TypeFlags.EnumLiteral) ? + (indexType).text : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + getPropertyNameForKnownSymbolName(((accessExpression.argumentExpression).name).text) : + undefined; + if (propName) { + const prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { + if (isTypeAny(objectType)) { + return anyType; + } + const indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike) && getIndexInfoOfType(objectType, IndexKind.Number) || + getIndexInfoOfType(objectType, IndexKind.String) || + undefined; + if (indexInfo) { + if (accessExpression && isAssignmentTarget(accessExpression) && indexInfo.isReadonly) { + error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, IndexKind.Number)) { + error(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + if (accessNode) { + const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? (accessNode).argumentExpression : (accessNode).indexType; + if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, (indexType).text, typeToString(objectType)); + } + else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) { + error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } + else { + error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + } + return unknownType; + } + + function getIndexedAccessForMappedType(type: MappedType, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode) { + const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; + if (accessExpression && isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + const mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType); + const templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + + function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, TypeFlags.TypeVariable | TypeFlags.Index) || + maybeTypeOfKind(objectType, TypeFlags.TypeVariable) && !(accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression) || + isGenericMappedType(objectType)) { + if (objectType.flags & TypeFlags.Any) { + return objectType; + } + // We first check that the index type is assignable to 'keyof T' for the object type. + if (accessNode) { + if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { + error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return unknownType; + } + } + // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes + // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the + // type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise we defer the operation by creating an indexed access type. + const id = objectType.id + "," + indexType.id; + return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); + } + // In the following we resolve T[K] to the type of the property in T selected by K. + const apparentObjectType = getApparentType(objectType); + if (indexType.flags & TypeFlags.Union && !(indexType.flags & TypeFlags.Primitive)) { + const propTypes: Type[] = []; + for (const t of (indexType).types) { + const propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + } + + function getTypeFromIndexedAccessTypeNode(node: IndexedAccessTypeNode) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + + function getTypeFromMappedTypeNode(node: MappedTypeNode): Type { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const type = createObjectType(ObjectFlags.Mapped, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node: TypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - const type = createObjectType(TypeFlags.Anonymous, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + const aliasSymbol = getAliasSymbolForTypeNode(node); + if (isEmpty(node.symbol.members) && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + const type = createObjectType(ObjectFlags.Anonymous, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + } } return links.resolvedType; } + function getAliasSymbolForTypeNode(node: TypeNode) { + return node.parent.kind === SyntaxKind.TypeAliasDeclaration ? getSymbolOfNode(node.parent) : undefined; + } + + function getAliasTypeArgumentsForTypeNode(node: TypeNode) { + const symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left: Type, right: Type, isFromObjectLiteral: boolean): Type { + if (left.flags & TypeFlags.Any || right.flags & TypeFlags.Any) { + return anyType; + } + left = filterType(left, t => !(t.flags & TypeFlags.Nullable)); + if (left.flags & TypeFlags.Never) { + return right; + } + right = filterType(right, t => !(t.flags & TypeFlags.Nullable)); + if (right.flags & TypeFlags.Never) { + return left; + } + if (left.flags & TypeFlags.Union) { + return mapType(left, t => getSpreadType(t, right, isFromObjectLiteral)); + } + if (right.flags & TypeFlags.Union) { + return mapType(right, t => getSpreadType(left, t, isFromObjectLiteral)); + } + + const members = createMap(); + const skippedPrivateMembers = createMap(); + let stringIndexInfo: IndexInfo; + let numberIndexInfo: IndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, IndexKind.String); + numberIndexInfo = getIndexInfoOfType(right, IndexKind.Number); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, IndexKind.String), getIndexInfoOfType(right, IndexKind.String)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, IndexKind.Number), getIndexInfoOfType(right, IndexKind.Number)); + } + + for (const rightProp of getPropertiesOfType(right)) { + // we approximate own properties as non-methods plus methods that are inside the object literal + const isOwnProperty = !(rightProp.flags & SymbolFlags.Method) || isFromObjectLiteral; + const isSetterWithoutGetter = rightProp.flags & SymbolFlags.SetAccessor && !(rightProp.flags & SymbolFlags.GetAccessor); + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (ModifierFlags.Private | ModifierFlags.Protected)) { + skippedPrivateMembers[rightProp.name] = true; + } + else if (isOwnProperty && !isSetterWithoutGetter) { + members[rightProp.name] = rightProp; + } + } + for (const leftProp of getPropertiesOfType(left)) { + if (leftProp.flags & SymbolFlags.SetAccessor && !(leftProp.flags & SymbolFlags.GetAccessor) + || leftProp.name in skippedPrivateMembers) { + continue; + } + if (leftProp.name in members) { + const rightProp = members[leftProp.name]; + const rightType = getTypeOfSymbol(rightProp); + if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) { + const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations); + const flags = SymbolFlags.Property | SymbolFlags.Transient | (leftProp.flags & SymbolFlags.Optional); + const result = createSymbol(flags, leftProp.name); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); + members[leftProp.name] = result; + } + } + else { + members[leftProp.name] = leftProp; + } + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + } + function createLiteralType(flags: TypeFlags, text: string) { const type = createType(flags); type.text = text; @@ -5690,7 +6335,7 @@ namespace ts { function getTypeFromJSDocTupleType(node: JSDocTupleType): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - const types = map(node.types, getTypeFromTypeNodeNoAlias); + const types = map(node.types, getTypeFromTypeNode); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -5717,11 +6362,7 @@ namespace ts { return links.resolvedType; } - function getTypeFromTypeNodeNoAlias(type: TypeNode) { - return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); - } - - function getTypeFromTypeNode(node: TypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { + function getTypeFromTypeNode(node: TypeNode): Type { switch (node.kind) { case SyntaxKind.AnyKeyword: case SyntaxKind.JSDocAllType: @@ -5772,9 +6413,9 @@ namespace ts { return getTypeFromTupleTypeNode(node); case SyntaxKind.UnionType: case SyntaxKind.JSDocUnionType: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case SyntaxKind.IntersectionType: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case SyntaxKind.ParenthesizedType: case SyntaxKind.JSDocNullableType: case SyntaxKind.JSDocNonNullableType: @@ -5789,7 +6430,13 @@ namespace ts { case SyntaxKind.TypeLiteral: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.JSDocFunctionType: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case SyntaxKind.TypeOperator: + return getTypeFromTypeOperatorNode(node); + case SyntaxKind.IndexedAccessType: + return getTypeFromIndexedAccessTypeNode(node); + case SyntaxKind.MappedType: + return getTypeFromMappedTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case SyntaxKind.Identifier: @@ -5816,6 +6463,19 @@ namespace ts { return items; } + function instantiateTypes(types: Type[], mapper: TypeMapper) { + return instantiateList(types, mapper, instantiateType); + } + + function instantiateSignatures(signatures: Signature[], mapper: TypeMapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + + function instantiateCached(type: T, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): T { + const instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function createUnaryTypeMapper(source: Type, target: Type): TypeMapper { return t => t === source ? target : t; } @@ -5842,7 +6502,6 @@ namespace ts { count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } @@ -5954,32 +6613,62 @@ namespace ts { return result; } - function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper): ObjectType { - if (mapper.instantiations) { - const cachedType = mapper.instantiations[type.id]; - if (cachedType) { - return cachedType; + function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper): AnonymousType { + const result = createObjectType(ObjectFlags.Anonymous | ObjectFlags.Instantiated, type.symbol); + result.target = type.objectFlags & ObjectFlags.Instantiated ? type.target : type; + result.mapper = type.objectFlags & ObjectFlags.Instantiated ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + + function instantiateMappedType(type: MappedType, mapper: TypeMapper): Type { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + const constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & TypeFlags.Index) { + const typeVariable = (constraintType).type; + const mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapType(mappedTypeVariable, t => { + if (isMappableType(t)) { + const replacementMapper = createUnaryTypeMapper(typeVariable, t); + const combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper); + combinedMapper.mappedTypes = mapper.mappedTypes; + return instantiateMappedObjectType(type, combinedMapper); + } + return t; + }); } } - else { - mapper.instantiations = []; - } - // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - const result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); - result.target = type; - result.mapper = mapper; + return instantiateMappedObjectType(type, mapper); + } + + function isMappableType(type: Type) { + return type.flags & (TypeFlags.TypeParameter | TypeFlags.Object | TypeFlags.Intersection | TypeFlags.IndexedAccess); + } + + function instantiateMappedObjectType(type: MappedType, mapper: TypeMapper): Type { + const result = createObjectType(ObjectFlags.Mapped | ObjectFlags.Instantiated, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; - mapper.instantiations[type.id] = result; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } function isSymbolInScopeOfMappedTypeParameter(symbol: Symbol, mapper: TypeMapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } const mappedTypes = mapper.mappedTypes; // Starting with the parent of the symbol's declaration, check if the mapper maps any of // the type parameters introduced by enclosing declarations. We just pick the first // declaration since multiple declarations will all have the same parent anyway. - let node = symbol.declarations[0].parent; + let node: Node = symbol.declarations[0]; while (node) { switch (node.kind) { case SyntaxKind.FunctionType: @@ -5999,7 +6688,7 @@ namespace ts { case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.TypeAliasDeclaration: - const declaration = node; + const declaration = node as DeclarationWithTypeParameters; if (declaration.typeParameters) { for (const d of declaration.typeParameters) { if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { @@ -6014,6 +6703,14 @@ namespace ts { } } break; + case SyntaxKind.JSDocFunctionType: + const func = node as JSDocFunctionType; + for (const p of func.parameters) { + if (contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; case SyntaxKind.ModuleDeclaration: case SyntaxKind.SourceFile: return false; @@ -6023,12 +6720,50 @@ namespace ts { return false; } + function isTopLevelTypeAlias(symbol: Symbol) { + if (symbol.declarations && symbol.declarations.length) { + const parentKind = symbol.declarations[0].parent.kind; + return parentKind === SyntaxKind.SourceFile || parentKind === SyntaxKind.ModuleBlock; + } + return false; + } + function instantiateType(type: Type, mapper: TypeMapper): Type { if (type && mapper !== identityMapper) { - if (type.flags & TypeFlags.TypeParameter) { - return mapper(type); + // If we are instantiating a type that has a top-level type alias, obtain the instantiation through + // the type alias instead in order to share instantiations for the same type arguments. This can + // dramatically reduce the number of structurally identical types we generate. Note that we can only + // perform this optimization for top-level type aliases. Consider: + // + // function f1(x: T) { + // type Foo = { x: X, t: T }; + // let obj: Foo = { x: x }; + // return obj; + // } + // function f2(x: U) { return f1(x); } + // let z = f2(42); + // + // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo + // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's + // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been + // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; } - if (type.flags & TypeFlags.Anonymous) { + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + + function instantiateTypeNoAlias(type: Type, mapper: TypeMapper): Type { + if (type.flags & TypeFlags.TypeParameter) { + return mapper(type); + } + if (type.flags & TypeFlags.Object) { + if ((type).objectFlags & ObjectFlags.Anonymous) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -6037,19 +6772,28 @@ namespace ts { // instantiation. return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && - (type.flags & TypeFlags.Instantiated || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateAnonymousType(type, mapper) : type; + ((type).objectFlags & ObjectFlags.Instantiated || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; } - if (type.flags & TypeFlags.Reference) { - return createTypeReference((type).target, instantiateList((type).typeArguments, mapper, instantiateType)); + if ((type).objectFlags & ObjectFlags.Mapped) { + return instantiateCached(type, mapper, instantiateMappedType); } - if (type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Primitive)) { - return getUnionType(instantiateList((type).types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); - } - if (type.flags & TypeFlags.Intersection) { - return getIntersectionType(instantiateList((type).types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if ((type).objectFlags & ObjectFlags.Reference) { + return createTypeReference((type).target, instantiateTypes((type).typeArguments, mapper)); } } + if (type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Primitive)) { + return getUnionType(instantiateTypes((type).types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & TypeFlags.Intersection) { + return getIntersectionType(instantiateTypes((type).types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & TypeFlags.Index) { + return getIndexType(instantiateType((type).type, mapper)); + } + if (type.flags & TypeFlags.IndexedAccess) { + return getIndexedAccessType(instantiateType((type).objectType, mapper), instantiateType((type).indexType, mapper)); + } return type; } @@ -6088,9 +6832,24 @@ namespace ts { } function isContextSensitiveFunctionLikeDeclaration(node: FunctionLikeDeclaration) { - const areAllParametersUntyped = !forEach(node.parameters, p => p.type); - const isNullaryArrow = node.kind === SyntaxKind.ArrowFunction && !node.parameters.length; - return !node.typeParameters && areAllParametersUntyped && !isNullaryArrow; + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (forEach(node.parameters, p => !p.type)) { + return true; + } + // For arrow functions we now know we're not context sensitive. + if (node.kind === SyntaxKind.ArrowFunction) { + return false; + } + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. Otherwise we + // know that all parameters (including 'this') have type annotations and nothing is + // subject to contextual typing. + const parameter = firstOrUndefined(node.parameters); + return !(parameter && parameterIsThisKeyword(parameter)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { @@ -6098,10 +6857,10 @@ namespace ts { } function getTypeWithoutSignatures(type: Type): Type { - if (type.flags & TypeFlags.ObjectType) { + if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - const result = createObjectType(TypeFlags.Anonymous, type.symbol); + const result = createObjectType(ObjectFlags.Anonymous, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -6408,7 +7167,7 @@ namespace ts { if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType) { + if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Object) { const id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; const related = relation[id]; if (related !== undefined) { @@ -6440,8 +7199,8 @@ namespace ts { containingMessageChain?: DiagnosticMessageChain): boolean { let errorInfo: DiagnosticMessageChain; - let sourceStack: ObjectType[]; - let targetStack: ObjectType[]; + let sourceStack: Type[]; + let targetStack: Type[]; let maybeStack: Map[]; let expandingFlags: number; let depth = 0; @@ -6476,9 +7235,15 @@ namespace ts { } if (!message) { - message = relation === comparableRelation ? - Diagnostics.Type_0_is_not_comparable_to_type_1 : - Diagnostics.Type_0_is_not_assignable_to_type_1; + if (relation === comparableRelation) { + message = Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = Diagnostics.Type_0_is_not_assignable_to_type_1; + } } reportError(message, sourceType, targetType); @@ -6496,6 +7261,25 @@ namespace ts { } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type: Type): boolean { + if (!(type.flags & TypeFlags.UnionOrIntersection)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + let seenNonNullable = false; + for (const t of (type).types) { + if (t.flags & TypeFlags.Nullable) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -6517,7 +7301,7 @@ namespace ts { if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; - if (source.flags & TypeFlags.ObjectLiteral && source.flags & TypeFlags.FreshLiteral) { + if (getObjectFlags(source) & ObjectFlags.ObjectLiteral && source.flags & TypeFlags.FreshLiteral) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -6528,14 +7312,16 @@ namespace ts { // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & TypeFlags.UnionOrIntersection) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } const saveErrorInfo = errorInfo; - // Note that these checks are specifically ordered to produce correct results. + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. if (source.flags & TypeFlags.Union) { if (relation === comparableRelation) { result = someTypeRelatedToType(source as UnionType, target, reportErrors && !(source.flags & TypeFlags.Primitive)); @@ -6543,66 +7329,136 @@ namespace ts { else { result = eachTypeRelatedToType(source as UnionType, target, reportErrors && !(source.flags & TypeFlags.Primitive)); } - if (result) { return result; } } + else if (target.flags & TypeFlags.Union) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive))) { + return result; + } + } else if (target.flags & TypeFlags.Intersection) { - result = typeRelatedToEachType(source, target as IntersectionType, reportErrors); - - if (result) { + if (result = typeRelatedToEachType(source, target as IntersectionType, reportErrors)) { return result; } } - else { - // It is necessary to try these "some" checks on both sides because there may be nested "each" checks - // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or - // A & B = (A & B) | (C & D). - if (source.flags & TypeFlags.Intersection) { - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + else if (source.flags & TypeFlags.Intersection) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { + return result; + } + } + else if (target.flags & TypeFlags.TypeParameter) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (getObjectFlags(source) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!(source).declaration.questionToken) { + const templateType = getTemplateTypeFromMappedType(source); + const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + else { + // Given a type parameter K with a constraint keyof T, a type S is + // assignable to K if S is assignable to keyof T. + const constraint = getConstraintOfTypeParameter(target); + if (constraint && constraint.flags & TypeFlags.Index) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & TypeFlags.Index) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & TypeFlags.Index) { + if (result = isRelatedTo((target).type, (source).type, /*reportErrors*/ false)) { return result; } } - if (target.flags & TypeFlags.Union) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive))) { + // Given a type variable T with a constraint C, a type S is assignable to + // keyof T if S is assignable to keyof C. + if ((target).type.flags & TypeFlags.TypeVariable) { + const constraint = getConstraintOfTypeVariable((target).type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + } + else if (target.flags & TypeFlags.IndexedAccess) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. + if (source.flags & TypeFlags.IndexedAccess && (source).indexType === (target).indexType) { + if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) { + return result; + } + } + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + if ((target).constraint) { + if (result = isRelatedTo(source, (target).constraint, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } if (source.flags & TypeFlags.TypeParameter) { - let constraint = getConstraintOfTypeParameter(source); - - if (!constraint || constraint.flags & TypeFlags.Any) { - constraint = emptyObjectType; + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + if (getObjectFlags(target) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + const templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } + else { + let constraint = getConstraintOfTypeParameter(source); - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); + if (!constraint || constraint.flags & TypeFlags.Any) { + constraint = emptyObjectType; + } - // Report constraint errors only if the constraint is not the empty object type - const reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; + // The constraint may need to be further instantiated with its 'this' type. + constraint = getTypeWithThisArgument(constraint, source); + + // Report constraint errors only if the constraint is not the empty object type + const reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + else if (source.flags & TypeFlags.IndexedAccess) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + if ((source).constraint) { + if (result = isRelatedTo((source).constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } } } else { - if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { + if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -6614,7 +7470,7 @@ namespace ts { // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) { + if (apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection) && target.flags & TypeFlags.Object) { // Report structural errors only if we haven't reported any errors yet const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & TypeFlags.Primitive); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { @@ -6625,10 +7481,10 @@ namespace ts { } if (reportErrors) { - if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.Primitive) { + if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Primitive) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & TypeFlags.ObjectType && globalObjectType === source) { + else if (source.symbol && source.flags & TypeFlags.Object && globalObjectType === source) { reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -6638,8 +7494,8 @@ namespace ts { function isIdenticalTo(source: Type, target: Type): Ternary { let result: Ternary; - if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType) { - if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { + if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Object) { + if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -6649,8 +7505,8 @@ namespace ts { } if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union || source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { - if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { - if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } @@ -6663,8 +7519,8 @@ namespace ts { // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type: Type, name: string): boolean { - if (type.flags & TypeFlags.ObjectType) { - const resolved = resolveStructuredTypeMembers(type); + if (type.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || (resolved.numberIndexInfo && isNumericLiteralName(name)) || @@ -6691,8 +7547,7 @@ namespace ts { } function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { - if (maybeTypeOfKind(target, TypeFlags.ObjectType) && - (!(target.flags & TypeFlags.ObjectType) || !(target as ObjectType).isObjectLiteralPatternWithComputedProperties)) { + if (maybeTypeOfKind(target, TypeFlags.Object) && !(getObjectFlags(target) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { for (const prop of getPropertiesOfObjectType(source)) { if (!isKnownProperty(target, prop.name)) { if (reportErrors) { @@ -6711,7 +7566,7 @@ namespace ts { return false; } - function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { + function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { let result = Ternary.True; const sourceTypes = source.types; for (const sourceType of sourceTypes) { @@ -6849,6 +7704,9 @@ namespace ts { if (expandingFlags === 3) { result = Ternary.Maybe; } + else if (isGenericMappedType(source) || isGenericMappedType(target)) { + result = mappedTypeRelatedTo(source, target, reportErrors); + } else { result = propertiesRelatedTo(source, target, reportErrors); if (result) { @@ -6880,13 +7738,45 @@ namespace ts { return result; } + // A type [P in S]: X is related to a type [P in T]: Y if T is related to S and X is related to Y. + function mappedTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + let result: Ternary; + if (relation === identityRelation) { + const readonlyMatches = !(source).declaration.readonlyToken === !(target).declaration.readonlyToken; + const optionalMatches = !(source).declaration.questionToken === !(target).declaration.questionToken; + if (readonlyMatches && optionalMatches) { + if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors); + } + } + } + else { + if (relation === comparableRelation || !(source).declaration.questionToken || (target).declaration.questionToken) { + if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + return result & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors); + } + } + } + } + } + else if (relation !== identityRelation) { + const resolved = resolveStructuredTypeMembers(target); + if (isEmptyObjectType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & TypeFlags.Any) { + return Ternary.True; + } + } + return Ternary.False; + } + function propertiesRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } let result = Ternary.True; const properties = getPropertiesOfObjectType(target); - const requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); + const requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & ObjectFlags.ObjectLiteral); for (const targetProp of properties) { const sourceProp = getPropertyOfType(source, targetProp.name); @@ -6944,7 +7834,8 @@ namespace ts { return Ternary.False; } result &= related; - if (sourceProp.flags & SymbolFlags.Optional && !(targetProp.flags & SymbolFlags.Optional)) { + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & SymbolFlags.Optional && !(targetProp.flags & SymbolFlags.Optional)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -6965,7 +7856,7 @@ namespace ts { } function propertiesIdenticalTo(source: Type, target: Type): Ternary { - if (!(source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType)) { + if (!(source.flags & TypeFlags.Object && target.flags & TypeFlags.Object)) { return Ternary.False; } const sourceProperties = getPropertiesOfObjectType(source); @@ -7167,7 +8058,7 @@ namespace ts { // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type: Type) { - if (type.flags & TypeFlags.Anonymous) { + if (getObjectFlags(type) & ObjectFlags.Anonymous) { const symbol = type.symbol; if (symbol && symbol.flags & SymbolFlags.Class) { const declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -7186,12 +8077,12 @@ namespace ts { // some level beyond that. function isDeeplyNestedGeneric(type: Type, stack: Type[], depth: number): boolean { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && depth >= 5) { + if (getObjectFlags(type) & (ObjectFlags.Reference | ObjectFlags.Instantiated) && depth >= 5) { const symbol = type.symbol; let count = 0; for (let i = 0; i < depth; i++) { const t = stack[i]; - if (t.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && t.symbol === symbol) { + if (getObjectFlags(t) & (ObjectFlags.Reference | ObjectFlags.Instantiated) && t.symbol === symbol) { count++; if (count >= 5) return true; } @@ -7394,13 +8285,13 @@ namespace ts { } function isArrayType(type: Type): boolean { - return type.flags & TypeFlags.Reference && (type).target === globalArrayType; + return getObjectFlags(type) & ObjectFlags.Reference && (type).target === globalArrayType; } function isArrayLikeType(type: Type): boolean { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & TypeFlags.Reference && ((type).target === globalArrayType || (type).target === globalReadonlyArrayType) || + return getObjectFlags(type) & ObjectFlags.Reference && ((type).target === globalArrayType || (type).target === globalReadonlyArrayType) || !(type.flags & TypeFlags.Nullable) && isTypeAssignableTo(type, anyReadonlyArrayType); } @@ -7423,7 +8314,7 @@ namespace ts { type.flags & TypeFlags.NumberLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getBaseTypeOfLiteralType)) : + type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : type; } @@ -7432,7 +8323,7 @@ namespace ts { type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getWidenedLiteralType)) : + type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; } @@ -7441,7 +8332,7 @@ namespace ts { * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type: Type): boolean { - return !!(type.flags & TypeFlags.Reference && (type).target.flags & TypeFlags.Tuple); + return !!(getObjectFlags(type) & ObjectFlags.Reference && (type).target.objectFlags & ObjectFlags.Tuple); } function getFalsyFlagsOfTypes(types: Type[]): TypeFlags { @@ -7525,7 +8416,7 @@ namespace ts { * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type: Type): Type { - if (!(type.flags & TypeFlags.ObjectLiteral && type.flags & TypeFlags.FreshLiteral)) { + if (!(getObjectFlags(type) & ObjectFlags.ObjectLiteral && type.flags & TypeFlags.FreshLiteral)) { return type; } const regularType = (type).regularType; @@ -7542,6 +8433,7 @@ namespace ts { resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~TypeFlags.FreshLiteral; + regularNew.objectFlags |= ObjectFlags.ObjectLiteral; (type).regularType = regularNew; return regularNew; } @@ -7567,14 +8459,14 @@ namespace ts { if (type.flags & TypeFlags.Nullable) { return anyType; } - if (type.flags & TypeFlags.ObjectLiteral) { + if (getObjectFlags(type) & ObjectFlags.ObjectLiteral) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & TypeFlags.Union) { - return getUnionType(map((type).types, getWidenedConstituentType)); + return getUnionType(sameMap((type).types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference((type).target, map((type).typeArguments, getWidenedType)); + return createTypeReference((type).target, sameMap((type).typeArguments, getWidenedType)); } } return type; @@ -7607,7 +8499,7 @@ namespace ts { } } } - if (type.flags & TypeFlags.ObjectLiteral) { + if (getObjectFlags(type) & ObjectFlags.ObjectLiteral) { for (const p of getPropertiesOfObjectType(type)) { const t = getTypeOfSymbol(p); if (t.flags & TypeFlags.ContainsWideningType) { @@ -7708,26 +8600,78 @@ namespace ts { // Return true if the given type could possibly reference a type parameter for which // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. - function couldContainTypeParameters(type: Type): boolean { - return !!(type.flags & TypeFlags.TypeParameter || - type.flags & TypeFlags.Reference && forEach((type).typeArguments, couldContainTypeParameters) || - type.flags & TypeFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class) || - type.flags & TypeFlags.UnionOrIntersection && couldUnionOrIntersectionContainTypeParameters(type)); + function couldContainTypeVariables(type: Type): boolean { + const objectFlags = getObjectFlags(type); + return !!(type.flags & TypeFlags.TypeVariable || + objectFlags & ObjectFlags.Reference && forEach((type).typeArguments, couldContainTypeVariables) || + objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class) || + objectFlags & ObjectFlags.Mapped || + type.flags & TypeFlags.UnionOrIntersection && couldUnionOrIntersectionContainTypeVariables(type)); } - function couldUnionOrIntersectionContainTypeParameters(type: UnionOrIntersectionType): boolean { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = forEach(type.types, couldContainTypeParameters); + function couldUnionOrIntersectionContainTypeVariables(type: UnionOrIntersectionType): boolean { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = forEach(type.types, couldContainTypeVariables); } - return type.couldContainTypeParameters; + return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type: Type, typeParameter: TypeParameter): boolean { return type === typeParameter || type.flags & TypeFlags.UnionOrIntersection && forEach((type).types, t => isTypeParameterAtTopLevel(t, typeParameter)); } - function inferTypes(context: InferenceContext, originalSource: Type, originalTarget: Type) { - const typeParameters = context.signature.typeParameters; + // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + // an object type with the same set of properties as the source type, where the type of each + // property is computed by inferring from the source property type to X for the type + // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + function inferTypeForHomomorphicMappedType(source: Type, target: MappedType): Type { + const properties = getPropertiesOfType(source); + let indexInfo = getIndexInfoOfType(source, IndexKind.String); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + const typeVariable = getIndexedAccessType((getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target)); + const typeVariableArray = [typeVariable]; + const typeInferences = createTypeInferencesObject(); + const typeInferencesArray = [typeInferences]; + const templateType = getTemplateTypeFromMappedType(target); + const readonlyMask = target.declaration.readonlyToken ? false : true; + const optionalMask = target.declaration.questionToken ? 0 : SymbolFlags.Optional; + const members = createSymbolTable(properties); + for (const prop of properties) { + const inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + const inferredProp = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | prop.flags & optionalMask, prop.name); + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); + members[prop.name] = inferredProp; + } + if (indexInfo) { + const inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + + function inferTargetType(sourceType: Type): Type { + typeInferences.primary = undefined; + typeInferences.secondary = undefined; + inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); + const inferences = typeInferences.primary || typeInferences.secondary; + return inferences && getUnionType(inferences, /*subtypeReduction*/ true); + } + } + + function inferTypesWithContext(context: InferenceContext, originalSource: Type, originalTarget: Type) { + inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); + } + + function inferTypes(typeVariables: TypeVariable[], typeInferences: TypeInferences[], originalSource: Type, originalTarget: Type) { let sourceStack: Type[]; let targetStack: Type[]; let depth = 0; @@ -7745,7 +8689,17 @@ namespace ts { } function inferFromTypes(source: Type, target: Type) { - if (!couldContainTypeParameters(target)) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + const sourceTypes = source.aliasTypeArguments; + const targetTypes = target.aliasTypeArguments; + for (let i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } return; } if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) || @@ -7785,7 +8739,7 @@ namespace ts { target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & TypeFlags.TypeParameter) { + if (target.flags & TypeFlags.TypeVariable) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -7795,9 +8749,9 @@ namespace ts { if (source.flags & TypeFlags.ContainsAnyFunctionType) { return; } - for (let i = 0; i < typeParameters.length; i++) { - if (target === typeParameters[i]) { - const inferences = context.inferences[i]; + for (let i = 0; i < typeVariables.length; i++) { + if (target === typeVariables[i]) { + const inferences = typeInferences[i]; if (!inferences.isFixed) { // Any inferences that are made to a type parameter in a union type are inferior // to inferences made to a flat (non-union) type. This is because if we infer to @@ -7811,7 +8765,7 @@ namespace ts { if (!contains(candidates, source)) { candidates.push(source); } - if (!isTypeParameterAtTopLevel(originalTarget, target)) { + if (target.flags & TypeFlags.TypeParameter && !isTypeParameterAtTopLevel(originalTarget, target)) { inferences.topLevel = false; } } @@ -7819,7 +8773,7 @@ namespace ts { } } } - else if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { + else if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments const sourceTypes = (source).typeArguments || emptyArray; const targetTypes = (target).typeArguments || emptyArray; @@ -7830,24 +8784,24 @@ namespace ts { } else if (target.flags & TypeFlags.UnionOrIntersection) { const targetTypes = (target).types; - let typeParameterCount = 0; - let typeParameter: TypeParameter; - // First infer to each type in union or intersection that isn't a type parameter + let typeVariableCount = 0; + let typeVariable: TypeVariable; + // First infer to each type in union or intersection that isn't a type variable for (const t of targetTypes) { - if (t.flags & TypeFlags.TypeParameter && contains(typeParameters, t)) { - typeParameter = t; - typeParameterCount++; + if (t.flags & TypeFlags.TypeVariable && contains(typeVariables, t)) { + typeVariable = t; + typeVariableCount++; } else { inferFromTypes(source, t); } } - // Next, if target containings a single naked type parameter, make a secondary inference to that type - // parameter. This gives meaningful results for union types in co-variant positions and intersection + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection // types in contra-variant positions (such as callback parameters). - if (typeParameterCount === 1) { + if (typeVariableCount === 1) { inferiority++; - inferFromTypes(source, typeParameter); + inferFromTypes(source, typeVariable); inferiority--; } } @@ -7860,7 +8814,7 @@ namespace ts { } else { source = getApparentType(source); - if (source.flags & TypeFlags.ObjectType) { + if (source.flags & TypeFlags.Object) { if (isInProcess(source, target)) { return; } @@ -7879,15 +8833,45 @@ namespace ts { sourceStack[depth] = source; targetStack[depth] = target; depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, SignatureKind.Call); - inferFromSignatures(source, target, SignatureKind.Construct); - inferFromIndexTypes(source, target); + inferFromObjectTypes(source, target); depth--; } } } + function inferFromObjectTypes(source: Type, target: Type) { + if (getObjectFlags(target) & ObjectFlags.Mapped) { + const constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & TypeFlags.Index) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + const index = indexOf(typeVariables, (constraintType).type); + if (index >= 0 && !typeInferences[index].isFixed) { + const inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + inferiority++; + inferFromTypes(inferredType, typeVariables[index]); + inferiority--; + } + } + return; + } + if (constraintType.flags & TypeFlags.TypeParameter) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, SignatureKind.Call); + inferFromSignatures(source, target, SignatureKind.Construct); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source: Type, target: Type) { const properties = getPropertiesOfObjectType(target); for (const targetProp of properties) { @@ -7975,7 +8959,7 @@ namespace ts { function hasPrimitiveConstraint(type: TypeParameter): boolean { const constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive); + return constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive | TypeFlags.Index); } function getInferredType(context: InferenceContext, index: number): Type { @@ -7992,7 +8976,7 @@ namespace ts { const widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - const baseInferences = widenLiteralTypes ? map(inferences, getWidenedLiteralType) : inferences; + const baseInferences = widenLiteralTypes ? sameMap(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype const unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; @@ -8252,7 +9236,7 @@ namespace ts { type === falseType ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : type === falseType ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; } - if (flags & TypeFlags.ObjectType) { + if (flags & TypeFlags.Object) { return isFunctionObjectType(type) ? strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; @@ -8282,13 +9266,13 @@ namespace ts { function getTypeWithDefault(type: Type, defaultExpression: Expression) { if (defaultExpression) { - const defaultType = checkExpression(defaultExpression); + const defaultType = getTypeOfExpression(defaultExpression); return getUnionType([getTypeWithFacts(type, TypeFacts.NEUndefined), defaultType]); } return type; } - function getTypeOfDestructuredProperty(type: Type, name: Identifier | LiteralExpression | ComputedPropertyName) { + function getTypeOfDestructuredProperty(type: Type, name: PropertyName) { const text = getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && getIndexTypeOfType(type, IndexKind.Number) || @@ -8302,22 +9286,22 @@ namespace ts { unknownType; } - function getTypeOfDestructuredSpreadElement(type: Type) { + function getTypeOfDestructuredSpreadExpression(type: Type) { return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node: BinaryExpression): Type { return node.parent.kind === SyntaxKind.ArrayLiteralExpression || node.parent.kind === SyntaxKind.PropertyAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : - checkExpression(node.right); + getTypeOfExpression(node.right); } function getAssignedTypeOfArrayLiteralElement(node: ArrayLiteralExpression, element: Expression): Type { return getTypeOfDestructuredArrayElement(getAssignedType(node), indexOf(node.elements, element)); } - function getAssignedTypeOfSpreadElement(node: SpreadElementExpression): Type { - return getTypeOfDestructuredSpreadElement(getAssignedType(node.parent)); + function getAssignedTypeOfSpreadExpression(node: SpreadElement): Type { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); } function getAssignedTypeOfPropertyAssignment(node: PropertyAssignment | ShorthandPropertyAssignment): Type { @@ -8341,8 +9325,8 @@ namespace ts { return undefinedType; case SyntaxKind.ArrayLiteralExpression: return getAssignedTypeOfArrayLiteralElement(parent, node); - case SyntaxKind.SpreadElementExpression: - return getAssignedTypeOfSpreadElement(parent); + case SyntaxKind.SpreadElement: + return getAssignedTypeOfSpreadExpression(parent); case SyntaxKind.PropertyAssignment: return getAssignedTypeOfPropertyAssignment(parent); case SyntaxKind.ShorthandPropertyAssignment: @@ -8358,7 +9342,7 @@ namespace ts { getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadElement(parentType); + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -8367,7 +9351,7 @@ namespace ts { // from its initializer, we'll already have cached the type. Otherwise we compute it now // without caching such that transient types are reflected. const links = getNodeLinks(node); - return links.resolvedType || checkExpression(node); + return links.resolvedType || getTypeOfExpression(node); } function getInitialTypeOfVariableDeclaration(node: VariableDeclaration) { @@ -8395,6 +9379,13 @@ namespace ts { getAssignedType(node); } + function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { + return node.kind === SyntaxKind.VariableDeclaration && (node).initializer && + isEmptyArrayLiteral((node).initializer) || + node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && + isEmptyArrayLiteral((node.parent).right); + } + function getReferenceCandidate(node: Expression): Expression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: @@ -8410,9 +9401,17 @@ namespace ts { return node; } + function getReferenceRoot(node: Node): Node { + const parent = node.parent; + return parent.kind === SyntaxKind.ParenthesizedExpression || + parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node || + parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.CommaToken && (parent).right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause: CaseClause | DefaultClause) { if (clause.kind === SyntaxKind.CaseClause) { - const caseType = getRegularTypeOfLiteralType(checkExpression((clause).expression)); + const caseType = getRegularTypeOfLiteralType(getTypeOfExpression((clause).expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -8452,6 +9451,10 @@ namespace ts { return containsType(target.types, source); } + function forEachType(type: Type, f: (t: Type) => T): T { + return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); + } + function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { const types = (type).types; @@ -8461,6 +9464,28 @@ namespace ts { return f(type) ? type : neverType; } + function mapType(type: Type, f: (t: Type) => Type): Type { + return type.flags & TypeFlags.Union ? getUnionType(map((type).types, f)) : f(type); + } + + function extractTypesOfKind(type: Type, kind: TypeFlags) { + return filterType(type, t => (t.flags & kind) !== 0); + } + + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral)) { + return mapType(typeWithPrimitives, t => + t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) : + t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t); + } + return typeWithPrimitives; + } + function isIncomplete(flowType: FlowType) { return flowType.flags === 0; } @@ -8473,21 +9498,131 @@ namespace ts { return incomplete ? { flags: 0, type } : type; } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType: Type): EvolvingArrayType { + const result = createObjectType(ObjectFlags.EvolvingArray); + result.elementType = elementType; + return result; + } + + function getEvolvingArrayType(elementType: Type): EvolvingArrayType { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType: EvolvingArrayType, node: Expression): EvolvingArrayType { + const elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + + function createFinalArrayType(elementType: Type) { + return elementType.flags & TypeFlags.Never ? + autoArrayType : + createArrayType(elementType.flags & TypeFlags.Union ? + getUnionType((elementType).types, /*subtypeReduction*/ true) : + elementType); + } + + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType: EvolvingArrayType): Type { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + + function finalizeEvolvingArrayType(type: Type): Type { + return getObjectFlags(type) & ObjectFlags.EvolvingArray ? getFinalArrayType(type) : type; + } + + function getElementTypeOfEvolvingArrayType(type: Type) { + return getObjectFlags(type) & ObjectFlags.EvolvingArray ? (type).elementType : neverType; + } + + function isEvolvingArrayTypeList(types: Type[]) { + let hasEvolvingArrayType = false; + for (const t of types) { + if (!(t.flags & TypeFlags.Never)) { + if (!(getObjectFlags(t) & ObjectFlags.EvolvingArray)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node: Node) { + const root = getReferenceRoot(node); + const parent = root.parent; + const isLengthPushOrUnshift = parent.kind === SyntaxKind.PropertyAccessExpression && ( + (parent).name.text === "length" || + parent.parent.kind === SyntaxKind.CallExpression && isPushOrUnshiftIdentifier((parent).name)); + const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && + (parent).expression === root && + parent.parent.kind === SyntaxKind.BinaryExpression && + (parent.parent).operatorToken.kind === SyntaxKind.EqualsToken && + (parent.parent).left === parent && + !isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression((parent).argumentExpression), TypeFlags.NumberLike | TypeFlags.Undefined); + return isLengthPushOrUnshift || isElementAssignment; + } + + function maybeTypePredicateCall(node: CallExpression) { + const links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + + function getMaybeTypePredicate(node: CallExpression) { + if (node.expression.kind !== SyntaxKind.SuperKeyword) { + const funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + const apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + return !!forEach(callSignatures, sig => sig.typePredicate); + } + } + } + return false; + } + function getFlowTypeOfReference(reference: Node, declaredType: Type, assumeInitialized: boolean, flowContainer: Node) { let key: string; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & TypeFlags.Narrowable)) { return declaredType; } const initialType = assumeInitialized ? declaredType : - declaredType === autoType ? undefinedType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : includeFalsyTypes(declaredType, TypeFlags.Undefined); const visitedFlowStart = visitedFlowCount; - const result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow: FlowNode): FlowType { while (true) { @@ -8524,6 +9659,13 @@ namespace ts { getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & FlowFlags.ArrayMutation) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = (flow).antecedent; + continue; + } + } else if (flow.flags & FlowFlags.Start) { // Check if we should continue with the control flow of the containing function. const container = (flow).container; @@ -8536,8 +9678,8 @@ namespace ts { } else { // Unreachable code errors are reported in the binding phase. Here we - // simply return the declared type to reduce follow-on errors. - type = declaredType; + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); } if (flow.flags & FlowFlags.Shared) { // Record visited node and the associated type in the cache. @@ -8554,13 +9696,21 @@ namespace ts { // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - if (node.parent.kind === SyntaxKind.PrefixUnaryExpression || node.parent.kind === SyntaxKind.PostfixUnaryExpression) { + if (getAssignmentTargetKind(node) === AssignmentKind.Compound) { const flowType = getTypeAtFlowNode(flow.antecedent); return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); } - return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : - declaredType.flags & TypeFlags.Union ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + const assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & TypeFlags.Union) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -8573,24 +9723,56 @@ namespace ts { return undefined; } + function getTypeAtFlowArrayMutation(flow: FlowArrayMutation): FlowType { + const node = flow.node; + const expr = node.kind === SyntaxKind.CallExpression ? + ((node).expression).expression : + ((node).left).expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + const flowType = getTypeAtFlowNode(flow.antecedent); + const type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & ObjectFlags.EvolvingArray) { + let evolvedType = type; + if (node.kind === SyntaxKind.CallExpression) { + for (const arg of (node).arguments) { + evolvedType = addEvolvingArrayElementType(evolvedType, arg); + } + } + else { + const indexType = getTypeOfExpression(((node).left).argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike | TypeFlags.Undefined)) { + evolvedType = addEvolvingArrayElementType(evolvedType, (node).right); + } + } + return evolvedType === type ? flowType : createFlowType(evolvedType, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow: FlowCondition): FlowType { const flowType = getTypeAtFlowNode(flow.antecedent); - let type = getTypeFromFlowType(flowType); - if (!(type.flags & TypeFlags.Never)) { - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & TypeFlags.Never && isIncomplete(flowType)) { - type = silentNeverType; - } + const type = getTypeFromFlowType(flowType); + if (type.flags & TypeFlags.Never) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0; + const nonEvolvingType = finalizeEvolvingArrayType(type); + const narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + const incomplete = isIncomplete(flowType); + const resultType = incomplete && narrowedType.flags & TypeFlags.Never ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType { @@ -8633,7 +9815,7 @@ namespace ts { seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow: FlowLabel): FlowType { @@ -8649,11 +9831,15 @@ namespace ts { } // If this flow loop junction and reference are already being processed, return // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. for (let i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -8696,7 +9882,7 @@ namespace ts { } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - const result = getUnionType(antecedentTypes, subtypeReduction); + const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -8778,7 +9964,7 @@ namespace ts { if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { assumeTrue = !assumeTrue; } - const valueType = checkExpression(value); + const valueType = getTypeOfExpression(value); if (valueType.flags & TypeFlags.Nullable) { if (!strictNullChecks) { return type; @@ -8796,7 +9982,7 @@ namespace ts { } if (assumeTrue) { const narrowedType = filterType(type, t => areTypesComparable(t, valueType)); - return narrowedType.flags & TypeFlags.Never ? type : narrowedType; + return narrowedType.flags & TypeFlags.Never ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { const regularType = getRegularTypeOfLiteralType(valueType); @@ -8843,7 +10029,9 @@ namespace ts { const clauseTypes = switchTypes.slice(clauseStart, clauseEnd); const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType); const discriminantType = getUnionType(clauseTypes); - const caseType = discriminantType.flags & TypeFlags.Never ? neverType : filterType(type, t => isTypeComparableTo(discriminantType, t)); + const caseType = + discriminantType.flags & TypeFlags.Never ? neverType : + replacePrimitivesWithLiterals(filterType(type, t => isTypeComparableTo(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -8863,7 +10051,7 @@ namespace ts { } // Check that right operand is a function type with a prototype property - const rightType = checkExpression(expr.right); + const rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } @@ -8886,10 +10074,10 @@ namespace ts { if (!targetType) { // Target type is type of construct signature let constructSignatures: Signature[]; - if (rightType.flags & TypeFlags.Interface) { + if (getObjectFlags(rightType) & ObjectFlags.Interface) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & TypeFlags.Anonymous) { + else if (getObjectFlags(rightType) & ObjectFlags.Anonymous) { constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); } if (constructSignatures && constructSignatures.length) { @@ -8898,20 +10086,20 @@ namespace ts { } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue); + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); } return type; } - function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean) { + function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean, isRelated: (source: Type, target: Type) => boolean) { if (!assumeTrue) { - return filterType(type, t => !isTypeInstanceOf(t, candidate)); + return filterType(type, t => !isRelated(t, candidate)); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. if (type.flags & TypeFlags.Union) { - const assignableType = filterType(type, t => isTypeInstanceOf(t, candidate)); + const assignableType = filterType(type, t => isRelated(t, candidate)); if (!(assignableType.flags & TypeFlags.Never)) { return assignableType; } @@ -8929,7 +10117,7 @@ namespace ts { } function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { - if (!hasMatchingArgument(callExpression, reference)) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { return type; } const signature = getResolvedSignature(callExpression); @@ -8947,7 +10135,7 @@ namespace ts { const predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; @@ -8955,12 +10143,12 @@ namespace ts { } } else { - const invokedExpression = skipParenthesizedNodes(callExpression.expression); + const invokedExpression = skipParentheses(callExpression.expression); if (invokedExpression.kind === SyntaxKind.ElementAccessExpression || invokedExpression.kind === SyntaxKind.PropertyAccessExpression) { const accessExpression = invokedExpression as ElementAccessExpression | PropertyAccessExpression; - const possibleReference = skipParenthesizedNodes(accessExpression.expression); + const possibleReference = skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue); + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } if (containsMatchingReference(reference, possibleReference)) { return declaredType; @@ -9004,7 +10192,7 @@ namespace ts { location = location.parent; } if (isPartOfExpression(location) && !isAssignmentTarget(location)) { - const type = checkExpression(location); + const type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -9018,13 +10206,6 @@ namespace ts { return getTypeOfSymbol(symbol); } - function skipParenthesizedNodes(expression: Expression): Expression { - while (expression.kind === SyntaxKind.ParenthesizedExpression) { - expression = (expression as ParenthesizedExpression).expression; - } - return expression; - } - function getControlFlowContainer(node: Node): Node { while (true) { node = node.parent; @@ -9076,8 +10257,15 @@ namespace ts { } } + function isConstVariable(symbol: Symbol) { + return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return unknownType; + } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -9087,7 +10275,7 @@ namespace ts { // can explicitly bound arguments objects if (symbol === argumentsSymbol) { const container = getContainingFunction(node); - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { if (container.kind === SyntaxKind.ArrowFunction) { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -9099,6 +10287,7 @@ namespace ts { if (node.flags & NodeFlags.AwaitContext) { getNodeLinks(container).flags |= NodeCheckFlags.CaptureArguments; } + return getTypeOfSymbol(symbol); } if (symbol.flags & SymbolFlags.Alias && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { @@ -9112,8 +10301,7 @@ namespace ts { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (languageVersion === ScriptTarget.ES6 - && declaration.kind === SyntaxKind.ClassDeclaration + if (declaration.kind === SyntaxKind.ClassDeclaration && nodeIsDecorated(declaration)) { let container = getContainingClass(node); while (container !== undefined) { @@ -9151,9 +10339,22 @@ namespace ts { const type = getTypeOfSymbol(localOrExportSymbol); const declaration = localOrExportSymbol.valueDeclaration; + const assignmentKind = getAssignmentTargetKind(node); + + if (assignmentKind) { + if (!(localOrExportSymbol.flags & SymbolFlags.Variable)) { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + // We only narrow variables and parameters occurring in a non-assignment position. For all other // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & SymbolFlags.Variable) || isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & SymbolFlags.Variable) || assignmentKind === AssignmentKind.Definite || !declaration) { return type; } // The declaration container is the innermost function that encloses the declaration of the variable @@ -9166,28 +10367,28 @@ namespace ts { // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && - (flowContainer.kind === SyntaxKind.FunctionExpression || flowContainer.kind === SyntaxKind.ArrowFunction) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || + flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). const assumeInitialized = isParameter || isOuterVariable || - type !== autoType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) || isInAmbientContext(declaration); const flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType) { - if (flowType === autoType) { + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { if (compilerOptions.noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); - error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } - return anyType; + return convertAutoToAny(flowType); } } else if (!assumeInitialized && !(getFalsyFlags(type) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) { @@ -9195,7 +10396,7 @@ namespace ts { // Return the declared type to reduce follow-on errors return type; } - return flowType; + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isInsideFunction(node: Node, threshold: Node): boolean { @@ -9211,7 +10412,7 @@ namespace ts { } function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { - if (languageVersion >= ScriptTarget.ES6 || + if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) { return; @@ -9343,6 +10544,29 @@ namespace ts { return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node: Node, container: Node, diagnosticMessage: DiagnosticMessage) { + const containingClassDecl = container.parent; + const baseTypeNode = getClassExtendsHeritageClauseElement(containingClassDecl); + + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + const superCall = getSuperCallInConstructor(container); + + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node: Node): Type { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. @@ -9350,26 +10574,7 @@ namespace ts { let needToCaptureLexicalThis = false; if (container.kind === SyntaxKind.Constructor) { - const containingClassDecl = container.parent; - const baseTypeNode = getClassExtendsHeritageClauseElement(containingClassDecl); - - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - const superCall = getSuperCallInConstructor(container); - - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. @@ -9377,7 +10582,7 @@ namespace ts { container = getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES6); + needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES2015); } switch (container.kind) { @@ -9430,7 +10635,7 @@ namespace ts { } } - const thisType = getThisTypeOfDeclaration(container); + const thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return thisType; } @@ -9457,9 +10662,9 @@ namespace ts { } function getTypeForThisExpressionFromJSDoc(node: Node) { - const typeTag = getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === SyntaxKind.JSDocFunctionType) { - const jsDocFunctionType = typeTag.typeExpression.type; + const jsdocType = getJSDocType(node); + if (jsdocType && jsdocType.kind === SyntaxKind.JSDocFunctionType) { + const jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === SyntaxKind.JSDocThisType) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } @@ -9485,7 +10690,7 @@ namespace ts { if (!isCallExpression) { while (container && container.kind === SyntaxKind.ArrowFunction) { container = getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6; + needToCaptureLexicalThis = languageVersion < ScriptTarget.ES2015; } } @@ -9517,6 +10722,10 @@ namespace ts { return unknownType; } + if (!isCallExpression && container.kind === SyntaxKind.Constructor) { + checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if ((getModifierFlags(container) & ModifierFlags.Static) || isCallExpression) { nodeCheckFlag = NodeCheckFlags.SuperStatic; } @@ -9599,7 +10808,7 @@ namespace ts { } if (container.parent.kind === SyntaxKind.ObjectLiteralExpression) { - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; } @@ -9670,14 +10879,16 @@ namespace ts { } } - function getContextualThisParameter(func: FunctionLikeDeclaration): Symbol { + function getContextualThisParameterType(func: FunctionLikeDeclaration): Type { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== SyntaxKind.ArrowFunction) { const contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + const thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } } } - return undefined; } @@ -9857,7 +11068,7 @@ namespace ts { // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { - return checkExpression(binaryExpression.left); + return getTypeOfExpression(binaryExpression.left); } } else if (operator === SyntaxKind.BarBarToken) { @@ -9865,7 +11076,7 @@ namespace ts { // expression has no contextual type, the right operand is contextually typed by the type of the left operand. let type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = checkExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left); } return type; } @@ -9967,7 +11178,7 @@ namespace ts { const index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) - || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); + || (languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); } return undefined; } @@ -10072,16 +11283,32 @@ namespace ts { // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. - function getNonGenericSignature(type: Type): Signature { + function getNonGenericSignature(type: Type, node: FunctionExpression | ArrowFunction | MethodDeclaration): Signature { const signatures = getSignaturesOfStructuredType(type, SignatureKind.Call); if (signatures.length === 1) { const signature = signatures[0]; - if (!signature.typeParameters) { + if (!signature.typeParameters && !isAritySmaller(signature, node)) { return signature; } } } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature: Signature, target: FunctionExpression | ArrowFunction | MethodDeclaration) { + let targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + const param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + const sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node: Node): node is FunctionExpression | ArrowFunction { return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction; } @@ -10111,12 +11338,12 @@ namespace ts { return undefined; } if (!(type.flags & TypeFlags.Union)) { - return getNonGenericSignature(type); + return getNonGenericSignature(type, node); } let signatureList: Signature[]; const types = (type).types; for (const current of types) { - const signature = getNonGenericSignature(current); + const signature = getNonGenericSignature(current, node); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -10163,14 +11390,8 @@ namespace ts { return mapper && mapper.context; } - function checkSpreadElementExpression(node: SpreadElementExpression, contextualMapper?: TypeMapper): Type { - // It is usually not safe to call checkExpressionCached if we can be contextually typing. - // You can tell that we are contextually typing because of the contextualMapper parameter. - // While it is true that a spread element can have a contextual type, it does not do anything - // with this type. It is neither affected by it, nor does it propagate it to its operand. - // So the fact that contextualMapper is passed is not important, because the operand of a spread - // element is not contextually typed. - const arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + function checkSpreadExpression(node: SpreadElement, contextualMapper?: TypeMapper): Type { + const arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } @@ -10185,7 +11406,7 @@ namespace ts { const elementTypes: Type[] = []; const inDestructuringPattern = isAssignmentTarget(node); for (const e of elements) { - if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElementExpression) { + if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElement) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -10198,9 +11419,9 @@ namespace ts { // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - const restArrayType = checkExpression((e).expression, contextualMapper); + const restArrayType = checkExpression((e).expression, contextualMapper); const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || - (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); + (languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -10209,7 +11430,7 @@ namespace ts { const type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression; + hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElement; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -10310,10 +11531,10 @@ namespace ts { return links.resolvedType; } - function getObjectLiteralIndexInfo(node: ObjectLiteralExpression, properties: Symbol[], kind: IndexKind): IndexInfo { + function getObjectLiteralIndexInfo(propertyNodes: NodeArray, offset: number, properties: Symbol[], kind: IndexKind): IndexInfo { const propTypes: Type[] = []; for (let i = 0; i < properties.length; i++) { - if (kind === IndexKind.String || isNumericName(node.properties[i].name)) { + if (kind === IndexKind.String || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -10326,8 +11547,11 @@ namespace ts { // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - const propertiesTable = createMap(); - const propertiesArray: Symbol[] = []; + let propertiesTable = createMap(); + let propertiesArray: Symbol[] = []; + let spread: Type = emptyObjectType; + let propagatedFlags: TypeFlags = 0; + const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); @@ -10336,7 +11560,9 @@ namespace ts { let hasComputedStringProperty = false; let hasComputedNumberProperty = false; - for (const memberDecl of node.properties) { + let offset = 0; + for (let i = 0; i < node.properties.length; i++) { + const memberDecl = node.properties[i]; let member = memberDecl.symbol; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || @@ -10352,6 +11578,7 @@ namespace ts { Debug.assert(memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment); type = checkExpressionForMutableLocation((memberDecl).name, contextualMapper); } + typeFlags |= type.flags; const prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); if (inDestructuringPattern) { @@ -10367,15 +11594,15 @@ namespace ts { patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && - !(contextualType.flags & TypeFlags.ObjectType && (contextualType as ObjectType).isObjectLiteralPatternWithComputedProperties)) { + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. const impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & SymbolFlags.Optional; } - else if (!compilerOptions.suppressExcessPropertyErrors) { + + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, IndexKind.String)) { error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } @@ -10390,6 +11617,27 @@ namespace ts { prop.target = member; member = prop; } + else if (memberDecl.kind === SyntaxKind.SpreadAssignment) { + if (languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + propertiesArray = []; + propertiesTable = createMap(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + const type = checkExpression((memberDecl as SpreadAssignment).expression); + if (!isValidSpreadType(type)) { + error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type, /*isFromObjectLiteral*/ false); + offset = i + 1; + continue; + } else { // TypeScript 1.0 spec (April 2014) // A get accessor declaration is processed in the same manner as @@ -10429,18 +11677,44 @@ namespace ts { } } - const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.String) : undefined; - const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.Number) : undefined; - const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); - if (patternWithComputedProperties) { - result.isObjectLiteralPatternWithComputedProperties = true; + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); + } + if (spread.flags & TypeFlags.Object) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } + return spread; } - if (inDestructuringPattern) { - result.pattern = node; + + return createObjectLiteralType(); + + function createObjectLiteralType() { + const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.String) : undefined; + const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.Number) : undefined; + const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; + result.flags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); + result.objectFlags |= ObjectFlags.ObjectLiteral; + if (patternWithComputedProperties) { + result.objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & TypeFlags.Nullable)) { + propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags); + } + return result; } - return result; + } + + function isValidSpreadType(type: Type): boolean { + return !!(type.flags & (TypeFlags.Any | TypeFlags.Null | TypeFlags.Undefined) || + type.flags & TypeFlags.Object && !isGenericMappedType(type) || + type.flags & TypeFlags.UnionOrIntersection && !forEach((type).types, t => !isValidSpreadType(t))); } function checkJsxSelfClosingElement(node: JsxSelfClosingElement) { @@ -10543,6 +11817,9 @@ namespace ts { } function checkJsxSpreadAttribute(node: JsxSpreadAttribute, elementAttributesType: Type, nameTable: Map) { + if (compilerOptions.jsx === JsxEmit.React) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Assign); + } const type = checkExpression(node.expression); const props = getPropertiesOfType(type); for (const prop of props) { @@ -10631,7 +11908,7 @@ namespace ts { } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, @@ -10681,7 +11958,7 @@ namespace ts { } if (elemType.flags & TypeFlags.Union) { const types = (elemType).types; - return getUnionType(types.map(type => { + return getUnionType(map(types, type => { return getResolvedJsxType(node, type, elemClassType); }), /*subtypeReduction*/ true); } @@ -10858,14 +12135,20 @@ namespace ts { function checkJsxOpeningLikeElement(node: JsxOpeningLikeElement) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - - // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there - // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. const reactRefErr = compilerOptions.jsx === JsxEmit.React ? Diagnostics.Cannot_find_name_0 : undefined; - const reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + const reactNamespace = getJsxNamespace(); const reactSym = resolveName(node.tagName, reactNamespace, SymbolFlags.Value, reactRefErr, reactNamespace); if (reactSym) { - getSymbolLinks(reactSym).referenced = true; + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = true; + + // If react symbol is alias, mark it as refereced + if (reactSym.flags & SymbolFlags.Alias && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } } const targetAttributesType = getJsxElementAttributesType(node); @@ -10951,7 +12234,7 @@ namespace ts { // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < ScriptTarget.ES6 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { + if (languageVersion < ScriptTarget.ES2015 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. @@ -11016,7 +12299,7 @@ namespace ts { } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (TypeFlags.Class | TypeFlags.Interface) && hasBaseType(type, enclosingClass))) { + if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(type, enclosingClass))) { error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -11046,6 +12329,35 @@ namespace ts { return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } + function reportNonexistentProperty(propNode: Identifier, containingType: Type) { + let errorInfo: DiagnosticMessageChain; + if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { + for (const subtype of (containingType as UnionType).types) { + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } + + function markPropertyAsReferenced(prop: Symbol) { + if (prop && + noUnusedIdentifiers && + (prop.flags & SymbolFlags.ClassMember) && + prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { + if (prop.flags & SymbolFlags.Instantiated) { + getSymbolLinks(prop).target.isReferenced = true; + + } + else { + prop.isReferenced = true; + } + } + } + function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { const type = checkNonNullExpression(left); if (isTypeAny(type) || type === silentNeverType) { @@ -11065,17 +12377,7 @@ namespace ts { return unknownType; } - if (noUnusedIdentifiers && - (prop.flags & SymbolFlags.ClassMember) && - prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { - if (prop.flags & SymbolFlags.Instantiated) { - getSymbolLinks(prop).target.isReferenced = true; - - } - else { - prop.isReferenced = true; - } - } + markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; @@ -11084,30 +12386,25 @@ namespace ts { } const propType = getTypeOfSymbol(prop); + const assignmentKind = getAssignmentTargetKind(node); + + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); + return unknownType; + } + } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== SyntaxKind.PropertyAccessExpression || isAssignmentTarget(node) || + if (node.kind !== SyntaxKind.PropertyAccessExpression || assignmentKind === AssignmentKind.Definite || !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) && !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); - - function reportNonexistentProperty(propNode: Identifier, containingType: Type) { - let errorInfo: DiagnosticMessageChain; - if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { - for (const subtype of (containingType as UnionType).types) { - if (!getPropertyOfType(subtype, propNode.text)) { - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); - break; - } - } - } - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); - diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); - } + const flowType = getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { @@ -11154,7 +12451,7 @@ namespace ts { * that references a for-in variable for an object with numeric property names. */ function isForInVariableForNumericPropertyNames(expr: Expression) { - const e = skipParenthesizedNodes(expr); + const e = skipParentheses(expr); if (e.kind === SyntaxKind.Identifier) { const symbol = getResolvedSymbol(e); if (symbol.flags & SymbolFlags.Variable) { @@ -11164,7 +12461,7 @@ namespace ts { if (node.kind === SyntaxKind.ForInStatement && child === (node).statement && getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(checkExpression((node).expression))) { + hasNumericPropertyNames(getTypeOfExpression((node).expression))) { return true; } child = node; @@ -11176,8 +12473,10 @@ namespace ts { } function checkIndexedAccess(node: ElementAccessExpression): Type { - // Grammar checking - if (!node.argumentExpression) { + const objectType = checkNonNullExpression(node.expression); + + const indexExpression = node.argumentExpression; + if (!indexExpression) { const sourceFile = getSourceFileOfNode(node); if (node.parent.kind === SyntaxKind.NewExpression && (node.parent).expression === node) { const start = skipTrivia(sourceFile.text, node.expression.end); @@ -11189,116 +12488,23 @@ namespace ts { const end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Expression_expected); } + return unknownType; } - // Obtain base constraint such that we can bail out if the constraint is an unknown type - const objectType = getApparentType(checkNonNullExpression(node.expression)); - const indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + const indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - const isConstEnum = isConstEnumObjectType(objectType); - if (isConstEnum && - (!node.argumentExpression || node.argumentExpression.kind !== SyntaxKind.StringLiteral)) { - error(node.argumentExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + if (isConstEnumObjectType(objectType) && indexExpression.kind !== SyntaxKind.StringLiteral) { + error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } - // TypeScript 1.0 spec (April 2014): 4.10 Property Access - // - If IndexExpr is a string literal or a numeric literal and ObjExpr's apparent type has a property with the name - // given by that literal(converted to its string representation in the case of a numeric literal), the property access is of the type of that property. - // - Otherwise, if ObjExpr's apparent type has a numeric index signature and IndexExpr is of type Any, the Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if ObjExpr's apparent type has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, - // the property access is of the type of that index signature. - // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. - - // See if we can index as a property. - if (node.argumentExpression) { - const name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name !== undefined) { - const prop = getPropertyOfType(objectType, name); - if (prop) { - getNodeLinks(node).resolvedSymbol = prop; - return getTypeOfSymbol(prop); - } - else if (isConstEnum) { - error(node.argumentExpression, Diagnostics.Property_0_does_not_exist_on_const_enum_1, name, symbolToString(objectType.symbol)); - return unknownType; - } - } - } - - // Check for compatible indexer types. - const allowedNullableFlags = strictNullChecks ? 0 : TypeFlags.Nullable; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol | allowedNullableFlags)) { - - // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { - const numberIndexInfo = getIndexInfoOfType(objectType, IndexKind.Number); - if (numberIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; - return numberIndexInfo.type; - } - } - - // Try to use string indexing. - const stringIndexInfo = getIndexInfoOfType(objectType, IndexKind.String); - if (stringIndexInfo) { - getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; - return stringIndexInfo.type; - } - - // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, getIndexTypeOfType(objectType, IndexKind.Number) ? - Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : - Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); - } - - return anyType; - } - - // REVIEW: Users should know the type that was actually used. - error(node, Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); - - return unknownType; + return getIndexedAccessType(objectType, indexType, node); } - /** - * If indexArgumentExpression is a string literal or number literal, returns its text. - * If indexArgumentExpression is a constant value, returns its string value. - * If indexArgumentExpression is a well known symbol, returns the property name corresponding - * to this symbol, as long as it is a proper symbol reference. - * Otherwise, returns undefined. - */ - function getPropertyNameForIndexedAccess(indexArgumentExpression: Expression, indexArgumentType: Type): string { - if (indexArgumentExpression.kind === SyntaxKind.StringLiteral || indexArgumentExpression.kind === SyntaxKind.NumericLiteral) { - return (indexArgumentExpression).text; - } - if (indexArgumentExpression.kind === SyntaxKind.ElementAccessExpression || indexArgumentExpression.kind === SyntaxKind.PropertyAccessExpression) { - const value = getConstantValue(indexArgumentExpression); - if (value !== undefined) { - return value.toString(); - } - } - if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - const rightHandSideName = ((indexArgumentExpression).name).text; - return getPropertyNameForKnownSymbolName(rightHandSideName); - } - - return undefined; - } - - /** - * A proper symbol reference requires the following: - * 1. The property access denotes a property that exists - * 2. The expression is of the form Symbol. - * 3. The property access is of the primitive type symbol. - * 4. Symbol in this context resolves to the global Symbol object - */ function checkThatExpressionIsProperSymbolReference(expression: Expression, expressionType: Type, reportError: boolean): boolean { if (expressionType === unknownType) { // There is already an error, so no need to report one. @@ -11415,7 +12621,7 @@ namespace ts { function getSpreadArgumentIndex(args: Expression[]): number { for (let i = 0; i < args.length; i++) { const arg = args[i]; - if (arg && arg.kind === SyntaxKind.SpreadElementExpression) { + if (arg && arg.kind === SyntaxKind.SpreadElement) { return i; } } @@ -11503,7 +12709,7 @@ namespace ts { // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type: Type): Signature { - if (type.flags & TypeFlags.ObjectType) { + if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -11518,7 +12724,7 @@ namespace ts { const context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, (source, target) => { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context, instantiateType(source, contextualMapper), target); + inferTypesWithContext(context, instantiateType(source, contextualMapper), target); }); return getSignatureInstantiation(signature, getInferredTypes(context)); } @@ -11553,7 +12759,7 @@ namespace ts { if (thisType) { const thisArgumentNode = getThisArgumentOfCall(node); const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, thisType); + inferTypesWithContext(context, thisArgumentType, thisType); } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use @@ -11564,7 +12770,7 @@ namespace ts { // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { const paramType = getTypeAtPosition(signature, i); - let argType = getEffectiveArgumentType(node, i, arg); + let argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. @@ -11575,7 +12781,7 @@ namespace ts { argType = checkExpressionWithContextualType(arg, paramType, mapper); } - inferTypes(context, argType, paramType); + inferTypesWithContext(context, argType, paramType); } } @@ -11590,7 +12796,7 @@ namespace ts { if (excludeArgument[i] === false) { const arg = args[i]; const paramType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } @@ -11650,7 +12856,7 @@ namespace ts { if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) const paramType = getTypeAtPosition(signature, i); - let argType = getEffectiveArgumentType(node, i, arg); + let argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. @@ -11943,7 +13149,7 @@ namespace ts { /** * Gets the effective argument type for an argument in a call expression. */ - function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number, arg: Expression): Type { + function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number): Type { // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors @@ -12112,7 +13318,7 @@ namespace ts { else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { const typeArguments = (node).typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -12143,7 +13349,7 @@ namespace ts { for (let candidate of candidates) { if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, map(typeArguments, getTypeFromTypeNodeNoAlias)); + candidate = getSignatureInstantiation(candidate, map(typeArguments, getTypeFromTypeNode)); } return candidate; } @@ -12179,7 +13385,7 @@ namespace ts { if (candidate.typeParameters) { let typeArgumentTypes: Type[]; if (typeArguments) { - typeArgumentTypes = map(typeArguments, getTypeFromTypeNodeNoAlias); + typeArgumentTypes = map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -12409,13 +13615,14 @@ namespace ts { const containingClass = getContainingClass(node); if (containingClass) { const containingType = getTypeOfNode(containingClass); - const baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + let baseTypes = getBaseTypes(containingType as InterfaceType); + while (baseTypes.length) { const baseType = baseTypes[0]; if (modifiers & ModifierFlags.Protected && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType as InterfaceType); } } if (modifiers & ModifierFlags.Private) { @@ -12596,13 +13803,41 @@ namespace ts { } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (isInJavaScriptFile(node) && isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { + if (isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } return getReturnTypeOfSignature(signature); } + function isCommonJsRequire(node: Node) { + if (!isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { + return false; + } + // Make sure require is not a local function + const resolvedRequire = resolveName(node.expression, (node.expression).text, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require + return true; + } + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & SymbolFlags.Alias) { + return false; + } + + const targetDeclarationKind = resolvedRequire.flags & SymbolFlags.Function + ? SyntaxKind.FunctionDeclaration + : resolvedRequire.flags & SymbolFlags.Variable + ? SyntaxKind.VariableDeclaration + : SyntaxKind.Unknown; + if (targetDeclarationKind !== SyntaxKind.Unknown) { + const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node: TaggedTemplateExpression): Type { return getReturnTypeOfSignature(getResolvedSignature(node)); } @@ -12645,21 +13880,36 @@ namespace ts { function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (isInferentialContext(mapper)) { + for (let i = 0; i < len; i++) { + const declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); + } + } + } if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + const parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !(parameter.valueDeclaration).type) { + if (!parameter) { + signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } for (let i = 0; i < len; i++) { const parameter = signature.parameters[i]; - const contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!(parameter.valueDeclaration).type) { + const contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { const parameter = lastOrUndefined(signature.parameters); - const contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + if (!(parameter.valueDeclaration).type) { + const contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } } } @@ -12667,7 +13917,7 @@ namespace ts { // the destructured type into the contained binding elements. function assignBindingElementTypes(node: VariableLikeDeclaration) { if (isBindingPattern(node.name)) { - for (const element of (node.name).elements) { + for (const element of node.name.elements) { if (!isOmittedExpression(element)) { if (element.name.kind === SyntaxKind.Identifier) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); @@ -12720,7 +13970,7 @@ namespace ts { // T in the second overload so that we do not infer Base as a candidate for T // (inferring Base would make type argument inference inconsistent between the two // overloads). - inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); } } @@ -12748,7 +13998,7 @@ namespace ts { function createPromiseReturnType(func: FunctionLikeDeclaration, promisedType: Type) { const promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { - error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + error(func, Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } @@ -12848,7 +14098,7 @@ namespace ts { if (!node.possiblyExhaustive) { return false; } - const type = checkExpression(node.expression); + const type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; } @@ -12856,7 +14106,7 @@ namespace ts { if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func: FunctionLikeDeclaration) { @@ -13112,7 +14362,7 @@ namespace ts { function isReferenceThroughNamespaceImport(expr: Expression): boolean { if (expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) { - const node = skipParenthesizedNodes((expr as PropertyAccessExpression | ElementAccessExpression).expression); + const node = skipParentheses((expr as PropertyAccessExpression | ElementAccessExpression).expression); if (node.kind === SyntaxKind.Identifier) { const symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & SymbolFlags.Alias) { @@ -13124,38 +14374,13 @@ namespace ts { return false; } - function checkReferenceExpression(expr: Expression, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { + function checkReferenceExpression(expr: Expression, invalidReferenceMessage: DiagnosticMessage): boolean { // References are combinations of identifiers, parentheses, and property accesses. - const node = skipParenthesizedNodes(expr); + const node = skipParentheses(expr); if (node.kind !== SyntaxKind.Identifier && node.kind !== SyntaxKind.PropertyAccessExpression && node.kind !== SyntaxKind.ElementAccessExpression) { error(expr, invalidReferenceMessage); return false; } - // Because we get the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - const links = getNodeLinks(node); - const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol) { - if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { - // Only variables (and not functions, classes, namespaces, enum objects, or enum members) - // are considered references when referenced using a simple identifier. - if (node.kind === SyntaxKind.Identifier && !(symbol.flags & SymbolFlags.Variable)) { - error(expr, invalidReferenceMessage); - return false; - } - if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { - error(expr, constantVariableMessage); - return false; - } - } - } - else if (node.kind === SyntaxKind.ElementAccessExpression) { - if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { - error(expr, constantVariableMessage); - return false; - } - } return true; } @@ -13217,9 +14442,7 @@ namespace ts { Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -13235,9 +14458,7 @@ namespace ts { Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } @@ -13287,7 +14508,7 @@ namespace ts { } function isConstEnumObjectType(type: Type): boolean { - return type.flags & (TypeFlags.ObjectType | TypeFlags.Anonymous) && type.symbol && isConstEnumSymbol(type.symbol); + return getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol: Symbol): boolean { @@ -13321,24 +14542,25 @@ namespace ts { // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, TypeFlags.NumberLike | TypeFlags.ESSymbol))) { error(left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.Object | TypeFlags.TypeVariable)) { error(right, Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; } - function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, contextualMapper?: TypeMapper): Type { + function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type): Type { const properties = node.properties; for (const p of properties) { - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, contextualMapper); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, contextualMapper?: TypeMapper) { + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, allProperties?: ObjectLiteralElementLike[]) { if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) { const name = (property).name; if (name.kind === SyntaxKind.ComputedPropertyName) { @@ -13367,6 +14589,19 @@ namespace ts { error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), declarationNameToString(name)); } } + else if (property.kind === SyntaxKind.SpreadAssignment) { + if (languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(property, ExternalEmitHelpers.Rest); + } + const nonRestNames: PropertyName[] = []; + if (allProperties) { + for (let i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } else { error(property, Diagnostics.Property_assignment_expected); } @@ -13389,7 +14624,7 @@ namespace ts { const elements = node.elements; const element = elements[elementIndex]; if (element.kind !== SyntaxKind.OmittedExpression) { - if (element.kind !== SyntaxKind.SpreadElementExpression) { + if (element.kind !== SyntaxKind.SpreadElement) { const propName = "" + elementIndex; const type = isTypeAny(sourceType) ? sourceType @@ -13413,10 +14648,10 @@ namespace ts { } else { if (elementIndex < elements.length - 1) { - error(element, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - const restExpression = (element).expression; + const restExpression = (element).expression; if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -13453,7 +14688,7 @@ namespace ts { target = (target).left; } if (target.kind === SyntaxKind.ObjectLiteralExpression) { - return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + return checkObjectLiteralAssignment(target, sourceType); } if (target.kind === SyntaxKind.ArrayLiteralExpression) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); @@ -13463,7 +14698,10 @@ namespace ts { function checkReferenceAssignment(target: Expression, sourceType: Type, contextualMapper?: TypeMapper): Type { const targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { + const error = target.parent.kind === SyntaxKind.SpreadAssignment ? + Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -13667,6 +14905,8 @@ namespace ts { case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(leftType); + rightType = getBaseTypeOfLiteralType(rightType); if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -13746,11 +14986,7 @@ namespace ts { // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - const ok = checkReferenceExpression(left, - Diagnostics.Invalid_left_hand_side_of_assignment_expression, - Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); - // Use default messages - if (ok) { + if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); } @@ -13881,21 +15117,21 @@ namespace ts { } function isTypeAssertion(node: Expression) { - node = skipParenthesizedNodes(node); + node = skipParentheses(node); return node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression; } function checkDeclarationInitializer(declaration: VariableLikeDeclaration) { const type = checkExpressionCached(declaration.initializer); return getCombinedNodeFlags(declaration) & NodeFlags.Const || - getCombinedModifierFlags(declaration) & ModifierFlags.Readonly || + getCombinedModifierFlags(declaration) & ModifierFlags.Readonly && !isParameterPropertyDeclaration(declaration) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } function isLiteralContextualType(contextualType: Type) { if (contextualType) { - if (contextualType.flags & TypeFlags.TypeParameter) { - const apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & TypeFlags.TypeVariable) { + const apparentType = getApparentTypeOfTypeVariable(contextualType); // If the type parameter is constrained to the base primitive type we're checking for, // consider this a literal context. For example, given a type parameter 'T extends string', // this causes us to infer string literal types for T. @@ -13904,7 +15140,7 @@ namespace ts { } contextualType = apparentType; } - return maybeTypeOfKind(contextualType, TypeFlags.Literal); + return maybeTypeOfKind(contextualType, (TypeFlags.Literal | TypeFlags.Index)); } return false; } @@ -13957,6 +15193,24 @@ namespace ts { return type; } + // Returns the type of an expression. Unlike checkExpression, this function is simply concerned + // with computing the type and may not fully check all contained sub-expressions for errors. + function getTypeOfExpression(node: Expression) { + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (node.kind === SyntaxKind.CallExpression && (node).expression.kind !== SyntaxKind.SuperKeyword) { + const funcType = checkNonNullExpression((node).expression); + const signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return checkExpression(node); + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -14053,8 +15307,8 @@ namespace ts { return checkBinaryExpression(node, contextualMapper); case SyntaxKind.ConditionalExpression: return checkConditionalExpression(node, contextualMapper); - case SyntaxKind.SpreadElementExpression: - return checkSpreadElementExpression(node, contextualMapper); + case SyntaxKind.SpreadElement: + return checkSpreadExpression(node, contextualMapper); case SyntaxKind.OmittedExpression: return undefinedWideningType; case SyntaxKind.YieldExpression: @@ -14251,6 +15505,13 @@ namespace ts { checkGrammarFunctionLikeDeclaration(node); } + if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES2017) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); + if (languageVersion < ScriptTarget.ES2015) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); + } + } + checkTypeParameters(node.typeParameters); forEach(node.parameters, checkParameter); @@ -14273,7 +15534,7 @@ namespace ts { } if (node.type) { - if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) { + if (languageVersion >= ScriptTarget.ES2015 && isSyntacticallyValidGenerator(node)) { const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -14631,7 +15892,7 @@ namespace ts { const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); + typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); mapper = createTypeMapper(typeParameters, typeArguments); } const typeArgument = typeArguments[i]; @@ -14696,6 +15957,19 @@ namespace ts { forEach(node.types, checkSourceElement); } + function checkIndexedAccessType(node: IndexedAccessTypeNode) { + getTypeFromIndexedAccessTypeNode(node); + } + + function checkMappedType(node: MappedTypeNode) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + const type = getTypeFromMappedTypeNode(node); + const constraintType = getConstraintTypeFromMappedType(type); + const keyType = constraintType.flags & TypeFlags.TypeVariable ? getApparentTypeOfTypeVariable(constraintType) : constraintType; + checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node: Node): boolean { return (getModifierFlags(node) & ModifierFlags.Private) && isInAmbientContext(node); } @@ -15052,7 +16326,7 @@ namespace ts { return undefined; } - if (promise.flags & TypeFlags.Reference) { + if (getObjectFlags(promise) & ObjectFlags.Reference) { if ((promise).target === tryGetGlobalPromiseType() || (promise).target === getGlobalPromiseLikeType()) { return (promise).typeArguments[0]; @@ -15074,7 +16348,7 @@ namespace ts { return undefined; } - const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)), TypeFacts.NEUndefined); + const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)), TypeFacts.NEUndefinedOrNull); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -15191,61 +16465,19 @@ namespace ts { } /** - * Checks that the return type provided is an instantiation of the global Promise type - * and returns the awaited type of the return type. + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. * - * @param returnType The return type of a FunctionLikeDeclaration - * @param location The node on which to report the error. + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check */ - function checkCorrectPromiseType(returnType: Type, location: Node, diagnostic: DiagnosticMessage, typeName?: string) { - if (returnType === unknownType) { - // The return type already had some other error, so we ignore and return - // the unknown type. - return unknownType; - } - - const globalPromiseType = getGlobalPromiseType(); - if (globalPromiseType === emptyGenericType - || globalPromiseType === getTargetType(returnType)) { - // Either we couldn't resolve the global promise type, which would have already - // reported an error, or we could resolve it and the return type is a valid type - // reference to the global type. In either case, we return the awaited type for - // the return type. - return checkAwaitedType(returnType, location, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - } - - // The promise type was not a valid type reference to the global promise type, so we - // report an error and return the unknown type. - error(location, diagnostic, typeName); - return unknownType; - } - - /** - * Checks the return type of an async function to ensure it is a compatible - * Promise implementation. - * @param node The signature to check - * @param returnType The return type for the function - * @remarks - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. - */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { - if (languageVersion >= ScriptTarget.ES6) { - const returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - } - - const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); - if (globalPromiseConstructorLikeType === emptyObjectType) { - // If we couldn't resolve the global PromiseConstructorLike type we cannot verify - // compatibility with __awaiter. - return unknownType; - } - // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -15270,47 +16502,67 @@ namespace ts { // then(...): Promise; // } // - // When we get the type of the `Promise` symbol here, we get the type of the static - // side of the `Promise` class, which would be `{ new (...): Promise }`. + const returnType = getTypeFromTypeNode(node.type); - const promiseType = getTypeFromTypeNode(node.type); - if (promiseType === unknownType && compilerOptions.isolatedModules) { - // If we are compiling with isolatedModules, we may not be able to resolve the - // type as a value. As such, we will just return unknownType; - return unknownType; + if (languageVersion >= ScriptTarget.ES2015) { + if (returnType === unknownType) { + return unknownType; + } + const globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(node.type, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(node.type); - const promiseConstructor = getNodeLinks(node.type).resolvedSymbol; - if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - // try to fall back to global promise type. - const typeName = promiseConstructor - ? symbolToString(promiseConstructor) - : typeToString(promiseType); - return checkCorrectPromiseType(promiseType, node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - } + if (returnType === unknownType) { + return unknownType; + } - // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. - checkReturnTypeAnnotationAsExpression(node); + const promiseConstructorName = getEntityNameFromTypeNode(node.type); + if (promiseConstructorName === undefined) { + error(node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } - // Validate the promise constructor type. - const promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { - return unknownType; - } + const promiseConstructorSymbol = resolveEntityName(promiseConstructorName, SymbolFlags.Value, /*ignoreErrors*/ true); + const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + error(node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + return unknownType; + } - // Verify there is no local declaration that could collide with the promise constructor. - const promiseName = getEntityNameFromTypeNode(node.type); - const promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); - const rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, SymbolFlags.Value); - if (rootSymbol) { - error(rootSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, - promiseNameOrNamespaceRoot.text, - getFullyQualifiedName(promiseConstructor)); - return unknownType; + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + return unknownType; + } + + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, + Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + + // Verify there is no local declaration that could collide with the promise constructor. + const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + const collidingSymbol = getSymbol(node.locals, rootName.text, SymbolFlags.Value); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, + rootName.text, + entityNameToString(promiseConstructorName)); + return unknownType; + } } // Get and return the awaited type of the return type. - return checkAwaitedType(promiseType, node, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return checkAwaitedType(returnType, node, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } /** Check a decorator */ @@ -15363,47 +16615,26 @@ namespace ts { errorInfo); } - /** Checks a type reference node as an expression. */ - function checkTypeNodeAsExpression(node: TypeNode) { - // When we are emitting type metadata for decorators, we need to try to check the type - // as if it were an expression so that we can emit the type in a value position when we - // serialize the type metadata. - if (node && node.kind === SyntaxKind.TypeReference) { - const root = getFirstIdentifier((node).typeName); - const meaning = root.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; - // Resolve type so we know which symbol is referenced - const rootSymbol = resolveName(root, root.text, meaning | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - // Resolved symbol is alias - if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) { - const aliasTarget = resolveAlias(rootSymbol); - // If alias has value symbol - mark alias as referenced - if (aliasTarget.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - markAliasSymbolAsReferenced(rootSymbol); - } - } - } - } - /** - * Checks the type annotation of an accessor declaration or property declaration as - * an expression if it is a type reference to a type with a value declaration. - */ - function checkTypeAnnotationAsExpression(node: VariableLikeDeclaration) { - checkTypeNodeAsExpression((node).type); - } - - function checkReturnTypeAnnotationAsExpression(node: FunctionLikeDeclaration) { - checkTypeNodeAsExpression(node.type); - } - - /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ - function checkParameterTypeAnnotationsAsExpressions(node: FunctionLikeDeclaration) { - // ensure all type annotations with a value declaration are checked as an expression - for (const parameter of node.parameters) { - checkTypeAnnotationAsExpression(parameter); + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node: TypeNode) { + const typeName = node && getEntityNameFromTypeNode(node); + const rootName = typeName && getFirstIdentifier(typeName); + const rootSymbol = rootName && resolveName(rootName, rootName.text, (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (rootSymbol + && rootSymbol.flags & SymbolFlags.Alias + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node: ParameterDeclaration): TypeNode { + return node.dotDotDotToken ? getRestParameterElementType(node.type) : node.type; + } + /** Check the decorators of a node */ function checkDecorators(node: Node): void { if (!node.decorators) { @@ -15420,26 +16651,41 @@ namespace ts { error(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } + const firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Decorate); + if (node.kind === SyntaxKind.Parameter) { + checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Param); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, ExternalEmitHelpers.Metadata); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { case SyntaxKind.ClassDeclaration: const constructor = getFirstConstructorWithBody(node); if (constructor) { - checkParameterTypeAnnotationsAsExpressions(constructor); + for (const parameter of constructor.parameters) { + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } } break; case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - checkParameterTypeAnnotationsAsExpressions(node); - checkReturnTypeAnnotationAsExpression(node); + for (const parameter of (node).parameters) { + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + + markTypeNodeAsReferenced((node).type); break; case SyntaxKind.PropertyDeclaration: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case SyntaxKind.Parameter: - checkTypeAnnotationAsExpression(node); + markTypeNodeAsReferenced((node).type); break; } } @@ -15585,25 +16831,52 @@ namespace ts { for (const key in node.locals) { const local = node.locals[key]; if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === SyntaxKind.Parameter) { - const parameter = local.valueDeclaration; + if (local.valueDeclaration && getRootDeclaration(local.valueDeclaration).kind === SyntaxKind.Parameter) { + const parameter = getRootDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !isParameterPropertyDeclaration(parameter) && !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { + !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - forEach(local.declarations, d => error(d.name || d, Diagnostics._0_is_declared_but_never_used, local.name)); + forEach(local.declarations, d => errorUnusedLocal(d.name || d, local.name)); } } } } } - function parameterNameStartsWithUnderscore(parameter: ParameterDeclaration) { - return parameter.name && parameter.name.kind === SyntaxKind.Identifier && (parameter.name).text.charCodeAt(0) === CharacterCodes._; + function isRemovedPropertyFromObjectSpread(node: Node) { + if (isBindingElement(node) && isObjectBindingPattern(node.parent)) { + const lastElement = lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + + function errorUnusedLocal(node: Node, name: string) { + if (isIdentifierThatStartsWithUnderScore(node)) { + const declaration = getRootDeclaration(node.parent); + if (declaration.kind === SyntaxKind.VariableDeclaration && + (declaration.parent.parent.kind === SyntaxKind.ForInStatement || + declaration.parent.parent.kind === SyntaxKind.ForOfStatement)) { + return; + } + } + + if (!isRemovedPropertyFromObjectSpread(node.kind === SyntaxKind.Identifier ? node.parent : node)) { + error(node, Diagnostics._0_is_declared_but_never_used, name); + } + } + + function parameterNameStartsWithUnderscore(parameterName: DeclarationName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + + function isIdentifierThatStartsWithUnderScore(node: Node) { + return node.kind === SyntaxKind.Identifier && (node).text.charCodeAt(0) === CharacterCodes._; } function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression): void { @@ -15653,7 +16926,7 @@ namespace ts { if (!local.isReferenced && !local.exportSymbol) { for (const declaration of local.declarations) { if (!isAmbientModule(declaration)) { - error(declaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + errorUnusedLocal(declaration.name, local.name); } } } @@ -15763,7 +17036,7 @@ namespace ts { function checkCollisionWithRequireExportsInGeneratedCode(node: Node, name: Identifier) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ModuleKind.ES6) { + if (modulekind >= ModuleKind.ES2015) { return; } @@ -15786,7 +17059,7 @@ namespace ts { } function checkCollisionWithGlobalPromiseInGeneratedCode(node: Node, name: Identifier): void { - if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= ScriptTarget.ES2017 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } @@ -15911,7 +17184,8 @@ namespace ts { // so we need to do a bit of extra work to check if reference is legal const enclosingContainer = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === SyntaxKind.Parameter) { + if (symbol.valueDeclaration.kind === SyntaxKind.Parameter || + symbol.valueDeclaration.kind === SyntaxKind.BindingElement) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -15944,7 +17218,7 @@ namespace ts { } function convertAutoToAny(type: Type) { - return type === autoType ? anyType : type; + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; } // Check variable, parameter, or property declaration @@ -15963,6 +17237,9 @@ namespace ts { } if (node.kind === SyntaxKind.BindingElement) { + if (node.parent.kind === SyntaxKind.ObjectBindingPattern && languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Rest); + } // check computed properties inside property names of binding elements if (node.propertyName && node.propertyName.kind === SyntaxKind.ComputedPropertyName) { checkComputedPropertyName(node.propertyName); @@ -15973,6 +17250,7 @@ namespace ts { const parentType = getTypeForBindingElementParent(parent); const name = node.propertyName || node.name; const property = getPropertyOfType(parentType, getTextOfPropertyName(name)); + markPropertyAsReferenced(property); if (parent.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent, parent.initializer, parentType, property); } @@ -16172,8 +17450,7 @@ namespace ts { } else { const leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); // iteratedType will be undefined if the rightType was missing properties/signatures // required to get its iteratedType (like [Symbol.iterator] or next). This may be @@ -16195,6 +17472,7 @@ namespace ts { // Grammar checking checkGrammarForInOrForOfStatement(node); + const rightType = checkNonNullExpression(node.expression); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement @@ -16205,7 +17483,6 @@ namespace ts { if (variable && isBindingPattern(variable.name)) { error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - checkForInOrForOfVariableDeclaration(node); } else { @@ -16218,20 +17495,18 @@ namespace ts { if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, TypeFlags.StringLike)) { + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, Diagnostics.Invalid_left_hand_side_in_for_in_statement, - Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); + checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - const rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.Object | TypeFlags.TypeVariable)) { error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } @@ -16259,7 +17534,7 @@ namespace ts { if (isTypeAny(inputType)) { return inputType; } - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { @@ -16321,7 +17596,7 @@ namespace ts { if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & TypeFlags.Reference) && (type).target === getGlobalIterableType()) { + if ((getObjectFlags(type) & ObjectFlags.Reference) && (type).target === getGlobalIterableType()) { typeAsIterable.iterableElementType = (type).typeArguments[0]; } else { @@ -16367,7 +17642,7 @@ namespace ts { if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & TypeFlags.Reference) && (type).target === getGlobalIteratorType()) { + if ((getObjectFlags(type) & ObjectFlags.Reference) && (type).target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = (type).typeArguments[0]; } else { @@ -16411,7 +17686,7 @@ namespace ts { // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & TypeFlags.Reference) && (type).target === getGlobalIterableIteratorType()) { + if ((getObjectFlags(type) & ObjectFlags.Reference) && (type).target === getGlobalIterableIteratorType()) { return (type).typeArguments[0]; } @@ -16437,13 +17712,17 @@ namespace ts { * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable). */ function checkElementTypeOfArrayOrString(arrayOrStringType: Type, errorNode: Node): Type { - Debug.assert(languageVersion < ScriptTarget.ES6); + Debug.assert(languageVersion < ScriptTarget.ES2015); - // After we remove all types that are StringLike, we will know if there was a string constituent - // based on whether the remaining type is the same as the initial type. let arrayType = arrayOrStringType; if (arrayOrStringType.flags & TypeFlags.Union) { - arrayType = getUnionType(filter((arrayOrStringType as UnionType).types, t => !(t.flags & TypeFlags.StringLike)), /*subtypeReduction*/ true); + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + const arrayTypes = (arrayOrStringType as UnionType).types; + const filteredTypes = filter(arrayTypes, t => !(t.flags & TypeFlags.StringLike)); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + } } else if (arrayOrStringType.flags & TypeFlags.StringLike) { arrayType = neverType; @@ -16589,6 +17868,7 @@ namespace ts { let hasDuplicateDefaultClause = false; const expressionType = checkExpression(node.expression); + const expressionIsLiteral = isLiteralType(expressionType); forEach(node.caseBlock.clauses, clause => { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) { @@ -16609,10 +17889,16 @@ namespace ts { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. - const caseType = checkExpression(caseClause.expression); - if (!isTypeEqualityComparableTo(expressionType, caseType)) { + let caseType = checkExpression(caseClause.expression); + const caseIsLiteral = isLiteralType(caseType); + let comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); } } forEach(clause.statements, checkSourceElement); @@ -16665,22 +17951,20 @@ namespace ts { if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.name.kind !== SyntaxKind.Identifier) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.name, Diagnostics.Catch_clause_variable_name_must_be_an_identifier); - } - else if (catchClause.variableDeclaration.type) { + if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); } else if (catchClause.variableDeclaration.initializer) { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - const identifierName = (catchClause.variableDeclaration.name).text; - const locals = catchClause.block.locals; - if (locals) { - const localSymbol = locals[identifierName]; - if (localSymbol && (localSymbol.flags & SymbolFlags.BlockScopedVariable) !== 0) { - grammarErrorOnNode(localSymbol.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + const blockLocals = catchClause.block.locals; + if (blockLocals) { + for (const caughtName in catchClause.locals) { + const blockLocal = blockLocals[caughtName]; + if (blockLocal && (blockLocal.flags & SymbolFlags.BlockScopedVariable) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } } } } @@ -16708,7 +17992,7 @@ namespace ts { checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); - if (type.flags & TypeFlags.Class && isClassLike(type.symbol.valueDeclaration)) { + if (getObjectFlags(type) & ObjectFlags.Class && isClassLike(type.symbol.valueDeclaration)) { const classDeclaration = type.symbol.valueDeclaration; for (const member of classDeclaration.members) { // Only process instance properties with computed names here. @@ -16727,7 +18011,7 @@ namespace ts { if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & TypeFlags.Interface)) { + if (!errorNode && (getObjectFlags(type) & ObjectFlags.Interface)) { const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -16764,7 +18048,7 @@ namespace ts { else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & TypeFlags.Interface) { + else if (getObjectFlags(containingType) & ObjectFlags.Interface) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -16873,6 +18157,10 @@ namespace ts { const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { + if (languageVersion < ScriptTarget.ES2015 && !isInAmbientContext(node)) { + checkExternalEmitHelpers(baseTypeNode.parent, ExternalEmitHelpers.Extends); + } + const baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { const baseType = baseTypes[0]; @@ -16891,7 +18179,9 @@ namespace ts { checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType.symbol.valueDeclaration && !isInAmbientContext(baseType.symbol.valueDeclaration)) { + if (baseType.symbol.valueDeclaration && + !isInAmbientContext(baseType.symbol.valueDeclaration) && + baseType.symbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration) { if (!isBlockScopedNameDeclaredBeforeUse(baseType.symbol.valueDeclaration, node)) { error(baseTypeNode, Diagnostics.A_class_must_be_declared_after_its_base_class); } @@ -16921,8 +18211,8 @@ namespace ts { if (produceDiagnostics) { const t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - const declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; - if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) { + const declaredType = getObjectFlags(t) & ObjectFlags.Reference ? (t).target : t; + if (getObjectFlags(declaredType) & ObjectFlags.ClassOrInterface) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -16939,14 +18229,14 @@ namespace ts { } } - function checkBaseTypeAccessibility(type: ObjectType, node: ExpressionWithTypeArguments) { + function checkBaseTypeAccessibility(type: Type, node: ExpressionWithTypeArguments) { const signatures = getSignaturesOfType(type, SignatureKind.Construct); if (signatures.length) { const declaration = signatures[0].declaration; if (declaration && getModifierFlags(declaration) & ModifierFlags.Private) { const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, (node.expression).text); + error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } } } @@ -17175,6 +18465,7 @@ namespace ts { checkGrammarDecorators(node) || checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); checkSourceElement(node.type); } @@ -17295,6 +18586,7 @@ namespace ts { } return undefined; case SyntaxKind.NumericLiteral: + checkGrammarNumericLiteral(e); return +(e).text; case SyntaxKind.ParenthesizedExpression: return evalConstant((e).expression); @@ -17341,7 +18633,7 @@ namespace ts { } } - enumType = checkExpression(expression); + enumType = getTypeOfExpression(expression); // allow references to constant members of other enums if (!(enumType.symbol && (enumType.symbol.flags & SymbolFlags.Enum))) { return undefined; @@ -17748,7 +19040,7 @@ namespace ts { } } else { - if (modulekind === ModuleKind.ES6 && !isInAmbientContext(node)) { + if (modulekind === ModuleKind.ES2015 && !isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, Diagnostics.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); } @@ -17819,7 +19111,13 @@ namespace ts { const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { - error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + if (node.isExportEquals) { + error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; } // Grammar checking @@ -17836,7 +19134,7 @@ namespace ts { checkExternalModuleExports(container); if (node.isExportEquals && !isInAmbientContext(node)) { - if (modulekind === ModuleKind.ES6) { + if (modulekind === ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -17959,7 +19257,12 @@ namespace ts { case SyntaxKind.IntersectionType: return checkUnionOrIntersectionType(node); case SyntaxKind.ParenthesizedType: - return checkSourceElement((node).type); + case SyntaxKind.TypeOperator: + return checkSourceElement((node).type); + case SyntaxKind.IndexedAccessType: + return checkIndexedAccessType(node); + case SyntaxKind.MappedType: + return checkMappedType(node); case SyntaxKind.FunctionDeclaration: return checkFunctionDeclaration(node); case SyntaxKind.Block: @@ -18134,9 +19437,33 @@ namespace ts { function getDiagnosticsWorker(sourceFile: SourceFile): Diagnostic[] { throwIfNonDiagnosticsProducing(); if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); - return diagnostics.getDiagnostics(sourceFile.fileName); + + const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics); + return concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + + return semanticDiagnostics; } + + // Global diagnostics are always added when a file is not provided to + // getDiagnostics forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); } @@ -18362,7 +19689,7 @@ namespace ts { // Since we already checked for ExportAssignment, this really could only be an Import const importEqualsDeclaration = getAncestor(entityName, SyntaxKind.ImportEqualsDeclaration); Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } if (isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { @@ -18482,7 +19809,7 @@ namespace ts { // fallthrough case SyntaxKind.SuperKeyword: - const type = isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + const type = isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); return type.symbol; case SyntaxKind.ThisType: @@ -18512,7 +19839,7 @@ namespace ts { case SyntaxKind.NumericLiteral: // index access if (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { - const objectType = checkExpression((node.parent).expression); + const objectType = getTypeOfExpression((node.parent).expression); if (objectType === unknownType) return undefined; const apparentType = getApparentType(objectType); if (apparentType === unknownType) return undefined; @@ -18551,7 +19878,7 @@ namespace ts { } if (isPartOfExpression(node)) { - return getTypeOfExpression(node); + return getRegularTypeOfExpression(node); } if (isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -18613,7 +19940,7 @@ namespace ts { // If this is from "for" initializer // for ({a } = elems[0];.....) { } if (expr.parent.kind === SyntaxKind.BinaryExpression) { - const iteratedType = checkExpression((expr.parent).right); + const iteratedType = getTypeOfExpression((expr.parent).right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from nested object binding pattern @@ -18643,11 +19970,11 @@ namespace ts { return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); } - function getTypeOfExpression(expr: Expression): Type { + function getRegularTypeOfExpression(expr: Expression): Type { if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) { expr = expr.parent; } - return getRegularTypeOfLiteralType(checkExpression(expr)); + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } /** @@ -18689,6 +20016,10 @@ namespace ts { return symbols; } else if (symbol.flags & SymbolFlags.Transient) { + if ((symbol as SymbolLinks).leftSpread) { + const links = symbol as SymbolLinks; + return [links.leftSpread, links.rightSpread]; + } let target: Symbol; let next = symbol; while (next = getSymbolLinks(next).target) { @@ -18745,7 +20076,7 @@ namespace ts { function isNameOfModuleOrEnumDeclaration(node: Identifier) { const parent = node.parent; - return isModuleOrEnumDeclaration(parent) && node === parent.name; + return parent && isModuleOrEnumDeclaration(parent) && node === parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration @@ -18996,7 +20327,7 @@ namespace ts { } function isFunctionType(type: Type): boolean { - return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Call).length > 0; + return type.flags & TypeFlags.Object && getSignaturesOfType(type, SignatureKind.Call).length > 0; } function getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind { @@ -19070,7 +20401,7 @@ namespace ts { } function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - const type = getWidenedType(getTypeOfExpression(expr)); + const type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -19177,7 +20508,8 @@ namespace ts { getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration, - writeLiteralConstValue + writeLiteralConstValue, + getJsxFactoryEntity: () => _jsxFactoryEntity }; // defined here to avoid outer scope pollution @@ -19216,6 +20548,10 @@ namespace ts { if (typeReferenceDirective) { (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } } } return typeReferenceDirectives; @@ -19272,8 +20608,6 @@ namespace ts { // Initialize global symbol table let augmentations: LiteralExpression[][]; - let requestedExternalEmitHelpers: NodeFlags = 0; - let firstFileRequestingExternalHelpers: SourceFile; for (const file of host.getSourceFiles()) { if (!isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); @@ -19293,15 +20627,6 @@ namespace ts { } } } - if ((compilerOptions.isolatedModules || isExternalModule(file)) && !file.isDeclarationFile) { - const fileRequestedExternalEmitHelpers = file.flags & NodeFlags.EmitHelperFlags; - if (fileRequestedExternalEmitHelpers) { - requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; - if (firstFileRequestingExternalHelpers === undefined) { - firstFileRequestingExternalHelpers = file; - } - } - } } if (augmentations) { @@ -19348,7 +20673,7 @@ namespace ts { getGlobalTemplateStringsArrayType = memoize(() => getGlobalType("TemplateStringsArray")); - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { getGlobalESSymbolType = memoize(() => getGlobalType("Symbol")); getGlobalIterableType = memoize(() => getGlobalType("Iterable", /*arity*/ 1)); getGlobalIteratorType = memoize(() => getGlobalType("Iterator", /*arity*/ 1)); @@ -19362,57 +20687,56 @@ namespace ts { } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); const symbol = getGlobalSymbol("ReadonlyArray", SymbolFlags.Type, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + } - // If we have specified that we are importing helpers, we should report global - // errors if we cannot resolve the helpers external module, or if it does not have - // the necessary helpers exported. - if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { - // Find the first reference to the helpers module. - const helpersModule = resolveExternalModule( - firstFileRequestingExternalHelpers, - externalHelpersModuleNameText, - Diagnostics.Cannot_find_module_0, - /*errorNode*/ undefined); - - // If we found the module, report errors if it does not have the necessary exports. - if (helpersModule) { - const exports = helpersModule.exports; - if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES6) { - verifyHelperSymbol(exports, "__extends", SymbolFlags.Value); - } - if (requestedExternalEmitHelpers & NodeFlags.HasJsxSpreadAttributes && compilerOptions.jsx !== JsxEmit.Preserve) { - verifyHelperSymbol(exports, "__assign", SymbolFlags.Value); - } - if (requestedExternalEmitHelpers & NodeFlags.HasDecorators) { - verifyHelperSymbol(exports, "__decorate", SymbolFlags.Value); - if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", SymbolFlags.Value); - } - } - if (requestedExternalEmitHelpers & NodeFlags.HasParamDecorators) { - verifyHelperSymbol(exports, "__param", SymbolFlags.Value); - } - if (requestedExternalEmitHelpers & NodeFlags.HasAsyncFunctions) { - verifyHelperSymbol(exports, "__awaiter", SymbolFlags.Value); - if (languageVersion < ScriptTarget.ES6) { - verifyHelperSymbol(exports, "__generator", SymbolFlags.Value); + function checkExternalEmitHelpers(location: Node, helpers: ExternalEmitHelpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + const sourceFile = getSourceFileOfNode(location); + if (isEffectiveExternalModule(sourceFile, compilerOptions)) { + const helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + const uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (let helper = ExternalEmitHelpers.FirstEmitHelper; helper <= ExternalEmitHelpers.LastEmitHelper; helper <<= 1) { + if (uncheckedHelpers & helper) { + const name = getHelperName(helper); + const symbol = getSymbol(helpersModule.exports, escapeIdentifier(name), SymbolFlags.Value); + if (!symbol) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, externalHelpersModuleNameText, name); + } + } } } + requestedExternalEmitHelpers |= helpers; } } } - function verifyHelperSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags) { - const symbol = getSymbol(symbols, escapeIdentifier(name), meaning); - if (!symbol) { - error(/*location*/ undefined, Diagnostics.Module_0_has_no_exported_member_1, externalHelpersModuleNameText, name); + function getHelperName(helper: ExternalEmitHelpers) { + switch (helper) { + case ExternalEmitHelpers.Extends: return "__extends"; + case ExternalEmitHelpers.Assign: return "__assign"; + case ExternalEmitHelpers.Rest: return "__rest"; + case ExternalEmitHelpers.Decorate: return "__decorate"; + case ExternalEmitHelpers.Metadata: return "__metadata"; + case ExternalEmitHelpers.Param: return "__param"; + case ExternalEmitHelpers.Awaiter: return "__awaiter"; + case ExternalEmitHelpers.Generator: return "__generator"; } } + function resolveHelpersModule(node: SourceFile, errorNode: Node) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + + function createInstantiatedPromiseLikeType(): ObjectType { const promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { @@ -19427,7 +20751,7 @@ namespace ts { const thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - const thenableType = createObjectType(TypeFlags.Anonymous); + const thenableType = createObjectType(ObjectFlags.Anonymous); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -19744,7 +21068,7 @@ namespace ts { } } - function checkGrammarTypeParameterList(node: FunctionLikeDeclaration, typeParameters: NodeArray, file: SourceFile): boolean { + function checkGrammarTypeParameterList(typeParameters: NodeArray, file: SourceFile): boolean { if (checkGrammarForDisallowedTrailingComma(typeParameters)) { return true; } @@ -19795,7 +21119,7 @@ namespace ts { function checkGrammarFunctionLikeDeclaration(node: FunctionLikeDeclaration): boolean { // Prevent cascading error by short-circuit const file = getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } @@ -19947,7 +21271,6 @@ namespace ts { checkGrammarHeritageClause(heritageClause); } } - return false; } @@ -19975,13 +21298,13 @@ namespace ts { if (!node.body) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); } - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher); } } } - function checkGrammarForInvalidQuestionMark(node: Declaration, questionToken: Node, message: DiagnosticMessage): boolean { + function checkGrammarForInvalidQuestionMark(questionToken: Node, message: DiagnosticMessage): boolean { if (questionToken) { return grammarErrorOnNode(questionToken, message); } @@ -19995,6 +21318,9 @@ namespace ts { const GetOrSetAccessor = GetAccessor | SetAccessor; for (const prop of node.properties) { + if (prop.kind === SyntaxKind.SpreadAssignment) { + continue; + } const name = prop.name; if (name.kind === SyntaxKind.ComputedPropertyName) { // If the name is not a ComputedPropertyName, the grammar checking will skip it @@ -20027,7 +21353,7 @@ namespace ts { let currentKind: number; if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) { // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop, (prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); + checkGrammarForInvalidQuestionMark((prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { checkGrammarNumericLiteral(name); } @@ -20155,6 +21481,9 @@ namespace ts { else if (accessor.body === undefined && !(getModifierFlags(accessor) & ModifierFlags.Abstract)) { return grammarErrorAtPos(getSourceFileOfNode(accessor), accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); } + else if (accessor.body && getModifierFlags(accessor) & ModifierFlags.Abstract) { + return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); } @@ -20211,7 +21540,7 @@ namespace ts { } if (node.parent.kind === SyntaxKind.ObjectLiteralExpression) { - if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { @@ -20298,7 +21627,7 @@ namespace ts { if (node.dotDotDotToken) { const elements = (node.parent).elements; if (node !== lastOrUndefined(elements)) { - return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === SyntaxKind.ArrayBindingPattern || node.name.kind === SyntaxKind.ObjectBindingPattern) { @@ -20306,7 +21635,7 @@ namespace ts { } if (node.initializer) { - // Error on equals token which immediate precedes the initializer + // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer); } } @@ -20562,8 +21891,22 @@ namespace ts { function checkGrammarNumericLiteral(node: NumericLiteral): boolean { // Grammar checking - if (node.isOctalLiteral && languageVersion >= ScriptTarget.ES5) { - return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); + if (node.isOctalLiteral) { + let diagnosticMessage: DiagnosticMessage | undefined; + if (languageVersion >= ScriptTarget.ES5) { + diagnosticMessage = Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (isChildOfNodeWithKind(node, SyntaxKind.LiteralType)) { + diagnosticMessage = Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (isChildOfNodeWithKind(node, SyntaxKind.EnumMember)) { + diagnosticMessage = Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + const withMinus = isPrefixUnaryExpression(node.parent) && node.parent.operator === SyntaxKind.MinusToken; + const literal = `${withMinus ? "-" : ""}0o${node.text}`; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 72dd42b3997..e5b7d9a8152 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -77,6 +77,11 @@ namespace ts { type: "string", description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, + { + name: "jsxFactory", + type: "string", + description: Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, { name: "listFiles", type: "boolean", @@ -101,7 +106,7 @@ namespace ts { "amd": ModuleKind.AMD, "system": ModuleKind.System, "umd": ModuleKind.UMD, - "es6": ModuleKind.ES6, + "es6": ModuleKind.ES2015, "es2015": ModuleKind.ES2015, }), description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, @@ -261,10 +266,13 @@ namespace ts { type: createMap({ "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, - "es6": ScriptTarget.ES6, + "es6": ScriptTarget.ES2015, "es2015": ScriptTarget.ES2015, + "es2016": ScriptTarget.ES2016, + "es2017": ScriptTarget.ES2017, + "esnext": ScriptTarget.ESNext, }), - description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, + description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, paramType: Diagnostics.VERSION, }, { @@ -426,7 +434,8 @@ namespace ts { "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" + "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", + "es2017.string": "lib.es2017.string.d.ts", }), }, description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon @@ -444,15 +453,27 @@ namespace ts { name: "importHelpers", type: "boolean", description: Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ - export let typingOptionDeclarations: CommandLineOption[] = [ + export let typeAcquisitionDeclarations: CommandLineOption[] = [ { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ name: "enableAutoDiscovery", type: "boolean", }, + { + name: "enable", + type: "boolean", + }, { name: "include", type: "list", @@ -487,6 +508,20 @@ namespace ts { let optionNameMapCache: OptionNameMap; + /* @internal */ + export function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { + const result: TypeAcquisition = { + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] + }; + return result; + } + return typeAcquisition; + } + /* @internal */ export function getOptionNameMap(): OptionNameMap { if (optionNameMapCache) { @@ -508,23 +543,13 @@ namespace ts { /* @internal */ export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic { - const namesOfType: string[] = []; - for (const key in opt.type) { - namesOfType.push(` '${key}'`); - } + const namesOfType = Object.keys(opt.type).map(key => `'${key}'`).join(", "); return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType); } /* @internal */ export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) { - const key = trimString((value || "")).toLowerCase(); - const map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } /* @internal */ @@ -547,7 +572,6 @@ namespace ts { } } - /* @internal */ export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine { const options: CompilerOptions = {}; const fileNames: string[] = []; @@ -595,7 +619,13 @@ namespace ts { i++; break; case "boolean": - options[opt.name] = true; + // boolean flag has optional value true, false, others + let optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } break; case "string": options[opt.name] = args[i] || ""; @@ -810,15 +840,16 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine { + export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine { const errors: Diagnostic[] = []; + basePath = normalizeSlashes(basePath); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { return { options: {}, fileNames: [], - typingOptions: {}, + typeAcquisition: {}, raw: json, errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))], wildcardDirectories: {} @@ -826,7 +857,10 @@ namespace ts { } let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + const jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); if (json["extends"]) { let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}]; @@ -857,7 +891,7 @@ namespace ts { return { options, fileNames, - typingOptions, + typeAcquisition, raw: json, errors, wildcardDirectories, @@ -867,7 +901,7 @@ namespace ts { function tryExtendsName(extendedConfig: string): [string[], string[], string[], CompilerOptions] { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) { - errors.push(createCompilerDiagnostic(Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return; } let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName); @@ -902,6 +936,9 @@ namespace ts { if (hasProperty(json, "files")) { if (isArray(json["files"])) { fileNames = json["files"]; + if (fileNames.length === 0) { + errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } } else { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); @@ -931,8 +968,8 @@ namespace ts { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders and the outDir - excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + // If no includes were specified, exclude common package folders and the outDir + excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; if (outDir) { @@ -944,7 +981,18 @@ namespace ts { includeSpecs = ["**/*"]; } - return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); + + if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) { + errors.push( + createCompilerDiagnostic( + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + configFileName || "tsconfig.json", + JSON.stringify(includeSpecs || []), + JSON.stringify(excludeSpecs || []))); + } + + return result; } } @@ -965,9 +1013,9 @@ namespace ts { return { options, errors }; } - export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypingOptions, errors: Diagnostic[] } { + export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition, errors: Diagnostic[] } { const errors: Diagnostic[] = []; - const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options, errors }; } @@ -981,18 +1029,18 @@ namespace ts { return options; } - function convertTypingOptionsFromJsonWorker(jsonOptions: any, - basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions { + function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, + basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition { + + const options: TypeAcquisition = { enable: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(typeAcquisitionDeclarations, typeAcquisition, basePath, options, Diagnostics.Unknown_type_acquisition_option_0, errors); - const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json" - ? { enableAutoDiscovery: true, include: [], exclude: [] } - : { enableAutoDiscovery: false, include: [], exclude: [] }; - convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors); return options; } function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string, - defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) { + defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) { if (!jsonOptions) { return; @@ -1137,7 +1185,7 @@ namespace ts { * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult { + function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult { basePath = normalizePath(basePath); // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -1171,7 +1219,7 @@ namespace ts { // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. - const supportedExtensions = getSupportedExtensions(options); + const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. @@ -1239,12 +1287,13 @@ namespace ts { /** * Gets directories in a set of include patterns that should be watched for changes. */ - function getWildcardDirectories(include: string[], exclude: string[], path: string, useCaseSensitiveFileNames: boolean) { + function getWildcardDirectories(include: string[], exclude: string[], path: string, useCaseSensitiveFileNames: boolean): Map { // 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 + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler // // We watch a directory without recursion if it contains a wildcard in the file segment of // the pattern: @@ -1257,15 +1306,14 @@ namespace ts { if (include !== undefined) { const recursiveKeys: string[] = []; for (const file of include) { - const name = normalizePath(combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name)) { + const spec = normalizePath(combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { continue; } - const match = wildcardDirectoryPattern.exec(name); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { - const key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - const flags = watchRecursivePattern.test(name) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None; + const { key, flags } = match; const existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -1289,6 +1337,20 @@ namespace ts { return wildcardDirectories; } + function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: boolean): { key: string, flags: WatchDirectoryFlags } | undefined { + const match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None + }; + } + if (isImplicitGlob(spec)) { + return { key: spec, flags: WatchDirectoryFlags.Recursive }; + } + return undefined; + } + /** * Determines whether a literal or wildcard file has already been included that has a higher * extension priority. diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts index 116a8e849a3..bd9190dbec7 100644 --- a/src/compiler/comments.ts +++ b/src/compiler/comments.ts @@ -156,6 +156,9 @@ namespace ts { if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { @@ -188,7 +191,7 @@ namespace ts { } } - function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + function emitLeadingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { if (!hasWrittenComment) { emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -211,7 +214,7 @@ namespace ts { forEachTrailingCommentToEmit(pos, emitTrailingComment); } - function emitTrailingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) { + function emitTrailingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -242,7 +245,7 @@ namespace ts { } } - function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) { + function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space emitPos(commentPos); diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7c68306211a..ceff1359579 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,6 +1,11 @@ /// /// +namespace ts { + /** The version of the TypeScript compiler release */ + export const version = "2.2.0"; +} + /* @internal */ namespace ts { /** @@ -20,6 +25,9 @@ namespace ts { const createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; + export function createMap(template?: MapLike): Map { const map: Map = createObject(null); // tslint:disable-line:no-null-keyword @@ -121,6 +129,13 @@ namespace ts { return undefined; } + export function zipWith(arrayA: T[], arrayB: U[], callback: (a: T, b: U, index: number) => void): void { + Debug.assert(arrayA.length === arrayB.length); + for (let i = 0; i < arrayA.length; i++) { + callback(arrayA[i], arrayB[i], i); + } + } + /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -265,13 +280,33 @@ namespace ts { if (array) { result = []; for (let i = 0; i < array.length; i++) { - const v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } + // Maps from T to T and avoids allocation if all elements map to themselves + export function sameMap(array: T[], f: (x: T, i: number) => T): T[] { + let result: T[]; + if (array) { + for (let i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + const item = array[i]; + const mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + /** * Flattens an array containing a mix of array or non-array elements. * @@ -399,9 +434,25 @@ namespace ts { return result; } + export function some(array: T[], predicate?: (value: T) => boolean): boolean { + if (array) { + if (predicate) { + for (const v of array) { + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + export function concatenate(array1: T[], array2: T[]): T[] { - if (!array2 || !array2.length) return array1; - if (!array1 || !array1.length) return array2; + if (!some(array2)) return array1; + if (!some(array1)) return array2; return [...array1, ...array2]; } @@ -422,6 +473,44 @@ namespace ts { return result; } + export function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean { + if (!array1 || !array2) { + return array1 === array2; + } + + if (array1.length !== array2.length) { + return false; + } + + for (let i = 0; i < array1.length; i++) { + const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; + } + } + + return true; + } + + export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !equalOwnProperties(oldOptions.paths, newOptions.paths); + } + /** * Compacts an array, removing any falsey elements. */ @@ -443,6 +532,27 @@ namespace ts { return result || array; } + /** + * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: (x: T, y: T) => Comparison = compareValues, offsetA = 0, offsetB = 0): T[] | undefined { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; + const result: T[] = []; + outer: for (; offsetB < arrayB.length; offsetB++) { + inner: for (; offsetA < arrayA.length; offsetA++) { + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case Comparison.LessThan: break inner; + case Comparison.EqualTo: continue outer; + case Comparison.GreaterThan: continue inner; + } + } + result.push(arrayB[offsetB]); + } + return result; + } + export function sum(array: any[], prop: string): number { let result = 0; for (const v of array) { @@ -451,14 +561,45 @@ namespace ts { return result; } - export function addRange(to: T[], from: T[]): void { - if (to && from) { - for (const v of from) { - if (v !== undefined) { - to.push(v); - } - } + /** + * Appends a value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param value The value to append to the array. If `value` is `undefined`, nothing is + * appended. + */ + export function append(to: T[] | undefined, value: T | undefined): T[] | undefined { + if (value === undefined) return to; + if (to === undefined) return [value]; + to.push(value); + return to; + } + + /** + * Appends a range of value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + export function addRange(to: T[] | undefined, from: T[] | undefined): T[] | undefined { + if (from === undefined) return to; + for (const v of from) { + to = append(to, v); } + return to; + } + + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + export function stableSort(array: T[], comparer: (x: T, y: T) => Comparison = compareValues) { + return array + .map((_, i) => i) // create array of indices + .sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)) // sort indices by value then position + .map(i => array[i]); // get sorted array } export function rangeEquals(array1: T[], array2: T[], pos: number, end: number) { @@ -471,31 +612,47 @@ namespace ts { return true; } + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ export function firstOrUndefined(array: T[]): T { return array && array.length > 0 ? array[0] : undefined; } + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + export function lastOrUndefined(array: T[]): T { + return array && array.length > 0 + ? array[array.length - 1] + : undefined; + } + + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ export function singleOrUndefined(array: T[]): T { return array && array.length === 1 ? array[0] : undefined; } + /** + * Returns the only element of an array if it contains only one element; otheriwse, returns the + * array. + */ export function singleOrMany(array: T[]): T | T[] { return array && array.length === 1 ? array[0] : array; } - /** - * Returns the last element of an array if non-empty, undefined otherwise. - */ - export function lastOrUndefined(array: T[]): T { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + export function replaceElement(array: T[], index: number, value: T): T[] { + const result = array.slice(0); + result[index] = value; + return result; } /** @@ -505,12 +662,12 @@ namespace ts { * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - export function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number { + export function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number, offset?: number): number { if (!array || array.length === 0) { return -1; } - let low = 0; + let low = offset || 0; let high = array.length - 1; comparer = comparer !== undefined ? comparer @@ -669,6 +826,13 @@ namespace ts { } } + export function appendProperty(map: Map, key: string | number, value: T): Map { + if (key === undefined || value === undefined) return map; + if (map === undefined) map = createMap(); + map[key] = value; + return map; + } + export function assign, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3; export function assign, T2>(t: T1, arg1: T2): T1 & T2; export function assign>(t: T1, ...args: any[]): any; @@ -699,24 +863,6 @@ namespace ts { return result; } - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - export function reduceOwnProperties(map: MapLike, callback: (aggregate: U, value: T, key: string) => U, initial: U): U { - let result = initial; - for (const key in map) if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -781,7 +927,7 @@ namespace ts { return result; } - export function extend(first: T1 , second: T2): T1 & T2 { + export function extend(first: T1, second: T2): T1 & T2 { const result: T1 & T2 = {}; for (const id in second) if (hasOwnProperty.call(second, id)) { (result as any)[id] = (second as any)[id]; @@ -796,7 +942,7 @@ namespace ts { * Adds the value to an array of values associated with the key, and returns the array. * Creates the array if it does not already exist. */ - export function multiMapAdd(map: Map, key: string, value: V): V[] { + export function multiMapAdd(map: Map, key: string | number, value: V): V[] { const values = map[key]; if (values) { values.push(value); @@ -829,6 +975,14 @@ namespace ts { return Array.isArray ? Array.isArray(value) : value instanceof Array; } + /** Does nothing. */ + export function noop(): void {} + + /** Throws an error because a function is not implemented. */ + export function notImplemented(): never { + throw new Error("Not implemented"); + } + export function memoize(callback: () => T): () => T { let value: T; return () => { @@ -869,7 +1023,7 @@ namespace ts { return t => compose(a(t)); } else { - return t => u => u; + return _ => u => u; } } @@ -906,10 +1060,10 @@ namespace ts { } } - function formatStringFromArgs(text: string, args: { [index: number]: any; }, baseIndex?: number): string { + function formatStringFromArgs(text: string, args: { [index: number]: string; }, baseIndex?: number): string { baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, (match, index?) => args[+index + baseIndex]); + return text.replace(/{(\d+)}/g, (_match, index?) => args[+index + baseIndex]); } export let localizedDiagnosticMessages: Map = undefined; @@ -918,7 +1072,7 @@ namespace ts { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } - export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; + export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic { const end = start + length; @@ -926,8 +1080,8 @@ namespace ts { Debug.assert(length >= 0, "length must be non-negative, is " + length); if (file) { - Debug.assert(start <= file.text.length, `start must be within the bounds of the file. ${ start } > ${ file.text.length }`); - Debug.assert(end <= file.text.length, `end must be the bounds of the file. ${ end } > ${ file.text.length }`); + Debug.assert(start <= file.text.length, `start must be within the bounds of the file. ${start} > ${file.text.length}`); + Debug.assert(end <= file.text.length, `end must be the bounds of the file. ${end} > ${file.text.length}`); } let text = getLocaleSpecificMessage(message); @@ -948,7 +1102,7 @@ namespace ts { } /* internal */ - export function formatMessage(dummy: any, message: DiagnosticMessage): string { + export function formatMessage(_dummy: any, message: DiagnosticMessage): string { let text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -958,7 +1112,7 @@ namespace ts { return text; } - export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; + export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { let text = getLocaleSpecificMessage(message); @@ -977,6 +1131,18 @@ namespace ts { }; } + export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic { + return { + file: undefined, + start: undefined, + length: undefined, + + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText + }; + } + export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain { let text = getLocaleSpecificMessage(message); @@ -1016,7 +1182,8 @@ namespace ts { if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (collator && String.prototype.localeCompare) { + // accent means a ≠ b, a ≠ á, a = A const result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo; } @@ -1177,12 +1344,12 @@ namespace ts { /** * Returns the path except for its basename. Eg: - * + * * /path/to/file.ext -> /path/to */ export function getDirectoryPath(path: Path): Path; export function getDirectoryPath(path: string): string; - export function getDirectoryPath(path: string): any { + export function getDirectoryPath(path: string): string { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); } @@ -1203,7 +1370,15 @@ namespace ts { export function getEmitModuleKind(compilerOptions: CompilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : - getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; + getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS; + } + + export function getEmitModuleResolutionKind(compilerOptions: CompilerOptions) { + let moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; + } + return moduleResolution; } /* @internal */ @@ -1442,6 +1617,10 @@ namespace ts { return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } + export function hasExtension(fileName: string): boolean { + return getBaseFileName(fileName).indexOf(".") >= 0; + } + export function fileExtensionIs(path: string, extension: string): boolean { return path.length > extension.length && endsWith(path, extension); } @@ -1476,7 +1655,7 @@ namespace ts { return undefined; } - const replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; + const replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; const singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; /** @@ -1487,73 +1666,21 @@ namespace ts { let pattern = ""; let hasWrittenSubpattern = false; - spec: for (const spec of specs) { + for (const spec of specs) { if (!spec) { continue; } - let subpattern = ""; - let hasRecursiveDirectoryWildcard = false; - let hasWrittenComponent = false; - const 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]); - - let optionalCount = 0; - for (let component of components) { - if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - continue spec; - } - - subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; - hasWrittenComponent = true; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - - if (hasWrittenComponent) { - subpattern += directorySeparator; - } - - if (usage !== "exclude") { - // The * and ? wildcards should not match directories or files that start with . if they - // appear first in a component. Dotted directories and files can be included explicitly - // like so: **/.*/.* - if (component.charCodeAt(0) === CharacterCodes.asterisk) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === CharacterCodes.question) { - subpattern += "[^./]"; - component = component.substr(1); - } - } - - subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); - hasWrittenComponent = true; - } - } - - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; + const subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter); + if (subPattern === undefined) { + continue; } if (hasWrittenSubpattern) { pattern += "|"; } - pattern += "(" + subpattern + ")"; + pattern += "(" + subPattern + ")"; hasWrittenSubpattern = true; } @@ -1561,7 +1688,83 @@ namespace ts { return undefined; } - return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + const terminator = usage === "exclude" ? "($|/)" : "$"; + return `^(${pattern})${terminator}`; + } + + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + export function isImplicitGlob(lastPathComponent: string): boolean { + return !/[.*?]/.test(lastPathComponent); + } + + function getSubPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude", singleAsteriskRegexFragment: string, doubleAsteriskRegexFragment: string, replaceWildcardCharacter: (match: string) => string): string | undefined { + let subpattern = ""; + let hasRecursiveDirectoryWildcard = false; + let hasWrittenComponent = false; + const components = getNormalizedPathComponents(spec, basePath); + const lastComponent = lastOrUndefined(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + + let optionalCount = 0; + for (let component of components) { + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + return undefined; + } + + subpattern += doubleAsteriskRegexFragment; + hasRecursiveDirectoryWildcard = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + + if (hasWrittenComponent) { + subpattern += directorySeparator; + } + + if (usage !== "exclude") { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === CharacterCodes.asterisk) { + subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === CharacterCodes.question) { + subpattern += "[^./]"; + component = component.substr(1); + } + } + + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + + hasWrittenComponent = true; + } + + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + + return subpattern; } function replaceWildCardCharacterFiles(match: string) { @@ -1588,7 +1791,7 @@ namespace ts { basePaths: string[]; } - export function getFileMatcherPatterns(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns { + export function getFileMatcherPatterns(path: string, excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -1605,7 +1808,7 @@ namespace ts { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); const regexFlag = useCaseSensitiveFileNames ? "" : "i"; const includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); @@ -1648,6 +1851,7 @@ namespace ts { function getBasePaths(path: string, includes: string[], useCaseSensitiveFileNames: boolean) { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). const basePaths: string[] = [path]; + if (includes) { // Storage for literal base paths amongst the include patterns. const includeBasePaths: string[] = []; @@ -1655,14 +1859,8 @@ namespace ts { // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") const absolute: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - - const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - const includeBasePath = wildcardOffset < 0 - ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) - : absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset)); - // Append the literal and canonical candidate base paths. - includeBasePaths.push(includeBasePath); + includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. @@ -1670,21 +1868,27 @@ namespace ts { // Iterate over each include base path and include unique base paths that are not a // subpath of an existing base path - include: for (let i = 0; i < includeBasePaths.length; i++) { - const includeBasePath = includeBasePaths[i]; - for (let j = 0; j < basePaths.length; j++) { - if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { - continue include; - } + for (const includeBasePath of includeBasePaths) { + if (ts.every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + basePaths.push(includeBasePath); } - - basePaths.push(includeBasePath); } } return basePaths; } + function getIncludeBasePath(absolute: string): string { + const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset)); + } + export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -1718,10 +1922,20 @@ namespace ts { /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ export const supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; export const supportedJavascriptExtensions = [".js", ".jsx"]; - const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions); + const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions); - export function getSupportedExtensions(options?: CompilerOptions): string[] { - return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions; + export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] { + const needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions; + } + const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0); + for (const extInfo of extraFileExtensions) { + if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) { + extensions.push(extInfo.extension); + } + } + return extensions; } export function hasJavaScriptFileExtension(fileName: string) { @@ -1732,10 +1946,10 @@ namespace ts { return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension)); } - export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) { + export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) { if (!fileName) { return false; } - for (const extension of getSupportedExtensions(compilerOptions)) { + for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -1815,10 +2029,6 @@ namespace ts { return path.substring(0, path.length - extension.length); } - export function isJsxOrTsxExtension(ext: string): boolean { - return ext === ".jsx" || ext === ".tsx"; - } - export function changeExtension(path: T, newExtension: string): T { return (removeFileExtension(path) + newExtension); } @@ -1839,11 +2049,11 @@ namespace ts { this.declarations = undefined; } - function Type(this: Type, checker: TypeChecker, flags: TypeFlags) { + function Type(this: Type, _checker: TypeChecker, flags: TypeFlags) { this.flags = flags; } - function Signature(checker: TypeChecker) { + function Signature() { } function Node(this: Node, kind: SyntaxKind, pos: number, end: number) { @@ -1876,9 +2086,6 @@ namespace ts { } export namespace Debug { - declare var process: any; - declare var require: any; - export let currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { @@ -1902,6 +2109,17 @@ namespace ts { } /** Remove an item from an array, moving everything to its right one space left. */ + export function orderedRemoveItem(array: T[], item: T): boolean { + for (let i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + + /** Remove an item by index from an array, moving everything to its right one space left. */ export function orderedRemoveItemAt(array: T[], index: number): void { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. for (let i = index; i < array.length - 1; i++) { @@ -2014,4 +2232,38 @@ namespace ts { // pos === undefined || pos === null || isNaN(pos) || pos < 0; return !(pos >= 0); } + + /** True if an extension is one of the supported TypeScript extensions. */ + export function extensionIsTypeScript(ext: Extension): boolean { + return ext <= Extension.LastTypeScriptExtension; + } + + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + export function extensionFromPath(path: string): Extension { + const ext = tryGetExtensionFromPath(path); + if (ext !== undefined) { + return ext; + } + Debug.fail(`File ${path} has unknown extension.`); + } + export function tryGetExtensionFromPath(path: string): Extension | undefined { + if (fileExtensionIs(path, ".d.ts")) { + return Extension.Dts; + } + if (fileExtensionIs(path, ".ts")) { + return Extension.Ts; + } + if (fileExtensionIs(path, ".tsx")) { + return Extension.Tsx; + } + if (fileExtensionIs(path, ".js")) { + return Extension.Js; + } + if (fileExtensionIs(path, ".jsx")) { + return Extension.Jsx; + } + } } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 8bcce86c31f..cd98622e080 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -63,7 +63,7 @@ namespace ts { let isCurrentFileExternalModule: boolean; let reportedDeclarationError = false; let errorNameNode: DeclarationName; - const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; + const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; let noDeclare: boolean; @@ -194,6 +194,7 @@ namespace ts { writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -371,7 +372,7 @@ namespace ts { function writeJsDocComments(declaration: Node) { if (declaration) { - const jsDocComments = getJsDocCommentsFromText(declaration, currentText); + const jsDocComments = getJSDocCommentRanges(declaration, currentText); emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange); @@ -413,6 +414,12 @@ namespace ts { return emitIntersectionType(type); case SyntaxKind.ParenthesizedType: return emitParenType(type); + case SyntaxKind.TypeOperator: + return emitTypeOperator(type); + case SyntaxKind.IndexedAccessType: + return emitIndexedAccessType(type); + case SyntaxKind.MappedType: + return emitMappedType(type); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: return emitSignatureDeclarationWithJsDocComments(type); @@ -506,6 +513,45 @@ namespace ts { write(")"); } + function emitTypeOperator(type: TypeOperatorNode) { + write(tokenToString(type.operator)); + write(" "); + emitType(type.type); + } + + function emitIndexedAccessType(node: IndexedAccessTypeNode) { + emitType(node.objectType); + write("["); + emitType(node.indexType); + write("]"); + } + + function emitMappedType(node: MappedTypeNode) { + const prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + writeEntityName(node.typeParameter.name); + write(" in "); + emitType(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emitType(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + enclosingDeclaration = prevEnclosingDeclaration; + } + function emitTypeLiteral(type: TypeLiteralNode) { write("{"); if (type.members.length) { @@ -580,7 +626,7 @@ namespace ts { writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + function getDefaultExportAccessibilityDiagnostic(): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -710,7 +756,7 @@ namespace ts { } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + function getImportEntityNameVisibilityError(): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -888,7 +934,7 @@ namespace ts { writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + function getTypeAliasDeclarationVisibilityError(): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -955,7 +1001,7 @@ namespace ts { } } - function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + function getTypeParameterConstraintVisibilityError(): SymbolAccessibilityDiagnostic { // Type parameter constraints are named by user so we should always be able to name it let diagnosticMessage: DiagnosticMessage; switch (node.parent.kind) { @@ -992,6 +1038,10 @@ namespace ts { diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; + case SyntaxKind.TypeAliasDeclaration: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } @@ -1029,7 +1079,7 @@ namespace ts { resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); } - function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { @@ -1098,7 +1148,10 @@ namespace ts { const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); + const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression)); + if (interfaceExtendsTypes && interfaceExtendsTypes.length) { + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); + } write(" {"); writeLine(); increaseIndent(); @@ -1573,6 +1626,12 @@ namespace ts { Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case SyntaxKind.IndexSignature: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (hasModifier(node.parent, ModifierFlags.Static)) { @@ -1743,7 +1802,7 @@ namespace ts { } return addedBundledEmitReference; - function getDeclFileName(emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) { + function getDeclFileName(emitFileNames: EmitFileNames, _sourceFiles: SourceFile[], isBundledEmit: boolean) { // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path if (isBundledEmit && !addBundledFileReference) { return; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index f0ccc7f33e2..7e8dc1ce209 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -163,7 +163,7 @@ "category": "Error", "code": 1054 }, - "Type '{0}' is not a valid async function return type.": { + "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.": { "category": "Error", "code": 1055 }, @@ -227,7 +227,7 @@ "category": "Error", "code": 1084 }, - "Octal literals are not available when targeting ECMAScript 5 and higher.": { + "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'.": { "category": "Error", "code": 1085 }, @@ -603,10 +603,6 @@ "category": "Error", "code": 1194 }, - "Catch clause variable name must be an identifier.": { - "category": "Error", - "code": 1195 - }, "Catch clause variable cannot have a type annotation.": { "category": "Error", "code": 1196 @@ -855,6 +851,14 @@ "category": "Error", "code": 1317 }, + "An abstract accessor cannot have an implementation.": { + "category": "Error", + "code": 1318 + }, + "A default export can only be used in an ECMAScript-style module.": { + "category": "Error", + "code": 1319 + }, "Duplicate identifier '{0}'.": { "category": "Error", "code": 2300 @@ -1027,6 +1031,10 @@ "category": "Error", "code": 2342 }, + "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'.": { + "category": "Error", + "code": 2343 + }, "Type '{0}' does not satisfy the constraint '{1}'.": { "category": "Error", "code": 2344 @@ -1067,6 +1075,10 @@ "category": "Error", "code": 2353 }, + "This syntax requires an imported helper but module '{0}' cannot be found.": { + "category": "Error", + "code": 2354 + }, "A function whose declared type is neither 'void' nor 'any' must return a value.": { "category": "Error", "code": 2355 @@ -1075,7 +1087,7 @@ "category": "Error", "code": 2356 }, - "The operand of an increment or decrement operator must be a variable, property or indexer.": { + "The operand of an increment or decrement operator must be a variable or a property access.": { "category": "Error", "code": 2357 }, @@ -1103,7 +1115,7 @@ "category": "Error", "code": 2363 }, - "Invalid left-hand side of assignment expression.": { + "The left-hand side of an assignment expression must be a variable or a property access.": { "category": "Error", "code": 2364 }, @@ -1263,7 +1275,7 @@ "category": "Error", "code": 2405 }, - "Invalid left-hand side in 'for...in' statement.": { + "The left-hand side of a 'for...in' statement must be a variable or a property access.": { "category": "Error", "code": 2406 }, @@ -1415,14 +1427,6 @@ "category": "Error", "code": 2448 }, - "The operand of an increment or decrement operator cannot be a constant or a read-only property.": { - "category": "Error", - "code": 2449 - }, - "Left-hand side of assignment expression cannot be a constant or a read-only property.": { - "category": "Error", - "code": 2450 - }, "Cannot redeclare block-scoped variable '{0}'.": { "category": "Error", "code": 2451 @@ -1467,7 +1471,7 @@ "category": "Error", "code": 2461 }, - "A rest element must be last in an array destructuring pattern": { + "A rest element must be last in a destructuring pattern": { "category": "Error", "code": 2462 }, @@ -1555,15 +1559,7 @@ "category": "Error", "code": 2484 }, - "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property.": { - "category": "Error", - "code": 2485 - }, - "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property.": { - "category": "Error", - "code": 2486 - }, - "Invalid left-hand side in 'for...of' statement.": { + "The left-hand side of a 'for...of' statement must be a variable or a property access.": { "category": "Error", "code": 2487 }, @@ -1751,6 +1747,34 @@ "category": "Error", "code": 2535 }, + "Type '{0}' cannot be used to index type '{1}'.": { + "category": "Error", + "code": 2536 + }, + "Type '{0}' has no matching index signature for type '{1}'.": { + "category": "Error", + "code": 2537 + }, + "Type '{0}' cannot be used as an index type.": { + "category": "Error", + "code": 2538 + }, + "Cannot assign to '{0}' because it is not a variable.": { + "category": "Error", + "code": 2539 + }, + "Cannot assign to '{0}' because it is a constant or a read-only property.": { + "category": "Error", + "code": 2540 + }, + "The target of an assignment must be a variable or a property access.": { + "category": "Error", + "code": 2541 + }, + "Index signature in type '{0}' only permits reading.": { + "category": "Error", + "code": 2542 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -1847,6 +1871,10 @@ "category": "Error", "code": 2664 }, + "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented.": { + "category": "Error", + "code": 2665 + }, "Exports and export assignments are not permitted in module augmentations.": { "category": "Error", "code": 2666 @@ -1927,7 +1955,7 @@ "category": "Error", "code": 2685 }, - "Identifier '{0}' must be imported from a module": { + "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead.": { "category": "Error", "code": 2686 }, @@ -1971,6 +1999,26 @@ "category": "Error", "code": 2696 }, + "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.": { + "category": "Error", + "code": 2697 + }, + "Spread types may only be created from object types.": { + "category": "Error", + "code": 2698 + }, + "Rest types may only be created from object types.": { + "category": "Error", + "code": 2700 + }, + "The target of an object rest assignment must be a variable or a property access.": { + "category": "Error", + "code": 2701 + }, + "'{0}' only refers to a type, but is being used as a namespace here.": { + "category": "Error", + "code": 2702 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -2252,10 +2300,22 @@ "category": "Error", "code": 4082 }, + "Type parameter '{0}' of exported type alias has or is using private name '{1}'.": { + "category": "Error", + "code": 4083 + }, "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict.": { "category": "Message", "code": 4090 }, + "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'.": { + "category": "Error", + "code": 4091 + }, + "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'.": { + "category": "Error", + "code": 4092 + }, "The current host does not support the '{0}' option.": { "category": "Error", @@ -2369,6 +2429,10 @@ "category": "Error", "code": 5066 }, + "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name.": { + "category": "Error", + "code": 5067 + }, "Concatenate and emit output to single file.": { "category": "Message", "code": 6001 @@ -2417,7 +2481,7 @@ "category": "Message", "code": 6012 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": { + "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'": { "category": "Message", "code": 6015 }, @@ -2629,6 +2693,10 @@ "category": "Message", "code": 6080 }, + "File '{0}' has an unsupported extension, so skipping it.": { + "category": "Message", + "code": 6081 + }, "Only 'amd' and 'system' modules are supported alongside --{0}.": { "category": "Error", "code": 6082 @@ -2701,7 +2769,7 @@ "category": "Message", "code": 6099 }, - "'package.json' does not have 'types' field.": { + "'package.json' does not have a 'types' or 'main' field.": { "category": "Message", "code": 6100 }, @@ -2849,7 +2917,7 @@ "category": "Message", "code": 6136 }, - "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'": { + "No types specified in 'package.json', so returning 'main' value of '{0}'": { "category": "Message", "code": 6137 }, @@ -2865,6 +2933,34 @@ "category": "Error", "code": 6140 }, + "Parse in strict mode and emit \"use strict\" for each source file": { + "category": "Message", + "code": 6141 + }, + "Module '{0}' was resolved to '{1}', but '--jsx' is not set.": { + "category": "Error", + "code": 6142 + }, + "Module '{0}' was resolved to '{1}', but '--allowJs' is not set.": { + "category": "Error", + "code": 6143 + }, + "Module '{0}' was resolved as locally declared ambient module in file '{1}'.": { + "category": "Message", + "code": 6144 + }, + "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified.": { + "category": "Message", + "code": 6145 + }, + "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'.": { + "category": "Message", + "code": 6146 + }, + "Resolution for module '{0}' was found in cache": { + "category": "Message", + "code": 6147 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", "code": 7005 @@ -2897,7 +2993,11 @@ "category": "Error", "code": 7015 }, - "Index signature of object type implicitly has an 'any' type.": { + "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type.": { + "category": "Error", + "code": 7016 + }, + "Element implicitly has an 'any' type because type '{0}' has no index signature.": { "category": "Error", "code": 7017 }, @@ -2961,7 +3061,7 @@ "category": "Error", "code": 7033 }, - "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined.": { + "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined.": { "category": "Error", "code": 7034 }, @@ -3033,6 +3133,10 @@ "category": "Error", "code": 9003 }, + "Language service is disabled.": { + "category": "Error", + "code": 9004 + }, "JSX attributes must only be assigned a non-empty 'expression'.": { "category": "Error", "code": 17000 @@ -3073,18 +3177,32 @@ "category": "Error", "code": 17009 }, - "Unknown typing option '{0}'.": { + "Unknown type acquisition option '{0}'.": { "category": "Error", "code": 17010 }, + "'super' must be called before accessing a property of 'super' in the constructor of a derived class.": { + "category": "Error", + "code": 17011 + }, + "Circularity detected while resolving configuration: {0}": { "category": "Error", "code": 18000 }, - "The path in an 'extends' options must be relative or rooted.": { + "A path in an 'extends' option must be relative or rooted, but '{0}' is not.": { "category": "Error", "code": 18001 }, + "The 'files' list in config file '{0}' is empty.": { + "category": "Error", + "code": 18002 + }, + "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'.": { + "category": "Error", + "code": 18003 + }, + "Add missing 'super()' call.": { "category": "Message", "code": 90001 @@ -3112,5 +3230,33 @@ "Implement inherited abstract class": { "category": "Message", "code": 90007 + }, + "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig": { + "category": "Error", + "code": 90009 + }, + "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated.": { + "category": "Error", + "code": 90010 + }, + "Import {0} from {1}": { + "category": "Message", + "code": 90013 + }, + "Change {0} to {1}": { + "category": "Message", + "code": 90014 + }, + "Add {0} to existing import declaration from {1}": { + "category": "Message", + "code": 90015 + }, + "Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": { + "category": "Error", + "code": 8017 + }, + "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'.": { + "category": "Error", + "code": 8018 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index dae75e2516c..0a03ec6863f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -14,180 +14,12 @@ namespace ts { } const id = (s: SourceFile) => s; - const nullTransformers: Transformer[] = [ctx => id]; + const nullTransformers: Transformer[] = [_ => id]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult { const delimiters = createDelimiterMap(); const brackets = createBracketsMap(); - - // emit output for the __extends helper function - const extendsHelper = ` -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -};`; - - // Emit output for the __assign helper function. - // This is typically used for JSX spread attributes, - // and can be used for object literal spread properties. - const assignHelper = ` -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -};`; - - // emit output for the __decorate helper function - const decorateHelper = ` -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -};`; - - // emit output for the __metadata helper function - const metadataHelper = ` -var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); -};`; - - // emit output for the __param helper function - const paramHelper = ` -var __param = (this && this.__param) || function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -};`; - - // emit output for the __awaiter helper function - const awaiterHelper = ` -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); - }); -};`; - - // The __generator helper is used by down-level transformations to emulate the runtime - // semantics of an ES2015 generator function. When called, this helper returns an - // object that implements the Iterator protocol, in that it has `next`, `return`, and - // `throw` methods that step through the generator when invoked. - // - // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. - // - // variables: - // _ Persistent state for the generator that is shared between the helper and the - // generator body. The state object has the following members: - // sent() - A method that returns or throws the current completion value. - // label - The next point at which to resume evaluation of the generator body. - // trys - A stack of protected regions (try/catch/finally blocks). - // ops - A stack of pending instructions when inside of a finally block. - // f A value indicating whether the generator is executing. - // y An iterator to delegate for a yield*. - // t A temporary variable that holds one of the following values (note that these - // cases do not overlap): - // - The completion value when resuming from a `yield` or `yield*`. - // - The error value for a catch block. - // - The current protected region (array of try/catch/finally/end labels). - // - The verb (`next`, `throw`, or `return` method) to delegate to the expression - // of a `yield*`. - // - The result of evaluating the verb delegated to the expression of a `yield*`. - // - // functions: - // verb(n) Creates a bound callback to the `step` function for opcode `n`. - // step(op) Evaluates opcodes in a generator body until execution is suspended or - // completed. - // - // The __generator helper understands a limited set of instructions: - // 0: next(value?) - Start or resume the generator with the specified value. - // 1: throw(error) - Resume the generator with an exception. If the generator is - // suspended inside of one or more protected regions, evaluates - // any intervening finally blocks between the current label and - // the nearest catch block or function boundary. If uncaught, the - // exception is thrown to the caller. - // 2: return(value?) - Resume the generator as if with a return. If the generator is - // suspended inside of one or more protected regions, evaluates any - // intervening finally blocks. - // 3: break(label) - Jump to the specified label. If the label is outside of the - // current protected region, evaluates any intervening finally - // blocks. - // 4: yield(value?) - Yield execution to the caller with an optional value. When - // resumed, the generator will continue at the next label. - // 5: yield*(value) - Delegates evaluation to the supplied iterator. When - // delegation completes, the generator will continue at the next - // label. - // 6: catch(error) - Handles an exception thrown from within the generator body. If - // the current label is inside of one or more protected regions, - // evaluates any intervening finally blocks between the current - // label and the nearest catch block or function boundary. If - // uncaught, the exception is thrown to the caller. - // 7: endfinally - Ends a finally block, resuming the last instruction prior to - // entering a finally block. - // - // For examples of how these are used, see the comments in ./transformers/generators.ts - const generatorHelper = ` -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t; - return { next: verb(0), "throw": verb(1), "return": verb(2) }; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -};`; - - // emit output for the __export helper function - const exportStarHelper = ` -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -}`; - - // emit output for the UMD helper function. - const umdHelper = ` -(function (dependencies, factory) { - if (typeof module === 'object' && typeof module.exports === 'object') { - var v = factory(require, exports); if (v !== undefined) module.exports = v; - } - else if (typeof define === 'function' && define.amd) { - define(dependencies, factory); - } -})`; - - const superHelper = ` -const _super = name => super[name];`; - - const advancedSuperHelper = ` -const _super = (function (geti, seti) { - const cache = Object.create(null); - return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); -})(name => super[name], (name, value) => super[name] = value);`; - const compilerOptions = host.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); const moduleKind = getEmitModuleKind(compilerOptions); @@ -224,11 +56,7 @@ const _super = (function (geti, seti) { let currentSourceFile: SourceFile; let currentText: string; let currentFileIdentifiers: Map; - let extendsEmitted: boolean; - let assignEmitted: boolean; - let decorateEmitted: boolean; - let paramEmitted: boolean; - let awaiterEmitted: boolean; + let bundledHelpers: Map; let isOwnFileEmit: boolean; let emitSkipped = false; @@ -293,12 +121,13 @@ const _super = (function (geti, seti) { nodeIdToGeneratedName = []; autoGeneratedIdToGeneratedName = []; generatedNameSet = createMap(); + bundledHelpers = isBundledEmit ? createMap() : undefined; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { for (const sourceFile of sourceFiles) { - emitEmitHelpers(sourceFile); + emitHelpers(sourceFile, /*isBundle*/ true); } } @@ -314,7 +143,7 @@ const _super = (function (geti, seti) { // Write the source map if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Record source map data for the test harness. @@ -323,7 +152,7 @@ const _super = (function (geti, seti) { } // Write the output file - writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); @@ -333,11 +162,6 @@ const _super = (function (geti, seti) { tempFlags = TempFlags.Auto; currentSourceFile = undefined; currentText = undefined; - extendsEmitted = false; - assignEmitted = false; - decorateEmitted = false; - paramEmitted = false; - awaiterEmitted = false; isOwnFileEmit = false; } @@ -504,15 +328,29 @@ const _super = (function (geti, seti) { // Contextual keywords case SyntaxKind.AbstractKeyword: + case SyntaxKind.AsKeyword: case SyntaxKind.AnyKeyword: case SyntaxKind.AsyncKeyword: + case SyntaxKind.AwaitKeyword: case SyntaxKind.BooleanKeyword: + case SyntaxKind.ConstructorKeyword: case SyntaxKind.DeclareKeyword: - case SyntaxKind.NumberKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.IsKeyword: + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: + case SyntaxKind.NeverKeyword: case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.RequireKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.SetKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.SymbolKeyword: + case SyntaxKind.TypeKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.FromKeyword: case SyntaxKind.GlobalKeyword: + case SyntaxKind.OfKeyword: writeTokenText(kind); return; @@ -579,7 +417,13 @@ const _super = (function (geti, seti) { case SyntaxKind.ExpressionWithTypeArguments: return emitExpressionWithTypeArguments(node); case SyntaxKind.ThisType: - return emitThisType(node); + return emitThisType(); + case SyntaxKind.TypeOperator: + return emitTypeOperator(node); + case SyntaxKind.IndexedAccessType: + return emitIndexedAccessType(node); + case SyntaxKind.MappedType: + return emitMappedType(node); case SyntaxKind.LiteralType: return emitLiteralType(node); @@ -595,7 +439,7 @@ const _super = (function (geti, seti) { case SyntaxKind.TemplateSpan: return emitTemplateSpan(node); case SyntaxKind.SemicolonClassElement: - return emitSemicolonClassElement(node); + return emitSemicolonClassElement(); // Statements case SyntaxKind.Block: @@ -603,7 +447,7 @@ const _super = (function (geti, seti) { case SyntaxKind.VariableStatement: return emitVariableStatement(node); case SyntaxKind.EmptyStatement: - return emitEmptyStatement(node); + return emitEmptyStatement(); case SyntaxKind.ExpressionStatement: return emitExpressionStatement(node); case SyntaxKind.IfStatement: @@ -714,6 +558,8 @@ const _super = (function (geti, seti) { return emitPropertyAssignment(node); case SyntaxKind.ShorthandPropertyAssignment: return emitShorthandPropertyAssignment(node); + case SyntaxKind.SpreadAssignment: + return emitSpreadAssignment(node as SpreadAssignment); // Enum case SyntaxKind.EnumMember: @@ -804,8 +650,8 @@ const _super = (function (geti, seti) { return emitTemplateExpression(node); case SyntaxKind.YieldExpression: return emitYieldExpression(node); - case SyntaxKind.SpreadElementExpression: - return emitSpreadElementExpression(node); + case SyntaxKind.SpreadElement: + return emitSpreadExpression(node); case SyntaxKind.ClassExpression: return emitClassExpression(node); case SyntaxKind.OmittedExpression: @@ -824,6 +670,8 @@ const _super = (function (geti, seti) { // Transformation nodes case SyntaxKind.PartiallyEmittedExpression: return emitPartiallyEmittedExpression(node); + case SyntaxKind.RawExpression: + return writeLines((node).text); } } @@ -861,12 +709,7 @@ const _super = (function (geti, seti) { // function emitIdentifier(node: Identifier) { - if (getEmitFlags(node) & EmitFlags.UMDDefine) { - writeLines(umdHelper); - } - else { - write(getTextOfNode(node, /*includeTrivia*/ false)); - } + write(getTextOfNode(node, /*includeTrivia*/ false)); } // @@ -1000,7 +843,7 @@ const _super = (function (geti, seti) { write(";"); } - function emitSemicolonClassElement(node: SemicolonClassElement) { + function emitSemicolonClassElement() { write(";"); } @@ -1070,10 +913,46 @@ const _super = (function (geti, seti) { write(")"); } - function emitThisType(node: ThisTypeNode) { + function emitThisType() { write("this"); } + function emitTypeOperator(node: TypeOperatorNode) { + writeTokenText(node.operator); + write(" "); + emit(node.type); + } + + function emitIndexedAccessType(node: IndexedAccessTypeNode) { + emit(node.objectType); + write("["); + emit(node.indexType); + write("]"); + } + + function emitMappedType(node: MappedTypeNode) { + write("{"); + writeLine(); + increaseIndent(); + if (node.readonlyToken) { + write("readonly "); + } + write("["); + emit(node.typeParameter.name); + write(" in "); + emit(node.typeParameter.constraint); + write("]"); + if (node.questionToken) { + write("?"); + } + write(": "); + emit(node.type); + write(";"); + writeLine(); + decreaseIndent(); + write("}"); + } + function emitLiteralType(node: LiteralTypeNode) { emitExpression(node.literal); } @@ -1198,12 +1077,14 @@ const _super = (function (geti, seti) { function emitCallExpression(node: CallExpression) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments); } function emitNewExpression(node: NewExpression) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments); } @@ -1341,7 +1222,7 @@ const _super = (function (geti, seti) { emitExpressionWithPrefix(" ", node.expression); } - function emitSpreadElementExpression(node: SpreadElementExpression) { + function emitSpreadExpression(node: SpreadElement) { write("..."); emitExpression(node.expression); } @@ -1381,7 +1262,7 @@ const _super = (function (geti, seti) { // Statements // - function emitBlock(node: Block, format?: ListFormat) { + function emitBlock(node: Block) { if (isSingleLineEmptyBlock(node)) { writeToken(SyntaxKind.OpenBraceToken, node.pos, /*contextNode*/ node); write(" "); @@ -1409,7 +1290,7 @@ const _super = (function (geti, seti) { write(";"); } - function emitEmptyStatement(node: EmptyStatement) { + function emitEmptyStatement() { write(";"); } @@ -1424,28 +1305,28 @@ const _super = (function (geti, seti) { writeToken(SyntaxKind.OpenParenToken, openParenPos, node); emitExpression(node.expression); writeToken(SyntaxKind.CloseParenToken, node.expression.end, node); - emitEmbeddedStatement(node.thenStatement); + emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { - writeLine(); + writeLineOrSpace(node); writeToken(SyntaxKind.ElseKeyword, node.thenStatement.end, node); if (node.elseStatement.kind === SyntaxKind.IfStatement) { write(" "); emit(node.elseStatement); } else { - emitEmbeddedStatement(node.elseStatement); + emitEmbeddedStatement(node, node.elseStatement); } } } function emitDoStatement(node: DoStatement) { write("do"); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); if (isBlock(node.statement)) { write(" "); } else { - writeLine(); + writeLineOrSpace(node); } write("while ("); @@ -1457,7 +1338,7 @@ const _super = (function (geti, seti) { write("while ("); emitExpression(node.expression); write(")"); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); } function emitForStatement(node: ForStatement) { @@ -1470,7 +1351,7 @@ const _super = (function (geti, seti) { write(";"); emitExpressionWithPrefix(" ", node.incrementor); write(")"); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node: ForInStatement) { @@ -1481,7 +1362,7 @@ const _super = (function (geti, seti) { write(" in "); emitExpression(node.expression); writeToken(SyntaxKind.CloseParenToken, node.expression.end); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node: ForOfStatement) { @@ -1492,7 +1373,7 @@ const _super = (function (geti, seti) { write(" of "); emitExpression(node.expression); writeToken(SyntaxKind.CloseParenToken, node.expression.end); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); } function emitForBinding(node: VariableDeclarationList | Expression) { @@ -1528,7 +1409,7 @@ const _super = (function (geti, seti) { write("with ("); emitExpression(node.expression); write(")"); - emitEmbeddedStatement(node.statement); + emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node: SwitchStatement) { @@ -1556,9 +1437,12 @@ const _super = (function (geti, seti) { function emitTryStatement(node: TryStatement) { write("try "); emit(node.tryBlock); - emit(node.catchClause); + if (node.catchClause) { + writeLineOrSpace(node); + emit(node.catchClause); + } if (node.finallyBlock) { - writeLine(); + writeLineOrSpace(node); write("finally "); emit(node.finallyBlock); } @@ -1575,6 +1459,7 @@ const _super = (function (geti, seti) { function emitVariableDeclaration(node: VariableDeclaration) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -1606,13 +1491,13 @@ const _super = (function (geti, seti) { if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) { emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); } else { const savedTempFlags = tempFlags; tempFlags = 0; emitSignatureHead(node); - emitBlockFunctionBody(node, body); + emitBlockFunctionBody(body); tempFlags = savedTempFlags; } @@ -1639,7 +1524,7 @@ const _super = (function (geti, seti) { emitWithPrefix(": ", node.type); } - function shouldEmitBlockFunctionBodyOnSingleLine(parentNode: Node, body: Block) { + function shouldEmitBlockFunctionBodyOnSingleLine(body: Block) { // We must emit a function body as a single-line body in the following case: // * The body has NodeEmitFlags.SingleLine specified. @@ -1677,12 +1562,12 @@ const _super = (function (geti, seti) { return true; } - function emitBlockFunctionBody(parentNode: Node, body: Block) { + function emitBlockFunctionBody(body: Block) { write(" {"); increaseIndent(); emitBodyWithDetachedComments(body, body.statements, - shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker); @@ -2071,6 +1956,13 @@ const _super = (function (geti, seti) { } } + function emitSpreadAssignment(node: SpreadAssignment) { + if (node.expression) { + write("..."); + emitExpression(node.expression); + } + } + // // Enum // @@ -2127,82 +2019,39 @@ const _super = (function (geti, seti) { return statements.length; } - function emitHelpers(node: Node) { - const emitFlags = getEmitFlags(node); - let helpersEmitted = false; - if (emitFlags & EmitFlags.EmitEmitHelpers) { - helpersEmitted = emitEmitHelpers(currentSourceFile); - } - - if (emitFlags & EmitFlags.EmitExportStar) { - writeLines(exportStarHelper); - helpersEmitted = true; - } - - if (emitFlags & EmitFlags.EmitSuperHelper) { - writeLines(superHelper); - helpersEmitted = true; - } - - if (emitFlags & EmitFlags.EmitAdvancedSuperHelper) { - writeLines(advancedSuperHelper); - helpersEmitted = true; - } - - return helpersEmitted; - } - - function emitEmitHelpers(node: SourceFile) { - // Only emit helpers if the user did not say otherwise. - if (compilerOptions.noEmitHelpers) { - return false; - } - - // Don't emit helpers if we can import them. - if (compilerOptions.importHelpers - && (isExternalModule(node) || compilerOptions.isolatedModules)) { - return false; - } + function emitHelpers(node: Node, isBundle?: boolean) { + const sourceFile = isSourceFile(node) ? node : currentSourceFile; + const shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined); + const shouldBundle = isSourceFile(node) && !isOwnFileEmit; let helpersEmitted = false; + const helpers = getEmitHelpers(node); + if (helpers) { + for (const helper of stableSort(helpers, compareEmitHelpers)) { + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) continue; - // Only Emit __extends function when target ES5. - // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) { - writeLines(extendsHelper); - extendsEmitted = true; - helpersEmitted = true; - } + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers[helper.name]) { + continue; + } - if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttributes)) { - writeLines(assignHelper); - assignEmitted = true; - } + bundledHelpers[helper.name] = true; + } + } + else if (isBundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } - if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); + writeLines(helper.text); + helpersEmitted = true; } - - decorateEmitted = true; - helpersEmitted = true; - } - - if (!paramEmitted && node.flags & NodeFlags.HasParamDecorators) { - writeLines(paramHelper); - paramEmitted = true; - helpersEmitted = true; - } - - if (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions) { - writeLines(awaiterHelper); - if (languageVersion < ScriptTarget.ES6) { - writeLines(generatorHelper); - } - - awaiterEmitted = true; - helpersEmitted = true; } if (helpersEmitted) { @@ -2213,9 +2062,10 @@ const _super = (function (geti, seti) { } function writeLines(text: string): void { - const lines = text.split(/\r\n|\r|\n/g); + const lines = text.split(/\r\n?|\n/g); + const indentation = guessIndentation(lines); for (let i = 0; i < lines.length; i++) { - const line = lines[i]; + const line = indentation ? lines[i].slice(indentation) : lines[i]; if (line.length) { if (i > 0) { writeLine(); @@ -2225,6 +2075,21 @@ const _super = (function (geti, seti) { } } + function guessIndentation(lines: string[]) { + let indentation: number; + for (const line of lines) { + for (let i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { + if (!isWhiteSpace(line.charCodeAt(i))) { + if (indentation === undefined || i < indentation) { + indentation = i; + break; + } + } + } + } + return indentation; + } + // // Helpers // @@ -2266,8 +2131,8 @@ const _super = (function (geti, seti) { } } - function emitEmbeddedStatement(node: Statement) { - if (isBlock(node)) { + function emitEmbeddedStatement(parent: Node, node: Statement) { + if (isBlock(node) || getEmitFlags(parent) & EmitFlags.SingleLine) { write(" "); emit(node); } @@ -2432,6 +2297,15 @@ const _super = (function (geti, seti) { } } + function writeLineOrSpace(node: Node) { + if (getEmitFlags(node) & EmitFlags.SingleLine) { + write(" "); + } + else { + writeLine(); + } + } + function writeIfAny(nodes: NodeArray, text: string) { if (nodes && nodes.length > 0) { write(text); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index d050739470f..c2535cacbe5 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -102,19 +102,19 @@ namespace ts { // Literals - export function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral; + export function createLiteral(textSource: StringLiteral | NumericLiteral | Identifier, location?: TextRange): StringLiteral; export function createLiteral(value: string, location?: TextRange): StringLiteral; export function createLiteral(value: number, location?: TextRange): NumericLiteral; export function createLiteral(value: boolean, location?: TextRange): BooleanLiteral; export function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression; - export function createLiteral(value: string | number | boolean | StringLiteral | Identifier, location?: TextRange): PrimaryExpression { + export function createLiteral(value: string | number | boolean | StringLiteral | NumericLiteral | Identifier, location?: TextRange): PrimaryExpression { if (typeof value === "number") { - const node = createNode(SyntaxKind.NumericLiteral, location, /*flags*/ undefined); + const node = createNode(SyntaxKind.NumericLiteral, location, /*flags*/ undefined); node.text = value.toString(); return node; } else if (typeof value === "boolean") { - return createNode(value ? SyntaxKind.TrueKeyword : SyntaxKind.FalseKeyword, location, /*flags*/ undefined); + return createNode(value ? SyntaxKind.TrueKeyword : SyntaxKind.FalseKeyword, location, /*flags*/ undefined); } else if (typeof value === "string") { const node = createNode(SyntaxKind.StringLiteral, location, /*flags*/ undefined); @@ -226,20 +226,7 @@ namespace ts { // Signature elements - export function createParameter(name: string | Identifier | BindingPattern, initializer?: Expression, location?: TextRange) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - name, - /*questionToken*/ undefined, - /*type*/ undefined, - initializer, - location - ); - } - - export function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags) { + export function createParameter(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression, location?: TextRange, flags?: NodeFlags) { const node = createNode(SyntaxKind.Parameter, location, flags); node.decorators = decorators ? createNodeArray(decorators) : undefined; node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; @@ -251,9 +238,9 @@ namespace ts { return node; } - export function updateParameterDeclaration(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression) { - if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) { - return updateNode(createParameterDeclaration(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); + export function updateParameter(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: BindingName, type: TypeNode, initializer: Expression) { + if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) { + return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node); } return node; @@ -391,9 +378,9 @@ namespace ts { return node; } - export function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression) { - if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) { - return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node); + export function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken, propertyName: PropertyName, name: BindingName, initializer: Expression) { + if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) { + return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node); } return node; } @@ -525,9 +512,9 @@ namespace ts { return node; } - export function createFunctionExpression(asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) { + export function createFunctionExpression(modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) { const node = createNode(SyntaxKind.FunctionExpression, location, flags); - node.modifiers = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -537,9 +524,9 @@ namespace ts { return node; } - export function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + export function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); } return node; } @@ -659,13 +646,25 @@ namespace ts { return node; } - export function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange) { - const node = createNode(SyntaxKind.ConditionalExpression, location); - node.condition = condition; - node.questionToken = questionToken; - node.whenTrue = whenTrue; - node.colonToken = colonToken; - node.whenFalse = whenFalse; + export function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression, location?: TextRange): ConditionalExpression; + export function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange): ConditionalExpression; + export function createConditional(condition: Expression, questionTokenOrWhenTrue: QuestionToken | Expression, whenTrueOrWhenFalse: Expression, colonTokenOrLocation?: ColonToken | TextRange, whenFalse?: Expression, location?: TextRange) { + const node = createNode(SyntaxKind.ConditionalExpression, whenFalse ? location : colonTokenOrLocation); + node.condition = parenthesizeForConditionalHead(condition); + if (whenFalse) { + // second overload + node.questionToken = questionTokenOrWhenTrue; + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + node.colonToken = colonTokenOrLocation; + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse); + } + else { + // first overload + node.questionToken = createToken(SyntaxKind.QuestionToken); + node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue); + node.colonToken = createToken(SyntaxKind.ColonToken); + node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse); + } return node; } @@ -705,12 +704,12 @@ namespace ts { } export function createSpread(expression: Expression, location?: TextRange) { - const node = createNode(SyntaxKind.SpreadElementExpression, location); + const node = createNode(SyntaxKind.SpreadElement, location); node.expression = parenthesizeExpressionForList(expression); return node; } - export function updateSpread(node: SpreadElementExpression, expression: Expression) { + export function updateSpread(node: SpreadElement, expression: Expression) { if (node.expression !== expression) { return updateNode(createSpread(expression, node), node); } @@ -1413,6 +1412,12 @@ namespace ts { return node; } + export function createSpreadAssignment(expression: Expression, location?: TextRange) { + const node = createNode(SyntaxKind.SpreadAssignment, location); + node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined; + return node; + } + export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression) { if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) { return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node); @@ -1420,6 +1425,13 @@ namespace ts { return node; } + export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) { + if (node.expression !== expression) { + return updateNode(createSpreadAssignment(expression, node), node); + } + return node; + } + // Top-level nodes export function updateSourceFileNode(node: SourceFile, statements: Statement[]) { @@ -1454,7 +1466,6 @@ namespace ts { if (node.resolvedTypeReferenceDirectiveNames !== undefined) updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames; if (node.imports !== undefined) updated.imports = node.imports; if (node.moduleAugmentations !== undefined) updated.moduleAugmentations = node.moduleAugmentations; - if (node.externalHelpersModuleName !== undefined) updated.externalHelpersModuleName = node.externalHelpersModuleName; return updateNode(updated, node); } @@ -1475,6 +1486,28 @@ namespace ts { return node; } + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + export function createEndOfDeclarationMarker(original: Node) { + const node = createNode(SyntaxKind.EndOfDeclarationMarker); + node.emitNode = {}; + node.original = original; + return node; + } + + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + export function createMergeDeclarationMarker(original: Node) { + const node = createNode(SyntaxKind.MergeDeclarationMarker); + node.emitNode = {}; + node.original = original; + return node; + } + /** * Creates a synthetic expression to act as a placeholder for a not-emitted expression in * order to preserve comments or sourcemap positions. @@ -1497,6 +1530,19 @@ namespace ts { return node; } + /** + * Creates a node that emits a string of raw text in an expression position. Raw text is never + * transformed, should be ES3 compliant, and should have the same precedence as + * PrimaryExpression. + * + * @param text The raw text of the node. + */ + export function createRawExpression(text: string) { + const node = createNode(SyntaxKind.RawExpression); + node.text = text; + return node; + } + // Compound nodes export function createComma(left: Expression, right: Expression) { @@ -1507,6 +1553,8 @@ namespace ts { return createBinary(left, SyntaxKind.LessThanToken, right, location); } + export function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression, location?: TextRange): DestructuringAssignment; + export function createAssignment(left: Expression, right: Expression, location?: TextRange): BinaryExpression; export function createAssignment(left: Expression, right: Expression, location?: TextRange) { return createBinary(left, SyntaxKind.EqualsToken, right, location); } @@ -1547,6 +1595,14 @@ namespace ts { return createVoid(createLiteral(0)); } + export type TypeOfTag = "undefined" | "number" | "boolean" | "string" | "symbol" | "object" | "function"; + + export function createTypeCheck(value: Expression, tag: TypeOfTag) { + return tag === "undefined" + ? createStrictEquality(value, createVoidZero()) + : createStrictEquality(createTypeOf(value), createLiteral(tag)); + } + export function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression { if (isComputedPropertyName(memberName)) { return createElementAccess(target, memberName.expression, location); @@ -1558,18 +1614,6 @@ namespace ts { } } - export function createRestParameter(name: string | Identifier) { - return createParameterDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - createToken(SyntaxKind.DotDotDotToken), - name, - /*questionToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined - ); - } - export function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: Expression[], location?: TextRange) { return createCall( createPropertyAccess(func, "call"), @@ -1626,11 +1670,34 @@ namespace ts { // flag and setting a parent node. const react = createIdentifier(reactNamespace || "React"); react.flags &= ~NodeFlags.Synthesized; - react.parent = parent; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree + react.parent = getParseTreeNode(parent); return react; } - export function createReactCreateElement(reactNamespace: string, tagName: Expression, props: Expression, children: Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression { + function createJsxFactoryExpressionFromEntityName(jsxFactory: EntityName, parent: JsxOpeningLikeElement): Expression { + if (isQualifiedName(jsxFactory)) { + const left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); + const right = createSynthesizedNode(SyntaxKind.Identifier); + right.text = jsxFactory.right.text; + return createPropertyAccess(left, right); + } + else { + return createReactNamespace(jsxFactory.text, parent); + } + } + + function createJsxFactoryExpression(jsxFactoryEntity: EntityName, reactNamespace: string, parent: JsxOpeningLikeElement): Expression { + return jsxFactoryEntity ? + createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) : + createPropertyAccess( + createReactNamespace(reactNamespace, parent), + "createElement" + ); + } + + export function createExpressionForJsxElement(jsxFactoryEntity: EntityName, reactNamespace: string, tagName: Expression, props: Expression, children: Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression { const argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -1653,16 +1720,25 @@ namespace ts { } return createCall( - createPropertyAccess( - createReactNamespace(reactNamespace, parentElement), - "createElement" - ), + createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), /*typeArguments*/ undefined, argumentsList, location ); } + export function createExportDefault(expression: Expression) { + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); + } + + export function createExternalModuleExport(exportName: Identifier) { + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(exportName)])); + } + + export function createLetStatement(name: Identifier, initializer: Expression, location?: TextRange) { + return createVariableStatement(/*modifiers*/ undefined, createLetDeclarationList([createVariableDeclaration(name, /*type*/ undefined, initializer)]), location); + } + export function createLetDeclarationList(declarations: VariableDeclaration[], location?: TextRange) { return createVariableDeclarationList(declarations, location, NodeFlags.Let); } @@ -1673,280 +1749,11 @@ namespace ts { // Helpers - export function createHelperName(externalHelpersModuleName: Identifier | undefined, name: string) { - return externalHelpersModuleName - ? createPropertyAccess(externalHelpersModuleName, name) - : createIdentifier(name); + export function getHelperName(name: string) { + return setEmitFlags(createIdentifier(name), EmitFlags.HelperName | EmitFlags.AdviseOnEmitNode); } - export function createExtendsHelper(externalHelpersModuleName: Identifier | undefined, name: Identifier) { - return createCall( - createHelperName(externalHelpersModuleName, "__extends"), - /*typeArguments*/ undefined, - [ - name, - createIdentifier("_super") - ] - ); - } - - export function createAssignHelper(externalHelpersModuleName: Identifier | undefined, attributesSegments: Expression[]) { - return createCall( - createHelperName(externalHelpersModuleName, "__assign"), - /*typeArguments*/ undefined, - attributesSegments - ); - } - - export function createParamHelper(externalHelpersModuleName: Identifier | undefined, expression: Expression, parameterOffset: number, location?: TextRange) { - return createCall( - createHelperName(externalHelpersModuleName, "__param"), - /*typeArguments*/ undefined, - [ - createLiteral(parameterOffset), - expression - ], - location - ); - } - - export function createMetadataHelper(externalHelpersModuleName: Identifier | undefined, metadataKey: string, metadataValue: Expression) { - return createCall( - createHelperName(externalHelpersModuleName, "__metadata"), - /*typeArguments*/ undefined, - [ - createLiteral(metadataKey), - metadataValue - ] - ); - } - - export function createDecorateHelper(externalHelpersModuleName: Identifier | undefined, decoratorExpressions: Expression[], target: Expression, memberName?: Expression, descriptor?: Expression, location?: TextRange) { - const argumentsArray: Expression[] = []; - argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); - argumentsArray.push(target); - if (memberName) { - argumentsArray.push(memberName); - if (descriptor) { - argumentsArray.push(descriptor); - } - } - - return createCall(createHelperName(externalHelpersModuleName, "__decorate"), /*typeArguments*/ undefined, argumentsArray, location); - } - - export function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) { - const generatorFunc = createFunctionExpression( - createToken(SyntaxKind.AsteriskToken), - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, - body - ); - - // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= EmitFlags.AsyncFunctionBody; - - return createCall( - createHelperName(externalHelpersModuleName, "__awaiter"), - /*typeArguments*/ undefined, - [ - createThis(), - hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), - generatorFunc - ] - ); - } - - export function createHasOwnProperty(target: LeftHandSideExpression, propertyName: Expression) { - return createCall( - createPropertyAccess(target, "hasOwnProperty"), - /*typeArguments*/ undefined, - [propertyName] - ); - } - - function createObjectCreate(prototype: Expression) { - return createCall( - createPropertyAccess(createIdentifier("Object"), "create"), - /*typeArguments*/ undefined, - [prototype] - ); - } - - function createGeti(target: LeftHandSideExpression) { - // name => super[name] - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, - [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, - createElementAccess( - target, - createIdentifier("name") - ) - ); - } - - function createSeti(target: LeftHandSideExpression) { - // (name, value) => super[name] = value - return createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, - [ - createParameter("name"), - createParameter("value") - ], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, - createAssignment( - createElementAccess( - target, - createIdentifier("name") - ), - createIdentifier("value") - ) - ); - } - - export function createAdvancedAsyncSuperHelper() { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - - // const cache = Object.create(null); - const createCache = createVariableStatement( - /*modifiers*/ undefined, - createConstDeclarationList([ - createVariableDeclaration( - "cache", - /*type*/ undefined, - createObjectCreate(createNull()) - ) - ]) - ); - - // get value() { return geti(name); } - const getter = createGetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, - "value", - /*parameters*/ [], - /*type*/ undefined, - createBlock([ - createReturn( - createCall( - createIdentifier("geti"), - /*typeArguments*/ undefined, - [createIdentifier("name")] - ) - ) - ]) - ); - - // set value(v) { seti(name, v); } - const setter = createSetAccessor( - /*decorators*/ undefined, - /*modifiers*/ undefined, - "value", - [createParameter("v")], - createBlock([ - createStatement( - createCall( - createIdentifier("seti"), - /*typeArguments*/ undefined, - [ - createIdentifier("name"), - createIdentifier("v") - ] - ) - ) - ]) - ); - - // return name => cache[name] || ... - const getOrCreateAccessorsForName = createReturn( - createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, - [createParameter("name")], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, - createLogicalOr( - createElementAccess( - createIdentifier("cache"), - createIdentifier("name") - ), - createParen( - createAssignment( - createElementAccess( - createIdentifier("cache"), - createIdentifier("name") - ), - createObjectLiteral([ - getter, - setter - ]) - ) - ) - ) - ) - ); - - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - return createVariableStatement( - /*modifiers*/ undefined, - createConstDeclarationList([ - createVariableDeclaration( - "_super", - /*type*/ undefined, - createCall( - createParen( - createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - [ - createParameter("geti"), - createParameter("seti") - ], - /*type*/ undefined, - createBlock([ - createCache, - getOrCreateAccessorsForName - ]) - ) - ), - /*typeArguments*/ undefined, - [ - createGeti(createSuper()), - createSeti(createSuper()) - ] - ) - ) - ]) - ); - } - - export function createSimpleAsyncSuperHelper() { - return createVariableStatement( - /*modifiers*/ undefined, - createConstDeclarationList([ - createVariableDeclaration( - "_super", - /*type*/ undefined, - createGeti(createSuper()) - ) - ]) - ); - } + // Utilities export interface CallBinding { target: LeftHandSideExpression; @@ -1985,7 +1792,7 @@ namespace ts { } else if (callee.kind === SyntaxKind.SuperKeyword) { thisArg = createThis(); - target = languageVersion < ScriptTarget.ES6 ? createIdentifier("_super", /*location*/ callee) : callee; + target = languageVersion < ScriptTarget.ES2015 ? createIdentifier("_super", /*location*/ callee) : callee; } else { switch (callee.kind) { @@ -2091,6 +1898,7 @@ namespace ts { const properties: ObjectLiteralElementLike[] = []; if (getAccessor) { const getterFunction = createFunctionExpression( + getAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2106,6 +1914,7 @@ namespace ts { if (setAccessor) { const setterFunction = createFunctionExpression( + setAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2172,6 +1981,7 @@ namespace ts { createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode( createFunctionExpression( + method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2189,7 +1999,110 @@ namespace ts { ); } - // Utilities + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean) { + return getName(node, allowComments, allowSourceMaps, EmitFlags.LocalName); + } + + /** + * Gets whether an identifier should only be referred to by its local name. + */ + export function isLocalName(node: Identifier) { + return (getEmitFlags(node) & EmitFlags.LocalName) !== 0; + } + + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier { + return getName(node, allowComments, allowSourceMaps, EmitFlags.ExportName); + } + + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ + export function isExportName(node: Identifier) { + return (getEmitFlags(node) & EmitFlags.ExportName) !== 0; + } + + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getDeclarationName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean) { + return getName(node, allowComments, allowSourceMaps); + } + + function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { + if (node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name)) { + const name = getMutableClone(node.name); + emitFlags |= getEmitFlags(node.name); + if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; + if (!allowComments) emitFlags |= EmitFlags.NoComments; + if (emitFlags) setEmitFlags(name, emitFlags); + return name; + } + return getGeneratedNameForNode(node); + } + + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression { + if (ns && hasModifier(node, ModifierFlags.Export)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression { + const qualifiedName = createPropertyAccess(ns, nodeIsSynthesized(name) ? name : getSynthesizedClone(name), /*location*/ name); + let emitFlags: EmitFlags; + if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; + if (!allowComments) emitFlags |= EmitFlags.NoComments; + if (emitFlags) setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + + export function convertToFunctionBody(node: ConciseBody, multiLine?: boolean) { + return isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node, multiLine); + } function isUseStrictPrologue(node: ExpressionStatement): boolean { return (node.expression as StringLiteral).text === "use strict"; @@ -2207,7 +2120,7 @@ namespace ts { * @param visitor: Optional callback used to visit any custom prologue directives. */ export function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number { - Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); let foundUseStrict = false; let statementOffset = 0; const numStatements = source.length; @@ -2220,22 +2133,62 @@ namespace ts { target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (getEmitFlags(statement) & EmitFlags.CustomPrologue) { - target.push(visitor ? visitNode(statement, visitor, isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + const statement = source[statementOffset]; + if (getEmitFlags(statement) & EmitFlags.CustomPrologue) { + target.push(visitor ? visitNode(statement, visitor, isStatement) : statement); + } + else { + break; } statementOffset++; } return statementOffset; } + export function startsWithUseStrict(statements: Statement[]) { + const firstStatement = firstOrUndefined(statements); + return firstStatement !== undefined + && isPrologueDirective(firstStatement) + && isUseStrictPrologue(firstStatement); + } + + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ + export function ensureUseStrict(statements: NodeArray): NodeArray { + let foundUseStrict = false; + for (const statement of statements) { + if (isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement as ExpressionStatement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + + if (!foundUseStrict) { + return createNodeArray([ + startOnNewLine(createStatement(createLiteral("use strict"))), + ...statements + ], statements); + } + + return statements; + } + /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -2413,6 +2366,25 @@ namespace ts { return SyntaxKind.Unknown; } + export function parenthesizeForConditionalHead(condition: Expression) { + const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken); + const emittedCondition = skipPartiallyEmittedExpressions(condition); + const conditionPrecedence = getExpressionPrecedence(emittedCondition); + if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) { + return createParen(condition); + } + return condition; + } + + function parenthesizeSubexpressionOfConditionalExpression(e: Expression): Expression { + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + return e.kind === SyntaxKind.BinaryExpression && (e).operatorToken.kind === SyntaxKind.CommaToken + ? createParen(e) + : e; + } + /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a NewExpression node. @@ -2652,12 +2624,21 @@ namespace ts { } function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode) { - const { flags, commentRange, sourceMapRange, tokenSourceMapRanges } = sourceEmitNode; - if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) destEmitNode = {}; + const { + flags, + commentRange, + sourceMapRange, + tokenSourceMapRanges, + constantValue, + helpers + } = sourceEmitNode; + if (!destEmitNode) destEmitNode = {}; if (flags) destEmitNode.flags = flags; if (commentRange) destEmitNode.commentRange = commentRange; if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange; if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + if (constantValue !== undefined) destEmitNode.constantValue = constantValue; + if (helpers) destEmitNode.helpers = addRange(destEmitNode.helpers, helpers); return destEmitNode; } @@ -2694,7 +2675,7 @@ namespace ts { * * @param node The node. */ - function getOrCreateEmitNode(node: Node) { + export function getOrCreateEmitNode(node: Node) { if (!node.emitNode) { if (isParseTreeNode(node)) { // To avoid holding onto transformation artifacts, we keep track of any @@ -2735,6 +2716,16 @@ namespace ts { return node; } + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + export function getSourceMapRange(node: Node) { + const emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + /** * Sets a custom text range to use when emitting source maps. * @@ -2746,6 +2737,18 @@ namespace ts { return node; } + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + export function getTokenSourceMapRange(node: Node, token: SyntaxKind) { + const emitNode = node.emitNode; + const tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + /** * Sets the TextRange to use for source maps for a token of a node. * @@ -2760,14 +2763,6 @@ namespace ts { return node; } - /** - * Sets a custom text range to use when emitting comments. - */ - export function setCommentRange(node: T, range: TextRange) { - getOrCreateEmitNode(node).commentRange = range; - return node; - } - /** * Gets a custom text range to use when emitting comments. * @@ -2779,25 +2774,11 @@ namespace ts { } /** - * Gets a custom text range to use when emitting source maps. - * - * @param node The node. + * Sets a custom text range to use when emitting comments. */ - export function getSourceMapRange(node: Node) { - const emitNode = node.emitNode; - return (emitNode && emitNode.sourceMapRange) || node; - } - - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - */ - export function getTokenSourceMapRange(node: Node, token: SyntaxKind) { - const emitNode = node.emitNode; - const tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; - return tokenSourceMapRanges && tokenSourceMapRanges[token]; + export function setCommentRange(node: T, range: TextRange) { + getOrCreateEmitNode(node).commentRange = range; + return node; } /** @@ -2817,6 +2798,113 @@ namespace ts { return node; } + export function getExternalHelpersModuleName(node: SourceFile) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; + } + + export function getOrCreateExternalHelpersModuleNameIfNeeded(node: SourceFile, compilerOptions: CompilerOptions) { + if (compilerOptions.importHelpers && (isExternalModule(node) || compilerOptions.isolatedModules)) { + const externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + + const helpers = getEmitHelpers(node); + if (helpers) { + for (const helper of helpers) { + if (!helper.scoped) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(externalHelpersModuleNameText)); + } + } + } + } + } + /** + * Adds an EmitHelper to a node. + */ + export function addEmitHelper(node: T, helper: EmitHelper): T { + const emitNode = getOrCreateEmitNode(node); + emitNode.helpers = append(emitNode.helpers, helper); + return node; + } + + /** + * Adds an EmitHelper to a node. + */ + export function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T { + if (some(helpers)) { + const emitNode = getOrCreateEmitNode(node); + for (const helper of helpers) { + if (!contains(emitNode.helpers, helper)) { + emitNode.helpers = append(emitNode.helpers, helper); + } + } + } + return node; + } + + /** + * Removes an EmitHelper from a node. + */ + export function removeEmitHelper(node: Node, helper: EmitHelper): boolean { + const emitNode = node.emitNode; + if (emitNode) { + const helpers = emitNode.helpers; + if (helpers) { + return orderedRemoveItem(helpers, helper); + } + } + return false; + } + + /** + * Gets the EmitHelpers of a node. + */ + export function getEmitHelpers(node: Node): EmitHelper[] | undefined { + const emitNode = node.emitNode; + return emitNode && emitNode.helpers; + } + + /** + * Moves matching emit helpers from a source node to a target node. + */ + export function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean) { + const sourceEmitNode = source.emitNode; + const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!some(sourceEmitHelpers)) return; + + const targetEmitNode = getOrCreateEmitNode(target); + let helpersRemoved = 0; + for (let i = 0; i < sourceEmitHelpers.length; i++) { + const helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + if (!contains(targetEmitNode.helpers, helper)) { + targetEmitNode.helpers = append(targetEmitNode.helpers, helper); + } + } + else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } + } + + export function compareEmitHelpers(x: EmitHelper, y: EmitHelper) { + if (x === y) return Comparison.EqualTo; + if (x.priority === y.priority) return Comparison.EqualTo; + if (x.priority === undefined) return Comparison.GreaterThan; + if (y.priority === undefined) return Comparison.LessThan; + return compareValues(x.priority, y.priority); + } + export function setTextRange(node: T, location: TextRange): T { if (location) { node.pos = location.pos; @@ -2911,4 +2999,434 @@ namespace ts { function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ + export function getInitializerOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Expression | undefined { + if (isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` + return bindingElement.initializer; + } + + if (isPropertyAssignment(bindingElement)) { + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + return isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) + ? bindingElement.initializer.right + : undefined; + } + + if (isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` + return bindingElement.objectAssignmentInitializer; + } + + if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` + return bindingElement.right; + } + + if (isSpreadExpression(bindingElement)) { + // Recovery consistent with existing emit. + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } + } + + /** + * Gets the name of an BindingOrAssignmentElement. + */ + export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget { + if (isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` + return bindingElement.name; + } + + if (isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case SyntaxKind.PropertyAssignment: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + + case SyntaxKind.ShorthandPropertyAssignment: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` + return bindingElement.name; + + case SyntaxKind.SpreadAssignment: + // `a` in `({ ...a } = ...)` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + + // no target + return undefined; + } + + if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + + if (isSpreadExpression(bindingElement)) { + // `a` in `[...a] = ...` + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` + return bindingElement; + } + + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ + export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator { + switch (bindingElement.kind) { + case SyntaxKind.Parameter: + case SyntaxKind.BindingElement: + // `...` in `let [...a] = ...` + return (bindingElement).dotDotDotToken; + + case SyntaxKind.SpreadElement: + case SyntaxKind.SpreadAssignment: + // `...` in `[...a] = ...` + return bindingElement; + } + + return undefined; + } + + /** + * Gets the property name of a BindingOrAssignmentElement + */ + export function getPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement) { + switch (bindingElement.kind) { + case SyntaxKind.BindingElement: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` + if ((bindingElement).propertyName) { + const propertyName = (bindingElement).propertyName; + return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + + break; + + case SyntaxKind.PropertyAssignment: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` + if ((bindingElement).name) { + const propertyName = (bindingElement).name; + return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + ? propertyName.expression + : propertyName; + } + + break; + + case SyntaxKind.SpreadAssignment: + // `a` in `({ ...a } = ...)` + return (bindingElement).name; + } + + const target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && isPropertyName(target)) { + return isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) + ? target.expression + : target; + } + + Debug.fail("Invalid property name for binding element."); + } + + /** + * Gets the elements of a BindingOrAssignmentPattern + */ + export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): BindingOrAssignmentElement[] { + switch (name.kind) { + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ArrayLiteralExpression: + // `a` in `{a}` + // `a` in `[a]` + return name.elements; + + case SyntaxKind.ObjectLiteralExpression: + // `a` in `{a}` + return name.properties; + } + } + + export function convertToArrayAssignmentElement(element: BindingOrAssignmentElement) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(createSpread(element.name, element), element); + } + const expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression; + } + Debug.assertNode(element, isExpression); + return element; + } + + export function convertToObjectAssignmentElement(element: BindingOrAssignmentElement) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(createSpreadAssignment(element.name, element), element); + } + if (element.propertyName) { + const expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element); + } + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element); + } + Debug.assertNode(element, isObjectLiteralElementLike); + return element; + } + + export function convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern { + switch (node.kind) { + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ArrayLiteralExpression: + return convertToArrayAssignmentPattern(node); + + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ObjectLiteralExpression: + return convertToObjectAssignmentPattern(node); + } + } + + export function convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern) { + if (isObjectBindingPattern(node)) { + return setOriginalNode(createObjectLiteral(map(node.elements, convertToObjectAssignmentElement), node), node); + } + Debug.assertNode(node, isObjectLiteralExpression); + return node; + } + + export function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern) { + if (isArrayBindingPattern(node)) { + return setOriginalNode(createArrayLiteral(map(node.elements, convertToArrayAssignmentElement), node), node); + } + Debug.assertNode(node, isArrayLiteralExpression); + return node; + } + + export function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression { + if (isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + + Debug.assertNode(node, isExpression); + return node; + } + + export interface ExternalModuleInfo { + externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; // imports of other external modules + externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers + exportSpecifiers: Map; // export specifiers by name + exportedBindings: Map; // exported names of local declarations + exportedNames: Identifier[]; // all exported names local to module + exportEquals: ExportAssignment | undefined; // an export= declaration if one was present + hasExportStarsToExportValues: boolean; // whether this module contains export* + } + + export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo { + const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; + const exportSpecifiers = createMap(); + const exportedBindings = createMap(); + const uniqueExports = createMap(); + let exportedNames: Identifier[]; + let hasExportDefault = false; + let exportEquals: ExportAssignment = undefined; + let hasExportStarsToExportValues = false; + + const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); + const externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), + createLiteral(externalHelpersModuleNameText)); + + if (externalHelpersImportDeclaration) { + externalImports.push(externalHelpersImportDeclaration); + } + + for (const node of sourceFile.statements) { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + break; + + case SyntaxKind.ImportEqualsDeclaration: + if ((node).moduleReference.kind === SyntaxKind.ExternalModuleReference) { + // import x = require("mod") + externalImports.push(node); + } + + break; + + case SyntaxKind.ExportDeclaration: + if ((node).moduleSpecifier) { + if (!(node).exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (const specifier of (node).exportClause.elements) { + if (!uniqueExports[specifier.name.text]) { + const name = specifier.propertyName || specifier.name; + multiMapAdd(exportSpecifiers, name.text, specifier); + + const decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + + if (decl) { + multiMapAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + + uniqueExports[specifier.name.text] = true; + exportedNames = append(exportedNames, specifier.name); + } + } + } + break; + + case SyntaxKind.ExportAssignment: + if ((node).isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + + case SyntaxKind.VariableStatement: + if (hasModifier(node, ModifierFlags.Export)) { + for (const decl of (node).declarationList.declarations) { + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + + case SyntaxKind.FunctionDeclaration: + if (hasModifier(node, ModifierFlags.Export)) { + if (hasModifier(node, ModifierFlags.Default)) { + // export default function() { } + if (!hasExportDefault) { + multiMapAdd(exportedBindings, getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + const name = (node).name; + if (!uniqueExports[name.text]) { + multiMapAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports[name.text] = true; + exportedNames = append(exportedNames, name); + } + } + } + break; + + case SyntaxKind.ClassDeclaration: + if (hasModifier(node, ModifierFlags.Export)) { + if (hasModifier(node, ModifierFlags.Default)) { + // export default class { } + if (!hasExportDefault) { + multiMapAdd(exportedBindings, getOriginalNodeId(node), getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + const name = (node).name; + if (!uniqueExports[name.text]) { + multiMapAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports[name.text] = true; + exportedNames = append(exportedNames, name); + } + } + } + break; + } + } + + return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, externalHelpersImportDeclaration }; + } + + function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map, exportedNames: Identifier[]) { + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!isGeneratedIdentifier(decl.name)) { + if (!uniqueExports[decl.name.text]) { + uniqueExports[decl.name.text] = true; + exportedNames = append(exportedNames, decl.name); + } + } + return exportedNames; + } } diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 4ebdc59e6dd..be8f4d6f0cb 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -5,7 +5,7 @@ namespace ts { /* @internal */ export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; - export function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void { + export function trace(host: ModuleResolutionHost): void { host.trace(formatMessage.apply(undefined, arguments)); } @@ -14,27 +14,77 @@ namespace ts { return compilerOptions.traceResolution && host.trace !== undefined; } - /* @internal */ - export function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { - return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations }; + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(value: T): void; } - function moduleHasNonRelativeName(moduleName: string): boolean { + /** + * Result of trying to resolve a module. + * At least one of `ts` and `js` should be defined, or the whole thing should be `undefined`. + */ + interface Resolved { + path: string; + extension: Extension; + } + + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + const enum Extensions { + TypeScript, /** '.ts', '.tsx', or '.d.ts' */ + JavaScript, /** '.js' or '.jsx' */ + DtsOnly /** Only '.d.ts' */ + } + + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved: Resolved | undefined): string | undefined { + if (!resolved) { + return undefined; + } + Debug.assert(extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + + /** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */ + function resolvedModuleFromResolved({ path, extension }: Resolved, isExternalLibraryImport: boolean): ResolvedModuleFull { + return { resolvedFileName: path, extension, isExternalLibraryImport }; + } + + function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { + return { resolvedModule: resolved && resolvedModuleFromResolved(resolved, isExternalLibraryImport), failedLookupLocations }; + } + + export function moduleHasNonRelativeName(moduleName: string): boolean { return !(isRootedDiskPath(moduleName) || isExternalModuleNameRelative(moduleName)); } - /* @internal */ - export interface ModuleResolutionState { + interface ModuleResolutionState { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; - // skip .tsx files if jsx is not enabled - skipTsx: boolean; } - function tryReadTypesSection(packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string { + /** Reads from "main" or "types"/"typings" depending on `extensions`. */ + function tryReadPackageJsonMainOrTypes(extensions: Extensions, packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string { const jsonContent = readJson(packageJsonPath, state.host); + switch (extensions) { + case Extensions.DtsOnly: + case Extensions.TypeScript: + return tryReadFromField("typings") || tryReadFromField("types"); + + case Extensions.JavaScript: + if (typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); + } + return normalizePath(combinePaths(baseDirectory, jsonContent.main)); + } + return undefined; + } + function tryReadFromField(fieldName: string) { if (hasProperty(jsonContent, fieldName)) { const typesFile = (jsonContent)[fieldName]; @@ -52,21 +102,6 @@ namespace ts { } } } - - const typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - const mainFilePath = normalizePath(combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; } function readJson(path: string, host: ModuleResolutionHost): { typings?: string, types?: string, main?: string } { @@ -80,8 +115,6 @@ namespace ts { } } - const typeReferenceExtensions = [".d.ts"]; - export function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean, getCurrentDirectory?: () => string }): string[] | undefined { if (options.typeRoots) { return options.typeRoots; @@ -95,7 +128,9 @@ namespace ts { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } } /** @@ -109,20 +144,13 @@ namespace ts { } let typeRoots: string[]; - - while (true) { - const atTypes = combinePaths(currentDirectory, nodeModulesAtTypes); + forEachAncestorDirectory(currentDirectory, directory => { + const atTypes = combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); } - - const parent = getDirectoryPath(currentDirectory); - if (parent === currentDirectory) { - break; - } - currentDirectory = parent; - } - + return undefined; + }); return typeRoots; } const nodeModulesAtTypes = combinePaths("node_modules", "@types"); @@ -132,12 +160,11 @@ namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host: host, - skipTsx: true, traceEnabled }; @@ -163,67 +190,67 @@ namespace ts { const failedLookupLocations: string[] = []; - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - const primarySearchPaths = typeRoots; - for (const typeRoot of primarySearchPaths) { - const candidate = combinePaths(typeRoot, typeReferenceDirectiveName); - const candidateDirectory = getDirectoryPath(candidate); - const resolvedFile = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, - !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + let resolved = primaryLookup(); + let primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } - if (resolvedFile) { - if (traceEnabled) { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile }, - failedLookupLocations - }; + let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary, resolvedFileName: resolved }; + } + + return { resolvedTypeReferenceDirective, failedLookupLocations }; + + function primaryLookup(): string | undefined { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return forEach(typeRoots, typeRoot => { + const candidate = combinePaths(typeRoot, typeReferenceDirectiveName); + const candidateDirectory = getDirectoryPath(candidate); + return resolvedTypeScriptOnly( + loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, + !directoryProbablyExists(candidateDirectory, host), moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } } - else { - if (traceEnabled) { - trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - let resolvedFile: string; - let initialLocationForSecondaryLookup: string; - if (containingFile) { - initialLocationForSecondaryLookup = getDirectoryPath(containingFile); - } + function secondaryLookup(): string | undefined { + let resolvedFile: string; + const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile); - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); - if (traceEnabled) { - if (resolvedFile) { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - else { + const result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + resolvedFile = resolvedTypeScriptOnly(result && result.value); + if (!resolvedFile && traceEnabled) { trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } } } - else { - if (traceEnabled) { - trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations - }; } /** @@ -264,33 +291,171 @@ namespace ts { return result; } - export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + export interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string): Map; + } + + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + export interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + } + + export interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache { + const directoryToModuleNameMap = createFileMap>(); + const moduleNameToDirectoryMap = createMap(); + + return { getOrCreateCacheForDirectory, getOrCreateCacheForModuleName }; + + function getOrCreateCacheForDirectory(directoryName: string) { + const path = toPath(directoryName, currentDirectory, getCanonicalFileName); + let perFolderCache = directoryToModuleNameMap.get(path); + if (!perFolderCache) { + perFolderCache = createMap(); + directoryToModuleNameMap.set(path, perFolderCache); + } + return perFolderCache; + } + + function getOrCreateCacheForModuleName(nonRelativeModuleName: string) { + if (!moduleHasNonRelativeName(nonRelativeModuleName)) { + return undefined; + } + let perModuleNameCache = moduleNameToDirectoryMap[nonRelativeModuleName]; + if (!perModuleNameCache) { + moduleNameToDirectoryMap[nonRelativeModuleName] = perModuleNameCache = createPerModuleNameCache(); + } + return perModuleNameCache; + } + + function createPerModuleNameCache(): PerModuleNameCache { + const directoryPathMap = createFileMap(); + + return { get, set }; + + function get(directory: string): ResolvedModuleWithFailedLookupLocations { + return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName)); + } + + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void { + const path = toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.contains(path)) { + return; + } + directoryPathMap.set(path, result); + + const resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + // find common prefix between directory and resolved file name + // this common prefix should be the shorted path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + const commonPrefix = getCommonPrefix(path, resolvedFileName); + let current = path; + while (true) { + const parent = getDirectoryPath(current); + if (parent === current || directoryPathMap.contains(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + + if (current == commonPrefix) { + break; + } + } + } + + function getCommonPrefix(directory: Path, resolution: string) { + if (resolution === undefined) { + return undefined; + } + const resolutionDirectory = toPath(getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + + // find first position where directory and resolution differs + let i = 0; + while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + + // find last directory separator before position i + const sep = directory.lastIndexOf(directorySeparator, i); + if (sep < 0) { + return undefined; + } + + return directory.substr(0, sep); + } + } + } + + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); } + const containingDirectory = getDirectoryPath(containingFile); + let perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + let result = perFolderCache && perFolderCache[moduleName]; - let moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; + if (result) { if (traceEnabled) { - trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); + trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); } } else { - if (traceEnabled) { - trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); + let moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); + } } - } - let result: ResolvedModuleWithFailedLookupLocations; - switch (moduleResolution) { - case ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; + switch (moduleResolution) { + case ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + break; + case ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + break; + } + + if (perFolderCache) { + perFolderCache[moduleName] = result; + // put result in per-module name cache + const perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); + if (perModuleNameCache) { + perModuleNameCache.set(containingDirectory, result); + } + } } if (traceEnabled) { @@ -313,7 +478,7 @@ namespace ts { * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ - type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string; + type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to @@ -375,19 +540,19 @@ namespace ts { * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { + function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, + failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); } else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); } } - function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { + function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, + failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.rootDirs) { return undefined; @@ -432,7 +597,7 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -451,7 +616,7 @@ namespace ts { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); - const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -463,9 +628,7 @@ namespace ts { return undefined; } - function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], - supportedExtensions: string[], state: ModuleResolutionState): string { - + function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.baseUrl) { return undefined; } @@ -488,18 +651,21 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } - for (const subst of state.compilerOptions.paths[matchedPatternText]) { + return forEach(state.compilerOptions.paths[matchedPatternText], subst => { const path = matchedStar ? subst.replace("*", matchedStar) : subst; const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path)); if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; + // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. + const tsExtension = tryGetExtensionFromPath(candidate); + if (tsExtension !== undefined) { + const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/false, state); + return path && { path, extension: tsExtension }; } - } - return undefined; + + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + }); } else { const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); @@ -508,56 +674,65 @@ namespace ts { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } } - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { const containingDirectory = getDirectoryPath(containingFile); - const supportedExtensions = getSupportedExtensions(compilerOptions); const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state = { compilerOptions, host, traceEnabled, skipTsx: false }; - let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, - failedLookupLocations, supportedExtensions, state); + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + + const result = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + if (result && result.value) { + const { resolved, isExternalLibraryImport } = result.value; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations }; + + function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { + const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + if (resolved) { + return toSearchResult({ resolved, isExternalLibraryImport: false }); + } - let isExternalLibraryImport = false; - if (!resolvedFileName) { if (moduleHasNonRelativeName(moduleName)) { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); - isExternalLibraryImport = resolvedFileName !== undefined; + const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return resolved && { value: resolved.value && { resolved: { path: realpath(resolved.value.path, host, traceEnabled), extension: resolved.value.extension }, isExternalLibraryImport: true } }; } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + return resolved && toSearchResult({ resolved, isExternalLibraryImport: false }); } } - - if (resolvedFileName && host.realpath) { - const originalFileName = resolvedFileName; - resolvedFileName = normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); } - function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[], - onlyRecordFailures: boolean, state: ModuleResolutionState): string { + function realpath(path: string, host: ModuleResolutionHost, traceEnabled: boolean): string { + if (!host.realpath) { + return path; + } + const real = normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + + function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } - const resolvedFileName = !pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + const resolvedFromFile = !pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ @@ -570,9 +745,9 @@ namespace ts { * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } @@ -585,12 +760,12 @@ namespace ts { const extension = candidate.substring(extensionless.length); trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing const directory = getDirectoryPath(candidate); @@ -598,12 +773,24 @@ namespace ts { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } } - return forEach(extensions, ext => - !(state.skipTsx && isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state)); + + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts", Extension.Dts); + case Extensions.TypeScript: + return tryExtension(".ts", Extension.Ts) || tryExtension(".tsx", Extension.Tsx) || tryExtension(".d.ts", Extension.Dts); + case Extensions.JavaScript: + return tryExtension(".js", Extension.Js) || tryExtension(".jsx", Extension.Jsx); + } + + function tryExtension(ext: string, extension: Extension): Resolved | undefined { + const path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + return path && { path, extension }; + } } /** Return the file if it exists. */ - function tryFile(fileName: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function tryFile(fileName: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); @@ -614,31 +801,39 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, fileName); } - failedLookupLocation.push(fileName); + failedLookupLocations.push(fileName); return undefined; } } - function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { + function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { const packageJsonPath = pathToPackageJson(candidate); const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath); } - const typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(typesFile), state.host); + const mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); + if (mainOrTypesFile) { + const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(mainOrTypesFile), state.host); // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - const result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures, state); - if (result) { - return result; + const fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures, state); + if (fromExactFile) { + const resolved = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); + if (resolved) { + return resolved; + } + trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); + } + const resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures, state); + if (resolved) { + return resolved; } } else { if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_types_field); + trace(state.host, Diagnostics.package_json_does_not_have_a_types_or_main_field); } } } @@ -647,115 +842,176 @@ namespace ts { trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); + failedLookupLocations.push(packageJsonPath); } - return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions: Extensions, path: string): Resolved | undefined { + const extension = tryGetExtensionFromPath(path); + return extension !== undefined && extensionIsOk(extensions, extension) ? { path, extension } : undefined; + } + + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions: Extensions, extension: Extension): boolean { + switch (extensions) { + case Extensions.JavaScript: + return extension === Extension.Js || extension === Extension.Jsx; + case Extensions.TypeScript: + return extension === Extension.Ts || extension === Extension.Tsx || extension === Extension.Dts; + case Extensions.DtsOnly: + return extension === Extension.Dts; + } } function pathToPackageJson(directory: string): string { return combinePaths(directory, "package.json"); } - function loadModuleFromNodeModulesFolder(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string { + function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); - const supportedExtensions = getSupportedExtensions(state.compilerOptions); - let result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + + function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache): SearchResult { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + } + function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): SearchResult { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + } + + function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache): SearchResult { + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { + if (getBaseFileName(ancestorDirectory) !== "node_modules") { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + } + }); + } + + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ + function loadModuleFromNodeModulesOneLevel(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly = false): Resolved | undefined { + const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state); + if (packageResult) { + return packageResult; } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; + if (extensions !== Extensions.JavaScript) { + return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, combinePaths("@types", moduleName), directory, failedLookupLocations, state); } } - /* @internal */ - export function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string { - return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false); + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult { + const result = cache && cache.get(containingDirectory); + if (result) { + if (traceEnabled) { + trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName) + } + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + } } - function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string { - return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true); - } + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations { + const traceEnabled = isTraceEnabled(compilerOptions, host); + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + const failedLookupLocations: string[] = []; + const containingDirectory = getDirectoryPath(containingFile); - function loadModuleFromNodeModulesWorker(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean, typesOnly: boolean): string { - directory = normalizeSlashes(directory); - while (true) { - const baseName = getBaseFileName(directory); - if (baseName !== "node_modules") { - let packageResult: string | undefined; - if (!typesOnly) { - // Try to load source from the package - packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; + const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + + function tryResolve(extensions: Extensions): SearchResult { + const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + + if (moduleHasNonRelativeName(moduleName)) { + // Climb up parent directories looking for a module. + const resolved = forEachAncestorDirectory(containingDirectory, directory => { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + if (resolutionFromCache) { + return resolutionFromCache; } + const searchName = normalizePath(combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + }); + if (resolved) { + return resolved; } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + } + } + } - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - const typesResult = loadModuleFromNodeModulesFolder(combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + export function loadModuleFromGlobalCache(moduleName: string, projectName: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations { + const traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + const failedLookupLocations: string[] = []; + const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + + /** + * Represents result of search. Normally when searching among several alternatives we treat value `undefined` as indicator + * that search fails and we should try another option. + * However this does not allow us to represent final result that should be used instead of further searching (i.e. a final result that was found in cache). + * SearchResult is used to deal with this issue, its values represents following outcomes: + * - undefined - not found, continue searching + * - { value: undefined } - not found - stop searching + * - { value: } - found - stop searching + */ + type SearchResult = { value: T | undefined } | undefined; + + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value: T | undefined): SearchResult { + return value !== undefined ? { value } : undefined; + } + + + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory: string, callback: (directory: string) => SearchResult): SearchResult { + while (true) { + const result = callback(directory); + if (result !== undefined) { + return result; } const parentPath = getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; + if (parentPath === directory) { + return undefined; } directory = parentPath; } - return undefined; - } - - export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - const traceEnabled = isTraceEnabled(compilerOptions, host); - const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx }; - const failedLookupLocations: string[] = []; - const supportedExtensions = getSupportedExtensions(compilerOptions); - const containingDirectory = getDirectoryPath(containingFile); - - const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); - } - - let referencedSourceFile: string; - if (moduleHasNonRelativeName(moduleName)) { - referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || - // If we didn't find the file normally, look it up in @types. - loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); - } - else { - const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - - - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations }; - } - - /** Climb up parent directories looking for a module. */ - function loadModuleFromAncestorDirectories(moduleName: string, containingDirectory: string, supportedExtensions: string[], failedLookupLocations: string[], state: ModuleResolutionState): string | undefined { - while (true) { - const searchName = normalizePath(combinePaths(containingDirectory, moduleName)); - const referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - return referencedSourceFile; - } - const parentPath = getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - return undefined; - } - containingDirectory = parentPath; - } } } \ No newline at end of file diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1133a5bafd6..8019b864ad5 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -74,6 +74,8 @@ namespace ts { visitNode(cbNode, (node).questionToken) || visitNode(cbNode, (node).equalsToken) || visitNode(cbNode, (node).objectAssignmentInitializer); + case SyntaxKind.SpreadAssignment: + return visitNode(cbNode, (node).expression); case SyntaxKind.Parameter: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -134,7 +136,16 @@ namespace ts { case SyntaxKind.IntersectionType: return visitNodes(cbNodes, (node).types); case SyntaxKind.ParenthesizedType: - return visitNode(cbNode, (node).type); + case SyntaxKind.TypeOperator: + return visitNode(cbNode, (node).type); + case SyntaxKind.IndexedAccessType: + return visitNode(cbNode, (node).objectType) || + visitNode(cbNode, (node).indexType); + case SyntaxKind.MappedType: + return visitNode(cbNode, (node).readonlyToken) || + visitNode(cbNode, (node).typeParameter) || + visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).type); case SyntaxKind.LiteralType: return visitNode(cbNode, (node).literal); case SyntaxKind.ObjectBindingPattern: @@ -193,8 +204,8 @@ namespace ts { visitNode(cbNode, (node).whenTrue) || visitNode(cbNode, (node).colonToken) || visitNode(cbNode, (node).whenFalse); - case SyntaxKind.SpreadElementExpression: - return visitNode(cbNode, (node).expression); + case SyntaxKind.SpreadElement: + return visitNode(cbNode, (node).expression); case SyntaxKind.Block: case SyntaxKind.ModuleBlock: return visitNodes(cbNodes, (node).statements); @@ -408,10 +419,13 @@ namespace ts { return visitNode(cbNode, (node).typeExpression); case SyntaxKind.JSDocTypeTag: return visitNode(cbNode, (node).typeExpression); + case SyntaxKind.JSDocAugmentsTag: + return visitNode(cbNode, (node).typeExpression); case SyntaxKind.JSDocTemplateTag: return visitNodes(cbNodes, (node).typeParameters); case SyntaxKind.JSDocTypedefTag: return visitNode(cbNode, (node).typeExpression) || + visitNode(cbNode, (node).fullName) || visitNode(cbNode, (node).name) || visitNode(cbNode, (node).jsDocTypeLiteral); case SyntaxKind.JSDocTypeLiteral: @@ -434,6 +448,10 @@ namespace ts { return result; } + export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + export function isExternalModule(file: SourceFile): boolean { return file.externalModuleIndicator !== undefined; } @@ -573,10 +591,10 @@ namespace ts { // attached to the EOF token. let parseErrorBeforeNextFinishedNode = false; - export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile { + export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile { scriptKind = ensureScriptKind(fileName, scriptKind); - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); const result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -585,12 +603,22 @@ namespace ts { return result; } + export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName { + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS); + // Prime the scanner. + nextToken(); + const entityName = parseEntityName(/*allowReservedWords*/ true); + const isInvalid = token() === SyntaxKind.EndOfFileToken && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + function getLanguageVariant(scriptKind: ScriptKind) { // .tsx and .jsx files are treated as jsx language variant. return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS ? LanguageVariant.JSX : LanguageVariant.Standard; } - function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) { + function initializeState(_sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) { NodeConstructor = objectAllocator.getNodeConstructor(); TokenConstructor = objectAllocator.getTokenConstructor(); IdentifierConstructor = objectAllocator.getIdentifierConstructor(); @@ -656,7 +684,7 @@ namespace ts { function addJSDocComment(node: T): T { - const comments = getJsDocCommentsFromText(node, sourceFile.text); + const comments = getJSDocCommentRanges(node, sourceFile.text); if (comments) { for (const comment of comments) { const jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); @@ -664,10 +692,10 @@ namespace ts { continue; } - if (!node.jsDocComments) { - node.jsDocComments = []; + if (!node.jsDoc) { + node.jsDoc = []; } - node.jsDocComments.push(jsDoc); + node.jsDoc.push(jsDoc); } } @@ -694,11 +722,11 @@ namespace ts { const saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDocComments) { - for (const jsDocComment of n.jsDocComments) { - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); + if (n.jsDoc) { + for (const jsDoc of n.jsDoc) { + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); } } parent = saveParent; @@ -1143,7 +1171,7 @@ namespace ts { function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName { if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) { - return parseLiteralNode(/*internName*/ true); + return parseLiteralNode(/*internName*/ true); } if (allowComputedPropertyNames && token() === SyntaxKind.OpenBracketToken) { return parseComputedPropertyName(); @@ -1265,9 +1293,11 @@ namespace ts { // which would be a candidate for improved error reporting. return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); case ParsingContext.ObjectLiteralMembers: - return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || isLiteralPropertyName(); + return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); + case ParsingContext.RestProperties: + return isLiteralPropertyName(); case ParsingContext.ObjectBindingElements: - return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); + return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); case ParsingContext.HeritageClauseElement: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. @@ -1394,6 +1424,7 @@ namespace ts { case ParsingContext.ArrayBindingElements: return token() === SyntaxKind.CloseBracketToken; case ParsingContext.Parameters: + case ParsingContext.RestProperties: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.CloseBracketToken /*|| token === SyntaxKind.OpenBraceToken*/; case ParsingContext.TypeArguments: @@ -1579,6 +1610,9 @@ namespace ts { case ParsingContext.Parameters: return isReusableParameter(node); + case ParsingContext.RestProperties: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the @@ -1776,6 +1810,7 @@ namespace ts { case ParsingContext.BlockStatements: return Diagnostics.Declaration_or_statement_expected; case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected; case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected; + case ParsingContext.RestProperties: // fallthrough case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected; case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected; @@ -2395,6 +2430,36 @@ namespace ts { return members; } + function isStartOfMappedType() { + nextToken(); + if (token() === SyntaxKind.ReadonlyKeyword) { + nextToken(); + } + return token() === SyntaxKind.OpenBracketToken && nextTokenIsIdentifier() && nextToken() === SyntaxKind.InKeyword; + } + + function parseMappedTypeParameter() { + const node = createNode(SyntaxKind.TypeParameter); + node.name = parseIdentifier(); + parseExpected(SyntaxKind.InKeyword); + node.constraint = parseType(); + return finishNode(node); + } + + function parseMappedType() { + const node = createNode(SyntaxKind.MappedType); + parseExpected(SyntaxKind.OpenBraceToken); + node.readonlyToken = parseOptionalToken(SyntaxKind.ReadonlyKeyword); + parseExpected(SyntaxKind.OpenBracketToken); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(SyntaxKind.CloseBracketToken); + node.questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(SyntaxKind.CloseBraceToken); + return finishNode(node); + } + function parseTupleType(): TupleTypeNode { const node = createNode(SyntaxKind.TupleType); node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); @@ -2468,7 +2533,7 @@ namespace ts { case SyntaxKind.TypeOfKeyword: return parseTypeQuery(); case SyntaxKind.OpenBraceToken: - return parseTypeLiteral(); + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); case SyntaxKind.OpenBracketToken: return parseTupleType(); case SyntaxKind.OpenParenToken: @@ -2494,6 +2559,8 @@ namespace ts { case SyntaxKind.OpenBraceToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.LessThanToken: + case SyntaxKind.BarToken: + case SyntaxKind.AmpersandToken: case SyntaxKind.NewKeyword: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: @@ -2519,15 +2586,41 @@ namespace ts { function parseArrayTypeOrHigher(): TypeNode { let type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) { - parseExpected(SyntaxKind.CloseBracketToken); - const node = createNode(SyntaxKind.ArrayType, type.pos); - node.elementType = type; - type = finishNode(node); + if (isStartOfType()) { + const node = createNode(SyntaxKind.IndexedAccessType, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(SyntaxKind.CloseBracketToken); + type = finishNode(node); + } + else { + const node = createNode(SyntaxKind.ArrayType, type.pos); + node.elementType = type; + parseExpected(SyntaxKind.CloseBracketToken); + type = finishNode(node); + } } return type; } + function parseTypeOperator(operator: SyntaxKind.KeyOfKeyword) { + const node = createNode(SyntaxKind.TypeOperator); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + + function parseTypeOperatorOrHigher(): TypeNode { + switch (token()) { + case SyntaxKind.KeyOfKeyword: + return parseTypeOperator(SyntaxKind.KeyOfKeyword); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode { + parseOptional(operator); let type = parseConstituentType(); if (token() === operator) { const types = createNodeArray([type], type.pos); @@ -2543,7 +2636,7 @@ namespace ts { } function parseIntersectionTypeOrHigher(): TypeNode { - return parseUnionOrIntersectionType(SyntaxKind.IntersectionType, parseArrayTypeOrHigher, SyntaxKind.AmpersandToken); + return parseUnionOrIntersectionType(SyntaxKind.IntersectionType, parseTypeOperatorOrHigher, SyntaxKind.AmpersandToken); } function parseUnionTypeOrHigher(): TypeNode { @@ -4094,7 +4187,7 @@ namespace ts { } function parseSpreadElement(): Expression { - const node = createNode(SyntaxKind.SpreadElementExpression); + const node = createNode(SyntaxKind.SpreadElement); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -4134,6 +4227,12 @@ namespace ts { function parseObjectLiteralElement(): ObjectLiteralElementLike { const fullStart = scanner.getStartPos(); + const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); + if (dotDotDotToken) { + const spreadElement = createNode(SyntaxKind.SpreadAssignment, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } const decorators = parseDecorators(); const modifiers = parseModifiers(); @@ -4837,6 +4936,7 @@ namespace ts { function parseObjectBindingElement(): BindingElement { const node = createNode(SyntaxKind.BindingElement); + node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); const tokenIsIdentifier = isIdentifier(); const propertyName = parsePropertyName(); if (tokenIsIdentifier && token() !== SyntaxKind.ColonToken) { @@ -5261,7 +5361,7 @@ namespace ts { parseExpected(SyntaxKind.ClassKeyword); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ true); + node.heritageClauses = parseHeritageClauses(); if (parseExpected(SyntaxKind.OpenBraceToken)) { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -5291,7 +5391,7 @@ namespace ts { return token() === SyntaxKind.ImplementsKeyword && lookAhead(nextTokenIsIdentifierOrKeyword); } - function parseHeritageClauses(isClassHeritageClause: boolean): NodeArray { + function parseHeritageClauses(): NodeArray { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } @@ -5339,7 +5439,7 @@ namespace ts { parseExpected(SyntaxKind.InterfaceKeyword); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); + node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); return addJSDocComment(finishNode(node)); } @@ -5421,7 +5521,7 @@ namespace ts { node.flags |= NodeFlags.GlobalAugmentation; } else { - node.name = parseLiteralNode(/*internName*/ true); + node.name = parseLiteralNode(/*internName*/ true); } if (token() === SyntaxKind.OpenBraceToken) { @@ -5474,7 +5574,7 @@ namespace ts { exportDeclaration.name = parseIdentifier(); - parseExpected(SyntaxKind.SemicolonToken); + parseSemicolon(); return finishNode(exportDeclaration); } @@ -5781,6 +5881,7 @@ namespace ts { JsxChildren, // Things between opening and closing JSX tags ArrayLiteralMembers, // Members in array literal Parameters, // Parameters in parameter list + RestProperties, // Property names in a rest type list TypeParameters, // Type parameters in type parameter list TypeArguments, // Type arguments in type argument list TupleElementTypes, // Element types in tuple element type list @@ -5819,7 +5920,7 @@ namespace ts { } export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number) { - initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); + initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS); scanner.setText(content, start, length); currentToken = scanner.scan(); @@ -6136,7 +6237,7 @@ namespace ts { } export function parseIsolatedJSDocComment(content: string, start: number, length: number) { - initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); + initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); sourceFile = { languageVariant: LanguageVariant.Standard, text: content }; const jsDoc = parseJSDocCommentWorker(start, length); const diagnostics = parseDiagnostics; @@ -6210,6 +6311,7 @@ namespace ts { } if (token() === SyntaxKind.NewLineTrivia) { state = JSDocState.BeginningOfLine; + indent = 0; nextJSDocToken(); } while (token() !== SyntaxKind.EndOfFileToken) { @@ -6237,7 +6339,7 @@ namespace ts { break; case SyntaxKind.AsteriskToken: const asterisk = scanner.getTokenText(); - if (state === JSDocState.SawAsterisk) { + if (state === JSDocState.SawAsterisk || state === JSDocState.SavingComments) { // If we've already seen an asterisk, then we can no longer parse a tag on this line state = JSDocState.SavingComments; pushComment(asterisk); @@ -6258,7 +6360,10 @@ namespace ts { case SyntaxKind.WhitespaceTrivia: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin const whitespace = scanner.getTokenText(); - if (state === JSDocState.SavingComments || margin !== undefined && indent + whitespace.length > margin) { + if (state === JSDocState.SavingComments) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -6266,6 +6371,8 @@ namespace ts { case SyntaxKind.EndOfFileToken: break; default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = JSDocState.SavingComments; pushComment(scanner.getTokenText()); break; } @@ -6331,6 +6438,9 @@ namespace ts { let tag: JSDocTag; if (tagName) { switch (tagName.text) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; case "param": tag = parseParamTag(atToken, tagName); break; @@ -6547,6 +6657,16 @@ namespace ts { return finishNode(result); } + function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag { + const typeExpression = tryParseTypeExpression(); + + const result = createNode(SyntaxKind.JSDocAugmentsTag, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag { const typeExpression = tryParseTypeExpression(); skipWhitespace(); @@ -6554,7 +6674,14 @@ namespace ts { const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.name = parseJSDocIdentifierName(); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); + if (typedefTag.fullName) { + let rightNode = typedefTag.fullName; + while (rightNode.kind !== SyntaxKind.Identifier) { + rightNode = rightNode.body; + } + typedefTag.name = rightNode; + } typedefTag.typeExpression = typeExpression; skipWhitespace(); @@ -6617,8 +6744,27 @@ namespace ts { scanner.setTextPos(resumePos); return finishNode(jsDocTypeLiteral); } + + function parseJSDocTypeNameWithNamespace(flags: NodeFlags) { + const pos = scanner.getTokenPos(); + const typeNameOrNamespaceName = parseJSDocIdentifierName(); + + if (typeNameOrNamespaceName && parseOptional(SyntaxKind.DotToken)) { + const jsDocNamespaceNode = createNode(SyntaxKind.ModuleDeclaration, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(NodeFlags.NestedNamespace); + return jsDocNamespaceNode; + } + + if (typeNameOrNamespaceName && flags & NodeFlags.NestedNamespace) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } } + function tryParseChildTag(parentTag: JSDocTypeLiteral): boolean { Debug.assert(token() === SyntaxKind.AtToken); const atToken = createNode(SyntaxKind.AtToken, scanner.getStartPos()); @@ -6641,12 +6787,16 @@ namespace ts { return true; case "prop": case "property": - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = >[]; - } const propertyTag = parsePropertyTag(atToken, tagName); - parentTag.jsDocPropertyTags.push(propertyTag); - return true; + if (propertyTag) { + if (!parentTag.jsDocPropertyTags) { + parentTag.jsDocPropertyTags = >[]; + } + parentTag.jsDocPropertyTags.push(propertyTag); + return true; + } + // Error parsing property tag + return false; } return false; } @@ -6829,8 +6979,8 @@ namespace ts { } forEachChild(node, visitNode, visitArray); - if (node.jsDocComments) { - for (const jsDocComment of node.jsDocComments) { + if (node.jsDoc) { + for (const jsDocComment of node.jsDoc) { forEachChild(jsDocComment, visitNode, visitArray); } } diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index e8f064e81cd..a48eb117e28 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -12,7 +12,7 @@ namespace ts.performance { const profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent - : (markName: string) => { }; + : (_markName: string) => { }; let enabled = false; let profilerStart = 0; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index a52ffc85452..4ab709d8455 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -3,10 +3,6 @@ /// namespace ts { - /** The version of the TypeScript compiler release */ - - export const version = "2.1.0"; - const emptyArray: any[] = []; export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string { @@ -239,11 +235,11 @@ namespace ts { const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); const fileName = diagnostic.file.fileName; const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)); - output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `; + output += `${relativeFileName}(${line + 1},${character + 1}): `; } const category = DiagnosticCategory[diagnostic.category].toLowerCase(); - output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) }${ host.getNewLine() }`; + output += `${category} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`; } return output; } @@ -307,7 +303,7 @@ namespace ts { // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track @@ -329,12 +325,22 @@ namespace ts { // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createFileMap(getCanonicalFileName); - let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => ResolvedModule[]; + let moduleResolutionCache: ModuleResolutionCache; + let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => ResolvedModuleFull[]; if (host.resolveModuleNames) { - resolveModuleNamesWorker = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile); + resolveModuleNamesWorker = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile).map(resolved => { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) { + return resolved as ResolvedModuleFull; + } + const withExtension = clone(resolved) as ResolvedModuleFull; + withExtension.extension = extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); } else { - const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x)); + const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(moduleNames, containingFile, loader); } @@ -360,7 +366,8 @@ namespace ts { if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side - const containingFilename = combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingFilename = combinePaths(containingDirectory, "__inferred type names__.ts"); const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (let i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -386,6 +393,9 @@ namespace ts { } } + // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks + moduleResolutionCache = undefined; + // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -412,6 +422,7 @@ namespace ts { getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics, getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, + isSourceFileFromExternalLibrary, dropDiagnosticsProducingTypeChecker }; @@ -422,13 +433,14 @@ namespace ts { return program; function getCommonSourceDirectory() { - if (typeof commonSourceDirectory === "undefined") { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + if (commonSourceDirectory === undefined) { + const emittedFiles = filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { - commonSourceDirectory = computeCommonSourceDirectory(files); + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { // Make sure directory path ends with directory separator so this string can directly @@ -454,6 +466,130 @@ namespace ts { return classifiableNames; } + interface OldProgramState { + program: Program; + file: SourceFile; + modifiedFilePaths: Path[]; + } + + function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile, oldProgramState?: OldProgramState) { + if (!oldProgramState && !file.ambientModuleNames.length) { + // if old program state is not supplied and file does not contain locally defined ambient modules + // then the best we can do is fallback to the default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + + // at this point we know that either + // - file has local declarations for ambient modules + // OR + // - old program state is available + // OR + // - both of items above + // With this it is possible that we can tell how some module names from the initial list will be resolved + // without doing actual resolution (in particular if some name was resolved to ambient module). + // Such names should be excluded from the list of module names that will be provided to `resolveModuleNamesWorker` + // since we don't want to resolve them again. + + // this is a list of modules for which we cannot predict resolution so they should be actually resolved + let unknownModuleNames: string[]; + // this is a list of combined results assembles from predicted and resolved results. + // Order in this list matches the order in the original list of module names `moduleNames` which is important + // so later we can split results to resolutions of modules and resolutions of module augmentations. + let result: ResolvedModuleFull[]; + // a transient placeholder that is used to mark predicted resolution in the result list + const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = {}; + + for (let i = 0; i < moduleNames.length; i++) { + const moduleName = moduleNames[i]; + // module name is known to be resolved to ambient module if + // - module name is contained in the list of ambient modules that are locally declared in the file + // - in the old program module name was resolved to ambient module whose declaration is in non-modified file + // (so the same module declaration will land in the new program) + let isKnownToResolveToAmbientModule = false; + if (contains(file.ambientModuleNames, moduleName)) { + isKnownToResolveToAmbientModule = true; + if (isTraceEnabled(options, host)) { + trace(host, Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + isKnownToResolveToAmbientModule = checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + + if (isKnownToResolveToAmbientModule) { + if (!unknownModuleNames) { + // found a first module name for which result can be prediced + // this means that this module name should not be passed to `resolveModuleNamesWorker`. + // We'll use a separate list for module names that are definitely unknown. + result = new Array(moduleNames.length); + // copy all module names that appear before the current one in the list + // since they are known to be unknown + unknownModuleNames = moduleNames.slice(0, i); + } + // mark prediced resolution in the result list + result[i] = predictedToResolveToAmbientModuleMarker; + } + else if (unknownModuleNames) { + // found unknown module name and we are already using separate list for those - add it to the list + unknownModuleNames.push(moduleName); + } + } + + if (!unknownModuleNames) { + // we've looked throught the list but have not seen any predicted resolution + // use default logic + return resolveModuleNamesWorker(moduleNames, containingFile); + } + + const resolutions = unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + : emptyArray; + + // combine results of resolutions and predicted results + let j = 0; + for (let i = 0; i < result.length; i++) { + if (result[i] == predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; + } + else { + result[i] = resolutions[j]; + j++; + } + } + Debug.assert(j === resolutions.length); + return result; + + function checkModuleNameResolvedToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState?: OldProgramState): boolean { + if (!oldProgramState) { + return false; + } + const resolutionToFile = getResolvedModule(oldProgramState.file, moduleName); + if (resolutionToFile) { + // module used to be resolved to file - ignore it + return false; + } + const ambientModule = oldProgram.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + + // at least one of declarations should come from non-modified source file + const firstUnmodifiedFile = forEach(ambientModule.declarations, d => { + const f = getSourceFileOfNode(d); + return !contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + + if (!firstUnmodifiedFile) { + return false; + } + + if (isTraceEnabled(options, host)) { + trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } + function tryReuseStructureFromOldProgram(): boolean { if (!oldProgram) { return false; @@ -462,21 +598,7 @@ namespace ts { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused const oldOptions = oldProgram.getCompilerOptions(); - if ((oldOptions.module !== options.module) || - (oldOptions.moduleResolution !== options.moduleResolution) || - (oldOptions.noResolve !== options.noResolve) || - (oldOptions.target !== options.target) || - (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx) || - (oldOptions.allowJs !== options.allowJs) || - (oldOptions.rootDir !== options.rootDir) || - (oldOptions.configFilePath !== options.configFilePath) || - (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || - !arrayIsEqualTo(oldOptions.lib, options.lib) || - !arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || - !arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !equalOwnProperties(oldOptions.paths, options.paths)) { + if (changesAffectModuleResolution(oldOptions, options)) { return false; } @@ -495,7 +617,7 @@ namespace ts { // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; const filePaths: Path[] = []; - const modifiedSourceFiles: SourceFile[] = []; + const modifiedSourceFiles: { oldFile: SourceFile, newFile: SourceFile }[] = []; for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFileByPath @@ -538,29 +660,8 @@ namespace ts { return false; } - const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - if (resolveModuleNamesWorker) { - const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); - const resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath); - // ensure that module resolution results are still correct - const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, x => x.fileName); - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - // ensure that types resolutions are still correct - const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); - if (resolutionsChanged) { - return false; - } - } - // pass the cache of module/types resolutions from the old source file - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - modifiedSourceFiles.push(newSourceFile); + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } else { // file has no changes - use it as is @@ -571,6 +672,33 @@ namespace ts { newSourceFiles.push(newSourceFile); } + const modifiedFilePaths = modifiedSourceFiles.map(f => f.newFile.path); + // try to verify results of module resolution + for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { + const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + if (resolveModuleNamesWorker) { + const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, { file: oldSourceFile, program: oldProgram, modifiedFilePaths }); + // ensure that module resolution results are still correct + const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, x => x.fileName); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct + const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); + if (resolutionsChanged) { + return false; + } + } + // pass the cache of module/types resolutions from the old source file + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + // update fileName -> file mapping for (let i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); @@ -580,7 +708,7 @@ namespace ts { fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); for (const modifiedFile of modifiedSourceFiles) { - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); oldProgram.structureIsReused = true; @@ -598,13 +726,17 @@ namespace ts { getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: (file: SourceFile) => !!sourceFilesFoundSearchingNodeModules[file.path], + isSourceFileFromExternalLibrary, writeFile: writeFileCallback || ( (fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)), isEmitBlocked, }; } + function isSourceFileFromExternalLibrary(file: SourceFile): boolean { + return sourceFilesFoundSearchingNodeModules[file.path]; + } + function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); } @@ -724,7 +856,15 @@ namespace ts { } } - function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { + function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } return sourceFile.parseDiagnostics; } @@ -757,64 +897,38 @@ namespace ts { Debug.assert(!!sourceFile.bindDiagnostics); const bindDiagnostics = sourceFile.bindDiagnostics; - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? - getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : - typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report semantic errors. + // Instead, we'll report errors for using TypeScript-only constructs from within a + // JavaScript file when we get syntactic diagnostics for the file. + const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken); const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); }); } - function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] { return runWithCancellationToken(() => { const diagnostics: Diagnostic[] = []; + let parent: Node = sourceFile; walk(sourceFile); return diagnostics; - function walk(node: Node): boolean { - if (!node) { - return false; - } + function walk(node: Node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child - switch (node.kind) { - case SyntaxKind.ImportEqualsDeclaration: - diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case SyntaxKind.ExportAssignment: - if ((node).isExportEquals) { - diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; + switch (parent.kind) { + case SyntaxKind.Parameter: + case SyntaxKind.PropertyDeclaration: + if ((parent).questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; } - break; - case SyntaxKind.ClassDeclaration: - let classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case SyntaxKind.HeritageClause: - let heritageClause = node; - if (heritageClause.token === SyntaxKind.ImplementsKeyword) { - diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case SyntaxKind.InterfaceDeclaration: - diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case SyntaxKind.ModuleDeclaration: - diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case SyntaxKind.TypeAliasDeclaration: - diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; + + // Pass through case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: @@ -824,124 +938,151 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: - const functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case SyntaxKind.VariableStatement: - const variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; case SyntaxKind.VariableDeclaration: - const variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; + // type annotation + if ((parent).type === node) { + diagnostics.push(createDiagnosticForNode(node, Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + + switch (node.kind) { + case SyntaxKind.ImportEqualsDeclaration: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.ExportAssignment: + if ((node).isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case SyntaxKind.HeritageClause: + let heritageClause = node; + if (heritageClause.token === SyntaxKind.ImplementsKeyword) { + diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case SyntaxKind.InterfaceDeclaration: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.ModuleDeclaration: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.TypeAliasDeclaration: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.EnumDeclaration: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.TypeAssertionExpression: + let typeAssertionExpression = node; + diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + } + + const prevParent = parent; + parent = node; + forEachChild(node, walk, walkArray); + parent = prevParent; + } + + function walkArray(nodes: NodeArray) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + + switch (parent.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.Constructor: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.FunctionExpression: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionDeclaration: + // Check type parameters + if (nodes === (parent).typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // pass through + case SyntaxKind.VariableStatement: + // Check modifiers + if (nodes === (parent).modifiers) { + return checkModifiers(>nodes, parent.kind === SyntaxKind.VariableStatement); + } + break; + case SyntaxKind.PropertyDeclaration: + // Check modifiers of property declaration + if (nodes === (parent).modifiers) { + for (const modifier of >nodes) { + if (modifier.kind !== SyntaxKind.StaticKeyword) { + diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); + } + } + return; + } + break; + case SyntaxKind.Parameter: + // Check modifiers of parameter declaration + if (nodes === (parent).modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; } break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - const expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - const start = expression.typeArguments.pos; - diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, - Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; + case SyntaxKind.ExpressionWithTypeArguments: + // Check type arguments + if (nodes === (parent).typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; } break; - case SyntaxKind.Parameter: - const parameter = node; - if (parameter.modifiers) { - const start = parameter.modifiers.pos; - diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, - Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return true; - } - if (parameter.type) { - diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case SyntaxKind.PropertyDeclaration: - const propertyDeclaration = node; - if (propertyDeclaration.modifiers) { - for (const modifier of propertyDeclaration.modifiers) { - if (modifier.kind !== SyntaxKind.StaticKeyword) { - diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); - return true; - } + } + + for (const node of nodes) { + walk(node); + } + } + + function checkModifiers(modifiers: NodeArray, isConstValid: boolean) { + for (const modifier of modifiers) { + switch (modifier.kind) { + case SyntaxKind.ConstKeyword: + if (isConstValid) { + continue; } - } - if (checkTypeAnnotation((node).type)) { - return true; - } - break; - case SyntaxKind.EnumDeclaration: - diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case SyntaxKind.TypeAssertionExpression: - let typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case SyntaxKind.Decorator: - if (!options.experimentalDecorators) { - diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); - } - return true; - } + // Fallthrough to report error + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.DeclareKeyword: + case SyntaxKind.AbstractKeyword: + diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); + break; - return forEachChild(node, walk); - } - - function checkTypeParameters(typeParameters: NodeArray): boolean { - if (typeParameters) { - const start = typeParameters.pos; - diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - - function checkTypeAnnotation(type: TypeNode): boolean { - if (type) { - diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - - return false; - } - - function checkModifiers(modifiers: NodeArray): boolean { - if (modifiers) { - for (const modifier of modifiers) { - switch (modifier.kind) { - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.ReadonlyKeyword: - case SyntaxKind.DeclareKeyword: - diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); - return true; - - // These are all legal modifiers. - case SyntaxKind.StaticKeyword: - case SyntaxKind.ExportKeyword: - case SyntaxKind.ConstKeyword: - case SyntaxKind.DefaultKeyword: - case SyntaxKind.AbstractKeyword: - } + // These are all legal modifiers. + case SyntaxKind.StaticKeyword: + case SyntaxKind.ExportKeyword: + case SyntaxKind.DefaultKeyword: } } + } - return false; + function createDiagnosticForNodeArray(nodes: NodeArray, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic { + const start = nodes.pos; + return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic { + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } }); } @@ -950,8 +1091,7 @@ namespace ts { return runWithCancellationToken(() => { const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - const writeFile: WriteFileCallback = () => { }; - return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile); }); } @@ -972,12 +1112,8 @@ namespace ts { return sortAndDeduplicateDiagnostics(allDiagnostics); } - function hasExtension(fileName: string): boolean { - return getBaseFileName(fileName).indexOf(".") >= 0; - } - function processRootFile(fileName: string, isDefaultLib: boolean) { - processSourceFile(normalizePath(fileName), isDefaultLib, /*isReference*/ true); + processSourceFile(normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean { @@ -999,18 +1135,25 @@ namespace ts { const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); + const isDtsFile = isDeclarationFile(file); let imports: LiteralExpression[]; let moduleAugmentations: LiteralExpression[]; + let ambientModules: string[]; // If we are importing helpers, we need to add a synthetic reference to resolve the // helpers library. if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { - const externalHelpersModuleReference = createNode(SyntaxKind.StringLiteral); + // synthesize 'import "tslib"' declaration + const externalHelpersModuleReference = createSynthesizedNode(SyntaxKind.StringLiteral); externalHelpersModuleReference.text = externalHelpersModuleNameText; - externalHelpersModuleReference.parent = file; + const importDecl = createSynthesizedNode(SyntaxKind.ImportDeclaration); + + importDecl.parent = file; + externalHelpersModuleReference.parent = importDecl; + imports = [externalHelpersModuleReference]; } @@ -1023,6 +1166,7 @@ namespace ts { file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; return; @@ -1058,6 +1202,10 @@ namespace ts { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { + if (isDtsFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(moduleName.text); + } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. @@ -1085,10 +1233,7 @@ namespace ts { } } - /** - * 'isReference' indicates whether the file was brought in via a reference directive (rather than an import declaration) - */ - function processSourceFile(fileName: string, isDefaultLib: boolean, isReference: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { + function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { let diagnosticArgument: string[]; let diagnostic: DiagnosticMessage; if (hasExtension(fileName)) { @@ -1096,7 +1241,7 @@ namespace ts { diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -1106,13 +1251,13 @@ namespace ts { } } else { - const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd); + const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, isReference, refFile, refPos, refEnd))) { + else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { diagnostic = Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -1141,7 +1286,7 @@ namespace ts { } // Get source file from normalized fileName - function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, isReference: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile { + function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile { if (filesByName.contains(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -1155,18 +1300,18 @@ namespace ts { if (file && sourceFilesFoundSearchingNodeModules[file.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file.path] = false; if (!options.noResolve) { - processReferencedFiles(file, getDirectoryPath(fileName), isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } modulesWithElidedImports[file.path] = false; - processImportedModules(file, getDirectoryPath(fileName)); + processImportedModules(file); } // See if we need to reprocess the imports due to prior skipped imports else if (file && modulesWithElidedImports[file.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { modulesWithElidedImports[file.path] = false; - processImportedModules(file, getDirectoryPath(fileName)); + processImportedModules(file); } } @@ -1202,14 +1347,13 @@ namespace ts { skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - const basePath = getDirectoryPath(fileName); if (!options.noResolve) { - processReferencedFiles(file, basePath, isDefaultLib); + processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } // always process imported modules to record module name resolutions - processImportedModules(file, basePath); + processImportedModules(file); if (isDefaultLib) { files.unshift(file); @@ -1222,10 +1366,10 @@ namespace ts { return file; } - function processReferencedFiles(file: SourceFile, basePath: string, isDefaultLib: boolean) { + function processReferencedFiles(file: SourceFile, isDefaultLib: boolean) { forEach(file.referencedFiles, ref => { const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, /*isReference*/ true, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); }); } @@ -1256,27 +1400,30 @@ namespace ts { if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents // for sameness and possibly issue an error if (previousResolution) { - const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, - Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, - typeReferenceDirective, - resolvedTypeReferenceDirective.resolvedFileName, - previousResolution.resolvedFileName - )); + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, + Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, + typeReferenceDirective, + resolvedTypeReferenceDirective.resolvedFileName, + previousResolution.resolvedFileName + )); + } } // don't overwrite previous resolution result saveResolution = false; } else { // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); } } } @@ -1302,41 +1449,48 @@ namespace ts { return host.getCanonicalFileName(fileName); } - function processImportedModules(file: SourceFile, basePath: string) { + function processImportedModules(file: SourceFile) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = createMap(); - const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); - const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); + file.resolvedModules = createMap(); + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + const nonGlobalAugmentation = filter(file.moduleAugmentations, (moduleAugmentation) => moduleAugmentation.kind === SyntaxKind.StringLiteral); + const moduleNames = map(concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory), file); + Debug.assert(resolutions.length === moduleNames.length); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + + const isFromNodeModulesSearch = resolution.isExternalLibraryImport; + const isJsFileFromNodeModules = isFromNodeModulesSearch && !extensionIsTypeScript(resolution.extension); + const resolvedFileName = resolution.resolvedFileName; + + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name comes from the list of imports // - it's not a top level JavaScript module that exceeded the search max - const isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; - const isJsFileFromNodeModules = isFromNodeModulesSearch && hasJavaScriptFileExtension(resolution.resolvedFileName); - - if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; - } - - const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; - const shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; + const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, - toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), - /*isDefaultLib*/ false, /*isReference*/ false, - file, - skipTrivia(file.text, file.imports[i].pos), - file.imports[i].end); + const path = toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + const pos = skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); } if (isFromNodeModulesSearch) { @@ -1348,7 +1502,6 @@ namespace ts { // no imports - drop cached module resolutions file.resolvedModules = undefined; } - return; } function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string { @@ -1473,12 +1626,16 @@ namespace ts { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } + const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (options.isolatedModules) { - if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) { + if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } @@ -1488,7 +1645,7 @@ namespace ts { programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); @@ -1529,7 +1686,15 @@ namespace ts { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } - if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) { + if (options.jsxFactory) { + if (options.reactNamespace) { + programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + } + if (!parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + } + } + else if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } @@ -1537,7 +1702,7 @@ namespace ts { if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); - forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => { + forEachExpectedEmitFile(emitHost, (emitFileNames) => { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); }); @@ -1549,13 +1714,19 @@ namespace ts { const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { - createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + let chain: DiagnosticMessageChain; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain = chainDiagnosticMessages(chain, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain)); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error - createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + blockEmittingOfFile(emitFileName, createCompilerDiagnostic(Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { emitFilesSeen.set(emitFilePath, true); @@ -1564,9 +1735,37 @@ namespace ts { } } - function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) { + function blockEmittingOfFile(emitFileName: string, diag: Diagnostic) { hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true); - programDiagnostics.add(createCompilerDiagnostic(message, emitFileName)); + programDiagnostics.add(diag); + } + } + + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + export function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModuleFull): DiagnosticMessage | undefined { + switch (extension) { + case Extension.Ts: + case Extension.Dts: + // These are always allowed. + return undefined; + case Extension.Tsx: + return needJsx(); + case Extension.Jsx: + return needJsx() || needAllowJs(); + case Extension.Js: + return needAllowJs(); + } + + function needJsx() { + return options.jsx ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; } } } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index e7b3872f2e3..82302e98e37 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -90,6 +90,7 @@ namespace ts { "instanceof": SyntaxKind.InstanceOfKeyword, "interface": SyntaxKind.InterfaceKeyword, "is": SyntaxKind.IsKeyword, + "keyof": SyntaxKind.KeyOfKeyword, "let": SyntaxKind.LetKeyword, "module": SyntaxKind.ModuleKeyword, "namespace": SyntaxKind.NamespaceKeyword, @@ -723,7 +724,7 @@ namespace ts { return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); } - function appendCommentRange(pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: any, comments: CommentRange[]) { + function appendCommentRange(pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, _state: any, comments: CommentRange[]) { if (!comments) { comments = []; } @@ -1190,7 +1191,7 @@ namespace ts { } function scanBinaryOrOctalDigits(base: number): number { - Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); let value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. @@ -1799,6 +1800,9 @@ namespace ts { case CharacterCodes.comma: pos++; return token = SyntaxKind.CommaToken; + case CharacterCodes.dot: + pos++; + return token = SyntaxKind.DotToken; } if (isIdentifierStart(ch, ScriptTarget.Latest)) { diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 46db5188e33..650b9b0ef02 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -427,7 +427,7 @@ namespace ts { encodeLastRecordedSourceMapSpan(); - return stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 7cf7d75bc02..a1e82a66595 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -17,7 +17,11 @@ namespace ts { readFile(path: string, encoding?: string): string; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; @@ -34,6 +38,8 @@ namespace ts { realpath?(path: string): string; /*@internal*/ getEnvironmentVariable(name: string): string; /*@internal*/ tryEnableSourceMapsForHost?(): void; + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout?(timeoutId: any): void; } export interface FileWatcher { @@ -46,13 +52,9 @@ namespace ts { } declare var require: any; - declare var module: any; declare var process: any; declare var global: any; declare var __filename: string; - declare var Buffer: { - new (str: string, encoding?: string): any; - }; declare class Enumerator { public atEnd(): boolean; @@ -324,7 +326,7 @@ namespace ts { const platform: string = _os.platform(); const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - function readFile(fileName: string, encoding?: string): string { + function readFile(fileName: string, _encoding?: string): string { if (!fileExists(fileName)) { return undefined; } @@ -441,6 +443,7 @@ namespace ts { return filter(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory)); } + const noOpFileWatcher: FileWatcher = { close: noop }; const nodeSystem: System = { args: process.argv.slice(2), newLine: _os.EOL, @@ -450,7 +453,7 @@ namespace ts { }, readFile, writeFile, - watchFile: (fileName, callback) => { + watchFile: (fileName, callback, pollingInterval) => { if (useNonPollingWatchers) { const watchedFile = watchedFileSet.addFile(fileName, callback); return { @@ -458,7 +461,7 @@ namespace ts { }; } else { - _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); return { close: () => _fs.unwatchFile(fileName, fileChanged) }; @@ -476,6 +479,10 @@ namespace ts { // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) let options: any; + if (!directoryExists(directoryName)) { + return noOpFileWatcher; + } + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -560,7 +567,9 @@ namespace ts { catch (e) { // Could not enable source maps. } - } + }, + setTimeout, + clearTimeout }; return nodeSystem; } @@ -572,7 +581,7 @@ namespace ts { args: ChakraHost.args, useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, - readFile(path: string, encoding?: string) { + readFile(path: string, _encoding?: string) { // encoding is automatically handled by the implementation in ChakraHost return ChakraHost.readFile(path); }, @@ -591,9 +600,9 @@ namespace ts { getExecutingFilePath: () => ChakraHost.executingFile, getCurrentDirectory: () => ChakraHost.currentDirectory, getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || ((name: string) => ""), + getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (() => ""), readDirectory: (path: string, extensions?: string[], excludes?: string[], includes?: string[]) => { - const pattern = getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + const pattern = getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, exit: ChakraHost.quit, diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 92407af2bb9..10a718448e9 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -1,17 +1,20 @@ /// /// /// -/// -/// +/// +/// +/// +/// /// +/// /// /// -/// +/// /* @internal */ namespace ts { const moduleTransformerMap = createMap({ - [ModuleKind.ES6]: transformES6Module, + [ModuleKind.ES2015]: transformES2015Module, [ModuleKind.System]: transformSystemModule, [ModuleKind.AMD]: transformModule, [ModuleKind.CommonJS]: transformModule, @@ -24,84 +27,6 @@ namespace ts { EmitNotifications = 1 << 1, } - export interface TransformationResult { - /** - * Gets the transformed source files. - */ - transformed: SourceFile[]; - - /** - * Emits the substitute for a node, if one is available; otherwise, emits the node. - * - * @param emitContext The current emit context. - * @param node The node to substitute. - * @param emitCallback A callback used to emit the node or its substitute. - */ - emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; - - /** - * Emits a node with possible notification. - * - * @param emitContext The current emit context. - * @param node The node to emit. - * @param emitCallback A callback used to emit the node. - */ - emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; - } - - export interface TransformationContext extends LexicalEnvironment { - getCompilerOptions(): CompilerOptions; - getEmitResolver(): EmitResolver; - getEmitHost(): EmitHost; - - /** - * Hoists a function declaration to the containing scope. - */ - hoistFunctionDeclaration(node: FunctionDeclaration): void; - - /** - * Hoists a variable declaration to the containing scope. - */ - hoistVariableDeclaration(node: Identifier): void; - - /** - * Enables expression substitutions in the pretty printer for the provided SyntaxKind. - */ - enableSubstitution(kind: SyntaxKind): void; - - /** - * Determines whether expression substitutions are enabled for the provided node. - */ - isSubstitutionEnabled(node: Node): boolean; - - /** - * Hook used by transformers to substitute expressions just before they - * are emitted by the pretty printer. - */ - onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node; - - /** - * Enables before/after emit notifications in the pretty printer for the provided - * SyntaxKind. - */ - enableEmitNotification(kind: SyntaxKind): void; - - /** - * Determines whether before/after emit notifications should be raised in the pretty - * printer when it emits a node. - */ - isEmitNotificationEnabled(node: Node): boolean; - - /** - * Hook used to allow transformers to capture state before or after - * the printer emits a node. - */ - onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; - } - - /* @internal */ - export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; - export function getTransformers(compilerOptions: CompilerOptions) { const jsx = compilerOptions.jsx; const languageVersion = getEmitScriptTarget(compilerOptions); @@ -109,19 +34,36 @@ namespace ts { const transformers: Transformer[] = []; transformers.push(transformTypeScript); - transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ModuleKind.None]); if (jsx === JsxEmit.React) { transformers.push(transformJsx); } - transformers.push(transformES7); + if (languageVersion < ScriptTarget.ESNext) { + transformers.push(transformESNext); + } - if (languageVersion < ScriptTarget.ES6) { - transformers.push(transformES6); + if (languageVersion < ScriptTarget.ES2017) { + transformers.push(transformES2017); + } + + if (languageVersion < ScriptTarget.ES2016) { + transformers.push(transformES2016); + } + + if (languageVersion < ScriptTarget.ES2015) { + transformers.push(transformES2015); transformers.push(transformGenerators); } + transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ModuleKind.None]); + + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < ScriptTarget.ES5) { + transformers.push(transformES5); + } + return transformers; } @@ -134,14 +76,18 @@ namespace ts { * @param transforms An array of Transformers. */ export function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult { - const lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = []; - const lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = []; const enabledSyntaxKindFeatures = new Array(SyntaxKind.Count); + let lexicalEnvironmentDisabled = false; + + let lexicalEnvironmentVariableDeclarations: VariableDeclaration[]; + let lexicalEnvironmentFunctionDeclarations: FunctionDeclaration[]; + let lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = []; + let lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = []; let lexicalEnvironmentStackOffset = 0; - let hoistedVariableDeclarations: VariableDeclaration[]; - let hoistedFunctionDeclarations: FunctionDeclaration[]; - let lexicalEnvironmentDisabled: boolean; + let lexicalEnvironmentSuspended = false; + + let emitHelpers: EmitHelper[]; // The transformation context is provided to each transformer as part of transformer // initialization. @@ -149,11 +95,15 @@ namespace ts { getCompilerOptions: () => host.getCompilerOptions(), getEmitResolver: () => resolver, getEmitHost: () => host, + startLexicalEnvironment, + suspendLexicalEnvironment, + resumeLexicalEnvironment, + endLexicalEnvironment, hoistVariableDeclaration, hoistFunctionDeclaration, - startLexicalEnvironment, - endLexicalEnvironment, - onSubstituteNode: (emitContext, node) => node, + requestEmitHelper, + readEmitHelpers, + onSubstituteNode: (_emitContext, node) => node, enableSubstitution, isSubstitutionEnabled, onEmitNode: (node, emitContext, emitCallback) => emitCallback(node, emitContext), @@ -265,11 +215,11 @@ namespace ts { function hoistVariableDeclaration(name: Identifier): void { Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); const decl = createVariableDeclaration(name); - if (!hoistedVariableDeclarations) { - hoistedVariableDeclarations = [decl]; + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; } else { - hoistedVariableDeclarations.push(decl); + lexicalEnvironmentVariableDeclarations.push(decl); } } @@ -278,11 +228,11 @@ namespace ts { */ function hoistFunctionDeclaration(func: FunctionDeclaration): void { Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = [func]; + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; } else { - hoistedFunctionDeclarations.push(func); + lexicalEnvironmentFunctionDeclarations.push(func); } } @@ -292,16 +242,31 @@ namespace ts { */ function startLexicalEnvironment(): void { Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); // Save the current lexical environment. Rather than resizing the array we adjust the // stack size variable. This allows us to reuse existing array slots we've // already allocated between transformations to avoid allocation and GC overhead during // transformation. - lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations; - lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations; + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; - hoistedVariableDeclarations = undefined; - hoistedFunctionDeclarations = undefined; + lexicalEnvironmentVariableDeclarations = undefined; + lexicalEnvironmentFunctionDeclarations = undefined; + } + + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + function suspendLexicalEnvironment(): void { + Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + function resumeLexicalEnvironment(): void { + Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase."); + Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; } /** @@ -310,17 +275,18 @@ namespace ts { */ function endLexicalEnvironment(): Statement[] { Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); let statements: Statement[]; - if (hoistedVariableDeclarations || hoistedFunctionDeclarations) { - if (hoistedFunctionDeclarations) { - statements = [...hoistedFunctionDeclarations]; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = [...lexicalEnvironmentFunctionDeclarations]; } - if (hoistedVariableDeclarations) { + if (lexicalEnvironmentVariableDeclarations) { const statement = createVariableStatement( /*modifiers*/ undefined, - createVariableDeclarationList(hoistedVariableDeclarations) + createVariableDeclarationList(lexicalEnvironmentVariableDeclarations) ); if (!statements) { @@ -334,9 +300,26 @@ namespace ts { // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; - hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; - hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + } return statements; } + + function requestEmitHelper(helper: EmitHelper): void { + Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + emitHelpers = append(emitHelpers, helper); + } + + function readEmitHelpers(): EmitHelper[] | undefined { + Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); + const helpers = emitHelpers; + emitHelpers = undefined; + return helpers; + } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index c7219866df7..8e32259ff0f 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -3,412 +3,397 @@ /*@internal*/ namespace ts { + interface FlattenContext { + context: TransformationContext; + level: FlattenLevel; + hoistTempVariables: boolean; + emitExpression: (value: Expression) => void; + emitBindingOrAssignment: (target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) => void; + createArrayBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ArrayBindingOrAssignmentPattern; + createObjectBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ObjectBindingOrAssignmentPattern; + createArrayBindingOrAssignmentElement: (node: Identifier) => BindingOrAssignmentElement; + visitor?: (node: Node) => VisitResult; + } + + export const enum FlattenLevel { + All, + ObjectRest, + } + /** - * Flattens a destructuring assignment expression. + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. * - * @param root The destructuring assignment expression. - * @param needsValue Indicates whether the value from the right-hand-side of the - * destructuring assignment is needed as part of a larger expression. - * @param recordTempVariable A callback used to record new temporary variables. - * @param visitor An optional visitor to use to visit expressions. + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. */ export function flattenDestructuringAssignment( + node: VariableDeclaration | DestructuringAssignment, + visitor: ((node: Node) => VisitResult) | undefined, context: TransformationContext, - node: BinaryExpression, - needsValue: boolean, - recordTempVariable: (node: Identifier) => void, - visitor?: (node: Node) => VisitResult): Expression { - - if (isEmptyObjectLiteralOrArrayLiteral(node.left)) { - const right = node.right; - if (isDestructuringAssignment(right)) { - return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor); - } - else { - return node.right; - } - } - + level: FlattenLevel, + needsValue?: boolean, + createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression { let location: TextRange = node; - let value = node.right; - const expressions: Expression[] = []; - if (needsValue) { - // If the right-hand value of the destructuring assignment needs to be preserved (as - // is the case when the destructuring assignmen) is part of a larger expression), - // then we need to cache the right-hand value. - // - // The source map location for the assignment should point to the entire binary - // expression. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor); - } - else if (nodeIsSynthesized(node)) { - // Generally, the source map location for a destructuring assignment is the root - // expression. - // - // However, if the root expression is synthesized (as in the case - // of the initializer when transforming a ForOfStatement), then the source map - // location should point to the right-hand value of the expression. - location = value; + let value: Expression; + if (isDestructuringAssignment(node)) { + value = node.right; + while (isEmptyObjectLiteralOrArrayLiteral(node.left)) { + if (isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } + else { + return value; + } + } } - flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor); + let expressions: Expression[]; + const flattenContext: FlattenContext = { + context, + level, + hoistTempVariables: true, + emitExpression, + emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern, + createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern, + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor + }; + + if (value) { + value = visitNode(value, visitor, isExpression); + if (needsValue) { + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + } + else if (nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. + location = value; + } + } + + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ isDestructuringAssignment(node)); + + if (value && needsValue) { + if (!some(expressions)) { + return value; + } - if (needsValue) { expressions.push(value); } - const expression = inlineExpressions(expressions); - aggregateTransformFlags(expression); - return expression; - - function emitAssignment(name: Identifier, value: Expression, location: TextRange) { - const expression = createAssignment(name, value, location); + return aggregateTransformFlags(inlineExpressions(expressions)) || createOmittedExpression(); + function emitExpression(expression: Expression) { // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. setEmitFlags(expression, EmitFlags.NoNestedSourceMaps); - aggregateTransformFlags(expression); - expressions.push(expression); + expressions = append(expressions, expression); } - function emitTempVariableAssignment(value: Expression, location: TextRange) { - const name = createTempVariable(recordTempVariable); - emitAssignment(name, value, location); - return name; - } - } - - /** - * Flattens binding patterns in a parameter declaration. - * - * @param node The ParameterDeclaration to flatten. - * @param value The rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. - */ - export function flattenParameterDestructuring( - context: TransformationContext, - node: ParameterDeclaration, - value: Expression, - visitor?: (node: Node) => VisitResult) { - const declarations: VariableDeclaration[] = []; - - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - - return declarations; - - function emitAssignment(name: Identifier, value: Expression, location: TextRange) { - const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location); - - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - setEmitFlags(declaration, EmitFlags.NoNestedSourceMaps); - - aggregateTransformFlags(declaration); - declarations.push(declaration); - } - - function emitTempVariableAssignment(value: Expression, location: TextRange) { - const name = createTempVariable(/*recordTempVariable*/ undefined); - emitAssignment(name, value, location); - return name; - } - } - - /** - * Flattens binding patterns in a variable declaration. - * - * @param node The VariableDeclaration to flatten. - * @param value An optional rhs value for the binding pattern. - * @param visitor An optional visitor to use to visit expressions. - */ - export function flattenVariableDestructuring( - context: TransformationContext, - node: VariableDeclaration, - value?: Expression, - visitor?: (node: Node) => VisitResult, - recordTempVariable?: (node: Identifier) => void) { - const declarations: VariableDeclaration[] = []; - - let pendingAssignments: Expression[]; - flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor); - - return declarations; - - function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) { - if (pendingAssignments) { - pendingAssignments.push(value); - value = inlineExpressions(pendingAssignments); - pendingAssignments = undefined; - } - - const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location); - declaration.original = original; - - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - setEmitFlags(declaration, EmitFlags.NoNestedSourceMaps); - - declarations.push(declaration); - aggregateTransformFlags(declaration); - } - - function emitTempVariableAssignment(value: Expression, location: TextRange) { - const name = createTempVariable(recordTempVariable); - if (recordTempVariable) { - const assignment = createAssignment(name, value, location); - if (pendingAssignments) { - pendingAssignments.push(assignment); - } - else { - pendingAssignments = [assignment]; - } - } - else { - emitAssignment(name, value, location, /*original*/ undefined); - } - return name; - } - } - - /** - * Flattens binding patterns in a variable declaration and transforms them into an expression. - * - * @param node The VariableDeclaration to flatten. - * @param recordTempVariable A callback used to record new temporary variables. - * @param nameSubstitution An optional callback used to substitute binding names. - * @param visitor An optional visitor to use to visit expressions. - */ - export function flattenVariableDestructuringToExpression( - context: TransformationContext, - node: VariableDeclaration, - recordTempVariable: (name: Identifier) => void, - nameSubstitution?: (name: Identifier) => Expression, - visitor?: (node: Node) => VisitResult) { - - const pendingAssignments: Expression[] = []; - - flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor); - - const expression = inlineExpressions(pendingAssignments); - aggregateTransformFlags(expression); - return expression; - - function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) { - const left = nameSubstitution && nameSubstitution(name) || name; - emitPendingAssignment(left, value, location, original); - } - - function emitTempVariableAssignment(value: Expression, location: TextRange) { - const name = createTempVariable(recordTempVariable); - emitPendingAssignment(name, value, location, /*original*/ undefined); - return name; - } - - function emitPendingAssignment(name: Expression, value: Expression, location: TextRange, original: Node) { - const expression = createAssignment(name, value, location); + function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) { + Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression); + const expression = createAssignmentCallback + ? createAssignmentCallback(target, value, location) + : createAssignment(visitNode(target, visitor, isExpression), value, location); expression.original = original; - - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - setEmitFlags(expression, EmitFlags.NoNestedSourceMaps); - - pendingAssignments.push(expression); - return expression; + emitExpression(expression); } } - function flattenDestructuring( + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ + export function flattenDestructuringBinding( + node: VariableDeclaration | ParameterDeclaration, + visitor: (node: Node) => VisitResult, context: TransformationContext, - root: VariableDeclaration | ParameterDeclaration | BindingElement | BinaryExpression, - value: Expression, + level: FlattenLevel, + rval?: Expression, + hoistTempVariables?: boolean, + skipInitializer?: boolean): VariableDeclaration[] { + let pendingExpressions: Expression[]; + const pendingDeclarations: { pendingExpressions?: Expression[], name: BindingName, value: Expression, location?: TextRange, original?: Node; }[] = []; + const declarations: VariableDeclaration[] = []; + const flattenContext: FlattenContext = { + context, + level, + hoistTempVariables, + emitExpression, + emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: makeArrayBindingPattern, + createObjectBindingOrAssignmentPattern: makeObjectBindingPattern, + createArrayBindingOrAssignmentElement: makeBindingElement, + visitor + }; + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + const temp = createTempVariable(/*recordTempVariable*/ undefined); + if (hoistTempVariables) { + const value = inlineExpressions(pendingExpressions); + pendingExpressions = undefined; + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + } + else { + context.hoistVariableDeclaration(temp); + const pendingDeclaration = lastOrUndefined(pendingDeclarations); + pendingDeclaration.pendingExpressions = append( + pendingDeclaration.pendingExpressions, + createAssignment(temp, pendingDeclaration.value) + ); + addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (const { pendingExpressions, name, value, location, original } of pendingDeclarations) { + const variable = createVariableDeclaration( + name, + /*type*/ undefined, + pendingExpressions ? inlineExpressions(append(pendingExpressions, value)) : value, + location); + variable.original = original; + if (isIdentifier(name)) { + setEmitFlags(variable, EmitFlags.NoNestedSourceMaps); + } + aggregateTransformFlags(variable); + declarations.push(variable); + } + return declarations; + + function emitExpression(value: Expression) { + pendingExpressions = append(pendingExpressions, value); + } + + function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) { + Debug.assertNode(target, isBindingName); + if (pendingExpressions) { + value = inlineExpressions(append(pendingExpressions, value)); + pendingExpressions = undefined; + } + pendingDeclarations.push({ pendingExpressions, name: target, value, location, original }); + } + } + + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ + function flattenBindingOrAssignmentElement( + flattenContext: FlattenContext, + element: BindingOrAssignmentElement, + value: Expression | undefined, location: TextRange, - emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void, - emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier, - visitor?: (node: Node) => VisitResult) { - if (value && visitor) { - value = visitNode(value, visitor, isExpression); - } - - if (isBinaryExpression(root)) { - emitDestructuringAssignment(root.left, value, location); - } - else { - emitBindingElement(root, value); - } - - function emitDestructuringAssignment(bindingTarget: Expression | ShorthandPropertyAssignment, value: Expression, location: TextRange) { - // When emitting target = value use source map node to highlight, including any temporary assignments needed for this - let target: Expression; - if (isShorthandPropertyAssignment(bindingTarget)) { - const initializer = visitor - ? visitNode(bindingTarget.objectAssignmentInitializer, visitor, isExpression) - : bindingTarget.objectAssignmentInitializer; - - if (initializer) { - value = createDefaultValueCheck(value, initializer, location); - } - - target = bindingTarget.name; - } - else if (isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === SyntaxKind.EqualsToken) { - const initializer = visitor - ? visitNode(bindingTarget.right, visitor, isExpression) - : bindingTarget.right; - - value = createDefaultValueCheck(value, initializer, location); - target = bindingTarget.left; - } - else { - target = bindingTarget; - } - - if (target.kind === SyntaxKind.ObjectLiteralExpression) { - emitObjectLiteralAssignment(target, value, location); - } - else if (target.kind === SyntaxKind.ArrayLiteralExpression) { - emitArrayLiteralAssignment(target, value, location); - } - else { - const name = getMutableClone(target); - setSourceMapRange(name, target); - setCommentRange(name, target); - emitAssignment(name, value, location, /*original*/ undefined); - } - } - - function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression, location: TextRange) { - const properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - - for (const p of properties) { - if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - const propName = (p).name; - const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? p : (p).initializer || propName; - // Assignment for target = value.propName should highligh whole property, hence use p as source map node - emitDestructuringAssignment(target, createDestructuringPropertyAccess(value, propName), p); - } - } - } - - function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) { - const elements = target.elements; - const numElements = elements.length; - if (numElements !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - } - - for (let i = 0; i < numElements; i++) { - const e = elements[i]; - if (e.kind !== SyntaxKind.OmittedExpression) { - // Assignment for target = value.propName should highligh whole property, hence use e as source map node - if (e.kind !== SyntaxKind.SpreadElementExpression) { - emitDestructuringAssignment(e, createElementAccess(value, createLiteral(i)), e); - } - else if (i === numElements - 1) { - emitDestructuringAssignment((e).expression, createArraySlice(value, i), e); - } - } - } - } - - function emitBindingElement(target: VariableDeclaration | ParameterDeclaration | BindingElement, value: Expression) { - // Any temporary assignments needed to emit target = value should point to target - const initializer = visitor ? visitNode(target.initializer, visitor, isExpression) : target.initializer; + skipInitializer?: boolean) { + if (!skipInitializer) { + const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression); if (initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, initializer, target) : initializer; + value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer value = createVoidZero(); } - - const name = target.name; - if (isBindingPattern(name)) { - const elements = name.elements; - const numElements = elements.length; - if (numElements !== 1) { - // For anything other than a single-element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. Additionally, if we have zero elements - // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, - // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment); - } - for (let i = 0; i < numElements; i++) { - const element = elements[i]; - if (isOmittedExpression(element)) { - continue; - } - else if (name.kind === SyntaxKind.ObjectBindingPattern) { - // Rewrite element to a declaration with an initializer that fetches property - const propName = element.propertyName || element.name; - emitBindingElement(element, createDestructuringPropertyAccess(value, propName)); - } - else { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, createElementAccess(value, i)); - } - else if (i === numElements - 1) { - emitBindingElement(element, createArraySlice(value, i)); - } - } - } - } - else { - emitAssignment(name, value, target, target); - } } - - function createDefaultValueCheck(value: Expression, defaultValue: Expression, location: TextRange): Expression { - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment); - return createConditional( - createStrictEquality(value, createVoidZero()), - createToken(SyntaxKind.QuestionToken), - defaultValue, - createToken(SyntaxKind.ColonToken), - value - ); + const bindingTarget = getTargetOfBindingOrAssignmentElement(element); + if (isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } + else if (isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } + else { + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + } + } - /** - * Creates either a PropertyAccessExpression or an ElementAccessExpression for the - * right-hand side of a transformed destructuring assignment. - * - * @param expression The right-hand expression that is the source of the property. - * @param propertyName The destructuring property name. - */ - function createDestructuringPropertyAccess(expression: Expression, propertyName: PropertyName): LeftHandSideExpression { - if (isComputedPropertyName(propertyName)) { - return createElementAccess( - expression, - ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment) - ); - } - else if (isLiteralExpression(propertyName)) { - const clone = getSynthesizedClone(propertyName); - clone.text = unescapeIdentifier(clone.text); - return createElementAccess(expression, clone); - } - else { - if (isGeneratedIdentifier(propertyName)) { - const clone = getSynthesizedClone(propertyName); - clone.text = unescapeIdentifier(clone.text); - return createPropertyAccess(expression, clone); + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ObjectBindingOrAssignmentPattern, value: Expression, location: TextRange) { + const elements = getElementsOfBindingOrAssignmentPattern(pattern); + const numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + let bindingElements: BindingOrAssignmentElement[]; + let computedTempVariables: Expression[]; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { + const propertyName = getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= FlattenLevel.ObjectRest + && !(element.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) + && !(getTargetOfBindingOrAssignmentElement(element).transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest)) + && !isComputedPropertyName(propertyName)) { + bindingElements = append(bindingElements, element); } else { - return createPropertyAccess(expression, createIdentifier(unescapeIdentifier(propertyName.text))); + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (isComputedPropertyName(propertyName)) { + computedTempVariables = append(computedTempVariables, (rhsValue as ElementAccessExpression).argumentExpression); + } + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } } + else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = undefined; + } + const rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + } + + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ + function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ArrayBindingOrAssignmentPattern, value: Expression, location: TextRange) { + const elements = getElementsOfBindingOrAssignmentPattern(pattern); + const numElements = elements.length; + if (numElements !== 1 && (flattenContext.level < FlattenLevel.ObjectRest || numElements === 0)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + let bindingElements: BindingOrAssignmentElement[]; + let restContainingElements: [Identifier, BindingOrAssignmentElement][]; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + if (flattenContext.level >= FlattenLevel.ObjectRest) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & TransformFlags.ContainsObjectRest) { + const temp = createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + + restContainingElements = append(restContainingElements, <[Identifier, BindingOrAssignmentElement]>[temp, element]); + bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } + else { + bindingElements = append(bindingElements, element); + } + } + else if (isOmittedExpression(element)) { + continue; + } + else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { + const rhsValue = createElementAccess(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + else if (i === numElements - 1) { + const rhsValue = createArraySlice(value, i); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (const [id, element] of restContainingElements) { + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } + } + + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ + function createDefaultValueCheck(flattenContext: FlattenContext, value: Expression, defaultValue: Expression, location: TextRange): Expression { + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + return createConditional(createTypeCheck(value, "undefined"), defaultValue, value); + } + + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ + function createDestructuringPropertyAccess(flattenContext: FlattenContext, value: Expression, propertyName: PropertyName): LeftHandSideExpression { + if (isComputedPropertyName(propertyName)) { + const argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + return createElementAccess(value, argumentExpression); + } + else if (isStringOrNumericLiteral(propertyName)) { + const argumentExpression = getSynthesizedClone(propertyName); + argumentExpression.text = unescapeIdentifier(argumentExpression.text); + return createElementAccess(value, argumentExpression); + } + else { + const name = createIdentifier(unescapeIdentifier(propertyName.text)); + return createPropertyAccess(value, name); } } @@ -417,29 +402,96 @@ namespace ts { * This function is useful to ensure that the expression's value can be read from in subsequent expressions. * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. * + * @param flattenContext Options used to control flattening. * @param value the expression whose value needs to be bound. * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; - * false if it is necessary to always emit an identifier. + * false if it is necessary to always emit an identifier. * @param location The location to use for source maps and comments. - * @param emitTempVariableAssignment A callback used to emit a temporary variable. - * @param visitor An optional callback used to visit the value. */ - function ensureIdentifier( - value: Expression, - reuseIdentifierExpressions: boolean, - location: TextRange, - emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier, - visitor?: (node: Node) => VisitResult) { - + function ensureIdentifier(flattenContext: FlattenContext, value: Expression, reuseIdentifierExpressions: boolean, location: TextRange) { if (isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - if (visitor) { - value = visitNode(value, visitor, isExpression); + const temp = createTempVariable(/*recordTempVariable*/ undefined); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(createAssignment(temp, value, location)); } - - return emitTempVariableAssignment(value, location); + else { + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + } + return temp; } } + + function makeArrayBindingPattern(elements: BindingOrAssignmentElement[]) { + Debug.assertEachNode(elements, isArrayBindingElement); + return createArrayBindingPattern(elements); + } + + function makeArrayAssignmentPattern(elements: BindingOrAssignmentElement[]) { + return createArrayLiteral(map(elements, convertToArrayAssignmentElement)); + } + + function makeObjectBindingPattern(elements: BindingOrAssignmentElement[]) { + Debug.assertEachNode(elements, isBindingElement); + return createObjectBindingPattern(elements); + } + + function makeObjectAssignmentPattern(elements: BindingOrAssignmentElement[]) { + return createObjectLiteral(map(elements, convertToObjectAssignmentElement)); + } + + function makeBindingElement(name: Identifier) { + return createBindingElement(/*propertyName*/ undefined, /*dotDotDotToken*/ undefined, name); + } + + function makeAssignmentElement(name: Identifier) { + return name; + } + + const restHelper: EmitHelper = { + name: "typescript:rest", + scoped: false, + text: ` + var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; + };` + }; + + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/ + function createRestCall(context: TransformationContext, value: Expression, elements: BindingOrAssignmentElement[], computedTempVariables: Expression[], location: TextRange): Expression { + context.requestEmitHelper(restHelper); + const propertyNames: Expression[] = []; + let computedTempVariableOffset = 0; + for (let i = 0; i < elements.length - 1; i++) { + const propertyName = getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (isComputedPropertyName(propertyName)) { + const temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" + propertyNames.push( + createConditional( + createTypeCheck(temp, "symbol"), + temp, + createAdd(temp, createLiteral("")) + ) + ); + } + else { + propertyNames.push(createLiteral(propertyName)); + } + } + } + return createCall(getHelperName("__rest"), undefined, [value, createArrayLiteral(propertyNames, location)]); + } } diff --git a/src/compiler/transformers/es6.ts b/src/compiler/transformers/es2015.ts similarity index 85% rename from src/compiler/transformers/es6.ts rename to src/compiler/transformers/es2015.ts index 8d8a817c183..5dae1da7b74 100644 --- a/src/compiler/transformers/es6.ts +++ b/src/compiler/transformers/es2015.ts @@ -3,8 +3,7 @@ /*@internal*/ namespace ts { - - const enum ES6SubstitutionFlags { + const enum ES2015SubstitutionFlags { /** Enables substitutions for captured `this` */ CapturedThis = 1 << 0, /** Enables substitutions for block-scoped bindings. */ @@ -163,9 +162,10 @@ namespace ts { ReplaceWithReturn, } - export function transformES6(context: TransformationContext) { + export function transformES2015(context: TransformationContext) { const { startLexicalEnvironment, + resumeLexicalEnvironment, endLexicalEnvironment, hoistVariableDeclaration, } = context; @@ -186,6 +186,7 @@ namespace ts { let enclosingFunction: FunctionLikeDeclaration; let enclosingNonArrowFunction: FunctionLikeDeclaration; let enclosingNonAsyncFunctionBody: FunctionLikeDeclaration | ClassElement; + let isInConstructorWithCapturedSuper: boolean; /** * Used to track if we are emitting body of the converted loop @@ -197,7 +198,7 @@ namespace ts { * They are persisted between each SourceFile transformation and should not * be reset. */ - let enabledSubstitutions: ES6SubstitutionFlags; + let enabledSubstitutions: ES2015SubstitutionFlags; return transformSourceFile; @@ -208,7 +209,13 @@ namespace ts { currentSourceFile = node; currentText = node.text; - return visitNode(node, visitor, isSourceFile); + + const visited = saveStateAndInvoke(node, visitSourceFile); + addEmitHelpers(visited, context.readEmitHelpers()); + + currentSourceFile = undefined; + currentText = undefined; + return visited; } function visitor(node: Node): VisitResult { @@ -231,14 +238,17 @@ namespace ts { const savedCurrentParent = currentParent; const savedCurrentNode = currentNode; const savedConvertedLoopState = convertedLoopState; + const savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper; if (nodeStartsNewLexicalEnvironment(node)) { - // don't treat content of nodes that start new lexical environment as part of converted loop copy + // don't treat content of nodes that start new lexical environment as part of converted loop copy or constructor body + isInConstructorWithCapturedSuper = false; convertedLoopState = undefined; } onBeforeVisitNode(node); const visited = f(node); + isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper; convertedLoopState = savedConvertedLoopState; enclosingFunction = savedEnclosingFunction; enclosingNonArrowFunction = savedEnclosingNonArrowFunction; @@ -251,17 +261,72 @@ namespace ts { return visited; } + function onBeforeVisitNode(node: Node) { + if (currentNode) { + if (isBlockScope(currentNode, currentParent)) { + enclosingBlockScopeContainer = currentNode; + enclosingBlockScopeContainerParent = currentParent; + } + + if (isFunctionLike(currentNode)) { + enclosingFunction = currentNode; + if (currentNode.kind !== SyntaxKind.ArrowFunction) { + enclosingNonArrowFunction = currentNode; + if (!(getEmitFlags(currentNode) & EmitFlags.AsyncFunctionBody)) { + enclosingNonAsyncFunctionBody = currentNode; + } + } + } + + // keep track of the enclosing variable statement when in the context of + // variable statements, variable declarations, binding elements, and binding + // patterns. + switch (currentNode.kind) { + case SyntaxKind.VariableStatement: + enclosingVariableStatement = currentNode; + break; + + case SyntaxKind.VariableDeclarationList: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.BindingElement: + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + break; + + default: + enclosingVariableStatement = undefined; + } + } + + currentParent = currentNode; + currentNode = node; + } + + function returnCapturedThis(node: Node): Node { + return setOriginalNode(createReturn(createIdentifier("_this")), node); + } + + function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean { + return isInConstructorWithCapturedSuper && node.kind === SyntaxKind.ReturnStatement && !(node).expression; + } + function shouldCheckNode(node: Node): boolean { - return (node.transformFlags & TransformFlags.ES6) !== 0 || + return (node.transformFlags & TransformFlags.ES2015) !== 0 || node.kind === SyntaxKind.LabeledStatement || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); } function visitorWorker(node: Node): VisitResult { - if (shouldCheckNode(node)) { + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + else if (shouldCheckNode(node)) { return visitJavaScript(node); } - else if (node.transformFlags & TransformFlags.ContainsES6) { + else if (node.transformFlags & TransformFlags.ContainsES2015 || (isInConstructorWithCapturedSuper && !isExpression(node))) { + // we want to dive in this branch either if node has children with ES2015 specific syntax + // or we are inside constructor that captures result of the super call so all returns without expression should be + // rewritten. Note: we skip expressions since returns should never appear there return visitEachChild(node, visitor, context); } else { @@ -283,6 +348,7 @@ namespace ts { function visitNodesInConvertedLoop(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.ReturnStatement: + node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node; return visitReturnStatement(node); case SyntaxKind.VariableStatement: @@ -308,8 +374,8 @@ namespace ts { function visitJavaScript(node: Node): VisitResult { switch (node.kind) { - case SyntaxKind.ExportKeyword: - return node; + case SyntaxKind.StaticKeyword: + return undefined; // elide static keyword case SyntaxKind.ClassDeclaration: return visitClassDeclaration(node); @@ -362,6 +428,9 @@ namespace ts { case SyntaxKind.ObjectLiteralExpression: return visitObjectLiteralExpression(node); + case SyntaxKind.CatchClause: + return visitCatchClause(node); + case SyntaxKind.ShorthandPropertyAssignment: return visitShorthandPropertyAssignment(node); @@ -395,8 +464,11 @@ namespace ts { case SyntaxKind.YieldExpression: return visitYieldExpression(node); + case SyntaxKind.SpreadElement: + return visitSpreadElement(node); + case SyntaxKind.SuperKeyword: - return visitSuperKeyword(node); + return visitSuperKeyword(); case SyntaxKind.YieldExpression: // `yield` will be handled by a generators transform. @@ -405,9 +477,6 @@ namespace ts { case SyntaxKind.MethodDeclaration: return visitMethodDeclaration(node); - case SyntaxKind.SourceFile: - return visitSourceFileNode(node); - case SyntaxKind.VariableStatement: return visitVariableStatement(node); @@ -415,48 +484,19 @@ namespace ts { Debug.failBadSyntaxKind(node); return visitEachChild(node, visitor, context); } - } - function onBeforeVisitNode(node: Node) { - if (currentNode) { - if (isBlockScope(currentNode, currentParent)) { - enclosingBlockScopeContainer = currentNode; - enclosingBlockScopeContainerParent = currentParent; - } - - if (isFunctionLike(currentNode)) { - enclosingFunction = currentNode; - if (currentNode.kind !== SyntaxKind.ArrowFunction) { - enclosingNonArrowFunction = currentNode; - if (!(getEmitFlags(currentNode) & EmitFlags.AsyncFunctionBody)) { - enclosingNonAsyncFunctionBody = currentNode; - } - } - } - - // keep track of the enclosing variable statement when in the context of - // variable statements, variable declarations, binding elements, and binding - // patterns. - switch (currentNode.kind) { - case SyntaxKind.VariableStatement: - enclosingVariableStatement = currentNode; - break; - - case SyntaxKind.VariableDeclarationList: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.BindingElement: - case SyntaxKind.ObjectBindingPattern: - case SyntaxKind.ArrayBindingPattern: - break; - - default: - enclosingVariableStatement = undefined; - } - } - - currentParent = currentNode; - currentNode = node; + function visitSourceFile(node: SourceFile): SourceFile { + const statements: Statement[] = []; + startLexicalEnvironment(); + const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); + addCaptureThisForNodeIfNeeded(statements, node); + addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); + addRange(statements, endLexicalEnvironment()); + return updateSourceFileNode( + node, + createNodeArray(statements, node.statements) + ); } function visitSwitchStatement(node: SwitchStatement): SwitchStatement { @@ -584,47 +624,39 @@ namespace ts { // return C; // }()); - const modifierFlags = getModifierFlags(node); - const isExported = modifierFlags & ModifierFlags.Export; - const isDefault = modifierFlags & ModifierFlags.Default; - - // Add an `export` modifier to the statement if needed (for `--target es5 --module es6`) - const modifiers = isExported && !isDefault - ? filter(node.modifiers, isExportModifier) - : undefined; - - const statement = createVariableStatement( - modifiers, - createVariableDeclarationList([ - createVariableDeclaration( - getDeclarationName(node, /*allowComments*/ true), - /*type*/ undefined, - transformClassLikeDeclarationToExpression(node) - ) - ]), - /*location*/ node + const variable = createVariableDeclaration( + getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, + transformClassLikeDeclarationToExpression(node) ); + setOriginalNode(variable, node); + + const statements: Statement[] = []; + const statement = createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList([variable]), /*location*/ node); + setOriginalNode(statement, node); startOnNewLine(statement); + statements.push(statement); // Add an `export default` statement for default exports (for `--target es5 --module es6`) - if (isExported && isDefault) { - const statements: Statement[] = [statement]; - statements.push(createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, - getDeclarationName(node, /*allowComments*/ false) - )); - return statements; + if (hasModifier(node, ModifierFlags.Export)) { + const exportStatement = hasModifier(node, ModifierFlags.Default) + ? createExportDefault(getLocalName(node)) + : createExternalModuleExport(getLocalName(node)); + + setOriginalNode(exportStatement, statement); + statements.push(exportStatement); } - return statement; - } + const emitFlags = getEmitFlags(node); + if ((emitFlags & EmitFlags.HasEndOfDeclarationMarker) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(createEndOfDeclarationMarker(node)); + setEmitFlags(statement, emitFlags | EmitFlags.HasEndOfDeclarationMarker); + } - function isExportModifier(node: Modifier) { - return node.kind === SyntaxKind.ExportKeyword; + return singleOrMany(statements); } /** @@ -681,10 +713,11 @@ namespace ts { const extendsClauseElement = getClassExtendsHeritageClauseElement(node); const classFunction = createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - extendsClauseElement ? [createParameter("_super")] : [], + extendsClauseElement ? [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement) ); @@ -763,7 +796,7 @@ namespace ts { if (extendsClauseElement) { statements.push( createStatement( - createExtendsHelper(currentSourceFile.externalHelpersModuleName, getDeclarationName(node)), + createExtendsHelper(context, getLocalName(node)), /*location*/ extendsClauseElement ) ); @@ -807,17 +840,14 @@ namespace ts { * @param hasSynthesizedSuper A value indicating whether the constructor starts with a * synthesized `super` call. */ - function transformConstructorParameters(constructor: ConstructorDeclaration, hasSynthesizedSuper: boolean): ParameterDeclaration[] { + function transformConstructorParameters(constructor: ConstructorDeclaration, hasSynthesizedSuper: boolean) { // If the TypeScript transformer needed to synthesize a constructor for property // initializers, it would have also added a synthetic `...args` parameter and // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - if (constructor && !hasSynthesizedSuper) { - return visitNodes(constructor.parameters, visitor, isParameter); - } - - return []; + return visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + || []; } /** @@ -831,14 +861,14 @@ namespace ts { */ function transformConstructorBody(constructor: ConstructorDeclaration | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments, hasSynthesizedSuper: boolean) { const statements: Statement[] = []; - startLexicalEnvironment(); + resumeLexicalEnvironment(); let statementOffset = -1; if (hasSynthesizedSuper) { // If a super call has already been synthesized, // we're going to assume that we should just transform everything after that. // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 1; + statementOffset = 0; } else if (constructor) { // Otherwise, try to emit all potential prologue directives first. @@ -860,7 +890,10 @@ namespace ts { } if (constructor) { - const body = saveStateAndInvoke(constructor, constructor => visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset)); + const body = saveStateAndInvoke(constructor, constructor => { + isInConstructorWithCapturedSuper = superCaptureStatus === SuperCaptureResult.ReplaceSuperCapture; + return visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset); + }); addRange(statements, body); } @@ -991,9 +1024,25 @@ namespace ts { } } - // Return the result if we have an immediate super() call on the last statement. - if (superCallExpression && statementOffset === ctorStatements.length - 1) { - statements.push(createReturn(superCallExpression)); + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. + if (superCallExpression + && statementOffset === ctorStatements.length - 1 + && !(ctor.transformFlags & (TransformFlags.ContainsLexicalThis | TransformFlags.ContainsCapturedLexicalThis))) { + const returnStatement = createReturn(superCallExpression); + + if (superCallExpression.kind !== SyntaxKind.BinaryExpression + || (superCallExpression as BinaryExpression).left.kind !== SyntaxKind.CallExpression) { + Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); + } + + // Shift comments from the original super call to the return statement. + setCommentRange(returnStatement, getCommentRange( + setEmitFlags( + (superCallExpression as BinaryExpression).left, + EmitFlags.NoComments))); + + statements.push(returnStatement); return SuperCaptureResult.ReplaceWithReturn; } @@ -1034,7 +1083,12 @@ namespace ts { // evaluated inside the function body. return setOriginalNode( createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined, /*location*/ node ), @@ -1045,7 +1099,12 @@ namespace ts { // Initializers are elided return setOriginalNode( createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined, /*location*/ node ), @@ -1117,7 +1176,13 @@ namespace ts { createVariableStatement( /*modifiers*/ undefined, createVariableDeclarationList( - flattenParameterDestructuring(context, parameter, temp, visitor) + flattenDestructuringBinding( + parameter, + visitor, + context, + FlattenLevel.All, + temp + ) ) ), EmitFlags.CustomPrologue @@ -1150,10 +1215,7 @@ namespace ts { function addDefaultValueAssignmentForInitializer(statements: Statement[], parameter: ParameterDeclaration, name: Identifier, initializer: Expression): void { initializer = visitNode(initializer, visitor, isExpression); const statement = createIf( - createStrictEquality( - getSynthesizedClone(name), - createVoidZero() - ), + createTypeCheck(getSynthesizedClone(name), "undefined"), setEmitFlags( createBlock([ createStatement( @@ -1247,7 +1309,9 @@ namespace ts { createAssignment( createElementAccess( expressionName, - createSubtract(temp, createLiteral(restIndex)) + restIndex === 0 + ? temp + : createSubtract(temp, createLiteral(restIndex)) ), createElementAccess(createIdentifier("arguments"), temp) ), @@ -1349,20 +1413,13 @@ namespace ts { function transformClassMethodDeclarationToStatement(receiver: LeftHandSideExpression, member: MethodDeclaration) { const commentRange = getCommentRange(member); const sourceMapRange = getSourceMapRange(member); - - const func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setEmitFlags(func, EmitFlags.NoComments); - setSourceMapRange(func, sourceMapRange); + const memberName = createMemberAccessForPropertyName(receiver, visitNode(member.name, visitor, isPropertyName), /*location*/ member.name); + const memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); + setEmitFlags(memberFunction, EmitFlags.NoComments); + setSourceMapRange(memberFunction, sourceMapRange); const statement = createStatement( - createAssignment( - createMemberAccessForPropertyName( - receiver, - visitNode(member.name, visitor, isPropertyName), - /*location*/ member.name - ), - func - ), + createAssignment(memberName, memberFunction), /*location*/ member ); @@ -1416,6 +1473,7 @@ namespace ts { if (getAccessor) { const getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + setEmitFlags(getterFunction, EmitFlags.NoLeadingComments); const getter = createPropertyAssignment("get", getterFunction); setCommentRange(getter, getCommentRange(getAccessor)); properties.push(getter); @@ -1424,6 +1482,7 @@ namespace ts { if (setAccessor) { const setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + setEmitFlags(setterFunction, EmitFlags.NoLeadingComments); const setter = createPropertyAssignment("set", setterFunction); setCommentRange(setter, getCommentRange(setAccessor)); properties.push(setter); @@ -1458,8 +1517,17 @@ namespace ts { if (node.transformFlags & TransformFlags.ContainsLexicalThis) { enableSubstitutionsForCapturedThis(); } - - const func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); + const func = createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node), + node + ); + setOriginalNode(func, node); setEmitFlags(func, EmitFlags.CapturesThis); return func; } @@ -1470,7 +1538,17 @@ namespace ts { * @param node a FunctionExpression node. */ function visitFunctionExpression(node: FunctionExpression): Expression { - return transformFunctionLikeToExpression(node, /*location*/ node, node.name); + return updateFunctionExpression( + node, + /*modifiers*/ undefined, + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + node.transformFlags & TransformFlags.ES2015 + ? transformFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); } /** @@ -1479,19 +1557,18 @@ namespace ts { * @param node a FunctionDeclaration node. */ function visitFunctionDeclaration(node: FunctionDeclaration): FunctionDeclaration { - return setOriginalNode( - createFunctionDeclaration( - /*decorators*/ undefined, - node.modifiers, - node.asteriskToken, - node.name, - /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), - /*type*/ undefined, - transformFunctionBody(node), - /*location*/ node - ), - /*original*/ node); + return updateFunctionDeclaration( + node, + /*decorators*/ undefined, + node.modifiers, + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + node.transformFlags & TransformFlags.ES2015 + ? transformFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); } /** @@ -1509,10 +1586,11 @@ namespace ts { const expression = setOriginalNode( createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location @@ -1539,7 +1617,7 @@ namespace ts { const body = node.body; let statementOffset: number; - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array @@ -1593,7 +1671,7 @@ namespace ts { closeBraceLocation = body; } - const lexicalEnvironment = endLexicalEnvironment(); + const lexicalEnvironment = context.endLexicalEnvironment(); addRange(statements, lexicalEnvironment); // If we added any final generated statements, this must be a multi-line block @@ -1619,20 +1697,14 @@ namespace ts { * * @param node An ExpressionStatement node. */ - function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement { + function visitExpressionStatement(node: ExpressionStatement): Statement { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { case SyntaxKind.ParenthesizedExpression: - return updateStatement(node, - visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false) - ); - + return updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); case SyntaxKind.BinaryExpression: - return updateStatement(node, - visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false) - ); + return updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } - return visitEachChild(node, visitor, context); } @@ -1645,22 +1717,14 @@ namespace ts { */ function visitParenthesizedExpression(node: ParenthesizedExpression, needsDestructuringValue: boolean): ParenthesizedExpression { // If we are here it is most likely because our expression is a destructuring assignment. - if (needsDestructuringValue) { + if (!needsDestructuringValue) { switch (node.expression.kind) { case SyntaxKind.ParenthesizedExpression: - return createParen( - visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node - ); - + return updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); case SyntaxKind.BinaryExpression: - return createParen( - visitBinaryExpression(node.expression, /*needsDestructuringValue*/ true), - /*location*/ node - ); + return updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } - return visitEachChild(node, visitor, context); } @@ -1673,8 +1737,14 @@ namespace ts { */ function visitBinaryExpression(node: BinaryExpression, needsDestructuringValue: boolean): Expression { // If we are here it is because this is a destructuring assignment. - Debug.assert(isDestructuringAssignment(node)); - return flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor); + if (isDestructuringAssignment(node)) { + return flattenDestructuringAssignment( + node, + visitor, + context, + FlattenLevel.All, + needsDestructuringValue); + } } function visitVariableStatement(node: VariableStatement): Statement { @@ -1686,7 +1756,12 @@ namespace ts { if (decl.initializer) { let assignment: Expression; if (isBindingPattern(decl.name)) { - assignment = flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); + assignment = flattenDestructuringAssignment( + decl, + visitor, + context, + FlattenLevel.All + ); } else { assignment = createBinary(decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression)); @@ -1837,10 +1912,16 @@ namespace ts { function visitVariableDeclaration(node: VariableDeclaration): VisitResult { // If we are here it is because the name contains a binding pattern. if (isBindingPattern(node.name)) { - const recordTempVariablesInLine = !enclosingVariableStatement - || !hasModifier(enclosingVariableStatement, ModifierFlags.Export); - return flattenVariableDestructuring(context, node, /*value*/ undefined, visitor, - recordTempVariablesInLine ? undefined : hoistVariableDeclaration); + const hoistTempVariables = enclosingVariableStatement + && hasModifier(enclosingVariableStatement, ModifierFlags.Export); + return flattenDestructuringBinding( + node, + visitor, + context, + FlattenLevel.All, + /*value*/ undefined, + hoistTempVariables + ); } return visitEachChild(node, visitor, context); @@ -1929,6 +2010,7 @@ namespace ts { const rhsReference = expression.kind === SyntaxKind.Identifier ? createUniqueName((expression).text) : createTempVariable(/*recordTempVariable*/ undefined); + const elementAccess = createElementAccess(rhsReference, counter); // Initialize LHS // var v = _a[_i]; @@ -1941,11 +2023,12 @@ namespace ts { if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. - const declarations = flattenVariableDestructuring( - context, + const declarations = flattenDestructuringBinding( firstOriginalDeclaration, - createElementAccess(rhsReference, counter), - visitor + visitor, + context, + FlattenLevel.All, + elementAccess ); const declarationList = createVariableDeclarationList(declarations, /*location*/ initializer); @@ -1970,13 +2053,16 @@ namespace ts { statements.push( createVariableStatement( /*modifiers*/ undefined, - createVariableDeclarationList([ - createVariableDeclaration( - firstOriginalDeclaration ? firstOriginalDeclaration.name : createTempVariable(/*recordTempVariable*/ undefined), - /*type*/ undefined, - createElementAccess(rhsReference, counter) - ) - ], /*location*/ moveRangePos(initializer, -1)), + setOriginalNode( + createVariableDeclarationList([ + createVariableDeclaration( + firstOriginalDeclaration ? firstOriginalDeclaration.name : createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, + createElementAccess(rhsReference, counter) + ) + ], /*location*/ moveRangePos(initializer, -1)), + initializer + ), /*location*/ moveRangeEnd(initializer, -1) ) ); @@ -1985,17 +2071,16 @@ namespace ts { else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - const assignment = createAssignment(initializer, createElementAccess(rhsReference, counter)); + const assignment = createAssignment(initializer, elementAccess); if (isDestructuringAssignment(assignment)) { // This is a destructuring pattern, so we flatten the destructuring instead. statements.push( createStatement( flattenDestructuringAssignment( - context, assignment, - /*needsValue*/ false, - hoistVariableDeclaration, - visitor + visitor, + context, + FlattenLevel.All ) ) ); @@ -2038,10 +2123,13 @@ namespace ts { setEmitFlags(body, EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps); const forStatement = createFor( - createVariableDeclarationList([ - createVariableDeclaration(counter, /*type*/ undefined, createLiteral(0), /*location*/ moveRangePos(node.expression, -1)), - createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) - ], /*location*/ node.expression), + setEmitFlags( + createVariableDeclarationList([ + createVariableDeclaration(counter, /*type*/ undefined, createLiteral(0), /*location*/ moveRangePos(node.expression, -1)), + createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) + ], /*location*/ node.expression), + EmitFlags.NoHoisting + ), createLessThan( counter, createPropertyAccess(rhsReference, "length"), @@ -2201,18 +2289,26 @@ namespace ts { } } - let loopBody = visitNode(node.statement, visitor, isStatement); + startLexicalEnvironment(); + let loopBody = visitNode(node.statement, visitor, isStatement, /*optional*/ false, liftToBlock); + const lexicalEnvironment = endLexicalEnvironment(); const currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { const statements = isBlock(loopBody) ? (loopBody).statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, CopyDirection.ToOutParameter, statements); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, CopyDirection.ToOutParameter, statements); + } + addRange(statements, lexicalEnvironment) loopBody = createBlock(statements, /*location*/ undefined, /*multiline*/ true); } - if (!isBlock(loopBody)) { + if (isBlock(loopBody)) { + loopBody.multiLine = true; + } + else { loopBody = createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); } @@ -2233,24 +2329,28 @@ namespace ts { const convertedLoopVariable = createVariableStatement( /*modifiers*/ undefined, - createVariableDeclarationList( - [ - createVariableDeclaration( - functionName, - /*type*/ undefined, - setEmitFlags( - createFunctionExpression( - isAsyncBlockContainingAwait ? createToken(SyntaxKind.AsteriskToken) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - loopParameters, - /*type*/ undefined, - loopBody - ), - loopBodyFlags + setEmitFlags( + createVariableDeclarationList( + [ + createVariableDeclaration( + functionName, + /*type*/ undefined, + setEmitFlags( + createFunctionExpression( + /*modifiers*/ undefined, + isAsyncBlockContainingAwait ? createToken(SyntaxKind.AsteriskToken) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + loopParameters, + /*type*/ undefined, + loopBody + ), + loopBodyFlags + ) ) - ) - ] + ] + ), + EmitFlags.NoHoisting ) ); @@ -2501,7 +2601,7 @@ namespace ts { } } else { - loopParameters.push(createParameter(name)); + loopParameters.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & NodeCheckFlags.NeedsLoopOutParameter) { const outParamName = createUniqueName("out_" + name.text); loopOutParameters.push({ originalName: name, outParamName }); @@ -2534,15 +2634,15 @@ namespace ts { break; case SyntaxKind.PropertyAssignment: - expressions.push(transformPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; case SyntaxKind.ShorthandPropertyAssignment: - expressions.push(transformShorthandPropertyAssignmentToExpression(node, property, receiver, node.multiLine)); + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; case SyntaxKind.MethodDeclaration: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(node, property, receiver, node.multiLine)); + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine)); break; default: @@ -2559,7 +2659,7 @@ namespace ts { * @param property The PropertyAssignment node. * @param receiver The receiver for the assignment. */ - function transformPropertyAssignmentToExpression(node: ObjectLiteralExpression, property: PropertyAssignment, receiver: Expression, startsOnNewLine: boolean) { + function transformPropertyAssignmentToExpression(property: PropertyAssignment, receiver: Expression, startsOnNewLine: boolean) { const expression = createAssignment( createMemberAccessForPropertyName( receiver, @@ -2581,7 +2681,7 @@ namespace ts { * @param property The ShorthandPropertyAssignment node. * @param receiver The receiver for the assignment. */ - function transformShorthandPropertyAssignmentToExpression(node: ObjectLiteralExpression, property: ShorthandPropertyAssignment, receiver: Expression, startsOnNewLine: boolean) { + function transformShorthandPropertyAssignmentToExpression(property: ShorthandPropertyAssignment, receiver: Expression, startsOnNewLine: boolean) { const expression = createAssignment( createMemberAccessForPropertyName( receiver, @@ -2603,7 +2703,7 @@ namespace ts { * @param method The MethodDeclaration node. * @param receiver The receiver for the assignment. */ - function transformObjectLiteralMethodDeclarationToExpression(node: ObjectLiteralExpression, method: MethodDeclaration, receiver: Expression, startsOnNewLine: boolean) { + function transformObjectLiteralMethodDeclarationToExpression(method: MethodDeclaration, receiver: Expression, startsOnNewLine: boolean) { const expression = createAssignment( createMemberAccessForPropertyName( receiver, @@ -2618,6 +2718,30 @@ namespace ts { return expression; } + function visitCatchClause(node: CatchClause): CatchClause { + Debug.assert(isBindingPattern(node.variableDeclaration.name)); + + const temp = createTempVariable(undefined); + const newVariableDeclaration = createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration); + + const vars = flattenDestructuringBinding( + node.variableDeclaration, + visitor, + context, + FlattenLevel.All, + temp + ); + const list = createVariableDeclarationList(vars, /*location*/node.variableDeclaration, /*flags*/node.variableDeclaration.flags); + const destructure = createVariableStatement(undefined, list); + + return updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } + + function addStatementToStartOfBlock(block: Block, statement: Statement): Block { + const transformedStatements = visitNodes(block.statements, visitor, isStatement); + return updateBlock(block, [statement].concat(transformedStatements)); + } + /** * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a * PropertyAssignment. @@ -2693,7 +2817,7 @@ namespace ts { setEmitFlags(thisArg, EmitFlags.NoSubstitution); } let resultingCall: CallExpression | BinaryExpression; - if (node.transformFlags & TransformFlags.ContainsSpreadElementExpression) { + if (node.transformFlags & TransformFlags.ContainsSpread) { // [source] // f(...a, b) // x.m(...a, b) @@ -2724,7 +2848,6 @@ namespace ts { // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = createFunctionCall( visitNode(target, visitor, isExpression), visitNode(thisArg, visitor, isExpression), @@ -2755,7 +2878,7 @@ namespace ts { */ function visitNewExpression(node: NewExpression): LeftHandSideExpression { // We are here because we contain a SpreadElementExpression. - Debug.assert((node.transformFlags & TransformFlags.ContainsSpreadElementExpression) !== 0); + Debug.assert((node.transformFlags & TransformFlags.ContainsSpread) !== 0); // [source] // new C(...a) @@ -2776,7 +2899,7 @@ namespace ts { } /** - * Transforms an array of Expression nodes that contains a SpreadElementExpression. + * Transforms an array of Expression nodes that contains a SpreadExpression. * * @param elements The array of Expression nodes. * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. @@ -2793,14 +2916,14 @@ namespace ts { // expressions into an array literal. const numElements = elements.length; const segments = flatten( - spanMap(elements, partitionSpreadElement, (partition, visitPartition, start, end) => + spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements) ) ); if (segments.length === 1) { const firstElement = elements[0]; - return needsUniqueCopy && isSpreadElementExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression + return needsUniqueCopy && isSpreadExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression ? createArraySlice(segments[0]) : segments[0]; } @@ -2809,17 +2932,17 @@ namespace ts { return createArrayConcat(segments.shift(), segments); } - function partitionSpreadElement(node: Expression) { - return isSpreadElementExpression(node) - ? visitSpanOfSpreadElements - : visitSpanOfNonSpreadElements; + function partitionSpread(node: Expression) { + return isSpreadExpression(node) + ? visitSpanOfSpreads + : visitSpanOfNonSpreads; } - function visitSpanOfSpreadElements(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult { - return map(chunk, visitExpressionOfSpreadElement); + function visitSpanOfSpreads(chunk: Expression[]): VisitResult { + return map(chunk, visitExpressionOfSpread); } - function visitSpanOfNonSpreadElements(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult { + function visitSpanOfNonSpreads(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult { return createArrayLiteral( visitNodes(createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, isExpression), /*location*/ undefined, @@ -2827,12 +2950,16 @@ namespace ts { ); } + function visitSpreadElement(node: SpreadElement) { + return visitNode(node.expression, visitor, isExpression); + } + /** - * Transforms the expression of a SpreadElementExpression node. + * Transforms the expression of a SpreadExpression node. * - * @param node A SpreadElementExpression node. + * @param node A SpreadExpression node. */ - function visitExpressionOfSpreadElement(node: SpreadElementExpression) { + function visitExpressionOfSpread(node: SpreadElement) { return visitNode(node.expression, visitor, isExpression); } @@ -3004,7 +3131,7 @@ namespace ts { /** * Visits the `super` keyword */ - function visitSuperKeyword(node: PrimaryExpression): LeftHandSideExpression { + function visitSuperKeyword(): LeftHandSideExpression { return enclosingNonAsyncFunctionBody && isClassElement(enclosingNonAsyncFunctionBody) && !hasModifier(enclosingNonAsyncFunctionBody, ModifierFlags.Static) @@ -3013,19 +3140,6 @@ namespace ts { : createIdentifier("_super"); } - function visitSourceFileNode(node: SourceFile): SourceFile { - const [prologue, remaining] = span(node.statements, isPrologueDirective); - const statements: Statement[] = []; - startLexicalEnvironment(); - addRange(statements, prologue); - addCaptureThisForNodeIfNeeded(statements, node); - addRange(statements, visitNodes(createNodeArray(remaining), visitor, isStatement)); - addRange(statements, endLexicalEnvironment()); - const clone = getMutableClone(node); - clone.statements = createNodeArray(statements, /*location*/ node.statements); - return clone; - } - /** * Called by the printer just before a node is printed. * @@ -3034,7 +3148,7 @@ namespace ts { function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) { const savedEnclosingFunction = enclosingFunction; - if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis && isFunctionLike(node)) { + if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } @@ -3049,8 +3163,8 @@ namespace ts { * contains block-scoped bindings (e.g. `let` or `const`). */ function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) === 0) { - enabledSubstitutions |= ES6SubstitutionFlags.BlockScopedBindings; + if ((enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) === 0) { + enabledSubstitutions |= ES2015SubstitutionFlags.BlockScopedBindings; context.enableSubstitution(SyntaxKind.Identifier); } } @@ -3060,8 +3174,8 @@ namespace ts { * contains a captured `this`. */ function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & ES6SubstitutionFlags.CapturedThis) === 0) { - enabledSubstitutions |= ES6SubstitutionFlags.CapturedThis; + if ((enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis) === 0) { + enabledSubstitutions |= ES2015SubstitutionFlags.CapturedThis; context.enableSubstitution(SyntaxKind.ThisKeyword); context.enableEmitNotification(SyntaxKind.Constructor); context.enableEmitNotification(SyntaxKind.MethodDeclaration); @@ -3076,9 +3190,8 @@ namespace ts { /** * Hooks node substitutions. * + * @param emitContext The context for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ function onSubstituteNode(emitContext: EmitContext, node: Node) { node = previousOnSubstituteNode(emitContext, node); @@ -3100,7 +3213,7 @@ namespace ts { function substituteIdentifier(node: Identifier) { // Only substitute the identifier if we have enabled substitutions for block-scoped // bindings. - if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { const original = getParseTreeNode(node, isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return getGeneratedNameForNode(original); @@ -3153,7 +3266,7 @@ namespace ts { * @param node An Identifier node. */ function substituteExpressionIdentifier(node: Identifier): Identifier { - if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { const declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { return getGeneratedNameForNode(declaration.name); @@ -3169,7 +3282,7 @@ namespace ts { * @param node The ThisKeyword node. */ function substituteThisKeyword(node: PrimaryExpression): PrimaryExpression { - if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis + if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && enclosingFunction && getEmitFlags(enclosingFunction) & EmitFlags.CapturesThis) { return createIdentifier("_this", /*location*/ node); @@ -3178,45 +3291,6 @@ namespace ts { return node; } - /** - * Gets the local name for a declaration for use in expressions. - * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getLocalName(node: ClassDeclaration | ClassExpression | FunctionDeclaration, allowComments?: boolean, allowSourceMaps?: boolean) { - return getDeclarationName(node, allowComments, allowSourceMaps, EmitFlags.LocalName); - } - - /** - * Gets the name of a declaration, without source map or comments. - * - * @param node The declaration. - * @param allowComments Allow comments for the name. - */ - function getDeclarationName(node: ClassDeclaration | ClassExpression | FunctionDeclaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { - if (node.name && !isGeneratedIdentifier(node.name)) { - const name = getMutableClone(node.name); - emitFlags |= getEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= EmitFlags.NoSourceMap; - } - if (!allowComments) { - emitFlags |= EmitFlags.NoComments; - } - if (emitFlags) { - setEmitFlags(name, emitFlags); - } - return name; - } - - return getGeneratedNameForNode(node); - } - function getClassMemberPrefix(node: ClassExpression | ClassDeclaration, member: ClassElement) { const expression = getLocalName(node); return hasModifier(member, ModifierFlags.Static) ? expression : createPropertyAccess(expression, "prototype"); @@ -3227,8 +3301,7 @@ namespace ts { return false; } - const parameter = singleOrUndefined(constructor.parameters); - if (!parameter || !nodeIsSynthesized(parameter) || !parameter.dotDotDotToken) { + if (some(constructor.parameters)) { return false; } @@ -3248,12 +3321,36 @@ namespace ts { } const callArgument = singleOrUndefined((statementExpression).arguments); - if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElementExpression) { + if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) { return false; } - const expression = (callArgument).expression; - return isIdentifier(expression) && expression === parameter.name; + const expression = (callArgument).expression; + return isIdentifier(expression) && expression.text === "arguments"; } } -} \ No newline at end of file + + function createExtendsHelper(context: TransformationContext, name: Identifier) { + context.requestEmitHelper(extendsHelper); + return createCall( + getHelperName("__extends"), + /*typeArguments*/ undefined, + [ + name, + createIdentifier("_super") + ] + ); + } + + const extendsHelper: EmitHelper = { + name: "typescript:extends", + scoped: false, + priority: 0, + text: ` + var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + };` + }; +} diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts new file mode 100644 index 00000000000..5959753fcef --- /dev/null +++ b/src/compiler/transformers/es2016.ts @@ -0,0 +1,91 @@ +/// +/// + +/*@internal*/ +namespace ts { + export function transformES2016(context: TransformationContext) { + const { hoistVariableDeclaration } = context; + + return transformSourceFile; + + function transformSourceFile(node: SourceFile) { + if (isDeclarationFile(node)) { + return node; + } + + return visitEachChild(node, visitor, context); + } + + function visitor(node: Node): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsES2016) === 0) { + return node; + } + switch (node.kind) { + case SyntaxKind.BinaryExpression: + return visitBinaryExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + + function visitBinaryExpression(node: BinaryExpression): Expression { + switch (node.operatorToken.kind) { + case SyntaxKind.AsteriskAsteriskEqualsToken: + return visitExponentiationAssignmentExpression(node); + case SyntaxKind.AsteriskAsteriskToken: + return visitExponentiationExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + + function visitExponentiationAssignmentExpression(node: BinaryExpression) { + let target: Expression; + let value: Expression; + const left = visitNode(node.left, visitor, isExpression); + const right = visitNode(node.right, visitor, isExpression); + if (isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` + const expressionTemp = createTempVariable(hoistVariableDeclaration); + const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration); + target = createElementAccess( + createAssignment(expressionTemp, left.expression, /*location*/ left.expression), + createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), + /*location*/ left + ); + value = createElementAccess( + expressionTemp, + argumentExpressionTemp, + /*location*/ left + ); + } + else if (isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` + const expressionTemp = createTempVariable(hoistVariableDeclaration); + target = createPropertyAccess( + createAssignment(expressionTemp, left.expression, /*location*/ left.expression), + left.name, + /*location*/ left + ); + value = createPropertyAccess( + expressionTemp, + left.name, + /*location*/ left + ); + } + else { + // Transforms `a **= b` into `a = Math.pow(a, b)` + target = left; + value = left; + } + return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node); + } + + function visitExponentiationExpression(node: BinaryExpression) { + // Transforms `a ** b` into `Math.pow(a, b)` + const left = visitNode(node.left, visitor, isExpression); + const right = visitNode(node.right, visitor, isExpression); + return createMathPow(left, right, /*location*/ node); + } + } +} diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts new file mode 100644 index 00000000000..c87dbe32518 --- /dev/null +++ b/src/compiler/transformers/es2017.ts @@ -0,0 +1,518 @@ +/// +/// + +/*@internal*/ +namespace ts { + type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration; + + const enum ES2017SubstitutionFlags { + /** Enables substitutions for async methods with `super` calls. */ + AsyncMethodsWithSuper = 1 << 0 + } + + export function transformES2017(context: TransformationContext) { + const { + startLexicalEnvironment, + resumeLexicalEnvironment, + endLexicalEnvironment, + } = context; + + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + + // These variables contain state that changes as we descend into the tree. + let currentSourceFile: SourceFile; + + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + let enabledSubstitutions: ES2017SubstitutionFlags; + + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + let currentSuperContainer: SuperContainer; + + // Save the previous transformation hooks. + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + + return transformSourceFile; + + function transformSourceFile(node: SourceFile) { + if (isDeclarationFile(node)) { + return node; + } + + currentSourceFile = node; + + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + + currentSourceFile = undefined; + return visited; + } + + function visitor(node: Node): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsES2017) === 0) { + return node; + } + + switch (node.kind) { + case SyntaxKind.AsyncKeyword: + // ES2017 async modifier should be elided for targets < ES2017 + return undefined; + + case SyntaxKind.AwaitExpression: + // ES2017 'await' expressions must be transformed for targets < ES2017. + return visitAwaitExpression(node); + + case SyntaxKind.MethodDeclaration: + // ES2017 method declarations may be 'async' + return visitMethodDeclaration(node); + + case SyntaxKind.FunctionDeclaration: + // ES2017 function declarations may be 'async' + return visitFunctionDeclaration(node); + + case SyntaxKind.FunctionExpression: + // ES2017 function expressions may be 'async' + return visitFunctionExpression(node); + + case SyntaxKind.ArrowFunction: + // ES2017 arrow functions may be 'async' + return visitArrowFunction(node); + + default: + return visitEachChild(node, visitor, context); + } + } + + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ + function visitAwaitExpression(node: AwaitExpression): Expression { + return setOriginalNode( + createYield( + /*asteriskToken*/ undefined, + visitNode(node.expression, visitor, isExpression), + /*location*/ node + ), + node + ); + } + + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ + function visitMethodDeclaration(node: MethodDeclaration) { + return updateMethod( + node, + /*decorators*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); + } + + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { + return updateFunctionDeclaration( + node, + /*decorators*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); + } + + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitFunctionExpression(node: FunctionExpression): Expression { + if (nodeIsMissing(node.body)) { + return createOmittedExpression(); + } + return updateFunctionExpression( + node, + /*modifiers*/ undefined, + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); + } + + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ + function visitArrowFunction(node: ArrowFunction) { + return updateArrowFunction( + node, + visitNodes(node.modifiers, visitor, isModifier), + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + isAsyncFunctionLike(node) + ? transformAsyncFunctionBody(node) + : visitFunctionBody(node.body, visitor, context) + ); + } + + function transformAsyncFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody; + function transformAsyncFunctionBody(node: ArrowFunction): ConciseBody; + function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody { + resumeLexicalEnvironment(); + + const original = getOriginalNode(node, isFunctionLike); + const nodeType = original.type; + const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined; + const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; + const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; + + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + + if (!isArrowFunction) { + const statements: Statement[] = []; + const statementOffset = addPrologueDirectives(statements, (node.body).statements, /*ensureUseStrict*/ false, visitor); + statements.push( + createReturn( + createAwaiterHelper( + context, + hasLexicalArguments, + promiseConstructor, + transformFunctionBodyWorker(node.body, statementOffset) + ) + ) + ); + + addRange(statements, endLexicalEnvironment()); + + const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= ScriptTarget.ES2015) { + if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { + enableSubstitutionForAsyncMethodsWithSuper(); + addEmitHelper(block, advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { + enableSubstitutionForAsyncMethodsWithSuper(); + addEmitHelper(block, asyncSuperHelper); + } + } + + return block; + } + else { + const expression = createAwaiterHelper( + context, + hasLexicalArguments, + promiseConstructor, + transformFunctionBodyWorker(node.body) + ); + + const declarations = endLexicalEnvironment(); + if (some(declarations)) { + const block = convertToFunctionBody(expression); + return updateBlock(block, createNodeArray(concatenate(block.statements, declarations), block.statements)); + } + + return expression; + } + } + + function transformFunctionBodyWorker(body: ConciseBody, start?: number) { + if (isBlock(body)) { + return updateBlock(body, visitLexicalEnvironment(body.statements, visitor, context, start)); + } + else { + startLexicalEnvironment(); + const visited = convertToFunctionBody(visitNode(body, visitor, isConciseBody)); + const declarations = endLexicalEnvironment(); + return updateBlock(visited, createNodeArray(concatenate(visited.statements, declarations), visited.statements)); + } + } + + function getPromiseConstructor(type: TypeNode) { + const typeName = type && getEntityNameFromTypeNode(type); + if (typeName && isEntityName(typeName)) { + const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + + return undefined; + } + + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) { + enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper; + + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(SyntaxKind.CallExpression); + context.enableSubstitution(SyntaxKind.PropertyAccessExpression); + context.enableSubstitution(SyntaxKind.ElementAccessExpression); + + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(SyntaxKind.ClassDeclaration); + context.enableEmitNotification(SyntaxKind.MethodDeclaration); + context.enableEmitNotification(SyntaxKind.GetAccessor); + context.enableEmitNotification(SyntaxKind.SetAccessor); + context.enableEmitNotification(SyntaxKind.Constructor); + } + } + + function substituteExpression(node: Expression) { + switch (node.kind) { + case SyntaxKind.PropertyAccessExpression: + return substitutePropertyAccessExpression(node); + case SyntaxKind.ElementAccessExpression: + return substituteElementAccessExpression(node); + case SyntaxKind.CallExpression: + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) { + return substituteCallExpression(node); + } + break; + } + + return node; + } + + function substitutePropertyAccessExpression(node: PropertyAccessExpression) { + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod( + createLiteral(node.name.text), + flags, + node + ); + } + } + + return node; + } + + function substituteElementAccessExpression(node: ElementAccessExpression) { + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod( + node.argumentExpression, + flags, + node + ); + } + } + + return node; + } + + function substituteCallExpression(node: CallExpression): Expression { + const expression = node.expression; + if (isSuperProperty(expression)) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + const argumentExpression = isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return createCall( + createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, + [ + createThis(), + ...node.arguments + ] + ); + } + } + return node; + } + + function isSuperContainer(node: Node): node is SuperContainer { + const kind = node.kind; + return kind === SyntaxKind.ClassDeclaration + || kind === SyntaxKind.Constructor + || kind === SyntaxKind.MethodDeclaration + || kind === SyntaxKind.GetAccessor + || kind === SyntaxKind.SetAccessor; + } + + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { + const savedCurrentSuperContainer = currentSuperContainer; + currentSuperContainer = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSuperContainer = savedCurrentSuperContainer; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(emitContext: EmitContext, node: Node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === EmitContext.Expression) { + return substituteExpression(node); + } + + return node; + } + + function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression { + if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) { + return createPropertyAccess( + createCall( + createIdentifier("_super"), + /*typeArguments*/ undefined, + [argumentExpression] + ), + "value", + location + ); + } + else { + return createCall( + createIdentifier("_super"), + /*typeArguments*/ undefined, + [argumentExpression], + location + ); + } + } + + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding); + } + } + + function createAwaiterHelper(context: TransformationContext, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) { + context.requestEmitHelper(awaiterHelper); + const generatorFunc = createFunctionExpression( + /*modifiers*/ undefined, + createToken(SyntaxKind.AsteriskToken), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + body + ); + + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= EmitFlags.AsyncFunctionBody; + + return createCall( + getHelperName("__awaiter"), + /*typeArguments*/ undefined, + [ + createThis(), + hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(promiseConstructor) : createVoidZero(), + generatorFunc + ] + ); + } + + const awaiterHelper: EmitHelper = { + name: "typescript:awaiter", + scoped: false, + priority: 5, + text: ` + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + };` + }; + + const asyncSuperHelper: EmitHelper = { + name: "typescript:async-super", + scoped: true, + text: ` + const _super = name => super[name];` + }; + + const advancedAsyncSuperHelper: EmitHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: ` + const _super = (function (geti, seti) { + const cache = Object.create(null); + return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + })(name => super[name], (name, value) => super[name] = value);` + }; +} diff --git a/src/compiler/transformers/es5.ts b/src/compiler/transformers/es5.ts new file mode 100644 index 00000000000..6dd875965d9 --- /dev/null +++ b/src/compiler/transformers/es5.ts @@ -0,0 +1,119 @@ +/// +/// + +/*@internal*/ +namespace ts { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ + export function transformES5(context: TransformationContext) { + const compilerOptions = context.getCompilerOptions(); + + // enable emit notification only if using --jsx preserve + let previousOnEmitNode: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; + let noSubstitution: boolean[]; + if (compilerOptions.jsx === JsxEmit.Preserve) { + previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.enableEmitNotification(SyntaxKind.JsxOpeningElement); + context.enableEmitNotification(SyntaxKind.JsxClosingElement); + context.enableEmitNotification(SyntaxKind.JsxSelfClosingElement); + noSubstitution = []; + } + + const previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(SyntaxKind.PropertyAccessExpression); + context.enableSubstitution(SyntaxKind.PropertyAssignment); + return transformSourceFile; + + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ + function transformSourceFile(node: SourceFile) { + return node; + } + + /** + * Called by the printer just before a node is printed. + * + * @param node The node to be printed. + */ + function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) { + switch (node.kind) { + case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxClosingElement: + case SyntaxKind.JsxSelfClosingElement: + const tagName = (node).tagName; + noSubstitution[getOriginalNodeId(tagName)] = true; + break; + } + + previousOnEmitNode(emitContext, node, emitCallback); + } + + /** + * Hooks node substitutions. + * + * @param emitContext The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext: EmitContext, node: Node) { + if (node.id && noSubstitution && noSubstitution[node.id]) { + return previousOnSubstituteNode(emitContext, node); + } + + node = previousOnSubstituteNode(emitContext, node); + if (isPropertyAccessExpression(node)) { + return substitutePropertyAccessExpression(node); + } + else if (isPropertyAssignment(node)) { + return substitutePropertyAssignment(node); + } + return node; + } + + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ + function substitutePropertyAccessExpression(node: PropertyAccessExpression): Expression { + const literalName = trySubstituteReservedName(node.name); + if (literalName) { + return createElementAccess(node.expression, literalName, /*location*/ node); + } + return node; + } + + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ + function substitutePropertyAssignment(node: PropertyAssignment): PropertyAssignment { + const literalName = isIdentifier(node.name) && trySubstituteReservedName(node.name); + if (literalName) { + return updatePropertyAssignment(node, literalName, node.initializer); + } + return node; + } + + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ + function trySubstituteReservedName(name: Identifier) { + const token = name.originalKeywordKind || (nodeIsSynthesized(name) ? stringToToken(name.text) : undefined); + if (token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord) { + return createLiteral(name, /*location*/ name); + } + return undefined; + } + } +} \ No newline at end of file diff --git a/src/compiler/transformers/es7.ts b/src/compiler/transformers/es7.ts deleted file mode 100644 index 4d5e96134c4..00000000000 --- a/src/compiler/transformers/es7.ts +++ /dev/null @@ -1,101 +0,0 @@ -/// -/// - -/*@internal*/ -namespace ts { - export function transformES7(context: TransformationContext) { - const { hoistVariableDeclaration } = context; - - return transformSourceFile; - - function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { - return node; - } - - return visitEachChild(node, visitor, context); - } - - function visitor(node: Node): VisitResult { - if (node.transformFlags & TransformFlags.ES7) { - return visitorWorker(node); - } - else if (node.transformFlags & TransformFlags.ContainsES7) { - return visitEachChild(node, visitor, context); - } - else { - return node; - } - } - - function visitorWorker(node: Node): VisitResult { - switch (node.kind) { - case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node); - - default: - Debug.failBadSyntaxKind(node); - return visitEachChild(node, visitor, context); - } - } - - function visitBinaryExpression(node: BinaryExpression): Expression { - // We are here because ES7 adds support for the exponentiation operator. - const left = visitNode(node.left, visitor, isExpression); - const right = visitNode(node.right, visitor, isExpression); - if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) { - let target: Expression; - let value: Expression; - if (isElementAccessExpression(left)) { - // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` - const expressionTemp = createTempVariable(hoistVariableDeclaration); - - const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration); - - target = createElementAccess( - createAssignment(expressionTemp, left.expression, /*location*/ left.expression), - createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), - /*location*/ left - ); - - value = createElementAccess( - expressionTemp, - argumentExpressionTemp, - /*location*/ left - ); - } - else if (isPropertyAccessExpression(left)) { - // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` - const expressionTemp = createTempVariable(hoistVariableDeclaration); - - target = createPropertyAccess( - createAssignment(expressionTemp, left.expression, /*location*/ left.expression), - left.name, - /*location*/ left - ); - - value = createPropertyAccess( - expressionTemp, - left.name, - /*location*/ left - ); - } - else { - // Transforms `a **= b` into `a = Math.pow(a, b)` - target = left; - value = left; - } - - return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node); - } - else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) { - // Transforms `a ** b` into `Math.pow(a, b)` - return createMathPow(left, right, /*location*/ node); - } - else { - Debug.failBadSyntaxKind(node); - return visitEachChild(node, visitor, context); - } - } - } -} \ No newline at end of file diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts new file mode 100644 index 00000000000..0a529a8e871 --- /dev/null +++ b/src/compiler/transformers/esnext.ts @@ -0,0 +1,412 @@ +/// +/// + +/*@internal*/ +namespace ts { + export function transformESNext(context: TransformationContext) { + const { + resumeLexicalEnvironment, + endLexicalEnvironment + } = context; + return transformSourceFile; + + function transformSourceFile(node: SourceFile) { + if (isDeclarationFile(node)) { + return node; + } + + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + + function visitor(node: Node): VisitResult { + return visitorWorker(node, /*noDestructuringValue*/ false); + } + + function visitorNoDestructuringValue(node: Node): VisitResult { + return visitorWorker(node, /*noDestructuringValue*/ true); + } + + function visitorWorker(node: Node, noDestructuringValue: boolean): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { + return node; + } + + switch (node.kind) { + case SyntaxKind.ObjectLiteralExpression: + return visitObjectLiteralExpression(node as ObjectLiteralExpression); + case SyntaxKind.BinaryExpression: + return visitBinaryExpression(node as BinaryExpression, noDestructuringValue); + case SyntaxKind.VariableDeclaration: + return visitVariableDeclaration(node as VariableDeclaration); + case SyntaxKind.ForOfStatement: + return visitForOfStatement(node as ForOfStatement); + case SyntaxKind.ForStatement: + return visitForStatement(node as ForStatement); + case SyntaxKind.VoidExpression: + return visitVoidExpression(node as VoidExpression); + case SyntaxKind.Constructor: + return visitConstructorDeclaration(node as ConstructorDeclaration); + case SyntaxKind.MethodDeclaration: + return visitMethodDeclaration(node as MethodDeclaration); + case SyntaxKind.GetAccessor: + return visitGetAccessorDeclaration(node as GetAccessorDeclaration); + case SyntaxKind.SetAccessor: + return visitSetAccessorDeclaration(node as SetAccessorDeclaration); + case SyntaxKind.FunctionDeclaration: + return visitFunctionDeclaration(node as FunctionDeclaration); + case SyntaxKind.FunctionExpression: + return visitFunctionExpression(node as FunctionExpression); + case SyntaxKind.ArrowFunction: + return visitArrowFunction(node as ArrowFunction); + case SyntaxKind.Parameter: + return visitParameter(node as ParameterDeclaration); + case SyntaxKind.ExpressionStatement: + return visitExpressionStatement(node as ExpressionStatement); + case SyntaxKind.ParenthesizedExpression: + return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue); + default: + return visitEachChild(node, visitor, context); + } + } + + function chunkObjectLiteralElements(elements: ObjectLiteralElement[]): Expression[] { + let chunkObject: (ShorthandPropertyAssignment | PropertyAssignment)[]; + const objects: Expression[] = []; + for (const e of elements) { + if (e.kind === SyntaxKind.SpreadAssignment) { + if (chunkObject) { + objects.push(createObjectLiteral(chunkObject)); + chunkObject = undefined; + } + const target = (e as SpreadAssignment).expression; + objects.push(visitNode(target, visitor, isExpression)); + } + else { + if (!chunkObject) { + chunkObject = []; + } + if (e.kind === SyntaxKind.PropertyAssignment) { + const p = e as PropertyAssignment; + chunkObject.push(createPropertyAssignment(p.name, visitNode(p.initializer, visitor, isExpression))); + } + else { + chunkObject.push(e as ShorthandPropertyAssignment); + } + } + } + if (chunkObject) { + objects.push(createObjectLiteral(chunkObject)); + } + + return objects; + } + + function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression { + if (node.transformFlags & TransformFlags.ContainsObjectSpread) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + const objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) { + objects.unshift(createObjectLiteral()); + } + return createAssignHelper(context, objects); + } + return visitEachChild(node, visitor, context); + } + + function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement { + return visitEachChild(node, visitorNoDestructuringValue, context); + } + + function visitParenthesizedExpression(node: ParenthesizedExpression, noDestructuringValue: boolean): ParenthesizedExpression { + return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); + } + + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ + function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression { + if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRest) { + return flattenDestructuringAssignment( + node, + visitor, + context, + FlattenLevel.ObjectRest, + !noDestructuringValue + ); + } + else if (node.operatorToken.kind === SyntaxKind.CommaToken) { + return updateBinary( + node, + visitNode(node.left, visitorNoDestructuringValue, isExpression), + visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, isExpression) + ); + } + return visitEachChild(node, visitor, context); + } + + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ + function visitVariableDeclaration(node: VariableDeclaration): VisitResult { + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRest) { + return flattenDestructuringBinding( + node, + visitor, + context, + FlattenLevel.ObjectRest + ); + } + return visitEachChild(node, visitor, context); + } + + function visitForStatement(node: ForStatement): VisitResult { + return updateFor( + node, + visitNode(node.initializer, visitorNoDestructuringValue, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, visitor, isExpression), + visitNode(node.statement, visitor, isStatement) + ); + } + + function visitVoidExpression(node: VoidExpression) { + return visitEachChild(node, visitorNoDestructuringValue, context); + } + + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ + function visitForOfStatement(node: ForOfStatement): VisitResult { + let leadingStatements: Statement[]; + let temp: Identifier; + const initializer = skipParentheses(node.initializer); + if (initializer.transformFlags & TransformFlags.ContainsObjectRest) { + if (isVariableDeclarationList(initializer)) { + temp = createTempVariable(/*recordTempVariable*/ undefined); + const firstDeclaration = firstOrUndefined(initializer.declarations); + const declarations = flattenDestructuringBinding( + firstDeclaration, + visitor, + context, + FlattenLevel.ObjectRest, + temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true, + ); + if (some(declarations)) { + const statement = createVariableStatement( + /*modifiers*/ undefined, + updateVariableDeclarationList(initializer, declarations), + /*location*/ initializer + ); + leadingStatements = append(leadingStatements, statement); + } + } + else if (isAssignmentPattern(initializer)) { + temp = createTempVariable(/*recordTempVariable*/ undefined); + const expression = flattenDestructuringAssignment( + aggregateTransformFlags(createAssignment(initializer, temp, /*location*/ node.initializer)), + visitor, + context, + FlattenLevel.ObjectRest + ); + leadingStatements = append(leadingStatements, createStatement(expression, /*location*/ node.initializer)); + } + } + if (temp) { + const expression = visitNode(node.expression, visitor, isExpression); + const statement = visitNode(node.statement, visitor, isStatement); + const block = isBlock(statement) + ? updateBlock(statement, createNodeArray(concatenate(leadingStatements, statement.statements), statement.statements)) + : createBlock(append(leadingStatements, statement), statement, /*multiLine*/ true); + return updateForOf( + node, + createVariableDeclarationList( + [ + createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer) + ], + node.initializer, + NodeFlags.Let + ), + expression, + block + ); + } + return visitEachChild(node, visitor, context); + } + + function visitParameter(node: ParameterDeclaration): ParameterDeclaration { + if (node.transformFlags & TransformFlags.ContainsObjectRest) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return updateParameter( + node, + /*decorators*/ undefined, + /*modifiers*/ undefined, + node.dotDotDotToken, + getGeneratedNameForNode(node), + /*type*/ undefined, + visitNode(node.initializer, visitor, isExpression) + ); + } + return visitEachChild(node, visitor, context); + } + + function visitConstructorDeclaration(node: ConstructorDeclaration) { + return updateConstructor( + node, + /*decorators*/ undefined, + node.modifiers, + visitParameterList(node.parameters, visitor, context), + transformFunctionBody(node) + ); + } + + function visitGetAccessorDeclaration(node: GetAccessorDeclaration) { + return updateGetAccessor( + node, + /*decorators*/ undefined, + node.modifiers, + visitNode(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node) + ); + } + + function visitSetAccessorDeclaration(node: SetAccessorDeclaration) { + return updateSetAccessor( + node, + /*decorators*/ undefined, + node.modifiers, + visitNode(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, visitor, context), + transformFunctionBody(node) + ); + } + + function visitMethodDeclaration(node: MethodDeclaration) { + return updateMethod( + node, + /*decorators*/ undefined, + node.modifiers, + visitNode(node.name, visitor, isPropertyName), + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node) + ); + } + + function visitFunctionDeclaration(node: FunctionDeclaration) { + return updateFunctionDeclaration( + node, + /*decorators*/ undefined, + node.modifiers, + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node) + ); + } + + function visitArrowFunction(node: ArrowFunction) { + return updateArrowFunction( + node, + node.modifiers, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node) + ); + } + + function visitFunctionExpression(node: FunctionExpression) { + return updateFunctionExpression( + node, + node.modifiers, + node.name, + /*typeParameters*/ undefined, + visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, + transformFunctionBody(node) + ); + } + + function transformFunctionBody(node: FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | AccessorDeclaration): FunctionBody; + function transformFunctionBody(node: ArrowFunction): ConciseBody; + function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody { + resumeLexicalEnvironment(); + let leadingStatements: Statement[]; + for (const parameter of node.parameters) { + if (parameter.transformFlags & TransformFlags.ContainsObjectRest) { + const temp = getGeneratedNameForNode(parameter); + const declarations = flattenDestructuringBinding( + parameter, + visitor, + context, + FlattenLevel.ObjectRest, + temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true, + ); + if (some(declarations)) { + const statement = createVariableStatement( + /*modifiers*/ undefined, + createVariableDeclarationList( + declarations + ) + ); + setEmitFlags(statement, EmitFlags.CustomPrologue); + leadingStatements = append(leadingStatements, statement); + } + } + } + const body = visitNode(node.body, visitor, isConciseBody); + const trailingStatements = endLexicalEnvironment(); + if (some(leadingStatements) || some(trailingStatements)) { + const block = convertToFunctionBody(body, /*multiLine*/ true); + return updateBlock(block, createNodeArray(concatenate(concatenate(leadingStatements, block.statements), trailingStatements), block.statements)); + } + return body; + } + } + + const assignHelper: EmitHelper = { + name: "typescript:assign", + scoped: false, + priority: 1, + text: ` + var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + };` + }; + + export function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]) { + context.requestEmitHelper(assignHelper); + return createCall( + getHelperName("__assign"), + /*typeArguments*/ undefined, + attributesSegments + ); + } +} diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 5e8a96f3ff1..1b909da4f6a 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -227,7 +227,7 @@ namespace ts { export function transformGenerators(context: TransformationContext) { const { - startLexicalEnvironment, + resumeLexicalEnvironment, endLexicalEnvironment, hoistFunctionDeclaration, hoistVariableDeclaration, @@ -291,17 +291,18 @@ namespace ts { return transformSourceFile; function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (isDeclarationFile(node) + || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { return node; } - if (node.transformFlags & TransformFlags.ContainsGenerator) { - currentSourceFile = node; - node = visitEachChild(node, visitor, context); - currentSourceFile = undefined; - } + currentSourceFile = node; - return node; + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + + currentSourceFile = undefined; + return visited; } /** @@ -449,11 +450,11 @@ namespace ts { node = setOriginalNode( createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, + node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, - node.parameters, + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node @@ -496,10 +497,11 @@ namespace ts { if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { node = setOriginalNode( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, - node.parameters, + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body), /*location*/ node @@ -577,7 +579,7 @@ namespace ts { state = createTempVariable(/*recordTempVariable*/ undefined); // Build the generator - startLexicalEnvironment(); + resumeLexicalEnvironment(); const statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor); @@ -936,7 +938,7 @@ namespace ts { } markLabel(resumeLabel); - return createGeneratorResume(); + return createGeneratorResume(/*location*/ node); } /** @@ -945,7 +947,7 @@ namespace ts { * @param node The node to visit. */ function visitArrayLiteralExpression(node: ArrayLiteralExpression) { - return visitElements(node.elements, node.multiLine); + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); } /** @@ -955,7 +957,7 @@ namespace ts { * @param elements The elements to visit. * @param multiLine Whether array literals created should be emitted on multiple lines. */ - function visitElements(elements: NodeArray, multiLine: boolean) { + function visitElements(elements: NodeArray, leadingElement?: Expression, location?: TextRange, multiLine?: boolean) { // [source] // ar = [1, yield, 2]; // @@ -970,18 +972,22 @@ namespace ts { const temp = declareLocal(); let hasAssignedTemp = false; if (numInitialElements > 0) { + const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements); emitAssignment(temp, createArrayLiteral( - visitNodes(elements, visitor, isExpression, 0, numInitialElements) + leadingElement + ? [leadingElement, ...initialElements] + : initialElements ) ); + leadingElement = undefined; hasAssignedTemp = true; } const expressions = reduceLeft(elements, reduceElement, [], numInitialElements); return hasAssignedTemp - ? createArrayConcat(temp, [createArrayLiteral(expressions)]) - : createArrayLiteral(expressions); + ? createArrayConcat(temp, [createArrayLiteral(expressions, /*location*/ undefined, multiLine)]) + : createArrayLiteral(leadingElement ? [leadingElement, ...expressions] : expressions, location, multiLine); function reduceElement(expressions: Expression[], element: Expression) { if (containsYield(element) && expressions.length > 0) { @@ -990,11 +996,16 @@ namespace ts { hasAssignedTemp ? createArrayConcat( temp, - [createArrayLiteral(expressions)] + [createArrayLiteral(expressions, /*location*/ undefined, multiLine)] + ) + : createArrayLiteral( + leadingElement ? [leadingElement, ...expressions] : expressions, + /*location*/ undefined, + multiLine ) - : createArrayLiteral(expressions) ); hasAssignedTemp = true; + leadingElement = undefined; expressions = []; } @@ -1101,7 +1112,7 @@ namespace ts { createFunctionApply( cacheExpression(visitNode(target, visitor, isLeftHandSideExpression)), thisArg, - visitElements(node.arguments, /*multiLine*/ false), + visitElements(node.arguments), /*location*/ node ), node @@ -1130,7 +1141,10 @@ namespace ts { createFunctionApply( cacheExpression(visitNode(target, visitor, isExpression)), thisArg, - visitElements(node.arguments, /*multiLine*/ false) + visitElements( + node.arguments, + /*leadingElement*/ createVoidZero() + ) ), /*typeArguments*/ undefined, [], @@ -1220,7 +1234,9 @@ namespace ts { function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList { for (const variable of node.declarations) { - hoistVariableDeclaration(variable.name); + const name = getSynthesizedClone(variable.name); + setCommentRange(name, variable.name); + hoistVariableDeclaration(name); } const variables = getInitializedVariables(node); @@ -1273,7 +1289,7 @@ namespace ts { if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { const endLabel = defineLabel(); const elseLabel = node.elseStatement ? defineLabel() : undefined; - emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, visitNode(node.expression, visitor, isExpression)); + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, visitNode(node.expression, visitor, isExpression), /*location*/ node.expression); transformAndEmitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { emitBreak(endLabel); @@ -2368,7 +2384,7 @@ namespace ts { labelExpressions = []; } - const expression = createSynthesizedNode(SyntaxKind.NumericLiteral); + const expression = createLiteral(-1); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -2379,7 +2395,7 @@ namespace ts { return expression; } - return createNode(SyntaxKind.OmittedExpression); + return createOmittedExpression(); } /** @@ -2584,27 +2600,24 @@ namespace ts { withBlockStack = undefined; const buildResult = buildStatements(); - return createCall( - createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), - /*typeArguments*/ undefined, - [ - createThis(), - setEmitFlags( - createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - [createParameter(state)], - /*type*/ undefined, - createBlock( - buildResult, - /*location*/ undefined, - /*multiLine*/ buildResult.length > 0 - ) - ), - EmitFlags.ReuseTempVariableScope - ) - ] + return createGeneratorHelper( + context, + setEmitFlags( + createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, + createBlock( + buildResult, + /*location*/ undefined, + /*multiLine*/ buildResult.length > 0 + ) + ), + EmitFlags.ReuseTempVariableScope + ) ); } @@ -2954,12 +2967,15 @@ namespace ts { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; writeStatement( - createReturn( - createArrayLiteral(expression - ? [createInstruction(Instruction.Return), expression] - : [createInstruction(Instruction.Return)] + setEmitFlags( + createReturn( + createArrayLiteral(expression + ? [createInstruction(Instruction.Return), expression] + : [createInstruction(Instruction.Return)] + ), + operationLocation ), - operationLocation + EmitFlags.NoTokenSourceMaps ) ); } @@ -2973,12 +2989,15 @@ namespace ts { function writeBreak(label: Label, operationLocation: TextRange): void { lastOperationWasAbrupt = true; writeStatement( - createReturn( - createArrayLiteral([ - createInstruction(Instruction.Break), - createLabel(label) - ]), - operationLocation + setEmitFlags( + createReturn( + createArrayLiteral([ + createInstruction(Instruction.Break), + createLabel(label) + ]), + operationLocation + ), + EmitFlags.NoTokenSourceMaps ) ); } @@ -2992,15 +3011,21 @@ namespace ts { */ function writeBreakWhenTrue(label: Label, condition: Expression, operationLocation: TextRange): void { writeStatement( - createIf( - condition, - createReturn( - createArrayLiteral([ - createInstruction(Instruction.Break), - createLabel(label) - ]), - operationLocation - ) + setEmitFlags( + createIf( + condition, + setEmitFlags( + createReturn( + createArrayLiteral([ + createInstruction(Instruction.Break), + createLabel(label) + ]), + operationLocation + ), + EmitFlags.NoTokenSourceMaps + ) + ), + EmitFlags.SingleLine ) ); } @@ -3014,15 +3039,21 @@ namespace ts { */ function writeBreakWhenFalse(label: Label, condition: Expression, operationLocation: TextRange): void { writeStatement( - createIf( - createLogicalNot(condition), - createReturn( - createArrayLiteral([ - createInstruction(Instruction.Break), - createLabel(label) - ]), - operationLocation - ) + setEmitFlags( + createIf( + createLogicalNot(condition), + setEmitFlags( + createReturn( + createArrayLiteral([ + createInstruction(Instruction.Break), + createLabel(label) + ]), + operationLocation + ), + EmitFlags.NoTokenSourceMaps + ) + ), + EmitFlags.SingleLine ) ); } @@ -3036,13 +3067,16 @@ namespace ts { function writeYield(expression: Expression, operationLocation: TextRange): void { lastOperationWasAbrupt = true; writeStatement( - createReturn( - createArrayLiteral( - expression - ? [createInstruction(Instruction.Yield), expression] - : [createInstruction(Instruction.Yield)] + setEmitFlags( + createReturn( + createArrayLiteral( + expression + ? [createInstruction(Instruction.Yield), expression] + : [createInstruction(Instruction.Yield)] + ), + operationLocation ), - operationLocation + EmitFlags.NoTokenSourceMaps ) ); } @@ -3056,12 +3090,15 @@ namespace ts { function writeYieldStar(expression: Expression, operationLocation: TextRange): void { lastOperationWasAbrupt = true; writeStatement( - createReturn( - createArrayLiteral([ - createInstruction(Instruction.YieldStar), - expression - ]), - operationLocation + setEmitFlags( + createReturn( + createArrayLiteral([ + createInstruction(Instruction.YieldStar), + expression + ]), + operationLocation + ), + EmitFlags.NoTokenSourceMaps ) ); } @@ -3080,4 +3117,105 @@ namespace ts { ); } } -} \ No newline at end of file + + function createGeneratorHelper(context: TransformationContext, body: FunctionExpression) { + context.requestEmitHelper(generatorHelper); + return createCall( + getHelperName("__generator"), + /*typeArguments*/ undefined, + [createThis(), body]); + } + + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + const generatorHelper: EmitHelper = { + name: "typescript:generator", + scoped: false, + priority: 6, + text: ` + var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + };` + }; +} diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 95a4016bb0a..ecb5dd053e0 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -1,13 +1,13 @@ /// /// +/// /*@internal*/ namespace ts { - const entities: Map = createEntitiesMap(); - export function transformJsx(context: TransformationContext) { const compilerOptions = context.getCompilerOptions(); let currentSourceFile: SourceFile; + return transformSourceFile; /** @@ -21,18 +21,18 @@ namespace ts { } currentSourceFile = node; - node = visitEachChild(node, visitor, context); + + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; - return node; + return visited; } function visitor(node: Node): VisitResult { - if (node.transformFlags & TransformFlags.Jsx) { + if (node.transformFlags & TransformFlags.ContainsJsx) { return visitorWorker(node); } - else if (node.transformFlags & TransformFlags.ContainsJsx) { - return visitEachChild(node, visitor, context); - } else { return node; } @@ -50,8 +50,7 @@ namespace ts { return visitJsxExpression(node); default: - Debug.failBadSyntaxKind(node); - return undefined; + return visitEachChild(node, visitor, context); } } @@ -109,11 +108,14 @@ namespace ts { // Either emit one big object literal (no spread attribs), or // a call to the __assign helper. - objectProperties = singleOrUndefined(segments) - || createAssignHelper(currentSourceFile.externalHelpersModuleName, segments); + objectProperties = singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = createAssignHelper(context, segments); + } } - const element = createReactCreateElement( + const element = createExpressionForJsxElement( + context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, @@ -275,261 +277,259 @@ namespace ts { } } - function createEntitiesMap(): Map { - return createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - } + const entities = createMap({ + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }); } \ No newline at end of file diff --git a/src/compiler/transformers/module/es2015.ts b/src/compiler/transformers/module/es2015.ts new file mode 100644 index 00000000000..5611f890164 --- /dev/null +++ b/src/compiler/transformers/module/es2015.ts @@ -0,0 +1,117 @@ +/// +/// + +/*@internal*/ +namespace ts { + export function transformES2015Module(context: TransformationContext) { + const compilerOptions = context.getCompilerOptions(); + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(SyntaxKind.SourceFile); + context.enableSubstitution(SyntaxKind.Identifier); + + let currentSourceFile: SourceFile; + return transformSourceFile; + + function transformSourceFile(node: SourceFile) { + if (isDeclarationFile(node)) { + return node; + } + + if (isExternalModule(node) || compilerOptions.isolatedModules) { + const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); + if (externalHelpersModuleName) { + const statements: Statement[] = []; + const statementOffset = addPrologueDirectives(statements, node.statements); + append(statements, + createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), + createLiteral(externalHelpersModuleNameText) + ) + ); + + addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); + return updateSourceFileNode( + node, + createNodeArray(statements, node.statements)); + } + else { + return visitEachChild(node, visitor, context); + } + } + + return node; + } + + function visitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ImportEqualsDeclaration: + // Elide `import=` as it is not legal with --module ES6 + return undefined; + case SyntaxKind.ExportAssignment: + return visitExportAssignment(node); + } + + return node; + } + + function visitExportAssignment(node: ExportAssignment): VisitResult { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; + } + + // + // Emit Notification + // + + /** + * Hook for node emit. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { + if (isSourceFile(node)) { + currentSourceFile = node; + previousOnEmitNode(emitContext, node, emitCallback); + currentSourceFile = undefined; + } + else { + previousOnEmitNode(emitContext, node, emitCallback); + } + } + + // + // Substitutions + // + + /** + * Hooks node substitutions. + * + * @param emitContext A context hint for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(emitContext: EmitContext, node: Node) { + node = previousOnSubstituteNode(emitContext, node); + if (isIdentifier(node) && emitContext === EmitContext.Expression) { + return substituteExpressionIdentifier(node); + } + return node; + } + + function substituteExpressionIdentifier(node: Identifier): Expression { + if (getEmitFlags(node) & EmitFlags.HelperName) { + const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return createPropertyAccess(externalHelpersModuleName, node); + } + } + return node; + } + } +} diff --git a/src/compiler/transformers/module/es6.ts b/src/compiler/transformers/module/es6.ts deleted file mode 100644 index 09a2890727c..00000000000 --- a/src/compiler/transformers/module/es6.ts +++ /dev/null @@ -1,144 +0,0 @@ -/// -/// - -/*@internal*/ -namespace ts { - export function transformES6Module(context: TransformationContext) { - const compilerOptions = context.getCompilerOptions(); - const resolver = context.getEmitResolver(); - - let currentSourceFile: SourceFile; - - return transformSourceFile; - - function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { - return node; - } - - if (isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - return visitEachChild(node, visitor, context); - } - return node; - } - - function visitor(node: Node): VisitResult { - switch (node.kind) { - case SyntaxKind.ImportDeclaration: - return visitImportDeclaration(node); - case SyntaxKind.ImportEqualsDeclaration: - return visitImportEqualsDeclaration(node); - case SyntaxKind.ImportClause: - return visitImportClause(node); - case SyntaxKind.NamedImports: - case SyntaxKind.NamespaceImport: - return visitNamedBindings(node); - case SyntaxKind.ImportSpecifier: - return visitImportSpecifier(node); - case SyntaxKind.ExportAssignment: - return visitExportAssignment(node); - case SyntaxKind.ExportDeclaration: - return visitExportDeclaration(node); - case SyntaxKind.NamedExports: - return visitNamedExports(node); - case SyntaxKind.ExportSpecifier: - return visitExportSpecifier(node); - } - - return node; - } - - function visitExportAssignment(node: ExportAssignment): ExportAssignment { - if (node.isExportEquals) { - return undefined; // do not emit export equals for ES6 - } - const original = getOriginalNode(node); - return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; - } - - function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; - } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; - } - const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true); - if (node.exportClause === newExportClause) { - return node; - } - return newExportClause - ? createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - newExportClause, - node.moduleSpecifier) - : undefined; - } - - function visitNamedExports(node: NamedExports): NamedExports { - const newExports = visitNodes(node.elements, visitor, isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? createNamedExports(newExports) : undefined; - } - - function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - - function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration { - return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - - function visitImportDeclaration(node: ImportDeclaration) { - if (node.importClause) { - const newImportClause = visitNode(node.importClause, visitor, isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - newImportClause, - node.moduleSpecifier); - } - } - return node; - } - - function visitImportClause(node: ImportClause): ImportClause { - let newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? createImportClause(newDefaultImport, newNamedBindings) - : node; - } - - function visitNamedBindings(node: NamedImportBindings): VisitResult { - if (node.kind === SyntaxKind.NamespaceImport) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - const newNamedImportElements = visitNodes((node).elements, visitor, isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === (node).elements) { - return node; - } - return createNamedImports(newNamedImportElements); - } - } - - function visitImportSpecifier(node: ImportSpecifier) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - } -} \ No newline at end of file diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 516ed5433b8..c900b7d20e1 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -4,6 +4,12 @@ /*@internal*/ namespace ts { export function transformModule(context: TransformationContext) { + interface AsynchronousDependencies { + aliasedModuleNames: Expression[]; + unaliasedModuleNames: Expression[]; + importAliasNames: ParameterDeclaration[]; + } + const transformModuleDelegates = createMap<(node: SourceFile) => SourceFile>({ [ModuleKind.None]: transformCommonJSModule, [ModuleKind.CommonJS]: transformCommonJSModule, @@ -13,8 +19,7 @@ namespace ts { const { startLexicalEnvironment, - endLexicalEnvironment, - hoistVariableDeclaration, + endLexicalEnvironment } = context; const compilerOptions = context.getCompilerOptions(); @@ -26,22 +31,19 @@ namespace ts { const previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(SyntaxKind.Identifier); - context.enableSubstitution(SyntaxKind.BinaryExpression); - context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); - context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); - context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment); - context.enableEmitNotification(SyntaxKind.SourceFile); + context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols. + context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); // Substitutes updates to exported symbols. + context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); // Substitutes updates to exported symbols. + context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file. - let currentSourceFile: SourceFile; - let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; - let exportSpecifiers: Map; - let exportEquals: ExportAssignment; - let bindingNameExportSpecifiersMap: Map; - // Subset of exportSpecifiers that is a binding-name. - // This is to reduce amount of memory we have to keep around even after we done with module-transformer - const bindingNameExportSpecifiersForFileMap = createMap>(); - let hasExportStarsToExportValues: boolean; + const moduleInfoMap = createMap(); // The ExternalModuleInfo for each file. + const deferredExports = createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + + let currentSourceFile: SourceFile; // The current file. + let currentModuleInfo: ExternalModuleInfo; // The ExternalModuleInfo for the current file. + let noSubstitution: Map; // Set of nodes for which substitution rules should be ignored. return transformSourceFile; @@ -51,30 +53,22 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (isDeclarationFile(node) + || !(isExternalModule(node) + || compilerOptions.isolatedModules)) { return node; } - if (isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[getOriginalNodeId(node)] = collectExternalModuleInfo(node, resolver, compilerOptions); - // Collect information about the external module. - ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver)); + // Perform the transformation. + const transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ModuleKind.None]; + const updated = transformModule(node); - // Perform the transformation. - const transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ModuleKind.None]; - const updated = transformModule(node); - aggregateTransformFlags(updated); - - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - return updated; - } - - return node; + currentSourceFile = undefined; + currentModuleInfo = undefined; + return aggregateTransformFlags(updated); } /** @@ -86,14 +80,15 @@ namespace ts { startLexicalEnvironment(); const statements: Statement[] = []; - const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); - addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); + const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true)); + addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset)); addRange(statements, endLexicalEnvironment()); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - const updated = updateSourceFile(node, statements); - if (hasExportStarsToExportValues) { - setEmitFlags(updated, EmitFlags.EmitExportStar | getEmitFlags(node)); + const updated = updateSourceFileNode(node, createNodeArray(statements, node.statements)); + if (currentModuleInfo.hasExportStarsToExportValues) { + addEmitHelper(updated, exportStarHelper); } return updated; @@ -116,8 +111,7 @@ namespace ts { * @param node The SourceFile node. */ function transformUMDModule(node: SourceFile) { - const define = createIdentifier("define"); - setEmitFlags(define, EmitFlags.UMDDefine); + const define = createRawExpression(umdHelper); return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); } @@ -156,44 +150,98 @@ namespace ts { // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return updateSourceFile(node, [ - createStatement( - createCall( - define, - /*typeArguments*/ undefined, - [ - // Add the module name (if provided). - ...(moduleName ? [moduleName] : []), + return updateSourceFileNode(node, createNodeArray( + [ + createStatement( + createCall( + define, + /*typeArguments*/ undefined, + [ + // Add the module name (if provided). + ...(moduleName ? [moduleName] : []), - // Add the dependency array argument: - // - // ["require", "exports", module1", "module2", ...] - createArrayLiteral([ - createLiteral("require"), - createLiteral("exports"), - ...aliasedModuleNames, - ...unaliasedModuleNames - ]), + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + createArrayLiteral([ + createLiteral("require"), + createLiteral("exports"), + ...aliasedModuleNames, + ...unaliasedModuleNames + ]), - // Add the module body function argument: - // - // function (require, exports, module1, module2) ... - createFunctionExpression( - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - [ - createParameter("require"), - createParameter("exports"), - ...importAliasNames - ], - /*type*/ undefined, - transformAsynchronousModuleBody(node) - ) - ] + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + [ + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"), + ...importAliasNames + ], + /*type*/ undefined, + transformAsynchronousModuleBody(node) + ) + ] + ) ) - ) - ]); + ], + /*location*/ node.statements) + ); + } + + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ + function collectAsynchronousDependencies(node: SourceFile, includeNonAmdDependencies: boolean): AsynchronousDependencies { + // names of modules with corresponding parameter in the factory function + const aliasedModuleNames: Expression[] = []; + + // names of modules with no corresponding parameters in factory function + const unaliasedModuleNames: Expression[] = []; + + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + const importAliasNames: ParameterDeclaration[] = []; + + // Fill in amd-dependency tags + for (const amdDependency of node.amdDependencies) { + if (amdDependency.name) { + aliasedModuleNames.push(createLiteral(amdDependency.path)); + importAliasNames.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + } + else { + unaliasedModuleNames.push(createLiteral(amdDependency.path)); + } + } + + for (const importNode of currentModuleInfo.externalImports) { + // Find the name of the external module + const externalModuleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + + // Find the name of the module alias, if there is one + const importAliasName = getLocalNameForExternalImport(importNode, currentSourceFile); + if (includeNonAmdDependencies && importAliasName) { + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + setEmitFlags(importAliasName, EmitFlags.NoSubstitution); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + + return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; } /** @@ -205,10 +253,11 @@ namespace ts { startLexicalEnvironment(); const statements: Statement[] = []; - const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitor); + const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); // Visit each statement of the module body. - addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); + append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true)); + addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset)); // End the lexical environment for the module body // and merge any new lexical declarations. @@ -218,21 +267,29 @@ namespace ts { addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); const body = createBlock(statements, /*location*/ undefined, /*multiLine*/ true); - if (hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. - setEmitFlags(body, EmitFlags.EmitExportStar); + addEmitHelper(body, exportStarHelper); } return body; } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (currentModuleInfo.exportEquals) { if (emitAsReturn) { const statement = createReturn( - exportEquals.expression, - /*location*/ exportEquals + currentModuleInfo.exportEquals.expression, + /*location*/ currentModuleInfo.exportEquals ); setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments); @@ -245,9 +302,9 @@ namespace ts { createIdentifier("module"), "exports" ), - exportEquals.expression + currentModuleInfo.exportEquals.expression ), - /*location*/ exportEquals + /*location*/ currentModuleInfo.exportEquals ); setEmitFlags(statement, EmitFlags.NoComments); @@ -256,12 +313,16 @@ namespace ts { } } + // + // Top-Level Source Element Visitors + // + /** * Visits a node at the top level of the source file. * - * @param node The node. + * @param node The node to visit. */ - function visitor(node: Node): VisitResult { + function sourceElementVisitor(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.ImportDeclaration: return visitImportDeclaration(node); @@ -284,8 +345,11 @@ namespace ts { case SyntaxKind.ClassDeclaration: return visitClassDeclaration(node); - case SyntaxKind.ExpressionStatement: - return visitExpressionStatement(node); + case SyntaxKind.MergeDeclarationMarker: + return visitMergeDeclarationMarker(node); + + case SyntaxKind.EndOfDeclarationMarker: + return visitEndOfDeclarationMarker(node); default: // This visitor does not descend into the tree, as export/import statements @@ -297,24 +361,15 @@ namespace ts { /** * Visits an ImportDeclaration node. * - * @param node The ImportDeclaration node. + * @param node The node to visit. */ function visitImportDeclaration(node: ImportDeclaration): VisitResult { - if (!contains(externalImports, node)) { - return undefined; - } - - const statements: Statement[] = []; + let statements: Statement[]; const namespaceDeclaration = getNamespaceDeclarationNode(node); if (moduleKind !== ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - statements.push( - createStatement( - createRequireCall(node), - /*location*/ node - ) - ); + return createStatement(createRequireCall(node), /*location*/ node); } else { const variables: VariableDeclaration[] = []; @@ -352,10 +407,14 @@ namespace ts { } } - statements.push( + statements = append(statements, createVariableStatement( /*modifiers*/ undefined, - createConstDeclarationList(variables), + createVariableDeclarationList( + variables, + /*location*/ undefined, + languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None + ), /*location*/ node ) ); @@ -363,39 +422,66 @@ namespace ts { } else if (namespaceDeclaration && isDefaultImport(node)) { // import d, * as n from "mod"; - statements.push( + statements = append(statements, createVariableStatement( /*modifiers*/ undefined, - createVariableDeclarationList([ - createVariableDeclaration( - getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, - getGeneratedNameForNode(node), - /*location*/ node - ) - ]) + createVariableDeclarationList( + [ + createVariableDeclaration( + getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, + getGeneratedNameForNode(node), + /*location*/ node + ) + ], + /*location*/ undefined, + languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None + ) ) ); } - addExportImportAssignments(statements, node); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } + return singleOrMany(statements); } - function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { - if (!contains(externalImports, node)) { - return undefined; + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ + function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) { + const moduleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + const args: Expression[] = []; + if (moduleName) { + args.push(moduleName); } - // Set emitFlags on the name of the importEqualsDeclaration - // This is so the printer will not substitute the identifier - setEmitFlags(node.name, EmitFlags.NoSubstitution); - const statements: Statement[] = []; + return createCall(createIdentifier("require"), /*typeArguments*/ undefined, args); + } + + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + + let statements: Statement[]; if (moduleKind !== ModuleKind.AMD) { if (hasModifier(node, ModifierFlags.Export)) { - statements.push( + statements = append(statements, createStatement( - createExportAssignment( + createExportExpression( node.name, createRequireCall(node) ), @@ -404,18 +490,20 @@ namespace ts { ); } else { - statements.push( + statements = append(statements, createVariableStatement( /*modifiers*/ undefined, - createVariableDeclarationList([ - createVariableDeclaration( - getSynthesizedClone(node.name), - /*type*/ undefined, - createRequireCall(node) - ) - ], - /*location*/ undefined, - /*flags*/ languageVersion >= ScriptTarget.ES6 ? NodeFlags.Const : NodeFlags.None), + createVariableDeclarationList( + [ + createVariableDeclaration( + getSynthesizedClone(node.name), + /*type*/ undefined, + createRequireCall(node) + ) + ], + /*location*/ undefined, + /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None + ), /*location*/ node ) ); @@ -423,21 +511,36 @@ namespace ts { } else { if (hasModifier(node, ModifierFlags.Export)) { - statements.push( + statements = append(statements, createStatement( - createExportAssignment(node.name, node.name), + createExportExpression(getExportName(node), getLocalName(node)), /*location*/ node ) ); } } - addExportImportAssignments(statements, node); - return statements; + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + + return singleOrMany(statements); } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ function visitExportDeclaration(node: ExportDeclaration): VisitResult { - if (!contains(externalImports, node)) { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. return undefined; } @@ -461,23 +564,21 @@ namespace ts { ); } for (const specifier of node.exportClause.elements) { - if (resolver.isValueAliasDeclaration(specifier)) { - const exportedValue = createPropertyAccess( - generatedName, - specifier.propertyName || specifier.name - ); - statements.push( - createStatement( - createExportAssignment(specifier.name, exportedValue), - /*location*/ specifier - ) - ); - } + const exportedValue = createPropertyAccess( + generatedName, + specifier.propertyName || specifier.name + ); + statements.push( + createStatement( + createExportExpression(getExportName(specifier), exportedValue), + /*location*/ specifier + ) + ); } return singleOrMany(statements); } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + else { // export * from "mod"; return createStatement( createCall( @@ -494,220 +595,45 @@ namespace ts { } } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ function visitExportAssignment(node: ExportAssignment): VisitResult { - if (!node.isExportEquals) { - if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - const statements: Statement[] = []; - addExportDefault(statements, node.expression, /*location*/ node); - return statements; - } + if (node.isExportEquals) { + return undefined; } - return undefined; - } - - function addExportDefault(statements: Statement[], expression: Expression, location: TextRange): void { - tryAddExportDefaultCompat(statements); - - statements.push( - createStatement( - createExportAssignment( - createIdentifier("default"), - expression - ), - location - ) - ); - } - - function tryAddExportDefaultCompat(statements: Statement[]) { - const original = getOriginalNode(currentSourceFile); - Debug.assert(original.kind === SyntaxKind.SourceFile); - - if (!original.symbol.exports["___esModule"]) { - if (languageVersion === ScriptTarget.ES3) { - statements.push( - createStatement( - createExportAssignment( - createIdentifier("__esModule"), - createLiteral(true) - ) - ) - ); - } - else { - statements.push( - createStatement( - createCall( - createPropertyAccess(createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, - [ - createIdentifier("exports"), - createLiteral("__esModule"), - createObjectLiteral([ - createPropertyAssignment("value", createLiteral(true)) - ]) - ] - ) - ) - ); - } - } - } - - function addExportImportAssignments(statements: Statement[], node: ImportEqualsDeclaration | ImportDeclaration) { - if (isImportEqualsDeclaration(node)) { - addExportMemberAssignments(statements, node.name); + let statements: Statement[]; + const original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); } else { - const names = reduceEachChild(node, collectExportMembers, []); - for (const name of names) { - addExportMemberAssignments(statements, name); - } - } - } - - function collectExportMembers(names: Identifier[], node: Node): Identifier[] { - if (isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && isDeclaration(node)) { - const name = node.name; - if (isIdentifier(name)) { - names.push(name); - } + statements = appendExportStatement(statements, createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); } - return reduceEachChild(node, collectExportMembers, names); - } - - function addExportMemberAssignments(statements: Statement[], name: Identifier): void { - if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) { - for (const specifier of exportSpecifiers[name.text]) { - statements.push( - startOnNewLine( - createStatement( - createExportAssignment(specifier.name, name), - /*location*/ specifier.name - ) - ) - ); - } - } - } - - function addExportMemberAssignment(statements: Statement[], node: DeclarationStatement) { - if (hasModifier(node, ModifierFlags.Default)) { - addExportDefault(statements, getDeclarationName(node), /*location*/ node); - } - else { - statements.push( - createExportStatement(node.name, setEmitFlags(getSynthesizedClone(node.name), EmitFlags.LocalName), /*location*/ node) - ); - } - } - - function visitVariableStatement(node: VariableStatement): VisitResult { - // If the variable is for a generated declaration, - // we should maintain it and just strip off the 'export' modifier if necessary. - const originalKind = getOriginalNode(node).kind; - if (originalKind === SyntaxKind.ModuleDeclaration || - originalKind === SyntaxKind.EnumDeclaration || - originalKind === SyntaxKind.ClassDeclaration) { - - if (!hasModifier(node, ModifierFlags.Export)) { - return node; - } - - return setOriginalNode( - createVariableStatement( - /*modifiers*/ undefined, - node.declarationList - ), - node - ); - } - - const resultStatements: Statement[] = []; - - // If we're exporting these variables, then these just become assignments to 'exports.blah'. - // We only want to emit assignments for variables with initializers. - if (hasModifier(node, ModifierFlags.Export)) { - const variables = getInitializedVariables(node.declarationList); - if (variables.length > 0) { - const inlineAssignments = createStatement( - inlineExpressions( - map(variables, transformInitializedVariable) - ), - node - ); - resultStatements.push(inlineAssignments); - } - } - else { - resultStatements.push(node); - } - - // While we might not have been exported here, each variable might have been exported - // later on in an export specifier (e.g. `export {foo as blah, bar}`). - for (const decl of node.declarationList.declarations) { - addExportMemberAssignmentsForBindingName(resultStatements, decl.name); - } - - return resultStatements; + return singleOrMany(statements); } /** - * Creates appropriate assignments for each binding identifier that is exported in an export specifier, - * and inserts it into 'resultStatements'. + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. */ - function addExportMemberAssignmentsForBindingName(resultStatements: Statement[], name: BindingName): void { - if (isBindingPattern(name)) { - for (const element of name.elements) { - if (!isOmittedExpression(element)) { - addExportMemberAssignmentsForBindingName(resultStatements, element.name); - } - } - } - else { - if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) { - const sourceFileId = getOriginalNodeId(currentSourceFile); - if (!bindingNameExportSpecifiersForFileMap[sourceFileId]) { - bindingNameExportSpecifiersForFileMap[sourceFileId] = createMap(); - } - bindingNameExportSpecifiersForFileMap[sourceFileId][name.text] = exportSpecifiers[name.text]; - addExportMemberAssignments(resultStatements, name); - } - } - } - - function transformInitializedVariable(node: VariableDeclaration): Expression { - const name = node.name; - if (isBindingPattern(name)) { - return flattenVariableDestructuringToExpression( - context, - node, - hoistVariableDeclaration, - getModuleMemberName, - visitor - ); - } - else { - return createAssignment( - getModuleMemberName(name), - visitNode(node.initializer, visitor, isExpression) - ); - } - } - function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { - const statements: Statement[] = []; - const name = node.name || getGeneratedNameForNode(node); + let statements: Statement[]; if (hasModifier(node, ModifierFlags.Export)) { - statements.push( + statements = append(statements, setOriginalNode( createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, + visitNodes(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, - name, + getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, node.parameters, /*type*/ undefined, @@ -717,30 +643,37 @@ namespace ts { /*original*/ node ) ); - - addExportMemberAssignment(statements, node); } else { - statements.push(node); + statements = append(statements, node); } - if (node.name) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return singleOrMany(statements); } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ function visitClassDeclaration(node: ClassDeclaration): VisitResult { - const statements: Statement[] = []; - const name = node.name || getGeneratedNameForNode(node); + let statements: Statement[]; if (hasModifier(node, ModifierFlags.Export)) { - statements.push( + statements = append(statements, setOriginalNode( createClassDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, - name, + visitNodes(node.modifiers, modifierVisitor, isModifier), + getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, node.heritageClauses, node.members, @@ -749,108 +682,472 @@ namespace ts { /*original*/ node ) ); - - addExportMemberAssignment(statements, node); } else { - statements.push(node); + statements = append(statements, node); } - // Decorators end up creating a series of assignment expressions which overwrite - // the local binding that we export, so we need to defer from exporting decorated classes - // until the decoration assignments take place. We do this when visiting expression-statements. - if (node.name && !(node.decorators && node.decorators.length)) { - addExportMemberAssignments(statements, node.name); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); } return singleOrMany(statements); } - function visitExpressionStatement(node: ExpressionStatement): VisitResult { - const original = getOriginalNode(node); - const origKind = original.kind; + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ + function visitVariableStatement(node: VariableStatement): VisitResult { + let statements: Statement[]; + let variables: VariableDeclaration[]; + let expressions: Expression[]; + if (hasModifier(node, ModifierFlags.Export)) { + let modifiers: NodeArray; - if (origKind === SyntaxKind.EnumDeclaration || origKind === SyntaxKind.ModuleDeclaration) { - return visitExpressionStatementForEnumOrNamespaceDeclaration(node, original); - } - else if (origKind === SyntaxKind.ClassDeclaration) { - // The decorated assignment for a class name may need to be transformed. - const classDecl = original as ClassDeclaration; - if (classDecl.name) { - const statements = [node]; - addExportMemberAssignments(statements, classDecl.name); - return statements; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. + for (const variable of node.declarationList.declarations) { + if (isIdentifier(variable.name) && isLocalName(variable.name)) { + if (!modifiers) { + modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); + } + + variables = append(variables, variable); + } + else if (variable.initializer) { + expressions = append(expressions, transformInitializedVariable(variable)); + } } + + if (variables) { + statements = append(statements, updateVariableStatement(node, modifiers, updateVariableDeclarationList(node.declarationList, variables))); + } + + if (expressions) { + statements = append(statements, createStatement(inlineExpressions(expressions), /*location*/ node)); + } + } + else { + statements = append(statements, node); + } + + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); + } + else { + statements = appendExportsOfVariableStatement(statements, node); + } + + return singleOrMany(statements); + } + + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ + function transformInitializedVariable(node: VariableDeclaration): Expression { + if (isBindingPattern(node.name)) { + return flattenDestructuringAssignment( + node, + /*visitor*/ undefined, + context, + FlattenLevel.All, + /*needsValue*/ false, + createExportExpression + ); + } + else { + return createAssignment( + createPropertyAccess( + createIdentifier("exports"), + node.name, + /*location*/ node.name + ), + node.initializer + ); + } + } + + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node: MergeDeclarationMarker): VisitResult { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) { + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } return node; } - function visitExpressionStatementForEnumOrNamespaceDeclaration(node: ExpressionStatement, original: EnumDeclaration | ModuleDeclaration): VisitResult { - const statements: Statement[] = [node]; + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node: Node) { + return (getEmitFlags(node) & EmitFlags.HasEndOfDeclarationMarker) !== 0; + } - // Preserve old behavior for enums in which a variable statement is emitted after the body itself. - if (hasModifier(original, ModifierFlags.Export) && - original.kind === SyntaxKind.EnumDeclaration && - isFirstDeclarationOfKind(original, SyntaxKind.EnumDeclaration)) { - addVarForExportedEnumOrNamespaceDeclaration(statements, original); + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node: EndOfDeclarationMarker): VisitResult { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + const id = getOriginalNodeId(node); + const statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return append(statements, node); } - addExportMemberAssignments(statements, original.name); + return node; + } + + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements: Statement[] | undefined, decl: ImportDeclaration): Statement[] | undefined { + if (currentModuleInfo.exportEquals) { + return statements; + } + + const importClause = decl.importClause; + if (!importClause) { + return statements; + } + + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case SyntaxKind.NamespaceImport: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + + case SyntaxKind.NamedImports: + for (const importBinding of namedBindings.elements) { + statements = appendExportsOfDeclaration(statements, importBinding); + } + + break; + } + } return statements; } /** - * Adds a trailing VariableStatement for an enum or module declaration. + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. */ - function addVarForExportedEnumOrNamespaceDeclaration(statements: Statement[], node: EnumDeclaration | ModuleDeclaration) { - const transformedStatement = createVariableStatement( - /*modifiers*/ undefined, - [createVariableDeclaration( - getDeclarationName(node), - /*type*/ undefined, - createPropertyAccess(createIdentifier("exports"), getDeclarationName(node)) - )], - /*location*/ node + function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, decl: ImportEqualsDeclaration): Statement[] | undefined { + if (currentModuleInfo.exportEquals) { + return statements; + } + + return appendExportsOfDeclaration(statements, decl); + } + + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ + function appendExportsOfVariableStatement(statements: Statement[] | undefined, node: VariableStatement): Statement[] | undefined { + if (currentModuleInfo.exportEquals) { + return statements; + } + + for (const decl of node.declarationList.declarations) { + statements = appendExportsOfBindingElement(statements, decl); + } + + return statements; + } + + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfBindingElement(statements: Statement[] | undefined, decl: VariableDeclaration | BindingElement): Statement[] | undefined { + if (currentModuleInfo.exportEquals) { + return statements; + } + + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element); + } + } + } + else if (!isGeneratedIdentifier(decl.name)) { + statements = appendExportsOfDeclaration(statements, decl); + } + + return statements; + } + + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements: Statement[] | undefined, decl: ClassDeclaration | FunctionDeclaration): Statement[] | undefined { + if (currentModuleInfo.exportEquals) { + return statements; + } + + if (hasModifier(decl, ModifierFlags.Export)) { + const exportName = hasModifier(decl, ModifierFlags.Default) ? createIdentifier("default") : decl.name; + statements = appendExportStatement(statements, exportName, getLocalName(decl), /*location*/ decl); + } + + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl); + } + + return statements; + } + + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ + function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration): Statement[] | undefined { + const name = getDeclarationName(decl); + const exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + } + } + return statements; + } + + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean): Statement[] | undefined { + if (exportName.text === "default") { + const sourceFile = getOriginalNode(currentSourceFile, isSourceFile); + if (sourceFile && !sourceFile.symbol.exports["___esModule"]) { + if (languageVersion === ScriptTarget.ES3) { + statements = append(statements, + createStatement( + createExportExpression( + createIdentifier("__esModule"), + createLiteral(true) + ) + ) + ); + } + else { + statements = append(statements, + createStatement( + createCall( + createPropertyAccess(createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, + [ + createIdentifier("exports"), + createLiteral("__esModule"), + createObjectLiteral([ + createPropertyAssignment("value", createLiteral(true)) + ]) + ] + ) + ) + ); + } + } + } + + statements = append(statements, createExportStatement(exportName, expression, location, allowComments)); + return statements; + } + + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name: Identifier, value: Expression, location?: TextRange, allowComments?: boolean) { + const statement = createStatement(createExportExpression(name, value), location); + startOnNewLine(statement); + if (!allowComments) { + setEmitFlags(statement, EmitFlags.NoComments); + } + + return statement; + } + + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ + function createExportExpression(name: Identifier, value: Expression, location?: TextRange) { + return createAssignment( + createPropertyAccess( + createIdentifier("exports"), + getSynthesizedClone(name) + ), + value, + location ); - setEmitFlags(transformedStatement, EmitFlags.NoComments); - statements.push(transformedStatement); } - function getDeclarationName(node: DeclarationStatement) { - return node.name ? getSynthesizedClone(node.name) : getGeneratedNameForNode(node); + // + // Modifier Visitors + // + + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node: Node): VisitResult { + // Elide module-specific modifiers. + switch (node.kind) { + case SyntaxKind.ExportKeyword: + case SyntaxKind.DefaultKeyword: + return undefined; + } + + return node; } + // + // Emit Notification + // + + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { if (node.kind === SyntaxKind.SourceFile) { - bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[getOriginalNodeId(node)]; + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[getOriginalNodeId(currentSourceFile)]; + noSubstitution = createMap(); + previousOnEmitNode(emitContext, node, emitCallback); - bindingNameExportSpecifiersMap = undefined; + + currentSourceFile = undefined; + currentModuleInfo = undefined; + noSubstitution = undefined; } else { previousOnEmitNode(emitContext, node, emitCallback); } } + // + // Substitutions + // + /** * Hooks node substitutions. * + * @param emitContext A context hint for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ function onSubstituteNode(emitContext: EmitContext, node: Node) { node = previousOnSubstituteNode(emitContext, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (emitContext === EmitContext.Expression) { return substituteExpression(node); } else if (isShorthandPropertyAssignment(node)) { return substituteShorthandPropertyAssignment(node); } + return node; } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ function substituteShorthandPropertyAssignment(node: ShorthandPropertyAssignment): ObjectLiteralElementLike { const name = node.name; const exportedOrImportedName = substituteExpressionIdentifier(name); @@ -866,6 +1163,11 @@ namespace ts { return node; } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.Identifier: @@ -880,220 +1182,166 @@ namespace ts { return node; } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ function substituteExpressionIdentifier(node: Identifier): Expression { - return trySubstituteExportedName(node) - || trySubstituteImportedName(node) - || node; - } - - function substituteBinaryExpression(node: BinaryExpression): Expression { - const left = node.left; - // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier - if (isIdentifier(left) && isAssignmentOperator(node.operatorToken.kind)) { - if (bindingNameExportSpecifiersMap && hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setEmitFlags(node, EmitFlags.NoSubstitution); - let nestedExportAssignment: BinaryExpression; - for (const specifier of bindingNameExportSpecifiersMap[left.text]) { - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, node); - } - return nestedExportAssignment; + if (getEmitFlags(node) & EmitFlags.HelperName) { + const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return createPropertyAccess(externalHelpersModuleName, node); } + return node; } - return node; - } - function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression { - // Because how the compiler only parse plusplus and minusminus to be either prefixUnaryExpression or postFixUnaryExpression depended on where they are - // We don't need to check that the operator has SyntaxKind.plusplus or SyntaxKind.minusminus - const operator = node.operator; - const operand = node.operand; - if (isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { - if (bindingNameExportSpecifiersMap && hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setEmitFlags(node, EmitFlags.NoSubstitution); - let transformedUnaryExpression: BinaryExpression; - if (node.kind === SyntaxKind.PostfixUnaryExpression) { - transformedUnaryExpression = createBinary( - operand, - createToken(operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusEqualsToken : SyntaxKind.MinusEqualsToken), - createLiteral(1), - /*location*/ node - ); - // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setEmitFlags(transformedUnaryExpression, EmitFlags.NoSubstitution); - } - let nestedExportAssignment: BinaryExpression; - for (const specifier of bindingNameExportSpecifiersMap[operand.text]) { - nestedExportAssignment = nestedExportAssignment ? - createExportAssignment(specifier.name, nestedExportAssignment) : - createExportAssignment(specifier.name, transformedUnaryExpression || node); - } - return nestedExportAssignment; + if (!isGeneratedIdentifier(node) && !isLocalName(node)) { + const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node)); + if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) { + return createPropertyAccess( + createIdentifier("exports"), + getSynthesizedClone(node), + /*location*/ node + ); } - } - return node; - } - function trySubstituteExportedName(node: Identifier) { - const emitFlags = getEmitFlags(node); - if ((emitFlags & EmitFlags.LocalName) === 0) { - const container = resolver.getReferencedExportContainer(node, (emitFlags & EmitFlags.ExportName) !== 0); - if (container) { - if (container.kind === SyntaxKind.SourceFile) { + const importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (isImportClause(importDeclaration)) { return createPropertyAccess( - createIdentifier("exports"), - getSynthesizedClone(node), + getGeneratedNameForNode(importDeclaration.parent), + createIdentifier("default"), + /*location*/ node + ); + } + else if (isImportSpecifier(importDeclaration)) { + const name = importDeclaration.propertyName || importDeclaration.name; + return createPropertyAccess( + getGeneratedNameForNode(importDeclaration.parent.parent.parent), + getSynthesizedClone(name), /*location*/ node ); } } } - - return undefined; + return node; } - function trySubstituteImportedName(node: Identifier): Expression { - if ((getEmitFlags(node) & EmitFlags.LocalName) === 0) { - const declaration = resolver.getReferencedImportDeclaration(node); - if (declaration) { - if (isImportClause(declaration)) { - if (languageVersion >= ScriptTarget.ES5) { - return createPropertyAccess( - getGeneratedNameForNode(declaration.parent), - createIdentifier("default"), - /*location*/ node - ); - } - else { - // TODO: ES3 transform to handle x.default -> x["default"] - return createElementAccess( - getGeneratedNameForNode(declaration.parent), - createLiteral("default"), - /*location*/ node - ); - } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteBinaryExpression(node: BinaryExpression): Expression { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) + && !isGeneratedIdentifier(node.left) + && !isLocalName(node.left) + && !isDeclarationNameOfEnumOrNamespace(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + let expression: Expression = node; + for (const exportName of exportedNames) { + // Mark the node to prevent triggering this rule again. + noSubstitution[getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression, /*location*/ node); } - else if (isImportSpecifier(declaration)) { - const name = declaration.propertyName || declaration.name; - if (name.originalKeywordKind === SyntaxKind.DefaultKeyword && languageVersion <= ScriptTarget.ES3) { - // TODO: ES3 transform to handle x.default -> x["default"] - return createElementAccess( - getGeneratedNameForNode(declaration.parent.parent.parent), - createLiteral(name.text), - /*location*/ node - ); - } - else { - return createPropertyAccess( - getGeneratedNameForNode(declaration.parent.parent.parent), - getSynthesizedClone(name), - /*location*/ node - ); - } + + return expression; + } + } + + return node; + } + + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression { + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) + && isIdentifier(node.operand) + && !isGeneratedIdentifier(node.operand) + && !isLocalName(node.operand) + && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + const exportedNames = getExports(node.operand); + if (exportedNames) { + let expression: Expression = node.kind === SyntaxKind.PostfixUnaryExpression + ? createBinary( + node.operand, + createToken(node.operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusEqualsToken : SyntaxKind.MinusEqualsToken), + createLiteral(1), + /*location*/ node) + : node; + for (const exportName of exportedNames) { + // Mark the node to prevent triggering this rule again. + noSubstitution[getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); } - } - } - return undefined; - } - function getModuleMemberName(name: Identifier) { - return createPropertyAccess( - createIdentifier("exports"), - name, - /*location*/ name - ); - } - - function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) { - const moduleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - const args: Expression[] = []; - if (isDefined(moduleName)) { - args.push(moduleName); - } - - return createCall(createIdentifier("require"), /*typeArguments*/ undefined, args); - } - - function createExportStatement(name: Identifier, value: Expression, location?: TextRange) { - const statement = createStatement(createExportAssignment(name, value)); - statement.startsOnNewLine = true; - if (location) { - setSourceMapRange(statement, location); - } - - return statement; - } - - function createExportAssignment(name: Identifier, value: Expression) { - return createAssignment( - name.originalKeywordKind === SyntaxKind.DefaultKeyword && languageVersion === ScriptTarget.ES3 - ? createElementAccess( - createIdentifier("exports"), - createLiteral(name.text) - ) - : createPropertyAccess( - createIdentifier("exports"), - getSynthesizedClone(name) - ), - value - ); - } - - interface AsynchronousDependencies { - aliasedModuleNames: Expression[]; - unaliasedModuleNames: Expression[]; - importAliasNames: ParameterDeclaration[]; - } - - function collectAsynchronousDependencies(node: SourceFile, includeNonAmdDependencies: boolean): AsynchronousDependencies { - // names of modules with corresponding parameter in the factory function - const aliasedModuleNames: Expression[] = []; - - // names of modules with no corresponding parameters in factory function - const unaliasedModuleNames: Expression[] = []; - - // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - const importAliasNames: ParameterDeclaration[] = []; - - // Fill in amd-dependency tags - for (const amdDependency of node.amdDependencies) { - if (amdDependency.name) { - aliasedModuleNames.push(createLiteral(amdDependency.path)); - importAliasNames.push(createParameter(amdDependency.name)); - } - else { - unaliasedModuleNames.push(createLiteral(amdDependency.path)); + return expression; } } - for (const importNode of externalImports) { - // Find the name of the external module - const externalModuleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); - - // Find the name of the module alias, if there is one - const importAliasName = getLocalNameForExternalImport(importNode, currentSourceFile); - if (includeNonAmdDependencies && importAliasName) { - // Set emitFlags on the name of the classDeclaration - // This is so that when printer will not substitute the identifier - setEmitFlags(importAliasName, EmitFlags.NoSubstitution); - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(createParameter(importAliasName)); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - - return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; + return node; } - function updateSourceFile(node: SourceFile, statements: Statement[]) { - const updated = getMutableClone(node); - updated.statements = createNodeArray(statements, node.statements); - return updated; + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ + function getExports(name: Identifier): Identifier[] | undefined { + if (!isGeneratedIdentifier(name)) { + const valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (valueDeclaration) { + return currentModuleInfo + && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + } + } } } + + // emit output for the __export helper function + const exportStarHelper: EmitHelper = { + name: "typescript:export-star", + scoped: true, + text: ` + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + }` + }; + + // emit output for the UMD helper function. + const umdHelper = ` + (function (dependencies, factory) { + if (typeof module === 'object' && typeof module.exports === 'object') { + var v = factory(require, exports); if (v !== undefined) module.exports = v; + } + else if (typeof define === 'function' && define.amd) { + define(dependencies, factory); + } + })`; } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 303c0e1bb96..0e3a42da0d2 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -12,70 +12,53 @@ namespace ts { const { startLexicalEnvironment, endLexicalEnvironment, - hoistVariableDeclaration, - hoistFunctionDeclaration, + hoistVariableDeclaration } = context; const compilerOptions = context.getCompilerOptions(); const resolver = context.getEmitResolver(); const host = context.getEmitHost(); - const languageVersion = getEmitScriptTarget(compilerOptions); const previousOnSubstituteNode = context.onSubstituteNode; const previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(SyntaxKind.Identifier); - context.enableSubstitution(SyntaxKind.BinaryExpression); - context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); - context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); - context.enableEmitNotification(SyntaxKind.SourceFile); + context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols. + context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); // Substitutes updates to exported symbols. + context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); // Substitutes updates to exported symbols. + context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file. - const exportFunctionForFileMap: Identifier[] = []; - let currentSourceFile: SourceFile; - let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; - let exportSpecifiers: Map; - let exportEquals: ExportAssignment; - let hasExportStarsToExportValues: boolean; - let exportFunctionForFile: Identifier; - let contextObjectForFile: Identifier; - let exportedLocalNames: Identifier[]; - let exportedFunctionDeclarations: ExpressionStatement[]; + const moduleInfoMap = createMap(); // The ExternalModuleInfo for each file. + const deferredExports = createMap(); // Exports to defer until an EndOfDeclarationMarker is found. + const exportFunctionsMap = createMap(); // The export function associated with a source file. + const noSubstitutionMap = createMap>(); // Set of nodes for which substitution rules should be ignored for each file. + let currentSourceFile: SourceFile; // The current file. + let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file. + let exportFunction: Identifier; // The export function for the current file. + let contextObject: Identifier; // The context object for the current file. + let hoistedStatements: Statement[]; let enclosingBlockScopedContainer: Node; - let currentParent: Node; - let currentNode: Node; + let noSubstitution: Map; // Set of nodes for which substitution rules should be ignored. return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ function transformSourceFile(node: SourceFile) { - if (isDeclarationFile(node)) { + if (isDeclarationFile(node) + || !(isExternalModule(node) + || compilerOptions.isolatedModules)) { return node; } - if (isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; - currentNode = node; + const id = getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; - // Perform the transformation. - const updated = transformSystemModuleWorker(node); - aggregateTransformFlags(updated); - - currentSourceFile = undefined; - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStarsToExportValues = false; - exportFunctionForFile = undefined; - contextObjectForFile = undefined; - exportedLocalNames = undefined; - exportedFunctionDeclarations = undefined; - return updated; - } - - return node; - } - - function transformSystemModuleWorker(node: SourceFile) { // System modules have the following shape: // // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) @@ -88,66 +71,107 @@ namespace ts { // // The only exception in this rule is postfix unary operators, // see comment to 'substitutePostfixUnaryExpression' for more details - Debug.assert(!exportFunctionForFile); // Collect information about the external module and dependency groups. - ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver)); + moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(node, resolver, compilerOptions); // Make sure that the name of the 'exports' function does not conflict with // existing identifiers. - exportFunctionForFile = createUniqueName("exports"); - contextObjectForFile = createUniqueName("context"); - - exportFunctionForFileMap[getOriginalNodeId(node)] = exportFunctionForFile; - - const dependencyGroups = collectDependencyGroups(externalImports); - - const statements: Statement[] = []; + exportFunction = exportFunctionsMap[id] = createUniqueName("exports"); + contextObject = createUniqueName("context"); // Add the body of the module. - addSystemModuleBody(statements, node, dependencyGroups); - - const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions); - const dependencies = createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup)); - const body = createFunctionExpression( + const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + const moduleBodyFunction = createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - createParameter(exportFunctionForFile), - createParameter(contextObjectForFile) + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, - setEmitFlags( - createBlock(statements, /*location*/ undefined, /*multiLine*/ true), - EmitFlags.EmitEmitHelpers - ) + moduleBodyBlock ); // Write the call to `System.register` // Clear the emit-helpers flag for later passes since we'll have already used it in the module body // So the helper will be emit at the correct position instead of at the top of the source-file - return updateSourceFile(node, [ - createStatement( - createCall( - createPropertyAccess(createIdentifier("System"), "register"), - /*typeArguments*/ undefined, - moduleName - ? [moduleName, dependencies, body] - : [dependencies, body] - ) - ) - ], /*nodeEmitFlags*/ ~EmitFlags.EmitEmitHelpers & getEmitFlags(node)); + const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions); + const dependencies = createArrayLiteral(map(dependencyGroups, dependencyGroup => dependencyGroup.name)); + const updated = setEmitFlags( + updateSourceFileNode( + node, + createNodeArray([ + createStatement( + createCall( + createPropertyAccess(createIdentifier("System"), "register"), + /*typeArguments*/ undefined, + moduleName + ? [moduleName, dependencies, moduleBodyFunction] + : [dependencies, moduleBodyFunction] + ) + ) + ], node.statements) + ), EmitFlags.NoTrailingComments); + + if (!(compilerOptions.outFile || compilerOptions.out)) { + moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped); + } + + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = undefined; + } + + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + contextObject = undefined; + hoistedStatements = undefined; + enclosingBlockScopedContainer = undefined; + + return aggregateTransformFlags(updated); + } + + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ + function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) { + const groupIndices = createMap(); + const dependencyGroups: DependencyGroup[] = []; + for (let i = 0; i < externalImports.length; i++) { + const externalImport = externalImports[i]; + const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); + const text = externalModuleName.text; + if (hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + const groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].externalImports.push(externalImport); + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + + return dependencyGroups; } /** * Adds the statements for the module body function for the source file. * - * @param statements The output statements for the module body. * @param node The source file for the module. - * @param statementOffset The offset at which to begin visiting the statements of the SourceFile. + * @param dependencyGroups The grouped dependencies of the module. */ - function addSystemModuleBody(statements: Statement[], node: SourceFile, dependencyGroups: DependencyGroup[]) { + function createSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[]) { // Shape of the body in system modules: // // function (exports) { @@ -175,10 +199,9 @@ namespace ts { // Will be transformed to: // // function(exports) { - // var file_1; // local alias - // var y; // function foo() { return y + file_1.x(); } // exports("foo", foo); + // var file_1, y; // return { // setters: [ // function(v) { file_1 = v } @@ -190,13 +213,15 @@ namespace ts { // }; // } + const statements: Statement[] = []; + // We start a new lexical environment in this function body, but *not* in the // body of the execute function. This allows us to emit temporary declarations // only in the outer module body and not in the inner one. startLexicalEnvironment(); // Add any prologue directives. - const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, visitSourceElement); + const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); // var __moduleName = context_1 && context_1.id; statements.push( @@ -207,43 +232,43 @@ namespace ts { "__moduleName", /*type*/ undefined, createLogicalAnd( - contextObjectForFile, - createPropertyAccess(contextObjectForFile, "id") + contextObject, + createPropertyAccess(contextObject, "id") ) ) ]) ) ); + // Visit the synthetic external helpers import declaration if present + visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true); + // Visit the statements of the source file, emitting any transformations into // the `executeStatements` array. We do this *before* we fill the `setters` array // as we both emit transformations as well as aggregate some data used when creating // setters. This allows us to reduce the number of times we need to loop through the // statements of the source file. - const executeStatements = visitNodes(node.statements, visitSourceElement, isStatement, statementOffset); - - // We emit the lexical environment (hoisted variables and function declarations) - // early to align roughly with our previous emit output. - // Two key differences in this approach are: - // - Temporary variables will appear at the top rather than at the bottom of the file - // - Calls to the exporter for exported function declarations are grouped after - // the declarations. - addRange(statements, endLexicalEnvironment()); + const executeStatements = visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset); // Emit early exports for function declarations. - addRange(statements, exportedFunctionDeclarations); + addRange(statements, hoistedStatements); + + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file + addRange(statements, endLexicalEnvironment()); const exportStarFunction = addExportStarIfNeeded(statements); - statements.push( createReturn( setMultiLine( createObjectLiteral([ createPropertyAssignment("setters", - generateSetters(exportStarFunction, dependencyGroups) + createSettersArray(exportStarFunction, dependencyGroups) ), createPropertyAssignment("execute", createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -261,24 +286,32 @@ namespace ts { ) ) ); + + return createBlock(statements, /*location*/ undefined, /*multiLine*/ true); } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ function addExportStarIfNeeded(statements: Statement[]) { - if (!hasExportStarsToExportValues) { + if (!moduleInfo.hasExportStarsToExportValues) { return; } + // when resolving exports local exported entries/indirect exported entries in the module // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. // this set is used to filter names brought by star expors. // local names set should only be added if we have anything exported - if (!exportedLocalNames && isEmpty(exportSpecifiers)) { + if (!moduleInfo.exportedNames && isEmpty(moduleInfo.exportSpecifiers)) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. let hasExportDeclarationWithExportClause = false; - for (const externalImport of externalImports) { - if (externalImport.kind === SyntaxKind.ExportDeclaration && (externalImport).exportClause) { + for (const externalImport of moduleInfo.externalImports) { + if (externalImport.kind === SyntaxKind.ExportDeclaration && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -286,24 +319,30 @@ namespace ts { if (!hasExportDeclarationWithExportClause) { // we still need to emit exportStar helper - return addExportStarFunction(statements, /*localNames*/ undefined); + const exportStarFunction = createExportStarFunction(/*localNames*/ undefined); + statements.push(exportStarFunction); + return exportStarFunction.name; } } const exportedNames: ObjectLiteralElementLike[] = []; - if (exportedLocalNames) { - for (const exportedLocalName of exportedLocalNames) { + if (moduleInfo.exportedNames) { + for (const exportedLocalName of moduleInfo.exportedNames) { + if (exportedLocalName.text === "default") { + continue; + } + // write name of exported declaration, i.e 'export var x...' exportedNames.push( createPropertyAssignment( - createLiteral(exportedLocalName.text), + createLiteral(exportedLocalName), createLiteral(true) ) ); } } - for (const externalImport of externalImports) { + for (const externalImport of moduleInfo.externalImports) { if (externalImport.kind !== SyntaxKind.ExportDeclaration) { continue; } @@ -339,14 +378,96 @@ namespace ts { ) ); - return addExportStarFunction(statements, exportedNamesStorageRef); + const exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; } /** - * Emits a setter callback for each dependency group. - * @param write The callback used to write each callback. + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. */ - function generateSetters(exportStarFunction: Identifier, dependencyGroups: DependencyGroup[]) { + function createExportStarFunction(localNames: Identifier | undefined) { + const exportStarFunction = createUniqueName("exportStar"); + const m = createIdentifier("m"); + const n = createIdentifier("n"); + const exports = createIdentifier("exports"); + let condition: Expression = createStrictInequality(n, createLiteral("default")); + if (localNames) { + condition = createLogicalAnd( + condition, + createLogicalNot( + createCall( + createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, + [n] + ) + ) + ); + } + + return createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + exportStarFunction, + /*typeParameters*/ undefined, + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, + createBlock([ + createVariableStatement( + /*modifiers*/ undefined, + createVariableDeclarationList([ + createVariableDeclaration( + exports, + /*type*/ undefined, + createObjectLiteral([]) + ) + ]) + ), + createForIn( + createVariableDeclarationList([ + createVariableDeclaration(n, /*type*/ undefined) + ]), + m, + createBlock([ + setEmitFlags( + createIf( + condition, + createStatement( + createAssignment( + createElementAccess(exports, n), + createElementAccess(m, n) + ) + ) + ), + EmitFlags.SingleLine + ) + ]) + ), + createStatement( + createCall( + exportFunction, + /*typeArguments*/ undefined, + [exports] + ) + ) + ], + /*location*/ undefined, + /*multiline*/ true) + ); + } + + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ + function createSettersArray(exportStarFunction: Identifier, dependencyGroups: DependencyGroup[]) { const setters: Expression[] = []; for (const group of dependencyGroups) { // derive a unique name for parameter from the first named entry in the group @@ -401,7 +522,7 @@ namespace ts { statements.push( createStatement( createCall( - exportFunctionForFile, + exportFunction, /*typeArguments*/ undefined, [createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)] ) @@ -430,10 +551,11 @@ namespace ts { setters.push( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - [createParameter(parameterName)], + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, createBlock(statements, /*location*/ undefined, /*multiLine*/ true) ) @@ -443,7 +565,16 @@ namespace ts { return createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true); } - function visitSourceElement(node: Node): VisitResult { + // + // Top-level Source Element Visitors + // + + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.ImportDeclaration: return visitImportDeclaration(node); @@ -452,39 +583,569 @@ namespace ts { return visitImportEqualsDeclaration(node); case SyntaxKind.ExportDeclaration: - return visitExportDeclaration(node); + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. + return undefined; case SyntaxKind.ExportAssignment: return visitExportAssignment(node); default: - return visitNestedNode(node); + return nestedElementVisitor(node); } } - function visitNestedNode(node: Node): VisitResult { - const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; - const savedCurrentParent = currentParent; - const savedCurrentNode = currentNode; - - const currentGrandparent = currentParent; - currentParent = currentNode; - currentNode = node; - - if (currentParent && isBlockScope(currentParent, currentGrandparent)) { - enclosingBlockScopedContainer = currentParent; + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ + function visitImportDeclaration(node: ImportDeclaration): VisitResult { + let statements: Statement[]; + if (node.importClause) { + hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)); } - const result = visitNestedNodeWorker(node); + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportDeclaration(statements, node); + } - enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; - currentParent = savedCurrentParent; - currentNode = savedCurrentNode; - - return result; + return singleOrMany(statements); } - function visitNestedNodeWorker(node: Node): VisitResult { + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ + function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + + let statements: Statement[]; + hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)); + + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfImportEqualsDeclaration(statements, node); + } + + return singleOrMany(statements); + } + + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ + function visitExportAssignment(node: ExportAssignment): VisitResult { + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; + } + + const expression = visitNode(node.expression, destructuringVisitor, isExpression); + const original = node.original; + if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportStatement(deferredExports[id], createIdentifier("default"), expression, /*allowComments*/ true); + } + else { + return createExportStatement(createIdentifier("default"), expression, /*allowComments*/ true); + } + } + + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ + function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { + if (hasModifier(node, ModifierFlags.Export)) { + hoistedStatements = append(hoistedStatements, + updateFunctionDeclaration( + node, + node.decorators, + visitNodes(node.modifiers, modifierVisitor, isModifier), + getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, + visitNodes(node.parameters, destructuringVisitor, isParameterDeclaration), + /*type*/ undefined, + visitNode(node.body, destructuringVisitor, isBlock))); + } + else { + hoistedStatements = append(hoistedStatements, node); + } + + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + } + + return undefined; + } + + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ + function visitClassDeclaration(node: ClassDeclaration): VisitResult { + let statements: Statement[]; + + // Hoist the name of the class declaration to the outer module body function. + const name = getLocalName(node); + hoistVariableDeclaration(name); + + // Rewrite the class declaration into an assignment of a class expression. + statements = append(statements, + createStatement( + createAssignment( + name, + createClassExpression( + /*modifiers*/ undefined, + node.name, + /*typeParameters*/ undefined, + visitNodes(node.heritageClauses, destructuringVisitor, isHeritageClause), + visitNodes(node.members, destructuringVisitor, isClassElement), + /*location*/ node + ) + ), + /*location*/ node + ) + ); + + if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); + } + else { + statements = appendExportsOfHoistedDeclaration(statements, node); + } + + return singleOrMany(statements); + } + + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ + function visitVariableStatement(node: VariableStatement): VisitResult { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return visitNode(node, destructuringVisitor, isStatement); + } + + let expressions: Expression[]; + const isExportedDeclaration = hasModifier(node, ModifierFlags.Export); + const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); + for (const variable of node.declarationList.declarations) { + if (variable.initializer) { + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + } + else { + hoistBindingElement(variable); + } + } + + let statements: Statement[]; + if (expressions) { + statements = append(statements, createStatement(inlineExpressions(expressions), /*location*/ node)); + } + + if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node + const id = getOriginalNodeId(node); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); + } + else { + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); + } + + return singleOrMany(statements); + } + + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ + function hoistBindingElement(node: VariableDeclaration | BindingElement): void { + if (isBindingPattern(node.name)) { + for (const element of node.name.elements) { + if (!isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } + else { + hoistVariableDeclaration(getSynthesizedClone(node.name)); + } + } + + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ + function shouldHoistVariableDeclarationList(node: VariableDeclarationList) { + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (getEmitFlags(node) & EmitFlags.NoHoisting) === 0 + && (enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile + || (getOriginalNode(node).flags & NodeFlags.BlockScoped) === 0); + } + + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression { + const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return isBindingPattern(node.name) + ? flattenDestructuringAssignment( + node, + destructuringVisitor, + context, + FlattenLevel.All, + /*needsValue*/ false, + createAssignment + ) + : createAssignment(node.name, visitNode(node.initializer, destructuringVisitor, isExpression)); + } + + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ + function createNonExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) { + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ + function createVariableAssignment(name: Identifier, value: Expression, location: TextRange, isExportedDeclaration: boolean) { + hoistVariableDeclaration(getSynthesizedClone(name)); + return isExportedDeclaration + ? createExportExpression(name, preventSubstitution(createAssignment(name, value, location))) + : preventSubstitution(createAssignment(name, value, location)); + } + + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ + function visitMergeDeclarationMarker(node: MergeDeclarationMarker): VisitResult { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) { + const id = getOriginalNodeId(node); + const isExportedDeclaration = hasModifier(node.original, ModifierFlags.Export); + deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); + } + + return node; + } + + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ + function hasAssociatedEndOfDeclarationMarker(node: Node) { + return (getEmitFlags(node) & EmitFlags.HasEndOfDeclarationMarker) !== 0; + } + + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ + function visitEndOfDeclarationMarker(node: EndOfDeclarationMarker): VisitResult { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. + const id = getOriginalNodeId(node); + const statements = deferredExports[id]; + if (statements) { + delete deferredExports[id]; + return append(statements, node); + } + + return node; + } + + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportDeclaration(statements: Statement[], decl: ImportDeclaration) { + if (moduleInfo.exportEquals) { + return statements; + } + + const importClause = decl.importClause; + if (!importClause) { + return statements; + } + + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case SyntaxKind.NamespaceImport: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + + case SyntaxKind.NamedImports: + for (const importBinding of namedBindings.elements) { + statements = appendExportsOfDeclaration(statements, importBinding); + } + + break; + } + } + + return statements; + } + + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfImportEqualsDeclaration(statements: Statement[], decl: ImportEqualsDeclaration): Statement[] | undefined { + if (moduleInfo.exportEquals) { + return statements; + } + + return appendExportsOfDeclaration(statements, decl); + } + + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ + function appendExportsOfVariableStatement(statements: Statement[] | undefined, node: VariableStatement, exportSelf: boolean): Statement[] | undefined { + if (moduleInfo.exportEquals) { + return statements; + } + + for (const decl of node.declarationList.declarations) { + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + + return statements; + } + + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ + function appendExportsOfBindingElement(statements: Statement[] | undefined, decl: VariableDeclaration | BindingElement, exportSelf: boolean): Statement[] | undefined { + if (moduleInfo.exportEquals) { + return statements; + } + + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } + else if (!isGeneratedIdentifier(decl.name)) { + let excludeName: string; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, getLocalName(decl)); + excludeName = decl.name.text; + } + + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + + return statements; + } + + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ + function appendExportsOfHoistedDeclaration(statements: Statement[] | undefined, decl: ClassDeclaration | FunctionDeclaration): Statement[] | undefined { + if (moduleInfo.exportEquals) { + return statements; + } + + let excludeName: string; + if (hasModifier(decl, ModifierFlags.Export)) { + const exportName = hasModifier(decl, ModifierFlags.Default) ? createLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, getLocalName(decl)); + excludeName = exportName.text; + } + + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + + return statements; + } + + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ + function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, excludeName?: string): Statement[] | undefined { + if (moduleInfo.exportEquals) { + return statements; + } + + const name = getDeclarationName(decl); + const exportSpecifiers = moduleInfo.exportSpecifiers[name.text]; + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + if (exportSpecifier.name.text !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ + function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier | StringLiteral, expression: Expression, allowComments?: boolean): Statement[] | undefined { + statements = append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ + function createExportStatement(name: Identifier | StringLiteral, value: Expression, allowComments?: boolean) { + const statement = createStatement(createExportExpression(name, value)); + startOnNewLine(statement); + if (!allowComments) { + setEmitFlags(statement, EmitFlags.NoComments); + } + + return statement; + } + + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ + function createExportExpression(name: Identifier | StringLiteral, value: Expression) { + const exportName = isIdentifier(name) ? createLiteral(name) : name; + return createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]); + } + + // + // Top-Level or Nested Source Element Visitors + // + + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ + function nestedElementVisitor(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.VariableStatement: return visitVariableStatement(node); @@ -537,377 +1198,171 @@ namespace ts { case SyntaxKind.Block: return visitBlock(node); - case SyntaxKind.ExpressionStatement: - return visitExpressionStatement(node); + case SyntaxKind.MergeDeclarationMarker: + return visitMergeDeclarationMarker(node); + + case SyntaxKind.EndOfDeclarationMarker: + return visitEndOfDeclarationMarker(node); default: - return node; + return destructuringVisitor(node); } } - function visitImportDeclaration(node: ImportDeclaration): Node { - if (node.importClause && contains(externalImports, node)) { - hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)); - } - - return undefined; - } - - function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): Node { - if (contains(externalImports, node)) { - hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)); - } - - // NOTE(rbuckton): Do we support export import = require('') in System? - return undefined; - } - - function visitExportDeclaration(node: ExportDeclaration): VisitResult { - if (!node.moduleSpecifier) { - const statements: Statement[] = []; - addRange(statements, map(node.exportClause.elements, visitExportSpecifier)); - return statements; - } - - return undefined; - } - - function visitExportSpecifier(specifier: ExportSpecifier): Statement { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement( - specifier.name, - specifier.propertyName || specifier.name - ); - } - return undefined; - } - - function visitExportAssignment(node: ExportAssignment): Statement { - if (!node.isExportEquals) { - if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement( - createLiteral("default"), - node.expression - ); - } - } - - return undefined; - } - - /** - * Visits a variable statement, hoisting declared names to the top-level module body. - * Each declaration is rewritten into an assignment expression. - * - * @param node The variable statement to visit. - */ - function visitVariableStatement(node: VariableStatement): VisitResult { - // hoist only non-block scoped declarations or block scoped declarations parented by source file - const shouldHoist = - ((getCombinedNodeFlags(getOriginalNode(node.declarationList)) & NodeFlags.BlockScoped) == 0) || - enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile; - if (!shouldHoist) { - return node; - } - const isExported = hasModifier(node, ModifierFlags.Export); - const expressions: Expression[] = []; - for (const variable of node.declarationList.declarations) { - const visited = transformVariable(variable, isExported); - if (visited) { - expressions.push(visited); - } - } - - if (expressions.length) { - return createStatement(inlineExpressions(expressions), node); - } - - return undefined; - } - - /** - * Transforms a VariableDeclaration into one or more assignment expressions. - * - * @param node The VariableDeclaration to transform. - * @param isExported A value used to indicate whether the containing statement was exported. - */ - function transformVariable(node: VariableDeclaration, isExported: boolean): VariableDeclaration | Expression { - // Hoist any bound names within the declaration. - hoistBindingElement(node, isExported); - - if (!node.initializer) { - // If the variable has no initializer, ignore it. - return; - } - - const name = node.name; - if (isIdentifier(name)) { - // If the variable has an IdentifierName, write out an assignment expression in its place. - return createAssignment(name, node.initializer); - } - else { - // If the variable has a BindingPattern, flatten the variable into multiple assignment expressions. - return flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration); - } - } - - /** - * Visits a FunctionDeclaration, hoisting it to the outer module body function. - * - * @param node The function declaration to visit. - */ - function visitFunctionDeclaration(node: FunctionDeclaration): Node { - if (hasModifier(node, ModifierFlags.Export)) { - // If the function is exported, ensure it has a name and rewrite the function without any export flags. - const name = node.name || getGeneratedNameForNode(node); - const newNode = createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - node.asteriskToken, - name, - /*typeParameters*/ undefined, - node.parameters, - /*type*/ undefined, - node.body, - /*location*/ node); - - // Record a declaration export in the outer module body function. - recordExportedFunctionDeclaration(node); - - if (!hasModifier(node, ModifierFlags.Default)) { - recordExportName(name); - } - - setOriginalNode(newNode, node); - node = newNode; - } - - // Hoist the function declaration to the outer module body function. - hoistFunctionDeclaration(node); - return undefined; - } - - function visitExpressionStatement(node: ExpressionStatement): VisitResult { - const originalNode = getOriginalNode(node); - if ((originalNode.kind === SyntaxKind.ModuleDeclaration || originalNode.kind === SyntaxKind.EnumDeclaration) && hasModifier(originalNode, ModifierFlags.Export)) { - const name = getDeclarationName(originalNode); - // We only need to hoistVariableDeclaration for EnumDeclaration - // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement - // which then call transformsVariable for each declaration in declarationList - if (originalNode.kind === SyntaxKind.EnumDeclaration) { - hoistVariableDeclaration(name); - } - return [ - node, - createExportStatement(name, name) - ]; - } - return node; - } - - /** - * Visits a ClassDeclaration, hoisting its name to the outer module body function. - * - * @param node The class declaration to visit. - */ - function visitClassDeclaration(node: ClassDeclaration): VisitResult { - // Hoist the name of the class declaration to the outer module body function. - const name = getDeclarationName(node); - hoistVariableDeclaration(name); - - const statements: Statement[] = []; - - // Rewrite the class declaration into an assignment of a class expression. - statements.push( - createStatement( - createAssignment( - name, - createClassExpression( - /*modifiers*/ undefined, - node.name, - /*typeParameters*/ undefined, - node.heritageClauses, - node.members, - /*location*/ node - ) - ), - /*location*/ node - ) - ); - - // If the class was exported, write a declaration export to the inner module body function. - if (hasModifier(node, ModifierFlags.Export)) { - if (!hasModifier(node, ModifierFlags.Default)) { - recordExportName(name); - } - - statements.push(createDeclarationExport(node)); - } - - return statements; - } - - function shouldHoistLoopInitializer(node: VariableDeclarationList | Expression) { - return isVariableDeclarationList(node) && (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0; - } - /** * Visits the body of a ForStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitForStatement(node: ForStatement): ForStatement { - const initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - const expressions: Expression[] = []; - for (const variable of (initializer).declarations) { - const visited = transformVariable(variable, /*isExported*/ false); - if (visited) { - expressions.push(visited); - } - }; + function visitForStatement(node: ForStatement): VisitResult { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; - return createFor( - expressions.length - ? inlineExpressions(expressions) - : createSynthesizedNode(SyntaxKind.OmittedExpression), - node.condition, - node.incrementor, - visitNode(node.statement, visitNestedNode, isStatement), - /*location*/ node - ); - } - else { - return visitEachChild(node, visitNestedNode, context); - } - } + node = updateFor( + node, + visitForInitializer(node.initializer), + visitNode(node.condition, destructuringVisitor, isExpression, /*optional*/ true), + visitNode(node.incrementor, destructuringVisitor, isExpression, /*optional*/ true), + visitNode(node.statement, nestedElementVisitor, isStatement) + ); - /** - * Transforms and hoists the declaration list of a ForInStatement or ForOfStatement into an expression. - * - * @param node The decalaration list to transform. - */ - function transformForBinding(node: VariableDeclarationList): Expression { - const firstDeclaration = firstOrUndefined(node.declarations); - hoistBindingElement(firstDeclaration, /*isExported*/ false); - - const name = firstDeclaration.name; - return isIdentifier(name) - ? name - : flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; } /** * Visits the body of a ForInStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitForInStatement(node: ForInStatement): ForInStatement { - const initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - const updated = getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - return updated; - } - else { - return visitEachChild(node, visitNestedNode, context); - } + function visitForInStatement(node: ForInStatement): VisitResult { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + + node = updateForIn( + node, + visitForInitializer(node.initializer), + visitNode(node.expression, destructuringVisitor, isExpression), + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock) + ); + + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; } /** * Visits the body of a ForOfStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitForOfStatement(node: ForOfStatement): ForOfStatement { - const initializer = node.initializer; - if (shouldHoistLoopInitializer(initializer)) { - const updated = getMutableClone(node); - updated.initializer = transformForBinding(initializer); - updated.statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - return updated; + function visitForOfStatement(node: ForOfStatement): VisitResult { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + + node = updateForOf( + node, + visitForInitializer(node.initializer), + visitNode(node.expression, destructuringVisitor, isExpression), + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock) + ); + + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ + function shouldHoistForInitializer(node: ForInitializer): node is VariableDeclarationList { + return isVariableDeclarationList(node) + && shouldHoistVariableDeclarationList(node); + } + + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ + function visitForInitializer(node: ForInitializer): ForInitializer { + if (shouldHoistForInitializer(node)) { + let expressions: Expression[]; + for (const variable of node.declarations) { + expressions = append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + } + + return expressions ? inlineExpressions(expressions) : createOmittedExpression(); } else { - return visitEachChild(node, visitNestedNode, context); + return visitEachChild(node, nestedElementVisitor, context); } } /** * Visits the body of a DoStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitDoStatement(node: DoStatement) { - const statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - if (statement !== node.statement) { - const updated = getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; + function visitDoStatement(node: DoStatement): VisitResult { + return updateDo( + node, + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock), + visitNode(node.expression, destructuringVisitor, isExpression) + ); } /** * Visits the body of a WhileStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitWhileStatement(node: WhileStatement) { - const statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - if (statement !== node.statement) { - const updated = getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; + function visitWhileStatement(node: WhileStatement): VisitResult { + return updateWhile( + node, + visitNode(node.expression, destructuringVisitor, isExpression), + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock) + ); } /** * Visits the body of a LabeledStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitLabeledStatement(node: LabeledStatement) { - const statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - if (statement !== node.statement) { - const updated = getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; + function visitLabeledStatement(node: LabeledStatement): VisitResult { + return updateLabel( + node, + node.label, + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock) + ); } /** * Visits the body of a WithStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitWithStatement(node: WithStatement) { - const statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock); - if (statement !== node.statement) { - const updated = getMutableClone(node); - updated.statement = statement; - return updated; - } - return node; + function visitWithStatement(node: WithStatement): VisitResult { + return updateWith( + node, + visitNode(node.expression, destructuringVisitor, isExpression), + visitNode(node.statement, nestedElementVisitor, isStatement, /*optional*/ false, liftToBlock) + ); } /** * Visits the body of a SwitchStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitSwitchStatement(node: SwitchStatement) { - const caseBlock = visitNode(node.caseBlock, visitNestedNode, isCaseBlock); - if (caseBlock !== node.caseBlock) { - const updated = getMutableClone(node); - updated.caseBlock = caseBlock; - return updated; - } - return node; + function visitSwitchStatement(node: SwitchStatement): VisitResult { + return updateSwitch( + node, + visitNode(node.expression, destructuringVisitor, isExpression), + visitNode(node.caseBlock, nestedElementVisitor, isCaseBlock) + ); } /** @@ -915,97 +1370,227 @@ namespace ts { * * @param node The node to visit. */ - function visitCaseBlock(node: CaseBlock) { - const clauses = visitNodes(node.clauses, visitNestedNode, isCaseOrDefaultClause); - if (clauses !== node.clauses) { - const updated = getMutableClone(node); - updated.clauses = clauses; - return updated; - } + function visitCaseBlock(node: CaseBlock): CaseBlock { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + + node = updateCaseBlock( + node, + visitNodes(node.clauses, nestedElementVisitor, isCaseOrDefaultClause) + ); + + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } /** * Visits the body of a CaseClause to hoist declarations. * - * @param node The clause to visit. + * @param node The node to visit. */ - function visitCaseClause(node: CaseClause) { - const statements = visitNodes(node.statements, visitNestedNode, isStatement); - if (statements !== node.statements) { - const updated = getMutableClone(node); - updated.statements = statements; - return updated; - } - return node; + function visitCaseClause(node: CaseClause): VisitResult { + return updateCaseClause( + node, + visitNode(node.expression, destructuringVisitor, isExpression), + visitNodes(node.statements, nestedElementVisitor, isStatement) + ); } /** * Visits the body of a DefaultClause to hoist declarations. * - * @param node The clause to visit. + * @param node The node to visit. */ - function visitDefaultClause(node: DefaultClause) { - return visitEachChild(node, visitNestedNode, context); + function visitDefaultClause(node: DefaultClause): VisitResult { + return visitEachChild(node, nestedElementVisitor, context); } /** * Visits the body of a TryStatement to hoist declarations. * - * @param node The statement to visit. + * @param node The node to visit. */ - function visitTryStatement(node: TryStatement) { - return visitEachChild(node, visitNestedNode, context); + function visitTryStatement(node: TryStatement): VisitResult { + return visitEachChild(node, nestedElementVisitor, context); } /** * Visits the body of a CatchClause to hoist declarations. * - * @param node The clause to visit. + * @param node The node to visit. */ - function visitCatchClause(node: CatchClause) { - const block = visitNode(node.block, visitNestedNode, isBlock); - if (block !== node.block) { - const updated = getMutableClone(node); - updated.block = block; - return updated; - } + function visitCatchClause(node: CatchClause): CatchClause { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + + node = updateCatchClause( + node, + node.variableDeclaration, + visitNode(node.block, nestedElementVisitor, isBlock) + ); + + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } /** * Visits the body of a Block to hoist declarations. * - * @param node The block to visit. + * @param node The node to visit. */ - function visitBlock(node: Block) { - return visitEachChild(node, visitNestedNode, context); + function visitBlock(node: Block): Block { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + + node = visitEachChild(node, nestedElementVisitor, context); + + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; } // - // Substitutions + // Destructuring Assignment Visitors // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ + function destructuringVisitor(node: Node): VisitResult { + if (node.transformFlags & TransformFlags.DestructuringAssignment + && node.kind === SyntaxKind.BinaryExpression) { + return visitDestructuringAssignment(node); + } + else if (node.transformFlags & TransformFlags.ContainsDestructuringAssignment) { + return visitEachChild(node, destructuringVisitor, context); + } + else { + return node; + } + } + + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ + function visitDestructuringAssignment(node: DestructuringAssignment): VisitResult { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return flattenDestructuringAssignment( + node, + destructuringVisitor, + context, + FlattenLevel.All, + /*needsValue*/ true + ); + } + + return visitEachChild(node, destructuringVisitor, context); + } + + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ + function hasExportedReferenceInDestructuringTarget(node: Expression | ObjectLiteralElementLike): boolean { + if (isAssignmentExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.left); + } + else if (isSpreadExpression(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } + else if (isObjectLiteralExpression(node)) { + return some(node.properties, hasExportedReferenceInDestructuringTarget); + } + else if (isArrayLiteralExpression(node)) { + return some(node.elements, hasExportedReferenceInDestructuringTarget); + } + else if (isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } + else if (isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } + else if (isIdentifier(node)) { + const container = resolver.getReferencedExportContainer(node); + return container !== undefined && container.kind === SyntaxKind.SourceFile; + } + else { + return false; + } + } + + // + // Modifier Visitors + // + + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ + function modifierVisitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ExportKeyword: + case SyntaxKind.DefaultKeyword: + return undefined; + } + return node; + } + + // + // Emit Notification + // + + /** + * Hook for node emit notifications. + * + * @param emitContext A context hint for the emitter. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { if (node.kind === SyntaxKind.SourceFile) { - exportFunctionForFile = exportFunctionForFileMap[getOriginalNodeId(node)]; + const id = getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(emitContext, node, emitCallback); - exportFunctionForFile = undefined; + + currentSourceFile = undefined; + moduleInfo = undefined; + exportFunction = undefined; + noSubstitution = undefined; } else { previousOnEmitNode(emitContext, node, emitCallback); } } + // + // Substitutions + // + /** * Hooks node substitutions. * + * @param emitContext A context hint for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ function onSubstituteNode(emitContext: EmitContext, node: Node) { node = previousOnSubstituteNode(emitContext, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (emitContext === EmitContext.Expression) { return substituteExpression(node); } @@ -1028,378 +1613,175 @@ namespace ts { case SyntaxKind.PostfixUnaryExpression: return substituteUnaryExpression(node); } + return node; } /** - * Substitution for identifiers exported at the top level of a module. + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. */ function substituteExpressionIdentifier(node: Identifier): Expression { - const importDeclaration = resolver.getReferencedImportDeclaration(node); - if (importDeclaration) { - const importBinding = createImportBinding(importDeclaration); - if (importBinding) { - return importBinding; + if (getEmitFlags(node) & EmitFlags.HelperName) { + const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return createPropertyAccess(externalHelpersModuleName, node); + } + return node; + } + + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + if (!isGeneratedIdentifier(node) && !isLocalName(node)) { + const importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (isImportClause(importDeclaration)) { + return createPropertyAccess( + getGeneratedNameForNode(importDeclaration.parent), + createIdentifier("default"), + /*location*/ node + ); + } + else if (isImportSpecifier(importDeclaration)) { + return createPropertyAccess( + getGeneratedNameForNode(importDeclaration.parent.parent.parent), + getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name), + /*location*/ node + ); + } } } return node; } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteBinaryExpression(node: BinaryExpression): Expression { - if (isAssignmentOperator(node.operatorToken.kind)) { - return substituteAssignmentExpression(node); + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) + && !isGeneratedIdentifier(node.left) + && !isLocalName(node.left) + && !isDeclarationNameOfEnumOrNamespace(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + let expression: Expression = node; + for (const exportName of exportedNames) { + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + + return expression; + } } return node; } - function substituteAssignmentExpression(node: BinaryExpression): Expression { - setEmitFlags(node, EmitFlags.NoSubstitution); - - const left = node.left; - switch (left.kind) { - case SyntaxKind.Identifier: - const exportDeclaration = resolver.getReferencedExportContainer(left); - if (exportDeclaration) { - return createExportExpression(left, node); - } - break; - - case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.ArrayLiteralExpression: - if (hasExportedReferenceInDestructuringPattern(left)) { - return substituteDestructuring(node); - } - break; - } - - return node; - } - - function isExportedBinding(name: Identifier) { - const container = resolver.getReferencedExportContainer(name); - return container && container.kind === SyntaxKind.SourceFile; - } - - function hasExportedReferenceInDestructuringPattern(node: ObjectLiteralExpression | ArrayLiteralExpression | Identifier): boolean { - switch (node.kind) { - case SyntaxKind.Identifier: - return isExportedBinding(node); - - case SyntaxKind.ObjectLiteralExpression: - for (const property of (node).properties) { - if (hasExportedReferenceInObjectDestructuringElement(property)) { - return true; - } - } - - break; - - case SyntaxKind.ArrayLiteralExpression: - for (const element of (node).elements) { - if (hasExportedReferenceInArrayDestructuringElement(element)) { - return true; - } - } - - break; - } - - return false; - } - - function hasExportedReferenceInObjectDestructuringElement(node: ObjectLiteralElementLike): boolean { - if (isShorthandPropertyAssignment(node)) { - return isExportedBinding(node.name); - } - else if (isPropertyAssignment(node)) { - return hasExportedReferenceInDestructuringElement(node.initializer); - } - else { - return false; - } - } - - function hasExportedReferenceInArrayDestructuringElement(node: Expression): boolean { - if (isSpreadElementExpression(node)) { - const expression = node.expression; - return isIdentifier(expression) && isExportedBinding(expression); - } - else { - return hasExportedReferenceInDestructuringElement(node); - } - } - - function hasExportedReferenceInDestructuringElement(node: Expression): boolean { - if (isBinaryExpression(node)) { - const left = node.left; - return node.operatorToken.kind === SyntaxKind.EqualsToken - && isDestructuringPattern(left) - && hasExportedReferenceInDestructuringPattern(left); - } - else if (isIdentifier(node)) { - return isExportedBinding(node); - } - else if (isSpreadElementExpression(node)) { - const expression = node.expression; - return isIdentifier(expression) && isExportedBinding(expression); - } - else if (isDestructuringPattern(node)) { - return hasExportedReferenceInDestructuringPattern(node); - } - else { - return false; - } - } - - function isDestructuringPattern(node: Expression): node is ObjectLiteralExpression | ArrayLiteralExpression | Identifier { - const kind = node.kind; - return kind === SyntaxKind.Identifier - || kind === SyntaxKind.ObjectLiteralExpression - || kind === SyntaxKind.ArrayLiteralExpression; - } - - function substituteDestructuring(node: BinaryExpression) { - return flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration); - } - + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression { - const operand = node.operand; - const operator = node.operator; - const substitute = - isIdentifier(operand) && - ( - node.kind === SyntaxKind.PostfixUnaryExpression || - (node.kind === SyntaxKind.PrefixUnaryExpression && (operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken)) - ); + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) + && isIdentifier(node.operand) + && !isGeneratedIdentifier(node.operand) + && !isLocalName(node.operand) + && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + const exportedNames = getExports(node.operand); + if (exportedNames) { + let expression: Expression = node.kind === SyntaxKind.PostfixUnaryExpression + ? createPrefix( + node.operator, + node.operand, + /*location*/ node) + : node; - if (substitute) { - const exportDeclaration = resolver.getReferencedExportContainer(operand); - if (exportDeclaration) { - const expr = createPrefix(node.operator, operand, node); - setEmitFlags(expr, EmitFlags.NoSubstitution); - const call = createExportExpression(operand, expr); - if (node.kind === SyntaxKind.PrefixUnaryExpression) { - return call; + for (const exportName of exportedNames) { + expression = createExportExpression(exportName, preventSubstitution(expression)); } - else { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - return operator === SyntaxKind.PlusPlusToken - ? createSubtract(call, createLiteral(1)) - : createAdd(call, createLiteral(1)); + + if (node.kind === SyntaxKind.PostfixUnaryExpression) { + expression = node.operator === SyntaxKind.PlusPlusToken + ? createSubtract(preventSubstitution(expression), createLiteral(1)) + : createAdd(preventSubstitution(expression), createLiteral(1)); } + + return expression; } } + return node; } /** - * Gets a name to use for a DeclarationStatement. - * @param node The declaration statement. + * Gets the exports of a name. + * + * @param name The name. */ - function getDeclarationName(node: DeclarationStatement) { - return node.name ? getSynthesizedClone(node.name) : getGeneratedNameForNode(node); - } + function getExports(name: Identifier) { + let exportedNames: Identifier[]; + if (!isGeneratedIdentifier(name)) { + const valueDeclaration = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); - function addExportStarFunction(statements: Statement[], localNames: Identifier) { - const exportStarFunction = createUniqueName("exportStar"); - const m = createIdentifier("m"); - const n = createIdentifier("n"); - const exports = createIdentifier("exports"); - let condition: Expression = createStrictInequality(n, createLiteral("default")); - if (localNames) { - condition = createLogicalAnd( - condition, - createLogicalNot(createHasOwnProperty(localNames, n)) - ); - } + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) { + exportedNames = append(exportedNames, getDeclarationName(valueDeclaration)); + } - statements.push( - createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - exportStarFunction, - /*typeParameters*/ undefined, - [createParameter(m)], - /*type*/ undefined, - createBlock([ - createVariableStatement( - /*modifiers*/ undefined, - createVariableDeclarationList([ - createVariableDeclaration( - exports, - /*type*/ undefined, - createObjectLiteral([]) - ) - ]) - ), - createForIn( - createVariableDeclarationList([ - createVariableDeclaration(n, /*type*/ undefined) - ]), - m, - createBlock([ - setEmitFlags( - createIf( - condition, - createStatement( - createAssignment( - createElementAccess(exports, n), - createElementAccess(m, n) - ) - ) - ), - EmitFlags.SingleLine - ) - ]) - ), - createStatement( - createCall( - exportFunctionForFile, - /*typeArguments*/ undefined, - [exports] - ) - ) - ], - /*location*/ undefined, - /*multiline*/ true) - ) - ); - - return exportStarFunction; - } - - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportExpression(name: Identifier | StringLiteral, value: Expression) { - const exportName = isIdentifier(name) ? createLiteral(name.text) : name; - return createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exportName, value]); - } - - /** - * Creates a call to the current file's export function to export a value. - * @param name The bound name of the export. - * @param value The exported value. - */ - function createExportStatement(name: Identifier | StringLiteral, value: Expression) { - return createStatement(createExportExpression(name, value)); - } - - /** - * Creates a call to the current file's export function to export a declaration. - * @param node The declaration to export. - */ - function createDeclarationExport(node: DeclarationStatement) { - const declarationName = getDeclarationName(node); - const exportName = hasModifier(node, ModifierFlags.Default) ? createLiteral("default") : declarationName; - return createExportStatement(exportName, declarationName); - } - - function createImportBinding(importDeclaration: Declaration): LeftHandSideExpression { - let importAlias: Identifier; - let name: Identifier; - if (isImportClause(importDeclaration)) { - importAlias = getGeneratedNameForNode(importDeclaration.parent); - name = createIdentifier("default"); - } - else if (isImportSpecifier(importDeclaration)) { - importAlias = getGeneratedNameForNode(importDeclaration.parent.parent.parent); - name = importDeclaration.propertyName || importDeclaration.name; - } - else { - return undefined; - } - - if (name.originalKeywordKind && languageVersion === ScriptTarget.ES3) { - return createElementAccess(importAlias, createLiteral(name.text)); - } - else { - return createPropertyAccess(importAlias, getSynthesizedClone(name)); - } - } - - function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) { - const groupIndices = createMap(); - const dependencyGroups: DependencyGroup[] = []; - for (let i = 0; i < externalImports.length; i++) { - const externalImport = externalImports[i]; - const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); - const text = externalModuleName.text; - if (hasProperty(groupIndices, text)) { - // deduplicate/group entries in dependency list by the dependency name - const groupIndex = groupIndices[text]; - dependencyGroups[groupIndex].externalImports.push(externalImport); - continue; - } - else { - groupIndices[text] = dependencyGroups.length; - dependencyGroups.push({ - name: externalModuleName, - externalImports: [externalImport] - }); + exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); } } - return dependencyGroups; + return exportedNames; } - function getNameOfDependencyGroup(dependencyGroup: DependencyGroup) { - return dependencyGroup.name; + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ + function preventSubstitution(node: T): T { + if (noSubstitution === undefined) noSubstitution = createMap(); + noSubstitution[getNodeId(node)] = true; + return node; } - function recordExportName(name: Identifier) { - if (!exportedLocalNames) { - exportedLocalNames = []; - } - - exportedLocalNames.push(name); - } - - function recordExportedFunctionDeclaration(node: FunctionDeclaration) { - if (!exportedFunctionDeclarations) { - exportedFunctionDeclarations = []; - } - - exportedFunctionDeclarations.push(createDeclarationExport(node)); - } - - function hoistBindingElement(node: VariableDeclaration | ArrayBindingElement, isExported: boolean): void { - if (isOmittedExpression(node)) { - return; - } - - const name = node.name; - if (isIdentifier(name)) { - hoistVariableDeclaration(getSynthesizedClone(name)); - if (isExported) { - recordExportName(name); - } - } - else if (isBindingPattern(name)) { - forEach(name.elements, isExported ? hoistExportedBindingElement : hoistNonExportedBindingElement); - } - } - - function hoistExportedBindingElement(node: VariableDeclaration | ArrayBindingElement) { - hoistBindingElement(node, /*isExported*/ true); - } - - function hoistNonExportedBindingElement(node: VariableDeclaration | ArrayBindingElement) { - hoistBindingElement(node, /*isExported*/ false); - } - - function updateSourceFile(node: SourceFile, statements: Statement[], nodeEmitFlags: EmitFlags) { - const updated = getMutableClone(node); - updated.statements = createNodeArray(statements, node.statements); - setEmitFlags(updated, nodeEmitFlags); - return updated; + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ + function isSubstitutionPrevented(node: Node) { + return noSubstitution && node.id && noSubstitution[node.id]; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 41f03d20f2e..775f60355d8 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -4,8 +4,6 @@ /*@internal*/ namespace ts { - type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration; - /** * Indicates whether to emit type metadata in the new format. */ @@ -16,8 +14,6 @@ namespace ts { ClassAliases = 1 << 0, /** Enables substitutions for namespace exports. */ NamespaceExports = 1 << 1, - /** Enables substitutions for async methods with `super` calls. */ - AsyncMethodsWithSuper = 1 << 2, /* Enables substitutions for unqualified enum members */ NonQualifiedEnumMembers = 1 << 3 } @@ -25,6 +21,7 @@ namespace ts { export function transformTypeScript(context: TransformationContext) { const { startLexicalEnvironment, + resumeLexicalEnvironment, endLexicalEnvironment, hoistVariableDeclaration, } = context; @@ -52,7 +49,6 @@ namespace ts { let currentNamespaceContainerName: Identifier; let currentScope: SourceFile | Block | ModuleBlock | CaseBlock; let currentScopeFirstDeclarationsOfName: Map; - let currentSourceFileExternalHelpersModuleName: Identifier; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -72,12 +68,6 @@ namespace ts { */ let applicableSubstitutions: TypeScriptSubstitutionFlags; - /** - * This keeps track of containers where `super` is valid, for use with - * just-in-time substitution for `super` expressions inside of async methods. - */ - let currentSuperContainer: SuperContainer; - return transformSourceFile; /** @@ -90,7 +80,13 @@ namespace ts { return node; } - return visitNode(node, visitor, isSourceFile); + currentSourceFile = node; + + const visited = saveStateAndInvoke(node, visitSourceFile); + addEmitHelpers(visited, context.readEmitHelpers()); + + currentSourceFile = undefined; + return visited; } /** @@ -117,6 +113,32 @@ namespace ts { return visited; } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ + function onBeforeVisitNode(node: Node) { + switch (node.kind) { + case SyntaxKind.SourceFile: + case SyntaxKind.CaseBlock: + case SyntaxKind.ModuleBlock: + case SyntaxKind.Block: + currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + + case SyntaxKind.ClassDeclaration: + case SyntaxKind.FunctionDeclaration: + if (hasModifier(node, ModifierFlags.Ambient)) { + break; + } + + recordEmittedDeclarationInScope(node); + break; + } + } + /** * General-purpose node visitor. * @@ -132,10 +154,7 @@ namespace ts { * @param node The node to visit. */ function visitorWorker(node: Node): VisitResult { - if (node.kind === SyntaxKind.SourceFile) { - return visitSourceFile(node); - } - else if (node.transformFlags & TransformFlags.TypeScript) { + if (node.transformFlags & TransformFlags.TypeScript) { // This node is explicitly marked as TypeScript, so we should transform the node. return visitTypeScript(node); } @@ -147,6 +166,35 @@ namespace ts { return node; } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node: Node): VisitResult { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: + return visitImportDeclaration(node); + case SyntaxKind.ImportEqualsDeclaration: + return visitImportEqualsDeclaration(node); + case SyntaxKind.ExportAssignment: + return visitExportAssignment(node); + case SyntaxKind.ExportDeclaration: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } + /** * Specialized visitor that visits the immediate children of a namespace. * @@ -222,6 +270,17 @@ namespace ts { } } + function modifierVisitor(node: Node): VisitResult { + if (modifierToFlag(node.kind) & ModifierFlags.TypeScriptModifier) { + return undefined; + } + else if (currentNamespace && node.kind === SyntaxKind.ExportKeyword) { + return undefined; + } + + return node; + } + /** * Branching visitor, visits a TypeScript syntax node. * @@ -244,7 +303,6 @@ namespace ts { case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.AbstractKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DeclareKeyword: case SyntaxKind.ReadonlyKeyword: @@ -270,6 +328,9 @@ namespace ts { case SyntaxKind.IntersectionType: case SyntaxKind.ParenthesizedType: case SyntaxKind.ThisType: + case SyntaxKind.TypeOperator: + case SyntaxKind.IndexedAccessType: + case SyntaxKind.MappedType: case SyntaxKind.LiteralType: // TypeScript type nodes are elided. @@ -284,10 +345,10 @@ namespace ts { case SyntaxKind.PropertyDeclaration: // TypeScript property declarations are elided. + return undefined; case SyntaxKind.Constructor: - // TypeScript constructors are transformed in `visitClassDeclaration`. - return undefined; + return visitConstructor(node); case SyntaxKind.InterfaceDeclaration: // TypeScript interfaces are elided, but some comments may be preserved. @@ -304,7 +365,6 @@ namespace ts { // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassDeclaration(node); case SyntaxKind.ClassExpression: @@ -317,7 +377,6 @@ namespace ts { // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassExpression(node); case SyntaxKind.HeritageClause: @@ -332,7 +391,7 @@ namespace ts { return visitExpressionWithTypeArguments(node); case SyntaxKind.MethodDeclaration: - // TypeScript method declarations may be 'async', and may have decorators, modifiers + // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); @@ -341,19 +400,19 @@ namespace ts { return visitGetAccessor(node); case SyntaxKind.SetAccessor: - // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); case SyntaxKind.FunctionDeclaration: - // TypeScript function declarations may be 'async' + // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); case SyntaxKind.FunctionExpression: - // TypeScript function expressions may be 'async' + // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); case SyntaxKind.ArrowFunction: - // TypeScript arrow functions may be 'async' + // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case SyntaxKind.Parameter: @@ -377,6 +436,12 @@ namespace ts { // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); + case SyntaxKind.CallExpression: + return visitCallExpression(node); + + case SyntaxKind.NewExpression: + return visitNewExpression(node); + case SyntaxKind.NonNullExpression: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); @@ -385,14 +450,13 @@ namespace ts { // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case SyntaxKind.AwaitExpression: - // TypeScript 'await' expressions must be transformed. - return visitAwaitExpression(node); - case SyntaxKind.VariableStatement: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); + case SyntaxKind.VariableDeclaration: + return visitVariableDeclaration(node); + case SyntaxKind.ModuleDeclaration: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); @@ -407,69 +471,11 @@ namespace ts { } } - /** - * Performs actions that should always occur immediately before visiting a node. - * - * @param node The node to visit. - */ - function onBeforeVisitNode(node: Node) { - switch (node.kind) { - case SyntaxKind.SourceFile: - case SyntaxKind.CaseBlock: - case SyntaxKind.ModuleBlock: - case SyntaxKind.Block: - currentScope = node; - currentScopeFirstDeclarationsOfName = undefined; - break; - - case SyntaxKind.ClassDeclaration: - case SyntaxKind.FunctionDeclaration: - if (hasModifier(node, ModifierFlags.Ambient)) { - break; - } - - recordEmittedDeclarationInScope(node); - break; - } - } - function visitSourceFile(node: SourceFile) { - currentSourceFile = node; - - // If the source file requires any helpers and is an external module, and - // the importHelpers compiler option is enabled, emit a synthesized import - // statement for the helpers library. - if (node.flags & NodeFlags.EmitHelperFlags - && compilerOptions.importHelpers - && (isExternalModule(node) || compilerOptions.isolatedModules)) { - startLexicalEnvironment(); - const statements: Statement[] = []; - const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor); - const externalHelpersModuleName = createUniqueName(externalHelpersModuleNameText); - const externalHelpersModuleImport = createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), - createLiteral(externalHelpersModuleNameText) - ); - externalHelpersModuleImport.parent = node; - externalHelpersModuleImport.flags &= ~NodeFlags.Synthesized; - statements.push(externalHelpersModuleImport); - - currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); - addRange(statements, endLexicalEnvironment()); - currentSourceFileExternalHelpersModuleName = undefined; - - node = updateSourceFileNode(node, createNodeArray(statements, node.statements)); - node.externalHelpersModuleName = externalHelpersModuleName; - } - else { - node = visitEachChild(node, visitor, context); - } - - setEmitFlags(node, EmitFlags.EmitEmitHelpers | getEmitFlags(node)); - return node; + const alwaysStrict = compilerOptions.alwaysStrict && !(isExternalModule(node) && moduleKind === ModuleKind.ES2015); + return updateSourceFileNode( + node, + visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -510,7 +516,6 @@ namespace ts { const staticProperties = getInitializedProperties(node, /*isStatic*/ true); const hasExtendsClause = getClassExtendsHeritageClauseElement(node) !== undefined; const isDecoratedClass = shouldEmitDecorateCallForClass(node); - let classAlias: Identifier; // emit name if // - node has a name @@ -521,33 +526,11 @@ namespace ts { name = getGeneratedNameForNode(node); } - const statements: Statement[] = []; - if (!isDecoratedClass) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - const classDeclaration = createClassDeclaration( - /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), - name, - /*typeParameters*/ undefined, - visitNodes(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node, hasExtendsClause), - /*location*/ node - ); - setOriginalNode(classDeclaration, node); + const classStatement = isDecoratedClass + ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) + : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - if (staticProperties.length > 0) { - setEmitFlags(classDeclaration, EmitFlags.NoTrailingSourceMap | getEmitFlags(classDeclaration)); - } - - statements.push(classDeclaration); - } - else { - classAlias = addClassDeclarationHeadWithDecorators(statements, node, name, hasExtendsClause); - } + const statements: Statement[] = [classStatement]; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration @@ -555,13 +538,13 @@ namespace ts { // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if (staticProperties.length) { - addInitializedPropertyStatements(statements, node, staticProperties, getLocalName(node, /*noSourceMaps*/ true)); + addInitializedPropertyStatements(statements, staticProperties, getLocalName(node)); } // Write any decorators of the node. addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node, classAlias); + addConstructorDecorationStatement(statements, node); // If the class is exported as part of a TypeScript namespace, emit the namespace export. // Otherwise, if the class was exported at the top level and was decorated, emit an export @@ -571,29 +554,66 @@ namespace ts { } else if (isDecoratedClass) { if (isDefaultExternalModuleExport(node)) { - statements.push(createExportAssignment( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*isExportEquals*/ false, - getLocalName(node))); + statements.push(createExportDefault(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } else if (isNamedExternalModuleExport(node)) { - statements.push(createExternalModuleExport(name)); + statements.push(createExternalModuleExport(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } - return statements; + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(createEndOfDeclarationMarker(node)); + setEmitFlags(classStatement, getEmitFlags(classStatement) | EmitFlags.HasEndOfDeclarationMarker); + } + + return singleOrMany(statements); + } + + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param hasStaticProperties A value indicating whether the class has static properties. + */ + function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier, hasExtendsClause: boolean, hasStaticProperties: boolean) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + const classDeclaration = createClassDeclaration( + /*decorators*/ undefined, + visitNodes(node.modifiers, modifierVisitor, isModifier), + name, + /*typeParameters*/ undefined, + visitNodes(node.heritageClauses, visitor, isHeritageClause), + transformClassMembers(node, hasExtendsClause), + node); + + let emitFlags = getEmitFlags(node); + + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + if (hasStaticProperties) { + emitFlags |= EmitFlags.NoTrailingSourceMap; + } + + setOriginalNode(classDeclaration, node); + setEmitFlags(classDeclaration, emitFlags); + return classDeclaration; } /** * Transforms a decorated class declaration and appends the resulting statements. If * the class requires an alias to avoid issues with double-binding, the alias is returned. * + * @param statements A statement list to which to add the declaration. * @param node A ClassDeclaration node. * @param name The name of the class. - * @param hasExtendsClause A value indicating whether + * @param hasExtendsClause A value indicating whether the class has an extends clause. */ - function addClassDeclarationHeadWithDecorators(statements: Statement[], node: ClassDeclaration, name: Identifier, hasExtendsClause: boolean) { + function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier, hasExtendsClause: boolean) { // When we emit an ES6 class that has a class decorator, we must tailor the // emit to certain specific cases. // @@ -628,20 +648,20 @@ namespace ts { // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = C_1 = class C { // class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export { C }; + // | var C_1; // --------------------------------------------------------------------- // // If a class declaration is the default export of a module, we instead emit @@ -670,92 +690,34 @@ namespace ts { // --------------------------------------------------------------------- // TypeScript | Javascript // --------------------------------------------------------------------- - // @dec | let C_1 = class C { + // @dec | let C = class C { // export default class C { | static x() { return C_1.y; } // static x() { return C.y; } | } - // static y = 1; | let C = C_1; - // } | C.y = 1; - // | C = C_1 = __decorate([dec], C); + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); // | export default C; + // | var C_1; // --------------------------------------------------------------------- // const location = moveRangePastDecorators(node); + const classAlias = getClassAliasIfNeeded(node); + const declName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // ... = class ${name} ${heritageClauses} { // ${members} // } - const classExpression: Expression = setOriginalNode( - createClassExpression( - /*modifiers*/ undefined, - name, - /*typeParameters*/ undefined, - visitNodes(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node, hasExtendsClause), - /*location*/ location - ), - node - ); - - if (!name) { - name = getGeneratedNameForNode(node); - } - - // Record an alias to avoid class double-binding. - let classAlias: Identifier; - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference) { - enableSubstitutionForClassAliases(); - classAlias = createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? node.name.text : "default"); - classAliases[getOriginalNodeId(node)] = classAlias; - } - - const declaredName = getDeclarationName(node, /*allowComments*/ true); + const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause); + const members = transformClassMembers(node, hasExtendsClause); + const classExpression = createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members, location); + setOriginalNode(classExpression, node); // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference // or decoratedClassAlias if the class contain self-reference. - const transformedClassExpression = createVariableStatement( - /*modifiers*/ undefined, - createLetDeclarationList([ - createVariableDeclaration( - classAlias || declaredName, - /*type*/ undefined, - classExpression - ) - ]), - /*location*/ location - ); - setCommentRange(transformedClassExpression, node); - statements.push( - setOriginalNode( - /*node*/ transformedClassExpression, - /*original*/ node - ) - ); - - if (classAlias) { - // We emit the class alias as a `let` declaration here so that it has the same - // TDZ as the class. - - // let ${declaredName} = ${decoratedClassAlias} - statements.push( - setOriginalNode( - createVariableStatement( - /*modifiers*/ undefined, - createLetDeclarationList([ - createVariableDeclaration( - declaredName, - /*type*/ undefined, - classAlias - ) - ]), - /*location*/ location - ), - /*original*/ node - ) - ); - } - - return classAlias; + const statement = createLetStatement(declName, classAlias ? createAssignment(classAlias, classExpression) : classExpression, location); + setOriginalNode(statement, node); + setCommentRange(statement, node); + return statement; } /** @@ -770,7 +732,7 @@ namespace ts { function visitClassExpression(node: ClassExpression): Expression { const staticProperties = getInitializedProperties(node, /*isStatic*/ true); const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause); - const members = transformClassMembers(node, heritageClauses !== undefined); + const members = transformClassMembers(node, some(heritageClauses, c => c.token === SyntaxKind.ExtendsKeyword)); const classExpression = setOriginalNode( createClassExpression( @@ -797,7 +759,7 @@ namespace ts { // the body of a class with static initializers. setEmitFlags(classExpression, EmitFlags.Indented | getEmitFlags(classExpression)); expressions.push(startOnNewLine(createAssignment(temp, classExpression))); - addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); + addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(startOnNewLine(temp)); return inlineExpressions(expressions); } @@ -843,7 +805,7 @@ namespace ts { } const parameters = transformConstructorParameters(constructor); - const body = transformConstructorBody(node, constructor, hasExtendsClause, parameters); + const body = transformConstructorBody(node, constructor, hasExtendsClause); // constructor(${parameters}) { // ${body} @@ -885,9 +847,8 @@ namespace ts { // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. // Instead, we'll avoid using a rest parameter and spread into the super call as // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". - return constructor - ? visitNodes(constructor.parameters, visitor, isParameter) - : []; + return visitParameterList(constructor && constructor.parameters, visitor, context) + || []; } /** @@ -897,14 +858,12 @@ namespace ts { * @param node The current class. * @param constructor The current class constructor. * @param hasExtendsClause A value indicating whether the class has an extends clause. - * @param parameters The transformed parameters for the constructor. */ - function transformConstructorBody(node: ClassExpression | ClassDeclaration, constructor: ConstructorDeclaration, hasExtendsClause: boolean, parameters: ParameterDeclaration[]) { + function transformConstructorBody(node: ClassExpression | ClassDeclaration, constructor: ConstructorDeclaration, hasExtendsClause: boolean) { const statements: Statement[] = []; let indexOfFirstStatement = 0; - // The body of a constructor is a new lexical environment - startLexicalEnvironment(); + resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); @@ -951,7 +910,7 @@ namespace ts { // } // const properties = getInitializedProperties(node, /*isStatic*/ false); - addInitializedPropertyStatements(statements, node, properties, createThis()); + addInitializedPropertyStatements(statements, properties, createThis()); if (constructor) { // The class already had a constructor, so we should add the existing statements, skipping the initial super call. @@ -960,15 +919,13 @@ namespace ts { // End the lexical environment. addRange(statements, endLexicalEnvironment()); - return setMultiLine( - createBlock( - createNodeArray( - statements, - /*location*/ constructor ? constructor.body.statements : node.members - ), - /*location*/ constructor ? constructor.body : undefined + return createBlock( + createNodeArray( + statements, + /*location*/ constructor ? constructor.body.statements : node.members ), - true + /*location*/ constructor ? constructor.body : /*location*/ undefined, + /*multiLine*/ true ); } @@ -1091,13 +1048,12 @@ namespace ts { /** * Generates assignment statements for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function addInitializedPropertyStatements(statements: Statement[], node: ClassExpression | ClassDeclaration, properties: PropertyDeclaration[], receiver: LeftHandSideExpression) { + function addInitializedPropertyStatements(statements: Statement[], properties: PropertyDeclaration[], receiver: LeftHandSideExpression) { for (const property of properties) { - const statement = createStatement(transformInitializedProperty(node, property, receiver)); + const statement = createStatement(transformInitializedProperty(property, receiver)); setSourceMapRange(statement, moveRangePastModifiers(property)); setCommentRange(statement, property); statements.push(statement); @@ -1107,14 +1063,13 @@ namespace ts { /** * Generates assignment expressions for property initializers. * - * @param node The class node. * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function generateInitializedPropertyExpressions(node: ClassExpression | ClassDeclaration, properties: PropertyDeclaration[], receiver: LeftHandSideExpression) { + function generateInitializedPropertyExpressions(properties: PropertyDeclaration[], receiver: LeftHandSideExpression) { const expressions: Expression[] = []; for (const property of properties) { - const expression = transformInitializedProperty(node, property, receiver); + const expression = transformInitializedProperty(property, receiver); expression.startsOnNewLine = true; setSourceMapRange(expression, moveRangePastModifiers(property)); setCommentRange(expression, property); @@ -1127,11 +1082,10 @@ namespace ts { /** * Transforms a property initializer into an assignment statement. * - * @param node The class containing the property. * @param property The property declaration. * @param receiver The object receiving the property assignment. */ - function transformInitializedProperty(node: ClassExpression | ClassDeclaration, property: PropertyDeclaration, receiver: LeftHandSideExpression) { + function transformInitializedProperty(property: PropertyDeclaration, receiver: LeftHandSideExpression) { const propertyName = visitPropertyNameOfClassElement(property); const initializer = visitNode(property.initializer, visitor, isExpression); const memberAccess = createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -1269,11 +1223,12 @@ namespace ts { } const { firstAccessor, secondAccessor, setAccessor } = getAllAccessorDeclarations(node.members, accessor); - if (accessor !== firstAccessor) { + const firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - const decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + const decorators = firstAccessorWithDecorators.decorators; const parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -1322,7 +1277,7 @@ namespace ts { * @param node The declaration node. * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(node: Declaration, allDecorators: AllDecorators) { + function transformAllDecoratorsOfDeclaration(node: Declaration, container: ClassLikeDeclaration, allDecorators: AllDecorators) { if (!allDecorators) { return undefined; } @@ -1330,7 +1285,7 @@ namespace ts { const decoratorExpressions: Expression[] = []; addRange(decoratorExpressions, map(allDecorators.decorators, transformDecorator)); addRange(decoratorExpressions, flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } @@ -1379,7 +1334,7 @@ namespace ts { */ function generateClassElementDecorationExpression(node: ClassExpression | ClassDeclaration, member: ClassElement) { const allDecorators = getAllDecoratorsOfClassElement(node, member); - const decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + const decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -1400,13 +1355,13 @@ namespace ts { // __metadata("design:type", Function), // __metadata("design:paramtypes", [Object]), // __metadata("design:returntype", void 0) - // ], C.prototype, "method", undefined); + // ], C.prototype, "method", null); // // The emit for an accessor is: // // __decorate([ // dec - // ], C.prototype, "accessor", undefined); + // ], C.prototype, "accessor", null); // // The emit for a property is: // @@ -1429,7 +1384,7 @@ namespace ts { : undefined; const helper = createDecorateHelper( - currentSourceFileExternalHelpersModuleName, + context, decoratorExpressions, prefix, memberName, @@ -1446,8 +1401,8 @@ namespace ts { * * @param node The class node. */ - function addConstructorDecorationStatement(statements: Statement[], node: ClassDeclaration, decoratedClassAlias: Identifier) { - const expression = generateConstructorDecorationExpression(node, decoratedClassAlias); + function addConstructorDecorationStatement(statements: Statement[], node: ClassDeclaration) { + const expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(setOriginalNode(createStatement(expression), node)); } @@ -1458,61 +1413,20 @@ namespace ts { * * @param node The class node. */ - function generateConstructorDecorationExpression(node: ClassExpression | ClassDeclaration, decoratedClassAlias: Identifier) { + function generateConstructorDecorationExpression(node: ClassExpression | ClassDeclaration) { const allDecorators = getAllDecoratorsOfConstructor(node); - const decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + const decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = C_1 = __decorate([dec], C); - // - if (decoratedClassAlias) { - const expression = createAssignment( - decoratedClassAlias, - createDecorateHelper( - currentSourceFileExternalHelpersModuleName, - decoratorExpressions, - getDeclarationName(node) - ) - ); - - const result = createAssignment(getDeclarationName(node), expression, moveRangePastDecorators(node)); - setEmitFlags(result, EmitFlags.NoComments); - return result; - } - // Emit the call to __decorate. Given the class: - // - // @dec - // export declare class C { - // } - // - // The emit for the class is: - // - // C = __decorate([dec], C); - // - else { - const result = createAssignment( - getDeclarationName(node), - createDecorateHelper( - currentSourceFileExternalHelpersModuleName, - decoratorExpressions, - getDeclarationName(node) - ), - moveRangePastDecorators(node) - ); - - setEmitFlags(result, EmitFlags.NoComments); - return result; - } + const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; + const localName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const decorate = createDecorateHelper(context, decoratorExpressions, localName); + const expression = createAssignment(localName, classAlias ? createAssignment(classAlias, decorate) : decorate); + setEmitFlags(expression, EmitFlags.NoComments); + setSourceMapRange(expression, moveRangePastDecorators(node)); + return expression; } /** @@ -1536,7 +1450,7 @@ namespace ts { expressions = []; for (const decorator of decorators) { const helper = createParamHelper( - currentSourceFileExternalHelpersModuleName, + context, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); @@ -1554,43 +1468,43 @@ namespace ts { * @param node The declaration node. * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node: Declaration, decoratorExpressions: Expression[]) { + function addTypeMetadata(node: Declaration, container: ClassLikeDeclaration, decoratorExpressions: Expression[]) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node: Declaration, decoratorExpressions: Expression[]) { + function addOldTypeMetadata(node: Declaration, container: ClassLikeDeclaration, decoratorExpressions: Expression[]) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:type", serializeTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:returntype", serializeReturnTypeOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node: Declaration, decoratorExpressions: Expression[]) { + function addNewTypeMetadata(node: Declaration, container: ClassLikeDeclaration, decoratorExpressions: Expression[]) { if (compilerOptions.emitDecoratorMetadata) { let properties: ObjectLiteralElementLike[]; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(createPropertyAssignment("type", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeTypeOfNode(node)))); + (properties || (properties = [])).push(createPropertyAssignment("type", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, createToken(SyntaxKind.EqualsGreaterThanToken), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(createPropertyAssignment("paramTypes", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(createPropertyAssignment("paramTypes", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, createToken(SyntaxKind.EqualsGreaterThanToken), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(createPropertyAssignment("returnType", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(createPropertyAssignment("returnType", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, createToken(SyntaxKind.EqualsGreaterThanToken), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(createMetadataHelper(currentSourceFileExternalHelpersModuleName, "design:typeinfo", createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true))); } } } @@ -1629,20 +1543,27 @@ namespace ts { * @param node The node to test. */ function shouldAddParamTypesMetadata(node: Declaration): boolean { - const kind = node.kind; - return kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.ClassExpression - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; + switch (node.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + return getFirstConstructorWithBody(node) !== undefined; + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return true; + } + return false; } + type SerializedEntityNameAsExpression = Identifier | BinaryExpression | PropertyAccessExpression; + type SerializedTypeNode = SerializedEntityNameAsExpression | VoidExpression | ConditionalExpression; + /** * Serializes the type of a node for use with decorator type metadata. * * @param node The node that should have its type serialized. */ - function serializeTypeOfNode(node: Node): Expression { + function serializeTypeOfNode(node: Node): SerializedTypeNode { switch (node.kind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: @@ -1659,30 +1580,12 @@ namespace ts { } } - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node: TypeNode) { - if (node && node.kind === SyntaxKind.ArrayType) { - return (node).elementType; - } - else if (node && node.kind === SyntaxKind.TypeReference) { - return singleOrUndefined((node).typeArguments); - } - else { - return undefined; - } - } - /** * Serializes the types of the parameters of a node for use with decorator type metadata. * * @param node The node that should have its parameter types serialized. */ - function serializeParameterTypesOfNode(node: Node): Expression { + function serializeParameterTypesOfNode(node: Node, container: ClassLikeDeclaration): ArrayLiteralExpression { const valueDeclaration = isClassLike(node) ? getFirstConstructorWithBody(node) @@ -1690,9 +1593,9 @@ namespace ts { ? node : undefined; - const expressions: Expression[] = []; + const expressions: SerializedTypeNode[] = []; if (valueDeclaration) { - const parameters = valueDeclaration.parameters; + const parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); const numParameters = parameters.length; for (let i = 0; i < numParameters; i++) { const parameter = parameters[i]; @@ -1711,12 +1614,22 @@ namespace ts { return createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node: FunctionLikeDeclaration, container: ClassLikeDeclaration) { + if (container && node.kind === SyntaxKind.GetAccessor) { + const { setAccessor } = getAllAccessorDeclarations(container.members, node); + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** * Serializes the return type of a node for use with decorator type metadata. * * @param node The node that should have its return type serialized. */ - function serializeReturnTypeOfNode(node: Node): Expression { + function serializeReturnTypeOfNode(node: Node): SerializedTypeNode { if (isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); } @@ -1745,13 +1658,16 @@ namespace ts { * * @param node The type node to serialize. */ - function serializeTypeNode(node: TypeNode): Expression { + function serializeTypeNode(node: TypeNode): SerializedTypeNode { if (node === undefined) { return createIdentifier("Object"); } switch (node.kind) { case SyntaxKind.VoidKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.NeverKeyword: return createVoidZero(); case SyntaxKind.ParenthesizedType: @@ -1794,7 +1710,7 @@ namespace ts { return createIdentifier("Number"); case SyntaxKind.SymbolKeyword: - return languageVersion < ScriptTarget.ES6 + return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() : createIdentifier("Symbol"); @@ -1803,38 +1719,12 @@ namespace ts { case SyntaxKind.IntersectionType: case SyntaxKind.UnionType: - { - const unionOrIntersection = node; - let serializedUnion: Identifier; - for (const typeNode of unionOrIntersection.types) { - const serializedIndividual = serializeTypeNode(typeNode) as Identifier; - // Non identifier - if (serializedIndividual.kind !== SyntaxKind.Identifier) { - serializedUnion = undefined; - break; - } + return serializeUnionOrIntersectionType(node); - // One of the individual is global object, return immediately - if (serializedIndividual.text === "Object") { - return serializedIndividual; - } - - // Different types - if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { - serializedUnion = undefined; - break; - } - - serializedUnion = serializedIndividual; - } - - // If we were able to find common type - if (serializedUnion) { - return serializedUnion; - } - } - // Fallthrough case SyntaxKind.TypeQuery: + case SyntaxKind.TypeOperator: + case SyntaxKind.IndexedAccessType: + case SyntaxKind.MappedType: case SyntaxKind.TypeLiteral: case SyntaxKind.AnyKeyword: case SyntaxKind.ThisType: @@ -1848,25 +1738,55 @@ namespace ts { return createIdentifier("Object"); } + function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode { + let serializedUnion: SerializedTypeNode; + for (const typeNode of node.types) { + const serializedIndividual = serializeTypeNode(typeNode); + + if (isVoidExpression(serializedIndividual)) { + // If we dont have any other type already set, set the initial type + if (!serializedUnion) { + serializedUnion = serializedIndividual; + } + } + else if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + // One of the individual is global object, return immediately + return serializedIndividual; + } + // If there exists union that is not void 0 expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + else if (serializedUnion && !isVoidExpression(serializedUnion)) { + // Different types + if (!isIdentifier(serializedUnion) || + !isIdentifier(serializedIndividual) || + serializedUnion.text !== serializedIndividual.text) { + return createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedUnion = serializedIndividual; + } + } + + // If we were able to find common type, use it + return serializedUnion; + } + /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with * decorator type metadata. * * @param node The type reference node. */ - function serializeTypeReferenceNode(node: TypeReferenceNode) { + function serializeTypeReferenceNode(node: TypeReferenceNode): SerializedTypeNode { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { case TypeReferenceSerializationKind.Unknown: const serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); const temp = createTempVariable(hoistVariableDeclaration); return createLogicalOr( createLogicalAnd( - createStrictEquality( - createTypeOf( - createAssignment(temp, serialized) - ), - createLiteral("function") - ), + createTypeCheck(createAssignment(temp, serialized), "function"), temp ), createIdentifier("Object") @@ -1891,7 +1811,7 @@ namespace ts { return createIdentifier("Array"); case TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < ScriptTarget.ES6 + return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() : createIdentifier("Symbol"); @@ -1914,7 +1834,7 @@ namespace ts { * @param useFallback A value indicating whether to use logical operators to test for the * entity name at runtime. */ - function serializeEntityNameAsExpression(node: EntityName, useFallback: boolean): Expression { + function serializeEntityNameAsExpression(node: EntityName, useFallback: boolean): SerializedEntityNameAsExpression { switch (node.kind) { case SyntaxKind.Identifier: // Create a clone of the name with a new parent, and treat it as if it were @@ -1947,8 +1867,8 @@ namespace ts { * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node: QualifiedName, useFallback: boolean): Expression { - let left: Expression; + function serializeQualifiedNameAsExpression(node: QualifiedName, useFallback: boolean): PropertyAccessExpression { + let left: SerializedEntityNameAsExpression; if (node.left.kind === SyntaxKind.Identifier) { left = serializeEntityNameAsExpression(node.left, useFallback); } @@ -1973,15 +1893,10 @@ namespace ts { * Gets an expression that points to the global "Symbol" constructor at runtime if it is * available. */ - function getGlobalSymbolNameWithFallback(): Expression { + function getGlobalSymbolNameWithFallback(): ConditionalExpression { return createConditional( - createStrictEquality( - createTypeOf(createIdentifier("Symbol")), - createLiteral("function") - ), - createToken(SyntaxKind.QuestionToken), + createTypeCheck(createIdentifier("Symbol"), "function"), createIdentifier("Symbol"), - createToken(SyntaxKind.ColonToken), createIdentifier("Object") ); } @@ -2000,7 +1915,7 @@ namespace ts { : (name).expression; } else if (isIdentifier(name)) { - return createLiteral(name.text); + return createLiteral(unescapeIdentifier(name.text)); } else { return getSynthesizedClone(name); @@ -2083,12 +1998,20 @@ namespace ts { return !nodeIsMissing(node.body); } + function visitConstructor(node: ConstructorDeclaration) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + + return visitEachChild(node, visitor, context); + } + /** * Visits a method declaration of a class. * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node is marked as abstract, public, private, protected, or readonly * - The node has both a decorator and a computed property name * * @param node The method node. @@ -2097,26 +2020,23 @@ namespace ts { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - - const method = createMethod( + const updated = updateMethod( + node, /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), - node.asteriskToken, + visitNodes(node.modifiers, modifierVisitor, isModifier), visitPropertyNameOfClassElement(node), /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformFunctionBody(node), - /*location*/ node + visitFunctionBody(node.body, visitor, context) ); - - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, moveRangePastDecorators(node)); - setOriginalNode(method, node); - - return method; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(updated, node); + setSourceMapRange(updated, moveRangePastDecorators(node)); + } + return updated; } /** @@ -2142,24 +2062,22 @@ namespace ts { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - - const accessor = createGetAccessor( + const updated = updateGetAccessor( + node, /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), + visitNodes(node.modifiers, modifierVisitor, isModifier), visitPropertyNameOfClassElement(node), - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - node.body ? visitEachChild(node.body, visitor, context) : createBlock([]), - /*location*/ node + visitFunctionBody(node.body, visitor, context) || createBlock([]) ); - - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, moveRangePastDecorators(node)); - setOriginalNode(accessor, node); - - return accessor; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(updated, node); + setSourceMapRange(updated, moveRangePastDecorators(node)); + } + return updated; } /** @@ -2175,23 +2093,21 @@ namespace ts { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - - const accessor = createSetAccessor( + const updated = updateSetAccessor( + node, /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), + visitNodes(node.modifiers, modifierVisitor, isModifier), visitPropertyNameOfClassElement(node), - visitNodes(node.parameters, visitor, isParameter), - node.body ? visitEachChild(node.body, visitor, context) : createBlock([]), - /*location*/ node + visitParameterList(node.parameters, visitor, context), + visitFunctionBody(node.body, visitor, context) || createBlock([]) ); - - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, moveRangePastDecorators(node)); - setOriginalNode(accessor, node); - - return accessor; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(updated, node); + setSourceMapRange(updated, moveRangePastDecorators(node)); + } + return updated; } /** @@ -2199,8 +2115,8 @@ namespace ts { * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked async * - The node is exported from a TypeScript namespace + * - The node has decorators * * @param node The function node. */ @@ -2208,34 +2124,29 @@ namespace ts { if (!shouldEmitFunctionLikeDeclaration(node)) { return createNotEmittedStatement(node); } - - const func = createFunctionDeclaration( + const updated = updateFunctionDeclaration( + node, /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), - node.asteriskToken, + visitNodes(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformFunctionBody(node), - /*location*/ node + visitFunctionBody(node.body, visitor, context) || createBlock([]) ); - setOriginalNode(func, node); - if (isNamespaceExport(node)) { - const statements: Statement[] = [func]; + const statements: Statement[] = [updated]; addExportMemberAssignment(statements, node); return statements; } - - return func; + return updated; } /** * Visits a function expression node. * * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations * * @param node The function expression node. */ @@ -2243,155 +2154,33 @@ namespace ts { if (nodeIsMissing(node.body)) { return createOmittedExpression(); } - - const func = createFunctionExpression( - node.asteriskToken, + const updated = updateFunctionExpression( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformFunctionBody(node), - /*location*/ node + visitFunctionBody(node.body, visitor, context) ); - - setOriginalNode(func, node); - - return func; + return updated; } /** * @remarks * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations */ function visitArrowFunction(node: ArrowFunction) { - const func = createArrowFunction( - /*modifiers*/ undefined, + const updated = updateArrowFunction( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), + visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - node.equalsGreaterThanToken, - transformConciseBody(node), - /*location*/ node + visitFunctionBody(node.body, visitor, context) ); - - setOriginalNode(func, node); - - return func; - } - - function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { - if (isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - - return transformFunctionBodyWorker(node.body); - } - - function transformFunctionBodyWorker(body: Block, start = 0) { - const savedCurrentScope = currentScope; - currentScope = body; - startLexicalEnvironment(); - - const statements = visitNodes(body.statements, visitor, isStatement, start); - const visited = updateBlock(body, statements); - const declarations = endLexicalEnvironment(); - currentScope = savedCurrentScope; - return mergeFunctionBodyLexicalEnvironment(visited, declarations); - } - - function transformConciseBody(node: ArrowFunction): ConciseBody { - if (isAsyncFunctionLike(node)) { - return transformAsyncFunctionBody(node); - } - - return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); - } - - function transformConciseBodyWorker(body: Block | Expression, forceBlockFunctionBody: boolean) { - if (isBlock(body)) { - return transformFunctionBodyWorker(body); - } - else { - startLexicalEnvironment(); - const visited: Expression | Block = visitNode(body, visitor, isConciseBody); - const declarations = endLexicalEnvironment(); - const merged = mergeFunctionBodyLexicalEnvironment(visited, declarations); - if (forceBlockFunctionBody && !isBlock(merged)) { - return createBlock([ - createReturn(merged) - ]); - } - else { - return merged; - } - } - } - - function getPromiseConstructor(type: TypeNode) { - const typeName = getEntityNameFromTypeNode(type); - if (typeName && isEntityName(typeName)) { - const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - - return undefined; - } - - function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody { - const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(node.type) : undefined; - const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; - const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; - - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - - - if (!isArrowFunction) { - const statements: Statement[] = []; - const statementOffset = addPrologueDirectives(statements, (node.body).statements, /*ensureUseStrict*/ false, visitor); - statements.push( - createReturn( - createAwaiterHelper( - currentSourceFileExternalHelpersModuleName, - hasLexicalArguments, - promiseConstructor, - transformFunctionBodyWorker(node.body, statementOffset) - ) - ) - ); - - const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true); - - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES6) { - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); - setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper); - } - else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); - setEmitFlags(block, EmitFlags.EmitSuperHelper); - } - } - - return block; - } - else { - return createAwaiterHelper( - currentSourceFileExternalHelpersModuleName, - hasLexicalArguments, - promiseConstructor, - transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true) - ); - } + return updated; } /** @@ -2409,7 +2198,7 @@ namespace ts { return undefined; } - const parameter = createParameterDeclaration( + const parameter = createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, @@ -2459,12 +2248,13 @@ namespace ts { function transformInitializedVariable(node: VariableDeclaration): Expression { const name = node.name; if (isBindingPattern(name)) { - return flattenVariableDestructuringToExpression( - context, + return flattenDestructuringAssignment( node, - hoistVariableDeclaration, - getNamespaceMemberNameWithSourceMapsAndWithoutComments, - visitor + visitor, + context, + FlattenLevel.All, + /*needsValue*/ false, + createNamespaceExportExpression ); } else { @@ -2476,22 +2266,12 @@ namespace ts { } } - /** - * Visits an await expression. - * - * This function will be called any time a TypeScript await expression is encountered. - * - * @param node The await expression node. - */ - function visitAwaitExpression(node: AwaitExpression): Expression { - return setOriginalNode( - createYield( - /*asteriskToken*/ undefined, - visitNode(node.expression, visitor, isExpression), - /*location*/ node - ), - node - ); + function visitVariableDeclaration(node: VariableDeclaration) { + return updateVariableDeclaration( + node, + visitNode(node.name, visitor, isBindingName), + /*type*/ undefined, + visitNode(node.initializer, visitor, isExpression)); } /** @@ -2536,6 +2316,22 @@ namespace ts { return createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node: CallExpression) { + return updateCall( + node, + visitNode(node.expression, visitor, isExpression), + /*typeArguments*/ undefined, + visitNodes(node.arguments, visitor, isExpression)); + } + + function visitNewExpression(node: NewExpression) { + return updateNew( + node, + visitNode(node.expression, visitor, isExpression), + /*typeArguments*/ undefined, + visitNodes(node.arguments, visitor, isExpression)); + } + /** * Determines whether to emit an enum declaration. * @@ -2547,29 +2343,6 @@ namespace ts { || compilerOptions.isolatedModules; } - function shouldEmitVarForEnumDeclaration(node: EnumDeclaration | ModuleDeclaration) { - return isFirstEmittedDeclarationInScope(node) - && (!hasModifier(node, ModifierFlags.Export) - || isES6ExportedDeclaration(node)); - } - - - /* - * Adds a trailing VariableStatement for an enum or module declaration. - */ - function addVarForEnumExportedFromNamespace(statements: Statement[], node: EnumDeclaration | ModuleDeclaration) { - const statement = createVariableStatement( - /*modifiers*/ undefined, - [createVariableDeclaration( - getDeclarationName(node), - /*type*/ undefined, - getExportName(node) - )] - ); - setSourceMapRange(statement, node); - statements.push(statement); - } - /** * Visits an enum declaration. * @@ -2591,10 +2364,7 @@ namespace ts { // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - recordEmittedDeclarationInScope(node); - if (shouldEmitVarForEnumDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); - + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ModuleKind.System || currentScope !== currentSourceFile) { emitFlags |= EmitFlags.NoLeadingComments; @@ -2608,7 +2378,28 @@ namespace ts { const containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - const exportName = getExportName(node); + const exportName = hasModifier(node, ModifierFlags.Export) + ? getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + + // x || (x = {}) + // exports.x || (exports.x = {}) + let moduleArg = + createLogicalOr( + exportName, + createAssignment( + exportName, + createObjectLiteral() + ) + ); + + if (hasNamespaceQualifiedExportName(node)) { + // `localName` is the expression used within this node's containing scope for any local references. + const localName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + + // x = (exports.x || (exports.x = {})) + moduleArg = createAssignment(localName, moduleArg); + } // (function (x) { // x[x["y"] = 0] = "y"; @@ -2617,21 +2408,16 @@ namespace ts { const enumStatement = createStatement( createCall( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - [createParameter(parameterName)], + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName) ), /*typeArguments*/ undefined, - [createLogicalOr( - exportName, - createAssignment( - exportName, - createObjectLiteral() - ) - )] + [moduleArg] ), /*location*/ node ); @@ -2640,10 +2426,9 @@ namespace ts { setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - if (isNamespaceExport(node)) { - addVarForEnumExportedFromNamespace(statements, node); - } - + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. + statements.push(createEndOfDeclarationMarker(node)); return statements; } @@ -2728,9 +2513,15 @@ namespace ts { return isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isES6ExportedDeclaration(node: Node) { - return isExternalModuleExport(node) - && moduleKind === ModuleKind.ES6; + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ + function hasNamespaceQualifiedExportName(node: Node) { + return isNamespaceExport(node) + || (isExternalModuleExport(node) + && moduleKind !== ModuleKind.ES2015 + && moduleKind !== ModuleKind.System); } /** @@ -2768,57 +2559,65 @@ namespace ts { return false; } - function shouldEmitVarForModuleDeclaration(node: ModuleDeclaration) { - return isFirstEmittedDeclarationInScope(node); - } - /** * Adds a leading VariableStatement for a enum or module declaration. */ function addVarForEnumOrModuleDeclaration(statements: Statement[], node: ModuleDeclaration | EnumDeclaration) { // Emit a variable statement for the module. const statement = createVariableStatement( - isES6ExportedDeclaration(node) - ? visitNodes(node.modifiers, visitor, isModifier) - : undefined, + visitNodes(node.modifiers, modifierVisitor, isModifier), [ createVariableDeclaration( - getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) + getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) ) ] ); - setOriginalNode(statement, /*original*/ node); + setOriginalNode(statement, node); - // Adjust the source map emit to match the old emitter. - if (node.kind === SyntaxKind.EnumDeclaration) { - setSourceMapRange(statement.declarationList, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + // Adjust the source map emit to match the old emitter. + if (node.kind === SyntaxKind.EnumDeclaration) { + setSourceMapRange(statement.declarationList, node); + } + else { + setSourceMapRange(statement, node); + } + + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // + setCommentRange(statement, node); + setEmitFlags(statement, EmitFlags.NoTrailingComments | EmitFlags.HasEndOfDeclarationMarker); + statements.push(statement); + return true; } else { - setSourceMapRange(statement, node); + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. + const mergeMarker = createMergeDeclarationMarker(statement); + setEmitFlags(mergeMarker, EmitFlags.NoComments | EmitFlags.HasEndOfDeclarationMarker); + statements.push(mergeMarker); + return false; } - - // Trailing comments for module declaration should be emitted after the function closure - // instead of the variable statement: - // - // /** Module comment*/ - // module m1 { - // function foo4Export() { - // } - // } // trailing comment module - // - // Should emit: - // - // /** Module comment*/ - // var m1; - // (function (m1) { - // function foo4Export() { - // } - // })(m1 || (m1 = {})); // trailing comment module - // - setCommentRange(statement, node); - setEmitFlags(statement, EmitFlags.NoTrailingComments); - statements.push(statement); } /** @@ -2845,9 +2644,7 @@ namespace ts { // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - recordEmittedDeclarationInScope(node); - if (shouldEmitVarForModuleDeclaration(node)) { - addVarForEnumOrModuleDeclaration(statements, node); + if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ModuleKind.System || currentScope !== currentSourceFile) { emitFlags |= EmitFlags.NoLeadingComments; @@ -2861,7 +2658,9 @@ namespace ts { const containerName = getNamespaceContainerName(node); // `exportName` is the expression used within this node's container for any exported references. - const exportName = getExportName(node); + const exportName = hasModifier(node, ModifierFlags.Export) + ? getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x || (x = {}) // exports.x || (exports.x = {}) @@ -2874,9 +2673,9 @@ namespace ts { ) ); - if (hasModifier(node, ModifierFlags.Export) && !isES6ExportedDeclaration(node)) { + if (hasNamespaceQualifiedExportName(node)) { // `localName` is the expression used within this node's containing scope for any local references. - const localName = getLocalName(node); + const localName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); // x = (exports.x || (exports.x = {})) moduleArg = createAssignment(localName, moduleArg); @@ -2888,10 +2687,11 @@ namespace ts { const moduleStatement = createStatement( createCall( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - [createParameter(parameterName)], + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName) ), @@ -2904,6 +2704,10 @@ namespace ts { setOriginalNode(moduleStatement, node); setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. + statements.push(createEndOfDeclarationMarker(node)); return statements; } @@ -2927,7 +2731,7 @@ namespace ts { let blockLocation: TextRange; const body = node.body; if (body.kind === SyntaxKind.ModuleBlock) { - addRange(statements, visitNodes((body).statements, namespaceElementVisitor, isStatement)); + saveStateAndInvoke(body, body => addRange(statements, visitNodes((body).statements, namespaceElementVisitor, isStatement))); statementsLocation = (body).statements; blockLocation = body; } @@ -2993,6 +2797,133 @@ namespace ts { } } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node: ImportDeclaration): VisitResult { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + + // Elide the declaration if the import clause was elided. + const importClause = visitNode(node.importClause, visitImportClause, isImportClause, /*optional*/ true); + return importClause + ? updateImportDeclaration( + node, + /*decorators*/ undefined, + /*modifiers*/ undefined, + importClause, + node.moduleSpecifier) + : undefined; + } + + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node: ImportClause): VisitResult { + // Elide the import clause if we elide both its name and its named bindings. + const name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings, /*optional*/ true); + return (name || namedBindings) ? updateImportClause(node, name, namedBindings) : undefined; + } + + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node: NamedImportBindings): VisitResult { + if (node.kind === SyntaxKind.NamespaceImport) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier); + return some(elements) ? updateNamedImports(node, elements) : undefined; + } + } + + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node: ImportSpecifier): VisitResult { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node: ExportAssignment): VisitResult { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? visitEachChild(node, visitor, context) + : undefined; + } + + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node: ExportDeclaration): VisitResult { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + + // Elide the export declaration if all of its named exports are elided. + const exportClause = visitNode(node.exportClause, visitNamedExports, isNamedExports, /*optional*/ true); + return exportClause + ? updateExportDeclaration( + node, + /*decorators*/ undefined, + /*modifiers*/ undefined, + exportClause, + node.moduleSpecifier) + : undefined; + } + + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node: NamedExports): VisitResult { + // Elide the named exports if all of its export specifiers were elided. + const elements = visitNodes(node.elements, visitExportSpecifier, isExportSpecifier); + return some(elements) ? updateNamedExports(node, elements) : undefined; + } + + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node: ExportSpecifier): VisitResult { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** * Determines whether to emit an import equals declaration. * @@ -3014,7 +2945,10 @@ namespace ts { */ function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { if (isExternalModuleImportEqualsDeclaration(node)) { - return visitEachChild(node, visitor, context); + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { @@ -3029,12 +2963,15 @@ namespace ts { // var ${name} = ${moduleReference}; return setOriginalNode( createVariableStatement( - visitNodes(node.modifiers, visitor, isModifier), + visitNodes(node.modifiers, modifierVisitor, isModifier), createVariableDeclarationList([ - createVariableDeclaration( - node.name, - /*type*/ undefined, - moduleReference + setOriginalNode( + createVariableDeclaration( + node.name, + /*type*/ undefined, + moduleReference + ), + node ) ]), node @@ -3102,8 +3039,8 @@ namespace ts { function addExportMemberAssignment(statements: Statement[], node: ClassDeclaration | FunctionDeclaration) { const expression = createAssignment( - getExportName(node), - getLocalName(node, /*noSourceMaps*/ true) + getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), + getLocalName(node) ); setSourceMapRange(expression, createRange(node.name.pos, node.end)); @@ -3115,40 +3052,19 @@ namespace ts { function createNamespaceExport(exportName: Identifier, exportValue: Expression, location?: TextRange) { return createStatement( createAssignment( - getNamespaceMemberName(exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), + getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue ), location ); } - function createExternalModuleExport(exportName: Identifier) { - return createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - createNamedExports([ - createExportSpecifier(exportName) - ]) - ); - } - - function getNamespaceMemberName(name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): Expression { - const qualifiedName = createPropertyAccess(currentNamespaceContainerName, getSynthesizedClone(name), /*location*/ name); - let emitFlags: EmitFlags; - if (!allowComments) { - emitFlags |= EmitFlags.NoComments; - } - if (!allowSourceMaps) { - emitFlags |= EmitFlags.NoSourceMap; - } - if (emitFlags) { - setEmitFlags(qualifiedName, emitFlags); - } - return qualifiedName; + function createNamespaceExportExpression(exportName: Identifier, exportValue: Expression, location?: TextRange) { + return createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name: Identifier) { - return getNamespaceMemberName(name, /*allowComments*/ false, /*allowSourceMaps*/ true); + return getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); } /** @@ -3169,65 +3085,17 @@ namespace ts { } /** - * Gets the local name for a declaration for use in expressions. - * - * A local name will *never* be prefixed with an module or namespace export modifier like - * "exports.". - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. */ - function getLocalName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, noSourceMaps?: boolean, allowComments?: boolean) { - return getDeclarationName(node, allowComments, !noSourceMaps, EmitFlags.LocalName); - } - - /** - * Gets the export name for a declaration for use in expressions. - * - * An export name will *always* be prefixed with an module or namespace export modifier - * like "exports." if one is required. - * - * @param node The declaration. - * @param noSourceMaps A value indicating whether source maps may not be emitted for the name. - * @param allowComments A value indicating whether comments may be emitted for the name. - */ - function getExportName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, noSourceMaps?: boolean, allowComments?: boolean) { - if (isNamespaceExport(node)) { - return getNamespaceMemberName(getDeclarationName(node), allowComments, !noSourceMaps); - } - - return getDeclarationName(node, allowComments, !noSourceMaps, EmitFlags.ExportName); - } - - /** - * Gets the name for a declaration for use in declarations. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - * @param emitFlags Additional NodeEmitFlags to specify for the name. - */ - function getDeclarationName(node: FunctionDeclaration | ClassDeclaration | ClassExpression | ModuleDeclaration | EnumDeclaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { - if (node.name) { - const name = getMutableClone(node.name); - emitFlags |= getEmitFlags(node.name); - if (!allowSourceMaps) { - emitFlags |= EmitFlags.NoSourceMap; - } - - if (!allowComments) { - emitFlags |= EmitFlags.NoComments; - } - - if (emitFlags) { - setEmitFlags(name, emitFlags); - } - - return name; - } - else { - return getGeneratedNameForNode(node); + function getClassAliasIfNeeded(node: ClassDeclaration) { + if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference) { + enableSubstitutionForClassAliases(); + const classAlias = createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? node.name.text : "default"); + classAliases[getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } } @@ -3248,25 +3116,6 @@ namespace ts { } } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) === 0) { - enabledSubstitutions |= TypeScriptSubstitutionFlags.AsyncMethodsWithSuper; - - // We need to enable substitutions for call, property access, and element access - // if we need to rewrite super calls. - context.enableSubstitution(SyntaxKind.CallExpression); - context.enableSubstitution(SyntaxKind.PropertyAccessExpression); - context.enableSubstitution(SyntaxKind.ElementAccessExpression); - - // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(SyntaxKind.ClassDeclaration); - context.enableEmitNotification(SyntaxKind.MethodDeclaration); - context.enableEmitNotification(SyntaxKind.GetAccessor); - context.enableEmitNotification(SyntaxKind.SetAccessor); - context.enableEmitNotification(SyntaxKind.Constructor); - } - } - function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & TypeScriptSubstitutionFlags.ClassAliases) === 0) { enabledSubstitutions |= TypeScriptSubstitutionFlags.ClassAliases; @@ -3294,15 +3143,6 @@ namespace ts { } } - function isSuperContainer(node: Node): node is SuperContainer { - const kind = node.kind; - return kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; - } - function isTransformedModuleDeclaration(node: Node): boolean { return getOriginalNode(node).kind === SyntaxKind.ModuleDeclaration; } @@ -3314,17 +3154,12 @@ namespace ts { /** * Hook for node emit. * + * @param emitContext A context hint for the emitter. * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { const savedApplicableSubstitutions = applicableSubstitutions; - const savedCurrentSuperContainer = currentSuperContainer; - // If we need to support substitutions for `super` in an async method, - // we should track it here. - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports; @@ -3337,15 +3172,13 @@ namespace ts { previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } /** * Hooks node substitutions. * + * @param emitContext A context hint for the emitter. * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. */ function onSubstituteNode(emitContext: EmitContext, node: Node) { node = previousOnSubstituteNode(emitContext, node); @@ -3384,11 +3217,6 @@ namespace ts { return substitutePropertyAccessExpression(node); case SyntaxKind.ElementAccessExpression: return substituteElementAccessExpression(node); - case SyntaxKind.CallExpression: - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) { - return substituteCallExpression(node); - } - break; } return node; @@ -3426,11 +3254,11 @@ namespace ts { function trySubstituteNamespaceExportedName(node: Identifier): Expression { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getEmitFlags(node) & EmitFlags.LocalName) === 0) { + if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. const container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container) { + if (container && container.kind !== SyntaxKind.SourceFile) { const substitute = (applicableSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && container.kind === SyntaxKind.ModuleDeclaration) || (applicableSubstitutions & TypeScriptSubstitutionFlags.NonQualifiedEnumMembers && container.kind === SyntaxKind.EnumDeclaration); @@ -3443,54 +3271,11 @@ namespace ts { return undefined; } - function substituteCallExpression(node: CallExpression): Expression { - const expression = node.expression; - if (isSuperProperty(expression)) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - const argumentExpression = isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return createCall( - createPropertyAccess(argumentExpression, "call"), - /*typeArguments*/ undefined, - [ - createThis(), - ...node.arguments - ] - ); - } - } - return node; - } - function substitutePropertyAccessExpression(node: PropertyAccessExpression) { - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod( - createLiteral(node.name.text), - flags, - node - ); - } - } - return substituteConstantValue(node); } function substituteElementAccessExpression(node: ElementAccessExpression) { - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod( - node.argumentExpression, - flags, - node - ); - } - } - return substituteConstantValue(node); } @@ -3523,32 +3308,78 @@ namespace ts { ? resolver.getConstantValue(node) : undefined; } + } - function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression { - if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) { - return createPropertyAccess( - createCall( - createIdentifier("_super"), - /*typeArguments*/ undefined, - [argumentExpression] - ), - "value", - location - ); - } - else { - return createCall( - createIdentifier("_super"), - /*typeArguments*/ undefined, - [argumentExpression], - location - ); + const paramHelper: EmitHelper = { + name: "typescript:param", + scoped: false, + priority: 4, + text: ` + var __param = (this && this.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + };` + }; + + function createParamHelper(context: TransformationContext, expression: Expression, parameterOffset: number, location?: TextRange) { + context.requestEmitHelper(paramHelper); + return createCall( + getHelperName("__param"), + /*typeArguments*/ undefined, + [ + createLiteral(parameterOffset), + expression + ], + location + ); + } + + const metadataHelper: EmitHelper = { + name: "typescript:metadata", + scoped: false, + priority: 3, + text: ` + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + };` + }; + + function createMetadataHelper(context: TransformationContext, metadataKey: string, metadataValue: Expression) { + context.requestEmitHelper(metadataHelper); + return createCall( + getHelperName("__metadata"), + /*typeArguments*/ undefined, + [ + createLiteral(metadataKey), + metadataValue + ] + ); + } + + const decorateHelper: EmitHelper = { + name: "typescript:decorate", + scoped: false, + priority: 2, + text: ` + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + };` + }; + + function createDecorateHelper(context: TransformationContext, decoratorExpressions: Expression[], target: Expression, memberName?: Expression, descriptor?: Expression, location?: TextRange) { + context.requestEmitHelper(decorateHelper); + const argumentsArray: Expression[] = []; + argumentsArray.push(createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true)); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); } } - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding); - } + return createCall(getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray, location); } } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index b39c017384e..a7304eebe4b 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -29,7 +29,7 @@ namespace ts { } } - function reportEmittedFiles(files: string[], host: CompilerHost): void { + function reportEmittedFiles(files: string[]): void { if (!files || files.length == 0) { return; } @@ -43,66 +43,6 @@ namespace ts { } } - /** - * Checks to see if the locale is in the appropriate format, - * and if it is, attempts to set the appropriate language. - */ - function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); - - if (!matchResult) { - errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); - return false; - } - - const language = matchResult[1]; - const territory = matchResult[3]; - - // First try the entire locale, then fall back to just language if that's all we have. - // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { - trySetLanguageAndTerritory(language, undefined, errors); - } - - return true; - } - - function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { - const compilerFilePath = normalizePath(sys.getExecutingFilePath()); - const containingDirectoryPath = getDirectoryPath(compilerFilePath); - - let filePath = combinePaths(containingDirectoryPath, language); - - if (territory) { - filePath = filePath + "-" + territory; - } - - filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); - - if (!sys.fileExists(filePath)) { - return false; - } - - // TODO: Add codePage support for readFile? - let fileContents = ""; - try { - fileContents = sys.readFile(filePath); - } - catch (e) { - errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); - return false; - } - try { - ts.localizedDiagnosticMessages = JSON.parse(fileContents); - } - catch (e) { - errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); - return false; - } - - return true; - } - function countLines(program: Program): number { let count = 0; forEach(program.getSourceFiles(), file => { @@ -111,7 +51,7 @@ namespace ts { return count; } - function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { + function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } @@ -250,8 +190,8 @@ namespace ts { let compilerOptions: CompilerOptions; // Compiler options for compilation let compilerHost: CompilerHost; // Compiler host let hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host - let timerHandleForRecompilation: number; // Handle for 0.25s wait timer to trigger recompilation - let timerHandleForDirectoryChanges: number; // Handle for 0.25s wait timer to trigger directory change handler + let timerHandleForRecompilation: any; // Handle for 0.25s wait timer to trigger recompilation + let timerHandleForDirectoryChanges: any; // Handle for 0.25s wait timer to trigger directory change handler // This map stores and reuses results of fileExists check that happen inside 'createProgram' // This allows to save time in module resolution heavy scenarios when existence of the same file might be checked multiple times. @@ -263,7 +203,7 @@ namespace ts { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), /* host */ undefined); return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } - validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); + validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors); } // If there are any errors due to command line parsing and/or @@ -456,7 +396,7 @@ namespace ts { const sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && isWatchSet(compilerOptions) && sys.watchFile) { // Attach a file watcher - sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed)); + sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (_fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed)); } return sourceFile; } @@ -503,10 +443,14 @@ namespace ts { } function startTimerForHandlingDirectoryChanges() { - if (timerHandleForDirectoryChanges) { - clearTimeout(timerHandleForDirectoryChanges); + if (!sys.setTimeout || !sys.clearTimeout) { + return; } - timerHandleForDirectoryChanges = setTimeout(directoryChangeHandler, 250); + + if (timerHandleForDirectoryChanges) { + sys.clearTimeout(timerHandleForDirectoryChanges); + } + timerHandleForDirectoryChanges = sys.setTimeout(directoryChangeHandler, 250); } function directoryChangeHandler() { @@ -525,10 +469,14 @@ namespace ts { // operations (such as saving all modified files in an editor) a chance to complete before we kick // off a new compilation. function startTimerForRecompilation() { - if (timerHandleForRecompilation) { - clearTimeout(timerHandleForRecompilation); + if (!sys.setTimeout || !sys.clearTimeout) { + return; } - timerHandleForRecompilation = setTimeout(recompile, 250); + + if (timerHandleForRecompilation) { + sys.clearTimeout(timerHandleForRecompilation); + } + timerHandleForRecompilation = sys.setTimeout(recompile, 250); } function recompile() { @@ -617,7 +565,7 @@ namespace ts { reportDiagnostics(sortAndDeduplicateDiagnostics(diagnostics), compilerHost); - reportEmittedFiles(emitOutput.emittedFiles, compilerHost); + reportEmittedFiles(emitOutput.emittedFiles); if (emitOutput.emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index f128c994af1..cbbdbb04d50 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -8,7 +8,11 @@ "outFile": "../../built/local/tsc.js", "sourceMap": true, "declaration": true, - "stripInternal": true + "stripInternal": true, + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": [ ] }, "files": [ "core.ts", @@ -24,13 +28,17 @@ "visitor.ts", "transformers/ts.ts", "transformers/jsx.ts", - "transformers/es7.ts", - "transformers/es6.ts", + "transformers/esnext.ts", + "transformers/es2017.ts", + "transformers/es2016.ts", + "transformers/es2015.ts", + "transformers/es5.ts", "transformers/generators.ts", + "transformers/es5.ts", "transformers/destructuring.ts", "transformers/module/module.ts", "transformers/module/system.ts", - "transformers/module/es6.ts", + "transformers/module/es2015.ts", "transformer.ts", "comments.ts", "sourcemap.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e54157ba986..ee432b13240 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -45,6 +45,7 @@ namespace ts { // Literals NumericLiteral, StringLiteral, + JsxText, RegularExpressionLiteral, NoSubstitutionTemplateLiteral, // Pseudo-literals @@ -167,6 +168,7 @@ namespace ts { DeclareKeyword, GetKeyword, IsKeyword, + KeyOfKeyword, ModuleKeyword, NamespaceKeyword, NeverKeyword, @@ -215,6 +217,9 @@ namespace ts { IntersectionType, ParenthesizedType, ThisType, + TypeOperator, + IndexedAccessType, + MappedType, LiteralType, // Binding patterns ObjectBindingPattern, @@ -242,7 +247,7 @@ namespace ts { ConditionalExpression, TemplateExpression, YieldExpression, - SpreadElementExpression, + SpreadElement, ClassExpression, OmittedExpression, ExpressionWithTypeArguments, @@ -302,7 +307,6 @@ namespace ts { JsxElement, JsxSelfClosingElement, JsxOpeningElement, - JsxText, JsxClosingElement, JsxAttribute, JsxSpreadAttribute, @@ -317,6 +321,7 @@ namespace ts { // Property assignments PropertyAssignment, ShorthandPropertyAssignment, + SpreadAssignment, // Enum EnumMember, @@ -344,6 +349,7 @@ namespace ts { JSDocThisType, JSDocComment, JSDocTag, + JSDocAugmentsTag, JSDocParameterTag, JSDocReturnTag, JSDocTypeTag, @@ -362,6 +368,9 @@ namespace ts { // Transformation nodes NotEmittedStatement, PartiallyEmittedExpression, + MergeDeclarationMarker, + EndOfDeclarationMarker, + RawExpression, // Enum value count Count, @@ -409,25 +418,20 @@ namespace ts { HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding) HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding) GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope - HasClassExtends = 1 << 10, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding) - HasDecorators = 1 << 11, // If the file has decorators (initialized by binding) - HasParamDecorators = 1 << 12, // If the file has parameter decorators (initialized by binding) - HasAsyncFunctions = 1 << 13, // If the file has async functions (initialized by binding) - HasJsxSpreadAttributes = 1 << 14, // If the file as JSX spread attributes (initialized by binding) - DisallowInContext = 1 << 15, // If node was parsed in a context where 'in-expressions' are not allowed - YieldContext = 1 << 16, // If node was parsed in the 'yield' context created when parsing a generator - DecoratorContext = 1 << 17, // If node was parsed as part of a decorator - AwaitContext = 1 << 18, // If node was parsed in the 'await' context created when parsing an async function - ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node - JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript - ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error - HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node + HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding) + DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed + YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator + DecoratorContext = 1 << 13, // If node was parsed as part of a decorator + AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function + ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node + JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript + ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error + HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node BlockScoped = Let | Const, ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn, - EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasJsxSpreadAttributes, - ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags, + ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, // Parsing context flags ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile, @@ -449,13 +453,15 @@ namespace ts { Async = 1 << 8, // Property/Method/Function Default = 1 << 9, // Function/Class (export default declaration) Const = 1 << 11, // Variable declaration - HasComputedFlags = 1 << 29, // Modifier flags have been computed AccessibilityModifier = Public | Private | Protected, // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ParameterPropertyModifier = AccessibilityModifier | Readonly, NonPublicAccessibilityModifier = Private | Protected, + + TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const, + ExportDefault = Export | Default, } export const enum JsxFlags { @@ -486,7 +492,8 @@ namespace ts { parent?: Node; // Parent node (initialized by binding) /* @internal */ original?: Node; // The original node if this is an updated node. /* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms). - /* @internal */ jsDocComments?: JSDoc[]; // JSDoc for the node, if it has any. + /* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node + /* @internal */ jsDocCache?: (JSDoc | JSDocTag)[]; // All JSDoc that applies to the node, including parent docs and @param tags /* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding) /* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) /* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding) @@ -497,6 +504,7 @@ namespace ts { export interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; + /* @internal */ transformFlags?: TransformFlags; } export interface Token extends Node { @@ -511,6 +519,7 @@ namespace ts { export type EqualsGreaterThanToken = Token; export type EndOfFileToken = Token; export type AtToken = Token; + export type ReadonlyToken = Token; export type Modifier = Token @@ -543,6 +552,7 @@ namespace ts { originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later /*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier. /*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name. + isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace } // Transient identifier node (marked by id === -1) @@ -550,6 +560,14 @@ namespace ts { resolvedSymbol: Symbol; } + /*@internal*/ + export interface GeneratedIdentifier extends Identifier { + autoGenerateKind: GeneratedIdentifierKind.Auto + | GeneratedIdentifierKind.Loop + | GeneratedIdentifierKind.Unique + | GeneratedIdentifierKind.Node; + } + export interface QualifiedName extends Node { kind: SyntaxKind.QualifiedName; left: EntityName; @@ -558,9 +576,9 @@ namespace ts { export type EntityName = Identifier | QualifiedName; - export type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; + export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - export type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; export interface Declaration extends Node { _declarationBrand: any; @@ -568,7 +586,7 @@ namespace ts { } export interface DeclarationStatement extends Declaration, Statement { - name?: Identifier | LiteralExpression; + name?: Identifier | StringLiteral | NumericLiteral; } export interface ComputedPropertyName extends Node { @@ -632,7 +650,7 @@ namespace ts { export interface BindingElement extends Declaration { kind: SyntaxKind.BindingElement; propertyName?: PropertyName; // Binding property name (in object binding pattern) - dotDotDotToken?: DotDotDotToken; // Present on rest binding element + dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern) name: BindingName; // Declared binding element name initializer?: Expression; // Optional initializer } @@ -658,7 +676,7 @@ namespace ts { name?: PropertyName; } - export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; + export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment; export interface PropertyAssignment extends ObjectLiteralElement { kind: SyntaxKind.PropertyAssignment; @@ -677,6 +695,11 @@ namespace ts { objectAssignmentInitializer?: Expression; } + export interface SpreadAssignment extends ObjectLiteralElement { + kind: SyntaxKind.SpreadAssignment; + expression: Expression; + } + // SyntaxKind.VariableDeclaration // SyntaxKind.Parameter // SyntaxKind.BindingElement @@ -698,22 +721,20 @@ namespace ts { name: PropertyName; } - export interface BindingPattern extends Node { - elements: NodeArray; - } - - export interface ObjectBindingPattern extends BindingPattern { + export interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } - export type ArrayBindingElement = BindingElement | OmittedExpression; - - export interface ArrayBindingPattern extends BindingPattern { + export interface ArrayBindingPattern extends Node { kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } + export type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; + + export type ArrayBindingElement = BindingElement | OmittedExpression; + /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -868,6 +889,26 @@ namespace ts { type: TypeNode; } + export interface TypeOperatorNode extends TypeNode { + kind: SyntaxKind.TypeOperator; + operator: SyntaxKind.KeyOfKeyword; + type: TypeNode; + } + + export interface IndexedAccessTypeNode extends TypeNode { + kind: SyntaxKind.IndexedAccessType; + objectType: TypeNode; + indexType: TypeNode; + } + + export interface MappedTypeNode extends TypeNode, Declaration { + kind: SyntaxKind.MappedType; + readonlyToken?: ReadonlyToken; + typeParameter: TypeParameterDeclaration; + questionToken?: QuestionToken; + type?: TypeNode; + } + export interface LiteralTypeNode extends TypeNode { kind: SyntaxKind.LiteralType; literal: Expression; @@ -875,7 +916,7 @@ namespace ts { export interface StringLiteral extends LiteralExpression { kind: SyntaxKind.StringLiteral; - /* @internal */ textSourceNode?: Identifier | StringLiteral; // Allows a StringLiteral to get its text from another node (used by transforms). + /* @internal */ textSourceNode?: Identifier | StringLiteral | NumericLiteral; // Allows a StringLiteral to get its text from another node (used by transforms). } // Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing. @@ -939,10 +980,6 @@ namespace ts { operator: PostfixUnaryOperator; } - export interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; - } - export interface LeftHandSideExpression extends IncrementExpression { _leftHandSideExpressionBrand: any; } @@ -1144,6 +1181,65 @@ namespace ts { right: Expression; } + export type AssignmentOperatorToken = Token; + + export interface AssignmentExpression extends BinaryExpression { + left: LeftHandSideExpression; + operatorToken: TOperator; + } + + export interface ObjectDestructuringAssignment extends AssignmentExpression { + left: ObjectLiteralExpression; + } + + export interface ArrayDestructuringAssignment extends AssignmentExpression { + left: ArrayLiteralExpression; + } + + export type DestructuringAssignment + = ObjectDestructuringAssignment + | ArrayDestructuringAssignment + ; + + export type BindingOrAssignmentElement + = VariableDeclaration + | ParameterDeclaration + | BindingElement + | PropertyAssignment // AssignmentProperty + | ShorthandPropertyAssignment // AssignmentProperty + | SpreadAssignment // AssignmentRestProperty + | OmittedExpression // Elision + | SpreadElement // AssignmentRestElement + | ArrayLiteralExpression // ArrayAssignmentPattern + | ObjectLiteralExpression // ObjectAssignmentPattern + | AssignmentExpression // AssignmentElement + | Identifier // DestructuringAssignmentTarget + | PropertyAccessExpression // DestructuringAssignmentTarget + | ElementAccessExpression // DestructuringAssignmentTarget + ; + + export type BindingOrAssignmentElementRestIndicator + = DotDotDotToken // from BindingElement + | SpreadElement // AssignmentRestElement + | SpreadAssignment // AssignmentRestProperty + ; + + export type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + + export type ObjectBindingOrAssignmentPattern + = ObjectBindingPattern + | ObjectLiteralExpression // ObjectAssignmentPattern + ; + + export type ArrayBindingOrAssignmentPattern + = ArrayBindingPattern + | ArrayLiteralExpression // ArrayAssignmentPattern + ; + + export type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; + + export type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; + export interface ConditionalExpression extends Expression { kind: SyntaxKind.ConditionalExpression; condition: Expression; @@ -1239,8 +1335,8 @@ namespace ts { multiLine?: boolean; } - export interface SpreadElementExpression extends Expression { - kind: SyntaxKind.SpreadElementExpression; + export interface SpreadElement extends Expression { + kind: SyntaxKind.SpreadElement; expression: Expression; } @@ -1417,6 +1513,32 @@ namespace ts { kind: SyntaxKind.NotEmittedStatement; } + /** + * Marks the end of transformed declaration to properly emit exports. + */ + /* @internal */ + export interface EndOfDeclarationMarker extends Statement { + kind: SyntaxKind.EndOfDeclarationMarker; + } + + /** + * Emits a string of raw text in an expression position. Raw text is never transformed, should + * be ES3 compliant, and should have the same precedence as PrimaryExpression. + */ + /* @internal */ + export interface RawExpression extends PrimaryExpression { + kind: SyntaxKind.RawExpression; + text: string; + } + + /** + * Marks the beginning of a merged transformed declaration. + */ + /* @internal */ + export interface MergeDeclarationMarker extends Statement { + kind: SyntaxKind.MergeDeclarationMarker; + } + export interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1448,6 +1570,11 @@ namespace ts { expression: Expression; } + /* @internal */ + export interface PrologueDirective extends ExpressionStatement { + expression: StringLiteral; + } + export interface IfStatement extends Statement { kind: SyntaxKind.IfStatement; expression: Expression; @@ -1632,8 +1759,8 @@ namespace ts { export interface ModuleDeclaration extends DeclarationStatement { kind: SyntaxKind.ModuleDeclaration; - name: Identifier | LiteralExpression; - body?: ModuleBlock | NamespaceDeclaration; + name: Identifier | StringLiteral; + body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier; } export interface NamespaceDeclaration extends ModuleDeclaration { @@ -1641,6 +1768,11 @@ namespace ts { body: ModuleBlock | NamespaceDeclaration; } + export interface JSDocNamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: JSDocNamespaceDeclaration | Identifier; + } + export interface ModuleBlock extends Node, Statement { kind: SyntaxKind.ModuleBlock; statements: NodeArray; @@ -1833,7 +1965,7 @@ namespace ts { export interface JSDocRecordMember extends PropertySignature { kind: SyntaxKind.JSDocRecordMember; - name: Identifier | LiteralExpression; + name: Identifier | StringLiteral | NumericLiteral; type?: JSDocType; } @@ -1853,6 +1985,11 @@ namespace ts { kind: SyntaxKind.JSDocTag; } + export interface JSDocAugmentsTag extends JSDocTag { + kind: SyntaxKind.JSDocAugmentsTag; + typeExpression: JSDocTypeExpression; + } + export interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; @@ -1870,6 +2007,7 @@ namespace ts { export interface JSDocTypedefTag extends JSDocTag, Declaration { kind: SyntaxKind.JSDocTypedefTag; + fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; @@ -1908,8 +2046,9 @@ namespace ts { TrueCondition = 1 << 5, // Condition known to be true FalseCondition = 1 << 6, // Condition known to be false SwitchClause = 1 << 7, // Switch statement clause - Referenced = 1 << 8, // Referenced as antecedent once - Shared = 1 << 9, // Referenced as antecedent more than once + ArrayMutation = 1 << 8, // Potential array mutation + Referenced = 1 << 9, // Referenced as antecedent once + Shared = 1 << 10, // Referenced as antecedent more than once Label = BranchLabel | LoopLabel, Condition = TrueCondition | FalseCondition } @@ -1923,7 +2062,7 @@ namespace ts { // function, the container property references the function (which in turn has a flowNode // property for the containing control flow). export interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } // FlowLabel represents a junction with multiple possible preceding control flows. @@ -1952,6 +2091,13 @@ namespace ts { antecedent: FlowNode; } + // FlowArrayMutation represents a node potentially mutates an array, i.e. an + // operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'. + export interface FlowArrayMutation extends FlowNode { + node: CallExpression | BinaryExpression; + antecedent: FlowNode; + } + export type FlowType = Type | IncompleteType; // Incomplete types occur during control flow analysis of loops. An IncompleteType @@ -2015,6 +2161,9 @@ namespace ts { // as well as code diagnostics). /* @internal */ parseDiagnostics: Diagnostic[]; + // Stores additional file level diagnostics reported by the program + /* @internal */ additionalSyntacticDiagnostics?: Diagnostic[]; + // File level diagnostics reported by the binder. /* @internal */ bindDiagnostics: Diagnostic[]; @@ -2025,13 +2174,12 @@ namespace ts { // Stores a mapping 'external module reference text' -> 'resolved file name' | undefined // It is used to resolve module names in the checker. // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead - /* @internal */ resolvedModules: Map; + /* @internal */ resolvedModules: Map; /* @internal */ resolvedTypeReferenceDirectiveNames: Map; /* @internal */ imports: LiteralExpression[]; /* @internal */ moduleAugmentations: LiteralExpression[]; /* @internal */ patternAmbientModules?: PatternAmbientModule[]; - // The synthesized identifier for an imported external helpers module. - /* @internal */ externalHelpersModuleName?: Identifier; + /* @internal */ ambientModuleNames: string[]; } export interface ScriptReferenceHost { @@ -2119,6 +2267,7 @@ namespace ts { /* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection; /* @internal */ getResolvedTypeReferenceDirectives(): Map; + /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; // For testing purposes only. /* @internal */ structureIsReused?: boolean; } @@ -2224,6 +2373,10 @@ namespace ts { isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; + tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + + /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol; + // Should not be called directly. Should only be accessed through the Program instance. /* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; /* @internal */ getGlobalDiagnostics(): Diagnostic[]; @@ -2255,6 +2408,7 @@ namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -2305,6 +2459,12 @@ namespace ts { CannotBeNamed } + /* @internal */ + export const enum SyntheticSymbolKind { + UnionOrIntersection, + Spread + } + export const enum TypePredicateKind { This, Identifier @@ -2397,6 +2557,7 @@ namespace ts { getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: SymbolWriter): void; + getJsxFactoryEntity(): EntityName; } export const enum SymbolFlags { @@ -2412,7 +2573,7 @@ namespace ts { RegularEnum = 0x00000100, // Enum ValueModule = 0x00000200, // Instantiated module NamespaceModule = 0x00000400, // Uninstantiated module - TypeLiteral = 0x00000800, // Type Literal + TypeLiteral = 0x00000800, // Type Literal or mapped type ObjectLiteral = 0x00001000, // Object Literal Method = 0x00002000, // Method Constructor = 0x00004000, // Constructor @@ -2516,7 +2677,9 @@ namespace ts { instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) mapper?: TypeMapper; // Type mapper for instantiation alias referenced?: boolean; // True if alias symbol has been referenced as a value - containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property + containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property + leftSpread?: Symbol; // Left source for synthetic spread property + rightSpread?: Symbol; // Right source for synthetic spread property hasNonUniformType?: boolean; // True if constituents have non-uniform types isPartial?: boolean; // True if syntheric property of union type occurs in some but not all constituents isDiscriminantProperty?: boolean; // True if discriminant synthetic property @@ -2577,6 +2740,7 @@ namespace ts { resolvedSignature?: Signature; // Cached signature of signature node or call expression resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result + maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate enumMemberValue?: number; // Constant value of enum member isVisible?: boolean; // Is this node visible hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context @@ -2603,24 +2767,19 @@ namespace ts { Null = 1 << 12, Never = 1 << 13, // Never type TypeParameter = 1 << 14, // Type parameter - Class = 1 << 15, // Class - Interface = 1 << 16, // Interface - Reference = 1 << 17, // Generic type reference - Tuple = 1 << 18, // Synthesized generic tuple type - Union = 1 << 19, // Union (T | U) - Intersection = 1 << 20, // Intersection (T & U) - Anonymous = 1 << 21, // Anonymous - Instantiated = 1 << 22, // Instantiated anonymous type + Object = 1 << 15, // Object type + Union = 1 << 16, // Union (T | U) + Intersection = 1 << 17, // Intersection (T & U) + Index = 1 << 18, // keyof T + IndexedAccess = 1 << 19, // T[K] /* @internal */ - ObjectLiteral = 1 << 23, // Originates in an object literal + FreshLiteral = 1 << 20, // Fresh literal type /* @internal */ - FreshLiteral = 1 << 24, // Fresh literal type + ContainsWideningType = 1 << 21, // Type is or contains undefined or null widening type /* @internal */ - ContainsWideningType = 1 << 25, // Type is or contains undefined or null widening type + ContainsObjectLiteral = 1 << 22, // Type is or contains object literal type /* @internal */ - ContainsObjectLiteral = 1 << 26, // Type is or contains object literal type - /* @internal */ - ContainsAnyFunctionType = 1 << 27, // Type is or contains object literal type + ContainsAnyFunctionType = 1 << 23, // Type is or contains object literal type /* @internal */ Nullable = Undefined | Null, @@ -2633,19 +2792,19 @@ namespace ts { Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never, /* @internal */ Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal, - StringLike = String | StringLiteral, + StringLike = String | StringLiteral | Index, NumberLike = Number | NumberLiteral | Enum | EnumLiteral, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, - ObjectType = Class | Interface | Reference | Tuple | Anonymous, UnionOrIntersection = Union | Intersection, - StructuredType = ObjectType | Union | Intersection, - StructuredOrTypeParameter = StructuredType | TypeParameter, + StructuredType = Object | Union | Intersection, + StructuredOrTypeParameter = StructuredType | TypeParameter | Index, + TypeVariable = TypeParameter | IndexedAccess, // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol, - NotUnionOrUnit = Any | String | Number | ESSymbol | ObjectType, + Narrowable = Any | StructuredType | TypeParameter | Index | IndexedAccess | StringLike | NumberLike | BooleanLike | ESSymbol, + NotUnionOrUnit = Any | ESSymbol | Object, /* @internal */ RequiresWidening = ContainsWideningType | ContainsObjectLiteral, /* @internal */ @@ -2688,9 +2847,23 @@ namespace ts { baseType: EnumType & UnionType; // Base enum type } + export const enum ObjectFlags { + Class = 1 << 0, // Class + Interface = 1 << 1, // Interface + Reference = 1 << 2, // Generic type reference + Tuple = 1 << 3, // Synthesized generic tuple type + Anonymous = 1 << 4, // Anonymous + Mapped = 1 << 5, // Mapped + Instantiated = 1 << 6, // Instantiated anonymous or mapped type + ObjectLiteral = 1 << 7, // Originates in an object literal + EvolvingArray = 1 << 8, // Evolving array type + ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties + ClassOrInterface = Class | Interface + } + // Object types (TypeFlags.ObjectType) export interface ObjectType extends Type { - isObjectLiteralPatternWithComputedProperties?: boolean; + objectFlags: ObjectFlags; } // Class and interface types (TypeFlags.Class and TypeFlags.Interface) @@ -2737,13 +2910,17 @@ namespace ts { /* @internal */ resolvedProperties: SymbolTable; // Cache of resolved properties /* @internal */ - couldContainTypeParameters: boolean; + resolvedIndexType: IndexType; + /* @internal */ + couldContainTypeVariables: boolean; } export interface UnionType extends UnionOrIntersectionType { } export interface IntersectionType extends UnionOrIntersectionType { } + export type StructuredType = ObjectType | UnionType | IntersectionType; + /* @internal */ // An instantiated anonymous type has a target and a mapper export interface AnonymousType extends ObjectType { @@ -2751,6 +2928,21 @@ namespace ts { mapper?: TypeMapper; // Instantiation mapper } + /* @internal */ + export interface MappedType extends ObjectType { + declaration: MappedTypeNode; + typeParameter?: TypeParameter; + constraintType?: Type; + templateType?: Type; + modifiersType?: Type; + mapper?: TypeMapper; // Instantiation mapper + } + + export interface EvolvingArrayType extends ObjectType { + elementType: Type; // Element expressions of evolving array type + finalArrayType?: Type; // Final array type of evolving array type + } + /* @internal */ // Resolved object, union, or intersection type export interface ResolvedType extends ObjectType, UnionOrIntersectionType { @@ -2777,19 +2969,37 @@ namespace ts { iteratorElementType?: Type; } + export interface TypeVariable extends Type { + /* @internal */ + resolvedApparentType: Type; + /* @internal */ + resolvedIndexType: IndexType; + } + // Type parameters (TypeFlags.TypeParameter) - export interface TypeParameter extends Type { + export interface TypeParameter extends TypeVariable { constraint: Type; // Constraint /* @internal */ target?: TypeParameter; // Instantiation target /* @internal */ mapper?: TypeMapper; // Instantiation mapper /* @internal */ - resolvedApparentType: Type; - /* @internal */ isThisType?: boolean; } + // Indexed access types (TypeFlags.IndexedAccess) + // Possible forms are T[xxx], xxx[T], or xxx[keyof T], where T is a type variable + export interface IndexedAccessType extends TypeVariable { + objectType: Type; + indexType: Type; + constraint?: Type; + } + + // keyof T types (TypeFlags.Index) + export interface IndexType extends Type { + type: TypeVariable | UnionOrIntersectionType; + } + export const enum SignatureKind { Call, Construct, @@ -2821,6 +3031,8 @@ namespace ts { isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison /* @internal */ typePredicate?: TypePredicate; + /* @internal */ + instantiations?: Map; // Generic signature instantiation cache } export const enum IndexKind { @@ -2838,7 +3050,6 @@ namespace ts { export interface TypeMapper { (t: TypeParameter): Type; mappedTypes?: Type[]; // Types mapped by this mapper - targetTypes?: Type[]; // Types substituted for mapped types instantiations?: Type[]; // Cache of instantiations created using this type mapper. context?: InferenceContext; // The inference context this mapper was created from. // Only inference mappers have this set (in createInferenceMapper). @@ -2878,6 +3089,12 @@ namespace ts { ThisProperty } + export interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } + export interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -2918,11 +3135,7 @@ namespace ts { NodeJs = 2 } - export type RootPaths = string[]; - export type PathSubstitutions = MapLike; - export type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - - export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; export interface CompilerOptions { allowJs?: boolean; @@ -2930,6 +3143,7 @@ namespace ts { allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; /* @internal */ configFilePath?: string; @@ -2959,6 +3173,7 @@ namespace ts { moduleResolution?: ModuleResolutionKind; newLine?: NewLineKind; noEmit?: boolean; + /*@internal*/noEmitForJsFiles?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; @@ -2974,14 +3189,15 @@ namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; /* @internal */ pretty?: DiagnosticStyle; reactNamespace?: string; + jsxFactory?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -2994,7 +3210,7 @@ namespace ts { target?: ScriptTarget; traceResolution?: boolean; types?: string[]; - /** Paths used to used to compute primary types search locations */ + /** Paths used to compute primary types search locations */ typeRoots?: string[]; /*@internal*/ version?: boolean; /*@internal*/ watch?: boolean; @@ -3002,8 +3218,12 @@ namespace ts { [option: string]: CompilerOptionsValue | undefined; } - export interface TypingOptions { + export interface TypeAcquisition { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ enableAutoDiscovery?: boolean; + enable?: boolean; include?: string[]; exclude?: string[]; [option: string]: string[] | boolean | undefined; @@ -3014,8 +3234,9 @@ namespace ts { projectRootPath: string; // The path to the project root directory safeListPath: string; // The path used to retrieve the safe list packageNameToTypingLocation: Map; // The map of package names to their cached typing locations - typingOptions: TypingOptions; // Used to customize the typing inference process + typeAcquisition: TypeAcquisition; // Used to customize the type acquisition process compilerOptions: CompilerOptions; // Used as a source for typing inference + unresolvedImports: ReadonlyArray; // List of unresolved module ids from imports } export enum ModuleKind { @@ -3024,8 +3245,7 @@ namespace ts { AMD = 2, UMD = 3, System = 4, - ES6 = 5, - ES2015 = ES6, + ES2015 = 5, } export const enum JsxEmit { @@ -3058,9 +3278,11 @@ namespace ts { export const enum ScriptTarget { ES3 = 0, ES5 = 1, - ES6 = 2, - ES2015 = ES6, - Latest = ES6, + ES2015 = 2, + ES2016 = 3, + ES2017 = 4, + ESNext = 5, + Latest = ESNext, } export const enum LanguageVariant { @@ -3074,9 +3296,10 @@ namespace ts { Pretty, } + /** Either a parsed command line or a parsed tsconfig.json */ export interface ParsedCommandLine { options: CompilerOptions; - typingOptions?: TypingOptions; + typeAcquisition?: TypeAcquisition; fileNames: string[]; raw?: any; errors: Diagnostic[]; @@ -3279,10 +3502,18 @@ namespace ts { getDirectories?(path: string): string[]; } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ export interface ResolvedModule { + /** Path of the file the module was resolved to. */ resolvedFileName: string; - /* - * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be proper external module: + /** + * Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module: * - be a .d.ts file * - use top level imports\exports * - don't use tripleslash references @@ -3290,8 +3521,29 @@ namespace ts { isExternalLibraryImport?: boolean; } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + */ + export interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ + extension: Extension; + } + + export enum Extension { + Ts, + Tsx, + Dts, + Js, + Jsx, + LastTypeScriptExtension = Dts + } + export interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; + resolvedModule: ResolvedModuleFull | undefined; failedLookupLocations: string[]; } @@ -3343,103 +3595,139 @@ namespace ts { // - Flags used to indicate that a node or subtree contains syntax that requires transformation. TypeScript = 1 << 0, ContainsTypeScript = 1 << 1, - Jsx = 1 << 2, - ContainsJsx = 1 << 3, - ES7 = 1 << 4, - ContainsES7 = 1 << 5, - ES6 = 1 << 6, - ContainsES6 = 1 << 7, - DestructuringAssignment = 1 << 8, - Generator = 1 << 9, - ContainsGenerator = 1 << 10, + ContainsJsx = 1 << 2, + ContainsESNext = 1 << 3, + ContainsES2017 = 1 << 4, + ContainsES2016 = 1 << 5, + ES2015 = 1 << 6, + ContainsES2015 = 1 << 7, + Generator = 1 << 8, + ContainsGenerator = 1 << 9, + DestructuringAssignment = 1 << 10, + ContainsDestructuringAssignment = 1 << 11, // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsDecorators = 1 << 11, - ContainsPropertyInitializer = 1 << 12, - ContainsLexicalThis = 1 << 13, - ContainsCapturedLexicalThis = 1 << 14, - ContainsLexicalThisInComputedPropertyName = 1 << 15, - ContainsDefaultValueAssignments = 1 << 16, - ContainsParameterPropertyAssignments = 1 << 17, - ContainsSpreadElementExpression = 1 << 18, - ContainsComputedPropertyName = 1 << 19, - ContainsBlockScopedBinding = 1 << 20, - ContainsBindingPattern = 1 << 21, - ContainsYield = 1 << 22, - ContainsHoistedDeclarationOrCompletion = 1 << 23, + ContainsDecorators = 1 << 12, + ContainsPropertyInitializer = 1 << 13, + ContainsLexicalThis = 1 << 14, + ContainsCapturedLexicalThis = 1 << 15, + ContainsLexicalThisInComputedPropertyName = 1 << 16, + ContainsDefaultValueAssignments = 1 << 17, + ContainsParameterPropertyAssignments = 1 << 18, + ContainsSpread = 1 << 19, + ContainsObjectSpread = 1 << 20, + ContainsRest = ContainsSpread, + ContainsObjectRest = ContainsObjectSpread, + ContainsComputedPropertyName = 1 << 21, + ContainsBlockScopedBinding = 1 << 22, + ContainsBindingPattern = 1 << 23, + ContainsYield = 1 << 24, + ContainsHoistedDeclarationOrCompletion = 1 << 25, HasComputedFlags = 1 << 29, // Transform flags have been computed. // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. AssertTypeScript = TypeScript | ContainsTypeScript, - AssertJsx = Jsx | ContainsJsx, - AssertES7 = ES7 | ContainsES7, - AssertES6 = ES6 | ContainsES6, + AssertJsx = ContainsJsx, + AssertESNext = ContainsESNext, + AssertES2017 = ContainsES2017, + AssertES2016 = ContainsES2016, + AssertES2015 = ES2015 | ContainsES2015, AssertGenerator = Generator | ContainsGenerator, + AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment, // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment | Generator | HasComputedFlags, - ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, - FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, - ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, - MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, + NodeExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags, + ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, + FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, + ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, + MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName, ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, TypeExcludes = ~ContainsTypeScript, - ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName, - ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadElementExpression, - VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern, - ParameterExcludes = NodeExcludes | ContainsBindingPattern, + ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread, + ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread, + VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest, + ParameterExcludes = NodeExcludes, + CatchClauseExcludes = NodeExcludes | ContainsObjectRest, + BindingPatternExcludes = NodeExcludes | ContainsRest, // Masks // - Additional bitmasks TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators, - ES6FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, + ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, } /* @internal */ export interface EmitNode { - flags?: EmitFlags; - commentRange?: TextRange; - sourceMapRange?: TextRange; - tokenSourceMapRanges?: Map; annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. - constantValue?: number; + flags?: EmitFlags; // Flags that customize emit + commentRange?: TextRange; // The text range to use when emitting leading or trailing comments + sourceMapRange?: TextRange; // The text range to use when emitting leading or trailing source mappings + tokenSourceMapRanges?: Map; // The text range to use when emitting source mappings for tokens + constantValue?: number; // The constant value of an expression + externalHelpersModuleName?: Identifier; // The local name for an imported helpers module + helpers?: EmitHelper[]; // Emit helpers for the node } /* @internal */ export const enum EmitFlags { - EmitEmitHelpers = 1 << 0, // Any emit helpers should be written to this node. - EmitExportStar = 1 << 1, // The export * helper should be written to this node. - EmitSuperHelper = 1 << 2, // Emit the basic _super helper for async methods. - EmitAdvancedSuperHelper = 1 << 3, // Emit the advanced _super helper for async methods. - UMDDefine = 1 << 4, // This node should be replaced with the UMD define helper. - SingleLine = 1 << 5, // The contents of this node should be emitted on a single line. - AdviseOnEmitNode = 1 << 6, // The printer should invoke the onEmitNode callback when printing this node. - NoSubstitution = 1 << 7, // Disables further substitution of an expression. - CapturesThis = 1 << 8, // The function captures a lexical `this` - NoLeadingSourceMap = 1 << 9, // Do not emit a leading source map location for this node. - NoTrailingSourceMap = 1 << 10, // Do not emit a trailing source map location for this node. + SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. + AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node. + NoSubstitution = 1 << 2, // Disables further substitution of an expression. + CapturesThis = 1 << 3, // The function captures a lexical `this` + NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node. + NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node. NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node. - NoNestedSourceMaps = 1 << 11, // Do not emit source map locations for children of this node. - NoTokenLeadingSourceMaps = 1 << 12, // Do not emit leading source map location for token nodes. - NoTokenTrailingSourceMaps = 1 << 13, // Do not emit trailing source map location for token nodes. + NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node. + NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes. + NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes. NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node. - NoLeadingComments = 1 << 14, // Do not emit leading comments for this node. - NoTrailingComments = 1 << 15, // Do not emit trailing comments for this node. + NoLeadingComments = 1 << 9, // Do not emit leading comments for this node. + NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node. NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node. - NoNestedComments = 1 << 16, - ExportName = 1 << 17, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). - LocalName = 1 << 18, // Ensure an export prefix is not added for an identifier that points to an exported declaration. - Indented = 1 << 19, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). - NoIndentation = 1 << 20, // Do not indent the node. - AsyncFunctionBody = 1 << 21, - ReuseTempVariableScope = 1 << 22, // Reuse the existing temp variable scope during emit. - CustomPrologue = 1 << 23, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). + NoNestedComments = 1 << 11, + HelperName = 1 << 12, + ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). + LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration. + Indented = 1 << 15, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). + NoIndentation = 1 << 16, // Do not indent the node. + AsyncFunctionBody = 1 << 17, + ReuseTempVariableScope = 1 << 18, // Reuse the existing temp variable scope during emit. + CustomPrologue = 1 << 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). + NoHoisting = 1 << 20, // Do not hoist this declaration in --module system + HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration + } + + /* @internal */ + export interface EmitHelper { + readonly name: string; // A unique name for this helper. + readonly scoped: boolean; // Indicates whether ther helper MUST be emitted in the current scope. + readonly text: string; // ES3-compatible raw script text. + readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node. + } + + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ + export const enum ExternalEmitHelpers { + Extends = 1 << 0, // __extends (used by the ES2015 class transformation) + Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations) + Rest = 1 << 2, // __rest (used by ESNext object rest transformation) + Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation) + Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation) + Param = 1 << 5, // __param (used by TypeScript decorators transformation) + Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) + Generator = 1 << 7, // __generator (used by ES2015 generator transformation) + + FirstEmitHelper = Extends, + LastEmitHelper = Generator } /* @internal */ @@ -3450,16 +3738,123 @@ namespace ts { Unspecified, // Emitting an otherwise unspecified node } - /** Additional context provided to `visitEachChild` */ /* @internal */ - export interface LexicalEnvironment { + export interface EmitHost extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; + + /* @internal */ + isSourceFileFromExternalLibrary(file: SourceFile): boolean; + + getCommonSourceDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + + isEmitBlocked(emitFileName: string): boolean; + + writeFile: WriteFileCallback; + } + + /* @internal */ + export interface TransformationContext { + getCompilerOptions(): CompilerOptions; + getEmitResolver(): EmitResolver; + getEmitHost(): EmitHost; + /** Starts a new lexical environment. */ startLexicalEnvironment(): void; + /** Suspends the current lexical environment, usually after visiting a parameter list. */ + suspendLexicalEnvironment(): void; + + /** Resumes a suspended lexical environment, usually before visiting a function body. */ + resumeLexicalEnvironment(): void; + /** Ends a lexical environment, returning any declarations. */ endLexicalEnvironment(): Statement[]; + + /** + * Hoists a function declaration to the containing scope. + */ + hoistFunctionDeclaration(node: FunctionDeclaration): void; + + /** + * Hoists a variable declaration to the containing scope. + */ + hoistVariableDeclaration(node: Identifier): void; + + /** + * Records a request for a non-scoped emit helper in the current context. + */ + requestEmitHelper(helper: EmitHelper): void; + + /** + * Gets and resets the requested non-scoped emit helpers. + */ + readEmitHelpers(): EmitHelper[] | undefined; + + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ + enableSubstitution(kind: SyntaxKind): void; + + /** + * Determines whether expression substitutions are enabled for the provided node. + */ + isSubstitutionEnabled(node: Node): boolean; + + /** + * Hook used by transformers to substitute expressions just before they + * are emitted by the pretty printer. + */ + onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node; + + /** + * Enables before/after emit notifications in the pretty printer for the provided + * SyntaxKind. + */ + enableEmitNotification(kind: SyntaxKind): void; + + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ + isEmitNotificationEnabled(node: Node): boolean; + + /** + * Hook used to allow transformers to capture state before or after + * the printer emits a node. + */ + onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; } + /* @internal */ + export interface TransformationResult { + /** + * Gets the transformed source files. + */ + transformed: SourceFile[]; + + /** + * Emits the substitute for a node, if one is available; otherwise, emits the node. + * + * @param emitContext The current emit context. + * @param node The node to substitute. + * @param emitCallback A callback used to emit the node or its substitute. + */ + emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + + /** + * Emits a node with possible notification. + * + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ + emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + } + + /* @internal */ + export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; export interface TextSpan { start: number; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 558015bb0e3..3c64c4d4a34 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -28,21 +28,6 @@ namespace ts { string(): string; } - export interface EmitHost extends ScriptReferenceHost { - getSourceFiles(): SourceFile[]; - - /* @internal */ - isSourceFileFromExternalLibrary(file: SourceFile): boolean; - - getCommonSourceDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - - isEmitBlocked(emitFileName: string): boolean; - - writeFile: WriteFileCallback; - } - // Pool writers to avoid needing to allocate them for every symbol we write. const stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { @@ -58,16 +43,17 @@ namespace ts { writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: () => str += " ", - increaseIndent: () => { }, - decreaseIndent: () => { }, + increaseIndent: noop, + decreaseIndent: noop, clear: () => str = "", - trackSymbol: () => { }, - reportInaccessibleThisError: () => { } + trackSymbol: noop, + reportInaccessibleThisError: noop }; } @@ -83,36 +69,17 @@ namespace ts { return node.end - node.pos; } - export function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean { - if (!array1 || !array2) { - return array1 === array2; - } - - if (array1.length !== array2.length) { - return false; - } - - for (let i = 0; i < array1.length; i++) { - const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { - return false; - } - } - - return true; - } - export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean { return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } - export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule { + export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull { return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined; } - export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void { + export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = createMap(); + sourceFile.resolvedModules = createMap(); } sourceFile.resolvedModules[moduleNameText] = resolvedModule; @@ -127,8 +94,10 @@ namespace ts { } /* @internal */ - export function moduleResolutionIsEqualTo(oldResolution: ResolvedModule, newResolution: ResolvedModule): boolean { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport; + export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; } /* @internal */ @@ -209,7 +178,7 @@ namespace ts { export function nodePosToString(node: Node): string { const file = getSourceFileOfNode(node); const loc = getLineAndCharacterOfPosition(file, node.pos); - return `${ file.fileName }(${ loc.line + 1 },${ loc.character + 1 })`; + return `${file.fileName}(${loc.line + 1},${loc.character + 1})`; } export function getStartPosOfNode(node: Node): number { @@ -271,7 +240,7 @@ namespace ts { return !nodeIsMissing(node); } - export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDocComment?: boolean): number { + export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDoc?: boolean): number { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { @@ -282,8 +251,8 @@ namespace ts { return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { - return getTokenPosOfNode(node.jsDocComments[0]); + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while @@ -291,7 +260,7 @@ namespace ts { // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. if (node.kind === SyntaxKind.SyntaxList && (node)._children.length > 0) { - return getTokenPosOfNode((node)._children[0], sourceFile, includeJsDocComment); + return getTokenPosOfNode((node)._children[0], sourceFile, includeJsDoc); } return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -337,7 +306,7 @@ namespace ts { export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget) { // Any template literal or string literal with an extended escape // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + if (languageVersion < ScriptTarget.ES2015 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { return getQuotedEscapedLiteralText('"', node.text, '"'); } @@ -345,7 +314,7 @@ namespace ts { // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { const text = getSourceTextOfNodeFromSourceFile(sourceFile, node); - if (languageVersion < ScriptTarget.ES6 && isBinaryOrOctalIntegerLiteral(node, text)) { + if (languageVersion < ScriptTarget.ES2015 && isBinaryOrOctalIntegerLiteral(node, text)) { return node.text; } return text; @@ -406,7 +375,12 @@ namespace ts { export function isBlockOrCatchScoped(declaration: Declaration) { return (getCombinedNodeFlags(declaration) & NodeFlags.BlockScoped) !== 0 || - isCatchClauseVariableDeclaration(declaration); + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + + export function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration) { + const node = getRootDeclaration(declaration); + return node.kind === SyntaxKind.VariableDeclaration && node.parent.kind === SyntaxKind.CatchClause; } export function isAmbientModule(node: Node): boolean { @@ -414,6 +388,7 @@ namespace ts { ((node).name.kind === SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node)); } + /** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */ export function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } @@ -449,8 +424,12 @@ namespace ts { return false; } + export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) { + return isExternalModule(node) || compilerOptions.isolatedModules; + } + export function isBlockScope(node: Node, parentNode: Node) { - switch (node.kind) { + switch (node.kind) { case SyntaxKind.SourceFile: case SyntaxKind.CaseBlock: case SyntaxKind.CatchClause: @@ -489,13 +468,6 @@ namespace ts { } } - export function isCatchClauseVariableDeclaration(declaration: Declaration) { - return declaration && - declaration.kind === SyntaxKind.VariableDeclaration && - declaration.parent && - declaration.parent.kind === SyntaxKind.CatchClause; - } - // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. @@ -503,8 +475,39 @@ namespace ts { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } - export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic { + export function getTextOfPropertyName(name: PropertyName): string { + switch (name.kind) { + case SyntaxKind.Identifier: + return (name).text; + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + return (name).text; + case SyntaxKind.ComputedPropertyName: + if (isStringOrNumericLiteral((name).expression)) { + return ((name).expression).text; + } + } + + return undefined; + } + + export function entityNameToString(name: EntityNameOrEntityNameExpression): string { + switch (name.kind) { + case SyntaxKind.Identifier: + return getFullWidth(name) === 0 ? unescapeIdentifier((name).text) : getTextOfNode(name); + case SyntaxKind.QualifiedName: + return entityNameToString((name).left) + "." + entityNameToString((name).right); + case SyntaxKind.PropertyAccessExpression: + return entityNameToString((name).expression) + "." + entityNameToString((name).name); + } + } + + export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic { const sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + + export function createDiagnosticForNodeInSourceFile(sourceFile: SourceFile, node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic { const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } @@ -613,8 +616,9 @@ namespace ts { return n.kind === SyntaxKind.CallExpression && (n).expression.kind === SyntaxKind.SuperKeyword; } - export function isPrologueDirective(node: Node): boolean { - return node.kind === SyntaxKind.ExpressionStatement && (node).expression.kind === SyntaxKind.StringLiteral; + export function isPrologueDirective(node: Node): node is PrologueDirective { + return node.kind === SyntaxKind.ExpressionStatement + && (node).expression.kind === SyntaxKind.StringLiteral; } export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile) { @@ -625,25 +629,18 @@ namespace ts { return getLeadingCommentRanges(text, node.pos); } - export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) { - return getJsDocCommentsFromText(node, sourceFileOfNode.text); - } - - export function getJsDocCommentsFromText(node: Node, text: string) { + export function getJSDocCommentRanges(node: Node, text: string) { const commentRanges = (node.kind === SyntaxKind.Parameter || - node.kind === SyntaxKind.TypeParameter || - node.kind === SyntaxKind.FunctionExpression || - node.kind === SyntaxKind.ArrowFunction) ? + node.kind === SyntaxKind.TypeParameter || + node.kind === SyntaxKind.FunctionExpression || + node.kind === SyntaxKind.ArrowFunction) ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); - return filter(commentRanges, isJsDocComment); - - function isJsDocComment(comment: CommentRange) { - // True if the comment starts with '/**' but not if it is '/**/' - return text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && - text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk && - text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash; - } + // True if the comment starts with '/**' but not if it is '/**/' + return filter(commentRanges, comment => + text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && + text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk && + text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash); } export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; @@ -735,6 +732,20 @@ namespace ts { return false; } + export function isChildOfNodeWithKind(node: Node, kind: SyntaxKind): boolean { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + + export function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression { + return node.kind === SyntaxKind.PrefixUnaryExpression; + } + // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. export function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T { @@ -806,6 +817,23 @@ namespace ts { } } + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + export function getRestParameterElementType(node: TypeNode) { + if (node && node.kind === SyntaxKind.ArrayType) { + return (node).elementType; + } + else if (node && node.kind === SyntaxKind.TypeReference) { + return singleOrUndefined((node).typeArguments); + } + else { + return undefined; + } + } export function isVariableLike(node: Node): node is VariableLikeDeclaration { if (node) { @@ -895,6 +923,12 @@ namespace ts { return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression; } + export function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration { + return node.kind === SyntaxKind.MethodDeclaration && + (node.parent.kind === SyntaxKind.ObjectLiteralExpression || + node.parent.kind === SyntaxKind.ClassExpression); + } + export function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate { return predicate && predicate.kind === TypePredicateKind.Identifier; } @@ -1054,17 +1088,19 @@ namespace ts { } export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression { - if (node) { - switch (node.kind) { - case SyntaxKind.TypeReference: - return (node).typeName; - case SyntaxKind.ExpressionWithTypeArguments: - Debug.assert(isEntityNameExpression((node).expression)); - return (node).expression; - case SyntaxKind.Identifier: - case SyntaxKind.QualifiedName: - return (node); - } + switch (node.kind) { + case SyntaxKind.TypeReference: + case SyntaxKind.JSDocTypeReference: + return (node).typeName; + + case SyntaxKind.ExpressionWithTypeArguments: + return isEntityNameExpression((node).expression) + ? (node).expression + : undefined; + + case SyntaxKind.Identifier: + case SyntaxKind.QualifiedName: + return (node); } return undefined; @@ -1112,8 +1148,8 @@ namespace ts { // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return (node.parent).body !== undefined && (node.parent.kind === SyntaxKind.Constructor - || node.parent.kind === SyntaxKind.MethodDeclaration - || node.parent.kind === SyntaxKind.SetAccessor) + || node.parent.kind === SyntaxKind.MethodDeclaration + || node.parent.kind === SyntaxKind.SetAccessor) && node.parent.parent.kind === SyntaxKind.ClassDeclaration; } @@ -1178,7 +1214,7 @@ namespace ts { case SyntaxKind.PostfixUnaryExpression: case SyntaxKind.BinaryExpression: case SyntaxKind.ConditionalExpression: - case SyntaxKind.SpreadElementExpression: + case SyntaxKind.SpreadElement: case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.OmittedExpression: @@ -1241,6 +1277,7 @@ namespace ts { case SyntaxKind.Decorator: case SyntaxKind.JsxExpression: case SyntaxKind.JsxSpreadAttribute: + case SyntaxKind.SpreadAssignment: return true; case SyntaxKind.ExpressionWithTypeArguments: return (parent).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); @@ -1415,57 +1452,42 @@ namespace ts { (node).parameters[0].type.kind === SyntaxKind.JSDocConstructorType; } - function getJSDocTag(node: Node, kind: SyntaxKind, checkParentVariableStatement: boolean): JSDocTag { - if (!node) { - return undefined; - } - - const jsDocTags = getJSDocTags(node, checkParentVariableStatement); - if (!jsDocTags) { - return undefined; - } - - for (const tag of jsDocTags) { - if (tag.kind === kind) { - return tag; - } - } + export function getCommentsFromJSDoc(node: Node): string[] { + return map(getJSDocs(node), doc => doc.comment); } - function append(previous: T[] | undefined, additional: T[] | undefined): T[] | undefined { - if (additional) { - if (!previous) { - previous = []; - } - for (const x of additional) { - previous.push(x); - } - } - return previous; - } - - export function getJSDocComments(node: Node, checkParentVariableStatement: boolean): string[] { - return getJSDocs(node, checkParentVariableStatement, docs => map(docs, doc => doc.comment), tags => map(tags, tag => tag.comment)); - } - - function getJSDocTags(node: Node, checkParentVariableStatement: boolean): JSDocTag[] { - return getJSDocs(node, checkParentVariableStatement, docs => { + function getJSDocTags(node: Node, kind: SyntaxKind): JSDocTag[] { + const docs = getJSDocs(node); + if (docs) { const result: JSDocTag[] = []; for (const doc of docs) { - if (doc.tags) { - result.push(...doc.tags); + if (doc.kind === SyntaxKind.JSDocParameterTag) { + if (doc.kind === kind) { + result.push(doc as JSDocTag); + } + } + else { + result.push(...filter((doc as JSDoc).tags, tag => tag.kind === kind)); } } return result; - }, tags => tags); + } } - function getJSDocs(node: Node, checkParentVariableStatement: boolean, getDocs: (docs: JSDoc[]) => T[], getTags: (tags: JSDocTag[]) => T[]): T[] { - // TODO: Get rid of getJsDocComments and friends (note the lowercase 's' in Js) - // TODO: A lot of this work should be cached, maybe. I guess it's only used in services right now... - let result: T[] = undefined; - // prepend documentation from parent sources - if (checkParentVariableStatement) { + function getFirstJSDocTag(node: Node, kind: SyntaxKind): JSDocTag { + return node && firstOrUndefined(getJSDocTags(node, kind)); + } + + function getJSDocs(node: Node): (JSDoc | JSDocTag)[] { + let cache: (JSDoc | JSDocTag)[] = node.jsDocCache; + if (!cache) { + getJSDocsWorker(node); + node.jsDocCache = cache; + } + return cache; + + function getJSDocsWorker(node: Node) { + const parent = node.parent; // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** // * @param {number} name @@ -1473,68 +1495,55 @@ namespace ts { // */ // var x = function(name) { return name.length; } const isInitializerOfVariableDeclarationInStatement = - isVariableLike(node.parent) && - (node.parent).initializer === node && - node.parent.parent.parent.kind === SyntaxKind.VariableStatement; + isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === SyntaxKind.VariableStatement; const isVariableOfVariableDeclarationStatement = isVariableLike(node) && - node.parent.parent.kind === SyntaxKind.VariableStatement; - + parent.parent.kind === SyntaxKind.VariableStatement; const variableStatementNode = - isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : - isVariableOfVariableDeclarationStatement ? node.parent.parent : + isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - result = append(result, getJSDocs(variableStatementNode, checkParentVariableStatement, getDocs, getTags)); - } - if (node.kind === SyntaxKind.ModuleDeclaration && - node.parent && node.parent.kind === SyntaxKind.ModuleDeclaration) { - result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(variableStatementNode); } // Also recognize when the node is the RHS of an assignment expression - const parent = node.parent; const isSourceOfAssignmentExpressionStatement = parent && parent.parent && parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && parent.parent.kind === SyntaxKind.ExpressionStatement; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent.parent, checkParentVariableStatement, getDocs, getTags)); + getJSDocsWorker(parent.parent); } + const isModuleDeclaration = node.kind === SyntaxKind.ModuleDeclaration && + parent && parent.kind === SyntaxKind.ModuleDeclaration; const isPropertyAssignmentExpression = parent && parent.kind === SyntaxKind.PropertyAssignment; - if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent, checkParentVariableStatement, getDocs, getTags)); + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocsWorker(parent); } // Pull parameter comments from declaring function as well if (node.kind === SyntaxKind.Parameter) { - const paramTags = getJSDocParameterTag(node as ParameterDeclaration, checkParentVariableStatement); - if (paramTags) { - result = append(result, getTags(paramTags)); - } + cache = concatenate(cache, getJSDocParameterTags(node)); } - } - if (isVariableLike(node) && node.initializer) { - result = append(result, getJSDocs(node.initializer, /*checkParentVariableStatement*/ false, getDocs, getTags)); - } - - if (node.jsDocComments) { - if (result) { - result = append(result, getDocs(node.jsDocComments)); + if (isVariableLike(node) && node.initializer) { + cache = concatenate(cache, node.initializer.jsDoc); } - else { - return getDocs(node.jsDocComments); - } - } - return result; + cache = concatenate(cache, node.jsDoc); + } } - function getJSDocParameterTag(param: ParameterDeclaration, checkParentVariableStatement: boolean): JSDocTag[] { + export function getJSDocParameterTags(param: Node): JSDocParameterTag[] { + if (!isParameter(param)) { + return undefined; + } const func = param.parent as FunctionLikeDeclaration; - const tags = getJSDocTags(func, checkParentVariableStatement); + const tags = getJSDocTags(func, SyntaxKind.JSDocParameterTag) as JSDocParameterTag[]; if (!param.name) { // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification const i = func.parameters.indexOf(param); @@ -1545,10 +1554,7 @@ namespace ts { } else if (param.name.kind === SyntaxKind.Identifier) { const name = (param.name as Identifier).text; - const paramTags = filter(tags, tag => tag.kind === SyntaxKind.JSDocParameterTag && (tag as JSDocParameterTag).parameterName.text === name); - if (paramTags) { - return paramTags; - } + return filter(tags, tag => tag.kind === SyntaxKind.JSDocParameterTag && tag.parameterName.text === name); } else { // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines @@ -1557,39 +1563,28 @@ namespace ts { } } - export function getJSDocTypeTag(node: Node): JSDocTypeTag { - return getJSDocTag(node, SyntaxKind.JSDocTypeTag, /*checkParentVariableStatement*/ false); - } - - export function getJSDocReturnTag(node: Node): JSDocReturnTag { - return getJSDocTag(node, SyntaxKind.JSDocReturnTag, /*checkParentVariableStatement*/ true); - } - - export function getJSDocTemplateTag(node: Node): JSDocTemplateTag { - return getJSDocTag(node, SyntaxKind.JSDocTemplateTag, /*checkParentVariableStatement*/ false); - } - - export function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag { - if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param - // annotation. - const parameterName = (parameter.name).text; - - const jsDocTags = getJSDocTags(parameter.parent, /*checkParentVariableStatement*/ true); - if (!jsDocTags) { - return undefined; - } - for (const tag of jsDocTags) { - if (tag.kind === SyntaxKind.JSDocParameterTag) { - const parameterTag = tag; - if (parameterTag.parameterName.text === parameterName) { - return parameterTag; - } - } + export function getJSDocType(node: Node): JSDocType { + let tag: JSDocTypeTag | JSDocParameterTag = getFirstJSDocTag(node, SyntaxKind.JSDocTypeTag) as JSDocTypeTag; + if (!tag && node.kind === SyntaxKind.Parameter) { + const paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = find(paramTags, tag => !!tag.typeExpression); } } - return undefined; + return tag && tag.typeExpression && tag.typeExpression.type; + } + + export function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag { + return getFirstJSDocTag(node, SyntaxKind.JSDocAugmentsTag) as JSDocAugmentsTag; + } + + export function getJSDocReturnTag(node: Node): JSDocReturnTag { + return getFirstJSDocTag(node, SyntaxKind.JSDocReturnTag) as JSDocReturnTag; + } + + export function getJSDocTemplateTag(node: Node): JSDocTemplateTag { + return getFirstJSDocTag(node, SyntaxKind.JSDocTemplateTag) as JSDocTemplateTag; } export function hasRestParameter(s: SignatureDeclaration): boolean { @@ -1602,14 +1597,11 @@ namespace ts { export function isRestParameter(node: ParameterDeclaration) { if (node && (node.flags & NodeFlags.JavaScriptFile)) { - if (node.type && node.type.kind === SyntaxKind.JSDocVariadicType) { + if (node.type && node.type.kind === SyntaxKind.JSDocVariadicType || + forEach(getJSDocParameterTags(node), + t => t.typeExpression && t.typeExpression.type.kind === SyntaxKind.JSDocVariadicType)) { return true; } - - const paramTag = getCorrespondingJSDocParameterTag(node); - if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === SyntaxKind.JSDocVariadicType; - } } return isDeclaredRestParam(node); } @@ -1618,29 +1610,51 @@ namespace ts { return node && node.dotDotDotToken !== undefined; } + export const enum AssignmentKind { + None, Definite, Compound + } + + export function getAssignmentTargetKind(node: Node): AssignmentKind { + let parent = node.parent; + while (true) { + switch (parent.kind) { + case SyntaxKind.BinaryExpression: + const binaryOperator = (parent).operatorToken.kind; + return isAssignmentOperator(binaryOperator) && (parent).left === node ? + binaryOperator === SyntaxKind.EqualsToken ? AssignmentKind.Definite : AssignmentKind.Compound : + AssignmentKind.None; + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.PostfixUnaryExpression: + const unaryOperator = (parent).operator; + return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? AssignmentKind.Compound : AssignmentKind.None; + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + return (parent).initializer === node ? AssignmentKind.Definite : AssignmentKind.None; + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.SpreadElement: + node = parent; + break; + case SyntaxKind.ShorthandPropertyAssignment: + if ((parent).name !== node) { + return AssignmentKind.None; + } + // Fall through + case SyntaxKind.PropertyAssignment: + node = parent.parent; + break; + default: + return AssignmentKind.None; + } + parent = node.parent; + } + } + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. export function isAssignmentTarget(node: Node): boolean { - while (node.parent.kind === SyntaxKind.ParenthesizedExpression) { - node = node.parent; - } - while (true) { - const parent = node.parent; - if (parent.kind === SyntaxKind.ArrayLiteralExpression || parent.kind === SyntaxKind.SpreadElementExpression) { - node = parent; - continue; - } - if (parent.kind === SyntaxKind.PropertyAssignment || parent.kind === SyntaxKind.ShorthandPropertyAssignment) { - node = parent.parent; - continue; - } - return parent.kind === SyntaxKind.BinaryExpression && - isAssignmentOperator((parent).operatorToken.kind) && - (parent).left === node || - (parent.kind === SyntaxKind.ForInStatement || parent.kind === SyntaxKind.ForOfStatement) && - (parent).initializer === node; - } + return getAssignmentTargetKind(node) !== AssignmentKind.None; } export function isNodeDescendantOf(node: Node, ancestor: Node): boolean { @@ -1836,8 +1850,10 @@ namespace ts { return isFunctionLike(node) && hasModifier(node, ModifierFlags.Async) && !isAccessor(node); } - export function isStringOrNumericLiteral(kind: SyntaxKind): boolean { - return kind === SyntaxKind.StringLiteral || kind === SyntaxKind.NumericLiteral; + export function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral { + const kind = node.kind; + return kind === SyntaxKind.StringLiteral + || kind === SyntaxKind.NumericLiteral; } /** @@ -1853,7 +1869,7 @@ namespace ts { export function isDynamicName(name: DeclarationName): boolean { return name.kind === SyntaxKind.ComputedPropertyName && - !isStringOrNumericLiteral((name).expression.kind) && + !isStringOrNumericLiteral((name).expression) && !isWellKnownSymbolSyntactically((name).expression); } @@ -1866,7 +1882,7 @@ namespace ts { return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } - export function getPropertyNameForPropertyNameNode(name: DeclarationName): string { + export function getPropertyNameForPropertyNameNode(name: DeclarationName | ParameterDeclaration): string { if (name.kind === SyntaxKind.Identifier || name.kind === SyntaxKind.StringLiteral || name.kind === SyntaxKind.NumericLiteral || name.kind === SyntaxKind.Parameter) { return (name).text; } @@ -1895,6 +1911,10 @@ namespace ts { return node.kind === SyntaxKind.Identifier && (node).text === "Symbol"; } + export function isPushOrUnshiftIdentifier(node: Identifier) { + return node.text === "push" || node.text === "unshift"; + } + export function isModifierKind(token: SyntaxKind): boolean { switch (token) { case SyntaxKind.AbstractKeyword: @@ -1943,14 +1963,16 @@ namespace ts { || positionIsSynthesized(node.end); } - export function getOriginalNode(node: Node): Node { + export function getOriginalNode(node: Node): Node; + export function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + export function getOriginalNode(node: Node, nodeTest?: (node: Node) => boolean): Node { if (node) { while (node.original !== undefined) { node = node.original; } } - return node; + return !nodeTest || nodeTest(node) ? node : undefined; } /** @@ -2096,6 +2118,7 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.OmittedExpression: + case SyntaxKind.RawExpression: return 19; case SyntaxKind.TaggedTemplateExpression: @@ -2197,7 +2220,7 @@ namespace ts { case SyntaxKind.YieldExpression: return 2; - case SyntaxKind.SpreadElementExpression: + case SyntaxKind.SpreadElement: return 1; default: @@ -2521,22 +2544,39 @@ namespace ts { if (options.outFile || options.out) { const moduleKind = getEmitModuleKind(options); const moduleEmitEnabled = moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System; - const sourceFiles = host.getSourceFiles(); + const sourceFiles = getAllEmittableSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); } else { - const sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return filter(sourceFiles, isNonDeclarationFile); + const sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile]; + return filterSourceFilesInDirectory(sourceFiles, file => host.isSourceFileFromExternalLibrary(file)); } + + function getAllEmittableSourceFiles() { + return options.noEmitForJsFiles ? filter(host.getSourceFiles(), sourceFile => !isSourceFileJavaScript(sourceFile)) : host.getSourceFiles(); + } + } + + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. */ + export function filterSourceFilesInDirectory(sourceFiles: SourceFile[], isSourceFileFromExternalLibrary: (file: SourceFile) => boolean): SourceFile[] { + return filter(sourceFiles, file => shouldEmitInDirectory(file, isSourceFileFromExternalLibrary)); } function isNonDeclarationFile(sourceFile: SourceFile) { return !isDeclarationFile(sourceFile); } + /** + * Whether a file should be emitted in a non-`--outFile` case. + * Don't emit if source file is a declaration file, or was located under node_modules + */ + function shouldEmitInDirectory(sourceFile: SourceFile, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean): boolean { + return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile); + } + function isBundleEmitNonExternalModule(sourceFile: SourceFile) { - return !isDeclarationFile(sourceFile) && !isExternalModule(sourceFile); + return isNonDeclarationFile(sourceFile) && !isExternalModule(sourceFile); } /** @@ -2556,11 +2596,11 @@ namespace ts { const options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { - onBundledEmit(host, sourceFiles); + onBundledEmit(sourceFiles); } else { for (const sourceFile of sourceFiles) { - // Don't emit if source file is a declaration file, or was located under node_modules + // Don't emit if source file is a declaration file, or was located under node_modules if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { onSingleFileEmit(host, sourceFile); } @@ -2589,7 +2629,7 @@ namespace ts { action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } - function onBundledEmit(host: EmitHost, sourceFiles: SourceFile[]) { + function onBundledEmit(sourceFiles: SourceFile[]) { if (sourceFiles.length) { const jsFilePath = options.outFile || options.out; const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); @@ -2622,10 +2662,9 @@ namespace ts { onBundledEmit(host); } else { - const sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + const sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile]; for (const sourceFile of sourceFiles) { - // Don't emit if source file is a declaration file, or was located under node_modules - if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) { + if (shouldEmitInDirectory(sourceFile, file => host.isSourceFileFromExternalLibrary(file))) { onSingleFileEmit(host, sourceFile); } } @@ -2660,11 +2699,11 @@ namespace ts { function onBundledEmit(host: EmitHost) { // Can emit only sources that are not declaration file and are either non module code or module with // --module or --target es6 specified. Files included by searching under node_modules are also not emitted. - const bundledSources = filter(host.getSourceFiles(), + const bundledSources = filter(getSourceFilesToEmit(host), sourceFile => !isDeclarationFile(sourceFile) && - !host.isSourceFileFromExternalLibrary(sourceFile) && - (!isExternalModule(sourceFile) || - !!getEmitModuleKind(options))); + !host.isSourceFileFromExternalLibrary(sourceFile) && + (!isExternalModule(sourceFile) || + !!getEmitModuleKind(options))); if (bundledSources.length) { const jsFilePath = options.outFile || options.out; const emitFileNames: EmitFileNames = { @@ -2850,7 +2889,7 @@ namespace ts { writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean) { let leadingComments: CommentRange[]; - let currentDetachedCommentInfo: {nodePos: number, detachedCommentEndPos: number}; + let currentDetachedCommentInfo: { nodePos: number, detachedCommentEndPos: number }; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: @@ -3028,7 +3067,7 @@ namespace ts { } } - if (node.flags & NodeFlags.NestedNamespace) { + if (node.flags & NodeFlags.NestedNamespace || (node.kind === SyntaxKind.Identifier && (node).isInJSDocNamespace)) { flags |= ModifierFlags.Export; } @@ -3072,13 +3111,21 @@ namespace ts { } } - export function isDestructuringAssignment(node: Node): node is BinaryExpression { - if (isBinaryExpression(node)) { - if (node.operatorToken.kind === SyntaxKind.EqualsToken) { - const kind = node.left.kind; - return kind === SyntaxKind.ObjectLiteralExpression - || kind === SyntaxKind.ArrayLiteralExpression; - } + export function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression; + export function isAssignmentExpression(node: Node, excludeCompoundAssignment?: false): node is AssignmentExpression; + export function isAssignmentExpression(node: Node, excludeCompoundAssignment?: boolean): node is AssignmentExpression { + return isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === SyntaxKind.EqualsToken + : isAssignmentOperator(node.operatorToken.kind)) + && isLeftHandSideExpression(node.left); + } + + export function isDestructuringAssignment(node: Node): node is DestructuringAssignment { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + const kind = node.left.kind; + return kind === SyntaxKind.ObjectLiteralExpression + || kind === SyntaxKind.ArrayLiteralExpression; } return false; @@ -3173,55 +3220,6 @@ namespace ts { return output; } - /** - * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph - * as the fallback implementation does not check for circular references by default. - */ - export const stringify: (value: any) => string = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - - /** - * Serialize an object graph into a JSON string. - */ - function stringifyFallback(value: any): string { - // JSON.stringify returns `undefined` here, instead of the string "undefined". - return value === undefined ? undefined : stringifyValue(value); - } - - function stringifyValue(value: any): string { - return typeof value === "string" ? `"${escapeString(value)}"` - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : /*fallback*/ "null"; - } - - function cycleCheck(cb: (value: any) => string, value: any) { - Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - const result = cb(value); - delete value.__cycle; - return result; - } - - function stringifyArray(value: any) { - return `[${reduceLeft(value, stringifyElement, "")}]`; - } - - function stringifyElement(memo: string, value: any) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - - function stringifyObject(value: any) { - return `{${reduceOwnProperties(value, stringifyProperty, "")}}`; - } - - function stringifyProperty(memo: string, value: any, key: string) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + `"${escapeString(key)}":${stringifyValue(value)}`; - } - const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** @@ -3464,7 +3462,7 @@ namespace ts { * @param token The token. */ export function createTokenRange(pos: number, token: SyntaxKind): TextRange { - return createRange(pos, pos + tokenToString(token).length); + return createRange(pos, pos + tokenToString(token).length); } export function rangeIsOnSingleLine(range: TextRange, sourceFile: SourceFile) { @@ -3496,64 +3494,20 @@ namespace ts { return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos); } - export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver) { - const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; - const exportSpecifiers = createMap(); - let exportEquals: ExportAssignment = undefined; - let hasExportStarsToExportValues = false; - for (const node of sourceFile.statements) { - switch (node.kind) { - case SyntaxKind.ImportDeclaration: - if (!(node).importClause || - resolver.isReferencedAliasDeclaration((node).importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - - case SyntaxKind.ImportEqualsDeclaration: - if ((node).moduleReference.kind === SyntaxKind.ExternalModuleReference && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - - case SyntaxKind.ExportDeclaration: - if ((node).moduleSpecifier) { - if (!(node).exportClause) { - // export * from "mod" - if (resolver.moduleExportsSomeValue((node).moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (const specifier of (node).exportClause.elements) { - const name = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier); - } - } - break; - - case SyntaxKind.ExportAssignment: - if ((node).isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ + export function isDeclarationNameOfEnumOrNamespace(node: Identifier) { + const parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case SyntaxKind.EnumDeclaration: + case SyntaxKind.ModuleDeclaration: + return parseNode === (parseNode.parent).name; } } - - return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues }; + return false; } export function getInitializedVariables(node: VariableDeclarationList) { @@ -3641,7 +3595,11 @@ namespace ts { return node.kind === SyntaxKind.Identifier; } - export function isGeneratedIdentifier(node: Node): boolean { + export function isVoidExpression(node: Node): node is VoidExpression { + return node.kind === SyntaxKind.VoidExpression; + } + + export function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return isIdentifier(node) && node.autoGenerateKind > GeneratedIdentifierKind.None; } @@ -3724,6 +3682,7 @@ namespace ts { const kind = node.kind; return kind === SyntaxKind.PropertyAssignment || kind === SyntaxKind.ShorthandPropertyAssignment + || kind === SyntaxKind.SpreadAssignment || kind === SyntaxKind.MethodDeclaration || kind === SyntaxKind.GetAccessor || kind === SyntaxKind.SetAccessor @@ -3755,6 +3714,14 @@ namespace ts { // Binding patterns + export function isArrayBindingPattern(node: Node): node is ArrayBindingPattern { + return node.kind === SyntaxKind.ArrayBindingPattern; + } + + export function isObjectBindingPattern(node: Node): node is ObjectBindingPattern { + return node.kind === SyntaxKind.ObjectBindingPattern; + } + export function isBindingPattern(node: Node): node is BindingPattern { if (node) { const kind = node.kind; @@ -3765,6 +3732,12 @@ namespace ts { return false; } + export function isAssignmentPattern(node: Node): node is AssignmentPattern { + const kind = node.kind; + return kind === SyntaxKind.ArrayLiteralExpression + || kind === SyntaxKind.ObjectLiteralExpression; + } + export function isBindingElement(node: Node): node is BindingElement { return node.kind === SyntaxKind.BindingElement; } @@ -3775,8 +3748,65 @@ namespace ts { || kind === SyntaxKind.OmittedExpression; } + + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + export function isDeclarationBindingElement(bindingElement: BindingOrAssignmentElement): bindingElement is VariableDeclaration | ParameterDeclaration | BindingElement { + switch (bindingElement.kind) { + case SyntaxKind.VariableDeclaration: + case SyntaxKind.Parameter: + case SyntaxKind.BindingElement: + return true; + } + + return false; + } + + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + export function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is BindingOrAssignmentPattern { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + export function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ObjectBindingOrAssignmentPattern { + switch (node.kind) { + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ObjectLiteralExpression: + return true; + } + + return false; + } + + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + export function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ArrayBindingOrAssignmentPattern { + switch (node.kind) { + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ArrayLiteralExpression: + return true; + } + + return false; + } + // Expression + export function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression { + return node.kind === SyntaxKind.ArrayLiteralExpression; + } + + export function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression { + return node.kind === SyntaxKind.ObjectLiteralExpression; + } + export function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression { return node.kind === SyntaxKind.PropertyAccessExpression; } @@ -3803,8 +3833,8 @@ namespace ts { || kind === SyntaxKind.NoSubstitutionTemplateLiteral; } - export function isSpreadElementExpression(node: Node): node is SpreadElementExpression { - return node.kind === SyntaxKind.SpreadElementExpression; + export function isSpreadExpression(node: Node): node is SpreadElement { + return node.kind === SyntaxKind.SpreadElement; } export function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments { @@ -3835,7 +3865,8 @@ namespace ts { || kind === SyntaxKind.ThisKeyword || kind === SyntaxKind.TrueKeyword || kind === SyntaxKind.SuperKeyword - || kind === SyntaxKind.NonNullExpression; + || kind === SyntaxKind.NonNullExpression + || kind === SyntaxKind.RawExpression; } export function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression { @@ -3862,9 +3893,10 @@ namespace ts { || kind === SyntaxKind.YieldExpression || kind === SyntaxKind.ArrowFunction || kind === SyntaxKind.BinaryExpression - || kind === SyntaxKind.SpreadElementExpression + || kind === SyntaxKind.SpreadElement || kind === SyntaxKind.AsExpression || kind === SyntaxKind.OmittedExpression + || kind === SyntaxKind.RawExpression || isUnaryExpressionKind(kind); } @@ -4036,7 +4068,9 @@ namespace ts { || kind === SyntaxKind.VariableStatement || kind === SyntaxKind.WhileStatement || kind === SyntaxKind.WithStatement - || kind === SyntaxKind.NotEmittedStatement; + || kind === SyntaxKind.NotEmittedStatement + || kind === SyntaxKind.EndOfDeclarationMarker + || kind === SyntaxKind.MergeDeclarationMarker; } export function isDeclaration(node: Node): node is Declaration { @@ -4161,7 +4195,18 @@ namespace ts { namespace ts { export function getDefaultLibFileName(options: CompilerOptions): string { - return options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case ScriptTarget.ESNext: + case ScriptTarget.ES2017: + return "lib.es2017.d.ts"; + case ScriptTarget.ES2016: + return "lib.es2016.d.ts"; + case ScriptTarget.ES2015: + return "lib.es6.d.ts"; + + default: + return "lib.d.ts"; + } } export function textSpanEnd(span: TextSpan) { @@ -4391,7 +4436,7 @@ namespace ts { } } - export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean { + export function isParameterPropertyDeclaration(node: Node): boolean { return hasModifier(node, ModifierFlags.ParameterPropertyModifier) && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent); } @@ -4448,4 +4493,71 @@ namespace ts { return flags; } + + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ + export function validateLocaleAndSetLanguage( + locale: string, + sys: { getExecutingFilePath(): string, resolvePath(path: string): string, fileExists(fileName: string): boolean, readFile(fileName: string): string }, + errors?: Diagnostic[]) { + const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + + if (!matchResult) { + if (errors) { + errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + + const language = matchResult[1]; + const territory = matchResult[3]; + + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); + } + + function trySetLanguageAndTerritory(language: string, territory: string, errors?: Diagnostic[]): boolean { + const compilerFilePath = normalizePath(sys.getExecutingFilePath()); + const containingDirectoryPath = getDirectoryPath(compilerFilePath); + + let filePath = combinePaths(containingDirectoryPath, language); + + if (territory) { + filePath = filePath + "-" + territory; + } + + filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); + + if (!sys.fileExists(filePath)) { + return false; + } + + // TODO: Add codePage support for readFile? + let fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + + return true; + } + } } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 643c5c91eda..43e01ca56bb 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -99,20 +99,26 @@ namespace ts { return node ? f(initial, node) : initial; } + function reduceNodeArray(nodes: Node[], f: (memo: T, nodes: Node[]) => T, initial: T) { + return nodes ? f(initial, nodes) : initial; + } + /** * Similar to `reduceLeft`, performs a reduction against each child of a node. * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the * `nodeEdgeTraversalMap` above will be visited. * * @param node The node containing the children to reduce. - * @param f The callback function * @param initial The initial value to supply to the reduction. + * @param f The callback function */ - export function reduceEachChild(node: Node, f: (memo: T, node: Node) => T, initial: T): T { + export function reduceEachChild(node: Node, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: Node[]) => T): T { if (node === undefined) { return initial; } + const reduceNodes: (nodes: Node[], f: (memo: T, node: Node | Node[]) => T, initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft; + const cbNodes = cbNodeArray || cbNode; const kind = node.kind; // No need to visit nodes with no children. @@ -138,127 +144,127 @@ namespace ts { // Names case SyntaxKind.ComputedPropertyName: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; // Signature elements case SyntaxKind.Parameter: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; case SyntaxKind.Decorator: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; // Type member case SyntaxKind.PropertyDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; case SyntaxKind.MethodDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.Constructor: - result = reduceLeft((node).modifiers, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.GetAccessor: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.SetAccessor: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).body, cbNode, result); break; // Binding patterns case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: - result = reduceLeft((node).elements, f, result); + result = reduceNodes((node).elements, cbNodes, result); break; case SyntaxKind.BindingElement: - result = reduceNode((node).propertyName, f, result); - result = reduceNode((node).name, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNode((node).propertyName, cbNode, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; // Expression case SyntaxKind.ArrayLiteralExpression: - result = reduceLeft((node).elements, f, result); + result = reduceNodes((node).elements, cbNodes, result); break; case SyntaxKind.ObjectLiteralExpression: - result = reduceLeft((node).properties, f, result); + result = reduceNodes((node).properties, cbNodes, result); break; case SyntaxKind.PropertyAccessExpression: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).name, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).name, cbNode, result); break; case SyntaxKind.ElementAccessExpression: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).argumentExpression, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).argumentExpression, cbNode, result); break; case SyntaxKind.CallExpression: - result = reduceNode((node).expression, f, result); - result = reduceLeft((node).typeArguments, f, result); - result = reduceLeft((node).arguments, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNodes((node).typeArguments, cbNodes, result); + result = reduceNodes((node).arguments, cbNodes, result); break; case SyntaxKind.NewExpression: - result = reduceNode((node).expression, f, result); - result = reduceLeft((node).typeArguments, f, result); - result = reduceLeft((node).arguments, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNodes((node).typeArguments, cbNodes, result); + result = reduceNodes((node).arguments, cbNodes, result); break; case SyntaxKind.TaggedTemplateExpression: - result = reduceNode((node).tag, f, result); - result = reduceNode((node).template, f, result); + result = reduceNode((node).tag, cbNode, result); + result = reduceNode((node).template, cbNode, result); break; case SyntaxKind.FunctionExpression: - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.ArrowFunction: - result = reduceLeft((node).modifiers, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.ParenthesizedExpression: @@ -267,256 +273,260 @@ namespace ts { case SyntaxKind.VoidExpression: case SyntaxKind.AwaitExpression: case SyntaxKind.YieldExpression: - case SyntaxKind.SpreadElementExpression: + case SyntaxKind.SpreadElement: case SyntaxKind.NonNullExpression: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - result = reduceNode((node).operand, f, result); + result = reduceNode((node).operand, cbNode, result); break; case SyntaxKind.BinaryExpression: - result = reduceNode((node).left, f, result); - result = reduceNode((node).right, f, result); + result = reduceNode((node).left, cbNode, result); + result = reduceNode((node).right, cbNode, result); break; case SyntaxKind.ConditionalExpression: - result = reduceNode((node).condition, f, result); - result = reduceNode((node).whenTrue, f, result); - result = reduceNode((node).whenFalse, f, result); + result = reduceNode((node).condition, cbNode, result); + result = reduceNode((node).whenTrue, cbNode, result); + result = reduceNode((node).whenFalse, cbNode, result); break; case SyntaxKind.TemplateExpression: - result = reduceNode((node).head, f, result); - result = reduceLeft((node).templateSpans, f, result); + result = reduceNode((node).head, cbNode, result); + result = reduceNodes((node).templateSpans, cbNodes, result); break; case SyntaxKind.ClassExpression: - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).heritageClauses, f, result); - result = reduceLeft((node).members, f, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).heritageClauses, cbNodes, result); + result = reduceNodes((node).members, cbNodes, result); break; case SyntaxKind.ExpressionWithTypeArguments: - result = reduceNode((node).expression, f, result); - result = reduceLeft((node).typeArguments, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNodes((node).typeArguments, cbNodes, result); break; // Misc case SyntaxKind.TemplateSpan: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).literal, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).literal, cbNode, result); break; // Element case SyntaxKind.Block: - result = reduceLeft((node).statements, f, result); + result = reduceNodes((node).statements, cbNodes, result); break; case SyntaxKind.VariableStatement: - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).declarationList, f, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).declarationList, cbNode, result); break; case SyntaxKind.ExpressionStatement: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.IfStatement: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).thenStatement, f, result); - result = reduceNode((node).elseStatement, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).thenStatement, cbNode, result); + result = reduceNode((node).elseStatement, cbNode, result); break; case SyntaxKind.DoStatement: - result = reduceNode((node).statement, f, result); - result = reduceNode((node).expression, f, result); + result = reduceNode((node).statement, cbNode, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.WhileStatement: case SyntaxKind.WithStatement: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).statement, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).statement, cbNode, result); break; case SyntaxKind.ForStatement: - result = reduceNode((node).initializer, f, result); - result = reduceNode((node).condition, f, result); - result = reduceNode((node).incrementor, f, result); - result = reduceNode((node).statement, f, result); + result = reduceNode((node).initializer, cbNode, result); + result = reduceNode((node).condition, cbNode, result); + result = reduceNode((node).incrementor, cbNode, result); + result = reduceNode((node).statement, cbNode, result); break; case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - result = reduceNode((node).initializer, f, result); - result = reduceNode((node).expression, f, result); - result = reduceNode((node).statement, f, result); + result = reduceNode((node).initializer, cbNode, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).statement, cbNode, result); break; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.SwitchStatement: - result = reduceNode((node).expression, f, result); - result = reduceNode((node).caseBlock, f, result); + result = reduceNode((node).expression, cbNode, result); + result = reduceNode((node).caseBlock, cbNode, result); break; case SyntaxKind.LabeledStatement: - result = reduceNode((node).label, f, result); - result = reduceNode((node).statement, f, result); + result = reduceNode((node).label, cbNode, result); + result = reduceNode((node).statement, cbNode, result); break; case SyntaxKind.TryStatement: - result = reduceNode((node).tryBlock, f, result); - result = reduceNode((node).catchClause, f, result); - result = reduceNode((node).finallyBlock, f, result); + result = reduceNode((node).tryBlock, cbNode, result); + result = reduceNode((node).catchClause, cbNode, result); + result = reduceNode((node).finallyBlock, cbNode, result); break; case SyntaxKind.VariableDeclaration: - result = reduceNode((node).name, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; case SyntaxKind.VariableDeclarationList: - result = reduceLeft((node).declarations, f, result); + result = reduceNodes((node).declarations, cbNodes, result); break; case SyntaxKind.FunctionDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).parameters, f, result); - result = reduceNode((node).type, f, result); - result = reduceNode((node).body, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).parameters, cbNodes, result); + result = reduceNode((node).type, cbNode, result); + result = reduceNode((node).body, cbNode, result); break; case SyntaxKind.ClassDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).name, f, result); - result = reduceLeft((node).typeParameters, f, result); - result = reduceLeft((node).heritageClauses, f, result); - result = reduceLeft((node).members, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNodes((node).typeParameters, cbNodes, result); + result = reduceNodes((node).heritageClauses, cbNodes, result); + result = reduceNodes((node).members, cbNodes, result); break; case SyntaxKind.CaseBlock: - result = reduceLeft((node).clauses, f, result); + result = reduceNodes((node).clauses, cbNodes, result); break; case SyntaxKind.ImportDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).importClause, f, result); - result = reduceNode((node).moduleSpecifier, f, result); + result = reduceNodes((node).decorators, cbNodes, result); + result = reduceNodes((node).modifiers, cbNodes, result); + result = reduceNode((node).importClause, cbNode, result); + result = reduceNode((node).moduleSpecifier, cbNode, result); break; case SyntaxKind.ImportClause: - result = reduceNode((node).name, f, result); - result = reduceNode((node).namedBindings, f, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).namedBindings, cbNode, result); break; case SyntaxKind.NamespaceImport: - result = reduceNode((node).name, f, result); + result = reduceNode((node).name, cbNode, result); break; case SyntaxKind.NamedImports: case SyntaxKind.NamedExports: - result = reduceLeft((node).elements, f, result); + result = reduceNodes((node).elements, cbNodes, result); break; case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - result = reduceNode((node).propertyName, f, result); - result = reduceNode((node).name, f, result); + result = reduceNode((node).propertyName, cbNode, result); + result = reduceNode((node).name, cbNode, result); break; case SyntaxKind.ExportAssignment: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).expression, f, result); + result = reduceLeft((node).decorators, cbNode, result); + result = reduceLeft((node).modifiers, cbNode, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.ExportDeclaration: - result = reduceLeft((node).decorators, f, result); - result = reduceLeft((node).modifiers, f, result); - result = reduceNode((node).exportClause, f, result); - result = reduceNode((node).moduleSpecifier, f, result); + result = reduceLeft((node).decorators, cbNode, result); + result = reduceLeft((node).modifiers, cbNode, result); + result = reduceNode((node).exportClause, cbNode, result); + result = reduceNode((node).moduleSpecifier, cbNode, result); break; // JSX case SyntaxKind.JsxElement: - result = reduceNode((node).openingElement, f, result); - result = reduceLeft((node).children, f, result); - result = reduceNode((node).closingElement, f, result); + result = reduceNode((node).openingElement, cbNode, result); + result = reduceLeft((node).children, cbNode, result); + result = reduceNode((node).closingElement, cbNode, result); break; case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxOpeningElement: - result = reduceNode((node).tagName, f, result); - result = reduceLeft((node).attributes, f, result); + result = reduceNode((node).tagName, cbNode, result); + result = reduceNodes((node).attributes, cbNodes, result); break; case SyntaxKind.JsxClosingElement: - result = reduceNode((node).tagName, f, result); + result = reduceNode((node).tagName, cbNode, result); break; case SyntaxKind.JsxAttribute: - result = reduceNode((node).name, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; case SyntaxKind.JsxSpreadAttribute: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; case SyntaxKind.JsxExpression: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; // Clauses case SyntaxKind.CaseClause: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); // fall-through case SyntaxKind.DefaultClause: - result = reduceLeft((node).statements, f, result); + result = reduceNodes((node).statements, cbNodes, result); break; case SyntaxKind.HeritageClause: - result = reduceLeft((node).types, f, result); + result = reduceNodes((node).types, cbNodes, result); break; case SyntaxKind.CatchClause: - result = reduceNode((node).variableDeclaration, f, result); - result = reduceNode((node).block, f, result); + result = reduceNode((node).variableDeclaration, cbNode, result); + result = reduceNode((node).block, cbNode, result); break; // Property assignments case SyntaxKind.PropertyAssignment: - result = reduceNode((node).name, f, result); - result = reduceNode((node).initializer, f, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).initializer, cbNode, result); break; case SyntaxKind.ShorthandPropertyAssignment: - result = reduceNode((node).name, f, result); - result = reduceNode((node).objectAssignmentInitializer, f, result); + result = reduceNode((node).name, cbNode, result); + result = reduceNode((node).objectAssignmentInitializer, cbNode, result); + break; + + case SyntaxKind.SpreadAssignment: + result = reduceNode((node as SpreadAssignment).expression, cbNode, result); break; // Top-level nodes case SyntaxKind.SourceFile: - result = reduceLeft((node).statements, f, result); + result = reduceNodes((node).statements, cbNodes, result); break; case SyntaxKind.PartiallyEmittedExpression: - result = reduceNode((node).expression, f, result); + result = reduceNode((node).expression, cbNode, result); break; default: @@ -526,8 +536,8 @@ namespace ts { const value = (>node)[edge.name]; if (value !== undefined) { result = isArray(value) - ? reduceLeft(>value, f, result) - : f(result, value); + ? reduceNodes(>value, cbNodes, result) + : cbNode(result, value); } } } @@ -549,10 +559,11 @@ namespace ts { export function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray) => T): T; export function visitNode(node: T, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray) => T, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): T; export function visitNode(node: Node, visitor: (node: Node) => VisitResult, test: (node: Node) => boolean, optional?: boolean, lift?: (node: Node[]) => Node, parenthesize?: (node: Node, parentNode: Node) => Node, parentNode?: Node): Node { - if (node === undefined) { - return undefined; + if (node === undefined || visitor === undefined) { + return node; } + aggregateTransformFlags(node); const visited = visitor(node); if (visited === node) { return node; @@ -621,6 +632,7 @@ namespace ts { // Visit each original node. for (let i = 0; i < count; i++) { const node = nodes[i + start]; + aggregateTransformFlags(node); const visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { @@ -653,6 +665,53 @@ namespace ts { return updated || nodes; } + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ + export function visitLexicalEnvironment(statements: NodeArray, visitor: (node: Node) => VisitResult, context: TransformationContext, start?: number, ensureUseStrict?: boolean) { + context.startLexicalEnvironment(); + statements = visitNodes(statements, visitor, isStatement, start); + if (ensureUseStrict && !startsWithUseStrict(statements)) { + statements = createNodeArray([createStatement(createLiteral("use strict")), ...statements], statements); + } + const declarations = context.endLexicalEnvironment(); + return createNodeArray(concatenate(statements, declarations), statements); + } + + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ + export function visitParameterList(nodes: NodeArray, visitor: (node: Node) => VisitResult, context: TransformationContext) { + context.startLexicalEnvironment(); + const updated = visitNodes(nodes, visitor, isParameterDeclaration); + context.suspendLexicalEnvironment(); + return updated; + } + + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + export function visitFunctionBody(node: FunctionBody, visitor: (node: Node) => VisitResult, context: TransformationContext): FunctionBody; + /** + * Resumes a suspended lexical environment and visits a concise body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ + export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult, context: TransformationContext): ConciseBody; + export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult, context: TransformationContext): ConciseBody { + context.resumeLexicalEnvironment(); + const updated = visitNode(node, visitor, isConciseBody); + const declarations = context.endLexicalEnvironment(); + if (some(declarations)) { + const block = convertToFunctionBody(updated); + const statements = mergeLexicalEnvironment(block.statements, declarations); + return updateBlock(block, statements); + } + return updated; + } + /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -660,8 +719,8 @@ namespace ts { * @param visitor The callback used to visit each child. * @param context A lexical environment context for the visitor. */ - export function visitEachChild(node: T, visitor: (node: Node) => VisitResult, context: LexicalEnvironment): T; - export function visitEachChild(node: Node, visitor: (node: Node) => VisitResult, context: LexicalEnvironment): Node { + export function visitEachChild(node: T, visitor: (node: Node) => VisitResult, context: TransformationContext): T; + export function visitEachChild(node: Node, visitor: (node: Node) => VisitResult, context: TransformationContext): Node { if (node === undefined) { return undefined; } @@ -692,9 +751,10 @@ namespace ts { // Signature elements case SyntaxKind.Parameter: - return updateParameterDeclaration(node, + return updateParameter(node, visitNodes((node).decorators, visitor, isDecorator), visitNodes((node).modifiers, visitor, isModifier), + (node).dotDotDotToken, visitNode((node).name, visitor, isBindingName), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), visitNode((node).initializer, visitor, isExpression, /*optional*/ true)); @@ -714,41 +774,33 @@ namespace ts { visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), visitNodes((node).typeParameters, visitor, isTypeParameter), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), + visitParameterList((node).parameters, visitor, context), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.Constructor: return updateConstructor(node, visitNodes((node).decorators, visitor, isDecorator), visitNodes((node).modifiers, visitor, isModifier), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitParameterList((node).parameters, visitor, context), + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.GetAccessor: return updateGetAccessor(node, visitNodes((node).decorators, visitor, isDecorator), visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), + visitParameterList((node).parameters, visitor, context), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.SetAccessor: return updateSetAccessor(node, visitNodes((node).decorators, visitor, isDecorator), visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitParameterList((node).parameters, visitor, context), + visitFunctionBody((node).body, visitor, context)); // Binding patterns case SyntaxKind.ObjectBindingPattern: @@ -761,6 +813,7 @@ namespace ts { case SyntaxKind.BindingElement: return updateBindingElement(node, + (node).dotDotDotToken, visitNode((node).propertyName, visitor, isPropertyName, /*optional*/ true), visitNode((node).name, visitor, isBindingName), visitNode((node).initializer, visitor, isExpression, /*optional*/ true)); @@ -807,23 +860,20 @@ namespace ts { case SyntaxKind.FunctionExpression: return updateFunctionExpression(node, + visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), visitNodes((node).typeParameters, visitor, isTypeParameter), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), + visitParameterList((node).parameters, visitor, context), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.ArrowFunction: return updateArrowFunction(node, visitNodes((node).modifiers, visitor, isModifier), visitNodes((node).typeParameters, visitor, isTypeParameter), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), + visitParameterList((node).parameters, visitor, context), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isConciseBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.DeleteExpression: return updateDelete(node, @@ -869,9 +919,9 @@ namespace ts { return updateYield(node, visitNode((node).expression, visitor, isExpression)); - case SyntaxKind.SpreadElementExpression: - return updateSpread(node, - visitNode((node).expression, visitor, isExpression)); + case SyntaxKind.SpreadElement: + return updateSpread(node, + visitNode((node).expression, visitor, isExpression)); case SyntaxKind.ClassExpression: return updateClassExpression(node, @@ -994,11 +1044,9 @@ namespace ts { visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), visitNodes((node).typeParameters, visitor, isTypeParameter), - (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), + visitParameterList((node).parameters, visitor, context), visitNode((node).type, visitor, isTypeNode, /*optional*/ true), - mergeFunctionBodyLexicalEnvironment( - visitNode((node).body, visitor, isFunctionBody, /*optional*/ true), - context.endLexicalEnvironment())); + visitFunctionBody((node).body, visitor, context)); case SyntaxKind.ClassDeclaration: return updateClassDeclaration(node, @@ -1124,15 +1172,14 @@ namespace ts { visitNode((node).name, visitor, isIdentifier), visitNode((node).objectAssignmentInitializer, visitor, isExpression)); - // Top-level nodes + case SyntaxKind.SpreadAssignment: + return updateSpreadAssignment(node as SpreadAssignment, + visitNode((node as SpreadAssignment).expression, visitor, isExpression)); + + // Top-level nodes case SyntaxKind.SourceFile: - context.startLexicalEnvironment(); return updateSourceFileNode(node, - createNodeArray( - concatenate( - visitNodes((node).statements, visitor, isStatement), - context.endLexicalEnvironment()), - (node).statements)); + visitLexicalEnvironment((node).statements, visitor, context)); // Transformation nodes case SyntaxKind.PartiallyEmittedExpression: @@ -1166,6 +1213,24 @@ namespace ts { // return node; } + /** + * Merges generated lexical declarations into a new statement list. + */ + export function mergeLexicalEnvironment(statements: NodeArray, declarations: Statement[]): NodeArray; + /** + * Appends generated lexical declarations to an array of statements. + */ + export function mergeLexicalEnvironment(statements: Statement[], declarations: Statement[]): Statement[]; + export function mergeLexicalEnvironment(statements: Statement[], declarations: Statement[]) { + if (!some(declarations)) { + return statements; + } + return isNodeArray(statements) + ? createNodeArray(concatenate(statements, declarations), statements) + : addRange(statements, declarations); + } + + /** * Merges generated lexical declarations into the FunctionBody of a non-arrow function-like declaration. * @@ -1236,13 +1301,25 @@ namespace ts { if (node === undefined) { return TransformFlags.None; } - else if (node.transformFlags & TransformFlags.HasComputedFlags) { + if (node.transformFlags & TransformFlags.HasComputedFlags) { return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); } - else { - const subtreeFlags = aggregateTransformFlagsForSubtree(node); - return computeTransformFlagsForNode(node, subtreeFlags); + const subtreeFlags = aggregateTransformFlagsForSubtree(node); + return computeTransformFlagsForNode(node, subtreeFlags); + } + + function aggregateTransformFlagsForNodeArray(nodes: NodeArray): TransformFlags { + if (nodes === undefined) { + return TransformFlags.None; } + let subtreeFlags = TransformFlags.None; + let nodeArrayFlags = TransformFlags.None; + for (const node of nodes) { + subtreeFlags |= aggregateTransformFlagsForNode(node); + nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags; + } + nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags; + return subtreeFlags; } /** @@ -1256,92 +1333,64 @@ namespace ts { } // Aggregate the transform flags of each child. - return reduceEachChild(node, aggregateTransformFlagsForChildNode, TransformFlags.None); + return reduceEachChild(node, TransformFlags.None, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); } /** * Aggregates the TransformFlags of a child node with the TransformFlags of its * siblings. */ - function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, child: Node): TransformFlags { - return transformFlags | aggregateTransformFlagsForNode(child); + function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, node: Node): TransformFlags { + return transformFlags | aggregateTransformFlagsForNode(node); } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) { - if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) { - return TransformFlags.TypeExcludes; - } - - switch (kind) { - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - case SyntaxKind.ArrayLiteralExpression: - return TransformFlags.ArrayLiteralOrCallOrNewExcludes; - case SyntaxKind.ModuleDeclaration: - return TransformFlags.ModuleExcludes; - case SyntaxKind.Parameter: - return TransformFlags.ParameterExcludes; - case SyntaxKind.ArrowFunction: - return TransformFlags.ArrowFunctionExcludes; - case SyntaxKind.FunctionExpression: - case SyntaxKind.FunctionDeclaration: - return TransformFlags.FunctionExcludes; - case SyntaxKind.VariableDeclarationList: - return TransformFlags.VariableDeclarationListExcludes; - case SyntaxKind.ClassDeclaration: - case SyntaxKind.ClassExpression: - return TransformFlags.ClassExcludes; - case SyntaxKind.Constructor: - return TransformFlags.ConstructorExcludes; - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return TransformFlags.MethodOrAccessorExcludes; - case SyntaxKind.AnyKeyword: - case SyntaxKind.NumberKeyword: - case SyntaxKind.NeverKeyword: - case SyntaxKind.StringKeyword: - case SyntaxKind.BooleanKeyword: - case SyntaxKind.SymbolKeyword: - case SyntaxKind.VoidKeyword: - case SyntaxKind.TypeParameter: - case SyntaxKind.PropertySignature: - case SyntaxKind.MethodSignature: - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.TypeAliasDeclaration: - return TransformFlags.TypeExcludes; - case SyntaxKind.ObjectLiteralExpression: - return TransformFlags.ObjectLiteralExcludes; - default: - return TransformFlags.NodeExcludes; - } + function aggregateTransformFlagsForChildNodes(transformFlags: TransformFlags, nodes: NodeArray): TransformFlags { + return transformFlags | aggregateTransformFlagsForNodeArray(nodes); } export namespace Debug { export const failNotOptional = shouldAssert(AssertionLevel.Normal) ? (message?: string) => assert(false, message || "Node not optional.") - : (message?: string) => {}; + : noop; export const failBadSyntaxKind = shouldAssert(AssertionLevel.Normal) ? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`) - : (node: Node, message?: string) => {}; + : noop; + + export const assertEachNode = shouldAssert(AssertionLevel.Normal) + ? (nodes: Node[], test: (node: Node) => boolean, message?: string) => assert( + test === undefined || every(nodes, test), + message || "Unexpected node.", + () => `Node array did not pass test '${getFunctionName(test)}'.`) + : noop; export const assertNode = shouldAssert(AssertionLevel.Normal) ? (node: Node, test: (node: Node) => boolean, message?: string) => assert( test === undefined || test(node), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`) - : (node: Node, test: (node: Node) => boolean, message?: string) => {}; + : noop; + + export const assertOptionalNode = shouldAssert(AssertionLevel.Normal) + ? (node: Node, test: (node: Node) => boolean, message?: string) => assert( + test === undefined || node === undefined || test(node), + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`) + : noop; + + export const assertOptionalToken = shouldAssert(AssertionLevel.Normal) + ? (node: Node, kind: SyntaxKind, message?: string) => assert( + kind === undefined || node === undefined || node.kind === kind, + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`) + : noop; + + export const assertMissingNode = shouldAssert(AssertionLevel.Normal) + ? (node: Node, message?: string) => assert( + node === undefined, + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`) + : noop; function getFunctionName(func: Function) { if (typeof func !== "function") { @@ -1357,4 +1406,4 @@ namespace ts { } } } -} \ No newline at end of file +} diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index 70c6fdac329..327932f3667 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -170,7 +170,7 @@ class CompilerBaselineRunner extends RunnerBase { }); it("Correct Sourcemap output for " + fileName, () => { - Harness.Compiler.doSourcemapBaseline(justName, options, result); + Harness.Compiler.doSourcemapBaseline(justName, options, result, harnessSettings); }); it("Correct type/symbol baselines for " + fileName, () => { diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index af10f355e1f..2a0d37d190b 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -47,19 +47,6 @@ namespace FourSlash { ranges: Range[]; } - interface MemberListData { - result: { - maybeInaccurate: boolean; - isMemberCompletion: boolean; - entries: { - name: string; - type: string; - kind: string; - kindModifiers: string; - }[]; - }; - } - export interface Marker { fileName: string; position: number; @@ -178,15 +165,9 @@ namespace FourSlash { // Return object may lack some functionalities for other purposes. function createScriptSnapShot(sourceText: string): ts.IScriptSnapshot { return { - getText: (start: number, end: number) => { - return sourceText.substr(start, end - start); - }, - getLength: () => { - return sourceText.length; - }, - getChangeRange: (oldSnapshot: ts.IScriptSnapshot) => { - return undefined; - } + getText: (start: number, end: number) => sourceText.substr(start, end - start), + getLength: () => sourceText.length, + getChangeRange: () => undefined }; } @@ -360,6 +341,7 @@ namespace FourSlash { insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, insertSpaceAfterKeywordsInControlFlowStatements: true, insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, @@ -419,9 +401,8 @@ namespace FourSlash { public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) { const startMarker = this.getMarkerByName(startMarkerName); const endMarker = this.getMarkerByName(endMarkerName); - const predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { - return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; - }; + const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => + ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; const exists = this.anyErrorInRange(predicate, startMarker, endMarker); @@ -458,9 +439,8 @@ namespace FourSlash { private getAllDiagnostics(): ts.Diagnostic[] { const diagnostics: ts.Diagnostic[] = []; - const fileNames = this.languageServiceAdapterHost.getFilenames(); - for (let i = 0, n = fileNames.length; i < n; i++) { - diagnostics.push.apply(this.getDiagnostics(fileNames[i])); + for (const fileName of this.languageServiceAdapterHost.getFilenames()) { + diagnostics.push.apply(this.getDiagnostics(fileName)); } return diagnostics; @@ -471,14 +451,12 @@ namespace FourSlash { let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean; if (after) { - predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { - return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false; - }; + predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => + ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false; } else { - predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { - return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false; - }; + predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => + ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false; } const exists = this.anyErrorInRange(predicate, marker); @@ -501,7 +479,7 @@ namespace FourSlash { endPos = endMarker.position; } - errors.forEach(function(error: ts.Diagnostic) { + errors.forEach(function (error: ts.Diagnostic) { if (predicate(error.start, error.start + error.length, startPos, endPos)) { exists = true; } @@ -518,7 +496,7 @@ namespace FourSlash { Harness.IO.log("Unexpected error(s) found. Error list is:"); } - errors.forEach(function(error: ts.Diagnostic) { + errors.forEach(function (error: ts.Diagnostic) { Harness.IO.log(" minChar: " + error.start + ", limChar: " + (error.start + error.length) + ", message: " + ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()) + "\n"); @@ -602,12 +580,12 @@ namespace FourSlash { this.raiseError(`goToDefinitions failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}`); } - for (let i = 0; i < endMarkers.length; i++) { - const marker = this.getMarkerByName(endMarkers[i]), definition = definitions[i]; + ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => { + const marker = this.getMarkerByName(endMarker); if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) { this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); } - } + }); } public verifyGetEmitOutputForCurrentFile(expected: string): void { @@ -624,29 +602,19 @@ namespace FourSlash { public verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void { const emit = this.languageService.getEmitOutput(this.activeFile.fileName); assert.equal(emit.outputFiles.length, expected.length, "Number of emit output files"); - for (let i = 0; i < emit.outputFiles.length; i++) { - assert.equal(emit.outputFiles[i].name, expected[i].name, "FileName"); - assert.equal(emit.outputFiles[i].text, expected[i].text, "Content"); - } + ts.zipWith(emit.outputFiles, expected, (outputFile, expected) => { + assert.equal(outputFile.name, expected.name, "FileName"); + assert.equal(outputFile.text, expected.text, "Content"); + }); } - public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) { - const members = this.getMemberListAtCaret(); - if (members) { - this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind); - } - else { - this.raiseError("Expected a member list, but none was provided"); - } - } - - public verifyMemberListCount(expectedCount: number, negative: boolean) { + public verifyCompletionListCount(expectedCount: number, negative: boolean) { if (expectedCount === 0 && negative) { - this.verifyMemberListIsEmpty(/*negative*/ false); + this.verifyCompletionListIsEmpty(/*negative*/ false); return; } - const members = this.getMemberListAtCaret(); + const members = this.getCompletionListAtCaret(); if (members) { const match = members.entries.length === expectedCount; @@ -660,13 +628,6 @@ namespace FourSlash { } } - public verifyMemberListDoesNotContain(symbol: string) { - const members = this.getMemberListAtCaret(); - if (members && members.entries.filter(e => e.name === symbol).length !== 0) { - this.raiseError(`Member list did contain ${symbol}`); - } - } - public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) { const completions = this.getCompletionListAtCaret(); const itemsCount = completions.entries.length; @@ -690,9 +651,9 @@ namespace FourSlash { const entries = this.getCompletionListAtCaret().entries; assert.isTrue(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`); - for (let i = 0; i < items.length; i++) { - assert.equal(entries[i].name, items[i], `Unexpected item in completion list`); - } + ts.zipWith(entries, items, (entry, item) => { + assert.equal(entry.name, item, `Unexpected item in completion list`); + }); } public noItemsWithSameNameButDifferentKind(): void { @@ -708,37 +669,14 @@ namespace FourSlash { } } - public verifyMemberListIsEmpty(negative: boolean) { - const members = this.getMemberListAtCaret(); - if ((!members || members.entries.length === 0) && negative) { - this.raiseError("Member list is empty at Caret"); - } - else if ((members && members.entries.length !== 0) && !negative) { - - let errorMsg = "\n" + "Member List contains: [" + members.entries[0].name; - for (let i = 1; i < members.entries.length; i++) { - errorMsg += ", " + members.entries[i].name; - } - errorMsg += "]\n"; - - this.raiseError("Member list is not empty at Caret: " + errorMsg); - - } - } - public verifyCompletionListIsEmpty(negative: boolean) { const completions = this.getCompletionListAtCaret(); if ((!completions || completions.entries.length === 0) && negative) { this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); } else if (completions && completions.entries.length !== 0 && !negative) { - let errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name; - for (let i = 1; i < completions.entries.length; i++) { - errorMsg += ", " + completions.entries[i].name; - } - errorMsg += "]\n"; - - this.raiseError("Completion list is not empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition + errorMsg); + this.raiseError(`Completion list is not empty at caret at position ${this.activeFile.fileName} ${this.currentCaretPosition}\n` + + `Completion List contains: ${stringify(completions.entries.map(e => e.name))}`); } } @@ -912,8 +850,7 @@ namespace FourSlash { } private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) { - for (let i = 0; i < references.length; i++) { - const reference = references[i]; + for (const reference of references) { if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) { this.raiseError(`verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${reference.isWriteAccess}, expected: ${isWriteAccess}.`); @@ -929,10 +866,6 @@ namespace FourSlash { this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${stringify(missingItem)} in the returned list: (${stringify(references)})`); } - private getMemberListAtCaret() { - return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition); - } - private getCompletionListAtCaret() { return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition); } @@ -1030,16 +963,11 @@ namespace FourSlash { ranges = ranges.sort((r1, r2) => r1.start - r2.start); references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start); - for (let i = 0, n = ranges.length; i < n; i++) { - const reference = references[i]; - const range = ranges[i]; - - if (reference.textSpan.start !== range.start || - ts.textSpanEnd(reference.textSpan) !== range.end) { - + ts.zipWith(references, ranges, (reference, range) => { + if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) { this.raiseError("Rename location results do not match.\n\nExpected: " + stringify(ranges) + "\n\nActual:" + JSON.stringify(references)); } - } + }); } else { this.raiseError("Expected rename to succeed, but it actually failed."); @@ -1068,7 +996,7 @@ namespace FourSlash { ts.displayPartsToString(help.suffixDisplayParts), expected); } - public verifyCurrentParameterIsletiable(isVariable: boolean) { + public verifyCurrentParameterIsVariable(isVariable: boolean) { const signature = this.getActiveSignatureHelpItem(); assert.isOk(signature); assert.equal(isVariable, signature.isVariadic); @@ -1095,6 +1023,10 @@ namespace FourSlash { assert.equal(this.getActiveSignatureHelpItem().parameters.length, expectedCount); } + public verifyCurrentSignatureHelpIsVariadic(expected: boolean) { + assert.equal(this.getActiveSignatureHelpItem().isVariadic, expected); + } + public verifyCurrentSignatureHelpDocComment(docComment: string) { const actualDocComment = this.getActiveSignatureHelpItem().documentation; assert.equal(ts.displayPartsToString(actualDocComment), docComment, this.assertionMessageAtLastKnownMarker("current signature help doc comment")); @@ -1179,7 +1111,7 @@ namespace FourSlash { private alignmentForExtraInfo = 50; - private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) { + private spanInfoToString(spanInfo: ts.TextSpan, prefixString: string) { let resultString = "SpanInfo: " + JSON.stringify(spanInfo); if (spanInfo) { const spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); @@ -1230,7 +1162,7 @@ namespace FourSlash { startColumn = 0; length = 0; } - const spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); + const spanInfo = this.spanInfoToString(getSpanAtPos(pos), prefixString); if (previousSpanInfo && previousSpanInfo !== spanInfo) { addSpanInfoString(); previousSpanInfo = spanInfo; @@ -1269,8 +1201,7 @@ namespace FourSlash { const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on const allFourSlashFiles = this.testData.files; - for (let idx = 0; idx < allFourSlashFiles.length; idx++) { - const file = allFourSlashFiles[idx]; + for (const file of allFourSlashFiles) { if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") { // Find a file with the flag emitThisFile turned on emitFiles.push(file); @@ -1295,15 +1226,26 @@ namespace FourSlash { if (emitOutput.emitSkipped) { resultString += "Diagnostics:" + Harness.IO.newLine(); const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); - for (let i = 0, n = diagnostics.length; i < n; i++) { - resultString += " " + diagnostics[0].messageText + Harness.IO.newLine(); + for (const diagnostic of diagnostics) { + if (typeof diagnostic.messageText !== "string") { + let chainedMessage = diagnostic.messageText; + let indentation = " "; + while (chainedMessage) { + resultString += indentation + chainedMessage.messageText + Harness.IO.newLine(); + chainedMessage = chainedMessage.next; + indentation = indentation + " "; + } + } + else { + resultString += " " + diagnostic.messageText + Harness.IO.newLine(); + } } } - emitOutput.outputFiles.forEach((outputFile, idx, array) => { + for (const outputFile of emitOutput.outputFiles) { const fileName = "FileName : " + outputFile.name + Harness.IO.newLine(); resultString = resultString + fileName + outputFile.text; - }); + } resultString += Harness.IO.newLine(); }); @@ -1328,7 +1270,7 @@ namespace FourSlash { } public printBreakpointLocation(pos: number) { - Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(pos, this.getBreakpointStatementLocation(pos), " ")); + Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(this.getBreakpointStatementLocation(pos), " ")); } public printBreakpointAtCurrentLocation() { @@ -1362,8 +1304,7 @@ namespace FourSlash { } public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) { - for (let i = 0; i < this.testData.files.length; i++) { - const file = this.testData.files[i]; + for (const file of this.testData.files) { const active = (this.activeFile === file); Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`); let content = this.getFileContent(file.fileName); @@ -1382,11 +1323,6 @@ namespace FourSlash { Harness.IO.log(stringify(sigHelp)); } - public printMemberListMembers() { - const members = this.getMemberListAtCaret(); - this.printMembersOrCompletions(members); - } - public printCompletionListMembers() { const completions = this.getCompletionListAtCaret(); this.printMembersOrCompletions(completions); @@ -1598,10 +1534,10 @@ namespace FourSlash { edits = edits.sort((a, b) => a.span.start - b.span.start); // Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters const oldContent = this.getFileContent(this.activeFile.fileName); - for (let j = 0; j < edits.length; j++) { - this.languageServiceAdapterHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); - this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); - const change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; + for (const edit of edits) { + this.languageServiceAdapterHost.editScript(fileName, edit.span.start + runningOffset, ts.textSpanEnd(edit.span) + runningOffset, edit.newText); + this.updateMarkersForEdit(fileName, edit.span.start + runningOffset, ts.textSpanEnd(edit.span) + runningOffset, edit.newText); + const change = (edit.span.start - ts.textSpanEnd(edit.span)) + edit.newText.length; runningOffset += change; // TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150) // this.languageService.getScriptLexicalStructure(fileName); @@ -1830,7 +1766,7 @@ namespace FourSlash { return result; } - private rangeText({fileName, start, end}: Range, more = false): string { + private rangeText({fileName, start, end}: Range): string { return this.getFileContent(fileName).slice(start, end); } @@ -1925,7 +1861,7 @@ namespace FourSlash { } public printNameOrDottedNameSpans(pos: number) { - Harness.IO.log(this.spanInfoToString(pos, this.getNameOrDottedNameSpan(pos), "**")); + Harness.IO.log(this.spanInfoToString(this.getNameOrDottedNameSpan(pos), "**")); } private verifyClassifications(expected: { classificationType: string; text: string; textSpan?: TextSpan }[], actual: ts.ClassifiedSpan[]) { @@ -1935,10 +1871,7 @@ namespace FourSlash { jsonMismatchString()); } - for (let i = 0; i < expected.length; i++) { - const expectedClassification = expected[i]; - const actualClassification = actual[i]; - + ts.zipWith(expected, actual, (expectedClassification, actualClassification) => { const expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; if (expectedType !== actualClassification.classificationType) { this.raiseError("verifyClassifications failed - expected classifications type to be " + @@ -1968,7 +1901,7 @@ namespace FourSlash { actualText + jsonMismatchString()); } - } + }); function jsonMismatchString() { return Harness.IO.newLine() + @@ -2013,13 +1946,11 @@ namespace FourSlash { this.raiseError(`verifyOutliningSpans failed - expected total spans to be ${spans.length}, but was ${actual.length}`); } - for (let i = 0; i < spans.length; i++) { - const expectedSpan = spans[i]; - const actualSpan = actual[i]; + ts.zipWith(spans, actual, (expectedSpan, actualSpan, i) => { if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) { this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualSpan.textSpan.start},${ts.textSpanEnd(actualSpan.textSpan)})`); } - } + }); } public verifyTodoComments(descriptors: string[], spans: TextSpan[]) { @@ -2030,15 +1961,13 @@ namespace FourSlash { this.raiseError(`verifyTodoComments failed - expected total spans to be ${spans.length}, but was ${actual.length}`); } - for (let i = 0; i < spans.length; i++) { - const expectedSpan = spans[i]; - const actualComment = actual[i]; + ts.zipWith(spans, actual, (expectedSpan, actualComment, i) => { const actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) { this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualCommentSpan.start},${ts.textSpanEnd(actualCommentSpan)})`); } - } + }); } private getCodeFixes(errorCode?: number) { @@ -2049,13 +1978,13 @@ namespace FourSlash { this.raiseError("Errors expected."); } - if (diagnostics.length > 1 && errorCode !== undefined) { + if (diagnostics.length > 1 && errorCode === undefined) { this.raiseError("When there's more than one error, you must specify the errror to fix."); } const diagnostic = !errorCode ? diagnostics[0] : ts.find(diagnostics, d => d.code == errorCode); - return this.languageService.getCodeFixesAtPosition(fileName, diagnostic.start, diagnostic.length, [diagnostic.code]); + return this.languageService.getCodeFixesAtPosition(fileName, diagnostic.start, diagnostic.start + diagnostic.length, [diagnostic.code]); } public verifyCodeFixAtPosition(expectedText: string, errorCode?: number) { @@ -2082,6 +2011,34 @@ namespace FourSlash { } } + public verifyImportFixAtPosition(expectedTextArray: string[], errorCode?: number) { + const ranges = this.getRanges(); + if (ranges.length == 0) { + this.raiseError("At least one range should be specified in the testfile."); + } + + const codeFixes = this.getCodeFixes(errorCode); + + if (!codeFixes || codeFixes.length == 0) { + this.raiseError("No codefixes returned."); + } + + const actualTextArray: string[] = []; + const scriptInfo = this.languageServiceAdapterHost.getScriptInfo(codeFixes[0].changes[0].fileName); + const originalContent = scriptInfo.content; + for (const codeFix of codeFixes) { + this.applyEdits(codeFix.changes[0].fileName, codeFix.changes[0].textChanges, /*isFormattingEdit*/ false); + actualTextArray.push(this.normalizeNewlines(this.rangeText(ranges[0]))); + scriptInfo.updateContent(originalContent); + } + const sortedExpectedArray = ts.map(expectedTextArray, str => this.normalizeNewlines(str)).sort(); + const sortedActualArray = actualTextArray.sort(); + if (!ts.arrayIsEqualTo(sortedExpectedArray, sortedActualArray)) { + this.raiseError( + `Actual text array doesn't match expected text array. \nActual: \n"${sortedActualArray.join("\n\n")}"\n---\nExpected: \n'${sortedExpectedArray.join("\n\n")}'`); + } + } + public verifyDocCommentTemplate(expected?: ts.TextInsertion) { const name = "verifyDocCommentTemplate"; const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition); @@ -2115,6 +2072,10 @@ namespace FourSlash { }); } + private normalizeNewlines(str: string) { + return str.replace(/\r?\n/g, "\n"); + } + public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) { const openBraceMap = ts.createMap({ @@ -2185,11 +2146,9 @@ namespace FourSlash { public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string, fileName?: string) { const items = this.languageService.getNavigateToItems(searchValue, /*maxResultCount*/ undefined, fileName); let actual = 0; - let item: ts.NavigateToItem; // Count only the match that match the same MatchKind - for (let i = 0; i < items.length; i++) { - item = items[i]; + for (const item of items) { if (!matchKind || item.matchKind === matchKind) { actual++; } @@ -2217,8 +2176,7 @@ namespace FourSlash { this.raiseError("verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one."); } - for (let i = 0; i < items.length; i++) { - const item = items[i]; + for (const item of items) { if (item && item.name === name && item.kind === kind && (matchKind === undefined || item.matchKind === matchKind) && (fileName === undefined || item.fileName === fileName) && @@ -2269,24 +2227,16 @@ namespace FourSlash { public printNavigationItems(searchValue: string) { const items = this.languageService.getNavigateToItems(searchValue); - const length = items && items.length; - - Harness.IO.log(`NavigationItems list (${length} items)`); - - for (let i = 0; i < length; i++) { - const item = items[i]; + Harness.IO.log(`NavigationItems list (${items.length} items)`); + for (const item of items) { Harness.IO.log(`name: ${item.name}, kind: ${item.kind}, parentName: ${item.containerName}, fileName: ${item.fileName}`); } } public printNavigationBar() { const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - const length = items && items.length; - - Harness.IO.log(`Navigation bar (${length} items)`); - - for (let i = 0; i < length; i++) { - const item = items[i]; + Harness.IO.log(`Navigation bar (${items.length} items)`); + for (const item of items) { Harness.IO.log(`${repeatString(item.indent, " ")}name: ${item.text}, kind: ${item.kind}, childItems: ${item.childItems.map(child => child.text)}`); } } @@ -2407,8 +2357,7 @@ namespace FourSlash { } private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) { - for (let i = 0; i < items.length; i++) { - const item = items[i]; + for (const item of items) { if (item.name === name) { if (documentation != undefined || text !== undefined) { const details = this.getCompletionEntryDetails(item.name); @@ -2457,20 +2406,17 @@ namespace FourSlash { name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; const availableNames: string[] = []; - let foundIt = false; - for (let i = 0; i < this.testData.files.length; i++) { - const fn = this.testData.files[i].fileName; + result = ts.forEach(this.testData.files, file => { + const fn = file.fileName; if (fn) { if (fn === name) { - result = this.testData.files[i]; - foundIt = true; - break; + return file; } availableNames.push(fn); } - } + }); - if (!foundIt) { + if (!result) { throw new Error(`No test file named "${name}" exists. Available file names are: ${availableNames.join(", ")}`); } } @@ -2571,8 +2517,8 @@ ${code} function chompLeadingSpace(content: string) { const lines = content.split("\n"); - for (let i = 0; i < lines.length; i++) { - if ((lines[i].length !== 0) && (lines[i].charAt(0) !== " ")) { + for (const line of lines) { + if ((line.length !== 0) && (line.charAt(0) !== " ")) { return content; } } @@ -2610,8 +2556,7 @@ ${code} currentFileName = fileName; } - for (let i = 0; i < lines.length; i++) { - let line = lines[i]; + for (let line of lines) { const lineLength = line.length; if (lineLength > 0 && line.charAt(lineLength - 1) === "\r") { @@ -2658,7 +2603,7 @@ ${code} resetLocalData(); } - currentFileName = basePath + "/" + value; + currentFileName = ts.isRootedDiskPath(value) ? value : basePath + "/" + value; currentFileOptions[key] = value; } else { @@ -3081,19 +3026,8 @@ namespace FourSlashInterface { } } - // Verifies the member list contains the specified symbol. The - // member list is brought up if necessary - public memberListContains(symbol: string, text?: string, documentation?: string, kind?: string) { - if (this.negative) { - this.state.verifyMemberListDoesNotContain(symbol); - } - else { - this.state.verifyMemberListContains(symbol, text, documentation, kind); - } - } - - public memberListCount(expectedCount: number) { - this.state.verifyMemberListCount(expectedCount, this.negative); + public completionListCount(expectedCount: number) { + this.state.verifyCompletionListCount(expectedCount, this.negative); } // Verifies the completion list contains the specified symbol. The @@ -3129,10 +3063,6 @@ namespace FourSlashInterface { this.state.verifyCompletionListAllowsNewIdentifier(this.negative); } - public memberListIsEmpty() { - this.state.verifyMemberListIsEmpty(this.negative); - } - public signatureHelpPresent() { this.state.verifySignatureHelpPresent(!this.negative); } @@ -3287,6 +3217,10 @@ namespace FourSlashInterface { this.state.verifySignatureHelpCount(expected); } + public signatureHelpCurrentArgumentListIsVariadic(expected: boolean) { + this.state.verifyCurrentSignatureHelpIsVariadic(expected); + } + public signatureHelpArgumentCountIs(expected: number) { this.state.verifySignatureHelpArgumentCount(expected); } @@ -3351,6 +3285,10 @@ namespace FourSlashInterface { this.state.verifyCodeFixAtPosition(expectedText, errorCode); } + public importFixAtPosition(expectedTextArray: string[], errorCode?: number): void { + this.state.verifyImportFixAtPosition(expectedTextArray, errorCode); + } + public navigationBar(json: any) { this.state.verifyNavigationBar(json); } @@ -3526,10 +3464,6 @@ namespace FourSlashInterface { this.state.printCurrentSignatureHelp(); } - public printMemberListMembers() { - this.state.printMemberListMembers(); - } - public printCompletionListMembers() { this.state.printCompletionListMembers(); } @@ -3590,11 +3524,8 @@ namespace FourSlashInterface { this.state.formatOnType(this.state.getMarkerByName(posMarker).position, key); } - public setOption(name: string, value: number): void; - public setOption(name: string, value: string): void; - public setOption(name: string, value: boolean): void; - public setOption(name: string, value: any): void { - (this.state.formatCodeSettings)[name] = value; + public setOption(name: keyof ts.FormatCodeSettings, value: number | string | boolean): void { + this.state.formatCodeSettings[name] = value; } } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 7c82aeece78..26a4a6f963d 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -220,9 +220,7 @@ namespace Utils { } export function sourceFileToJSON(file: ts.Node): string { - return JSON.stringify(file, (k, v) => { - return isNodeOrArray(v) ? serializeNode(v) : v; - }, " "); + return JSON.stringify(file, (_, v) => isNodeOrArray(v) ? serializeNode(v) : v, " "); function getKindName(k: number | string): string { if (typeof k === "string") { @@ -472,19 +470,6 @@ namespace Utils { } } -namespace Harness.Path { - export function getFileName(fullPath: string) { - return fullPath.replace(/^.*[\\\/]/, ""); - } - - export function filePath(fullPath: string) { - fullPath = ts.normalizeSlashes(fullPath); - const components = fullPath.split("/"); - const path: string[] = components.slice(0, components.length - 1); - return path.join("/") + "/"; - } -} - namespace Harness { export interface IO { newLine(): string; @@ -692,7 +677,7 @@ namespace Harness { export const getCurrentDirectory = () => ""; export const args = () => []; export const getExecutingFilePath = () => ""; - export const exit = (exitCode: number) => { }; + export const exit = ts.noop; export const getDirectories = () => []; export let log = (s: string) => console.log(s); @@ -742,7 +727,7 @@ namespace Harness { } } - export function createDirectory(path: string) { + export function createDirectory() { // Do nothing (?) } @@ -750,7 +735,7 @@ namespace Harness { Http.writeToServerSync(serverRoot + path, "DELETE"); } - export function directoryExists(path: string): boolean { + export function directoryExists(): boolean { return false; } @@ -792,7 +777,7 @@ namespace Harness { return response.status === 200; } - export function _listFilesImpl(path: string, spec?: RegExp, options?: any) { + export let listFiles = Utils.memoize((path: string, spec?: RegExp): string[] => { const response = Http.getFileFromServerSync(serverRoot + path); if (response.status === 200) { const results = response.responseText.split(","); @@ -806,8 +791,7 @@ namespace Harness { else { return [""]; } - }; - export let listFiles = Utils.memoize(_listFilesImpl); + }); export function readFile(file: string) { const response = Http.getFileFromServerSync(serverRoot + file); @@ -941,7 +925,17 @@ namespace Harness { } export function getDefaultLibFileName(options: ts.CompilerOptions): string { - return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName; + switch (options.target) { + case ts.ScriptTarget.ES2017: + return "lib.es2017.d.ts"; + case ts.ScriptTarget.ES2016: + return "lib.es2016.d.ts"; + case ts.ScriptTarget.ES2015: + return es2015DefaultLibFileName; + + default: + return defaultLibFileName; + } } // Cache these between executions so we don't have to re-parse them for every test @@ -964,28 +958,38 @@ namespace Harness { // Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames const getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - const realPathMap: ts.FileMap = ts.createFileMap(); - const fileMap: ts.FileMap<() => ts.SourceFile> = ts.createFileMap<() => ts.SourceFile>(); + /** Maps a symlink name to a realpath. Used only for exposing `realpath`. */ + const realPathMap = ts.createFileMap(); + /** + * Maps a file name to a source file. + * This will have a different SourceFile for every symlink pointing to that file; + * if the program resolves realpaths then symlink entries will be ignored. + */ + const fileMap = ts.createFileMap(); for (const file of inputFiles) { if (file.content !== undefined) { const fileName = ts.normalizePath(file.unitName); const path = ts.toPath(file.unitName, currentDirectory, getCanonicalFileName); if (file.fileOptions && file.fileOptions["symlink"]) { - const link = file.fileOptions["symlink"]; - const linkPath = ts.toPath(link, currentDirectory, getCanonicalFileName); - realPathMap.set(linkPath, fileName); - fileMap.set(path, (): ts.SourceFile => { throw new Error("Symlinks should always be resolved to a realpath first"); }); + const links = file.fileOptions["symlink"].split(","); + for (const link of links) { + const linkPath = ts.toPath(link, currentDirectory, getCanonicalFileName); + realPathMap.set(linkPath, fileName); + // Create a different SourceFile for every symlink. + const sourceFile = createSourceFileAndAssertInvariants(linkPath, file.content, scriptTarget); + fileMap.set(linkPath, sourceFile); + } } const sourceFile = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget); - fileMap.set(path, () => sourceFile); + fileMap.set(path, sourceFile); } } - function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) { + function getSourceFile(fileName: string) { fileName = ts.normalizePath(fileName); - const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - if (fileMap.contains(path)) { - return fileMap.get(path)(); + const fromFileMap = fileMap.get(toPath(fileName)); + if (fromFileMap) { + return fromFileMap; } else if (fileName === fourslashFileName) { const tsFn = "tests/cases/fourslash/" + fourslashFileName; @@ -1004,6 +1008,9 @@ namespace Harness { newLineKind === ts.NewLineKind.LineFeed ? lineFeed : Harness.IO.newLine(); + function toPath(fileName: string): ts.Path { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } return { getCurrentDirectory: () => currentDirectory, @@ -1013,35 +1020,31 @@ namespace Harness { getCanonicalFileName, useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, getNewLine: () => newLine, - fileExists: fileName => { - const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - return fileMap.contains(path) || (realPathMap && realPathMap.contains(path)); - }, + fileExists: fileName => fileMap.contains(toPath(fileName)), readFile: (fileName: string): string => { - return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName))().getText(); + const file = fileMap.get(toPath(fileName)); + if (ts.endsWith(fileName, "json")) { + // strip comments + return file.getText(); + } + return file.text; + }, + realpath: (fileName: string): ts.Path => { + const path = toPath(fileName); + return (realPathMap.get(path) as ts.Path) || path; }, - realpath: realPathMap && ((f: string) => { - const path = ts.toPath(f, currentDirectory, getCanonicalFileName); - return realPathMap.contains(path) ? realPathMap.get(path) : path; - }), directoryExists: dir => { let path = ts.toPath(dir, currentDirectory, getCanonicalFileName); // Strip trailing /, which may exist if the path is a drive root if (path[path.length - 1] === "/") { path = path.substr(0, path.length - 1); } - let exists = false; - fileMap.forEachValue(key => { - if (key.indexOf(path) === 0 && key[path.length] === "/") { - exists = true; - } - }); - return exists; + return mapHasFileInDirectory(path, fileMap); }, getDirectories: d => { const path = ts.toPath(d, currentDirectory, getCanonicalFileName); const result: string[] = []; - fileMap.forEachValue((key, value) => { + fileMap.forEachValue(key => { if (key.indexOf(path) === 0 && key.lastIndexOf("/") > path.length) { let dirName = key.substr(path.length, key.indexOf("/", path.length + 1) - path.length); if (dirName[0] === "/") { @@ -1057,6 +1060,19 @@ namespace Harness { }; } + function mapHasFileInDirectory(directoryPath: ts.Path, map: ts.FileMap): boolean { + if (!map) { + return false; + } + let exists = false; + map.forEachValue(fileName => { + if (!exists && ts.startsWith(fileName, directoryPath) && fileName[directoryPath.length] === "/") { + exists = true; + } + }); + return exists; + } + interface HarnessOptions { useCaseSensitiveFileNames?: boolean; includeBuiltFile?: string; @@ -1076,7 +1092,9 @@ namespace Harness { { name: "suppressOutputPathCheck", type: "boolean" }, { name: "noImplicitReferences", type: "boolean" }, { name: "currentDirectory", type: "string" }, - { name: "symlink", type: "string" } + { name: "symlink", type: "string" }, + // Emitted js baseline will print full paths for every output file + { name: "fullEmitPaths", type: "boolean" } ]; let optionsIndex: ts.Map; @@ -1101,22 +1119,7 @@ namespace Harness { const option = getCommandLineOption(name); if (option) { const errors: ts.Diagnostic[] = []; - switch (option.type) { - case "boolean": - options[option.name] = value.toLowerCase() === "true"; - break; - case "string": - options[option.name] = value; - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - case "list": - options[option.name] = ts.parseListTypeOption(option, value, errors); - break; - default: - options[option.name] = ts.parseCustomTypeOption(option, value, errors); - break; - } - + options[option.name] = optionValue(option, value, errors); if (errors.length > 0) { throw new Error(`Unknown value '${value}' for compiler option '${name}'.`); } @@ -1128,6 +1131,27 @@ namespace Harness { } } + function optionValue(option: ts.CommandLineOption, value: string, errors: ts.Diagnostic[]): any { + switch (option.type) { + case "boolean": + return value.toLowerCase() === "true"; + case "string": + return value; + case "number": { + const number = parseInt(value, 10); + if (isNaN(number)) { + throw new Error(`Value must be a number, got: ${JSON.stringify(value)}`); + } + return number; + } + // If not a primitive, the possible types are specified in what is effectively a map of options. + case "list": + return ts.parseListTypeOption(option, value, errors); + default: + return ts.parseCustomTypeOption(option, value, errors); + } + } + export interface TestFile { unitName: string; content: string; @@ -1231,7 +1255,7 @@ namespace Harness { if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) { ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles)); ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles)); - const output = compileFiles(declInputFiles, declOtherFiles, harnessSettings, options, currentDirectory); + const output = compileFiles(declInputFiles, declOtherFiles, harnessSettings, options, currentDirectory || harnessSettings["currentDirectory"]); return { declInputFiles, declOtherFiles, declResult: output.result }; } @@ -1463,7 +1487,7 @@ namespace Harness { } if (typesError && symbolsError) { - throw new Error(typesError.message + ts.sys.newLine + symbolsError.message); + throw new Error(typesError.message + Harness.IO.newLine() + symbolsError.message); } if (typesError) { @@ -1545,7 +1569,7 @@ namespace Harness { return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : ""; } - export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult) { + export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult, harnessSettings: Harness.TestCaseParser.CompilerSettings) { if (options.inlineSourceMap) { if (result.sourceMaps.length > 0) { throw new Error("No sourcemap files should be generated if inlineSourceMaps was set."); @@ -1567,10 +1591,8 @@ namespace Harness { } let sourceMapCode = ""; - for (let i = 0; i < result.sourceMaps.length; i++) { - sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n"; - sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]); - sourceMapCode += result.sourceMaps[i].code; + for (const sourceMap of result.sourceMaps) { + sourceMapCode += fileOutput(sourceMap, harnessSettings); } return sourceMapCode; @@ -1591,23 +1613,19 @@ namespace Harness { tsCode += "//// [" + header + "] ////\r\n\r\n"; } for (let i = 0; i < tsSources.length; i++) { - tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n"; + tsCode += "//// [" + ts.getBaseFileName(tsSources[i].unitName) + "]\r\n"; tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : ""); } let jsCode = ""; - for (let i = 0; i < result.files.length; i++) { - jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n"; - jsCode += getByteOrderMarkText(result.files[i]); - jsCode += result.files[i].code; + for (const file of result.files) { + jsCode += fileOutput(file, harnessSettings); } if (result.declFilesCode.length > 0) { jsCode += "\r\n\r\n"; - for (let i = 0; i < result.declFilesCode.length; i++) { - jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n"; - jsCode += getByteOrderMarkText(result.declFilesCode[i]); - jsCode += result.declFilesCode[i].code; + for (const declFile of result.declFilesCode) { + jsCode += fileOutput(declFile, harnessSettings); } } @@ -1632,9 +1650,14 @@ namespace Harness { }); } + function fileOutput(file: GeneratedFile, harnessSettings: Harness.TestCaseParser.CompilerSettings): string { + const fileName = harnessSettings["fullEmitPaths"] ? file.fileName : ts.getBaseFileName(file.fileName); + return "//// [" + fileName + "]\r\n" + getByteOrderMarkText(file) + file.code; + } + export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string { // Collect, test, and sort the fileNames - outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName))); + outputFiles.sort((a, b) => ts.compareStrings(cleanName(a.fileName), cleanName(b.fileName))); // Emit them let result = ""; @@ -1659,9 +1682,9 @@ namespace Harness { } // This does not need to exist strictly speaking, but many tests will need to be updated if it's removed - export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) { + export function compileString(_code: string, _unitName: string, _callback: (result: CompilerResult) => void) { // NEWTODO: Re-implement 'compileString' - throw new Error("compileString NYI"); + return ts.notImplemented(); } export interface GeneratedFile { @@ -1748,7 +1771,7 @@ namespace Harness { } // Regex for parsing options in the format "@Alpha: Value of any sort" - const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines + const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines function extractCompilerSettings(content: string): CompilerSettings { const opts: CompilerSettings = {}; @@ -1757,7 +1780,7 @@ namespace Harness { /* tslint:disable:no-null-keyword */ while ((match = optionRegex.exec(content)) !== null) { /* tslint:enable:no-null-keyword */ - opts[match[1]] = match[2]; + opts[match[1]] = match[2].trim(); } return opts; @@ -1785,7 +1808,7 @@ namespace Harness { // Comment line, check for global/file @options and record them optionRegex.lastIndex = 0; const metaDataName = testMetaData[1].toLowerCase(); - currentFileOptions[testMetaData[1]] = testMetaData[2]; + currentFileOptions[testMetaData[1]] = testMetaData[2].trim(); if (metaDataName !== "filename") { continue; } @@ -1805,12 +1828,12 @@ namespace Harness { // Reset local data currentFileContent = undefined; currentFileOptions = {}; - currentFileName = testMetaData[2]; + currentFileName = testMetaData[2].trim(); refs = []; } else { // First metadata marker in the file - currentFileName = testMetaData[2]; + currentFileName = testMetaData[2].trim(); } } else { @@ -1828,7 +1851,7 @@ namespace Harness { } // normalize the fileName for the single file case - currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : Path.getFileName(fileName); + currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : ts.getBaseFileName(fileName); // EOF, push whatever remains const newTestFile2 = { @@ -1843,8 +1866,8 @@ namespace Harness { // unit tests always list files explicitly const parseConfigHost: ts.ParseConfigHost = { useCaseSensitiveFileNames: false, - readDirectory: (name) => [], - fileExists: (name) => true, + readDirectory: () => [], + fileExists: () => true, readFile: (name) => ts.forEach(testUnitData, data => data.name.toLowerCase() === name.toLowerCase() ? data.content : undefined) }; @@ -1992,7 +2015,7 @@ namespace Harness { export function isDefaultLibraryFile(filePath: string): boolean { // We need to make sure that the filePath is prefixed with "lib." not just containing "lib." and end with ".d.ts" - const fileName = Path.getFileName(filePath); + const fileName = ts.getBaseFileName(ts.normalizeSlashes(filePath)); return ts.startsWith(fileName, "lib.") && ts.endsWith(fileName, ".d.ts"); } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 7cc4c2044ef..a49f8926729 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -165,7 +165,7 @@ namespace Harness.LanguageService { throw new Error("No script with name '" + fileName + "'"); } - public openFile(fileName: string, content?: string, scriptKindName?: string): void { + public openFile(_fileName: string, _content?: string, _scriptKindName?: string): void { } /** @@ -198,7 +198,7 @@ namespace Harness.LanguageService { const script = this.getScriptInfo(fileName); return script ? new ScriptSnapshot(script) : undefined; } - getScriptKind(fileName: string): ts.ScriptKind { return ts.ScriptKind.Unknown; } + getScriptKind(): ts.ScriptKind { return ts.ScriptKind.Unknown; } getScriptVersion(fileName: string): string { const script = this.getScriptInfo(fileName); return script ? script.version.toString() : undefined; @@ -214,7 +214,7 @@ namespace Harness.LanguageService { this.getCurrentDirectory(), (p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p)); } - readFile(path: string, encoding?: string): string { + readFile(path: string): string { const snapshot = this.getScriptSnapshot(path); return snapshot.getText(0, snapshot.getLength()); } @@ -223,9 +223,9 @@ namespace Harness.LanguageService { } - log(s: string): void { } - trace(s: string): void { } - error(s: string): void { } + log(_: string): void { } + trace(_: string): void { } + error(_: string): void { } } export class NativeLanguageServiceAdapter implements LanguageServiceAdapter { @@ -308,19 +308,15 @@ namespace Harness.LanguageService { const nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName); return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot); } - getScriptKind(fileName: string): ts.ScriptKind { return this.nativeHost.getScriptKind(fileName); } + getScriptKind(): ts.ScriptKind { return this.nativeHost.getScriptKind(); } getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); } getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); } - readDirectory(rootDir: string, extension: string): string { - throw new Error("NYI"); - } - readDirectoryNames(path: string): string { - throw new Error("Not implemented."); - } - readFileNames(path: string): string { - throw new Error("Not implemented."); + readDirectory(_rootDir: string, _extension: string): string { + return ts.notImplemented(); } + readDirectoryNames = ts.notImplemented; + readFileNames = ts.notImplemented; fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; } readFile(fileName: string) { const snapshot = this.nativeHost.getScriptSnapshot(fileName); @@ -329,7 +325,7 @@ namespace Harness.LanguageService { log(s: string): void { this.nativeHost.log(s); } trace(s: string): void { this.nativeHost.trace(s); } error(s: string): void { this.nativeHost.error(s); } - directoryExists(directoryName: string): boolean { + directoryExists(): boolean { // for tests pessimistically assume that directory always exists return true; } @@ -338,8 +334,8 @@ namespace Harness.LanguageService { class ClassifierShimProxy implements ts.Classifier { constructor(private shim: ts.ClassifierShim) { } - getEncodedLexicalClassifications(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.Classifications { - throw new Error("NYI"); + getEncodedLexicalClassifications(_text: string, _lexState: ts.EndOfLineState, _classifyKeywordsInGenerics?: boolean): ts.Classifications { + return ts.notImplemented(); } getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult { const result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n"); @@ -411,7 +407,7 @@ namespace Harness.LanguageService { getCompletionEntryDetails(fileName: string, position: number, entryName: string): ts.CompletionEntryDetails { return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName)); } - getCompletionEntrySymbol(fileName: string, position: number, entryName: string): ts.Symbol { + getCompletionEntrySymbol(): ts.Symbol { throw new Error("getCompletionEntrySymbol not implemented across the shim layer."); } getQuickInfoAtPosition(fileName: string, position: number): ts.QuickInfo { @@ -490,7 +486,7 @@ namespace Harness.LanguageService { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean { return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPosition(fileName, position, openingBrace)); } - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): ts.CodeAction[] { + getCodeFixesAtPosition(): ts.CodeAction[] { throw new Error("Not supported on the shim."); } getEmitOutput(fileName: string): ts.EmitOutput { @@ -499,10 +495,10 @@ namespace Harness.LanguageService { getProgram(): ts.Program { throw new Error("Program can not be marshaled across the shim layer."); } - getNonBoundSourceFile(fileName: string): ts.SourceFile { + getNonBoundSourceFile(): ts.SourceFile { throw new Error("SourceFile can not be marshaled across the shim layer."); } - getSourceFile(fileName: string): ts.SourceFile { + getSourceFile(): ts.SourceFile { throw new Error("SourceFile can not be marshaled across the shim layer."); } dispose(): void { this.shim.dispose({}); } @@ -572,11 +568,11 @@ namespace Harness.LanguageService { super(cancellationToken, settings); } - onMessage(message: string): void { + onMessage(): void { } - writeMessage(message: string): void { + writeMessage(): void { } @@ -604,11 +600,11 @@ namespace Harness.LanguageService { this.newLine = this.host.getNewLine(); } - onMessage(message: string): void { + onMessage(): void { } - writeMessage(message: string): void { + writeMessage(_message: string): void { } write(message: string): void { @@ -624,7 +620,7 @@ namespace Harness.LanguageService { return snapshot && snapshot.getText(0, snapshot.getLength()); } - writeFile(name: string, text: string, writeByteOrderMark: boolean): void { + writeFile(): void { } resolvePath(path: string): string { @@ -635,7 +631,7 @@ namespace Harness.LanguageService { return !!this.host.getScriptSnapshot(path); } - directoryExists(path: string): boolean { + directoryExists(): boolean { // for tests assume that directory exists return true; } @@ -644,18 +640,18 @@ namespace Harness.LanguageService { return ""; } - exit(exitCode: number): void { + exit(): void { } - createDirectory(directoryName: string): void { - throw new Error("Not Implemented Yet."); + createDirectory(_directoryName: string): void { + return ts.notImplemented(); } getCurrentDirectory(): string { return this.host.getCurrentDirectory(); } - getDirectories(path: string): string[] { + getDirectories(): string[] { return []; } @@ -663,16 +659,16 @@ namespace Harness.LanguageService { return ts.sys.getEnvironmentVariable(name); } - readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[] { - throw new Error("Not implemented Yet."); + readDirectory(_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] { + return ts.notImplemented(); } - watchFile(fileName: string, callback: (fileName: string) => void): ts.FileWatcher { - return { close() { } }; + watchFile(): ts.FileWatcher { + return { close: ts.noop }; } - watchDirectory(path: string, callback: (path: string) => void, recursive?: boolean): ts.FileWatcher { - return { close() { } }; + watchDirectory(): ts.FileWatcher { + return { close: ts.noop }; } close(): void { @@ -717,13 +713,17 @@ namespace Harness.LanguageService { clearTimeout(timeoutId); } - setImmediate(callback: (...args: any[]) => void, ms: number, ...args: any[]): any { + setImmediate(callback: (...args: any[]) => void, _ms: number, ...args: any[]): any { return setImmediate(callback, args); } clearImmediate(timeoutId: any): void { clearImmediate(timeoutId); } + + createHash(s: string) { + return s; + } } export class ServerLanguageServiceAdapter implements LanguageServiceAdapter { @@ -760,6 +760,6 @@ namespace Harness.LanguageService { getHost() { return this.host; } getLanguageService(): ts.LanguageService { return this.client; } getClassifier(): ts.Classifier { throw new Error("getClassifier is not available using the server interface."); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); } + getPreProcessedFileInfo(): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); } } } diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts index 07dbf4a4e1c..eeb47f0cfa0 100644 --- a/src/harness/loggedIO.ts +++ b/src/harness/loggedIO.ts @@ -173,7 +173,7 @@ namespace Playback { path => callAndRecord(underlying.fileExists(path), recordLog.fileExists, { path }), memoize(path => { // If we read from the file, it must exist - if (findFileByPath(wrapper, replayLog.filesRead, path, /*throwFileNotFoundError*/ false)) { + if (findFileByPath(replayLog.filesRead, path, /*throwFileNotFoundError*/ false)) { return true; } else { @@ -217,7 +217,7 @@ namespace Playback { recordLog.filesRead.push(logEntry); return result; }, - memoize(path => findFileByPath(wrapper, replayLog.filesRead, path, /*throwFileNotFoundError*/ true).contents)); + memoize(path => findFileByPath(replayLog.filesRead, path, /*throwFileNotFoundError*/ true).contents)); wrapper.readDirectory = recordReplay(wrapper.readDirectory, underlying)( (path, extensions, exclude, include) => { @@ -226,7 +226,7 @@ namespace Playback { recordLog.directoriesRead.push(logEntry); return result; }, - (path, extensions, exclude) => { + path => { // Because extensions is an array of all allowed extension, we will want to merge each of the replayLog.directoriesRead into one // if each of the directoriesRead has matched path with the given path (directory with same path but different extension will considered // different entry). @@ -244,7 +244,7 @@ namespace Playback { wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)( (path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }), - (path: string, contents: string) => noOpReplay("writeFile")); + () => noOpReplay("writeFile")); wrapper.exit = (exitCode) => { if (recordLog !== undefined) { @@ -295,7 +295,7 @@ namespace Playback { return results[0].result; } - function findFileByPath(wrapper: { resolvePath(s: string): string }, logArray: IOLogFile[], + function findFileByPath(logArray: IOLogFile[], expectedPath: string, throwFileNotFoundError: boolean): FileInformation { const normalizedName = ts.normalizePath(expectedPath).toLowerCase(); // Try to find the result through normal fileName @@ -314,7 +314,7 @@ namespace Playback { } } - function noOpReplay(name: string) { + function noOpReplay(_name: string) { // console.log("Swallowed write operation during replay: " + name); } @@ -322,13 +322,17 @@ namespace Playback { const wrapper: PlaybackIO = {}; initWrapper(wrapper, underlying); - wrapper.directoryName = (path): string => { throw new Error("NotSupported"); }; - wrapper.createDirectory = (path): void => { throw new Error("NotSupported"); }; - wrapper.directoryExists = (path): boolean => { throw new Error("NotSupported"); }; - wrapper.deleteFile = (path): void => { throw new Error("NotSupported"); }; - wrapper.listFiles = (path, filter, options): string[] => { throw new Error("NotSupported"); }; + wrapper.directoryName = notSupported; + wrapper.createDirectory = notSupported; + wrapper.directoryExists = notSupported; + wrapper.deleteFile = notSupported; + wrapper.listFiles = notSupported; return wrapper; + + function notSupported(): never { + throw new Error("NotSupported"); + } } export function wrapSystem(underlying: ts.System): PlaybackSystem { diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index 415c09caff6..f7541dc9bfe 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -178,7 +178,7 @@ class ProjectRunner extends RunnerBase { function createCompilerHost(): ts.CompilerHost { return { getSourceFile, - getDefaultLibFileName: options => Harness.Compiler.defaultLibFileName, + getDefaultLibFileName: () => Harness.Compiler.defaultLibFileName, writeFile, getCurrentDirectory, getCanonicalFileName: Harness.Compiler.getCanonicalFileName, @@ -421,7 +421,7 @@ class ProjectRunner extends RunnerBase { return undefined; } - function writeFile(fileName: string, data: string, writeByteOrderMark: boolean) { + function writeFile() { } } diff --git a/src/harness/runner.ts b/src/harness/runner.ts index f8df1c51683..3ad6269e52f 100644 --- a/src/harness/runner.ts +++ b/src/harness/runner.ts @@ -61,6 +61,10 @@ function createRunner(kind: TestRunnerKind): RunnerBase { } } +if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.getEnvironmentVariable("NODE_ENV"))) { + Harness.IO.tryEnableSourceMapsForHost(); +} + // users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options const mytestconfigFileName = "mytest.config"; @@ -222,5 +226,5 @@ else { } if (!runUnitTests) { // patch `describe` to skip unit tests - describe = (function () { }); + describe = ts.noop as any; } diff --git a/src/harness/runnerbase.ts b/src/harness/runnerbase.ts index 346382b7a57..d50604803ed 100644 --- a/src/harness/runnerbase.ts +++ b/src/harness/runnerbase.ts @@ -32,7 +32,7 @@ abstract class RunnerBase { /** Replaces instances of full paths with fileNames only */ static removeFullPaths(path: string) { // If its a full path (starts with "C:" or "/") replace with just the filename - let fixedPath = /^(\w:|\/)/.test(path) ? Harness.Path.getFileName(path) : path; + let fixedPath = /^(\w:|\/)/.test(path) ? ts.getBaseFileName(path) : path; // when running in the browser the 'full path' is the host name, shows up in error baselines const localHost = /http:\/localhost:\d+/g; diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index 9f9bf8589f0..44d2c981c84 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -199,7 +199,7 @@ namespace RWC { } // Do not include the library in the baselines to avoid noise const baselineFiles = inputFiles.concat(otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName)); - const errors = compilerResult.errors.filter(e => !Harness.isDefaultLibraryFile(e.file.fileName)); + const errors = compilerResult.errors.filter(e => e.file && !Harness.isDefaultLibraryFile(e.file.fileName)); return Harness.Compiler.getErrorBaseline(baselineFiles, errors); }, baselineOpts); }); diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index f9d302ace81..f4057057e4e 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -10,7 +10,10 @@ "stripInternal": true, "types": [ "node", "mocha", "chai" - ] + ], + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true }, "files": [ "../compiler/core.ts", @@ -26,13 +29,17 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", - "../compiler/transformers/es7.ts", - "../compiler/transformers/es6.ts", + "../compiler/transformers/esnext.ts", + "../compiler/transformers/es2017.ts", + "../compiler/transformers/es2016.ts", + "../compiler/transformers/es2015.ts", + "../compiler/transformers/es5.ts", "../compiler/transformers/generators.ts", + "../compiler/transformers/es5.ts", "../compiler/transformers/destructuring.ts", "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", - "../compiler/transformers/module/es6.ts", + "../compiler/transformers/module/es2015.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", @@ -101,7 +108,7 @@ "./unittests/commandLineParsing.ts", "./unittests/configurationExtension.ts", "./unittests/convertCompilerOptionsFromJson.ts", - "./unittests/convertTypingOptionsFromJson.ts", + "./unittests/convertTypeAcquisitionFromJson.ts", "./unittests/tsserverProjectSystem.ts", "./unittests/matchFiles.ts", "./unittests/initializeTSConfig.ts", diff --git a/src/harness/unittests/cachingInServerLSHost.ts b/src/harness/unittests/cachingInServerLSHost.ts index 9489feb43e9..4286d3555d8 100644 --- a/src/harness/unittests/cachingInServerLSHost.ts +++ b/src/harness/unittests/cachingInServerLSHost.ts @@ -21,65 +21,43 @@ namespace ts { args: [], newLine: "\r\n", useCaseSensitiveFileNames: false, - write: (s: string) => { - }, - readFile: (path: string, encoding?: string): string => { - return path in fileMap ? fileMap[path].content : undefined; - }, - writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => { - throw new Error("NYI"); - }, - resolvePath: (path: string): string => { - throw new Error("NYI"); - }, - fileExists: (path: string): boolean => { - return path in fileMap; - }, - directoryExists: (path: string): boolean => { - return existingDirectories[path] || false; - }, - createDirectory: (path: string) => { - }, - getExecutingFilePath: (): string => { - return ""; - }, - getCurrentDirectory: (): string => { - return ""; - }, - getDirectories: (path: string) => [], - getEnvironmentVariable: (name: string) => "", - readDirectory: (path: string, extension?: string[], exclude?: string[], include?: string[]): string[] => { - throw new Error("NYI"); - }, - exit: (exitCode?: number) => { - }, - watchFile: (path, callback) => { - return { - close: () => { } - }; - }, - watchDirectory: (path, callback, recursive?) => { - return { - close: () => { } - }; - }, + write: noop, + readFile: path => path in fileMap ? fileMap[path].content : undefined, + writeFile: notImplemented, + resolvePath: notImplemented, + fileExists: path => path in fileMap, + directoryExists: path => existingDirectories[path] || false, + createDirectory: noop, + getExecutingFilePath: () => "", + getCurrentDirectory: () => "", + getDirectories: () => [], + getEnvironmentVariable: () => "", + readDirectory: notImplemented, + exit: noop, + watchFile: () => ({ + close: noop + }), + watchDirectory: () => ({ + close: noop + }), setTimeout, clearTimeout, - setImmediate, - clearImmediate + setImmediate: typeof setImmediate !== "undefined" ? setImmediate : action => setTimeout(action, 0), + clearImmediate: typeof clearImmediate !== "undefined" ? clearImmediate : clearTimeout, + createHash: s => s }; } function createProject(rootFile: string, serverHost: server.ServerHost): { project: server.Project, rootScriptInfo: server.ScriptInfo } { const logger: server.Logger = { - close() { }, + close: noop, hasLevel: () => false, loggingEnabled: () => false, - perftrc: (s: string) => { }, - info: (s: string) => { }, - startGroup: () => { }, - endGroup: () => { }, - msg: (s: string, type?: string) => { }, + perftrc: noop, + info: noop, + startGroup: noop, + endGroup: noop, + msg: noop, getLogFileName: (): string => undefined }; @@ -116,10 +94,7 @@ namespace ts { const originalFileExists = serverHost.fileExists; { // patch fileExists to make sure that disk is not touched - serverHost.fileExists = (fileName): boolean => { - assert.isTrue(false, "fileExists should not be called"); - return false; - }; + serverHost.fileExists = notImplemented; const newContent = `import {x} from "f1" var x: string = 1;`; diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 028786eef24..8c691992043 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -1,4 +1,4 @@ -/// +/// /// namespace ts { @@ -60,7 +60,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -87,7 +87,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--jsx' option must be: 'preserve', 'react'", + messageText: "Argument for '--jsx' option must be: 'preserve', 'react'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -113,7 +113,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'", + messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -139,7 +139,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'", + messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -165,7 +165,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -191,7 +191,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'", + messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -263,7 +263,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -283,7 +283,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -338,5 +338,38 @@ namespace ts { } }); }); + + it("Parse explicit boolean flag value", () => { + assertParseResult(["--strictNullChecks", "false", "0.ts"], + { + errors: [], + fileNames: ["0.ts"], + options: { + strictNullChecks: false, + } + }); + }); + + it("Parse non boolean argument after boolean flag", () => { + assertParseResult(["--noImplicitAny", "t", "0.ts"], + { + errors: [], + fileNames: ["t", "0.ts"], + options: { + noImplicitAny: true, + } + }); + }); + + it("Parse implicit boolean flag value", () => { + assertParseResult(["--strictNullChecks"], + { + errors: [], + fileNames: [], + options: { + strictNullChecks: true, + } + }); + }); }); } diff --git a/src/harness/unittests/compileOnSave.ts b/src/harness/unittests/compileOnSave.ts index 24fd47ee0cb..d7731a625fe 100644 --- a/src/harness/unittests/compileOnSave.ts +++ b/src/harness/unittests/compileOnSave.ts @@ -3,6 +3,8 @@ /// namespace ts.projectSystem { + import CommandNames = server.CommandNames; + function createTestTypingsInstaller(host: server.ServerHost) { return new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host); } @@ -75,7 +77,7 @@ namespace ts.projectSystem { }; // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1ShapeRequest1 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1ShapeRequest1 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -85,7 +87,7 @@ namespace ts.projectSystem { }); // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1InternalRequest1 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1InternalRequest1 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -95,7 +97,7 @@ namespace ts.projectSystem { }); // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1ShapeRequest2 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1ShapeRequest2 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -104,7 +106,7 @@ namespace ts.projectSystem { insertString: `export var T2: number;` }); - moduleFile1FileListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path }); + moduleFile1FileListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path }); }); it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { @@ -120,7 +122,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]); // Change the content of file1 to `export var T: number;export function Foo() { console.log('hi'); };` - const changeFile1InternalRequest = makeSessionRequest(server.CommandNames.Change, { + const changeFile1InternalRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 46, @@ -143,7 +145,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]); // Change file2 content to `let y = Foo();` - const removeFile1Consumer1ImportRequest = makeSessionRequest(server.CommandNames.Change, { + const removeFile1Consumer1ImportRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 1, offset: 1, @@ -156,7 +158,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer2] }]); // Add the import statements back to file2 - const addFile2ImportRequest = makeSessionRequest(server.CommandNames.Change, { + const addFile2ImportRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 1, offset: 1, @@ -167,7 +169,7 @@ namespace ts.projectSystem { session.executeCommand(addFile2ImportRequest); // Change the content of file1 to `export var T2: string;export var T: number;export function Foo() { };` - const changeModuleFile1ShapeRequest2 = makeSessionRequest(server.CommandNames.Change, { + const changeModuleFile1ShapeRequest2 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -272,7 +274,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([globalFile3], session); - const changeGlobalFile3ShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const changeGlobalFile3ShapeRequest = makeSessionRequest(CommandNames.Change, { file: globalFile3.path, line: 1, offset: 1, @@ -283,7 +285,7 @@ namespace ts.projectSystem { // check after file1 shape changes session.executeCommand(changeGlobalFile3ShapeRequest); - const globalFile3FileListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path }); + const globalFile3FileListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path }); sendAffectedFileRequestAndCheckResult(session, globalFile3FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2] }]); }); @@ -316,7 +318,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([moduleFile1], session); - const file1ChangeShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const file1ChangeShapeRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 27, @@ -345,7 +347,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([moduleFile1], session); - const file1ChangeShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const file1ChangeShapeRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 27, @@ -369,7 +371,7 @@ namespace ts.projectSystem { openFilesForSession([moduleFile1, file1Consumer1], session); sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer1Consumer1] }]); - const changeFile1Consumer1ShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const changeFile1Consumer1ShapeRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 2, offset: 1, @@ -400,7 +402,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([file1, file2], session); - const file1AffectedListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); + const file1AffectedListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [{ projectFileName: configFile.path, files: [file1, file2] }]); }); @@ -415,7 +417,7 @@ namespace ts.projectSystem { const session = createSession(host); openFilesForSession([file1, file2, file3], session); - const file1AffectedListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); + const file1AffectedListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [ { projectFileName: configFile1.path, files: [file1, file2] }, @@ -437,11 +439,11 @@ namespace ts.projectSystem { host.reloadFS([referenceFile1, configFile]); host.triggerFileWatcherCallback(moduleFile1.path, /*removed*/ true); - const request = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); + const request = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); sendAffectedFileRequestAndCheckResult(session, request, [ { projectFileName: configFile.path, files: [referenceFile1] } ]); - const requestForMissingFile = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path }); + const requestForMissingFile = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path }); sendAffectedFileRequestAndCheckResult(session, requestForMissingFile, []); }); @@ -456,7 +458,7 @@ namespace ts.projectSystem { const session = createSession(host); openFilesForSession([referenceFile1], session); - const request = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); + const request = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); sendAffectedFileRequestAndCheckResult(session, request, [ { projectFileName: configFile.path, files: [referenceFile1] } ]); @@ -483,12 +485,52 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([file1, file2], session); - const compileFileRequest = makeSessionRequest(server.CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path }); + const compileFileRequest = makeSessionRequest(CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path }); session.executeCommand(compileFileRequest); const expectedEmittedFileName = "/a/b/f1.js"; assert.isTrue(host.fileExists(expectedEmittedFileName)); assert.equal(host.readFile(expectedEmittedFileName), `"use strict";\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`); }); + + it("shoud not emit js files in external projects", () => { + const file1 = { + path: "/a/b/file1.ts", + content: "consonle.log('file1');" + }; + // file2 has errors. The emitting should not be blocked. + const file2 = { + path: "/a/b/file2.js", + content: "console.log'file2');" + }; + const file3 = { + path: "/a/b/file3.js", + content: "console.log('file3');" + }; + const externalProjectName = "externalproject"; + const host = createServerHost([file1, file2, file3, libFile]); + const session = createSession(host); + const projectService = session.getProjectService(); + + projectService.openExternalProject({ + rootFiles: toExternalFiles([file1.path, file2.path]), + options: { + allowJs: true, + outFile: "dist.js", + compileOnSave: true + }, + projectFileName: externalProjectName + }); + + const emitRequest = makeSessionRequest(CommandNames.CompileOnSaveEmitFile, { file: file1.path }); + session.executeCommand(emitRequest); + + const expectedOutFileName = "/a/b/dist.js"; + assert.isTrue(host.fileExists(expectedOutFileName)); + const outFileContent = host.readFile(expectedOutFileName); + assert.isTrue(outFileContent.indexOf(file1.content) !== -1); + assert.isTrue(outFileContent.indexOf(file2.content) === -1); + assert.isTrue(outFileContent.indexOf(file3.content) === -1); + }); }); } \ No newline at end of file diff --git a/src/harness/unittests/configurationExtension.ts b/src/harness/unittests/configurationExtension.ts index 4537dc77576..8e845925eb2 100644 --- a/src/harness/unittests/configurationExtension.ts +++ b/src/harness/unittests/configurationExtension.ts @@ -179,7 +179,7 @@ namespace ts { testFailure("can error when 'extends' is neither relative nor rooted.", "extends2.json", [{ code: 18001, category: DiagnosticCategory.Error, - messageText: `The path in an 'extends' options must be relative or rooted.` + messageText: `A path in an 'extends' option must be relative or rooted, but 'configs/base' is not.` }]); }); }); diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index 33cad7130c7..f44dc259710 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -94,7 +94,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--jsx' option must be: 'preserve', 'react'", + messageText: "Argument for '--jsx' option must be: 'preserve', 'react'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -122,7 +122,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'", + messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -150,7 +150,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'", + messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -176,7 +176,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -202,7 +202,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'", + messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -233,7 +233,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -264,7 +264,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -295,7 +295,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -326,7 +326,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory'", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/src/harness/unittests/convertTypingOptionsFromJson.ts b/src/harness/unittests/convertTypeAcquisitionFromJson.ts similarity index 53% rename from src/harness/unittests/convertTypingOptionsFromJson.ts rename to src/harness/unittests/convertTypeAcquisitionFromJson.ts index 439409b24b7..4c21b7ca2b9 100644 --- a/src/harness/unittests/convertTypingOptionsFromJson.ts +++ b/src/harness/unittests/convertTypeAcquisitionFromJson.ts @@ -2,12 +2,13 @@ /// namespace ts { - describe("convertTypingOptionsFromJson", () => { - function assertTypingOptions(json: any, configFileName: string, expectedResult: { typingOptions: TypingOptions, errors: Diagnostic[] }) { - const { options: actualTypingOptions, errors: actualErrors } = convertTypingOptionsFromJson(json["typingOptions"], "/apath/", configFileName); - const parsedTypingOptions = JSON.stringify(actualTypingOptions); - const expectedTypingOptions = JSON.stringify(expectedResult.typingOptions); - assert.equal(parsedTypingOptions, expectedTypingOptions); + describe("convertTypeAcquisitionFromJson", () => { + function assertTypeAcquisition(json: any, configFileName: string, expectedResult: { typeAcquisition: TypeAcquisition, errors: Diagnostic[] }) { + const jsonOptions = json["typeAcquisition"] || json["typingOptions"]; + const { options: actualTypeAcquisition, errors: actualErrors } = convertTypeAcquisitionFromJson(jsonOptions, "/apath/", configFileName); + const parsedTypeAcquisition = JSON.stringify(actualTypeAcquisition); + const expectedTypeAcquisition = JSON.stringify(expectedResult.typeAcquisition); + assert.equal(parsedTypeAcquisition, expectedTypeAcquisition); const expectedErrors = expectedResult.errors; assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`); @@ -20,8 +21,8 @@ namespace ts { } // tsconfig.json - it("Convert correctly format tsconfig.json to typing-options ", () => { - assertTypingOptions( + it("Convert deprecated typingOptions.enableAutoDiscovery format tsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition( { "typingOptions": { @@ -32,9 +33,9 @@ namespace ts { }, "tsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: true, + enable: true, include: ["0.d.ts", "1.d.ts"], exclude: ["0.js", "1.js"] }, @@ -42,25 +43,47 @@ namespace ts { }); }); - it("Convert incorrect format tsconfig.json to typing-options ", () => { - assertTypingOptions( + it("Convert correctly format tsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition( { - "typingOptions": + "typeAcquisition": + { + "enable": true, + "include": ["0.d.ts", "1.d.ts"], + "exclude": ["0.js", "1.js"] + } + }, + "tsconfig.json", + { + typeAcquisition: + { + enable: true, + include: ["0.d.ts", "1.d.ts"], + exclude: ["0.js", "1.js"] + }, + errors: [] + }); + }); + + it("Convert incorrect format tsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition( + { + "typeAcquisition": { "enableAutoDiscovy": true, } }, "tsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: false, + enable: false, include: [], exclude: [] }, errors: [ { - category: Diagnostics.Unknown_typing_option_0.category, - code: Diagnostics.Unknown_typing_option_0.code, + category: Diagnostics.Unknown_type_acquisition_option_0.category, + code: Diagnostics.Unknown_type_acquisition_option_0.code, file: undefined, start: 0, length: 0, @@ -70,12 +93,12 @@ namespace ts { }); }); - it("Convert default tsconfig.json to typing-options ", () => { - assertTypingOptions({}, "tsconfig.json", + it("Convert default tsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition({}, "tsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: false, + enable: false, include: [], exclude: [] }, @@ -83,18 +106,18 @@ namespace ts { }); }); - it("Convert tsconfig.json with only enableAutoDiscovery property to typing-options ", () => { - assertTypingOptions( + it("Convert tsconfig.json with only enable property to typeAcquisition ", () => { + assertTypeAcquisition( { - "typingOptions": + "typeAcquisition": { - "enableAutoDiscovery": true + "enable": true } }, "tsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: true, + enable: true, include: [], exclude: [] }, @@ -103,20 +126,20 @@ namespace ts { }); // jsconfig.json - it("Convert jsconfig.json to typing-options ", () => { - assertTypingOptions( + it("Convert jsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition( { - "typingOptions": + "typeAcquisition": { - "enableAutoDiscovery": false, + "enable": false, "include": ["0.d.ts"], "exclude": ["0.js"] } }, "jsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: false, + enable: false, include: ["0.d.ts"], exclude: ["0.js"] }, @@ -124,12 +147,12 @@ namespace ts { }); }); - it("Convert default jsconfig.json to typing-options ", () => { - assertTypingOptions({ }, "jsconfig.json", + it("Convert default jsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition({ }, "jsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: true, + enable: true, include: [], exclude: [] }, @@ -137,25 +160,25 @@ namespace ts { }); }); - it("Convert incorrect format jsconfig.json to typing-options ", () => { - assertTypingOptions( + it("Convert incorrect format jsconfig.json to typeAcquisition ", () => { + assertTypeAcquisition( { - "typingOptions": + "typeAcquisition": { "enableAutoDiscovy": true, } }, "jsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: true, + enable: true, include: [], exclude: [] }, errors: [ { category: Diagnostics.Unknown_compiler_option_0.category, - code: Diagnostics.Unknown_typing_option_0.code, + code: Diagnostics.Unknown_type_acquisition_option_0.code, file: undefined, start: 0, length: 0, @@ -165,18 +188,18 @@ namespace ts { }); }); - it("Convert jsconfig.json with only enableAutoDiscovery property to typing-options ", () => { - assertTypingOptions( + it("Convert jsconfig.json with only enable property to typeAcquisition ", () => { + assertTypeAcquisition( { - "typingOptions": + "typeAcquisition": { - "enableAutoDiscovery": false + "enable": false } }, "jsconfig.json", { - typingOptions: + typeAcquisition: { - enableAutoDiscovery: false, + enable: false, include: [], exclude: [] }, diff --git a/src/harness/unittests/incrementalParser.ts b/src/harness/unittests/incrementalParser.ts index 0082207e699..6088e5fe082 100644 --- a/src/harness/unittests/incrementalParser.ts +++ b/src/harness/unittests/incrementalParser.ts @@ -44,10 +44,10 @@ namespace ts { // NOTE: 'reusedElements' is the expected count of elements reused from the old tree to the new // tree. It may change as we tweak the parser. If the count increases then that should always - // be a good thing. If it decreases, that's not great (less reusability), but that may be - // unavoidable. If it does decrease an investigation should be done to make sure that things + // be a good thing. If it decreases, that's not great (less reusability), but that may be + // unavoidable. If it does decrease an investigation should be done to make sure that things // are still ok and we're still appropriately reusing most of the tree. - function compareTrees(oldText: IScriptSnapshot, newText: IScriptSnapshot, textChangeRange: TextChangeRange, expectedReusedElements: number, oldTree?: SourceFile): SourceFile { + function compareTrees(oldText: IScriptSnapshot, newText: IScriptSnapshot, textChangeRange: TextChangeRange, expectedReusedElements: number, oldTree?: SourceFile) { oldTree = oldTree || createTree(oldText, /*version:*/ "."); Utils.assertInvariants(oldTree, /*parent:*/ undefined); @@ -76,7 +76,7 @@ namespace ts { assert.equal(actualReusedCount, expectedReusedElements, actualReusedCount + " !== " + expectedReusedElements); } - return incrementalNewTree; + return { oldTree, newTree, incrementalNewTree }; } function reusedElements(oldNode: SourceFile, newNode: SourceFile): number { @@ -103,7 +103,7 @@ namespace ts { for (let i = 0; i < repeat; i++) { const oldText = ScriptSnapshot.fromString(source); const newTextAndChange = withDelete(oldText, index, 1); - const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree); + const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree).incrementalNewTree; source = newTextAndChange.text.getText(0, newTextAndChange.text.getLength()); oldTree = newTree; @@ -116,7 +116,7 @@ namespace ts { for (let i = 0; i < repeat; i++) { const oldText = ScriptSnapshot.fromString(source); const newTextAndChange = withInsert(oldText, index + i, toInsert.charAt(i)); - const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree); + const newTree = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1, oldTree).incrementalNewTree; source = newTextAndChange.text.getText(0, newTextAndChange.text.getLength()); oldTree = newTree; @@ -639,7 +639,7 @@ module m3 { }\ }); it("Unterminated comment after keyword converted to identifier", () => { - // 'public' as a keyword should be incrementally unusable (because it has an + // 'public' as a keyword should be incrementally unusable (because it has an // unterminated comment). When we convert it to an identifier, that shouldn't // change anything, and we should still get the same errors. const source = "return; a.public /*"; @@ -796,6 +796,16 @@ module m3 { }\ compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); }); + it("Reuse transformFlags of subtree during bind", () => { + const source = `class Greeter { constructor(element: HTMLElement) { } }`; + const oldText = ScriptSnapshot.fromString(source); + const newTextAndChange = withChange(oldText, 15, 0, "\n"); + const { oldTree, incrementalNewTree } = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1); + bindSourceFile(oldTree, {}); + bindSourceFile(incrementalNewTree, {}); + assert.equal(oldTree.transformFlags, incrementalNewTree.transformFlags); + }); + // Simulated typing tests. it("Type extends clause 1", () => { diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index 2c935439a9b..addd01b0e0a 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -101,7 +101,7 @@ namespace ts { Harness.Baseline.runBaseline("JSDocParsing/DocComments.parsesCorrectly." + name + ".json", () => JSON.stringify(comment.jsDoc, - (k, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4)); + (_, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4)); }); } diff --git a/src/harness/unittests/matchFiles.ts b/src/harness/unittests/matchFiles.ts index 6b499e56989..c562fcefe91 100644 --- a/src/harness/unittests/matchFiles.ts +++ b/src/harness/unittests/matchFiles.ts @@ -3,6 +3,7 @@ namespace ts { const caseInsensitiveBasePath = "c:/dev/"; + const caseInsensitiveTsconfigPath = "c:/dev/tsconfig.json"; const caseInsensitiveHost = new Utils.MockParseConfigHost(caseInsensitiveBasePath, /*useCaseSensitiveFileNames*/ false, [ "c:/dev/a.ts", "c:/dev/a.d.ts", @@ -88,7 +89,30 @@ namespace ts { "c:/dev/g.min.js/.g/g.ts" ]); + function assertParsed(actual: ts.ParsedCommandLine, expected: ts.ParsedCommandLine): void { + assert.deepEqual(actual.fileNames, expected.fileNames); + assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); + assert.deepEqual(actual.errors, expected.errors); + } + describe("matchFiles", () => { + it("with defaults", () => { + const json = {}; + const expected: ts.ParsedCommandLine = { + options: {}, + errors: [], + fileNames: [ + "c:/dev/a.ts", + "c:/dev/b.ts" + ], + wildcardDirectories: { + "c:/dev": ts.WatchDirectoryFlags.Recursive + }, + }; + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); + assertParsed(actual, expected); + }); + describe("with literal file list", () => { it("without exclusions", () => { const json = { @@ -107,9 +131,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("missing files are still present", () => { const json = { @@ -128,9 +150,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("are not removed due to excludes", () => { const json = { @@ -152,9 +172,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); }); @@ -176,9 +194,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with non .ts file extensions are excluded", () => { const json = { @@ -189,14 +205,15 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") + ], fileNames: [], wildcardDirectories: {}, }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("with missing files are excluded", () => { const json = { @@ -207,14 +224,15 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") + ], fileNames: [], wildcardDirectories: {}, }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("with literal excludes", () => { const json = { @@ -235,9 +253,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with wildcard excludes", () => { const json = { @@ -265,9 +281,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with recursive excludes", () => { const json = { @@ -294,9 +308,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with case sensitive exclude", () => { const json = { @@ -316,9 +328,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseSensitiveHost, caseSensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and no exclusions", () => { const json = { @@ -335,14 +345,15 @@ namespace ts { errors: [], fileNames: [ "c:/dev/a.ts", - "c:/dev/b.ts" + "c:/dev/b.ts", + "c:/dev/bower_components/a.ts", + "c:/dev/jspm_packages/a.ts", + "c:/dev/node_modules/a.ts" ], wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and exclusions", () => { const json = { @@ -369,9 +380,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and empty exclude", () => { const json = { @@ -381,8 +390,7 @@ namespace ts { "node_modules/a.ts", "bower_components/a.ts", "jspm_packages/a.ts" - ], - exclude: [] + ] }; const expected: ts.ParsedCommandLine = { options: {}, @@ -397,9 +405,7 @@ namespace ts { wildcardDirectories: {}, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); }); @@ -423,9 +429,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("`*` matches only ts files", () => { const json = { @@ -446,9 +450,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("`?` matches only a single character", () => { const json = { @@ -468,9 +470,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with recursive directory", () => { const json = { @@ -492,9 +492,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with multiple recursive directories", () => { const json = { @@ -518,9 +516,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("case sensitive", () => { const json = { @@ -539,9 +535,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseSensitiveHost, caseSensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with missing files are excluded", () => { const json = { @@ -551,16 +545,17 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") + ], fileNames: [], wildcardDirectories: { "c:/dev": ts.WatchDirectoryFlags.Recursive }, }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("always include literal files", () => { const json = { @@ -585,9 +580,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("exclude folders", () => { const json = { @@ -612,30 +605,29 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and no exclusions", () => { const json = { include: [ - "**/a.ts" + "**/a.ts" ] }; const expected: ts.ParsedCommandLine = { options: {}, errors: [], fileNames: [ - "c:/dev/a.ts" + "c:/dev/a.ts", + "c:/dev/bower_components/a.ts", + "c:/dev/jspm_packages/a.ts", + "c:/dev/node_modules/a.ts" ], wildcardDirectories: { "c:/dev": ts.WatchDirectoryFlags.Recursive }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and exclusions", () => { const json = { @@ -659,9 +651,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with common package folders and empty exclude", () => { const json = { @@ -684,9 +674,7 @@ namespace ts { }, }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("exclude .js files when allowJs=false", () => { const json = { @@ -701,16 +689,17 @@ namespace ts { options: { allowJs: false }, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") + ], fileNames: [], wildcardDirectories: { "c:/dev/js": ts.WatchDirectoryFlags.None } }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("include .js files when allowJs=true", () => { const json = { @@ -735,9 +724,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("include explicitly listed .min.js files when allowJs=true", () => { const json = { @@ -762,9 +749,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("include paths outside of the project", () => { const json = { @@ -788,9 +773,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("include paths outside of the project using relative paths", () => { const json = { @@ -813,9 +796,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("exclude paths outside of the project using relative paths", () => { const json = { @@ -828,14 +809,15 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude))] + , fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("include files with .. in their name", () => { const json = { @@ -855,9 +837,7 @@ namespace ts { wildcardDirectories: {} }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("exclude files with .. in their name", () => { const json = { @@ -879,9 +859,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with jsx=none, allowJs=false", () => { const json = { @@ -904,9 +882,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with jsx=preserve, allowJs=false", () => { const json = { @@ -931,9 +907,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with jsx=none, allowJs=true", () => { const json = { @@ -958,9 +932,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with jsx=preserve, allowJs=true", () => { const json = { @@ -987,9 +959,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("exclude .min.js files using wildcards", () => { const json = { @@ -1016,9 +986,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); describe("with trailing recursive directory", () => { it("in includes", () => { @@ -1030,15 +998,15 @@ namespace ts { const expected: ts.ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**") + ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**"), + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("in excludes", () => { const json = { @@ -1051,14 +1019,15 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude)) + ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); }); describe("with multiple recursive directory patterns", () => { @@ -1071,15 +1040,15 @@ namespace ts { const expected: ts.ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*") + ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*"), + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("in excludes", () => { const json = { @@ -1106,9 +1075,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); }); @@ -1122,15 +1089,15 @@ namespace ts { const expected: ts.ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*") + ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*"), + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("in includes after a subdirectory", () => { @@ -1142,15 +1109,15 @@ namespace ts { const expected: ts.ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*") + ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*"), + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); it("in excludes immediately after", () => { @@ -1178,9 +1145,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("in excludes after a subdirectory", () => { @@ -1195,7 +1160,7 @@ namespace ts { const expected: ts.ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..") + ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..") ], fileNames: [ "c:/dev/a.ts", @@ -1208,9 +1173,25 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); + }); + }); + + describe("with implicit globbification", () => { + it("Expands 'z' to 'z/**/*'", () => { + const json = { + include: ["z"] + }; + const expected: ts.ParsedCommandLine = { + options: {}, + errors: [], + fileNames: [ "a.ts", "aba.ts", "abz.ts", "b.ts", "bba.ts", "bbz.ts" ].map(x => `c:/dev/z/${x}`), + wildcardDirectories: { + "c:/dev/z": ts.WatchDirectoryFlags.Recursive + } + }; + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath); + assertParsed(actual, expected); }); }); }); @@ -1235,9 +1216,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); describe("that are explicitly included", () => { it("without wildcards", () => { @@ -1257,9 +1236,7 @@ namespace ts { wildcardDirectories: {} }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with recursive wildcards that match directories", () => { const json = { @@ -1281,9 +1258,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with recursive wildcards that match nothing", () => { const json = { @@ -1305,9 +1280,7 @@ namespace ts { } }; const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + assertParsed(actual, expected); }); it("with wildcard excludes that implicitly exclude dotted files", () => { const json = { @@ -1320,14 +1293,15 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [], + errors: [ + ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude)) + ], fileNames: [], wildcardDirectories: {} }; - const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - assert.deepEqual(actual.fileNames, expected.fileNames); - assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); - assert.deepEqual(actual.errors, expected.errors); + const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath); + assertParsed(actual, expected); }); }); }); diff --git a/src/harness/unittests/moduleResolution.ts b/src/harness/unittests/moduleResolution.ts index 3e1ac171216..35313e15308 100644 --- a/src/harness/unittests/moduleResolution.ts +++ b/src/harness/unittests/moduleResolution.ts @@ -1,6 +1,28 @@ /// namespace ts { + export function checkResolvedModule(expected: ResolvedModuleFull, actual: ResolvedModuleFull): boolean { + if (!expected === !actual) { + if (expected) { + assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`); + assert.isTrue(expected.extension === actual.extension, `'ext': expected '${Extension[expected.extension]}' to be equal to '${Extension[actual.extension]}'`); + assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`); + } + return true; + } + return false; + } + + export function checkResolvedModuleWithFailedLookupLocations(actual: ResolvedModuleWithFailedLookupLocations, expectedResolvedModule: ResolvedModuleFull, expectedFailedLookupLocations: string[]): void { + assert.isTrue(actual.resolvedModule !== undefined, "module should be resolved"); + checkResolvedModule(actual.resolvedModule, expectedResolvedModule); + assert.deepEqual(actual.failedLookupLocations, expectedFailedLookupLocations); + } + + export function createResolvedModule(resolvedFileName: string, isExternalLibraryImport = false): ResolvedModuleFull { + return { resolvedFileName, extension: extensionFromPath(resolvedFileName), isExternalLibraryImport }; + } + interface File { name: string; content?: string; @@ -53,8 +75,7 @@ namespace ts { const containingFile = { name: containingFileName }; const moduleFile = { name: moduleFileNameNoExt + ext }; const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, moduleFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, moduleFile.name); - assert.equal(!!resolution.resolvedModule.isExternalLibraryImport, false); + checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); const failedLookupLocations: string[] = []; const dir = getDirectoryPath(containingFileName); @@ -97,8 +118,7 @@ namespace ts { const packageJson = { name: packageJsonFileName, content: JSON.stringify({ "typings": fieldRef }) }; const moduleFile = { name: moduleFileName }; const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, moduleFile.name); - assert.equal(!!resolution.resolvedModule.isExternalLibraryImport, false); + checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); // expect three failed lookup location - attempt to load module as file with all supported extensions assert.equal(resolution.failedLookupLocations.length, supportedTypeScriptExtensions.length); } @@ -125,7 +145,7 @@ namespace ts { const resolution = nodeModuleNameResolver("b", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile, indexFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, indexPath); + checkResolvedModule(resolution.resolvedModule, createResolvedModule(indexPath, /*isExternalLibraryImport*/true)); } } @@ -138,7 +158,6 @@ namespace ts { /* tslint:enable no-null-keyword */ testTypingsIgnored(undefined); }); - it("module name as directory - load index.d.ts", () => { test(/*hasDirectoryExists*/ false); test(/*hasDirectoryExists*/ true); @@ -148,9 +167,7 @@ namespace ts { const packageJson = { name: "/a/b/foo/package.json", content: JSON.stringify({ main: "/c/d" }) }; const indexFile = { name: "/a/b/foo/index.d.ts" }; const resolution = nodeModuleNameResolver("./foo", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, indexFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, indexFile.name); - assert.equal(!!resolution.resolvedModule.isExternalLibraryImport, false); - assert.deepEqual(resolution.failedLookupLocations, [ + checkResolvedModuleWithFailedLookupLocations(resolution, createResolvedModule(indexFile.name), [ "/a/b/foo.ts", "/a/b/foo.tsx", "/a/b/foo.d.ts", @@ -170,35 +187,33 @@ namespace ts { const containingFile = { name: "/a/b/c/d/e.ts" }; const moduleFile = { name: "/a/b/node_modules/foo.ts" }; const resolution = nodeModuleNameResolver("foo", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, moduleFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, moduleFile.name); - assert.deepEqual(resolution.failedLookupLocations, [ + checkResolvedModuleWithFailedLookupLocations(resolution, createResolvedModule(moduleFile.name, /*isExternalLibraryImport*/ true), [ "/a/b/c/d/node_modules/foo.ts", "/a/b/c/d/node_modules/foo.tsx", "/a/b/c/d/node_modules/foo.d.ts", "/a/b/c/d/node_modules/foo/package.json", + "/a/b/c/d/node_modules/foo/index.ts", "/a/b/c/d/node_modules/foo/index.tsx", "/a/b/c/d/node_modules/foo/index.d.ts", - "/a/b/c/d/node_modules/@types/foo.ts", - "/a/b/c/d/node_modules/@types/foo.tsx", + "/a/b/c/d/node_modules/@types/foo.d.ts", "/a/b/c/d/node_modules/@types/foo/package.json", - "/a/b/c/d/node_modules/@types/foo/index.ts", - "/a/b/c/d/node_modules/@types/foo/index.tsx", + "/a/b/c/d/node_modules/@types/foo/index.d.ts", + "/a/b/c/node_modules/foo.ts", "/a/b/c/node_modules/foo.tsx", "/a/b/c/node_modules/foo.d.ts", "/a/b/c/node_modules/foo/package.json", + "/a/b/c/node_modules/foo/index.ts", "/a/b/c/node_modules/foo/index.tsx", "/a/b/c/node_modules/foo/index.d.ts", - "/a/b/c/node_modules/@types/foo.ts", - "/a/b/c/node_modules/@types/foo.tsx", + "/a/b/c/node_modules/@types/foo.d.ts", "/a/b/c/node_modules/@types/foo/package.json", - "/a/b/c/node_modules/@types/foo/index.ts", - "/a/b/c/node_modules/@types/foo/index.tsx", + "/a/b/c/node_modules/@types/foo/index.d.ts", ]); } @@ -212,8 +227,7 @@ namespace ts { const containingFile = { name: "/a/b/c/d/e.ts" }; const moduleFile = { name: "/a/b/node_modules/foo.d.ts" }; const resolution = nodeModuleNameResolver("foo", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, moduleFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, moduleFile.name); - assert.equal(resolution.resolvedModule.isExternalLibraryImport, true); + checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name, /*isExternalLibraryImport*/ true)); } }); @@ -225,55 +239,54 @@ namespace ts { const containingFile = { name: "/a/node_modules/b/c/node_modules/d/e.ts" }; const moduleFile = { name: "/a/node_modules/foo/index.d.ts" }; const resolution = nodeModuleNameResolver("foo", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, moduleFile)); - assert.equal(resolution.resolvedModule.resolvedFileName, moduleFile.name); - assert.equal(resolution.resolvedModule.isExternalLibraryImport, true); - assert.deepEqual(resolution.failedLookupLocations, [ + checkResolvedModuleWithFailedLookupLocations(resolution, createResolvedModule(moduleFile.name, /*isExternalLibraryImport*/ true), [ "/a/node_modules/b/c/node_modules/d/node_modules/foo.ts", "/a/node_modules/b/c/node_modules/d/node_modules/foo.tsx", "/a/node_modules/b/c/node_modules/d/node_modules/foo.d.ts", "/a/node_modules/b/c/node_modules/d/node_modules/foo/package.json", + "/a/node_modules/b/c/node_modules/d/node_modules/foo/index.ts", "/a/node_modules/b/c/node_modules/d/node_modules/foo/index.tsx", "/a/node_modules/b/c/node_modules/d/node_modules/foo/index.d.ts", - "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.ts", - "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.tsx", + "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo.d.ts", "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/package.json", - "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.ts", - "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.tsx", + "/a/node_modules/b/c/node_modules/d/node_modules/@types/foo/index.d.ts", + "/a/node_modules/b/c/node_modules/foo.ts", "/a/node_modules/b/c/node_modules/foo.tsx", "/a/node_modules/b/c/node_modules/foo.d.ts", "/a/node_modules/b/c/node_modules/foo/package.json", + "/a/node_modules/b/c/node_modules/foo/index.ts", "/a/node_modules/b/c/node_modules/foo/index.tsx", "/a/node_modules/b/c/node_modules/foo/index.d.ts", - "/a/node_modules/b/c/node_modules/@types/foo.ts", - "/a/node_modules/b/c/node_modules/@types/foo.tsx", + "/a/node_modules/b/c/node_modules/@types/foo.d.ts", "/a/node_modules/b/c/node_modules/@types/foo/package.json", - "/a/node_modules/b/c/node_modules/@types/foo/index.ts", - "/a/node_modules/b/c/node_modules/@types/foo/index.tsx", + "/a/node_modules/b/c/node_modules/@types/foo/index.d.ts", + "/a/node_modules/b/node_modules/foo.ts", "/a/node_modules/b/node_modules/foo.tsx", "/a/node_modules/b/node_modules/foo.d.ts", "/a/node_modules/b/node_modules/foo/package.json", + "/a/node_modules/b/node_modules/foo/index.ts", "/a/node_modules/b/node_modules/foo/index.tsx", "/a/node_modules/b/node_modules/foo/index.d.ts", - "/a/node_modules/b/node_modules/@types/foo.ts", - "/a/node_modules/b/node_modules/@types/foo.tsx", + "/a/node_modules/b/node_modules/@types/foo.d.ts", "/a/node_modules/b/node_modules/@types/foo/package.json", - "/a/node_modules/b/node_modules/@types/foo/index.ts", - "/a/node_modules/b/node_modules/@types/foo/index.tsx", + "/a/node_modules/b/node_modules/@types/foo/index.d.ts", + "/a/node_modules/foo.ts", "/a/node_modules/foo.tsx", "/a/node_modules/foo.d.ts", "/a/node_modules/foo/package.json", + "/a/node_modules/foo/index.ts", "/a/node_modules/foo/index.tsx" ]); @@ -290,7 +303,7 @@ namespace ts { return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined; }, getDefaultLibFileName: () => "lib.d.ts", - writeFile: (fileName, content): void => { throw new Error("NotImplemented"); }, + writeFile: notImplemented, getCurrentDirectory: () => currentDirectory, getDirectories: () => [], getCanonicalFileName: fileName => fileName.toLowerCase(), @@ -300,7 +313,7 @@ namespace ts { const path = normalizePath(combinePaths(currentDirectory, fileName)); return path in files; }, - readFile: (fileName): string => { throw new Error("NotImplemented"); } + readFile: notImplemented }; const program = createProgram(rootFiles, options, host); @@ -370,7 +383,7 @@ export = C; return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined; }, getDefaultLibFileName: () => "lib.d.ts", - writeFile: (fileName, content): void => { throw new Error("NotImplemented"); }, + writeFile: notImplemented, getCurrentDirectory: () => currentDirectory, getDirectories: () => [], getCanonicalFileName, @@ -380,7 +393,7 @@ export = C; const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName))); return path in files; }, - readFile: (fileName): string => { throw new Error("NotImplemented"); } + readFile: notImplemented }; const program = createProgram(rootFiles, options, host); const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics().concat(program.getOptionsDiagnostics())); @@ -481,21 +494,15 @@ import b = require("./moduleB"); const options: CompilerOptions = { moduleResolution, baseUrl: "/root" }; { const result = resolveModuleName("folder2/file2", file1.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, file2.name); - assert.deepEqual(result.failedLookupLocations, []); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(file2.name), []); } { const result = resolveModuleName("./file3", file2.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, file3.name); - assert.deepEqual(result.failedLookupLocations, []); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(file3.name), []); } { const result = resolveModuleName("/root/folder1/file1", file2.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, file1.name); - assert.deepEqual(result.failedLookupLocations, []); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(file1.name), []); } } } @@ -520,12 +527,11 @@ import b = require("./moduleB"); check("m1", main, m1); check("m2", main, m2); check("m3", main, m3Typings); - check("m4", main, m4); + check("m4", main, m4, /*isExternalLibraryImport*/true); - function check(name: string, caller: File, expected: File) { + function check(name: string, caller: File, expected: File, isExternalLibraryImport = false) { const result = resolveModuleName(name, caller.name, options, host); - assert.isTrue(result.resolvedModule !== undefined); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); + checkResolvedModule(result.resolvedModule, createResolvedModule(expected.name, isExternalLibraryImport)); } } }); @@ -547,8 +553,7 @@ import b = require("./moduleB"); function check(name: string, caller: File, expected: File) { const result = resolveModuleName(name, caller.name, options, host); - assert.isTrue(result.resolvedModule !== undefined); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); + checkResolvedModule(result.resolvedModule, createResolvedModule(expected.name)); } } }); @@ -590,9 +595,10 @@ import b = require("./moduleB"); "/root/folder1/file2.tsx", "/root/folder1/file2.d.ts", "/root/folder1/file2/package.json", + "/root/folder1/file2/index.ts", "/root/folder1/file2/index.tsx", - "/root/folder1/file2/index.d.ts" + "/root/folder1/file2/index.d.ts", // then first attempt on 'generated/*' was successful ]); check("folder2/file3", file3, [ @@ -601,14 +607,17 @@ import b = require("./moduleB"); "/root/folder2/file3.tsx", "/root/folder2/file3.d.ts", "/root/folder2/file3/package.json", + "/root/folder2/file3/index.ts", "/root/folder2/file3/index.tsx", "/root/folder2/file3/index.d.ts", + // then use remapped location "/root/generated/folder2/file3.ts", "/root/generated/folder2/file3.tsx", "/root/generated/folder2/file3.d.ts", "/root/generated/folder2/file3/package.json", + "/root/generated/folder2/file3/index.ts", "/root/generated/folder2/file3/index.tsx", // success on index.d.ts @@ -619,13 +628,15 @@ import b = require("./moduleB"); "/root/folder2/file4.tsx", "/root/folder2/file4.d.ts", "/root/folder2/file4/package.json", + "/root/folder2/file4/index.ts", "/root/folder2/file4/index.tsx", "/root/folder2/file4/index.d.ts", + // try to load from file from remapped location "/root/generated/folder2/file4.ts", "/root/generated/folder2/file4.tsx", - "/root/generated/folder2/file4.d.ts" + "/root/generated/folder2/file4.d.ts", // success on loading as from folder ]); check("somefolder/file5", file5, [ @@ -634,6 +645,7 @@ import b = require("./moduleB"); "/root/someanotherfolder/file5.ts", "/root/someanotherfolder/file5.tsx", "/root/someanotherfolder/file5.d.ts", + // load from folder "/root/someanotherfolder/file5/package.json", "/root/someanotherfolder/file5/index.ts", @@ -646,46 +658,47 @@ import b = require("./moduleB"); "/root/file6.ts", "/root/file6.tsx", "/root/file6.d.ts", + // load from folder "/root/file6/package.json", "/root/file6/index.ts", "/root/file6/index.tsx", "/root/file6/index.d.ts", + // then try 'generated/*' // load from file "/root/generated/file6.ts", "/root/generated/file6.tsx", "/root/generated/file6.d.ts", + // load from folder "/root/generated/file6/package.json", "/root/generated/file6/index.ts", "/root/generated/file6/index.tsx", "/root/generated/file6/index.d.ts", + // fallback to standard node behavior // load from file "/root/folder1/node_modules/file6.ts", "/root/folder1/node_modules/file6.tsx", "/root/folder1/node_modules/file6.d.ts", + // load from folder "/root/folder1/node_modules/file6/package.json", "/root/folder1/node_modules/file6/index.ts", "/root/folder1/node_modules/file6/index.tsx", "/root/folder1/node_modules/file6/index.d.ts", - "/root/folder1/node_modules/@types/file6.ts", - "/root/folder1/node_modules/@types/file6.tsx", - "/root/folder1/node_modules/@types/file6.d.ts", - "/root/folder1/node_modules/@types/file6/package.json", - "/root/folder1/node_modules/@types/file6/index.ts", - "/root/folder1/node_modules/@types/file6/index.tsx", - "/root/folder1/node_modules/@types/file6/index.d.ts" - // success on /root/node_modules/file6.ts - ]); - function check(name: string, expected: File, expectedFailedLookups: string[]) { + "/root/folder1/node_modules/@types/file6.d.ts", + + "/root/folder1/node_modules/@types/file6/package.json", + "/root/folder1/node_modules/@types/file6/index.d.ts", + // success on /root/node_modules/file6.ts + ], /*isExternalLibraryImport*/ true); + + function check(name: string, expected: File, expectedFailedLookups: string[], isExternalLibraryImport = false) { const result = resolveModuleName(name, main.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); - assert.deepEqual(result.failedLookupLocations, expectedFailedLookups); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(expected.name, isExternalLibraryImport), expectedFailedLookups); } } }); @@ -744,9 +757,7 @@ import b = require("./moduleB"); function check(name: string, expected: File, expectedFailedLookups: string[]) { const result = resolveModuleName(name, main.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); - assert.deepEqual(result.failedLookupLocations, expectedFailedLookups); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(expected.name), expectedFailedLookups); } } }); @@ -819,9 +830,7 @@ import b = require("./moduleB"); function check(name: string, container: File, expected: File, expectedFailedLookups: string[]) { const result = resolveModuleName(name, container.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); - assert.deepEqual(result.failedLookupLocations, expectedFailedLookups); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(expected.name), expectedFailedLookups); } } }); @@ -875,9 +884,7 @@ import b = require("./moduleB"); function check(name: string, container: File, expected: File, expectedFailedLookups: string[]) { const result = resolveModuleName(name, container.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, expected.name); - assert.deepEqual(result.failedLookupLocations, expectedFailedLookups); + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(expected.name), expectedFailedLookups); } } }); @@ -899,9 +906,7 @@ import b = require("./moduleB"); } }; const result = resolveModuleName("libs/guid", app.name, options, host); - assert.isTrue(result.resolvedModule !== undefined, "module should be resolved"); - assert.equal(result.resolvedModule.resolvedFileName, libsTypings.name); - assert.deepEqual(result.failedLookupLocations, [ + checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(libsTypings.name), [ // first try to load module as file "/root/src/libs/guid.ts", "/root/src/libs/guid.tsx", @@ -911,15 +916,11 @@ import b = require("./moduleB"); }); }); - function notImplemented(name: string): () => any { - return () => assert(`${name} is not implemented and should not be called`); - } - describe("ModuleResolutionHost.directoryExists", () => { it("No 'fileExists' calls if containing directory is missing", () => { const host: ModuleResolutionHost = { - readFile: notImplemented("readFile"), - fileExists: notImplemented("fileExists"), + readFile: notImplemented, + fileExists: notImplemented, directoryExists: _ => false }; @@ -1017,14 +1018,12 @@ import b = require("./moduleB"); const files = [f1, f2, f3, f4]; const names = map(files, f => f.name); - const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName); + const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName); const compilerHost: CompilerHost = { fileExists : fileName => fileName in sourceFiles, getSourceFile: fileName => sourceFiles[fileName], getDefaultLibFileName: () => "lib.d.ts", - writeFile(file, text) { - throw new Error("NYI"); - }, + writeFile: notImplemented, getCurrentDirectory: () => "/", getDirectories: () => [], getCanonicalFileName: f => f.toLowerCase(), @@ -1042,5 +1041,69 @@ import b = require("./moduleB"); assert.equal(diagnostics2.length, 1, "expected one diagnostic"); assert.equal(diagnostics1[0].messageText, diagnostics2[0].messageText, "expected one diagnostic"); }); + + it ("Modules in the same .d.ts file are preferred to external files", () => { + const f = { + name: "/a/b/c/c/app.d.ts", + content: ` + declare module "fs" { + export interface Stat { id: number } + } + declare module "fs-client" { + import { Stat } from "fs"; + export function foo(): Stat; + }` + }; + const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); + const compilerHost: CompilerHost = { + fileExists : fileName => fileName === file.fileName, + getSourceFile: fileName => fileName === file.fileName ? file : undefined, + getDefaultLibFileName: () => "lib.d.ts", + writeFile: notImplemented, + getCurrentDirectory: () => "/", + getDirectories: () => [], + getCanonicalFileName: f => f.toLowerCase(), + getNewLine: () => "\r\n", + useCaseSensitiveFileNames: () => false, + readFile: fileName => fileName === file.fileName ? file.text : undefined, + resolveModuleNames() { + assert(false, "resolveModuleNames should not be called"); + return undefined; + } + }; + createProgram([f.name], {}, compilerHost); + }); + + it ("Modules in .ts file are not checked in the same file", () => { + const f = { + name: "/a/b/c/c/app.ts", + content: ` + declare module "fs" { + export interface Stat { id: number } + } + declare module "fs-client" { + import { Stat } from "fs"; + export function foo(): Stat; + }` + }; + const file = createSourceFile(f.name, f.content, ScriptTarget.ES2015); + const compilerHost: CompilerHost = { + fileExists : fileName => fileName === file.fileName, + getSourceFile: fileName => fileName === file.fileName ? file : undefined, + getDefaultLibFileName: () => "lib.d.ts", + writeFile: notImplemented, + getCurrentDirectory: () => "/", + getDirectories: () => [], + getCanonicalFileName: f => f.toLowerCase(), + getNewLine: () => "\r\n", + useCaseSensitiveFileNames: () => false, + readFile: fileName => fileName === file.fileName ? file.text : undefined, + resolveModuleNames(moduleNames: string[], _containingFile: string) { + assert.deepEqual(moduleNames, ["fs"]); + return [undefined]; + } + }; + createProgram([f.name], {}, compilerHost); + }); }); } diff --git a/src/harness/unittests/reuseProgramStructure.ts b/src/harness/unittests/reuseProgramStructure.ts index 60687d34c55..6dbd74e71d2 100644 --- a/src/harness/unittests/reuseProgramStructure.ts +++ b/src/harness/unittests/reuseProgramStructure.ts @@ -22,6 +22,11 @@ namespace ts { interface ProgramWithSourceTexts extends Program { sourceTexts?: NamedSourceText[]; + host: TestCompilerHost; + } + + interface TestCompilerHost extends CompilerHost { + getTrace(): string[]; } class SourceText implements IScriptSnapshot { @@ -101,23 +106,32 @@ namespace ts { return file; } - function createTestCompilerHost(texts: NamedSourceText[], target: ScriptTarget): CompilerHost { - const files = arrayToMap(texts, t => t.name, t => createSourceFileWithText(t.name, t.text, target)); + function createTestCompilerHost(texts: NamedSourceText[], target: ScriptTarget, oldProgram?: ProgramWithSourceTexts): TestCompilerHost { + const files = arrayToMap(texts, t => t.name, t => { + if (oldProgram) { + const oldFile = oldProgram.getSourceFile(t.name); + if (oldFile && oldFile.sourceText.getVersion() === t.text.getVersion()) { + return oldFile; + } + } + return createSourceFileWithText(t.name, t.text, target); + }); + const trace: string[] = []; return { + trace: s => trace.push(s), + getTrace: () => trace, getSourceFile(fileName): SourceFile { return files[fileName]; }, getDefaultLibFileName(): string { return "lib.d.ts"; }, - writeFile(file, text) { - throw new Error("NYI"); - }, + writeFile: notImplemented, getCurrentDirectory(): string { return ""; }, - getDirectories(path: string): string[] { + getDirectories(): string[] { return []; }, getCanonicalFileName(fileName): string { @@ -132,37 +146,28 @@ namespace ts { fileExists: fileName => fileName in files, readFile: fileName => { return fileName in files ? files[fileName].text : undefined; - } + }, }; } - function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions): Program { + function newProgram(texts: NamedSourceText[], rootNames: string[], options: CompilerOptions): ProgramWithSourceTexts { const host = createTestCompilerHost(texts, options.target); const program = createProgram(rootNames, options, host); program.sourceTexts = texts; + program.host = host; return program; } - function updateProgram(oldProgram: Program, rootNames: string[], options: CompilerOptions, updater: (files: NamedSourceText[]) => void) { + function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: string[], options: CompilerOptions, updater: (files: NamedSourceText[]) => void) { const texts: NamedSourceText[] = (oldProgram).sourceTexts.slice(0); updater(texts); - const host = createTestCompilerHost(texts, options.target); + const host = createTestCompilerHost(texts, options.target, oldProgram); const program = createProgram(rootNames, options, host, oldProgram); program.sourceTexts = texts; + program.host = host; return program; } - function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): boolean { - if (!expected === !actual) { - if (expected) { - assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`); - assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`); - } - return true; - } - return false; - } - function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): boolean { if (!expected === !actual) { if (expected) { @@ -244,17 +249,13 @@ namespace ts { it("fails if change affects type references", () => { const program_1 = newProgram(files, ["a.ts"], { types: ["a"] }); - updateProgram(program_1, ["a.ts"], { types: ["b"] }, files => { - - }); + updateProgram(program_1, ["a.ts"], { types: ["b"] }, noop); assert.isTrue(!program_1.structureIsReused); }); it("succeeds if change doesn't affect type references", () => { const program_1 = newProgram(files, ["a.ts"], { types: ["a"] }); - updateProgram(program_1, ["a.ts"], { types: ["a"] }, files => { - - }); + updateProgram(program_1, ["a.ts"], { types: ["a"] }, noop); assert.isTrue(program_1.structureIsReused); }); @@ -280,19 +281,19 @@ namespace ts { it("fails if module kind changes", () => { const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS }); - updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, files => void 0); + updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, noop); assert.isTrue(!program_1.structureIsReused); }); it("fails if rootdir changes", () => { const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" }); - updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, files => void 0); + updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop); assert.isTrue(!program_1.structureIsReused); }); it("fails if config path changes", () => { const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/b/tsconfig.json" }); - updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, files => void 0); + updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, noop); assert.isTrue(!program_1.structureIsReused); }); @@ -306,7 +307,7 @@ namespace ts { const options: CompilerOptions = { target }; const program_1 = newProgram(files, ["a.ts"], options); - checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } })); + checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": createResolvedModule("b.ts") })); checkResolvedModulesCache(program_1, "b.ts", undefined); const program_2 = updateProgram(program_1, ["a.ts"], options, files => { @@ -315,7 +316,7 @@ namespace ts { assert.isTrue(program_1.structureIsReused); // content of resolution cache should not change - checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } })); + checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": createResolvedModule("b.ts") })); checkResolvedModulesCache(program_1, "b.ts", undefined); // imports has changed - program is not reused @@ -332,7 +333,7 @@ namespace ts { files[0].text = files[0].text.updateImportsAndExports(newImports); }); assert.isTrue(!program_3.structureIsReused); - checkResolvedModulesCache(program_4, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" }, "c": undefined })); + checkResolvedModulesCache(program_4, "a.ts", createMap({ "b": createResolvedModule("b.ts"), "c": undefined })); }); it("resolved type directives cache follows type directives", () => { @@ -372,6 +373,88 @@ namespace ts { assert.isTrue(!program_3.structureIsReused); checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } })); }); + + it("can reuse ambient module declarations from non-modified files", () => { + const files = [ + { name: "/a/b/app.ts", text: SourceText.New("", "import * as fs from 'fs'", "") }, + { name: "/a/b/node.d.ts", text: SourceText.New("", "", "declare module 'fs' {}") } + ]; + const options = { target: ScriptTarget.ES2015, traceResolution: true }; + const program = newProgram(files, files.map(f => f.name), options); + assert.deepEqual(program.host.getTrace(), + [ + "======== Resolving module 'fs' from '/a/b/app.ts'. ========", + "Module resolution kind is not specified, using 'Classic'.", + "File '/a/b/fs.ts' does not exist.", + "File '/a/b/fs.tsx' does not exist.", + "File '/a/b/fs.d.ts' does not exist.", + "File '/a/fs.ts' does not exist.", + "File '/a/fs.tsx' does not exist.", + "File '/a/fs.d.ts' does not exist.", + "File '/fs.ts' does not exist.", + "File '/fs.tsx' does not exist.", + "File '/fs.d.ts' does not exist.", + "File '/a/b/node_modules/@types/fs.d.ts' does not exist.", + "File '/a/b/node_modules/@types/fs/package.json' does not exist.", + "File '/a/b/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/a/node_modules/@types/fs.d.ts' does not exist.", + "File '/a/node_modules/@types/fs/package.json' does not exist.", + "File '/a/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/node_modules/@types/fs.d.ts' does not exist.", + "File '/node_modules/@types/fs/package.json' does not exist.", + "File '/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/a/b/fs.js' does not exist.", + "File '/a/b/fs.jsx' does not exist.", + "File '/a/fs.js' does not exist.", + "File '/a/fs.jsx' does not exist.", + "File '/fs.js' does not exist.", + "File '/fs.jsx' does not exist.", + "======== Module name 'fs' was not resolved. ========", + ], "should look for 'fs'"); + + const program_2 = updateProgram(program, program.getRootFileNames(), options, f => { + f[0].text = f[0].text.updateProgram("var x = 1;"); + }); + assert.deepEqual(program_2.host.getTrace(), [ + "Module 'fs' was resolved as ambient module declared in '/a/b/node.d.ts' since this file was not modified." + ], "should reuse 'fs' since node.d.ts was not changed"); + + const program_3 = updateProgram(program_2, program_2.getRootFileNames(), options, f => { + f[0].text = f[0].text.updateProgram("var y = 1;"); + f[1].text = f[1].text.updateProgram("declare var process: any"); + }); + assert.deepEqual(program_3.host.getTrace(), + [ + "======== Resolving module 'fs' from '/a/b/app.ts'. ========", + "Module resolution kind is not specified, using 'Classic'.", + "File '/a/b/fs.ts' does not exist.", + "File '/a/b/fs.tsx' does not exist.", + "File '/a/b/fs.d.ts' does not exist.", + "File '/a/fs.ts' does not exist.", + "File '/a/fs.tsx' does not exist.", + "File '/a/fs.d.ts' does not exist.", + "File '/fs.ts' does not exist.", + "File '/fs.tsx' does not exist.", + "File '/fs.d.ts' does not exist.", + "File '/a/b/node_modules/@types/fs.d.ts' does not exist.", + "File '/a/b/node_modules/@types/fs/package.json' does not exist.", + "File '/a/b/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/a/node_modules/@types/fs.d.ts' does not exist.", + "File '/a/node_modules/@types/fs/package.json' does not exist.", + "File '/a/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/node_modules/@types/fs.d.ts' does not exist.", + "File '/node_modules/@types/fs/package.json' does not exist.", + "File '/node_modules/@types/fs/index.d.ts' does not exist.", + "File '/a/b/fs.js' does not exist.", + "File '/a/b/fs.jsx' does not exist.", + "File '/a/fs.js' does not exist.", + "File '/a/fs.jsx' does not exist.", + "File '/fs.js' does not exist.", + "File '/fs.jsx' does not exist.", + "======== Module name 'fs' was not resolved. ========", + ], "should look for 'fs' again since node.d.ts was changed"); + + }); }); describe("host is optional", () => { diff --git a/src/harness/unittests/services/documentRegistry.ts b/src/harness/unittests/services/documentRegistry.ts index 09e95db6c76..ab624a17dbf 100644 --- a/src/harness/unittests/services/documentRegistry.ts +++ b/src/harness/unittests/services/documentRegistry.ts @@ -62,7 +62,7 @@ describe("DocumentRegistry", () => { const snapshot = ts.ScriptSnapshot.fromString(contents); // Always treat any change as a full change. - snapshot.getChangeRange = old => ts.createTextChangeRange(ts.createTextSpan(0, contents.length), contents.length); + snapshot.getChangeRange = () => ts.createTextChangeRange(ts.createTextSpan(0, contents.length), contents.length); // Simulate one LS getting the document. documentRegistry.acquireDocument("file1.ts", defaultCompilerOptions, snapshot, /* version */ "1"); diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index badbbaf526b..8800e84474b 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -10,41 +10,48 @@ namespace ts.server { useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile(): string { return void 0; }, - writeFile(): void {}, + writeFile: noop, resolvePath(): string { return void 0; }, fileExists: () => false, directoryExists: () => false, getDirectories: () => [], - createDirectory(): void {}, + createDirectory: noop, getExecutingFilePath(): string { return void 0; }, getCurrentDirectory(): string { return void 0; }, - getEnvironmentVariable(name: string): string { return ""; }, + getEnvironmentVariable(): string { return ""; }, readDirectory(): string[] { return []; }, - exit(): void { }, - setTimeout(callback, ms, ...args) { return 0; }, - clearTimeout(timeoutId) { }, + exit: noop, + setTimeout() { return 0; }, + clearTimeout: noop, setImmediate: () => 0, - clearImmediate() {} + clearImmediate: noop, + createHash: s => s }; const nullCancellationToken: HostCancellationToken = { isCancellationRequested: () => false }; const mockLogger: Logger = { - close(): void {}, + close: noop, hasLevel(): boolean { return false; }, loggingEnabled(): boolean { return false; }, - perftrc(s: string): void {}, - info(s: string): void {}, - startGroup(): void {}, - endGroup(): void {}, - msg(s: string, type?: string): void {}, + perftrc: noop, + info: noop, + startGroup: noop, + endGroup: noop, + msg: noop, getLogFileName: (): string => undefined }; + class TestSession extends Session { + getProjectService() { + return this.projectService; + } + } + describe("the Session class", () => { - let session: Session; + let session: TestSession; let lastSent: protocol.Message; beforeEach(() => { - session = new Session(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined, Utils.byteLength, process.hrtime, mockLogger, /*canUseEvents*/ true); + session = new TestSession(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined, Utils.byteLength, process.hrtime, mockLogger, /*canUseEvents*/ true); session.send = (msg: protocol.Message) => { lastSent = msg; }; @@ -55,7 +62,7 @@ namespace ts.server { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, - type: "command", + type: "request", arguments: { file: undefined } @@ -67,7 +74,7 @@ namespace ts.server { const req: protocol.Request = { command: "foobar", seq: 0, - type: "command" + type: "request" }; session.executeCommand(req); @@ -85,7 +92,7 @@ namespace ts.server { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, - type: "command", + type: "request", arguments: { hostInfo: "unit test", formatOptions: { @@ -106,6 +113,48 @@ namespace ts.server { body: undefined }); }); + it ("should handle literal types in request", () => { + const configureRequest: protocol.ConfigureRequest = { + command: CommandNames.Configure, + seq: 0, + type: "request", + arguments: { + formatOptions: { + indentStyle: "Block" + } + } + }; + + session.onMessage(JSON.stringify(configureRequest)); + + assert.equal(session.getProjectService().getFormatCodeOptions().indentStyle, IndentStyle.Block); + + const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { + command: CommandNames.CompilerOptionsForInferredProjects, + seq: 1, + type: "request", + arguments: { + options: { + module: "System", + target: "ES5", + jsx: "React", + newLine: "Lf", + moduleResolution: "Node" + } + } + }; + session.onMessage(JSON.stringify(setOptionsRequest)); + assert.deepEqual( + session.getProjectService().getCompilerOptionsForInferredProjects(), + { + module: ModuleKind.System, + target: ScriptTarget.ES5, + jsx: JsxEmit.React, + newLine: NewLineKind.LineFeed, + moduleResolution: ModuleResolutionKind.NodeJs, + allowNonTsExtensions: true // injected by tsserver + }); + }); }); describe("onMessage", () => { @@ -118,7 +167,7 @@ namespace ts.server { const req: protocol.Request = { command: name, seq: i, - type: "command" + type: "request" }; i++; session.onMessage(JSON.stringify(req)); @@ -151,7 +200,7 @@ namespace ts.server { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, - type: "command", + type: "request", arguments: { hostInfo: "unit test", formatOptions: { @@ -175,7 +224,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: server.protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; @@ -198,12 +247,12 @@ namespace ts.server { responseRequired: true }; - session.addProtocolHandler(command, (req) => result); + session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, - type: "command" + type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { @@ -216,9 +265,9 @@ namespace ts.server { }; const command = "newhandle"; - session.addProtocolHandler(command, (req) => resp); + session.addProtocolHandler(command, () => resp); - expect(() => session.addProtocolHandler(command, (req) => resp)) + expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); @@ -304,7 +353,7 @@ namespace ts.server { expect(session.executeCommand({ seq: 0, - type: "command", + type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, @@ -405,7 +454,7 @@ namespace ts.server { this.seq++; this.server.enqueue({ seq: this.seq, - type: "command", + type: "request", command, arguments: args }); diff --git a/src/harness/unittests/textStorage.ts b/src/harness/unittests/textStorage.ts new file mode 100644 index 00000000000..b4287f2610c --- /dev/null +++ b/src/harness/unittests/textStorage.ts @@ -0,0 +1,70 @@ +/// +/// +/// + +namespace ts.textStorage { + describe("Text storage", () => { + const f = { + path: "/a/app.ts", + content: ` + let x = 1; + let y = 2; + function bar(a: number) { + return a + 1; + }` + }; + + it("text based storage should be have exactly the same as script version cache", () => { + + const host = ts.projectSystem.createServerHost([f]); + + const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path)); + const ts2 = new server.TextStorage(host, server.asNormalizedPath(f.path)); + + ts1.useScriptVersionCache(); + ts2.useText(); + + const lineMap = computeLineStarts(f.content); + + for (let line = 0; line < lineMap.length; line++) { + const start = lineMap[line]; + const end = line === lineMap.length - 1 ? f.path.length : lineMap[line + 1]; + + for (let offset = 0; offset < end - start; offset++) { + const pos1 = ts1.lineOffsetToPosition(line + 1, offset + 1); + const pos2 = ts2.lineOffsetToPosition(line + 1, offset + 1); + assert.isTrue(pos1 === pos2, `lineOffsetToPosition ${line + 1}-${offset + 1}: expected ${pos1} to equal ${pos2}`); + } + + const {start: start1, length: length1 } = ts1.lineToTextSpan(line); + const {start: start2, length: length2 } = ts2.lineToTextSpan(line); + assert.isTrue(start1 === start2, `lineToTextSpan ${line}::start:: expected ${start1} to equal ${start2}`); + assert.isTrue(length1 === length2, `lineToTextSpan ${line}::length:: expected ${length1} to equal ${length2}`); + } + + for (let pos = 0; pos < f.content.length; pos++) { + const { line: line1, offset: offset1 } = ts1.positionToLineOffset(pos); + const { line: line2, offset: offset2 } = ts2.positionToLineOffset(pos); + assert.isTrue(line1 === line2, `positionToLineOffset ${pos}::line:: expected ${line1} to equal ${line2}`); + assert.isTrue(offset1 === offset2, `positionToLineOffset ${pos}::offset:: expected ${offset1} to equal ${offset2}`); + } + }); + + it("should switch to script version cache if necessary", () => { + const host = ts.projectSystem.createServerHost([f]); + const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path)); + + ts1.getSnapshot(); + assert.isTrue(!ts1.hasScriptVersionCache(), "should not have script version cache - 1"); + + ts1.edit(0, 5, " "); + assert.isTrue(ts1.hasScriptVersionCache(), "have script version cache - 1"); + + ts1.useText(); + assert.isTrue(!ts1.hasScriptVersionCache(), "should not have script version cache - 2"); + + ts1.getLineInfo(0); + assert.isTrue(ts1.hasScriptVersionCache(), "have script version cache - 2"); + }) + }); +} \ No newline at end of file diff --git a/src/harness/unittests/transpile.ts b/src/harness/unittests/transpile.ts index 808a5df37c1..20552ab9c2e 100644 --- a/src/harness/unittests/transpile.ts +++ b/src/harness/unittests/transpile.ts @@ -253,6 +253,10 @@ var x = 0;`, { options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } }); + transpilesCorrectly("Supports setting 'alwaysStrict'", "x;", { + options: { compilerOptions: { alwaysStrict: true }, fileName: "input.js", reportDiagnostics: true } + }); + transpilesCorrectly("Supports setting 'baseUrl'", "x;", { options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } }); @@ -381,6 +385,10 @@ var x = 0;`, { options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true } }); + transpilesCorrectly("Supports setting 'jsxFactory'", "x;", { + options: { compilerOptions: { jsxFactory: "createElement" }, fileName: "input.js", reportDiagnostics: true } + }); + transpilesCorrectly("Supports setting 'removeComments'", "x;", { options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true } }); diff --git a/src/harness/unittests/tsconfigParsing.ts b/src/harness/unittests/tsconfigParsing.ts index f38a05b9cfa..7b980cdd2d8 100644 --- a/src/harness/unittests/tsconfigParsing.ts +++ b/src/harness/unittests/tsconfigParsing.ts @@ -28,6 +28,14 @@ namespace ts { assert.isTrue(arrayIsEqualTo(parsed.fileNames.sort(), expectedFileList.sort())); } + function assertParseFileDiagnostics(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedDiagnosticCode: number) { + const json = JSON.parse(jsonText); + const host: ParseConfigHost = new Utils.MockParseConfigHost(basePath, true, allFileList); + const parsed = ts.parseJsonConfigFileContent(json, host, basePath, /*existingOptions*/ undefined, configFileName); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.filter(e => e.code === expectedDiagnosticCode).length > 0, `Expected error code ${expectedDiagnosticCode} to be in ${JSON.stringify(parsed.errors)}`); + } + it("returns empty config for file with only whitespaces", () => { assertParseResult("", { config : {} }); assertParseResult(" ", { config : {} }); @@ -202,5 +210,64 @@ namespace ts { assert.isTrue(diagnostics.length === 2); assert.equal(JSON.stringify(configJsonObject), JSON.stringify(expectedResult)); }); + + it("generates errors for empty files list", () => { + const content = `{ + "files": [] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code); + }); + + it("generates errors for directory with no .ts files", () => { + const content = `{ + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.js"], + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); + }); + + it("generates errors for empty directory", () => { + const content = `{ + "compilerOptions": { + "allowJs": true + } + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + [], + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); + }); + + it("generates errors for empty include", () => { + const content = `{ + "include": [] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); + }); + + it("generates errors for includes with outDir", () => { + const content = `{ + "compilerOptions": { + "outDir": "./" + }, + "include": ["**/*"] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); + }); }); } diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 08e4bac7b2c..d379b5bbf9c 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -18,15 +18,8 @@ namespace ts.projectSystem { }; export interface PostExecAction { - readonly requestKind: TI.RequestKind; - readonly error: Error; - readonly stdout: string; - readonly stderr: string; - readonly callback: (err: Error, stdout: string, stderr: string) => void; - } - - export function notImplemented(): any { - throw new Error("Not yet implemented"); + readonly success: boolean; + readonly callback: TI.RequestCompletedAction; } export const nullLogger: server.Logger = { @@ -53,9 +46,13 @@ namespace ts.projectSystem { export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller { protected projectService: server.ProjectService; - constructor(readonly globalTypingsCacheLocation: string, throttleLimit: number, readonly installTypingHost: server.ServerHost, log?: TI.Log) { - super(globalTypingsCacheLocation, "npm", safeList.path, throttleLimit, log); - this.init(); + constructor( + readonly globalTypingsCacheLocation: string, + throttleLimit: number, + installTypingHost: server.ServerHost, + readonly typesRegistry = createMap(), + log?: TI.Log) { + super(installTypingHost, globalTypingsCacheLocation, safeList.path, throttleLimit, log); } safeFileList = safeList.path; @@ -65,16 +62,15 @@ namespace ts.projectSystem { const actionsToRun = this.postExecActions; this.postExecActions = []; for (const action of actionsToRun) { - action.callback(action.error, action.stdout, action.stderr); + action.callback(action.success); } } - checkPendingCommands(expected: TI.RequestKind[]) { - assert.equal(this.postExecActions.length, expected.length, `Expected ${expected.length} post install actions`); - this.postExecActions.forEach((act, i) => assert.equal(act.requestKind, expected[i], "Unexpected post install action")); + checkPendingCommands(expectedCount: number) { + assert.equal(this.postExecActions.length, expectedCount, `Expected ${expectedCount} post install actions`); } - onProjectClosed(p: server.Project) { + onProjectClosed() { } attach(projectService: server.ProjectService) { @@ -85,34 +81,24 @@ namespace ts.projectSystem { return this.installTypingHost; } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: (err: Error, stdout: string, stderr: string) => void): void { - switch (requestKind) { - case TI.NpmViewRequest: - case TI.NpmInstallRequest: - break; - default: - assert.isTrue(false, `request ${requestKind} is not supported`); - } - this.addPostExecAction(requestKind, "success", cb); + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { + this.addPostExecAction("success", cb); } sendResponse(response: server.SetTypings | server.InvalidateCachedTypings) { this.projectService.updateTypingsForProject(response); } - enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) { - const request = server.createInstallTypingsRequest(project, typingOptions, this.globalTypingsCacheLocation); + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation); this.install(request); } - addPostExecAction(requestKind: TI.RequestKind, stdout: string | string[], cb: TI.RequestCompletedAction) { + addPostExecAction(stdout: string | string[], cb: TI.RequestCompletedAction) { const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout); const action: PostExecAction = { - error: undefined, - stdout: out, - stderr: "", - callback: cb, - requestKind + success: !!out, + callback: cb }; this.postExecActions.push(action); } @@ -126,7 +112,7 @@ namespace ts.projectSystem { return JSON.stringify({ dependencies: dependencies }); } - export function getExecutingFilePathFromLibFile(libFilePath: string): string { + export function getExecutingFilePathFromLibFile(): string { return combinePaths(getDirectoryPath(libFile.path), "tsc.js"); } @@ -139,7 +125,7 @@ namespace ts.projectSystem { } export class TestServerEventManager { - private events: server.ProjectServiceEvent[] = []; + public events: server.ProjectServiceEvent[] = []; handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => { this.events.push(event); @@ -154,31 +140,33 @@ namespace ts.projectSystem { export interface TestServerHostCreationParameters { useCaseSensitiveFileNames?: boolean; executingFilePath?: string; - libFile?: FileOrFolder; currentDirectory?: string; } - export function createServerHost(fileOrFolderList: FileOrFolder[], - params?: TestServerHostCreationParameters, - libFilePath: string = libFile.path): TestServerHost { - + export function createServerHost(fileOrFolderList: FileOrFolder[], params?: TestServerHostCreationParameters): TestServerHost { if (!params) { params = {}; } const host = new TestServerHost( params.useCaseSensitiveFileNames !== undefined ? params.useCaseSensitiveFileNames : false, - params.executingFilePath || getExecutingFilePathFromLibFile(libFilePath), + params.executingFilePath || getExecutingFilePathFromLibFile(), params.currentDirectory || "/", fileOrFolderList); - host.createFileOrFolder(safeList, /*createParentDirectory*/ true); return host; } + class TestSession extends server.Session { + getProjectService() { + return this.projectService; + } + }; + export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller, projectServiceEventHandler?: server.ProjectServiceEventHandler) { if (typingsInstaller === undefined) { typingsInstaller = new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host); } - return new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ projectServiceEventHandler !== undefined, projectServiceEventHandler); + + return new TestSession(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ projectServiceEventHandler !== undefined, projectServiceEventHandler); } export interface CreateProjectServiceParameters { @@ -319,9 +307,9 @@ namespace ts.projectSystem { count() { let n = 0; -/* tslint:disable:no-unused-variable */ for (const _ in this.map) { -/* tslint:enable:no-unused-variable */ + // TODO: GH#11734 + _; n++; } return n; @@ -364,7 +352,8 @@ namespace ts.projectSystem { reloadFS(filesOrFolders: FileOrFolder[]) { this.filesOrFolders = filesOrFolders; this.fs = createFileMap(); - for (const fileOrFolder of filesOrFolders) { + // always inject safelist file in the list of files + for (const fileOrFolder of filesOrFolders.concat(safeList)) { const path = this.toPath(fileOrFolder.path); const fullPath = getNormalizedAbsolutePath(fileOrFolder.path, this.currentDirectory); if (typeof fileOrFolder.content === "string") { @@ -443,6 +432,10 @@ namespace ts.projectSystem { }; } + createHash(s: string): string { + return s; + } + triggerDirectoryWatcherCallback(directoryName: string, fileName: string): void { const path = this.toPath(directoryName); const callbacks = this.watchedDirectories[path]; @@ -470,7 +463,7 @@ namespace ts.projectSystem { } // TOOD: record and invoke callbacks to simulate timer events - setTimeout(callback: TimeOutCallback, time: number, ...args: any[]) { + setTimeout(callback: TimeOutCallback, _time: number, ...args: any[]) { return this.timeoutCallbacks.register(callback, args); }; @@ -487,7 +480,7 @@ namespace ts.projectSystem { this.timeoutCallbacks.invoke(); } - setImmediate(callback: TimeOutCallback, time: number, ...args: any[]) { + setImmediate(callback: TimeOutCallback, _time: number, ...args: any[]) { return this.immediateCallbacks.register(callback, args); } @@ -519,13 +512,14 @@ namespace ts.projectSystem { this.reloadFS(filesOrFolders); } + write() { } + readonly readFile = (s: string) => (this.fs.get(this.toPath(s))).content; readonly resolvePath = (s: string) => s; readonly getExecutingFilePath = () => this.executingFilePath; readonly getCurrentDirectory = () => this.currentDirectory; - readonly write = (s: string) => notImplemented(); - readonly exit = () => notImplemented(); - readonly getEnvironmentVariable = (v: string) => notImplemented(); + readonly exit = notImplemented; + readonly getEnvironmentVariable = notImplemented; } export function makeSessionRequest(command: string, args: T) { @@ -582,6 +576,35 @@ namespace ts.projectSystem { checkWatchedDirectories(host, ["/a/b/c", "/a/b", "/a"]); }); + it("can handle tsconfig file name with difference casing", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ + include: [] + }) + }; + + const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false }); + const service = createProjectService(host); + service.openExternalProject({ + projectFileName: "/a/b/project.csproj", + rootFiles: toExternalFiles([f1.path, combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path))]), + options: {} + }); + service.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects[0], []); + + service.openClientFile(f1.path); + service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 }); + + checkProjectActualFiles(service.configuredProjects[0], []); + checkProjectActualFiles(service.inferredProjects[0], [f1.path]); + }) + it("create configured project without file list", () => { const configFile: FileOrFolder = { path: "/a/b/tsconfig.json", @@ -703,6 +726,66 @@ namespace ts.projectSystem { checkNumberOfInferredProjects(projectService, 1); }); + it("remove not-listed external projects", () => { + const f1 = { + path: "/a/app.ts", + content: "let x = 1" + }; + const f2 = { + path: "/b/app.ts", + content: "let x = 1" + }; + const f3 = { + path: "/c/app.ts", + content: "let x = 1" + }; + const makeProject = (f: FileOrFolder) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} }); + const p1 = makeProject(f1); + const p2 = makeProject(f2); + const p3 = makeProject(f3); + + const host = createServerHost([f1, f2, f3]); + const session = createSession(host); + + session.executeCommand({ + seq: 1, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p1, p2] } + }); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { externalProjects: 2 }); + assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName); + assert.equal(projectService.externalProjects[1].getProjectName(), p2.projectFileName); + + session.executeCommand({ + seq: 2, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p1, p3] } + }); + checkNumberOfProjects(projectService, { externalProjects: 2 }); + assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName); + assert.equal(projectService.externalProjects[1].getProjectName(), p3.projectFileName); + + session.executeCommand({ + seq: 3, + type: "request", + command: "openExternalProjects", + arguments: { projects: [] } + }); + checkNumberOfProjects(projectService, { externalProjects: 0 }); + + session.executeCommand({ + seq: 3, + type: "request", + command: "openExternalProjects", + arguments: { projects: [p2] } + }); + assert.equal(projectService.externalProjects[0].getProjectName(), p2.projectFileName); + }); + it("handle recreated files correctly", () => { const configFile: FileOrFolder = { path: "/a/b/tsconfig.json", @@ -1061,6 +1144,69 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, {}); }); + it("reload regular file after closing", () => { + const f1 = { + path: "/a/b/app.ts", + content: "x." + }; + const f2 = { + path: "/a/b/lib.ts", + content: "let x: number;" + }; + + const host = createServerHost([f1, f2, libFile]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "/a/b/project", rootFiles: toExternalFiles([f1.path, f2.path]), options: {} }) + + service.openClientFile(f1.path); + service.openClientFile(f2.path, "let x: string"); + + service.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); + + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2); + // should contain completions for string + assert.isTrue(completions1.entries.some(e => e.name === "charAt"), "should contain 'charAt'"); + assert.isFalse(completions1.entries.some(e => e.name === "toExponential"), "should not contain 'toExponential'"); + + service.closeClientFile(f2.path); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2); + // should contain completions for string + assert.isFalse(completions2.entries.some(e => e.name === "charAt"), "should not contain 'charAt'"); + assert.isTrue(completions2.entries.some(e => e.name === "toExponential"), "should contain 'toExponential'"); + }); + + it("clear mixed content file after closing", () => { + const f1 = { + path: "/a/b/app.ts", + content: " " + }; + const f2 = { + path: "/a/b/lib.html", + content: "" + }; + + const host = createServerHost([f1, f2, libFile]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "/a/b/project", rootFiles: [{ fileName: f1.path }, { fileName: f2.path, hasMixedContent: true }], options: {} }) + + service.openClientFile(f1.path); + service.openClientFile(f2.path, "let somelongname: string"); + + service.checkNumberOfProjects({ externalProjects: 1 }); + checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); + + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0); + assert.isTrue(completions1.entries.some(e => e.name === "somelongname"), "should contain 'somelongname'"); + + service.closeClientFile(f2.path); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0); + assert.isFalse(completions2.entries.some(e => e.name === "somelongname"), "should not contain 'somelongname'"); + const sf2 = service.externalProjects[0].getLanguageService().getProgram().getSourceFile(f2.path); + assert.equal(sf2.text, ""); + }); + + it("external project with included config file opened after configured project", () => { const file1 = { path: "/a/b/f1.ts", @@ -1092,6 +1238,7 @@ namespace ts.projectSystem { projectService.closeExternalProject(externalProjectName); checkNumberOfProjects(projectService, { configuredProjects: 0 }); }); + it("external project with included config file opened after configured project and then closed", () => { const file1 = { path: "/a/b/f1.ts", @@ -1445,6 +1592,67 @@ namespace ts.projectSystem { checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]); }); + it("tsconfig script block support", () => { + const file1 = { + path: "/a/b/f1.ts", + content: ` ` + }; + const file2 = { + path: "/a/b/f2.html", + content: `var hello = "hello";` + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true } }) + }; + const host = createServerHost([file1, file2, config]); + const session = createSession(host); + openFilesForSession([file1], session); + const projectService = session.getProjectService(); + + // HTML file will not be included in any projects yet + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]); + + // Specify .html extension as mixed content + const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }]; + const configureHostRequest = makeSessionRequest(CommandNames.Configure, { extraFileExtensions }); + session.executeCommand(configureHostRequest).response; + + // HTML file still not included in the project as it is closed + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]); + + // Open HTML file + projectService.applyChangesInOpenFiles( + /*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }], + /*changedFiles*/undefined, + /*closedFiles*/undefined); + + // Now HTML file is included in the project + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]); + + // Check identifiers defined in HTML content are available in .ts file + const project = projectService.configuredProjects[0]; + let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1); + assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`); + + // Close HTML file + projectService.applyChangesInOpenFiles( + /*openFiles*/undefined, + /*changedFiles*/undefined, + /*closedFiles*/[file2.path]); + + // HTML file is still included in project + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]); + + // Check identifiers defined in HTML content are not available in .ts file + completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5); + assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`); + }); + it("project structure update is deferred if files are not added\removed", () => { const file1 = { path: "/a/b/f1.ts", @@ -1490,7 +1698,7 @@ namespace ts.projectSystem { const project = projectService.externalProjects[0]; const scriptInfo = project.getScriptInfo(file1.path); - const snap = scriptInfo.snap(); + const snap = scriptInfo.getSnapshot(); const actualText = snap.getText(0, snap.getLength()); assert.equal(actualText, "", `expected content to be empty string, got "${actualText}"`); @@ -1503,7 +1711,7 @@ namespace ts.projectSystem { projectService.closeClientFile(file1.path); const scriptInfo2 = project.getScriptInfo(file1.path); - const snap2 = scriptInfo2.snap(); + const snap2 = scriptInfo2.getSnapshot(); const actualText2 = snap2.getText(0, snap.getLength()); assert.equal(actualText2, "", `expected content to be empty string, got "${actualText2}"`); }); @@ -1589,6 +1797,208 @@ namespace ts.projectSystem { projectService.closeClientFile(file1.path); checkNumberOfProjects(projectService, { configuredProjects: 0 }); }); + + it("language service disabled state is updated in external projects", () => { + const f1 = { + path: "/a/app.js", + content: "var x = 1" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const host = createServerHost([f1, f2]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + const service = createProjectService(host); + const projectFileName = "/a/proj.csproj"; + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 1"); + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isTrue(service.externalProjects[0].languageServiceEnabled, "language service should be enabled"); + + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([f1.path, f2.path]), + options: {} + }); + service.checkNumberOfProjects({ externalProjects: 1 }); + assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 2"); + }); + + it("files are properly detached when language service is disabled", () => { + const f1 = { + path: "/a/app.js", + content: "var x = 1" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const f3 = { + path: "/a/lib.js", + content: "var x = 1" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ compilerOptions: { allowJs: true } }) + }; + const host = createServerHost([f1, f2, f3, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + const projectService = createProjectService(host); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + + projectService.closeClientFile(f1.path); + projectService.checkNumberOfProjects({}); + + for (const f of [f2, f3]) { + const scriptInfo = projectService.getScriptInfoForNormalizedPath(server.toNormalizedPath(f.path)); + assert.equal(scriptInfo.containingProjects.length, 0, `expect 0 containing projects for '${f.path}'`) + } + }); + + it("language service disabled events are triggered", () => { + const f1 = { + path: "/a/app.js", + content: "let x = 1;" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const config = { + path: "/a/jsconfig.json", + content: "{}" + }; + const configWithExclude = { + path: config.path, + content: JSON.stringify({ exclude: ["largefile.js"] }) + }; + const host = createServerHost([f1, f2, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + + let lastEvent: server.ProjectLanguageServiceStateEvent; + const session = createSession(host, /*typingsInstaller*/ undefined, e => { + if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ContextEvent) { + return; + } + assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); + assert.equal(e.data.project.getProjectName(), config.path, "project name"); + lastEvent = e; + }); + session.executeCommand({ + seq: 0, + type: "request", + command: "open", + arguments: { file: f1.path } + }); + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects[0]; + assert.isFalse(project.languageServiceEnabled, "Language service enabled"); + assert.isTrue(!!lastEvent, "should receive event"); + assert.equal(lastEvent.data.project, project, "project name"); + assert.equal(lastEvent.data.project.getProjectName(), config.path, "config path"); + assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + + host.reloadFS([f1, f2, configWithExclude]); + host.triggerFileWatcherCallback(config.path, /*removed*/ false); + + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + assert.isTrue(project.languageServiceEnabled, "Language service enabled"); + assert.equal(lastEvent.data.project, project, "project"); + assert.isTrue(lastEvent.data.languageServiceEnabled, "Language service state"); + }); + + it("syntactic features work even if language service is disabled", () => { + const f1 = { + path: "/a/app.js", + content: "let x = 1;" + }; + const f2 = { + path: "/a/largefile.js", + content: "" + }; + const config = { + path: "/a/jsconfig.json", + content: "{}" + }; + const host = createServerHost([f1, f2, config]); + const originalGetFileSize = host.getFileSize; + host.getFileSize = (filePath: string) => + filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + let lastEvent: server.ProjectLanguageServiceStateEvent; + const session = createSession(host, /*typingsInstaller*/ undefined, e => { + if (e.eventName === server.ConfigFileDiagEvent) { + return; + } + assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); + lastEvent = e; + }); + session.executeCommand({ + seq: 0, + type: "request", + command: "open", + arguments: { file: f1.path } + }); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { configuredProjects: 1 }); + const project = projectService.configuredProjects[0]; + assert.isFalse(project.languageServiceEnabled, "Language service enabled"); + assert.isTrue(!!lastEvent, "should receive event"); + assert.equal(lastEvent.data.project, project, "project name"); + assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + + const options = projectService.getFormatCodeOptions(); + const edits = project.getLanguageService().getFormattingEditsForDocument(f1.path, options); + assert.deepEqual(edits, [{ span: createTextSpan(/*start*/ 7, /*length*/ 3), newText: " " }]); + }); + + it("snapshot from different caches are incompatible", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1;" + }; + const host = createServerHost([f1]); + const projectFileName = "/a/b/proj.csproj"; + const projectService = createProjectService(host); + projectService.openExternalProject({ + projectFileName, + rootFiles: [toExternalFile(f1.path)], + options: {} + }) + projectService.openClientFile(f1.path, "let x = 1;\nlet y = 2;"); + + projectService.checkNumberOfProjects({ externalProjects: 1 }); + projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/false).getNavigationBarItems(f1.path); + projectService.closeClientFile(f1.path); + + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ externalProjects: 1 }); + const navbar = projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/false).getNavigationBarItems(f1.path); + assert.equal(navbar[0].spans[0].length, f1.content.length); + }); }); describe("Proper errors", () => { @@ -1630,8 +2040,8 @@ namespace ts.projectSystem { options: {} }); projectService.checkNumberOfProjects({ externalProjects: 1 }); - const typingOptions = projectService.externalProjects[0].getTypingOptions(); - assert.isTrue(typingOptions.enableAutoDiscovery, "Typing autodiscovery should be enabled"); + const typeAcquisition = projectService.externalProjects[0].getTypeAcquisition(); + assert.isTrue(typeAcquisition.enable, "Typine acquisition should be enabled"); }); }); @@ -1662,90 +2072,56 @@ namespace ts.projectSystem { "File '/a/b/node_modules/lib.ts' does not exist.", "File '/a/b/node_modules/lib.tsx' does not exist.", "File '/a/b/node_modules/lib.d.ts' does not exist.", - "File '/a/b/node_modules/lib.js' does not exist.", - "File '/a/b/node_modules/lib.jsx' does not exist.", "File '/a/b/node_modules/lib/package.json' does not exist.", "File '/a/b/node_modules/lib/index.ts' does not exist.", "File '/a/b/node_modules/lib/index.tsx' does not exist.", "File '/a/b/node_modules/lib/index.d.ts' does not exist.", - "File '/a/b/node_modules/lib/index.js' does not exist.", - "File '/a/b/node_modules/lib/index.jsx' does not exist.", - "File '/a/b/node_modules/@types/lib.ts' does not exist.", - "File '/a/b/node_modules/@types/lib.tsx' does not exist.", "File '/a/b/node_modules/@types/lib.d.ts' does not exist.", - "File '/a/b/node_modules/@types/lib.js' does not exist.", - "File '/a/b/node_modules/@types/lib.jsx' does not exist.", "File '/a/b/node_modules/@types/lib/package.json' does not exist.", - "File '/a/b/node_modules/@types/lib/index.ts' does not exist.", - "File '/a/b/node_modules/@types/lib/index.tsx' does not exist.", "File '/a/b/node_modules/@types/lib/index.d.ts' does not exist.", - "File '/a/b/node_modules/@types/lib/index.js' does not exist.", - "File '/a/b/node_modules/@types/lib/index.jsx' does not exist.", "File '/a/node_modules/lib.ts' does not exist.", "File '/a/node_modules/lib.tsx' does not exist.", "File '/a/node_modules/lib.d.ts' does not exist.", - "File '/a/node_modules/lib.js' does not exist.", - "File '/a/node_modules/lib.jsx' does not exist.", "File '/a/node_modules/lib/package.json' does not exist.", "File '/a/node_modules/lib/index.ts' does not exist.", "File '/a/node_modules/lib/index.tsx' does not exist.", "File '/a/node_modules/lib/index.d.ts' does not exist.", - "File '/a/node_modules/lib/index.js' does not exist.", - "File '/a/node_modules/lib/index.jsx' does not exist.", - "File '/a/node_modules/@types/lib.ts' does not exist.", - "File '/a/node_modules/@types/lib.tsx' does not exist.", "File '/a/node_modules/@types/lib.d.ts' does not exist.", - "File '/a/node_modules/@types/lib.js' does not exist.", - "File '/a/node_modules/@types/lib.jsx' does not exist.", "File '/a/node_modules/@types/lib/package.json' does not exist.", - "File '/a/node_modules/@types/lib/index.ts' does not exist.", - "File '/a/node_modules/@types/lib/index.tsx' does not exist.", "File '/a/node_modules/@types/lib/index.d.ts' does not exist.", - "File '/a/node_modules/@types/lib/index.js' does not exist.", - "File '/a/node_modules/@types/lib/index.jsx' does not exist.", "File '/node_modules/lib.ts' does not exist.", "File '/node_modules/lib.tsx' does not exist.", "File '/node_modules/lib.d.ts' does not exist.", - "File '/node_modules/lib.js' does not exist.", - "File '/node_modules/lib.jsx' does not exist.", "File '/node_modules/lib/package.json' does not exist.", "File '/node_modules/lib/index.ts' does not exist.", "File '/node_modules/lib/index.tsx' does not exist.", "File '/node_modules/lib/index.d.ts' does not exist.", + "File '/node_modules/@types/lib.d.ts' does not exist.", + "File '/node_modules/@types/lib/package.json' does not exist.", + "File '/node_modules/@types/lib/index.d.ts' does not exist.", + "Loading module 'lib' from 'node_modules' folder.", + "File '/a/b/node_modules/lib.js' does not exist.", + "File '/a/b/node_modules/lib.jsx' does not exist.", + "File '/a/b/node_modules/lib/package.json' does not exist.", + "File '/a/b/node_modules/lib/index.js' does not exist.", + "File '/a/b/node_modules/lib/index.jsx' does not exist.", + "File '/a/node_modules/lib.js' does not exist.", + "File '/a/node_modules/lib.jsx' does not exist.", + "File '/a/node_modules/lib/package.json' does not exist.", + "File '/a/node_modules/lib/index.js' does not exist.", + "File '/a/node_modules/lib/index.jsx' does not exist.", + "File '/node_modules/lib.js' does not exist.", + "File '/node_modules/lib.jsx' does not exist.", + "File '/node_modules/lib/package.json' does not exist.", "File '/node_modules/lib/index.js' does not exist.", "File '/node_modules/lib/index.jsx' does not exist.", - "File '/node_modules/@types/lib.ts' does not exist.", - "File '/node_modules/@types/lib.tsx' does not exist.", - "File '/node_modules/@types/lib.d.ts' does not exist.", - "File '/node_modules/@types/lib.js' does not exist.", - "File '/node_modules/@types/lib.jsx' does not exist.", - "File '/node_modules/@types/lib/package.json' does not exist.", - "File '/node_modules/@types/lib/index.ts' does not exist.", - "File '/node_modules/@types/lib/index.tsx' does not exist.", - "File '/node_modules/@types/lib/index.d.ts' does not exist.", - "File '/node_modules/@types/lib/index.js' does not exist.", - "File '/node_modules/@types/lib/index.jsx' does not exist.", "======== Module name 'lib' was not resolved. ========", `Auto discovery for typings is enabled in project '${proj.getProjectName()}'. Running extra resolution pass for module 'lib' using cache location '/a/cache'.`, - "File '/a/cache/node_modules/lib.ts' does not exist.", - "File '/a/cache/node_modules/lib.tsx' does not exist.", "File '/a/cache/node_modules/lib.d.ts' does not exist.", - "File '/a/cache/node_modules/lib.js' does not exist.", - "File '/a/cache/node_modules/lib.jsx' does not exist.", "File '/a/cache/node_modules/lib/package.json' does not exist.", - "File '/a/cache/node_modules/lib/index.ts' does not exist.", - "File '/a/cache/node_modules/lib/index.tsx' does not exist.", "File '/a/cache/node_modules/lib/index.d.ts' does not exist.", - "File '/a/cache/node_modules/lib/index.js' does not exist.", - "File '/a/cache/node_modules/lib/index.jsx' does not exist.", - "File '/a/cache/node_modules/@types/lib.ts' does not exist.", - "File '/a/cache/node_modules/@types/lib.tsx' does not exist.", "File '/a/cache/node_modules/@types/lib.d.ts' does not exist.", - "File '/a/cache/node_modules/@types/lib.js' does not exist.", - "File '/a/cache/node_modules/@types/lib.jsx' does not exist.", "File '/a/cache/node_modules/@types/lib/package.json' does not exist.", - "File '/a/cache/node_modules/@types/lib/index.ts' does not exist.", - "File '/a/cache/node_modules/@types/lib/index.tsx' does not exist.", "File '/a/cache/node_modules/@types/lib/index.d.ts' exist - use it as a name resolution result.", ]); checkProjectActualFiles(proj, [file1.path, lib.path]); @@ -1971,6 +2347,33 @@ namespace ts.projectSystem { projectService.checkNumberOfProjects({ configuredProjects: 1 }); checkProjectActualFiles(projectService.configuredProjects[0], [libES5.path, libES2015Promise.path, app.path]); }); + + it("should handle non-existing directories in config file", () => { + const f = { + path: "/a/src/app.ts", + content: "let x = 1;" + }; + const config = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: {}, + include: [ + "src/**/*", + "notexistingfolder/*" + ] + }) + }; + const host = createServerHost([f, config]); + const projectService = createProjectService(host); + projectService.openClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + + projectService.closeClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 0 }); + + projectService.openClientFile(f.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + }); }); describe("prefer typings to js", () => { @@ -2108,13 +2511,13 @@ namespace ts.projectSystem { p.updateGraph(); const scriptInfo = p.getScriptInfo(f.path); - checkSnapLength(scriptInfo.snap(), f.content.length); + checkSnapLength(scriptInfo.getSnapshot(), f.content.length); // open project and replace its content with empty string projectService.openClientFile(f.path, ""); - checkSnapLength(scriptInfo.snap(), 0); + checkSnapLength(scriptInfo.getSnapshot(), 0); }); - function checkSnapLength(snap: server.LineIndexSnapshot, expectedLength: number) { + function checkSnapLength(snap: IScriptSnapshot, expectedLength: number) { assert.equal(snap.getLength(), expectedLength, "Incorrect snapshot size"); } }); @@ -2229,6 +2632,50 @@ namespace ts.projectSystem { assert.equal(diags.length, 0); }); + it("should property handle missing config files", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: "{}" + }; + const projectName = "project1"; + const host = createServerHost([f1]); + const projectService = createProjectService(host); + projectService.openExternalProject({ rootFiles: toExternalFiles([f1.path, config.path]), options: {}, projectFileName: projectName }); + + // should have one external project since config file is missing + projectService.checkNumberOfProjects({ externalProjects: 1 }); + + host.reloadFS([f1, config]); + projectService.openExternalProject({ rootFiles: toExternalFiles([f1.path, config.path]), options: {}, projectFileName: projectName }); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + }); + + it("types should load from config file path if config exists", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const config = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: [] } }) + }; + const node = { + path: "/a/b/node_modules/@types/node/index.d.ts", + content: "declare var process: any" + }; + const cwd = { + path: "/a/c" + }; + const host = createServerHost([f1, config, node, cwd], { currentDirectory: cwd.path }); + const projectService = createProjectService(host); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); + checkProjectActualFiles(projectService.configuredProjects[0], [f1.path, node.path]); + }); }); describe("add the missing module file for inferred project", () => { @@ -2290,6 +2737,14 @@ namespace ts.projectSystem { const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler); openFilesForSession([file], session); serverEventManager.checkEventCountOfType("configFileDiag", 1); + + for (const event of serverEventManager.events) { + if (event.eventName === "configFileDiag") { + assert.equal(event.data.configFileName, configFile.path); + assert.equal(event.data.triggerFile, file.path); + return; + } + } }); it("are generated when the config file doesn't have errors", () => { @@ -2310,6 +2765,43 @@ namespace ts.projectSystem { openFilesForSession([file], session); serverEventManager.checkEventCountOfType("configFileDiag", 1); }); + + it("are generated when the config file changes", () => { + const serverEventManager = new TestServerEventManager(); + const file = { + path: "/a/b/app.ts", + content: "let x = 10" + }; + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {} + }` + }; + + const host = createServerHost([file, configFile]); + const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler); + openFilesForSession([file], session); + serverEventManager.checkEventCountOfType("configFileDiag", 1); + + configFile.content = `{ + "compilerOptions": { + "haha": 123 + } + }`; + host.reloadFS([file, configFile]); + host.triggerFileWatcherCallback(configFile.path); + host.runQueuedTimeoutCallbacks(); + serverEventManager.checkEventCountOfType("configFileDiag", 2); + + configFile.content = `{ + "compilerOptions": {} + }`; + host.reloadFS([file, configFile]); + host.triggerFileWatcherCallback(configFile.path); + host.runQueuedTimeoutCallbacks(); + serverEventManager.checkEventCountOfType("configFileDiag", 3); + }); }); describe("skipLibCheck", () => { @@ -2387,4 +2879,216 @@ namespace ts.projectSystem { assert.isTrue(errorResult.length === 0); }); }); + + describe("non-existing directories listed in config file input array", () => { + it("should be tolerated without crashing the server", () => { + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "include": ["app/*", "test/**/*", "something"] + }` + }; + const file1 = { + path: "/a/b/file1.ts", + content: "let t = 10;" + }; + + const host = createServerHost([file1, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + host.runQueuedTimeoutCallbacks(); + checkNumberOfConfiguredProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 1); + + const configuredProject = projectService.configuredProjects[0]; + assert.isTrue(configuredProject.getFileNames().length == 0); + + const inferredProject = projectService.inferredProjects[0]; + assert.isTrue(inferredProject.containsFile(file1.path)); + }); + }); + + describe("reload", () => { + it("should work with temp file", () => { + const f1 = { + path: "/a/b/app.ts", + content: "let x = 1" + }; + const tmp = { + path: "/a/b/app.tmp", + content: "const y = 42" + }; + const host = createServerHost([f1, tmp]); + const session = createSession(host); + + // send open request + session.executeCommand({ + type: "request", + command: "open", + seq: 1, + arguments: { file: f1.path } + }); + + // reload from tmp file + session.executeCommand({ + type: "request", + command: "reload", + seq: 2, + arguments: { file: f1.path, tmpfile: tmp.path } + }); + + // verify content + const projectServiice = session.getProjectService(); + const snap1 = projectServiice.getScriptInfo(f1.path).getSnapshot(); + assert.equal(snap1.getText(0, snap1.getLength()), tmp.content, "content should be equal to the content of temp file"); + + // reload from original file file + session.executeCommand({ + type: "request", + command: "reload", + seq: 2, + arguments: { file: f1.path } + }); + + // verify content + const snap2 = projectServiice.getScriptInfo(f1.path).getSnapshot(); + assert.equal(snap2.getText(0, snap2.getLength()), f1.content, "content should be equal to the content of original file"); + + }); + }); + + describe("Inferred projects", () => { + it("should support files without extensions", () => { + const f = { + path: "/a/compile", + content: "let x = 1" + }; + const host = createServerHost([f]); + const session = createSession(host); + session.executeCommand({ + seq: 1, + type: "request", + command: "compilerOptionsForInferredProjects", + arguments: { + options: { + allowJs: true + } + } + }); + session.executeCommand({ + seq: 2, + type: "request", + command: "open", + arguments: { + file: f.path, + fileContent: f.content, + scriptKindName: "JS" + } + }); + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [f.path]); + }); + }); + + describe("No overwrite emit error", () => { + it("for inferred project", () => { + const f1 = { + path: "/a/b/f1.js", + content: "function test1() { }" + }; + const host = createServerHost([f1, libFile]); + const session = createSession(host); + openFilesForSession([f1], session); + + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const projectName = projectService.inferredProjects[0].getProjectName(); + + const diags = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName: projectName } + }).response; + assert.isTrue(diags.length === 0); + + session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsForInferredProjects, + seq: 3, + arguments: { options: { module: ModuleKind.CommonJS } } + }); + const diagsAfterUpdate = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 4, + arguments: { projectFileName: projectName } + }).response; + assert.isTrue(diagsAfterUpdate.length === 0); + }); + + it("for external project", () => { + const f1 = { + path: "/a/b/f1.js", + content: "function test1() { }" + }; + const host = createServerHost([f1, libFile]); + const session = createSession(host); + const projectService = session.getProjectService(); + const projectFileName = "/a/b/project.csproj"; + const externalFiles = toExternalFiles([f1.path]); + projectService.openExternalProject({ + projectFileName, + rootFiles: externalFiles, + options: {} + }); + + checkNumberOfProjects(projectService, { externalProjects: 1 }); + + const diags = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 2, + arguments: { projectFileName } + }).response; + assert.isTrue(diags.length === 0); + + session.executeCommand({ + type: "request", + command: server.CommandNames.OpenExternalProject, + seq: 3, + arguments: { + projectFileName, + rootFiles: externalFiles, + options: { module: ModuleKind.CommonJS } + } + }); + const diagsAfterUpdate = session.executeCommand({ + type: "request", + command: server.CommandNames.CompilerOptionsDiagnosticsFull, + seq: 4, + arguments: { projectFileName } + }).response; + assert.isTrue(diagsAfterUpdate.length === 0); + }); + }); + + describe("import helpers", () => { + it("should not crash in tsserver", () => { + const f1 = { + path: "/a/app.ts", + content: "export async function foo() { return 100; }" + }; + const tslib = { + path: "/a/node_modules/tslib/index.d.ts", + content: "" + }; + const host = createServerHost([f1, tslib]); + const service = createProjectService(host); + service.openExternalProject({ projectFileName: "p", rootFiles: [toExternalFile(f1.path)], options: { importHelpers: true } }); + service.checkNumberOfProjects({ externalProjects: 1 }); + }); + }); } \ No newline at end of file diff --git a/src/harness/unittests/typingsInstaller.ts b/src/harness/unittests/typingsInstaller.ts index d79a1a7723c..62d2f7ac801 100644 --- a/src/harness/unittests/typingsInstaller.ts +++ b/src/harness/unittests/typingsInstaller.ts @@ -8,6 +8,15 @@ namespace ts.projectSystem { interface InstallerParams { globalTypingsCacheLocation?: string; throttleLimit?: number; + typesRegistry?: Map; + } + + function createTypesRegistry(...list: string[]): Map { + const map = createMap(); + for (const l of list) { + map[l] = undefined; + } + return map; } class Installer extends TestTypingsInstaller { @@ -16,36 +25,26 @@ namespace ts.projectSystem { (p && p.globalTypingsCacheLocation) || "/a/data", (p && p.throttleLimit) || 5, host, + (p && p.typesRegistry), log); } - installAll(expectedView: typeof TI.NpmViewRequest[], expectedInstall: typeof TI.NpmInstallRequest[]) { - this.checkPendingCommands(expectedView); - this.executePendingCommands(); - this.checkPendingCommands(expectedInstall); + installAll(expectedCount: number) { + this.checkPendingCommands(expectedCount); this.executePendingCommands(); } } - describe("typingsInstaller", () => { - function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[], typingFiles: FileOrFolder[], requestKind: TI.RequestKind, cb: TI.RequestCompletedAction): void { - switch (requestKind) { - case TI.NpmInstallRequest: - self.addPostExecAction(requestKind, installedTypings, (err, stdout, stderr) => { - for (const file of typingFiles) { - host.createFileOrFolder(file, /*createParentDirectory*/ true); - } - cb(err, stdout, stderr); - }); - break; - case TI.NpmViewRequest: - self.addPostExecAction(requestKind, installedTypings, cb); - break; - default: - assert.isTrue(false, `unexpected request kind ${requestKind}`); - break; + function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[] | string, typingFiles: FileOrFolder[], cb: TI.RequestCompletedAction): void { + self.addPostExecAction(installedTypings, success => { + for (const file of typingFiles) { + host.createFileOrFolder(file, /*createParentDirectory*/ true); } - } + cb(success); + }); + } + + describe("typingsInstaller", () => { it("configured projects (typings installed) 1", () => { const file1 = { path: "/a/b/app.js", @@ -57,8 +56,8 @@ namespace ts.projectSystem { compilerOptions: { allowJs: true }, - typingOptions: { - enableAutoDiscovery: true + typeAcquisition: { + enable: true } }) }; @@ -79,12 +78,12 @@ namespace ts.projectSystem { const host = createServerHost([file1, tsconfig, packageJson]); const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jquery]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -95,7 +94,7 @@ namespace ts.projectSystem { const p = projectService.configuredProjects[0]; checkProjectActualFiles(p, [file1.path]); - installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { configuredProjects: 1 }); checkProjectActualFiles(p, [file1.path, jquery.path]); @@ -123,12 +122,12 @@ namespace ts.projectSystem { const host = createServerHost([file1, packageJson]); const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jquery]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -139,13 +138,13 @@ namespace ts.projectSystem { const p = projectService.inferredProjects[0]; checkProjectActualFiles(p, [file1.path]); - installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { inferredProjects: 1 }); checkProjectActualFiles(p, [file1.path, jquery.path]); }); - it("external project - no typing options, no .d.ts/js files", () => { + it("external project - no type acquisition, no .d.ts/js files", () => { const file1 = { path: "/a/b/app.ts", content: "" @@ -167,13 +166,13 @@ namespace ts.projectSystem { options: {}, rootFiles: [toExternalFile(file1.path)] }); - installer.checkPendingCommands([]); + installer.checkPendingCommands(/*expectedCount*/ 0); // by default auto discovery will kick in if project contain only .js/.d.ts files // in this case project contain only ts files - no auto discovery projectService.checkNumberOfProjects({ externalProjects: 1 }); }); - it("external project - no autoDiscovery in typing options, no .d.ts/js files", () => { + it("external project - no auto in typing acquisition, no .d.ts/js files", () => { const file1 = { path: "/a/b/app.ts", content: "" @@ -181,7 +180,7 @@ namespace ts.projectSystem { const host = createServerHost([file1]); const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery") }); } enqueueInstallTypingsRequest() { assert(false, "auto discovery should not be enabled"); @@ -194,11 +193,11 @@ namespace ts.projectSystem { projectFileName, options: {}, rootFiles: [toExternalFile(file1.path)], - typingOptions: { include: ["jquery"] } + typeAcquisition: { include: ["jquery"] } }); - installer.checkPendingCommands([]); + installer.checkPendingCommands(/*expectedCount*/ 0); // by default auto discovery will kick in if project contain only .js/.d.ts files - // in this case project contain only ts files - no auto discovery even if typing options is set + // in this case project contain only ts files - no auto discovery even if type acquisition is set projectService.checkNumberOfProjects({ externalProjects: 1 }); }); @@ -215,16 +214,16 @@ namespace ts.projectSystem { let enqueueIsCalled = false; const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { enqueueIsCalled = true; - super.enqueueInstallTypingsRequest(project, typingOptions); + super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { - const installedTypings = ["@types/jquery"]; + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { + const installedTypings = ["@types/node"]; const typingFiles = [jquery]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -234,17 +233,17 @@ namespace ts.projectSystem { projectFileName, options: {}, rootFiles: [toExternalFile(file1.path)], - typingOptions: { enableAutoDiscovery: true, include: ["node"] } + typeAcquisition: { enable: true, include: ["jquery"] } }); assert.isTrue(enqueueIsCalled, "expected enqueueIsCalled to be true"); - installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]); + installer.installAll(/*expectedCount*/ 1); - // autoDiscovery is set in typing options - use it even if project contains only .ts files + // auto is set in type acquisition - use it even if project contains only .ts files projectService.checkNumberOfProjects({ externalProjects: 1 }); }); - it("external project - no typing options, with only js, jsx, d.ts files", () => { + it("external project - no type acquisition, with only js, jsx, d.ts files", () => { // Tests: // 1. react typings are installed for .jsx // 2. loose files names are matched against safe list for typings if @@ -273,12 +272,12 @@ namespace ts.projectSystem { const host = createServerHost([file1, file2, file3]); const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("lodash", "react") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/lodash", "@types/react"]; const typingFiles = [lodash, react]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -288,20 +287,20 @@ namespace ts.projectSystem { projectFileName, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)], - typingOptions: {} + typeAcquisition: {} }); const p = projectService.externalProjects[0]; projectService.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path, file3.path]); - installer.installAll([TI.NpmViewRequest, TI.NpmViewRequest], [TI.NpmInstallRequest], ); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path, file3.path, lodash.path, react.path]); }); - it("external project - no typing options, with js & ts files", () => { + it("external project - no type acquisition, with js & ts files", () => { // Tests: // 1. No typings are included for JS projects when the project contains ts files const file1 = { @@ -317,16 +316,16 @@ namespace ts.projectSystem { let enqueueIsCalled = false; const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { enqueueIsCalled = true; - super.enqueueInstallTypingsRequest(project, typingOptions); + super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings: string[] = []; const typingFiles: FileOrFolder[] = []; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -336,24 +335,24 @@ namespace ts.projectSystem { projectFileName, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path)], - typingOptions: {} + typeAcquisition: {} }); const p = projectService.externalProjects[0]; projectService.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path]); - installer.checkPendingCommands([]); + installer.checkPendingCommands(/*expectedCount*/ 0); checkNumberOfProjects(projectService, { externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path]); }); - it("external project - with typing options, with only js, d.ts files", () => { + it("external project - with type acquisition, with only js, d.ts files", () => { // Tests: - // 1. Safelist matching, typing options includes/excludes and package.json typings are all acquired - // 2. Types for safelist matches are not included when they also appear in the typing option exclude list - // 3. Multiple includes and excludes are respected in typing options + // 1. Safelist matching, type acquisition includes/excludes and package.json typings are all acquired + // 2. Types for safelist matches are not included when they also appear in the type acquisition exclude list + // 3. Multiple includes and excludes are respected in type acquisition const file1 = { path: "/a/b/lodash.js", content: "" @@ -396,12 +395,12 @@ namespace ts.projectSystem { const host = createServerHost([file1, file2, file3, packageJson]); const installer = new (class extends Installer { constructor() { - super(host); + super(host, { typesRegistry: createTypesRegistry("jquery", "commander", "moment", "express") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment"]; const typingFiles = [commander, express, jquery, moment]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -411,17 +410,14 @@ namespace ts.projectSystem { projectFileName, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)], - typingOptions: { include: ["jquery", "moment"], exclude: ["lodash"] } + typeAcquisition: { include: ["jquery", "moment"], exclude: ["lodash"] } }); const p = projectService.externalProjects[0]; projectService.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path, file3.path]); - installer.installAll( - [TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest], - [TI.NpmInstallRequest] - ); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { externalProjects: 1 }); checkProjectActualFiles(p, [file1.path, file2.path, file3.path, commander.path, express.path, jquery.path, moment.path]); @@ -475,11 +471,11 @@ namespace ts.projectSystem { const host = createServerHost([lodashJs, commanderJs, file3, packageJson]); const installer = new (class extends Installer { constructor() { - super(host, { throttleLimit: 3 }); + super(host, { throttleLimit: 3, typesRegistry: createTypesRegistry("commander", "express", "jquery", "moment", "lodash") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment", "@types/lodash"]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -489,24 +485,13 @@ namespace ts.projectSystem { projectFileName, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)], - typingOptions: { include: ["jquery", "moment"] } + typeAcquisition: { include: ["jquery", "moment"] } }); const p = projectService.externalProjects[0]; projectService.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(p, [lodashJs.path, commanderJs.path, file3.path]); - // expected 3 view requests in the queue - installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]); - assert.equal(installer.pendingRunRequests.length, 2, "expected 2 pending requests"); - - // push view requests - installer.executePendingCommands(); - // expected 2 remaining view requests in the queue - installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest]); - // push view requests - installer.executePendingCommands(); - // expected one install request - installer.checkPendingCommands([TI.NpmInstallRequest]); + installer.checkPendingCommands(/*expectedCount*/ 1); installer.executePendingCommands(); // expected all typings file to exist for (const f of typingFiles) { @@ -565,22 +550,17 @@ namespace ts.projectSystem { const host = createServerHost([lodashJs, commanderJs, file3]); const installer = new (class extends Installer { constructor() { - super(host, { throttleLimit: 3 }); + super(host, { throttleLimit: 1, typesRegistry: createTypesRegistry("commander", "jquery", "lodash", "cordova", "gulp", "grunt") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { - if (requestKind === TI.NpmInstallRequest) { - let typingFiles: (FileOrFolder & { typings: string}) [] = []; - if (command.indexOf("commander") >= 0) { - typingFiles = [commander, jquery, lodash, cordova]; - } - else { - typingFiles = [grunt, gulp]; - } - executeCommand(this, host, typingFiles.map(f => f.typings), typingFiles, requestKind, cb); + installWorker(_requestId: number, args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { + let typingFiles: (FileOrFolder & { typings: string })[] = []; + if (args.indexOf("@types/commander") >= 0) { + typingFiles = [commander, jquery, lodash, cordova]; } else { - executeCommand(this, host, [], [], requestKind, cb); + typingFiles = [grunt, gulp]; } + executeCommand(this, host, typingFiles.map(f => f.typings), typingFiles, cb); } })(); @@ -591,11 +571,11 @@ namespace ts.projectSystem { projectFileName: projectFileName1, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)], - typingOptions: { include: ["jquery", "cordova" ] } + typeAcquisition: { include: ["jquery", "cordova"] } }); - installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]); - assert.equal(installer.pendingRunRequests.length, 1, "expect one throttled request"); + installer.checkPendingCommands(/*expectedCount*/ 1); + assert.equal(installer.pendingRunRequests.length, 0, "expect no throttled requests"); // Create project #2 with 2 typings const projectFileName2 = "/a/app/test2.csproj"; @@ -603,9 +583,9 @@ namespace ts.projectSystem { projectFileName: projectFileName2, options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: [toExternalFile(file3.path)], - typingOptions: { include: ["grunt", "gulp"] } + typeAcquisition: { include: ["grunt", "gulp"] } }); - assert.equal(installer.pendingRunRequests.length, 3, "expect three throttled request"); + assert.equal(installer.pendingRunRequests.length, 1, "expect one throttled request"); const p1 = projectService.externalProjects[0]; const p2 = projectService.externalProjects[1]; @@ -613,20 +593,16 @@ namespace ts.projectSystem { checkProjectActualFiles(p1, [lodashJs.path, commanderJs.path, file3.path]); checkProjectActualFiles(p2, [file3.path]); - installer.executePendingCommands(); - // expected one view request from the first project and two - from the second one - installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]); + + // expected one install request from the second project + installer.checkPendingCommands(/*expectedCount*/ 1); assert.equal(installer.pendingRunRequests.length, 0, "expected no throttled requests"); installer.executePendingCommands(); - // should be two install requests from both projects - installer.checkPendingCommands([TI.NpmInstallRequest, TI.NpmInstallRequest]); - installer.executePendingCommands(); - checkProjectActualFiles(p1, [lodashJs.path, commanderJs.path, file3.path, commander.path, jquery.path, lodash.path, cordova.path]); - checkProjectActualFiles(p2, [file3.path, grunt.path, gulp.path ]); + checkProjectActualFiles(p2, [file3.path, grunt.path, gulp.path]); }); it("configured projects discover from node_modules", () => { @@ -653,12 +629,12 @@ namespace ts.projectSystem { const host = createServerHost([app, jsconfig, jquery, jqueryPackage]); const installer = new (class extends Installer { constructor() { - super(host, { globalTypingsCacheLocation: "/tmp" }); + super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jqueryDTS]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -669,7 +645,7 @@ namespace ts.projectSystem { const p = projectService.configuredProjects[0]; checkProjectActualFiles(p, [app.path]); - installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { configuredProjects: 1 }); checkProjectActualFiles(p, [app.path, jqueryDTS.path]); @@ -687,10 +663,10 @@ namespace ts.projectSystem { const bowerJson = { path: "/bower.json", content: JSON.stringify({ - "dependencies": { - "jquery": "^3.1.0" - } - }) + "dependencies": { + "jquery": "^3.1.0" + } + }) }; const jqueryDTS = { path: "/tmp/node_modules/@types/jquery/index.d.ts", @@ -699,12 +675,12 @@ namespace ts.projectSystem { const host = createServerHost([app, jsconfig, bowerJson]); const installer = new (class extends Installer { constructor() { - super(host, { globalTypingsCacheLocation: "/tmp" }); + super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jqueryDTS]; - executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); + executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -715,31 +691,197 @@ namespace ts.projectSystem { const p = projectService.configuredProjects[0]; checkProjectActualFiles(p, [app.path]); - installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]); + installer.installAll(/*expectedCount*/ 1); checkNumberOfProjects(projectService, { configuredProjects: 1 }); checkProjectActualFiles(p, [app.path, jqueryDTS.path]); }); + + it("Malformed package.json should be watched", () => { + const f = { + path: "/a/b/app.js", + content: "var x = 1" + }; + const brokenPackageJson = { + path: "/a/b/package.json", + content: `{ "dependencies": { "co } }` + }; + const fixedPackageJson = { + path: brokenPackageJson.path, + content: `{ "dependencies": { "commander": "0.0.2" } }` + }; + const cachePath = "/a/cache/"; + const commander = { + path: cachePath + "node_modules/@types/commander/index.d.ts", + content: "export let x: number" + }; + const host = createServerHost([f, brokenPackageJson]); + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + const installedTypings = ["@types/commander"]; + const typingFiles = [commander]; + executeCommand(this, host, installedTypings, typingFiles, cb); + } + })(); + const service = createProjectService(host, { typingsInstaller: installer }); + service.openClientFile(f.path); + + installer.checkPendingCommands(/*expectedCount*/ 0); + + host.reloadFS([f, fixedPackageJson]); + host.triggerFileWatcherCallback(fixedPackageJson.path, /*removed*/ false); + // expected install request + installer.installAll(/*expectedCount*/ 1); + + service.checkNumberOfProjects({ inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [f.path, commander.path]); + }); + + it("should install typings for unresolved imports", () => { + const file = { + path: "/a/b/app.js", + content: ` + import * as fs from "fs"; + import * as commander from "commander";` + }; + const cachePath = "/a/cache"; + const node = { + path: cachePath + "/node_modules/@types/node/index.d.ts", + content: "export let x: number" + }; + const commander = { + path: cachePath + "/node_modules/@types/commander/index.d.ts", + content: "export let y: string" + }; + const host = createServerHost([file]); + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("node", "commander") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + const installedTypings = ["@types/node", "@types/commander"]; + const typingFiles = [node, commander]; + executeCommand(this, host, installedTypings, typingFiles, cb); + } + })(); + const service = createProjectService(host, { typingsInstaller: installer }); + service.openClientFile(file.path); + + service.checkNumberOfProjects({ inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [file.path]); + + installer.installAll(/*expectedCount*/1); + + assert.isTrue(host.fileExists(node.path), "typings for 'node' should be created"); + assert.isTrue(host.fileExists(commander.path), "typings for 'commander' should be created"); + + checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]); + }); + + it("should pick typing names from non-relative unresolved imports", () => { + const f1 = { + path: "/a/b/app.js", + content: ` + import * as a from "foo/a/a"; + import * as b from "foo/a/b"; + import * as c from "foo/a/c"; + import * as d from "@bar/router/"; + import * as e from "@bar/common/shared"; + import * as e from "@bar/common/apps"; + import * as f from "./lib" + ` + }; + + const host = createServerHost([f1]); + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("foo") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeCommand(this, host, ["foo"], [], cb); + } + })(); + const projectService = createProjectService(host, { typingsInstaller: installer }); + projectService.openClientFile(f1.path); + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + + const proj = projectService.inferredProjects[0]; + proj.updateGraph(); + + assert.deepEqual( + proj.getCachedUnresolvedImportsPerFile_TestOnly().get(f1.path), + ["foo", "foo", "foo", "@bar/router", "@bar/common", "@bar/common"] + ); + + installer.installAll(/*expectedCount*/ 1); + }); + + it("cached unresolved typings are not recomputed if program structure did not change", () => { + const host = createServerHost([]); + const session = createSession(host); + const f = { + path: "/a/app.js", + content: ` + import * as fs from "fs"; + import * as cmd from "commander + ` + }; + session.executeCommand({ + seq: 1, + type: "request", + command: "open", + arguments: { + file: f.path, + fileContent: f.content + } + }); + const projectService = session.getProjectService(); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + const proj = projectService.inferredProjects[0]; + const version1 = proj.getCachedUnresolvedImportsPerFile_TestOnly().getVersion(); + + // make a change that should not affect the structure of the program + session.executeCommand({ + seq: 2, + type: "request", + command: "change", + arguments: { + file: f.path, + insertString: "\nlet x = 1;", + line: 2, + offset: 0, + endLine: 2, + endOffset: 0 + } + }); + host.checkTimeoutQueueLength(1); + host.runQueuedTimeoutCallbacks(); + const version2 = proj.getCachedUnresolvedImportsPerFile_TestOnly().getVersion(); + assert.equal(version1, version2, "set of unresolved imports should not change"); + }); }); describe("Validate package name:", () => { - it ("name cannot be too long", () => { + it("name cannot be too long", () => { let packageName = "a"; for (let i = 0; i < 8; i++) { packageName += packageName; } assert.equal(TI.validatePackageName(packageName), TI.PackageNameValidationResult.NameTooLong); }); - it ("name cannot start with dot", () => { + it("name cannot start with dot", () => { assert.equal(TI.validatePackageName(".foo"), TI.PackageNameValidationResult.NameStartsWithDot); }); - it ("name cannot start with underscore", () => { + it("name cannot start with underscore", () => { assert.equal(TI.validatePackageName("_foo"), TI.PackageNameValidationResult.NameStartsWithUnderscore); }); - it ("scoped packages not supported", () => { + it("scoped packages not supported", () => { assert.equal(TI.validatePackageName("@scope/bar"), TI.PackageNameValidationResult.ScopedPackagesNotSupported); }); - it ("non URI safe characters are not supported", () => { + it("non URI safe characters are not supported", () => { assert.equal(TI.validatePackageName(" scope "), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters); assert.equal(TI.validatePackageName("; say ‘Hello from TypeScript!’ #"), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters); assert.equal(TI.validatePackageName("a/b/c"), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters); @@ -747,7 +889,7 @@ namespace ts.projectSystem { }); describe("Invalid package names", () => { - it ("should not be installed", () => { + it("should not be installed", () => { const f1 = { path: "/a/b/app.js", content: "let x = 1" @@ -766,15 +908,193 @@ namespace ts.projectSystem { constructor() { super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + installWorker(_requestId: number, _args: string[], _cwd: string, _cb: server.typingsInstaller.RequestCompletedAction) { assert(false, "runCommand should not be invoked"); } })(); const projectService = createProjectService(host, { typingsInstaller: installer }); projectService.openClientFile(f1.path); - installer.checkPendingCommands([]); + installer.checkPendingCommands(/*expectedCount*/ 0); assert.isTrue(messages.indexOf("Package name '; say ‘Hello from TypeScript!’ #' contains non URI safe characters") > 0, "should find package with invalid name"); }); }); + + describe("discover typings", () => { + it("should return node for core modules", () => { + const f = { + path: "/a/b/app.js", + content: "" + }; + const host = createServerHost([f]); + const cache = createMap(); + for (const name of JsTyping.nodeCoreModuleList) { + const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(f.path), /*safeListPath*/ undefined, cache, { enable: true }, [name, "somename"]); + assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]); + } + }); + + it("should use cached locaitons", () => { + const f = { + path: "/a/b/app.js", + content: "" + }; + const node = { + path: "/a/b/node.d.ts", + content: "" + }; + const host = createServerHost([f, node]); + const cache = createMap({ "node": node.path }); + const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(f.path), /*safeListPath*/ undefined, cache, { enable: true }, ["fs", "bar"]); + assert.deepEqual(result.cachedTypingPaths, [node.path]); + assert.deepEqual(result.newTypingNames, ["bar"]); + }); + }); + + describe("telemetry events", () => { + it ("should be received", () => { + const f1 = { + path: "/a/app.js", + content: "" + }; + const package = { + path: "/a/package.json", + content: JSON.stringify({ dependencies: { "commander": "1.0.0" } }) + }; + const cachePath = "/a/cache/"; + const commander = { + path: cachePath + "node_modules/@types/commander/index.d.ts", + content: "export let x: number" + }; + const host = createServerHost([f1, package]); + let seenTelemetryEvent = false; + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + const installedTypings = ["@types/commander"]; + const typingFiles = [commander]; + executeCommand(this, host, installedTypings, typingFiles, cb); + } + sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) { + if (response.kind === server.EventBeginInstallTypes) { + return; + } + if (response.kind === server.EventEndInstallTypes) { + assert.deepEqual(response.packagesToInstall, ["@types/commander"]); + seenTelemetryEvent = true; + return; + } + super.sendResponse(response); + } + })(); + const projectService = createProjectService(host, { typingsInstaller: installer }); + projectService.openClientFile(f1.path); + + installer.installAll(/*expectedCount*/ 1); + + assert.isTrue(seenTelemetryEvent); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [f1.path, commander.path]); + }); + }); + + describe("progress notifications", () => { + it ("should be sent for success", () => { + const f1 = { + path: "/a/app.js", + content: "" + }; + const package = { + path: "/a/package.json", + content: JSON.stringify({ dependencies: { "commander": "1.0.0" } }) + }; + const cachePath = "/a/cache/"; + const commander = { + path: cachePath + "node_modules/@types/commander/index.d.ts", + content: "export let x: number" + }; + const host = createServerHost([f1, package]); + let beginEvent: server.BeginInstallTypes; + let endEvent: server.EndInstallTypes; + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + const installedTypings = ["@types/commander"]; + const typingFiles = [commander]; + executeCommand(this, host, installedTypings, typingFiles, cb); + } + sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) { + if (response.kind === server.EventBeginInstallTypes) { + beginEvent = response; + return; + } + if (response.kind === server.EventEndInstallTypes) { + endEvent = response; + return; + } + super.sendResponse(response); + } + })(); + const projectService = createProjectService(host, { typingsInstaller: installer }); + projectService.openClientFile(f1.path); + + installer.installAll(/*expectedCount*/ 1); + + assert.isTrue(!!beginEvent); + assert.isTrue(!!endEvent); + assert.isTrue(beginEvent.eventId === endEvent.eventId); + assert.isTrue(endEvent.installSuccess); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [f1.path, commander.path]); + }); + + it ("should be sent for error", () => { + const f1 = { + path: "/a/app.js", + content: "" + }; + const package = { + path: "/a/package.json", + content: JSON.stringify({ dependencies: { "commander": "1.0.0" } }) + }; + const cachePath = "/a/cache/"; + const host = createServerHost([f1, package]); + let beginEvent: server.BeginInstallTypes; + let endEvent: server.EndInstallTypes; + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeCommand(this, host, "", [], cb); + } + sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) { + if (response.kind === server.EventBeginInstallTypes) { + beginEvent = response; + return; + } + if (response.kind === server.EventEndInstallTypes) { + endEvent = response; + return; + } + super.sendResponse(response); + } + })(); + const projectService = createProjectService(host, { typingsInstaller: installer }); + projectService.openClientFile(f1.path); + + installer.installAll(/*expectedCount*/ 1); + + assert.isTrue(!!beginEvent); + assert.isTrue(!!endEvent); + assert.isTrue(beginEvent.eventId === endEvent.eventId); + assert.isFalse(endEvent.installSuccess); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [f1.path]); + }); + }); } \ No newline at end of file diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index b520b18ea1d..d9825897ebc 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -76,6 +76,7 @@ interface DoubleRange { } interface EventInit { + scoped?: boolean; bubbles?: boolean; cancelable?: boolean; } @@ -917,15 +918,26 @@ declare var AnimationEvent: { new(): AnimationEvent; } +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": ErrorEvent; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + interface ApplicationCache extends EventTarget { - oncached: (this: this, ev: Event) => any; - onchecking: (this: this, ev: Event) => any; - ondownloading: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onnoupdate: (this: this, ev: Event) => any; - onobsolete: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onupdateready: (this: this, ev: Event) => any; + oncached: (this: ApplicationCache, ev: Event) => any; + onchecking: (this: ApplicationCache, ev: Event) => any; + ondownloading: (this: ApplicationCache, ev: Event) => any; + onerror: (this: ApplicationCache, ev: ErrorEvent) => any; + onnoupdate: (this: ApplicationCache, ev: Event) => any; + onobsolete: (this: ApplicationCache, ev: Event) => any; + onprogress: (this: ApplicationCache, ev: ProgressEvent) => any; + onupdateready: (this: ApplicationCache, ev: Event) => any; readonly status: number; abort(): void; swapCache(): void; @@ -936,14 +948,7 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: "cached", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "checking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "downloading", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "noupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "obsolete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "updateready", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -996,17 +1001,21 @@ declare var AudioBuffer: { new(): AudioBuffer; } +interface AudioBufferSourceNodeEventMap { + "ended": MediaStreamErrorEvent; +} + interface AudioBufferSourceNode extends AudioNode { buffer: AudioBuffer | null; readonly detune: AudioParam; loop: boolean; loopEnd: number; loopStart: number; - onended: (this: this, ev: MediaStreamErrorEvent) => any; + onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -1128,16 +1137,20 @@ declare var AudioTrack: { new(): AudioTrack; } +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + interface AudioTrackList extends EventTarget { readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; + onaddtrack: (this: AudioTrackList, ev: TrackEvent) => any; + onchange: (this: AudioTrackList, ev: Event) => any; + onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: AudioTrack; } @@ -1679,6 +1692,7 @@ interface CSSStyleDeclaration { writingMode: string | null; zIndex: string | null; zoom: string | null; + resize: string | null; getPropertyPriority(propertyName: string): string; getPropertyValue(propertyName: string): string; item(index: number): string; @@ -1748,6 +1762,7 @@ declare var CanvasGradient: { } interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; } declare var CanvasPattern: { @@ -1836,7 +1851,6 @@ interface CharacterData extends Node, ChildNode { insertData(offset: number, arg: string): void; replaceData(offset: number, count: number, arg: string): void; substringData(offset: number, count: number): string; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var CharacterData: { @@ -2161,6 +2175,8 @@ declare var DOMTokenList: { interface DataCue extends TextTrackCue { data: ArrayBuffer; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var DataCue: { @@ -2173,7 +2189,7 @@ interface DataTransfer { effectAllowed: string; readonly files: FileList; readonly items: DataTransferItemList; - readonly types: DOMStringList; + readonly types: string[]; clearData(format?: string): boolean; getData(format: string): string; setData(format: string, data: string): boolean; @@ -2289,7 +2305,98 @@ declare var DeviceRotationRate: { new(): DeviceRotationRate; } -interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode { +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforedeactivate": UIEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "fullscreenchange": Event; + "fullscreenerror": Event; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "mssitemodejumplistitemremoved": MSSiteModeEvent; + "msthumbnailclick": MSSiteModeEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectionchange": Event; + "selectstart": Event; + "stalled": Event; + "stop": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "volumechange": Event; + "waiting": Event; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** * Sets or gets the URL for the current document. */ @@ -2412,294 +2519,294 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (this: this, ev: UIEvent) => any; + onabort: (this: Document, ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. */ - onactivate: (this: this, ev: UIEvent) => any; + onactivate: (this: Document, ev: UIEvent) => any; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ - onbeforeactivate: (this: this, ev: UIEvent) => any; + onbeforeactivate: (this: Document, ev: UIEvent) => any; /** * Fires immediately before the activeElement is changed from the current object to another object in the parent document. * @param ev The event. */ - onbeforedeactivate: (this: this, ev: UIEvent) => any; + onbeforedeactivate: (this: Document, ev: UIEvent) => any; /** * Fires when the object loses the input focus. * @param ev The focus event. */ - onblur: (this: this, ev: FocusEvent) => any; + onblur: (this: Document, ev: FocusEvent) => any; /** * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; + oncanplay: (this: Document, ev: Event) => any; + oncanplaythrough: (this: Document, ev: Event) => any; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ - onchange: (this: this, ev: Event) => any; + onchange: (this: Document, ev: Event) => any; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ - onclick: (this: this, ev: MouseEvent) => any; + onclick: (this: Document, ev: MouseEvent) => any; /** * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ - oncontextmenu: (this: this, ev: PointerEvent) => any; + oncontextmenu: (this: Document, ev: PointerEvent) => any; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ - ondblclick: (this: this, ev: MouseEvent) => any; + ondblclick: (this: Document, ev: MouseEvent) => any; /** * Fires when the activeElement is changed from the current object to another object in the parent document. * @param ev The UI Event */ - ondeactivate: (this: this, ev: UIEvent) => any; + ondeactivate: (this: Document, ev: UIEvent) => any; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ - ondrag: (this: this, ev: DragEvent) => any; + ondrag: (this: Document, ev: DragEvent) => any; /** * Fires on the source object when the user releases the mouse at the close of a drag operation. * @param ev The event. */ - ondragend: (this: this, ev: DragEvent) => any; + ondragend: (this: Document, 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: (this: this, ev: DragEvent) => any; + ondragenter: (this: Document, 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. */ - ondragleave: (this: this, ev: DragEvent) => any; + ondragleave: (this: Document, ev: DragEvent) => any; /** * Fires on the target element continuously while the user drags the object over a valid drop target. * @param ev The event. */ - ondragover: (this: this, ev: DragEvent) => any; + ondragover: (this: Document, ev: DragEvent) => any; /** * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; + ondragstart: (this: Document, ev: DragEvent) => any; + ondrop: (this: Document, ev: DragEvent) => any; /** * Occurs when the duration attribute is updated. * @param ev The event. */ - ondurationchange: (this: this, ev: Event) => any; + ondurationchange: (this: Document, ev: Event) => any; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ - onemptied: (this: this, ev: Event) => any; + onemptied: (this: Document, ev: Event) => any; /** * Occurs when the end of playback is reached. * @param ev The event */ - onended: (this: this, ev: MediaStreamErrorEvent) => any; + onended: (this: Document, ev: MediaStreamErrorEvent) => any; /** * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (this: this, ev: ErrorEvent) => any; + onerror: (this: Document, ev: ErrorEvent) => any; /** * Fires when the object receives focus. * @param ev The event. */ - onfocus: (this: this, ev: FocusEvent) => any; - onfullscreenchange: (this: this, ev: Event) => any; - onfullscreenerror: (this: this, ev: Event) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; + onfocus: (this: Document, ev: FocusEvent) => any; + onfullscreenchange: (this: Document, ev: Event) => any; + onfullscreenerror: (this: Document, ev: Event) => any; + oninput: (this: Document, ev: Event) => any; + oninvalid: (this: Document, ev: Event) => any; /** * Fires when the user presses a key. * @param ev The keyboard event */ - onkeydown: (this: this, ev: KeyboardEvent) => any; + onkeydown: (this: Document, ev: KeyboardEvent) => any; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ - onkeypress: (this: this, ev: KeyboardEvent) => any; + onkeypress: (this: Document, ev: KeyboardEvent) => any; /** * Fires when the user releases a key. * @param ev The keyboard event */ - onkeyup: (this: this, ev: KeyboardEvent) => any; + onkeyup: (this: Document, ev: KeyboardEvent) => any; /** * Fires immediately after the browser loads the object. * @param ev The event. */ - onload: (this: this, ev: Event) => any; + onload: (this: Document, ev: Event) => any; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ - onloadeddata: (this: this, ev: Event) => any; + onloadeddata: (this: Document, ev: Event) => any; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ - onloadedmetadata: (this: this, ev: Event) => any; + onloadedmetadata: (this: Document, ev: Event) => any; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ - onloadstart: (this: this, ev: Event) => any; + onloadstart: (this: Document, ev: Event) => any; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ - onmousedown: (this: this, ev: MouseEvent) => any; + onmousedown: (this: Document, ev: MouseEvent) => any; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ - onmousemove: (this: this, ev: MouseEvent) => any; + onmousemove: (this: Document, ev: MouseEvent) => any; /** * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ - onmouseout: (this: this, ev: MouseEvent) => any; + onmouseout: (this: Document, ev: MouseEvent) => any; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ - onmouseover: (this: this, ev: MouseEvent) => any; + onmouseover: (this: Document, ev: MouseEvent) => any; /** * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ - onmouseup: (this: this, ev: MouseEvent) => any; + onmouseup: (this: Document, ev: MouseEvent) => any; /** * Fires when the wheel button is rotated. * @param ev The mouse event */ - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; + onmousewheel: (this: Document, ev: WheelEvent) => any; + onmscontentzoom: (this: Document, ev: UIEvent) => any; + onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Document, ev: MSGestureEvent) => any; + onmsgestureend: (this: Document, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Document, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Document, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Document, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Document, ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (this: Document, ev: MSManipulationEvent) => any; + onmspointercancel: (this: Document, ev: MSPointerEvent) => any; + onmspointerdown: (this: Document, ev: MSPointerEvent) => any; + onmspointerenter: (this: Document, ev: MSPointerEvent) => any; + onmspointerleave: (this: Document, ev: MSPointerEvent) => any; + onmspointermove: (this: Document, ev: MSPointerEvent) => any; + onmspointerout: (this: Document, ev: MSPointerEvent) => any; + onmspointerover: (this: Document, ev: MSPointerEvent) => any; + onmspointerup: (this: Document, ev: MSPointerEvent) => any; /** * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ - onmssitemodejumplistitemremoved: (this: this, ev: MSSiteModeEvent) => any; + onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; /** * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. * @param ev The event. */ - onmsthumbnailclick: (this: this, ev: MSSiteModeEvent) => any; + onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; /** * Occurs when playback is paused. * @param ev The event. */ - onpause: (this: this, ev: Event) => any; + onpause: (this: Document, ev: Event) => any; /** * Occurs when the play method is requested. * @param ev The event. */ - onplay: (this: this, ev: Event) => any; + onplay: (this: Document, ev: Event) => any; /** * Occurs when the audio or video has started playing. * @param ev The event. */ - onplaying: (this: this, ev: Event) => any; - onpointerlockchange: (this: this, ev: Event) => any; - onpointerlockerror: (this: this, ev: Event) => any; + onplaying: (this: Document, ev: Event) => any; + onpointerlockchange: (this: Document, ev: Event) => any; + onpointerlockerror: (this: Document, ev: Event) => any; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ - onprogress: (this: this, ev: ProgressEvent) => any; + onprogress: (this: Document, ev: ProgressEvent) => any; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ - onratechange: (this: this, ev: Event) => any; + onratechange: (this: Document, ev: Event) => any; /** * Fires when the state of the object has changed. * @param ev The event */ - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: Document, ev: ProgressEvent) => any; /** * Fires when the user resets a form. * @param ev The event. */ - onreset: (this: this, ev: Event) => any; + onreset: (this: Document, ev: Event) => any; /** * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ - onscroll: (this: this, ev: UIEvent) => any; + onscroll: (this: Document, ev: UIEvent) => any; /** * Occurs when the seek operation ends. * @param ev The event. */ - onseeked: (this: this, ev: Event) => any; + onseeked: (this: Document, ev: Event) => any; /** * Occurs when the current playback position is moved. * @param ev The event. */ - onseeking: (this: this, ev: Event) => any; + onseeking: (this: Document, ev: Event) => any; /** * Fires when the current selection changes. * @param ev The event. */ - onselect: (this: this, ev: UIEvent) => any; + onselect: (this: Document, ev: UIEvent) => any; /** * Fires when the selection state of a document changes. * @param ev The event. */ - onselectionchange: (this: this, ev: Event) => any; - onselectstart: (this: this, ev: Event) => any; + onselectionchange: (this: Document, ev: Event) => any; + onselectstart: (this: Document, ev: Event) => any; /** * Occurs when the download has stopped. * @param ev The event. */ - onstalled: (this: this, ev: Event) => any; + onstalled: (this: Document, ev: Event) => any; /** * Fires when the user clicks the Stop button or leaves the Web page. * @param ev The event. */ - onstop: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; + onstop: (this: Document, ev: Event) => any; + onsubmit: (this: Document, ev: Event) => any; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ - onsuspend: (this: this, ev: Event) => any; + onsuspend: (this: Document, ev: Event) => any; /** * Occurs to indicate the current playback position. * @param ev The event. */ - ontimeupdate: (this: this, ev: Event) => any; + ontimeupdate: (this: Document, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; @@ -2708,14 +2815,14 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ - onvolumechange: (this: this, ev: Event) => any; + onvolumechange: (this: Document, ev: Event) => any; /** * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ - onwaiting: (this: this, ev: Event) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; + onwaiting: (this: Document, ev: Event) => any; + onwebkitfullscreenchange: (this: Document, ev: Event) => any; + onwebkitfullscreenerror: (this: Document, ev: Event) => any; plugins: HTMLCollectionOf; readonly pointerLockElement: Element; /** @@ -2786,86 +2893,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Creates an instance of the element for the specified tag. * @param tagName The name of an element. */ - createElement(tagName: "a"): HTMLAnchorElement; - createElement(tagName: "applet"): HTMLAppletElement; - createElement(tagName: "area"): HTMLAreaElement; - createElement(tagName: "audio"): HTMLAudioElement; - createElement(tagName: "base"): HTMLBaseElement; - createElement(tagName: "basefont"): HTMLBaseFontElement; - createElement(tagName: "blockquote"): HTMLQuoteElement; - createElement(tagName: "body"): HTMLBodyElement; - createElement(tagName: "br"): HTMLBRElement; - createElement(tagName: "button"): HTMLButtonElement; - createElement(tagName: "canvas"): HTMLCanvasElement; - createElement(tagName: "caption"): HTMLTableCaptionElement; - createElement(tagName: "col"): HTMLTableColElement; - createElement(tagName: "colgroup"): HTMLTableColElement; - createElement(tagName: "datalist"): HTMLDataListElement; - createElement(tagName: "del"): HTMLModElement; - createElement(tagName: "dir"): HTMLDirectoryElement; - createElement(tagName: "div"): HTMLDivElement; - createElement(tagName: "dl"): HTMLDListElement; - createElement(tagName: "embed"): HTMLEmbedElement; - createElement(tagName: "fieldset"): HTMLFieldSetElement; - createElement(tagName: "font"): HTMLFontElement; - createElement(tagName: "form"): HTMLFormElement; - createElement(tagName: "frame"): HTMLFrameElement; - createElement(tagName: "frameset"): HTMLFrameSetElement; - createElement(tagName: "h1"): HTMLHeadingElement; - createElement(tagName: "h2"): HTMLHeadingElement; - createElement(tagName: "h3"): HTMLHeadingElement; - createElement(tagName: "h4"): HTMLHeadingElement; - createElement(tagName: "h5"): HTMLHeadingElement; - createElement(tagName: "h6"): HTMLHeadingElement; - createElement(tagName: "head"): HTMLHeadElement; - createElement(tagName: "hr"): HTMLHRElement; - createElement(tagName: "html"): HTMLHtmlElement; - createElement(tagName: "iframe"): HTMLIFrameElement; - createElement(tagName: "img"): HTMLImageElement; - createElement(tagName: "input"): HTMLInputElement; - createElement(tagName: "ins"): HTMLModElement; - createElement(tagName: "isindex"): HTMLUnknownElement; - createElement(tagName: "label"): HTMLLabelElement; - createElement(tagName: "legend"): HTMLLegendElement; - createElement(tagName: "li"): HTMLLIElement; - createElement(tagName: "link"): HTMLLinkElement; - createElement(tagName: "listing"): HTMLPreElement; - createElement(tagName: "map"): HTMLMapElement; - createElement(tagName: "marquee"): HTMLMarqueeElement; - createElement(tagName: "menu"): HTMLMenuElement; - createElement(tagName: "meta"): HTMLMetaElement; - createElement(tagName: "meter"): HTMLMeterElement; - createElement(tagName: "nextid"): HTMLUnknownElement; - createElement(tagName: "object"): HTMLObjectElement; - createElement(tagName: "ol"): HTMLOListElement; - createElement(tagName: "optgroup"): HTMLOptGroupElement; - createElement(tagName: "option"): HTMLOptionElement; - createElement(tagName: "p"): HTMLParagraphElement; - createElement(tagName: "param"): HTMLParamElement; - createElement(tagName: "picture"): HTMLPictureElement; - createElement(tagName: "pre"): HTMLPreElement; - createElement(tagName: "progress"): HTMLProgressElement; - createElement(tagName: "q"): HTMLQuoteElement; - createElement(tagName: "script"): HTMLScriptElement; - createElement(tagName: "select"): HTMLSelectElement; - createElement(tagName: "source"): HTMLSourceElement; - createElement(tagName: "span"): HTMLSpanElement; - createElement(tagName: "style"): HTMLStyleElement; - createElement(tagName: "table"): HTMLTableElement; - createElement(tagName: "tbody"): HTMLTableSectionElement; - createElement(tagName: "td"): HTMLTableDataCellElement; - createElement(tagName: "template"): HTMLTemplateElement; - createElement(tagName: "textarea"): HTMLTextAreaElement; - createElement(tagName: "tfoot"): HTMLTableSectionElement; - createElement(tagName: "th"): HTMLTableHeaderCellElement; - createElement(tagName: "thead"): HTMLTableSectionElement; - createElement(tagName: "title"): HTMLTitleElement; - createElement(tagName: "tr"): HTMLTableRowElement; - createElement(tagName: "track"): HTMLTrackElement; - createElement(tagName: "ul"): HTMLUListElement; - createElement(tagName: "video"): HTMLVideoElement; - createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; - createElement(tagName: "xmp"): HTMLPreElement; + createElement(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement @@ -2967,7 +2995,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. @@ -3001,182 +3029,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: "a"): NodeListOf; - getElementsByTagName(tagname: "abbr"): NodeListOf; - getElementsByTagName(tagname: "acronym"): NodeListOf; - getElementsByTagName(tagname: "address"): NodeListOf; - getElementsByTagName(tagname: "applet"): NodeListOf; - getElementsByTagName(tagname: "area"): NodeListOf; - getElementsByTagName(tagname: "article"): NodeListOf; - getElementsByTagName(tagname: "aside"): NodeListOf; - getElementsByTagName(tagname: "audio"): NodeListOf; - getElementsByTagName(tagname: "b"): NodeListOf; - getElementsByTagName(tagname: "base"): NodeListOf; - getElementsByTagName(tagname: "basefont"): NodeListOf; - getElementsByTagName(tagname: "bdo"): NodeListOf; - getElementsByTagName(tagname: "big"): NodeListOf; - getElementsByTagName(tagname: "blockquote"): NodeListOf; - getElementsByTagName(tagname: "body"): NodeListOf; - getElementsByTagName(tagname: "br"): NodeListOf; - getElementsByTagName(tagname: "button"): NodeListOf; - getElementsByTagName(tagname: "canvas"): NodeListOf; - getElementsByTagName(tagname: "caption"): NodeListOf; - getElementsByTagName(tagname: "center"): NodeListOf; - getElementsByTagName(tagname: "circle"): NodeListOf; - getElementsByTagName(tagname: "cite"): NodeListOf; - getElementsByTagName(tagname: "clippath"): NodeListOf; - getElementsByTagName(tagname: "code"): NodeListOf; - getElementsByTagName(tagname: "col"): NodeListOf; - getElementsByTagName(tagname: "colgroup"): NodeListOf; - getElementsByTagName(tagname: "datalist"): NodeListOf; - getElementsByTagName(tagname: "dd"): NodeListOf; - getElementsByTagName(tagname: "defs"): NodeListOf; - getElementsByTagName(tagname: "del"): NodeListOf; - getElementsByTagName(tagname: "desc"): NodeListOf; - getElementsByTagName(tagname: "dfn"): NodeListOf; - getElementsByTagName(tagname: "dir"): NodeListOf; - getElementsByTagName(tagname: "div"): NodeListOf; - getElementsByTagName(tagname: "dl"): NodeListOf; - getElementsByTagName(tagname: "dt"): NodeListOf; - getElementsByTagName(tagname: "ellipse"): NodeListOf; - getElementsByTagName(tagname: "em"): NodeListOf; - getElementsByTagName(tagname: "embed"): NodeListOf; - getElementsByTagName(tagname: "feblend"): NodeListOf; - getElementsByTagName(tagname: "fecolormatrix"): NodeListOf; - getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(tagname: "fecomposite"): NodeListOf; - getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf; - getElementsByTagName(tagname: "fediffuselighting"): NodeListOf; - getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf; - getElementsByTagName(tagname: "fedistantlight"): NodeListOf; - getElementsByTagName(tagname: "feflood"): NodeListOf; - getElementsByTagName(tagname: "fefunca"): NodeListOf; - getElementsByTagName(tagname: "fefuncb"): NodeListOf; - getElementsByTagName(tagname: "fefuncg"): NodeListOf; - getElementsByTagName(tagname: "fefuncr"): NodeListOf; - getElementsByTagName(tagname: "fegaussianblur"): NodeListOf; - getElementsByTagName(tagname: "feimage"): NodeListOf; - getElementsByTagName(tagname: "femerge"): NodeListOf; - getElementsByTagName(tagname: "femergenode"): NodeListOf; - getElementsByTagName(tagname: "femorphology"): NodeListOf; - getElementsByTagName(tagname: "feoffset"): NodeListOf; - getElementsByTagName(tagname: "fepointlight"): NodeListOf; - getElementsByTagName(tagname: "fespecularlighting"): NodeListOf; - getElementsByTagName(tagname: "fespotlight"): NodeListOf; - getElementsByTagName(tagname: "fetile"): NodeListOf; - getElementsByTagName(tagname: "feturbulence"): NodeListOf; - getElementsByTagName(tagname: "fieldset"): NodeListOf; - getElementsByTagName(tagname: "figcaption"): NodeListOf; - getElementsByTagName(tagname: "figure"): NodeListOf; - getElementsByTagName(tagname: "filter"): NodeListOf; - getElementsByTagName(tagname: "font"): NodeListOf; - getElementsByTagName(tagname: "footer"): NodeListOf; - getElementsByTagName(tagname: "foreignobject"): NodeListOf; - getElementsByTagName(tagname: "form"): NodeListOf; - getElementsByTagName(tagname: "frame"): NodeListOf; - getElementsByTagName(tagname: "frameset"): NodeListOf; - getElementsByTagName(tagname: "g"): NodeListOf; - getElementsByTagName(tagname: "h1"): NodeListOf; - getElementsByTagName(tagname: "h2"): NodeListOf; - getElementsByTagName(tagname: "h3"): NodeListOf; - getElementsByTagName(tagname: "h4"): NodeListOf; - getElementsByTagName(tagname: "h5"): NodeListOf; - getElementsByTagName(tagname: "h6"): NodeListOf; - getElementsByTagName(tagname: "head"): NodeListOf; - getElementsByTagName(tagname: "header"): NodeListOf; - getElementsByTagName(tagname: "hgroup"): NodeListOf; - getElementsByTagName(tagname: "hr"): NodeListOf; - getElementsByTagName(tagname: "html"): NodeListOf; - getElementsByTagName(tagname: "i"): NodeListOf; - getElementsByTagName(tagname: "iframe"): NodeListOf; - getElementsByTagName(tagname: "image"): NodeListOf; - getElementsByTagName(tagname: "img"): NodeListOf; - getElementsByTagName(tagname: "input"): NodeListOf; - getElementsByTagName(tagname: "ins"): NodeListOf; - getElementsByTagName(tagname: "isindex"): NodeListOf; - getElementsByTagName(tagname: "kbd"): NodeListOf; - getElementsByTagName(tagname: "keygen"): NodeListOf; - getElementsByTagName(tagname: "label"): NodeListOf; - getElementsByTagName(tagname: "legend"): NodeListOf; - getElementsByTagName(tagname: "li"): NodeListOf; - getElementsByTagName(tagname: "line"): NodeListOf; - getElementsByTagName(tagname: "lineargradient"): NodeListOf; - getElementsByTagName(tagname: "link"): NodeListOf; - getElementsByTagName(tagname: "listing"): NodeListOf; - getElementsByTagName(tagname: "map"): NodeListOf; - getElementsByTagName(tagname: "mark"): NodeListOf; - getElementsByTagName(tagname: "marker"): NodeListOf; - getElementsByTagName(tagname: "marquee"): NodeListOf; - getElementsByTagName(tagname: "mask"): NodeListOf; - getElementsByTagName(tagname: "menu"): NodeListOf; - getElementsByTagName(tagname: "meta"): NodeListOf; - getElementsByTagName(tagname: "metadata"): NodeListOf; - getElementsByTagName(tagname: "meter"): NodeListOf; - getElementsByTagName(tagname: "nav"): NodeListOf; - getElementsByTagName(tagname: "nextid"): NodeListOf; - getElementsByTagName(tagname: "nobr"): NodeListOf; - getElementsByTagName(tagname: "noframes"): NodeListOf; - getElementsByTagName(tagname: "noscript"): NodeListOf; - getElementsByTagName(tagname: "object"): NodeListOf; - getElementsByTagName(tagname: "ol"): NodeListOf; - getElementsByTagName(tagname: "optgroup"): NodeListOf; - getElementsByTagName(tagname: "option"): NodeListOf; - getElementsByTagName(tagname: "p"): NodeListOf; - getElementsByTagName(tagname: "param"): NodeListOf; - getElementsByTagName(tagname: "path"): NodeListOf; - getElementsByTagName(tagname: "pattern"): NodeListOf; - getElementsByTagName(tagname: "picture"): NodeListOf; - getElementsByTagName(tagname: "plaintext"): NodeListOf; - getElementsByTagName(tagname: "polygon"): NodeListOf; - getElementsByTagName(tagname: "polyline"): NodeListOf; - getElementsByTagName(tagname: "pre"): NodeListOf; - getElementsByTagName(tagname: "progress"): NodeListOf; - getElementsByTagName(tagname: "q"): NodeListOf; - getElementsByTagName(tagname: "radialgradient"): NodeListOf; - getElementsByTagName(tagname: "rect"): NodeListOf; - getElementsByTagName(tagname: "rt"): NodeListOf; - getElementsByTagName(tagname: "ruby"): NodeListOf; - getElementsByTagName(tagname: "s"): NodeListOf; - getElementsByTagName(tagname: "samp"): NodeListOf; - getElementsByTagName(tagname: "script"): NodeListOf; - getElementsByTagName(tagname: "section"): NodeListOf; - getElementsByTagName(tagname: "select"): NodeListOf; - getElementsByTagName(tagname: "small"): NodeListOf; - getElementsByTagName(tagname: "source"): NodeListOf; - getElementsByTagName(tagname: "span"): NodeListOf; - getElementsByTagName(tagname: "stop"): NodeListOf; - getElementsByTagName(tagname: "strike"): NodeListOf; - getElementsByTagName(tagname: "strong"): NodeListOf; - getElementsByTagName(tagname: "style"): NodeListOf; - getElementsByTagName(tagname: "sub"): NodeListOf; - getElementsByTagName(tagname: "sup"): NodeListOf; - getElementsByTagName(tagname: "svg"): NodeListOf; - getElementsByTagName(tagname: "switch"): NodeListOf; - getElementsByTagName(tagname: "symbol"): NodeListOf; - getElementsByTagName(tagname: "table"): NodeListOf; - getElementsByTagName(tagname: "tbody"): NodeListOf; - getElementsByTagName(tagname: "td"): NodeListOf; - getElementsByTagName(tagname: "template"): NodeListOf; - getElementsByTagName(tagname: "text"): NodeListOf; - getElementsByTagName(tagname: "textpath"): NodeListOf; - getElementsByTagName(tagname: "textarea"): NodeListOf; - getElementsByTagName(tagname: "tfoot"): NodeListOf; - getElementsByTagName(tagname: "th"): NodeListOf; - getElementsByTagName(tagname: "thead"): NodeListOf; - getElementsByTagName(tagname: "title"): NodeListOf; - getElementsByTagName(tagname: "tr"): NodeListOf; - getElementsByTagName(tagname: "track"): NodeListOf; - getElementsByTagName(tagname: "tspan"): NodeListOf; - getElementsByTagName(tagname: "tt"): NodeListOf; - getElementsByTagName(tagname: "u"): NodeListOf; - getElementsByTagName(tagname: "ul"): NodeListOf; - getElementsByTagName(tagname: "use"): NodeListOf; - getElementsByTagName(tagname: "var"): NodeListOf; - getElementsByTagName(tagname: "video"): NodeListOf; - getElementsByTagName(tagname: "view"): NodeListOf; - getElementsByTagName(tagname: "wbr"): NodeListOf; - getElementsByTagName(tagname: "x-ms-webview"): NodeListOf; - getElementsByTagName(tagname: "xmp"): NodeListOf; + getElementsByTagName(tagname: K): ElementListTagNameMap[K]; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -3247,103 +3100,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "fullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mssitemodejumplistitemremoved", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msthumbnailclick", listener: (this: this, ev: MSSiteModeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointerlockerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectionchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stop", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -3353,7 +3110,6 @@ declare var Document: { } interface DocumentFragment extends Node, NodeSelector, ParentNode { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var DocumentFragment: { @@ -3368,7 +3124,6 @@ interface DocumentType extends Node, ChildNode { readonly notations: NamedNodeMap; readonly publicId: string | null; readonly systemId: string | null; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var DocumentType: { @@ -3421,6 +3176,36 @@ declare var EXT_texture_filter_anisotropic: { readonly TEXTURE_MAX_ANISOTROPY_EXT: number; } +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": AriaRequestEvent; + "command": CommandEvent; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSGotPointerCapture": MSPointerEvent; + "MSInertiaStart": MSGestureEvent; + "MSLostPointerCapture": MSPointerEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { readonly classList: DOMTokenList; className: string; @@ -3431,33 +3216,33 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec id: string; msContentZoomFactor: number; readonly msRegionOverflow: string; - onariarequest: (this: this, ev: AriaRequestEvent) => any; - oncommand: (this: this, ev: CommandEvent) => any; - ongotpointercapture: (this: this, ev: PointerEvent) => any; - onlostpointercapture: (this: this, ev: PointerEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsgotpointercapture: (this: this, ev: MSPointerEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmslostpointercapture: (this: this, ev: MSPointerEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; + onariarequest: (this: Element, ev: AriaRequestEvent) => any; + oncommand: (this: Element, ev: CommandEvent) => any; + ongotpointercapture: (this: Element, ev: PointerEvent) => any; + onlostpointercapture: (this: Element, ev: PointerEvent) => any; + onmsgesturechange: (this: Element, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Element, ev: MSGestureEvent) => any; + onmsgestureend: (this: Element, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Element, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Element, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Element, ev: MSGestureEvent) => any; + onmsgotpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmsinertiastart: (this: Element, ev: MSGestureEvent) => any; + onmslostpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmspointercancel: (this: Element, ev: MSPointerEvent) => any; + onmspointerdown: (this: Element, ev: MSPointerEvent) => any; + onmspointerenter: (this: Element, ev: MSPointerEvent) => any; + onmspointerleave: (this: Element, ev: MSPointerEvent) => any; + onmspointermove: (this: Element, ev: MSPointerEvent) => any; + onmspointerout: (this: Element, ev: MSPointerEvent) => any; + onmspointerover: (this: Element, ev: MSPointerEvent) => any; + onmspointerup: (this: Element, ev: MSPointerEvent) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; - onwebkitfullscreenchange: (this: this, ev: Event) => any; - onwebkitfullscreenerror: (this: this, ev: Event) => any; + onwebkitfullscreenchange: (this: Element, ev: Event) => any; + onwebkitfullscreenerror: (this: Element, ev: Event) => any; readonly prefix: string | null; readonly scrollHeight: number; scrollLeft: number; @@ -3465,188 +3250,16 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; + readonly assignedSlot: HTMLSlotElement | null; + slot: string; + readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: "a"): NodeListOf; - getElementsByTagName(name: "abbr"): NodeListOf; - getElementsByTagName(name: "acronym"): NodeListOf; - getElementsByTagName(name: "address"): NodeListOf; - getElementsByTagName(name: "applet"): NodeListOf; - getElementsByTagName(name: "area"): NodeListOf; - getElementsByTagName(name: "article"): NodeListOf; - getElementsByTagName(name: "aside"): NodeListOf; - getElementsByTagName(name: "audio"): NodeListOf; - getElementsByTagName(name: "b"): NodeListOf; - getElementsByTagName(name: "base"): NodeListOf; - getElementsByTagName(name: "basefont"): NodeListOf; - getElementsByTagName(name: "bdo"): NodeListOf; - getElementsByTagName(name: "big"): NodeListOf; - getElementsByTagName(name: "blockquote"): NodeListOf; - getElementsByTagName(name: "body"): NodeListOf; - getElementsByTagName(name: "br"): NodeListOf; - getElementsByTagName(name: "button"): NodeListOf; - getElementsByTagName(name: "canvas"): NodeListOf; - getElementsByTagName(name: "caption"): NodeListOf; - getElementsByTagName(name: "center"): NodeListOf; - getElementsByTagName(name: "circle"): NodeListOf; - getElementsByTagName(name: "cite"): NodeListOf; - getElementsByTagName(name: "clippath"): NodeListOf; - getElementsByTagName(name: "code"): NodeListOf; - getElementsByTagName(name: "col"): NodeListOf; - getElementsByTagName(name: "colgroup"): NodeListOf; - getElementsByTagName(name: "datalist"): NodeListOf; - getElementsByTagName(name: "dd"): NodeListOf; - getElementsByTagName(name: "defs"): NodeListOf; - getElementsByTagName(name: "del"): NodeListOf; - getElementsByTagName(name: "desc"): NodeListOf; - getElementsByTagName(name: "dfn"): NodeListOf; - getElementsByTagName(name: "dir"): NodeListOf; - getElementsByTagName(name: "div"): NodeListOf; - getElementsByTagName(name: "dl"): NodeListOf; - getElementsByTagName(name: "dt"): NodeListOf; - getElementsByTagName(name: "ellipse"): NodeListOf; - getElementsByTagName(name: "em"): NodeListOf; - getElementsByTagName(name: "embed"): NodeListOf; - getElementsByTagName(name: "feblend"): NodeListOf; - getElementsByTagName(name: "fecolormatrix"): NodeListOf; - getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(name: "fecomposite"): NodeListOf; - getElementsByTagName(name: "feconvolvematrix"): NodeListOf; - getElementsByTagName(name: "fediffuselighting"): NodeListOf; - getElementsByTagName(name: "fedisplacementmap"): NodeListOf; - getElementsByTagName(name: "fedistantlight"): NodeListOf; - getElementsByTagName(name: "feflood"): NodeListOf; - getElementsByTagName(name: "fefunca"): NodeListOf; - getElementsByTagName(name: "fefuncb"): NodeListOf; - getElementsByTagName(name: "fefuncg"): NodeListOf; - getElementsByTagName(name: "fefuncr"): NodeListOf; - getElementsByTagName(name: "fegaussianblur"): NodeListOf; - getElementsByTagName(name: "feimage"): NodeListOf; - getElementsByTagName(name: "femerge"): NodeListOf; - getElementsByTagName(name: "femergenode"): NodeListOf; - getElementsByTagName(name: "femorphology"): NodeListOf; - getElementsByTagName(name: "feoffset"): NodeListOf; - getElementsByTagName(name: "fepointlight"): NodeListOf; - getElementsByTagName(name: "fespecularlighting"): NodeListOf; - getElementsByTagName(name: "fespotlight"): NodeListOf; - getElementsByTagName(name: "fetile"): NodeListOf; - getElementsByTagName(name: "feturbulence"): NodeListOf; - getElementsByTagName(name: "fieldset"): NodeListOf; - getElementsByTagName(name: "figcaption"): NodeListOf; - getElementsByTagName(name: "figure"): NodeListOf; - getElementsByTagName(name: "filter"): NodeListOf; - getElementsByTagName(name: "font"): NodeListOf; - getElementsByTagName(name: "footer"): NodeListOf; - getElementsByTagName(name: "foreignobject"): NodeListOf; - getElementsByTagName(name: "form"): NodeListOf; - getElementsByTagName(name: "frame"): NodeListOf; - getElementsByTagName(name: "frameset"): NodeListOf; - getElementsByTagName(name: "g"): NodeListOf; - getElementsByTagName(name: "h1"): NodeListOf; - getElementsByTagName(name: "h2"): NodeListOf; - getElementsByTagName(name: "h3"): NodeListOf; - getElementsByTagName(name: "h4"): NodeListOf; - getElementsByTagName(name: "h5"): NodeListOf; - getElementsByTagName(name: "h6"): NodeListOf; - getElementsByTagName(name: "head"): NodeListOf; - getElementsByTagName(name: "header"): NodeListOf; - getElementsByTagName(name: "hgroup"): NodeListOf; - getElementsByTagName(name: "hr"): NodeListOf; - getElementsByTagName(name: "html"): NodeListOf; - getElementsByTagName(name: "i"): NodeListOf; - getElementsByTagName(name: "iframe"): NodeListOf; - getElementsByTagName(name: "image"): NodeListOf; - getElementsByTagName(name: "img"): NodeListOf; - getElementsByTagName(name: "input"): NodeListOf; - getElementsByTagName(name: "ins"): NodeListOf; - getElementsByTagName(name: "isindex"): NodeListOf; - getElementsByTagName(name: "kbd"): NodeListOf; - getElementsByTagName(name: "keygen"): NodeListOf; - getElementsByTagName(name: "label"): NodeListOf; - getElementsByTagName(name: "legend"): NodeListOf; - getElementsByTagName(name: "li"): NodeListOf; - getElementsByTagName(name: "line"): NodeListOf; - getElementsByTagName(name: "lineargradient"): NodeListOf; - getElementsByTagName(name: "link"): NodeListOf; - getElementsByTagName(name: "listing"): NodeListOf; - getElementsByTagName(name: "map"): NodeListOf; - getElementsByTagName(name: "mark"): NodeListOf; - getElementsByTagName(name: "marker"): NodeListOf; - getElementsByTagName(name: "marquee"): NodeListOf; - getElementsByTagName(name: "mask"): NodeListOf; - getElementsByTagName(name: "menu"): NodeListOf; - getElementsByTagName(name: "meta"): NodeListOf; - getElementsByTagName(name: "metadata"): NodeListOf; - getElementsByTagName(name: "meter"): NodeListOf; - getElementsByTagName(name: "nav"): NodeListOf; - getElementsByTagName(name: "nextid"): NodeListOf; - getElementsByTagName(name: "nobr"): NodeListOf; - getElementsByTagName(name: "noframes"): NodeListOf; - getElementsByTagName(name: "noscript"): NodeListOf; - getElementsByTagName(name: "object"): NodeListOf; - getElementsByTagName(name: "ol"): NodeListOf; - getElementsByTagName(name: "optgroup"): NodeListOf; - getElementsByTagName(name: "option"): NodeListOf; - getElementsByTagName(name: "p"): NodeListOf; - getElementsByTagName(name: "param"): NodeListOf; - getElementsByTagName(name: "path"): NodeListOf; - getElementsByTagName(name: "pattern"): NodeListOf; - getElementsByTagName(name: "picture"): NodeListOf; - getElementsByTagName(name: "plaintext"): NodeListOf; - getElementsByTagName(name: "polygon"): NodeListOf; - getElementsByTagName(name: "polyline"): NodeListOf; - getElementsByTagName(name: "pre"): NodeListOf; - getElementsByTagName(name: "progress"): NodeListOf; - getElementsByTagName(name: "q"): NodeListOf; - getElementsByTagName(name: "radialgradient"): NodeListOf; - getElementsByTagName(name: "rect"): NodeListOf; - getElementsByTagName(name: "rt"): NodeListOf; - getElementsByTagName(name: "ruby"): NodeListOf; - getElementsByTagName(name: "s"): NodeListOf; - getElementsByTagName(name: "samp"): NodeListOf; - getElementsByTagName(name: "script"): NodeListOf; - getElementsByTagName(name: "section"): NodeListOf; - getElementsByTagName(name: "select"): NodeListOf; - getElementsByTagName(name: "small"): NodeListOf; - getElementsByTagName(name: "source"): NodeListOf; - getElementsByTagName(name: "span"): NodeListOf; - getElementsByTagName(name: "stop"): NodeListOf; - getElementsByTagName(name: "strike"): NodeListOf; - getElementsByTagName(name: "strong"): NodeListOf; - getElementsByTagName(name: "style"): NodeListOf; - getElementsByTagName(name: "sub"): NodeListOf; - getElementsByTagName(name: "sup"): NodeListOf; - getElementsByTagName(name: "svg"): NodeListOf; - getElementsByTagName(name: "switch"): NodeListOf; - getElementsByTagName(name: "symbol"): NodeListOf; - getElementsByTagName(name: "table"): NodeListOf; - getElementsByTagName(name: "tbody"): NodeListOf; - getElementsByTagName(name: "td"): NodeListOf; - getElementsByTagName(name: "template"): NodeListOf; - getElementsByTagName(name: "text"): NodeListOf; - getElementsByTagName(name: "textpath"): NodeListOf; - getElementsByTagName(name: "textarea"): NodeListOf; - getElementsByTagName(name: "tfoot"): NodeListOf; - getElementsByTagName(name: "th"): NodeListOf; - getElementsByTagName(name: "thead"): NodeListOf; - getElementsByTagName(name: "title"): NodeListOf; - getElementsByTagName(name: "tr"): NodeListOf; - getElementsByTagName(name: "track"): NodeListOf; - getElementsByTagName(name: "tspan"): NodeListOf; - getElementsByTagName(name: "tt"): NodeListOf; - getElementsByTagName(name: "u"): NodeListOf; - getElementsByTagName(name: "ul"): NodeListOf; - getElementsByTagName(name: "use"): NodeListOf; - getElementsByTagName(name: "var"): NodeListOf; - getElementsByTagName(name: "video"): NodeListOf; - getElementsByTagName(name: "view"): NodeListOf; - getElementsByTagName(name: "wbr"): NodeListOf; - getElementsByTagName(name: "x-ms-webview"): NodeListOf; - getElementsByTagName(name: "xmp"): NodeListOf; + getElementsByTagName(name: K): ElementListTagNameMap[K]; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -3686,42 +3299,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentElement(position: string, insertedElement: Element): Element | null; insertAdjacentHTML(where: string, html: string): void; insertAdjacentText(where: string, text: string): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -3757,10 +3336,12 @@ interface Event { readonly target: EventTarget; readonly timeStamp: number; readonly type: string; + readonly scoped: boolean; initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; preventDefault(): void; stopImmediatePropagation(): void; stopPropagation(): void; + deepPath(): EventTarget[]; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; @@ -3821,6 +3402,7 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -3991,6 +3573,8 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLAnchorElement: { @@ -4063,6 +3647,8 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLAppletElement: { @@ -4129,6 +3715,8 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLAreaElement: { @@ -4153,6 +3741,8 @@ declare var HTMLAreasCollection: { } interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLAudioElement: { @@ -4165,6 +3755,8 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLBRElement: { @@ -4181,6 +3773,8 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLBaseElement: { @@ -4197,6 +3791,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -4205,6 +3800,27 @@ declare var HTMLBaseFontElement: { new(): HTMLBaseFontElement; } +interface HTMLBodyElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + interface HTMLBodyElement extends HTMLElement { aLink: any; background: string; @@ -4212,147 +3828,27 @@ interface HTMLBodyElement extends HTMLElement { bgProperties: string; link: any; noWrap: boolean; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; + onafterprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; + onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; + onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; + onload: (this: HTMLBodyElement, ev: Event) => any; + onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; + onoffline: (this: HTMLBodyElement, ev: Event) => any; + ononline: (this: HTMLBodyElement, ev: Event) => any; + onorientationchange: (this: HTMLBodyElement, ev: Event) => any; + onpagehide: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; + onresize: (this: HTMLBodyElement, ev: UIEvent) => any; + onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; + onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -4425,6 +3921,8 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLButtonElement: { @@ -4458,6 +3956,8 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLCanvasElement: { @@ -4488,6 +3988,8 @@ declare var HTMLCollection: { interface HTMLDListElement extends HTMLElement { compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLDListElement: { @@ -4497,6 +3999,8 @@ declare var HTMLDListElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLDataListElement: { @@ -4506,6 +4010,8 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLDirectoryElement: { @@ -4522,6 +4028,8 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLDivElement: { @@ -4530,6 +4038,8 @@ declare var HTMLDivElement: { } interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLDocument: { @@ -4537,6 +4047,76 @@ declare var HTMLDocument: { new(): HTMLDocument; } +interface HTMLElementEventMap extends ElementEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforecopy": ClipboardEvent; + "beforecut": ClipboardEvent; + "beforedeactivate": UIEvent; + "beforepaste": ClipboardEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectstart": Event; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "volumechange": Event; + "waiting": Event; +} + interface HTMLElement extends Element { accessKey: string; readonly children: HTMLCollection; @@ -4555,73 +4135,73 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (this: this, ev: UIEvent) => any; - onactivate: (this: this, ev: UIEvent) => any; - onbeforeactivate: (this: this, ev: UIEvent) => any; - onbeforecopy: (this: this, ev: ClipboardEvent) => any; - onbeforecut: (this: this, ev: ClipboardEvent) => any; - onbeforedeactivate: (this: this, ev: UIEvent) => any; - onbeforepaste: (this: this, ev: ClipboardEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - oncopy: (this: this, ev: ClipboardEvent) => any; - oncuechange: (this: this, ev: Event) => any; - oncut: (this: this, ev: ClipboardEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondeactivate: (this: this, ev: UIEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onfocus: (this: this, ev: FocusEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmscontentzoom: (this: this, ev: UIEvent) => any; - onmsmanipulationstatechanged: (this: this, ev: MSManipulationEvent) => any; - onpaste: (this: this, ev: ClipboardEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreset: (this: this, ev: Event) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onselectstart: (this: this, ev: Event) => any; - onstalled: (this: this, ev: Event) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; + onabort: (this: HTMLElement, ev: UIEvent) => any; + onactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforecopy: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforecut: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforedeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforepaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onblur: (this: HTMLElement, ev: FocusEvent) => any; + oncanplay: (this: HTMLElement, ev: Event) => any; + oncanplaythrough: (this: HTMLElement, ev: Event) => any; + onchange: (this: HTMLElement, ev: Event) => any; + onclick: (this: HTMLElement, ev: MouseEvent) => any; + oncontextmenu: (this: HTMLElement, ev: PointerEvent) => any; + oncopy: (this: HTMLElement, ev: ClipboardEvent) => any; + oncuechange: (this: HTMLElement, ev: Event) => any; + oncut: (this: HTMLElement, ev: ClipboardEvent) => any; + ondblclick: (this: HTMLElement, ev: MouseEvent) => any; + ondeactivate: (this: HTMLElement, ev: UIEvent) => any; + ondrag: (this: HTMLElement, ev: DragEvent) => any; + ondragend: (this: HTMLElement, ev: DragEvent) => any; + ondragenter: (this: HTMLElement, ev: DragEvent) => any; + ondragleave: (this: HTMLElement, ev: DragEvent) => any; + ondragover: (this: HTMLElement, ev: DragEvent) => any; + ondragstart: (this: HTMLElement, ev: DragEvent) => any; + ondrop: (this: HTMLElement, ev: DragEvent) => any; + ondurationchange: (this: HTMLElement, ev: Event) => any; + onemptied: (this: HTMLElement, ev: Event) => any; + onended: (this: HTMLElement, ev: MediaStreamErrorEvent) => any; + onerror: (this: HTMLElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLElement, ev: FocusEvent) => any; + oninput: (this: HTMLElement, ev: Event) => any; + oninvalid: (this: HTMLElement, ev: Event) => any; + onkeydown: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeypress: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeyup: (this: HTMLElement, ev: KeyboardEvent) => any; + onload: (this: HTMLElement, ev: Event) => any; + onloadeddata: (this: HTMLElement, ev: Event) => any; + onloadedmetadata: (this: HTMLElement, ev: Event) => any; + onloadstart: (this: HTMLElement, ev: Event) => any; + onmousedown: (this: HTMLElement, ev: MouseEvent) => any; + onmouseenter: (this: HTMLElement, ev: MouseEvent) => any; + onmouseleave: (this: HTMLElement, ev: MouseEvent) => any; + onmousemove: (this: HTMLElement, ev: MouseEvent) => any; + onmouseout: (this: HTMLElement, ev: MouseEvent) => any; + onmouseover: (this: HTMLElement, ev: MouseEvent) => any; + onmouseup: (this: HTMLElement, ev: MouseEvent) => any; + onmousewheel: (this: HTMLElement, ev: WheelEvent) => any; + onmscontentzoom: (this: HTMLElement, ev: UIEvent) => any; + onmsmanipulationstatechanged: (this: HTMLElement, ev: MSManipulationEvent) => any; + onpaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onpause: (this: HTMLElement, ev: Event) => any; + onplay: (this: HTMLElement, ev: Event) => any; + onplaying: (this: HTMLElement, ev: Event) => any; + onprogress: (this: HTMLElement, ev: ProgressEvent) => any; + onratechange: (this: HTMLElement, ev: Event) => any; + onreset: (this: HTMLElement, ev: Event) => any; + onscroll: (this: HTMLElement, ev: UIEvent) => any; + onseeked: (this: HTMLElement, ev: Event) => any; + onseeking: (this: HTMLElement, ev: Event) => any; + onselect: (this: HTMLElement, ev: UIEvent) => any; + onselectstart: (this: HTMLElement, ev: Event) => any; + onstalled: (this: HTMLElement, ev: Event) => any; + onsubmit: (this: HTMLElement, ev: Event) => any; + onsuspend: (this: HTMLElement, ev: Event) => any; + ontimeupdate: (this: HTMLElement, ev: Event) => any; + onvolumechange: (this: HTMLElement, ev: Event) => any; + onwaiting: (this: HTMLElement, ev: Event) => any; outerHTML: string; outerText: string; spellcheck: boolean; @@ -4634,109 +4214,7 @@ interface HTMLElement extends Element { focus(): void; msGetInputContext(): MSInputMethodContext; setActive(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -4792,6 +4270,7 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -4831,6 +4310,8 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLFieldSetElement: { @@ -4843,6 +4324,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -4918,6 +4400,8 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [name: string]: any; } @@ -4926,6 +4410,10 @@ declare var HTMLFormElement: { new(): HTMLFormElement; } +interface HTMLFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Specifies the properties of a border drawn around an object. @@ -4978,7 +4466,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Raised when the object has been completely received from the server. */ - onload: (this: this, ev: Event) => any; + onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -4991,110 +4479,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5103,6 +4488,25 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; } +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "resize": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + interface HTMLFrameSetElement extends HTMLElement { border: string; /** @@ -5122,152 +4526,34 @@ interface HTMLFrameSetElement extends HTMLElement { */ frameSpacing: any; name: string; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; + onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; /** * Fires when the object loses the input focus. */ - onblur: (this: this, ev: FocusEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; + onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - onload: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onresize: (this: this, ev: UIEvent) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onunload: (this: this, ev: Event) => any; + onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; + onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; + onload: (this: HTMLFrameSetElement, ev: Event) => any; + onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; + onoffline: (this: HTMLFrameSetElement, ev: Event) => any; + ononline: (this: HTMLFrameSetElement, ev: Event) => any; + onorientationchange: (this: HTMLFrameSetElement, ev: Event) => any; + onpagehide: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; + onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; + onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5289,6 +4575,7 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5299,6 +4586,8 @@ declare var HTMLHRElement: { interface HTMLHeadElement extends HTMLElement { profile: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLHeadElement: { @@ -5311,6 +4600,8 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLHeadingElement: { @@ -5323,6 +4614,8 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLHtmlElement: { @@ -5330,6 +4623,10 @@ declare var HTMLHtmlElement: { new(): HTMLHtmlElement; } +interface HTMLIFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. @@ -5387,7 +4684,7 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Raised when the object has been completely received from the server. */ - onload: (this: this, ev: Event) => any; + onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -5405,110 +4702,7 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5599,6 +4793,8 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLImageElement: { @@ -5810,6 +5006,8 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLInputElement: { @@ -5823,6 +5021,8 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLLIElement: { @@ -5839,6 +5039,8 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLLabelElement: { @@ -5855,6 +5057,8 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLLegendElement: { @@ -5898,6 +5102,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5915,6 +5120,8 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMapElement: { @@ -5922,6 +5129,12 @@ declare var HTMLMapElement: { new(): HTMLMapElement; } +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + interface HTMLMarqueeElement extends HTMLElement { behavior: string; bgColor: any; @@ -5929,9 +5142,9 @@ interface HTMLMarqueeElement extends HTMLElement { height: string; hspace: number; loop: number; - onbounce: (this: this, ev: Event) => any; - onfinish: (this: this, ev: Event) => any; - onstart: (this: this, ev: Event) => any; + onbounce: (this: HTMLMarqueeElement, ev: Event) => any; + onfinish: (this: HTMLMarqueeElement, ev: Event) => any; + onstart: (this: HTMLMarqueeElement, ev: Event) => any; scrollAmount: number; scrollDelay: number; trueSpeed: boolean; @@ -5939,112 +5152,7 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "bounce", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "finish", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "start", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6053,6 +5161,11 @@ declare var HTMLMarqueeElement: { new(): HTMLMarqueeElement; } +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": MSMediaKeyNeededEvent; +} + interface HTMLMediaElement extends HTMLElement { /** * Returns an AudioTrackList object with the audio tracks for a given video element. @@ -6142,8 +5255,8 @@ interface HTMLMediaElement extends HTMLElement { * Gets the current network activity for the element. */ readonly networkState: number; - onencrypted: (this: this, ev: MediaEncryptedEvent) => any; - onmsneedkey: (this: this, ev: MSMediaKeyNeededEvent) => any; + onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; + onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; /** * Gets a flag that specifies whether playback is paused. */ @@ -6221,111 +5334,7 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6346,6 +5355,8 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMenuElement: { @@ -6378,6 +5389,8 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMetaElement: { @@ -6392,6 +5405,8 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMeterElement: { @@ -6408,6 +5423,8 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLModElement: { @@ -6422,6 +5439,8 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLOListElement: { @@ -6541,6 +5560,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6579,6 +5599,8 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLOptGroupElement: { @@ -6616,6 +5638,8 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLOptionElement: { @@ -6642,6 +5666,8 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLParagraphElement: { @@ -6666,6 +5692,8 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLParamElement: { @@ -6674,6 +5702,8 @@ declare var HTMLParamElement: { } interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLPictureElement: { @@ -6686,6 +5716,8 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLPreElement: { @@ -6710,6 +5742,8 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLProgressElement: { @@ -6722,6 +5756,8 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLQuoteElement: { @@ -6760,6 +5796,8 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLScriptElement: { @@ -6854,6 +5892,8 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [name: string]: any; } @@ -6878,6 +5918,8 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLSourceElement: { @@ -6886,6 +5928,8 @@ declare var HTMLSourceElement: { } interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLSpanElement: { @@ -6903,6 +5947,7 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6920,6 +5965,8 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableCaptionElement: { @@ -6973,6 +6020,7 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6994,6 +6042,7 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7114,6 +6163,8 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableElement: { @@ -7165,6 +6216,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7192,6 +6244,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7202,6 +6255,8 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTemplateElement: { @@ -7307,6 +6362,8 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTextAreaElement: { @@ -7319,6 +6376,8 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTitleElement: { @@ -7338,6 +6397,8 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTrackElement: { @@ -7352,6 +6413,8 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLUListElement: { @@ -7360,6 +6423,8 @@ declare var HTMLUListElement: { } interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLUnknownElement: { @@ -7367,6 +6432,12 @@ declare var HTMLUnknownElement: { new(): HTMLUnknownElement; } +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + interface HTMLVideoElement extends HTMLMediaElement { /** * Gets or sets the height of the video element. @@ -7378,9 +6449,9 @@ interface HTMLVideoElement extends HTMLMediaElement { msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; - onMSVideoFormatChanged: (this: this, ev: Event) => any; - onMSVideoFrameStepCompleted: (this: this, ev: Event) => any; - onMSVideoOptimalLayoutChanged: (this: this, ev: Event) => any; + onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; /** * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. */ @@ -7407,114 +6478,7 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullscreen(): void; webkitExitFullScreen(): void; webkitExitFullscreen(): void; - addEventListener(type: "MSContentZoom", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSManipulationStateChanged", listener: (this: this, ev: MSManipulationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFormatChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoFrameStepCompleted", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "activate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecopy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforecut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforedeactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "beforepaste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "copy", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "cut", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deactivate", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "encrypted", listener: (this: this, ev: MediaEncryptedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "msneedkey", listener: (this: this, ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; - addEventListener(type: "paste", listener: (this: this, ev: ClipboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "selectstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7582,11 +6546,16 @@ declare var IDBCursorWithValue: { new(): IDBCursorWithValue; } +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -7594,8 +6563,7 @@ interface IDBDatabase extends EventTarget { deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7672,13 +6640,15 @@ declare var IDBObjectStore: { new(): IDBObjectStore; } +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7687,16 +6657,20 @@ declare var IDBOpenDBRequest: { new(): IDBOpenDBRequest; } +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: string; readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7705,21 +6679,25 @@ declare var IDBRequest: { new(): IDBRequest; } +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; readonly error: DOMError; readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7852,18 +6830,22 @@ interface MSApp { } declare var MSApp: MSApp; +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8018,6 +7000,8 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MSHTMLWebViewElement: { @@ -8025,20 +7009,24 @@ declare var MSHTMLWebViewElement: { new(): MSHTMLWebViewElement; } +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + interface MSInputMethodContext extends EventTarget { readonly compositionEndOffset: number; readonly compositionStartOffset: number; - oncandidatewindowhide: (this: this, ev: Event) => any; - oncandidatewindowshow: (this: this, ev: Event) => any; - oncandidatewindowupdate: (this: this, ev: Event) => any; + oncandidatewindowhide: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowshow: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowupdate: (this: MSInputMethodContext, ev: Event) => any; readonly target: HTMLElement; getCandidateWindowClientRect(): ClientRect; getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: "MSCandidateWindowHide", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowShow", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "MSCandidateWindowUpdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8204,6 +7192,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8212,10 +7201,15 @@ declare var MSStreamReader: { new(): MSStreamReader; } +interface MSWebViewAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + oncomplete: (this: MSWebViewAsyncOperation, ev: Event) => any; + onerror: (this: MSWebViewAsyncOperation, ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -8227,8 +7221,7 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8265,12 +7258,16 @@ declare var MediaDeviceInfo: { new(): MediaDeviceInfo; } +interface MediaDevicesEventMap { + "devicechange": Event; +} + interface MediaDevices extends EventTarget { - ondevicechange: (this: this, ev: Event) => any; + ondevicechange: (this: MediaDevices, ev: Event) => any; enumerateDevices(): any; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): PromiseLike; - addEventListener(type: "devicechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8420,13 +7417,20 @@ declare var MediaSource: { isTypeSupported(type: string): boolean; } +interface MediaStreamEventMap { + "active": Event; + "addtrack": TrackEvent; + "inactive": Event; + "removetrack": TrackEvent; +} + interface MediaStream extends EventTarget { readonly active: boolean; readonly id: string; - onactive: (this: this, ev: Event) => any; - onaddtrack: (this: this, ev: TrackEvent) => any; - oninactive: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: TrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: TrackEvent) => any; addTrack(track: MediaStreamTrack): void; clone(): MediaStream; getAudioTracks(): MediaStreamTrack[]; @@ -8435,10 +7439,7 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: "active", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "inactive", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8475,16 +7476,23 @@ declare var MediaStreamErrorEvent: { new(type: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; } +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + interface MediaStreamTrack extends EventTarget { enabled: boolean; readonly id: string; readonly kind: string; readonly label: string; readonly muted: boolean; - onended: (this: this, ev: MediaStreamErrorEvent) => any; - onmute: (this: this, ev: Event) => any; - onoverconstrained: (this: this, ev: MediaStreamErrorEvent) => any; - onunmute: (this: this, ev: Event) => any; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; readonly readonly: boolean; readonly readyState: string; readonly remote: boolean; @@ -8494,10 +7502,7 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "overconstrained", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "unmute", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8538,12 +7543,16 @@ declare var MessageEvent: { new(type: string, eventInitDict?: MessageEventInit): MessageEvent; } +interface MessagePortEventMap { + "message": MessageEvent; +} + interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; + onmessage: (this: MessagePort, ev: MessageEvent) => any; close(): void; postMessage(message?: any, ports?: any): void; start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8602,7 +7611,7 @@ interface MouseEvent extends UIEvent { readonly x: number; readonly y: number; getModifierState(keyArg: string): boolean; - initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; } declare var MouseEvent: { @@ -8715,12 +7724,12 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly plugins: PluginArray; readonly pointerEnabled: boolean; readonly webdriver: boolean; + readonly hardwareConcurrency: number; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): PromiseLike; vibrate(pattern: number | number[]): boolean; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Navigator: { @@ -8732,18 +7741,18 @@ interface Node extends EventTarget { readonly attributes: NamedNodeMap; readonly baseURI: string | null; readonly childNodes: NodeList; - readonly firstChild: Node; - readonly lastChild: Node; + readonly firstChild: Node | null; + readonly lastChild: Node | null; readonly localName: string | null; readonly namespaceURI: string | null; - readonly nextSibling: Node; + readonly nextSibling: Node | null; readonly nodeName: string; readonly nodeType: number; nodeValue: string | null; readonly ownerDocument: Document; - readonly parentElement: HTMLElement; - readonly parentNode: Node; - readonly previousSibling: Node; + readonly parentElement: HTMLElement | null; + readonly parentNode: Node | null; + readonly previousSibling: Node | null; textContent: string | null; appendChild(newChild: Node): Node; cloneNode(deep?: boolean): Node; @@ -8895,10 +7904,14 @@ declare var OfflineAudioCompletionEvent: { new(): OfflineAudioCompletionEvent; } +interface OfflineAudioContextEventMap { + "complete": Event; +} + interface OfflineAudioContext extends AudioContext { - oncomplete: (this: this, ev: Event) => any; + oncomplete: (this: OfflineAudioContext, ev: Event) => any; startRendering(): PromiseLike; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8907,15 +7920,19 @@ declare var OfflineAudioContext: { new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; } +interface OscillatorNodeEventMap { + "ended": MediaStreamErrorEvent; +} + interface OscillatorNode extends AudioNode { readonly detune: AudioParam; readonly frequency: AudioParam; - onended: (this: this, ev: MediaStreamErrorEvent) => any; + onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; type: string; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9294,9 +8311,14 @@ declare var RTCDTMFToneChangeEvent: { new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; } +interface RTCDtlsTransportEventMap { + "dtlsstatechange": RTCDtlsTransportStateChangedEvent; + "error": ErrorEvent; +} + interface RTCDtlsTransport extends RTCStatsProvider { - ondtlsstatechange: ((this: this, ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((this: this, ev: ErrorEvent) => any) | null; + ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -9304,8 +8326,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: "dtlsstatechange", listener: (this: this, ev: RTCDtlsTransportStateChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9323,15 +8344,19 @@ declare var RTCDtlsTransportStateChangedEvent: { new(): RTCDtlsTransportStateChangedEvent; } +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + interface RTCDtmfSender extends EventTarget { readonly canInsertDTMF: boolean; readonly duration: number; readonly interToneGap: number; - ontonechange: (this: this, ev: RTCDTMFToneChangeEvent) => any; + ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: "tonechange", listener: (this: this, ev: RTCDTMFToneChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9349,15 +8374,19 @@ declare var RTCIceCandidatePairChangedEvent: { new(): RTCIceCandidatePairChangedEvent; } +interface RTCIceGathererEventMap { + "error": ErrorEvent; + "localcandidate": RTCIceGathererEvent; +} + interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onlocalcandidate: ((this: this, ev: RTCIceGathererEvent) => any) | null; + onerror: ((this: RTCIceGatherer, ev: ErrorEvent) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "localcandidate", listener: (this: this, ev: RTCIceGathererEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9375,11 +8404,16 @@ declare var RTCIceGathererEvent: { new(): RTCIceGathererEvent; } +interface RTCIceTransportEventMap { + "candidatepairchange": RTCIceCandidatePairChangedEvent; + "icestatechange": RTCIceTransportStateChangedEvent; +} + interface RTCIceTransport extends RTCStatsProvider { readonly component: string; readonly iceGatherer: RTCIceGatherer | null; - oncandidatepairchange: ((this: this, ev: RTCIceCandidatePairChangedEvent) => any) | null; - onicestatechange: ((this: this, ev: RTCIceTransportStateChangedEvent) => any) | null; + oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null; + onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null; readonly role: string; readonly state: string; addRemoteCandidate(remoteCandidate: RTCIceCandidate | RTCIceCandidateComplete): void; @@ -9390,8 +8424,7 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidate[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void; stop(): void; - addEventListener(type: "candidatepairchange", listener: (this: this, ev: RTCIceCandidatePairChangedEvent) => any, useCapture?: boolean): void; - addEventListener(type: "icestatechange", listener: (this: this, ev: RTCIceTransportStateChangedEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9409,8 +8442,12 @@ declare var RTCIceTransportStateChangedEvent: { new(): RTCIceTransportStateChangedEvent; } +interface RTCRtpReceiverEventMap { + "error": ErrorEvent; +} + interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; + onerror: ((this: RTCRtpReceiver, ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9419,7 +8456,7 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9429,9 +8466,14 @@ declare var RTCRtpReceiver: { getCapabilities(kind?: string): RTCRtpCapabilities; } +interface RTCRtpSenderEventMap { + "error": ErrorEvent; + "ssrcconflict": RTCSsrcConflictEvent; +} + interface RTCRtpSender extends RTCStatsProvider { - onerror: ((this: this, ev: ErrorEvent) => any) | null; - onssrcconflict: ((this: this, ev: RTCSsrcConflictEvent) => any) | null; + onerror: ((this: RTCRtpSender, ev: ErrorEvent) => any) | null; + onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9439,8 +8481,7 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ssrcconflict", listener: (this: this, ev: RTCSsrcConflictEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9450,10 +8491,14 @@ declare var RTCRtpSender: { getCapabilities(kind?: string): RTCRtpCapabilities; } +interface RTCSrtpSdesTransportEventMap { + "error": ErrorEvent; +} + interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((this: this, ev: ErrorEvent) => any) | null; + onerror: ((this: RTCSrtpSdesTransport, ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9528,6 +8573,7 @@ declare var Range: { interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9684,6 +8730,7 @@ interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SV readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9694,6 +8741,7 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9716,6 +8764,8 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGComponentTransferFunctionElement: { @@ -9730,6 +8780,7 @@ declare var SVGComponentTransferFunctionElement: { } interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9739,6 +8790,7 @@ declare var SVGDefsElement: { } interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9747,67 +8799,35 @@ declare var SVGDescElement: { new(): SVGDescElement; } +interface SVGElementEventMap extends ElementEventMap { + "click": MouseEvent; + "dblclick": MouseEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "load": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; +} + interface SVGElement extends Element { - onclick: (this: this, ev: MouseEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - onfocusin: (this: this, ev: FocusEvent) => any; - onfocusout: (this: this, ev: FocusEvent) => any; - onload: (this: this, ev: Event) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; + onclick: (this: SVGElement, ev: MouseEvent) => any; + ondblclick: (this: SVGElement, ev: MouseEvent) => any; + onfocusin: (this: SVGElement, ev: FocusEvent) => any; + onfocusout: (this: SVGElement, ev: FocusEvent) => any; + onload: (this: SVGElement, ev: Event) => any; + onmousedown: (this: SVGElement, ev: MouseEvent) => any; + onmousemove: (this: SVGElement, ev: MouseEvent) => any; + onmouseout: (this: SVGElement, ev: MouseEvent) => any; + onmouseover: (this: SVGElement, ev: MouseEvent) => any; + onmouseup: (this: SVGElement, ev: MouseEvent) => any; readonly ownerSVGElement: SVGSVGElement; readonly viewportElement: SVGElement; xmlbase: string; className: any; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9847,6 +8867,7 @@ interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, S readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9876,6 +8897,7 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9910,6 +8932,7 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9925,6 +8948,7 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9948,6 +8972,7 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9980,6 +9005,7 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -9998,6 +9024,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10017,6 +9044,7 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10033,6 +9061,8 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEDistantLightElement: { @@ -10041,6 +9071,7 @@ declare var SVGFEDistantLightElement: { } interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10086,6 +9117,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10096,6 +9128,7 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10105,6 +9138,7 @@ declare var SVGFEImageElement: { } interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10115,6 +9149,8 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEMergeNodeElement: { @@ -10130,6 +9166,7 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10145,6 +9182,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10157,6 +9195,8 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEPointLightElement: { @@ -10171,6 +9211,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10188,6 +9229,8 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFESpotLightElement: { @@ -10197,6 +9240,7 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10218,6 +9262,7 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10242,6 +9287,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLan readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10255,6 +9301,7 @@ interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransforma readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10264,6 +9311,7 @@ declare var SVGForeignObjectElement: { } interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10280,6 +9328,7 @@ interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourc readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10298,6 +9347,7 @@ interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVG readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10363,6 +9413,7 @@ interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGT readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10399,6 +9450,7 @@ interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExt readonly SVG_MARKER_ORIENT_ANGLE: number; readonly SVG_MARKER_ORIENT_AUTO: number; readonly SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10420,6 +9472,7 @@ interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10454,6 +9507,8 @@ declare var SVGMatrix: { } interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGMetadataElement: { @@ -10509,6 +9564,7 @@ interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGT getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10801,6 +9857,7 @@ interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSp readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10837,6 +9894,7 @@ declare var SVGPointList: { } interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10846,6 +9904,7 @@ declare var SVGPolygonElement: { } interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10924,6 +9983,7 @@ interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGT readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10932,18 +9992,27 @@ declare var SVGRectElement: { new(): SVGRectElement; } +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { contentScriptType: string; contentStyleType: string; currentScale: number; readonly currentTranslate: SVGPoint; readonly height: SVGAnimatedLength; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onunload: (this: this, ev: Event) => any; - onzoom: (this: this, ev: SVGZoomEvent) => any; + onabort: (this: SVGSVGElement, ev: Event) => any; + onerror: (this: SVGSVGElement, ev: Event) => any; + onresize: (this: SVGSVGElement, ev: UIEvent) => any; + onscroll: (this: SVGSVGElement, ev: UIEvent) => any; + onunload: (this: SVGSVGElement, ev: Event) => any; + onzoom: (this: SVGSVGElement, ev: SVGZoomEvent) => any; readonly pixelUnitToMillimeterX: number; readonly pixelUnitToMillimeterY: number; readonly screenPixelToMillimeterX: number; @@ -10975,58 +10044,7 @@ interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTest unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGotPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSLostPointerCapture", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "SVGAbort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGError", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGUnload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "SVGZoom", listener: (this: this, ev: SVGZoomEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ariarequest", listener: (this: this, ev: AriaRequestEvent) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "command", listener: (this: this, ev: CommandEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusin", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focusout", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "gotpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "lostpointercapture", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchcancel", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchend", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchmove", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "touchstart", listener: (this: this, ev: TouchEvent) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "webkitfullscreenerror", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11037,6 +10055,7 @@ declare var SVGSVGElement: { interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11047,6 +10066,7 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement, SVGStylable { readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11076,6 +10096,7 @@ interface SVGStyleElement extends SVGElement, SVGLangSpace { media: string; title: string; type: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11085,6 +10106,7 @@ declare var SVGStyleElement: { } interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11094,6 +10116,7 @@ declare var SVGSwitchElement: { } interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11125,6 +10148,7 @@ interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLa readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11137,7 +10161,6 @@ declare var SVGTextContentElement: { } interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTextElement: { @@ -11155,7 +10178,6 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTextPathElement: { @@ -11183,6 +10205,7 @@ declare var SVGTextPositioningElement: { } interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11254,6 +10277,7 @@ interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTe readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11264,6 +10288,7 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11295,6 +10320,10 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; } +interface ScreenEventMap { + "MSOrientationChange": Event; +} + interface Screen extends EventTarget { readonly availHeight: number; readonly availWidth: number; @@ -11307,14 +10336,14 @@ interface Screen extends EventTarget { readonly logicalXDPI: number; readonly logicalYDPI: number; readonly msOrientation: string; - onmsorientationchange: (this: this, ev: Event) => any; + onmsorientationchange: (this: Screen, ev: Event) => any; readonly pixelDepth: number; readonly systemXDPI: number; readonly systemYDPI: number; readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: "MSOrientationChange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11333,10 +10362,14 @@ declare var ScriptNotifyEvent: { new(): ScriptNotifyEvent; } +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; - onaudioprocess: (this: this, ev: AudioProcessingEvent) => any; - addEventListener(type: "audioprocess", listener: (this: this, ev: AudioProcessingEvent) => any, useCapture?: boolean): void; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11518,6 +10551,7 @@ declare var SubtleCrypto: { interface Text extends CharacterData { readonly wholeText: string; + readonly assignedSlot: HTMLSlotElement | null; splitText(offset: number): Text; } @@ -11567,6 +10601,12 @@ declare var TextMetrics: { new(): TextMetrics; } +interface TextTrackEventMap { + "cuechange": Event; + "error": ErrorEvent; + "load": Event; +} + interface TextTrack extends EventTarget { readonly activeCues: TextTrackCueList; readonly cues: TextTrackCueList; @@ -11575,9 +10615,9 @@ interface TextTrack extends EventTarget { readonly label: string; readonly language: string; mode: any; - oncuechange: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; + oncuechange: (this: TextTrack, ev: Event) => any; + onerror: (this: TextTrack, ev: ErrorEvent) => any; + onload: (this: TextTrack, ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; @@ -11588,9 +10628,7 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: "cuechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11606,18 +10644,22 @@ declare var TextTrack: { readonly SHOWING: number; } +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + interface TextTrackCue extends EventTarget { endTime: number; id: string; - onenter: (this: this, ev: Event) => any; - onexit: (this: this, ev: Event) => any; + onenter: (this: TextTrackCue, ev: Event) => any; + onexit: (this: TextTrackCue, ev: Event) => any; pauseOnExit: boolean; startTime: number; text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: "enter", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "exit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11638,11 +10680,15 @@ declare var TextTrackCueList: { new(): TextTrackCueList; } +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + interface TextTrackList extends EventTarget { readonly length: number; - onaddtrack: ((this: this, ev: TrackEvent) => any) | null; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: TextTrack; } @@ -11832,17 +10878,21 @@ declare var VideoTrack: { new(): VideoTrack; } +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + interface VideoTrackList extends EventTarget { readonly length: number; - onaddtrack: (this: this, ev: TrackEvent) => any; - onchange: (this: this, ev: Event) => any; - onremovetrack: (this: this, ev: TrackEvent) => any; + onaddtrack: (this: VideoTrackList, ev: TrackEvent) => any; + onchange: (this: VideoTrackList, ev: Event) => any; + onremovetrack: (this: VideoTrackList, ev: TrackEvent) => any; readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: "addtrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "removetrack", listener: (this: this, ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: VideoTrack; } @@ -12788,14 +11838,21 @@ declare var WebKitPoint: { new(x?: number, y?: number): WebKitPoint; } +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + interface WebSocket extends EventTarget { binaryType: string; readonly bufferedAmount: number; readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; readonly protocol: string; readonly readyState: number; readonly url: string; @@ -12805,10 +11862,7 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -12844,6 +11898,95 @@ declare var WheelEvent: { readonly DOM_DELTA_PIXEL: number; } +interface WindowEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "unload": Event; + "volumechange": Event; + "waiting": Event; +} + interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { readonly applicationCache: ApplicationCache; readonly clientInformation: Navigator; @@ -12853,7 +11996,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly devicePixelRatio: number; readonly doNotTrack: string; readonly document: Document; - event: Event; + event: Event | undefined; readonly external: External; readonly frameElement: Element; readonly frames: Window; @@ -12868,97 +12011,97 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (this: this, ev: UIEvent) => any; - onafterprint: (this: this, ev: Event) => any; - onbeforeprint: (this: this, ev: Event) => any; - onbeforeunload: (this: this, ev: BeforeUnloadEvent) => any; - onblur: (this: this, ev: FocusEvent) => any; - oncanplay: (this: this, ev: Event) => any; - oncanplaythrough: (this: this, ev: Event) => any; - onchange: (this: this, ev: Event) => any; - onclick: (this: this, ev: MouseEvent) => any; - oncompassneedscalibration: (this: this, ev: Event) => any; - oncontextmenu: (this: this, ev: PointerEvent) => any; - ondblclick: (this: this, ev: MouseEvent) => any; - ondevicelight: (this: this, ev: DeviceLightEvent) => any; - ondevicemotion: (this: this, ev: DeviceMotionEvent) => any; - ondeviceorientation: (this: this, ev: DeviceOrientationEvent) => any; - ondrag: (this: this, ev: DragEvent) => any; - ondragend: (this: this, ev: DragEvent) => any; - ondragenter: (this: this, ev: DragEvent) => any; - ondragleave: (this: this, ev: DragEvent) => any; - ondragover: (this: this, ev: DragEvent) => any; - ondragstart: (this: this, ev: DragEvent) => any; - ondrop: (this: this, ev: DragEvent) => any; - ondurationchange: (this: this, ev: Event) => any; - onemptied: (this: this, ev: Event) => any; - onended: (this: this, ev: MediaStreamErrorEvent) => any; + onabort: (this: Window, ev: UIEvent) => any; + onafterprint: (this: Window, ev: Event) => any; + onbeforeprint: (this: Window, ev: Event) => any; + onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; + onblur: (this: Window, ev: FocusEvent) => any; + oncanplay: (this: Window, ev: Event) => any; + oncanplaythrough: (this: Window, ev: Event) => any; + onchange: (this: Window, ev: Event) => any; + onclick: (this: Window, ev: MouseEvent) => any; + oncompassneedscalibration: (this: Window, ev: Event) => any; + oncontextmenu: (this: Window, ev: PointerEvent) => any; + ondblclick: (this: Window, ev: MouseEvent) => any; + ondevicelight: (this: Window, ev: DeviceLightEvent) => any; + ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; + ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; + ondrag: (this: Window, ev: DragEvent) => any; + ondragend: (this: Window, ev: DragEvent) => any; + ondragenter: (this: Window, ev: DragEvent) => any; + ondragleave: (this: Window, ev: DragEvent) => any; + ondragover: (this: Window, ev: DragEvent) => any; + ondragstart: (this: Window, ev: DragEvent) => any; + ondrop: (this: Window, ev: DragEvent) => any; + ondurationchange: (this: Window, ev: Event) => any; + onemptied: (this: Window, ev: Event) => any; + onended: (this: Window, ev: MediaStreamErrorEvent) => any; onerror: ErrorEventHandler; - onfocus: (this: this, ev: FocusEvent) => any; - onhashchange: (this: this, ev: HashChangeEvent) => any; - oninput: (this: this, ev: Event) => any; - oninvalid: (this: this, ev: Event) => any; - onkeydown: (this: this, ev: KeyboardEvent) => any; - onkeypress: (this: this, ev: KeyboardEvent) => any; - onkeyup: (this: this, ev: KeyboardEvent) => any; - onload: (this: this, ev: Event) => any; - onloadeddata: (this: this, ev: Event) => any; - onloadedmetadata: (this: this, ev: Event) => any; - onloadstart: (this: this, ev: Event) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onmousedown: (this: this, ev: MouseEvent) => any; - onmouseenter: (this: this, ev: MouseEvent) => any; - onmouseleave: (this: this, ev: MouseEvent) => any; - onmousemove: (this: this, ev: MouseEvent) => any; - onmouseout: (this: this, ev: MouseEvent) => any; - onmouseover: (this: this, ev: MouseEvent) => any; - onmouseup: (this: this, ev: MouseEvent) => any; - onmousewheel: (this: this, ev: WheelEvent) => any; - onmsgesturechange: (this: this, ev: MSGestureEvent) => any; - onmsgesturedoubletap: (this: this, ev: MSGestureEvent) => any; - onmsgestureend: (this: this, ev: MSGestureEvent) => any; - onmsgesturehold: (this: this, ev: MSGestureEvent) => any; - onmsgesturestart: (this: this, ev: MSGestureEvent) => any; - onmsgesturetap: (this: this, ev: MSGestureEvent) => any; - onmsinertiastart: (this: this, ev: MSGestureEvent) => any; - onmspointercancel: (this: this, ev: MSPointerEvent) => any; - onmspointerdown: (this: this, ev: MSPointerEvent) => any; - onmspointerenter: (this: this, ev: MSPointerEvent) => any; - onmspointerleave: (this: this, ev: MSPointerEvent) => any; - onmspointermove: (this: this, ev: MSPointerEvent) => any; - onmspointerout: (this: this, ev: MSPointerEvent) => any; - onmspointerover: (this: this, ev: MSPointerEvent) => any; - onmspointerup: (this: this, ev: MSPointerEvent) => any; - onoffline: (this: this, ev: Event) => any; - ononline: (this: this, ev: Event) => any; - onorientationchange: (this: this, ev: Event) => any; - onpagehide: (this: this, ev: PageTransitionEvent) => any; - onpageshow: (this: this, ev: PageTransitionEvent) => any; - onpause: (this: this, ev: Event) => any; - onplay: (this: this, ev: Event) => any; - onplaying: (this: this, ev: Event) => any; - onpopstate: (this: this, ev: PopStateEvent) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - onratechange: (this: this, ev: Event) => any; - onreadystatechange: (this: this, ev: ProgressEvent) => any; - onreset: (this: this, ev: Event) => any; - onresize: (this: this, ev: UIEvent) => any; - onscroll: (this: this, ev: UIEvent) => any; - onseeked: (this: this, ev: Event) => any; - onseeking: (this: this, ev: Event) => any; - onselect: (this: this, ev: UIEvent) => any; - onstalled: (this: this, ev: Event) => any; - onstorage: (this: this, ev: StorageEvent) => any; - onsubmit: (this: this, ev: Event) => any; - onsuspend: (this: this, ev: Event) => any; - ontimeupdate: (this: this, ev: Event) => any; + onfocus: (this: Window, ev: FocusEvent) => any; + onhashchange: (this: Window, ev: HashChangeEvent) => any; + oninput: (this: Window, ev: Event) => any; + oninvalid: (this: Window, ev: Event) => any; + onkeydown: (this: Window, ev: KeyboardEvent) => any; + onkeypress: (this: Window, ev: KeyboardEvent) => any; + onkeyup: (this: Window, ev: KeyboardEvent) => any; + onload: (this: Window, ev: Event) => any; + onloadeddata: (this: Window, ev: Event) => any; + onloadedmetadata: (this: Window, ev: Event) => any; + onloadstart: (this: Window, ev: Event) => any; + onmessage: (this: Window, ev: MessageEvent) => any; + onmousedown: (this: Window, ev: MouseEvent) => any; + onmouseenter: (this: Window, ev: MouseEvent) => any; + onmouseleave: (this: Window, ev: MouseEvent) => any; + onmousemove: (this: Window, ev: MouseEvent) => any; + onmouseout: (this: Window, ev: MouseEvent) => any; + onmouseover: (this: Window, ev: MouseEvent) => any; + onmouseup: (this: Window, ev: MouseEvent) => any; + onmousewheel: (this: Window, ev: WheelEvent) => any; + onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; + onmsgestureend: (this: Window, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; + onmspointercancel: (this: Window, ev: MSPointerEvent) => any; + onmspointerdown: (this: Window, ev: MSPointerEvent) => any; + onmspointerenter: (this: Window, ev: MSPointerEvent) => any; + onmspointerleave: (this: Window, ev: MSPointerEvent) => any; + onmspointermove: (this: Window, ev: MSPointerEvent) => any; + onmspointerout: (this: Window, ev: MSPointerEvent) => any; + onmspointerover: (this: Window, ev: MSPointerEvent) => any; + onmspointerup: (this: Window, ev: MSPointerEvent) => any; + onoffline: (this: Window, ev: Event) => any; + ononline: (this: Window, ev: Event) => any; + onorientationchange: (this: Window, ev: Event) => any; + onpagehide: (this: Window, ev: PageTransitionEvent) => any; + onpageshow: (this: Window, ev: PageTransitionEvent) => any; + onpause: (this: Window, ev: Event) => any; + onplay: (this: Window, ev: Event) => any; + onplaying: (this: Window, ev: Event) => any; + onpopstate: (this: Window, ev: PopStateEvent) => any; + onprogress: (this: Window, ev: ProgressEvent) => any; + onratechange: (this: Window, ev: Event) => any; + onreadystatechange: (this: Window, ev: ProgressEvent) => any; + onreset: (this: Window, ev: Event) => any; + onresize: (this: Window, ev: UIEvent) => any; + onscroll: (this: Window, ev: UIEvent) => any; + onseeked: (this: Window, ev: Event) => any; + onseeking: (this: Window, ev: Event) => any; + onselect: (this: Window, ev: UIEvent) => any; + onstalled: (this: Window, ev: Event) => any; + onstorage: (this: Window, ev: StorageEvent) => any; + onsubmit: (this: Window, ev: Event) => any; + onsuspend: (this: Window, ev: Event) => any; + ontimeupdate: (this: Window, ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; - onunload: (this: this, ev: Event) => any; - onvolumechange: (this: this, ev: Event) => any; - onwaiting: (this: this, ev: Event) => any; + onunload: (this: Window, ev: Event) => any; + onvolumechange: (this: Window, ev: Event) => any; + onwaiting: (this: Window, ev: Event) => any; opener: any; orientation: string | number; readonly outerHeight: number; @@ -13017,101 +12160,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: "MSGestureChange", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureDoubleTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureEnd", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureHold", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSGestureTap", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSInertiaStart", listener: (this: this, ev: MSGestureEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerCancel", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerDown", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerEnter", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerLeave", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerMove", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOut", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerOver", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "MSPointerUp", listener: (this: this, ev: MSPointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "afterprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeprint", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "beforeunload", listener: (this: this, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; - addEventListener(type: "blur", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "canplay", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "canplaythrough", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "click", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "compassneedscalibration", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "contextmenu", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dblclick", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicelight", listener: (this: this, ev: DeviceLightEvent) => any, useCapture?: boolean): void; - addEventListener(type: "devicemotion", listener: (this: this, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "deviceorientation", listener: (this: this, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drag", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragend", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragenter", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragleave", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragover", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "dragstart", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "drop", listener: (this: this, ev: DragEvent) => any, useCapture?: boolean): void; - addEventListener(type: "durationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "emptied", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "ended", listener: (this: this, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "focus", listener: (this: this, ev: FocusEvent) => any, useCapture?: boolean): void; - addEventListener(type: "hashchange", listener: (this: this, ev: HashChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "input", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "invalid", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "keydown", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keypress", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "keyup", listener: (this: this, ev: KeyboardEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadeddata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadedmetadata", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousedown", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseenter", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseleave", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousemove", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseout", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseover", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mouseup", listener: (this: this, ev: MouseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "mousewheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; - addEventListener(type: "offline", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "online", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "orientationchange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pagehide", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pageshow", listener: (this: this, ev: PageTransitionEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pause", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "play", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "playing", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "popstate", listener: (this: this, ev: PopStateEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "ratechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "reset", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "resize", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "scroll", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "seeked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "seeking", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "select", listener: (this: this, ev: UIEvent) => any, useCapture?: boolean): void; - addEventListener(type: "stalled", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "storage", listener: (this: this, ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "submit", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "suspend", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeupdate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "unload", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "volumechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13120,12 +12169,15 @@ declare var Window: { new(): Window; } +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; + onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, ports?: any): void; terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13135,6 +12187,8 @@ declare var Worker: { } interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var XMLDocument: { @@ -13142,8 +12196,12 @@ declare var XMLDocument: { new(): XMLDocument; } +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: Event) => any; + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13155,6 +12213,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; withCredentials: boolean; msCaching?: string; + readonly responseURL: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -13170,14 +12229,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13193,6 +12245,7 @@ declare var XMLHttpRequest: { } interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13213,7 +12266,7 @@ declare var XMLSerializer: { interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; } declare var XPathEvaluator: { @@ -13222,7 +12275,7 @@ declare var XPathEvaluator: { } interface XPathExpression { - evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; } declare var XPathExpression: { @@ -13292,9 +12345,13 @@ declare var XSLTProcessor: { new(): XSLTProcessor; } +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13405,25 +12462,29 @@ interface GetSVGDocument { getSVGDocument(): Document; } +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; +} + interface GlobalEventHandlers { - onpointercancel: (this: this, ev: PointerEvent) => any; - onpointerdown: (this: this, ev: PointerEvent) => any; - onpointerenter: (this: this, ev: PointerEvent) => any; - onpointerleave: (this: this, ev: PointerEvent) => any; - onpointermove: (this: this, ev: PointerEvent) => any; - onpointerout: (this: this, ev: PointerEvent) => any; - onpointerover: (this: this, ev: PointerEvent) => any; - onpointerup: (this: this, ev: PointerEvent) => any; - onwheel: (this: this, ev: WheelEvent) => any; - addEventListener(type: "pointercancel", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerdown", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerenter", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerleave", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointermove", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerout", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerover", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "pointerup", listener: (this: this, ev: PointerEvent) => any, useCapture?: boolean): void; - addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; + onpointercancel: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerdown: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerenter: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerleave: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointermove: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerout: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13450,25 +12511,29 @@ interface LinkStyle { readonly sheet: StyleSheet; } +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; readonly readyState: number; readonly result: any; abort(): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13517,359 +12582,9 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement | null; - querySelector(selectors: "abbr"): HTMLElement | null; - querySelector(selectors: "acronym"): HTMLElement | null; - querySelector(selectors: "address"): HTMLElement | null; - querySelector(selectors: "applet"): HTMLAppletElement | null; - querySelector(selectors: "area"): HTMLAreaElement | null; - querySelector(selectors: "article"): HTMLElement | null; - querySelector(selectors: "aside"): HTMLElement | null; - querySelector(selectors: "audio"): HTMLAudioElement | null; - querySelector(selectors: "b"): HTMLElement | null; - querySelector(selectors: "base"): HTMLBaseElement | null; - querySelector(selectors: "basefont"): HTMLBaseFontElement | null; - querySelector(selectors: "bdo"): HTMLElement | null; - querySelector(selectors: "big"): HTMLElement | null; - querySelector(selectors: "blockquote"): HTMLQuoteElement | null; - querySelector(selectors: "body"): HTMLBodyElement | null; - querySelector(selectors: "br"): HTMLBRElement | null; - querySelector(selectors: "button"): HTMLButtonElement | null; - querySelector(selectors: "canvas"): HTMLCanvasElement | null; - querySelector(selectors: "caption"): HTMLTableCaptionElement | null; - querySelector(selectors: "center"): HTMLElement | null; - querySelector(selectors: "circle"): SVGCircleElement | null; - querySelector(selectors: "cite"): HTMLElement | null; - querySelector(selectors: "clippath"): SVGClipPathElement | null; - querySelector(selectors: "code"): HTMLElement | null; - querySelector(selectors: "col"): HTMLTableColElement | null; - querySelector(selectors: "colgroup"): HTMLTableColElement | null; - querySelector(selectors: "datalist"): HTMLDataListElement | null; - querySelector(selectors: "dd"): HTMLElement | null; - querySelector(selectors: "defs"): SVGDefsElement | null; - querySelector(selectors: "del"): HTMLModElement | null; - querySelector(selectors: "desc"): SVGDescElement | null; - querySelector(selectors: "dfn"): HTMLElement | null; - querySelector(selectors: "dir"): HTMLDirectoryElement | null; - querySelector(selectors: "div"): HTMLDivElement | null; - querySelector(selectors: "dl"): HTMLDListElement | null; - querySelector(selectors: "dt"): HTMLElement | null; - querySelector(selectors: "ellipse"): SVGEllipseElement | null; - querySelector(selectors: "em"): HTMLElement | null; - querySelector(selectors: "embed"): HTMLEmbedElement | null; - querySelector(selectors: "feblend"): SVGFEBlendElement | null; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; - querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; - querySelector(selectors: "feflood"): SVGFEFloodElement | null; - querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; - querySelector(selectors: "feimage"): SVGFEImageElement | null; - querySelector(selectors: "femerge"): SVGFEMergeElement | null; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; - querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; - querySelector(selectors: "fetile"): SVGFETileElement | null; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; - querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; - querySelector(selectors: "figcaption"): HTMLElement | null; - querySelector(selectors: "figure"): HTMLElement | null; - querySelector(selectors: "filter"): SVGFilterElement | null; - querySelector(selectors: "font"): HTMLFontElement | null; - querySelector(selectors: "footer"): HTMLElement | null; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; - querySelector(selectors: "form"): HTMLFormElement | null; - querySelector(selectors: "frame"): HTMLFrameElement | null; - querySelector(selectors: "frameset"): HTMLFrameSetElement | null; - querySelector(selectors: "g"): SVGGElement | null; - querySelector(selectors: "h1"): HTMLHeadingElement | null; - querySelector(selectors: "h2"): HTMLHeadingElement | null; - querySelector(selectors: "h3"): HTMLHeadingElement | null; - querySelector(selectors: "h4"): HTMLHeadingElement | null; - querySelector(selectors: "h5"): HTMLHeadingElement | null; - querySelector(selectors: "h6"): HTMLHeadingElement | null; - querySelector(selectors: "head"): HTMLHeadElement | null; - querySelector(selectors: "header"): HTMLElement | null; - querySelector(selectors: "hgroup"): HTMLElement | null; - querySelector(selectors: "hr"): HTMLHRElement | null; - querySelector(selectors: "html"): HTMLHtmlElement | null; - querySelector(selectors: "i"): HTMLElement | null; - querySelector(selectors: "iframe"): HTMLIFrameElement | null; - querySelector(selectors: "image"): SVGImageElement | null; - querySelector(selectors: "img"): HTMLImageElement | null; - querySelector(selectors: "input"): HTMLInputElement | null; - querySelector(selectors: "ins"): HTMLModElement | null; - querySelector(selectors: "isindex"): HTMLUnknownElement | null; - querySelector(selectors: "kbd"): HTMLElement | null; - querySelector(selectors: "keygen"): HTMLElement | null; - querySelector(selectors: "label"): HTMLLabelElement | null; - querySelector(selectors: "legend"): HTMLLegendElement | null; - querySelector(selectors: "li"): HTMLLIElement | null; - querySelector(selectors: "line"): SVGLineElement | null; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; - querySelector(selectors: "link"): HTMLLinkElement | null; - querySelector(selectors: "listing"): HTMLPreElement | null; - querySelector(selectors: "map"): HTMLMapElement | null; - querySelector(selectors: "mark"): HTMLElement | null; - querySelector(selectors: "marker"): SVGMarkerElement | null; - querySelector(selectors: "marquee"): HTMLMarqueeElement | null; - querySelector(selectors: "mask"): SVGMaskElement | null; - querySelector(selectors: "menu"): HTMLMenuElement | null; - querySelector(selectors: "meta"): HTMLMetaElement | null; - querySelector(selectors: "metadata"): SVGMetadataElement | null; - querySelector(selectors: "meter"): HTMLMeterElement | null; - querySelector(selectors: "nav"): HTMLElement | null; - querySelector(selectors: "nextid"): HTMLUnknownElement | null; - querySelector(selectors: "nobr"): HTMLElement | null; - querySelector(selectors: "noframes"): HTMLElement | null; - querySelector(selectors: "noscript"): HTMLElement | null; - querySelector(selectors: "object"): HTMLObjectElement | null; - querySelector(selectors: "ol"): HTMLOListElement | null; - querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; - querySelector(selectors: "option"): HTMLOptionElement | null; - querySelector(selectors: "p"): HTMLParagraphElement | null; - querySelector(selectors: "param"): HTMLParamElement | null; - querySelector(selectors: "path"): SVGPathElement | null; - querySelector(selectors: "pattern"): SVGPatternElement | null; - querySelector(selectors: "picture"): HTMLPictureElement | null; - querySelector(selectors: "plaintext"): HTMLElement | null; - querySelector(selectors: "polygon"): SVGPolygonElement | null; - querySelector(selectors: "polyline"): SVGPolylineElement | null; - querySelector(selectors: "pre"): HTMLPreElement | null; - querySelector(selectors: "progress"): HTMLProgressElement | null; - querySelector(selectors: "q"): HTMLQuoteElement | null; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; - querySelector(selectors: "rect"): SVGRectElement | null; - querySelector(selectors: "rt"): HTMLElement | null; - querySelector(selectors: "ruby"): HTMLElement | null; - querySelector(selectors: "s"): HTMLElement | null; - querySelector(selectors: "samp"): HTMLElement | null; - querySelector(selectors: "script"): HTMLScriptElement | null; - querySelector(selectors: "section"): HTMLElement | null; - querySelector(selectors: "select"): HTMLSelectElement | null; - querySelector(selectors: "small"): HTMLElement | null; - querySelector(selectors: "source"): HTMLSourceElement | null; - querySelector(selectors: "span"): HTMLSpanElement | null; - querySelector(selectors: "stop"): SVGStopElement | null; - querySelector(selectors: "strike"): HTMLElement | null; - querySelector(selectors: "strong"): HTMLElement | null; - querySelector(selectors: "style"): HTMLStyleElement | null; - querySelector(selectors: "sub"): HTMLElement | null; - querySelector(selectors: "sup"): HTMLElement | null; - querySelector(selectors: "svg"): SVGSVGElement | null; - querySelector(selectors: "switch"): SVGSwitchElement | null; - querySelector(selectors: "symbol"): SVGSymbolElement | null; - querySelector(selectors: "table"): HTMLTableElement | null; - querySelector(selectors: "tbody"): HTMLTableSectionElement | null; - querySelector(selectors: "td"): HTMLTableDataCellElement | null; - querySelector(selectors: "template"): HTMLTemplateElement | null; - querySelector(selectors: "text"): SVGTextElement | null; - querySelector(selectors: "textpath"): SVGTextPathElement | null; - querySelector(selectors: "textarea"): HTMLTextAreaElement | null; - querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; - querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; - querySelector(selectors: "thead"): HTMLTableSectionElement | null; - querySelector(selectors: "title"): HTMLTitleElement | null; - querySelector(selectors: "tr"): HTMLTableRowElement | null; - querySelector(selectors: "track"): HTMLTrackElement | null; - querySelector(selectors: "tspan"): SVGTSpanElement | null; - querySelector(selectors: "tt"): HTMLElement | null; - querySelector(selectors: "u"): HTMLElement | null; - querySelector(selectors: "ul"): HTMLUListElement | null; - querySelector(selectors: "use"): SVGUseElement | null; - querySelector(selectors: "var"): HTMLElement | null; - querySelector(selectors: "video"): HTMLVideoElement | null; - querySelector(selectors: "view"): SVGViewElement | null; - querySelector(selectors: "wbr"): HTMLElement | null; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; - querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: K): ElementTagNameMap[K] | null; querySelector(selectors: string): Element | null; - 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: K): ElementListTagNameMap[K]; querySelectorAll(selectors: string): NodeListOf; } @@ -13969,21 +12684,25 @@ interface WindowTimersExtension { setImmediate(handler: any, ...args: any[]): number; } +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -14243,6 +12962,33 @@ interface ParentNode { readonly childElementCount: number; } +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly stylesheets: StyleSheetList; + getSelection(): Selection | null; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; +} + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + mode: 'open'|'closed'; + delegatesFocus?: boolean; +} + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -14290,6 +13036,447 @@ interface NavigatorUserMediaErrorCallback { interface ForEachCallback { (keyId: any, status: string): void; } +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "audio": HTMLAudioElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "del": HTMLModElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "font": HTMLFontElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nextid": HTMLUnknownElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "script": HTMLScriptElement; + "select": HTMLSelectElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "style": HTMLStyleElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "ul": HTMLUListElement; + "video": HTMLVideoElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "circle": SVGCircleElement; + "cite": HTMLElement; + "clippath": SVGClipPathElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "defs": SVGDefsElement; + "del": HTMLModElement; + "desc": SVGDescElement; + "dfn": HTMLElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "ellipse": SVGEllipseElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "feblend": SVGFEBlendElement; + "fecolormatrix": SVGFEColorMatrixElement; + "fecomponenttransfer": SVGFEComponentTransferElement; + "fecomposite": SVGFECompositeElement; + "feconvolvematrix": SVGFEConvolveMatrixElement; + "fediffuselighting": SVGFEDiffuseLightingElement; + "fedisplacementmap": SVGFEDisplacementMapElement; + "fedistantlight": SVGFEDistantLightElement; + "feflood": SVGFEFloodElement; + "fefunca": SVGFEFuncAElement; + "fefuncb": SVGFEFuncBElement; + "fefuncg": SVGFEFuncGElement; + "fefuncr": SVGFEFuncRElement; + "fegaussianblur": SVGFEGaussianBlurElement; + "feimage": SVGFEImageElement; + "femerge": SVGFEMergeElement; + "femergenode": SVGFEMergeNodeElement; + "femorphology": SVGFEMorphologyElement; + "feoffset": SVGFEOffsetElement; + "fepointlight": SVGFEPointLightElement; + "fespecularlighting": SVGFESpecularLightingElement; + "fespotlight": SVGFESpotLightElement; + "fetile": SVGFETileElement; + "feturbulence": SVGFETurbulenceElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "filter": SVGFilterElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "foreignobject": SVGForeignObjectElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "g": SVGGElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "image": SVGImageElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "line": SVGLineElement; + "lineargradient": SVGLinearGradientElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marker": SVGMarkerElement; + "marquee": HTMLMarqueeElement; + "mask": SVGMaskElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "metadata": SVGMetadataElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "picture": HTMLPictureElement; + "plaintext": HTMLElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "radialgradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "stop": SVGStopElement; + "strike": HTMLElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "text": SVGTextElement; + "textpath": SVGTextPathElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "tspan": SVGTSpanElement; + "tt": HTMLElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "use": SVGUseElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "view": SVGViewElement; + "wbr": HTMLElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface ElementListTagNameMap { + "a": NodeListOf; + "abbr": NodeListOf; + "acronym": NodeListOf; + "address": NodeListOf; + "applet": NodeListOf; + "area": NodeListOf; + "article": NodeListOf; + "aside": NodeListOf; + "audio": NodeListOf; + "b": NodeListOf; + "base": NodeListOf; + "basefont": NodeListOf; + "bdo": NodeListOf; + "big": NodeListOf; + "blockquote": NodeListOf; + "body": NodeListOf; + "br": NodeListOf; + "button": NodeListOf; + "canvas": NodeListOf; + "caption": NodeListOf; + "center": NodeListOf; + "circle": NodeListOf; + "cite": NodeListOf; + "clippath": NodeListOf; + "code": NodeListOf; + "col": NodeListOf; + "colgroup": NodeListOf; + "datalist": NodeListOf; + "dd": NodeListOf; + "defs": NodeListOf; + "del": NodeListOf; + "desc": NodeListOf; + "dfn": NodeListOf; + "dir": NodeListOf; + "div": NodeListOf; + "dl": NodeListOf; + "dt": NodeListOf; + "ellipse": NodeListOf; + "em": NodeListOf; + "embed": NodeListOf; + "feblend": NodeListOf; + "fecolormatrix": NodeListOf; + "fecomponenttransfer": NodeListOf; + "fecomposite": NodeListOf; + "feconvolvematrix": NodeListOf; + "fediffuselighting": NodeListOf; + "fedisplacementmap": NodeListOf; + "fedistantlight": NodeListOf; + "feflood": NodeListOf; + "fefunca": NodeListOf; + "fefuncb": NodeListOf; + "fefuncg": NodeListOf; + "fefuncr": NodeListOf; + "fegaussianblur": NodeListOf; + "feimage": NodeListOf; + "femerge": NodeListOf; + "femergenode": NodeListOf; + "femorphology": NodeListOf; + "feoffset": NodeListOf; + "fepointlight": NodeListOf; + "fespecularlighting": NodeListOf; + "fespotlight": NodeListOf; + "fetile": NodeListOf; + "feturbulence": NodeListOf; + "fieldset": NodeListOf; + "figcaption": NodeListOf; + "figure": NodeListOf; + "filter": NodeListOf; + "font": NodeListOf; + "footer": NodeListOf; + "foreignobject": NodeListOf; + "form": NodeListOf; + "frame": NodeListOf; + "frameset": NodeListOf; + "g": NodeListOf; + "h1": NodeListOf; + "h2": NodeListOf; + "h3": NodeListOf; + "h4": NodeListOf; + "h5": NodeListOf; + "h6": NodeListOf; + "head": NodeListOf; + "header": NodeListOf; + "hgroup": NodeListOf; + "hr": NodeListOf; + "html": NodeListOf; + "i": NodeListOf; + "iframe": NodeListOf; + "image": NodeListOf; + "img": NodeListOf; + "input": NodeListOf; + "ins": NodeListOf; + "isindex": NodeListOf; + "kbd": NodeListOf; + "keygen": NodeListOf; + "label": NodeListOf; + "legend": NodeListOf; + "li": NodeListOf; + "line": NodeListOf; + "lineargradient": NodeListOf; + "link": NodeListOf; + "listing": NodeListOf; + "map": NodeListOf; + "mark": NodeListOf; + "marker": NodeListOf; + "marquee": NodeListOf; + "mask": NodeListOf; + "menu": NodeListOf; + "meta": NodeListOf; + "metadata": NodeListOf; + "meter": NodeListOf; + "nav": NodeListOf; + "nextid": NodeListOf; + "nobr": NodeListOf; + "noframes": NodeListOf; + "noscript": NodeListOf; + "object": NodeListOf; + "ol": NodeListOf; + "optgroup": NodeListOf; + "option": NodeListOf; + "p": NodeListOf; + "param": NodeListOf; + "path": NodeListOf; + "pattern": NodeListOf; + "picture": NodeListOf; + "plaintext": NodeListOf; + "polygon": NodeListOf; + "polyline": NodeListOf; + "pre": NodeListOf; + "progress": NodeListOf; + "q": NodeListOf; + "radialgradient": NodeListOf; + "rect": NodeListOf; + "rt": NodeListOf; + "ruby": NodeListOf; + "s": NodeListOf; + "samp": NodeListOf; + "script": NodeListOf; + "section": NodeListOf; + "select": NodeListOf; + "small": NodeListOf; + "source": NodeListOf; + "span": NodeListOf; + "stop": NodeListOf; + "strike": NodeListOf; + "strong": NodeListOf; + "style": NodeListOf; + "sub": NodeListOf; + "sup": NodeListOf; + "svg": NodeListOf; + "switch": NodeListOf; + "symbol": NodeListOf; + "table": NodeListOf; + "tbody": NodeListOf; + "td": NodeListOf; + "template": NodeListOf; + "text": NodeListOf; + "textpath": NodeListOf; + "textarea": NodeListOf; + "tfoot": NodeListOf; + "th": NodeListOf; + "thead": NodeListOf; + "title": NodeListOf; + "tr": NodeListOf; + "track": NodeListOf; + "tspan": NodeListOf; + "tt": NodeListOf; + "u": NodeListOf; + "ul": NodeListOf; + "use": NodeListOf; + "var": NodeListOf; + "video": NodeListOf; + "view": NodeListOf; + "wbr": NodeListOf; + "x-ms-webview": NodeListOf; + "xmp": NodeListOf; +} + declare var Audio: {new(src?: string): HTMLAudioElement; }; declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; @@ -14301,7 +13488,7 @@ declare var defaultStatus: string; declare var devicePixelRatio: number; declare var doNotTrack: string; declare var document: Document; -declare var event: Event; +declare var event: Event | undefined; declare var external: External; declare var frameElement: Element; declare var frames: Window; @@ -14464,7 +13651,6 @@ declare function scroll(options?: ScrollToOptions): void; declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; @@ -14491,101 +13677,7 @@ declare var onwheel: (this: Window, ev: WheelEvent) => any; declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; -declare function addEventListener(type: "MSGestureChange", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureDoubleTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureEnd", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureHold", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSGestureTap", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSInertiaStart", listener: (this: Window, ev: MSGestureEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerCancel", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerDown", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerEnter", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerLeave", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerMove", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOut", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerOver", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "MSPointerUp", listener: (this: Window, ev: MSPointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "abort", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "afterprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeprint", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "beforeunload", listener: (this: Window, ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "blur", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplay", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "canplaythrough", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "change", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "click", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "compassneedscalibration", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "contextmenu", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dblclick", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicelight", listener: (this: Window, ev: DeviceLightEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "devicemotion", listener: (this: Window, ev: DeviceMotionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "deviceorientation", listener: (this: Window, ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drag", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragend", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragenter", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragleave", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragover", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "dragstart", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "drop", listener: (this: Window, ev: DragEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "durationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "emptied", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ended", listener: (this: Window, ev: MediaStreamErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "focus", listener: (this: Window, ev: FocusEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "hashchange", listener: (this: Window, ev: HashChangeEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "input", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "invalid", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keydown", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keypress", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "keyup", listener: (this: Window, ev: KeyboardEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "load", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadeddata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadedmetadata", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "loadstart", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: Window, ev: MessageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousedown", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseenter", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseleave", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseout", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseover", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mouseup", listener: (this: Window, ev: MouseEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "mousewheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "offline", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "online", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "orientationchange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pagehide", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pageshow", listener: (this: Window, ev: PageTransitionEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pause", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "play", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "playing", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointercancel", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerdown", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerenter", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerleave", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointermove", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerout", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerover", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "pointerup", listener: (this: Window, ev: PointerEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "popstate", listener: (this: Window, ev: PopStateEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "progress", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "ratechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "readystatechange", listener: (this: Window, ev: ProgressEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "reset", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "resize", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "scroll", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeked", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "seeking", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "select", listener: (this: Window, ev: UIEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "stalled", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "storage", listener: (this: Window, ev: StorageEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "submit", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "suspend", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "timeupdate", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "unload", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "volumechange", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "waiting", listener: (this: Window, ev: Event) => any, useCapture?: boolean): void; -declare function addEventListener(type: "wheel", listener: (this: Window, ev: WheelEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 5d570bb0866..356512ecf58 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -201,7 +201,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ diff --git a/src/lib/es2015.proxy.d.ts b/src/lib/es2015.proxy.d.ts index c37e8fb0f59..34aedce0128 100644 --- a/src/lib/es2015.proxy.d.ts +++ b/src/lib/es2015.proxy.d.ts @@ -1,5 +1,5 @@ interface ProxyHandler { - getPrototypeOf? (target: T): any; + getPrototypeOf? (target: T): {} | null; setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; @@ -12,11 +12,11 @@ interface ProxyHandler { enumerate? (target: T): PropertyKey[]; ownKeys? (target: T): PropertyKey[]; apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, argArray: any, newTarget?: any): {}; } interface ProxyConstructor { revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; new (target: T, handler: ProxyHandler): T } -declare var Proxy: ProxyConstructor; \ No newline at end of file +declare var Proxy: ProxyConstructor; diff --git a/src/lib/es2016.array.include.d.ts b/src/lib/es2016.array.include.d.ts index 17b3eaac1d3..fdd9ed4639f 100644 --- a/src/lib/es2016.array.include.d.ts +++ b/src/lib/es2016.array.include.d.ts @@ -7,6 +7,15 @@ interface Array { includes(searchElement: T, fromIndex?: number): boolean; } +interface ReadonlyArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + interface Int8Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. diff --git a/src/lib/es2017.d.ts b/src/lib/es2017.d.ts index 13f9d93f444..c234a9edb24 100644 --- a/src/lib/es2017.d.ts +++ b/src/lib/es2017.d.ts @@ -1,3 +1,4 @@ /// /// -/// \ No newline at end of file +/// +/// diff --git a/src/lib/es2017.object.d.ts b/src/lib/es2017.object.d.ts index 95cc5692a03..80c2161506a 100644 --- a/src/lib/es2017.object.d.ts +++ b/src/lib/es2017.object.d.ts @@ -4,11 +4,22 @@ interface ObjectConstructor { * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ values(o: { [s: string]: T }): T[]; + + /** + * Returns an array of values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ values(o: any): any[]; + /** * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ entries(o: { [s: string]: T }): [string, T][]; + + /** + * Returns an array of key/values of the enumerable properties of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ entries(o: any): [string, any][]; -} \ No newline at end of file +} diff --git a/src/lib/es2017.string.d.ts b/src/lib/es2017.string.d.ts new file mode 100644 index 00000000000..51f8e410ecf --- /dev/null +++ b/src/lib/es2017.string.d.ts @@ -0,0 +1,27 @@ +interface String { + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the start (left) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padStart(maxLength: number, fillString?: string): string; + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the end (right) of the current string. + * + * @param maxLength The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padEnd(maxLength: number, fillString?: string): string; +} diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index ccff01a8722..1e6b44788b3 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -180,7 +180,19 @@ interface ObjectConstructor { * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ - freeze(o: T): T; + freeze(a: T[]): ReadonlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): Readonly; /** * Prevents the addition of new properties to an object. @@ -244,6 +256,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of a function. */ + toString(): string; + prototype: any; readonly length: number; @@ -1340,6 +1355,34 @@ interface ArrayLike { readonly [n: number]: T; } +/** + * Make all properties in T optional + */ +type Partial = { + [P in keyof T]?: T[P]; +}; + +/** + * Make all properties in T readonly + */ +type Readonly = { + readonly [P in keyof T]: T[P]; +}; + +/** + * From T pick a set of properties K + */ +type Pick = { + [P in K]: T[P]; +} + +/** + * Construct a type with a set of properties K of type T + */ +type Record = { + [P in K]: T; +} + /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index b543939ef0a..089d0bdc5d5 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -8,6 +8,7 @@ interface Algorithm { } interface EventInit { + scoped?: boolean; bubbles?: boolean; cancelable?: boolean; } @@ -242,10 +243,12 @@ interface Event { readonly target: EventTarget; readonly timeStamp: number; readonly type: string; + readonly scoped: boolean; initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; preventDefault(): void; stopImmediatePropagation(): void; stopPropagation(): void; + deepPath(): EventTarget[]; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; @@ -298,6 +301,7 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -339,11 +343,16 @@ declare var IDBCursorWithValue: { new(): IDBCursorWithValue; } +interface IDBDatabaseEventMap { + "abort": Event; + "error": ErrorEvent; +} + interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -351,8 +360,7 @@ interface IDBDatabase extends EventTarget { deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -429,13 +437,15 @@ declare var IDBObjectStore: { new(): IDBObjectStore; } +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + interface IDBOpenDBRequest extends IDBRequest { - onblocked: (this: this, ev: Event) => any; - onupgradeneeded: (this: this, ev: IDBVersionChangeEvent) => any; - addEventListener(type: "blocked", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "upgradeneeded", listener: (this: this, ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -444,16 +454,20 @@ declare var IDBOpenDBRequest: { new(): IDBOpenDBRequest; } +interface IDBRequestEventMap { + "error": ErrorEvent; + "success": Event; +} + interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (this: this, ev: ErrorEvent) => any; - onsuccess: (this: this, ev: Event) => any; + onerror: (this: IDBRequest, ev: ErrorEvent) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; readonly readyState: string; readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "success", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -462,21 +476,25 @@ declare var IDBRequest: { new(): IDBRequest; } +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": ErrorEvent; +} + interface IDBTransaction extends EventTarget { readonly db: IDBDatabase; readonly error: DOMError; readonly mode: string; - onabort: (this: this, ev: Event) => any; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -533,18 +551,22 @@ interface MSApp { } declare var MSApp: MSApp; +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": ErrorEvent; +} + interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; - oncomplete: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: "complete", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -584,6 +606,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -627,12 +650,16 @@ declare var MessageEvent: { new(type: string, eventInitDict?: MessageEventInit): MessageEvent; } +interface MessagePortEventMap { + "message": MessageEvent; +} + interface MessagePort extends EventTarget { - onmessage: (this: this, ev: MessageEvent) => any; + onmessage: (this: MessagePort, ev: MessageEvent) => any; close(): void; postMessage(message?: any, ports?: any): void; start(): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -680,14 +707,21 @@ declare var ProgressEvent: { new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; } +interface WebSocketEventMap { + "close": CloseEvent; + "error": ErrorEvent; + "message": MessageEvent; + "open": Event; +} + interface WebSocket extends EventTarget { binaryType: string; readonly bufferedAmount: number; readonly extensions: string; - onclose: (this: this, ev: CloseEvent) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onmessage: (this: this, ev: MessageEvent) => any; - onopen: (this: this, ev: Event) => any; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: ErrorEvent) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; readonly protocol: string; readonly readyState: number; readonly url: string; @@ -697,10 +731,7 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: "close", listener: (this: this, ev: CloseEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; - addEventListener(type: "open", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -713,12 +744,15 @@ declare var WebSocket: { readonly OPEN: number; } +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + interface Worker extends EventTarget, AbstractWorker { - onmessage: (this: this, ev: MessageEvent) => any; + onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, ports?: any): void; terminate(): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -727,8 +761,12 @@ declare var Worker: { new(stringUrl: string): Worker; } +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: Event) => any; + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -740,6 +778,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; withCredentials: boolean; msCaching?: string; + readonly responseURL: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -754,14 +793,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -777,6 +809,7 @@ declare var XMLHttpRequest: { } interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -785,31 +818,39 @@ declare var XMLHttpRequestUpload: { new(): XMLHttpRequestUpload; } +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + interface AbstractWorker { - onerror: (this: this, ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + interface MSBaseReader { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; readonly readyState: number; readonly result: any; abort(): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -837,21 +878,25 @@ interface WindowConsole { readonly console: Console; } +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + interface XMLHttpRequestEventTarget { - onabort: (this: this, ev: Event) => any; - onerror: (this: this, ev: ErrorEvent) => any; - onload: (this: this, ev: Event) => any; - onloadend: (this: this, ev: ProgressEvent) => any; - onloadstart: (this: this, ev: Event) => any; - onprogress: (this: this, ev: ProgressEvent) => any; - ontimeout: (this: this, ev: ProgressEvent) => any; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; + onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -867,15 +912,18 @@ declare var FileReaderSync: { new(): FileReaderSync; } +interface WorkerGlobalScopeEventMap extends DedicatedWorkerGlobalScopeEventMap { + "error": ErrorEvent; +} + interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole { readonly location: WorkerLocation; - onerror: (this: this, ev: ErrorEvent) => any; + onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any; readonly self: WorkerGlobalScope; close(): void; msWriteProfilerMark(profilerMarkName: string): void; toString(): string; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -902,7 +950,7 @@ declare var WorkerLocation: { } interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine { - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly hardwareConcurrency: number; } declare var WorkerNavigator: { @@ -910,10 +958,14 @@ declare var WorkerNavigator: { new(): WorkerNavigator; } +interface DedicatedWorkerGlobalScopeEventMap { + "message": MessageEvent; +} + interface DedicatedWorkerGlobalScope { - onmessage: (this: this, ev: MessageEvent) => any; + onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; postMessage(data: any): void; - addEventListener(type: "message", listener: (this: this, ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -1174,7 +1226,6 @@ declare var self: WorkerGlobalScope; declare function close(): void; declare function msWriteProfilerMark(profilerMarkName: string): void; declare function toString(): string; -declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare var indexedDB: IDBFactory; @@ -1195,8 +1246,7 @@ declare function btoa(rawString: string): string; declare var onmessage: (this: WorkerGlobalScope, ev: MessageEvent) => any; declare function postMessage(data: any): void; declare var console: Console; -declare function addEventListener(type: "error", listener: (this: WorkerGlobalScope, ev: ErrorEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: "message", listener: (this: WorkerGlobalScope, ev: MessageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; type AlgorithmIdentifier = string | Algorithm; type IDBKeyPath = string; diff --git a/src/server/builder.ts b/src/server/builder.ts index 639c41d2b63..60f56dc3241 100644 --- a/src/server/builder.ts +++ b/src/server/builder.ts @@ -1,20 +1,10 @@ /// /// -/// /// /// namespace ts.server { - interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: string): any; - } - - const crypto: { - createHash(algorithm: string): Hash - } = require("crypto"); - export function shouldEmitFile(scriptInfo: ScriptInfo) { return !scriptInfo.hasMixedContent; } @@ -50,9 +40,7 @@ namespace ts.server { } private computeHash(text: string): string { - return crypto.createHash("md5") - .update(text) - .digest("base64"); + return this.project.projectService.host.createHash(text); } private getSourceFile(): SourceFile { @@ -87,17 +75,32 @@ namespace ts.server { getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; onProjectUpdateGraph(): void; emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + clear(): void; } abstract class AbstractBuilder implements Builder { - private fileInfos = createFileMap(); + /** + * stores set of files from the project. + * NOTE: this field is created on demand and should not be accessed directly. + * Use 'getFileInfos' instead. + */ + private fileInfos_doNotAccessDirectly: FileMap; constructor(public readonly project: Project, private ctor: { new (scriptInfo: ScriptInfo, project: Project): T }) { } + private getFileInfos() { + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = createFileMap()); + } + + public clear() { + // drop the existing list - it will be re-created as necessary + this.fileInfos_doNotAccessDirectly = undefined; + } + protected getFileInfo(path: Path): T { - return this.fileInfos.get(path); + return this.getFileInfos().get(path); } protected getOrCreateFileInfo(path: Path): T { @@ -111,19 +114,19 @@ namespace ts.server { } protected getFileInfoPaths(): Path[] { - return this.fileInfos.getKeys(); + return this.getFileInfos().getKeys(); } protected setFileInfo(path: Path, info: T) { - this.fileInfos.set(path, info); + this.getFileInfos().set(path, info); } protected removeFileInfo(path: Path) { - this.fileInfos.remove(path); + this.getFileInfos().remove(path); } protected forEachFileInfo(action: (fileInfo: T) => any) { - this.fileInfos.forEachValue((path: Path, value: T) => action(value)); + this.getFileInfos().forEachValue((_path, value) => action(value)); } abstract getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; @@ -243,6 +246,11 @@ namespace ts.server { private projectVersionForDependencyGraph: string; + public clear() { + this.projectVersionForDependencyGraph = undefined; + super.clear(); + } + private getReferencedFileInfos(fileInfo: ModuleBuilderFileInfo): ModuleBuilderFileInfo[] { if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { return []; diff --git a/src/server/cancellationToken/tsconfig.json b/src/server/cancellationToken/tsconfig.json index 1245fc34fd5..1c4c0d60826 100644 --- a/src/server/cancellationToken/tsconfig.json +++ b/src/server/cancellationToken/tsconfig.json @@ -10,7 +10,10 @@ "stripInternal": true, "types": [ "node" - ] + ], + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true }, "files": [ "cancellationToken.ts" diff --git a/src/server/client.ts b/src/server/client.ts index 058abdff41d..3b09a926754 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -1,16 +1,10 @@ /// namespace ts.server { - export interface SessionClientHost extends LanguageServiceHost { writeMessage(message: string): void; } - interface CompletionEntry extends CompletionInfo { - fileName: string; - position: number; - } - interface RenameEntry extends RenameInfo { fileName: string; position: number; @@ -247,8 +241,8 @@ namespace ts.server { return response.body[0]; } - getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol { - throw new Error("Not Implemented Yet."); + getCompletionEntrySymbol(_fileName: string, _position: number, _entryName: string): Symbol { + return notImplemented(); } getNavigateToItems(searchValue: string): NavigateToItem[] { @@ -279,7 +273,7 @@ namespace ts.server { }); } - getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): ts.TextChange[] { + getFormattingEditsForRange(fileName: string, start: number, end: number, _options: ts.FormatCodeOptions): ts.TextChange[] { const startLineOffset = this.positionToOneBasedLineOffset(fileName, start); const endLineOffset = this.positionToOneBasedLineOffset(fileName, end); const args: protocol.FormatRequestArgs = { @@ -301,7 +295,7 @@ namespace ts.server { return this.getFormattingEditsForRange(fileName, 0, this.host.getScriptSnapshot(fileName).getLength(), options); } - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): ts.TextChange[] { + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, _options: FormatCodeOptions): ts.TextChange[] { const lineOffset = this.positionToOneBasedLineOffset(fileName, position); const args: protocol.FormatOnKeyRequestArgs = { file: fileName, @@ -391,7 +385,7 @@ namespace ts.server { }); } - findReferences(fileName: string, position: number): ReferencedSymbol[] { + findReferences(_fileName: string, _position: number): ReferencedSymbol[] { // Not yet implemented. return []; } @@ -420,44 +414,50 @@ namespace ts.server { }); } - getEmitOutput(fileName: string): EmitOutput { - throw new Error("Not Implemented Yet."); + getEmitOutput(_fileName: string): EmitOutput { + return notImplemented(); } getSyntacticDiagnostics(fileName: string): Diagnostic[] { - const args: protocol.SyntacticDiagnosticsSyncRequestArgs = { file: fileName }; + const args: protocol.SyntacticDiagnosticsSyncRequestArgs = { file: fileName, includeLinePosition: true }; const request = this.processRequest(CommandNames.SyntacticDiagnosticsSync, args); const response = this.processResponse(request); - return (response.body).map(entry => this.convertDiagnostic(entry, fileName)); + return (response.body).map(entry => this.convertDiagnostic(entry, fileName)); } getSemanticDiagnostics(fileName: string): Diagnostic[] { - const args: protocol.SemanticDiagnosticsSyncRequestArgs = { file: fileName }; + const args: protocol.SemanticDiagnosticsSyncRequestArgs = { file: fileName, includeLinePosition: true }; const request = this.processRequest(CommandNames.SemanticDiagnosticsSync, args); const response = this.processResponse(request); - return (response.body).map(entry => this.convertDiagnostic(entry, fileName)); + return (response.body).map(entry => this.convertDiagnostic(entry, fileName)); } - convertDiagnostic(entry: protocol.Diagnostic, fileName: string): Diagnostic { - const start = this.lineOffsetToPosition(fileName, entry.start); - const end = this.lineOffsetToPosition(fileName, entry.end); + convertDiagnostic(entry: protocol.DiagnosticWithLinePosition, _fileName: string): Diagnostic { + let category: DiagnosticCategory; + for (const id in DiagnosticCategory) { + if (typeof id === "string" && entry.category === id.toLowerCase()) { + category = (DiagnosticCategory)[id]; + } + } + + Debug.assert(category !== undefined, "convertDiagnostic: category should not be undefined"); return { file: undefined, - start: start, - length: end - start, - messageText: entry.text, - category: undefined, + start: entry.start, + length: entry.length, + messageText: entry.message, + category: category, code: entry.code }; } getCompilerOptionsDiagnostics(): Diagnostic[] { - throw new Error("Not Implemented Yet."); + return notImplemented(); } getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo { @@ -561,12 +561,12 @@ namespace ts.server { this.lineOffsetToPosition(fileName, span.end, lineMap)); } - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan { - throw new Error("Not Implemented Yet."); + getNameOrDottedNameSpan(_fileName: string, _startPos: number, _endPos: number): TextSpan { + return notImplemented(); } - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan { - throw new Error("Not Implemented Yet."); + getBreakpointStatementAtPosition(_fileName: string, _position: number): TextSpan { + return notImplemented(); } getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems { @@ -655,20 +655,20 @@ namespace ts.server { } } - getOutliningSpans(fileName: string): OutliningSpan[] { - throw new Error("Not Implemented Yet."); + getOutliningSpans(_fileName: string): OutliningSpan[] { + return notImplemented(); } - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] { - throw new Error("Not Implemented Yet."); + getTodoComments(_fileName: string, _descriptors: TodoCommentDescriptor[]): TodoComment[] { + return notImplemented(); } - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion { - throw new Error("Not Implemented Yet."); + getDocCommentTemplateAtPosition(_fileName: string, _position: number): TextInsertion { + return notImplemented(); } - isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean { - throw new Error("Not Implemented Yet."); + isValidBraceCompletionAtPosition(_fileName: string, _position: number, _openingBrace: number): boolean { + return notImplemented(); } getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[] { @@ -734,35 +734,35 @@ namespace ts.server { }); } - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number { - throw new Error("Not Implemented Yet."); + getIndentationAtPosition(_fileName: string, _position: number, _options: EditorOptions): number { + return notImplemented(); } - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] { - throw new Error("Not Implemented Yet."); + getSyntacticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] { + return notImplemented(); } - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] { - throw new Error("Not Implemented Yet."); + getSemanticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] { + return notImplemented(); } - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications { - throw new Error("Not Implemented Yet."); + getEncodedSyntacticClassifications(_fileName: string, _span: TextSpan): Classifications { + return notImplemented(); } - getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications { - throw new Error("Not Implemented Yet."); + getEncodedSemanticClassifications(_fileName: string, _span: TextSpan): Classifications { + return notImplemented(); } getProgram(): Program { throw new Error("SourceFile objects are not serializable through the server protocol."); } - getNonBoundSourceFile(fileName: string): SourceFile { + getNonBoundSourceFile(_fileName: string): SourceFile { throw new Error("SourceFile objects are not serializable through the server protocol."); } - getSourceFile(fileName: string): SourceFile { + getSourceFile(_fileName: string): SourceFile { throw new Error("SourceFile objects are not serializable through the server protocol."); } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index dc2c45156cd..00df53e1e35 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1,6 +1,5 @@ /// /// -/// /// /// /// @@ -11,13 +10,93 @@ namespace ts.server { export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - export type ProjectServiceEvent = - { eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile?: string, configFileName: string, diagnostics: Diagnostic[] } }; + export const ContextEvent = "context"; + export const ConfigFileDiagEvent = "configFileDiag"; + export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + + export interface ContextEvent { + eventName: typeof ContextEvent; + data: { project: Project; fileName: NormalizedPath }; + } + + export interface ConfigFileDiagEvent { + eventName: typeof ConfigFileDiagEvent; + data: { triggerFile: string, configFileName: string, diagnostics: Diagnostic[] }; + } + + export interface ProjectLanguageServiceStateEvent { + eventName: typeof ProjectLanguageServiceStateEvent; + data: { project: Project, languageServiceEnabled: boolean }; + } + + export type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent; export interface ProjectServiceEventHandler { (event: ProjectServiceEvent): void; } + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map> { + const map: Map> = createMap>(); + for (const option of commandLineOptions) { + if (typeof option.type === "object") { + const optionMap = >option.type; + // verify that map contains only numbers + for (const id in optionMap) { + Debug.assert(typeof optionMap[id] === "number"); + } + map[option.name] = optionMap; + } + } + return map; + } + + const compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations); + const indentStyle = createMap({ + "none": IndentStyle.None, + "block": IndentStyle.Block, + "smart": IndentStyle.Smart + }); + + export function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings { + if (typeof protocolOptions.indentStyle === "string") { + protocolOptions.indentStyle = indentStyle[protocolOptions.indentStyle.toLowerCase()]; + Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + + export function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin { + for (const id in compilerOptionConverters) { + const propertyValue = protocolOptions[id]; + if (typeof propertyValue === "string") { + const mappedValues = compilerOptionConverters[id]; + protocolOptions[id] = mappedValues[propertyValue.toLowerCase()]; + } + } + return protocolOptions; + } + + export function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind { + return typeof scriptKindName === "string" + ? convertScriptKindName(scriptKindName) + : scriptKindName; + } + + export function convertScriptKindName(scriptKindName: protocol.ScriptKindName) { + switch (scriptKindName) { + case "JS": + return ScriptKind.JS; + case "JSX": + return ScriptKind.JSX; + case "TS": + return ScriptKind.TS; + case "TSX": + return ScriptKind.TSX; + default: + return ScriptKind.Unknown; + } + } + /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ @@ -29,6 +108,7 @@ namespace ts.server { export interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; } interface ConfigFileConversionResult { @@ -46,25 +126,28 @@ namespace ts.server { } export interface OpenConfiguredProjectResult { - configFileName?: string; + configFileName?: NormalizedPath; configFileErrors?: Diagnostic[]; } interface FilePropertyReader { getFileName(f: T): string; getScriptKind(f: T): ScriptKind; - hasMixedContent(f: T): boolean; + hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean; } const fileNamePropertyReader: FilePropertyReader = { getFileName: x => x, getScriptKind: _ => undefined, - hasMixedContent: _ => false + hasMixedContent: (fileName, extraFileExtensions) => { + const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension); + return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension)) + } }; const externalFilePropertyReader: FilePropertyReader = { getFileName: x => x.fileName, - getScriptKind: x => x.scriptKind, + getScriptKind: x => tryConvertScriptKindName(x.scriptKind), hasMixedContent: x => x.hasMixedContent }; @@ -178,7 +261,7 @@ namespace ts.server { private changedFiles: ScriptInfo[]; - private toCanonicalFileName: (f: string) => string; + readonly toCanonicalFileName: (f: string) => string; public lastDeletedFile: ScriptInfo; @@ -189,6 +272,8 @@ namespace ts.server { readonly typingsInstaller: ITypingsInstaller = nullTypingsInstaller, private readonly eventHandler?: ProjectServiceEventHandler) { + Debug.assert(!!host.createHash, "'ServerHost.createHash' is required for ProjectService"); + this.toCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); this.directoryWatchers = new DirectoryWatchers(this); this.throttledOperations = new ThrottledOperations(host); @@ -201,7 +286,8 @@ namespace ts.server { this.hostConfiguration = { formatCodeOptions: getDefaultFormatCodeSettings(this.host), - hostInfo: "Unknown host" + hostInfo: "Unknown host", + extraFileExtensions: [] }; this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); @@ -215,27 +301,44 @@ namespace ts.server { this.ensureInferredProjectsUpToDate(); } + getCompilerOptionsForInferredProjects() { + return this.compilerOptionsForInferredProjects; + } + + onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: ProjectLanguageServiceStateEvent, + data: { project, languageServiceEnabled } + }); + } + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void { const project = this.findProject(response.projectName); if (!project) { return; } switch (response.kind) { - case "set": - this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); - project.updateGraph(); + case ActionSet: + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); break; - case "invalidate": - this.typingsCache.invalidateCachedTypingsForProject(project); + case ActionInvalidate: + this.typingsCache.deleteTypingsForProject(response.projectName); break; } + project.updateGraph(); } setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void { - this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); + // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside + // previously we did not expose a way for user to change these settings and this option was enabled by default + this.compilerOptionsForInferredProjects.allowNonTsExtensions = true; this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; for (const proj of this.inferredProjects) { - proj.setCompilerOptions(projectCompilerOptions); + proj.setCompilerOptions(this.compilerOptionsForInferredProjects); proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; } this.updateProjectGraphs(this.inferredProjects); @@ -326,7 +429,7 @@ namespace ts.server { this.handleDeletedFile(info); } else { - if (info && (!info.isOpen)) { + if (info && (!info.isScriptOpen())) { // file has been changed which might affect the set of referenced files in projects that include // this file and set of inferred projects info.reloadFromFile(); @@ -342,7 +445,7 @@ namespace ts.server { // TODO: handle isOpen = true case - if (!info.isOpen) { + if (!info.isScriptOpen()) { this.filenameToScriptInfo.remove(info.path); this.lastDeletedFile = info; @@ -360,7 +463,10 @@ namespace ts.server { } for (const openFile of this.openFiles) { - this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); + this.eventHandler({ + eventName: ContextEvent, + data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } + }); } } @@ -369,7 +475,7 @@ namespace ts.server { private onTypeRootFileChanged(project: ConfiguredProject, fileName: string) { this.logger.info(`Type root file ${fileName} changed`); - this.throttledOperations.schedule(project.configFileName + " * type root", /*delay*/ 250, () => { + this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", /*delay*/ 250, () => { project.updateTypes(); this.updateConfiguredProject(project); // TODO: Figure out why this is needed (should be redundant?) this.refreshInferredProjects(); @@ -385,20 +491,20 @@ namespace ts.server { // If a change was made inside "folder/file", node will trigger the callback twice: // one with the fileName being "folder/file", and the other one with "folder". // We don't respond to the second one. - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { return; } this.logger.info(`Detected source file changes: ${fileName}`); this.throttledOperations.schedule( - project.configFileName, + project.getConfigFilePath(), /*delay*/250, - () => this.handleChangeInSourceFileForConfiguredProject(project)); + () => this.handleChangeInSourceFileForConfiguredProject(project, fileName)); } - private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) { - const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName); - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) { + const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()); + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f))); const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f))); @@ -419,8 +525,10 @@ namespace ts.server { } private onConfigChangedForConfiguredProject(project: ConfiguredProject) { - this.logger.info(`Config file changed: ${project.configFileName}`); - this.updateConfiguredProject(project); + const configFileName = project.getConfigFilePath(); + this.logger.info(`Config file changed: ${configFileName}`); + const configFileErrors = this.updateConfiguredProject(project); + this.reportConfigFileDiagnostics(configFileName, configFileErrors, /*triggerFile*/ configFileName); this.refreshInferredProjects(); } @@ -435,7 +543,7 @@ namespace ts.server { } const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName); - this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); this.logger.info(`Detected newly added tsconfig file: ${fileName}`); this.reloadProjects(); @@ -531,15 +639,17 @@ namespace ts.server { // Closing file should trigger re-reading the file content from disk. This is // because the user may chose to discard the buffer content before saving // to the disk, and the server's version of the file can be out of sync. - info.reloadFromFile(); + info.close(); removeItemFromSet(this.openFiles, info); - info.isOpen = false; // collect all projects that should be removed let projectsToRemove: Project[]; for (const p of info.containingProjects) { if (p.projectKind === ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } // last open file in configured project - close it if ((p).deleteOpenRef() === 0) { (projectsToRemove || (projectsToRemove = [])).push(p); @@ -549,6 +659,13 @@ namespace ts.server { // open file in inferred project (projectsToRemove || (projectsToRemove = [])).push(p); } + + if (!p.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request + p.markAsDirty(); + } } if (projectsToRemove) { for (const project of projectsToRemove) { @@ -674,7 +791,13 @@ namespace ts.server { } private findConfiguredProjectByProjectName(configFileName: NormalizedPath) { - return findProjectByName(configFileName, this.configuredProjects); + // make sure that casing of config file name is consistent + configFileName = asNormalizedPath(this.toCanonicalFileName(configFileName)); + for (const proj of this.configuredProjects) { + if (proj.canonicalConfigFilePath === configFileName) { + return proj; + } + } } private findExternalProjectByProjectName(projectFileName: string) { @@ -702,7 +825,9 @@ namespace ts.server { this.host, getDirectoryPath(configFilename), /*existingOptions*/ {}, - configFilename); + configFilename, + /*resolutionStack*/ [], + this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors = concatenate(errors, parsedCommandLine.errors); @@ -711,7 +836,7 @@ namespace ts.server { Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } @@ -720,7 +845,7 @@ namespace ts.server { compilerOptions: parsedCommandLine.options, configHasFilesProperty: config["files"] !== undefined, wildcardDirectories: createMap(parsedCommandLine.wildcardDirectories), - typingOptions: parsedCommandLine.typingOptions, + typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave }; return { success: true, projectOptions, configFileErrors: errors }; @@ -744,27 +869,28 @@ namespace ts.server { return false; } - private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typingOptions: TypingOptions) { + private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typeAcquisition: TypeAcquisition) { + const compilerOptions = convertCompilerOptions(options); const project = new ExternalProject( projectFileName, this, this.documentRegistry, - options, - /*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), + compilerOptions, + /*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typingOptions, /*configFileErrors*/ undefined); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typeAcquisition, /*configFileErrors*/ undefined); this.externalProjects.push(project); return project; } - private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string) { + private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile: string) { if (!this.eventHandler) { return; } - this.eventHandler({ - eventName: "configFileDiag", + this.eventHandler({ + eventName: ConfigFileDiagEvent, data: { configFileName, diagnostics: diagnostics || [], triggerFile } }); } @@ -781,7 +907,7 @@ namespace ts.server { /*languageServiceEnabled*/ !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); project.watchConfigFile(project => this.onConfigChangedForConfiguredProject(project)); if (!sizeLimitExceeded) { @@ -800,12 +926,12 @@ namespace ts.server { } } - private addFilesToProjectAndUpdateGraph(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader, clientFileName: string, typingOptions: TypingOptions, configFileErrors: Diagnostic[]): void { + private addFilesToProjectAndUpdateGraph(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader, clientFileName: string, typeAcquisition: TypeAcquisition, configFileErrors: Diagnostic[]): void { let errors: Diagnostic[]; for (const f of files) { const rootFilename = propertyReader.getFileName(f); const scriptKind = propertyReader.getScriptKind(f); - const hasMixedContent = propertyReader.hasMixedContent(f); + const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); if (this.host.fileExists(rootFilename)) { const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent); project.addRoot(info); @@ -815,7 +941,7 @@ namespace ts.server { } } project.setProjectErrors(concatenate(configFileErrors, errors)); - project.setTypingOptions(typingOptions); + project.setTypeAcquisition(typeAcquisition); project.updateGraph(); } @@ -832,7 +958,7 @@ namespace ts.server { }; } - private updateNonInferredProject(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader, newOptions: CompilerOptions, newTypingOptions: TypingOptions, compileOnSave: boolean, configFileErrors: Diagnostic[]) { + private updateNonInferredProject(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader, newOptions: CompilerOptions, newTypeAcquisition: TypeAcquisition, compileOnSave: boolean, configFileErrors: Diagnostic[]) { const oldRootScriptInfos = project.getRootScriptInfos(); const newRootScriptInfos: ScriptInfo[] = []; const newRootScriptInfoMap: NormalizedPathMap = createNormalizedPathMap(); @@ -851,7 +977,7 @@ namespace ts.server { rootFilesChanged = true; if (!scriptInfo) { const scriptKind = propertyReader.getScriptKind(f); - const hasMixedContent = propertyReader.hasMixedContent(f); + const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent); } } @@ -879,7 +1005,7 @@ namespace ts.server { } if (toAdd) { for (const f of toAdd) { - if (f.isOpen && isRootFileInInferredProject(f)) { + if (f.isScriptOpen() && isRootFileInInferredProject(f)) { // if file is already root in some inferred project // - remove the file from that project and delete the project if necessary const inferredProject = f.containingProjects[0]; @@ -894,7 +1020,7 @@ namespace ts.server { } project.setCompilerOptions(newOptions); - (project).setTypingOptions(newTypingOptions); + (project).setTypeAcquisition(newTypeAcquisition); // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently // therefore if it is undefined, it should not be updated. @@ -907,13 +1033,16 @@ namespace ts.server { } private updateConfiguredProject(project: ConfiguredProject) { - if (!this.host.fileExists(project.configFileName)) { + if (!this.host.fileExists(project.getConfigFilePath())) { this.logger.info("Config file deleted"); this.removeProject(project); return; } - const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName); + // note: the returned "success" is true does not mean the "configFileErrors" is empty. + // because we might have tolerated the errors and kept going. So always return the configFileErrors + // regardless the "success" here is true or not. + const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()); if (!success) { // reset project settings to default this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, /*compileOnSave*/false, configFileErrors); @@ -924,25 +1053,24 @@ namespace ts.server { project.setCompilerOptions(projectOptions.compilerOptions); if (!project.languageServiceEnabled) { // language service is already disabled - return; + return configFileErrors; } project.disableLanguageService(); project.stopWatchingDirectory(); } else { - if (!project.languageServiceEnabled) { - project.enableLanguageService(); - } + project.enableLanguageService(); this.watchConfigDirectoryForProject(project, projectOptions); - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); } + return configFileErrors; } createInferredProjectWithRootFileIfNecessary(root: ScriptInfo) { const useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; const project = useExistingProject ? this.inferredProjects[0] - : new InferredProject(this, this.documentRegistry, /*languageServiceEnabled*/ true, this.compilerOptionsForInferredProjects, /*compileOnSaveEnabled*/ this.compileOnSaveForInferredProjects); + : new InferredProject(this, this.documentRegistry, this.compilerOptionsForInferredProjects); project.addRoot(root); @@ -975,32 +1103,34 @@ namespace ts.server { getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean) { let info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - let content: string; - if (this.host.fileExists(fileName)) { - // by default pick whatever content was supplied as the argument - // if argument was not given - then for mixed content files assume that its content is empty string - content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); - // do not watch files with mixed content - server doesn't know how to interpret it + if (openedByClient || this.host.fileExists(fileName)) { + info = new ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); - if (!info.isOpen && !hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, _ => this.onSourceFileChanged(fileName))); + + if (openedByClient) { + if (fileContent === undefined) { + // if file is opened by client and its content is not specified - use file text + fileContent = this.host.readFile(fileName) || ""; + } + } + else { + // do not watch files with mixed content - server doesn't know how to interpret it + if (!hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, _ => this.onSourceFileChanged(fileName))); + } } } } if (info) { - if (fileContent !== undefined) { - info.reload(fileContent); + if (openedByClient && !info.isScriptOpen()) { + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } } - if (openedByClient) { - info.isOpen = true; + else if (fileContent !== undefined) { + info.reload(fileContent); } } return info; @@ -1019,7 +1149,7 @@ namespace ts.server { if (args.file) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); if (info) { - info.setFormatOptions(args.formatOptions); + info.setFormatOptions(convertFormatOptions(args.formatOptions)); this.logger.info(`Host configuration update for file ${args.file}`); } } @@ -1029,9 +1159,13 @@ namespace ts.server { this.logger.info(`Host information ${args.hostInfo}`); } if (args.formatOptions) { - mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.logger.info("Host file extension mappings updated"); + } } } @@ -1097,9 +1231,22 @@ namespace ts.server { } openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult { - const { configFileName = undefined, configFileErrors = undefined }: OpenConfiguredProjectResult = this.findContainingExternalProject(fileName) - ? {} - : this.openOrUpdateConfiguredProjectForFile(fileName); + let configFileName: NormalizedPath; + let configFileErrors: Diagnostic[]; + + let project: ConfiguredProject | ExternalProject = this.findContainingExternalProject(fileName); + if (!project) { + ({ configFileName, configFileErrors } = this.openOrUpdateConfiguredProjectForFile(fileName)); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + } + } + if (project && !project.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request + project.markAsDirty(); + } // at this point if file is the part of some configured/external project then this project should be created const info = this.getOrCreateScriptInfoForNormalizedPath(fileName, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent); @@ -1116,7 +1263,6 @@ namespace ts.server { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); if (info) { this.closeOpenFile(info); - info.isOpen = false; } this.printProjects(); } @@ -1141,9 +1287,9 @@ namespace ts.server { if (openFiles) { for (const file of openFiles) { const scriptInfo = this.getScriptInfo(file.fileName); - Debug.assert(!scriptInfo || !scriptInfo.isOpen); + Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); const normalizedPath = scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } } @@ -1213,13 +1359,42 @@ namespace ts.server { } } - openExternalProject(proj: protocol.ExternalProject): void { + openExternalProjects(projects: protocol.ExternalProject[]): void { + // record project list before the update + const projectsToClose = arrayToMap(this.externalProjects, p => p.getProjectName(), _ => true); + for (const externalProjectName in this.externalProjectToConfiguredProjectMap) { + projectsToClose[externalProjectName] = true; + } + + for (const externalProject of projects) { + this.openExternalProject(externalProject, /*suppressRefreshOfInferredProjects*/ true); + // delete project that is present in input list + delete projectsToClose[externalProject.projectFileName]; + } + + // close projects that were missing in the input list + for (const externalProjectName in projectsToClose) { + this.closeExternalProject(externalProjectName, /*suppressRefresh*/ true) + } + + this.refreshInferredProjects(); + } + + openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects = false): void { + // typingOptions has been deprecated and is only supported for backward compatibility + // purposes. It should be removed in future releases - use typeAcquisition instead. + if (proj.typingOptions && !proj.typeAcquisition) { + const typeAcquisition = convertEnableAutoDiscoveryToEnable(proj.typingOptions); + proj.typeAcquisition = typeAcquisition; + } let tsConfigFiles: NormalizedPath[]; const rootFiles: protocol.ExternalFile[] = []; for (const file of proj.rootFiles) { const normalized = toNormalizedPath(file.fileName); if (getBaseFileName(normalized) === "tsconfig.json") { - (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + if (this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } } else { rootFiles.push(file); @@ -1235,8 +1410,15 @@ namespace ts.server { let exisingConfigFiles: string[]; if (externalProject) { if (!tsConfigFiles) { + const compilerOptions = convertCompilerOptions(proj.options); + if (this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, proj.rootFiles, externalFilePropertyReader)) { + externalProject.disableLanguageService(); + } + else { + externalProject.enableLanguageService(); + } // external project already exists and not config files were added - update the project and return; - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, /*configFileErrors*/ undefined); + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, /*configFileErrors*/ undefined); return; } // some config files were added to external project (that previously were not there) @@ -1296,9 +1478,11 @@ namespace ts.server { else { // no config files - remove the item from the collection delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; - this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); + } + if (!suppressRefreshOfInferredProjects) { + this.refreshInferredProjects(); } - this.refreshInferredProjects(); } } } diff --git a/src/server/lsHost.ts b/src/server/lsHost.ts index b36f73a19c5..d73a31933f4 100644 --- a/src/server/lsHost.ts +++ b/src/server/lsHost.ts @@ -3,61 +3,67 @@ /// namespace ts.server { - export class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost { + export class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost { private compilationSettings: ts.CompilerOptions; - private readonly resolvedModuleNames: ts.FileMap>; - private readonly resolvedTypeReferenceDirectives: ts.FileMap>; + private readonly resolvedModuleNames = createFileMap>(); + private readonly resolvedTypeReferenceDirectives = createFileMap>(); private readonly getCanonicalFileName: (fileName: string) => string; + private filesWithChangedSetOfUnresolvedImports: Path[]; + private readonly resolveModuleName: typeof resolveModuleName; readonly trace: (s: string) => void; + readonly realpath?: (path: string) => string; constructor(private readonly host: ServerHost, private readonly project: Project, private readonly cancellationToken: HostCancellationToken) { this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.resolvedModuleNames = createFileMap>(); - this.resolvedTypeReferenceDirectives = createFileMap>(); if (host.trace) { this.trace = s => host.trace(s); } this.resolveModuleName = (moduleName, containingFile, compilerOptions, host) => { + const globalCache = this.project.getTypeAcquisition().enable + ? this.project.projectService.typingsInstaller.globalTypingsCacheLocation + : undefined; const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (primaryResult.resolvedModule) { - // return result immediately only if it is .ts, .tsx or .d.ts + // return result immediately only if it is .ts, .tsx or .d.ts + if (!(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { // otherwise try to load typings from @types - if (fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, supportedTypeScriptExtensions)) { - return primaryResult; + + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(moduleName, this.project.getProjectName(), compilerOptions, host, globalCache); + if (resolvedModule) { + return { resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; } } - // create different collection of failed lookup locations for second pass - // if it will fail and we've already found something during the first pass - we don't want to pollute its results - const secondaryLookupFailedLookupLocations: string[] = []; - const globalCache = this.project.projectService.typingsInstaller.globalTypingsCacheLocation; - if (this.project.getTypingOptions().enableAutoDiscovery && globalCache) { - const traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, this.project.getProjectName(), moduleName, globalCache); - } - const state: ModuleResolutionState = { compilerOptions, host, skipTsx: false, traceEnabled }; - const resolvedName = loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, /*checkOneLevel*/ true); - if (resolvedName) { - return createResolvedModule(resolvedName, /*isExternalLibraryImport*/ true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); - } - } - if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { - primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); - } return primaryResult; }; + + if (this.host.realpath) { + this.realpath = path => this.host.realpath(path); + } } - private resolveNamesWithLocalCache( + public startRecordingFilesWithChangedResolutions() { + this.filesWithChangedSetOfUnresolvedImports = []; + } + + public finishRecordingFilesWithChangedResolutions() { + const collected = this.filesWithChangedSetOfUnresolvedImports; + this.filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + + private resolveNamesWithLocalCache( names: string[], containingFile: string, cache: ts.FileMap>, loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T, - getResult: (s: T) => R): R[] { + getResult: (s: T) => R, + getResultFileName: (result: R) => string | undefined, + logChanges: boolean): R[] { const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); const currentResolutionsInFile = cache.get(path); @@ -79,6 +85,11 @@ namespace ts.server { else { newResolutions[name] = resolution = loader(name, containingFile, compilerOptions, this); } + if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + this.filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } } ts.Debug.assert(resolution !== undefined); @@ -90,6 +101,24 @@ namespace ts.server { cache.set(path, newResolutions); return resolvedModules; + function resolutionIsEqualTo(oldResolution: T, newResolution: T): boolean { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + const oldResult = getResult(oldResolution); + const newResult = getResult(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return getResultFileName(oldResult) === getResultFileName(newResult); + } + function moduleResolutionIsValid(resolution: T): boolean { if (!resolution) { return false; @@ -97,10 +126,7 @@ namespace ts.server { const result = getResult(resolution); if (result) { - if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) { - return false; - } - return true; + return getResultFileName(result) !== lastDeletedFileName; } // consider situation if we have no candidate locations as valid resolution. @@ -126,11 +152,13 @@ namespace ts.server { } resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, m => m.resolvedTypeReferenceDirective); + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, + m => m.resolvedTypeReferenceDirective, r => r.resolvedFileName, /*logChanges*/ false); } - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, m => m.resolvedModule); + resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModuleFull[] { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, + m => m.resolvedModule, r => r.resolvedFileName, /*logChanges*/ true); } getDefaultLibFileName() { @@ -141,7 +169,7 @@ namespace ts.server { getScriptSnapshot(filename: string): ts.IScriptSnapshot { const scriptInfo = this.project.getScriptInfoLSHost(filename); if (scriptInfo) { - return scriptInfo.snap(); + return scriptInfo.getSnapshot(); } } @@ -197,10 +225,11 @@ namespace ts.server { } setCompilationSettings(opt: ts.CompilerOptions) { + if (changesAffectModuleResolution(this.compilationSettings, opt)) { + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + } this.compilationSettings = opt; - // conservatively assume that changing compiler options might affect module resolution strategy - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); } } } \ No newline at end of file diff --git a/src/server/project.ts b/src/server/project.ts index a355d75f942..6085ee05159 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1,4 +1,4 @@ -/// +/// /// /// /// @@ -62,14 +62,52 @@ namespace ts.server { projectErrors: Diagnostic[]; } + export class UnresolvedImportsMap { + readonly perFileMap = createFileMap>(); + private version = 0; + + public clear() { + this.perFileMap.clear(); + this.version = 0; + } + + public getVersion() { + return this.version; + } + + public remove(path: Path) { + this.perFileMap.remove(path); + this.version++; + } + + public get(path: Path) { + return this.perFileMap.get(path); + } + + public set(path: Path, value: ReadonlyArray) { + this.perFileMap.set(path, value); + this.version++; + } + } + export abstract class Project { private rootFiles: ScriptInfo[] = []; private rootFilesMap: FileMap = createFileMap(); - private lsHost: ServerLanguageServiceHost; + private lsHost: LSHost; private program: ts.Program; - private languageService: LanguageService; + private cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); + private lastCachedUnresolvedImportsList: SortedReadonlyArray; + + private readonly languageService: LanguageService; + + public languageServiceEnabled = true; + builder: Builder; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ + private updatedFileNames: Map; /** * Set of files that was returned from the last call to getChangesSinceVersion. */ @@ -91,7 +129,7 @@ namespace ts.server { */ private projectStateVersion = 0; - private typingFiles: TypingsArray; + private typingFiles: SortedReadonlyArray; protected projectErrors: Diagnostic[]; @@ -107,12 +145,17 @@ namespace ts.server { return hasOneOrMoreJsAndNoTsFiles(this); } + public getCachedUnresolvedImportsPerFile_TestOnly() { + return this.cachedUnresolvedImportsPerFile; + } + constructor( + private readonly projectName: string, readonly projectKind: ProjectKind, readonly projectService: ProjectService, private documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, - public languageServiceEnabled: boolean, + languageServiceEnabled: boolean, private compilerOptions: CompilerOptions, public compileOnSaveEnabled: boolean) { @@ -126,10 +169,14 @@ namespace ts.server { this.compilerOptions.allowNonTsExtensions = true; } - if (languageServiceEnabled) { - this.enableLanguageService(); - } - else { + this.setInternalCompilerOptionsForEmittingJsFiles(); + + this.lsHost = new LSHost(this.projectService.host, this, this.projectService.cancellationToken); + this.lsHost.setCompilationSettings(this.compilerOptions); + + this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); + + if (!languageServiceEnabled) { this.disableLanguageService(); } @@ -137,6 +184,12 @@ namespace ts.server { this.markAsDirty(); } + private setInternalCompilerOptionsForEmittingJsFiles() { + if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { + this.compilerOptions.noEmitForJsFiles = true; + } + } + getProjectErrors() { return this.projectErrors; } @@ -161,23 +214,27 @@ namespace ts.server { } enableLanguageService() { - const lsHost = new LSHost(this.projectService.host, this, this.projectService.cancellationToken); - lsHost.setCompilationSettings(this.compilerOptions); - this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); - - this.lsHost = lsHost; + if (this.languageServiceEnabled) { + return; + } this.languageServiceEnabled = true; + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true); } disableLanguageService() { - this.languageService = nullLanguageService; - this.lsHost = nullLanguageServiceHost; + if (!this.languageServiceEnabled) { + return; + } + this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); } - abstract getProjectName(): string; + getProjectName() { + return this.projectName; + } abstract getProjectRootPath(): string | undefined; - abstract getTypingOptions(): TypingOptions; + abstract getTypeAcquisition(): TypeAcquisition; getSourceFile(path: Path) { if (!this.program) { @@ -200,8 +257,9 @@ namespace ts.server { info.detachFromProject(this); } } - else { - // release all root files + if (!this.program || !this.languageServiceEnabled) { + // release all root files either if there is no program or language service is disabled. + // in the latter case set of root files can be larger than the set of files in program. for (const root of this.rootFiles) { root.detachFromProject(this); } @@ -230,7 +288,10 @@ namespace ts.server { const result: string[] = []; if (this.rootFiles) { for (const f of this.rootFiles) { - result.push(f.fileName); + if (this.languageServiceEnabled || f.isScriptOpen()) { + // if language service is disabled - process only files that are open + result.push(f.fileName); + } } if (this.typingFiles) { for (const f of this.typingFiles) { @@ -246,6 +307,10 @@ namespace ts.server { } getScriptInfos() { + if (!this.languageServiceEnabled) { + // if language service is not enabled - return just root files + return this.rootFiles; + } return map(this.program.getSourceFiles(), sourceFile => { const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { @@ -262,7 +327,7 @@ namespace ts.server { return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); } - getFileNames() { + getFileNames(excludeFilesFromExternalLibraries?: boolean) { if (!this.program) { return []; } @@ -278,8 +343,14 @@ namespace ts.server { } return rootFiles; } - const sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(sourceFile => asNormalizedPath(sourceFile.fileName)); + const result: NormalizedPath[] = []; + for (const f of this.program.getSourceFiles()) { + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(asNormalizedPath(f.fileName)); + } + return result; } getAllEmittableFiles() { @@ -303,7 +374,7 @@ namespace ts.server { containsFile(filename: NormalizedPath, requireOpen?: boolean) { const info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isOpen || !requireOpen)) { + if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } } @@ -326,6 +397,7 @@ namespace ts.server { removeFile(info: ScriptInfo, detachFromProject = true) { this.removeRootFileIfNecessary(info); this.lsHost.notifyFileRemoved(info); + this.cachedUnresolvedImportsPerFile.remove(info.path); if (detachFromProject) { info.detachFromProject(this); @@ -334,30 +406,99 @@ namespace ts.server { this.markAsDirty(); } + registerFileUpdate(fileName: string) { + (this.updatedFileNames || (this.updatedFileNames = createMap()))[fileName] = fileName; + } + markAsDirty() { this.projectStateVersion++; } + private extractUnresolvedImportsFromSourceFile(file: SourceFile, result: string[]) { + const cached = this.cachedUnresolvedImportsPerFile.get(file.path); + if (cached) { + // found cached result - use it and return + for (const f of cached) { + result.push(f); + } + return; + } + let unresolvedImports: string[]; + if (file.resolvedModules) { + for (const name in file.resolvedModules) { + // pick unresolved non-relative names + if (!file.resolvedModules[name] && !isExternalModuleNameRelative(name)) { + // for non-scoped names extract part up-to the first slash + // for scoped names - extract up to the second slash + let trimmed = name.trim(); + let i = trimmed.indexOf("/"); + if (i !== -1 && trimmed.charCodeAt(0) === CharacterCodes.at) { + i = trimmed.indexOf("/", i + 1); + } + if (i !== -1) { + trimmed = trimmed.substr(0, i); + } + (unresolvedImports || (unresolvedImports = [])).push(trimmed); + result.push(trimmed); + } + } + } + this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || emptyArray); + } + /** * Updates set of files that contribute to this project * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean { - if (!this.languageServiceEnabled) { - return true; - } + this.lsHost.startRecordingFilesWithChangedResolutions(); + let hasChanges = this.updateGraphWorker(); - const cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); + + const changedFiles: ReadonlyArray = this.lsHost.finishRecordingFilesWithChangedResolutions() || emptyArray; + + for (const file of changedFiles) { + // delete cached information for changed files + this.cachedUnresolvedImportsPerFile.remove(file); + } + + // 1. no changes in structure, no changes in unresolved imports - do nothing + // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files + // (can reuse cached imports for files that were not changed) + // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files + // (can reuse cached imports for files that were not changed) + // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch + let unresolvedImports: SortedReadonlyArray; + if (hasChanges || changedFiles.length) { + const result: string[] = []; + for (const sourceFile of this.program.getSourceFiles()) { + this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + } + this.lastCachedUnresolvedImportsList = toSortedReadonlyArray(result); + } + unresolvedImports = this.lastCachedUnresolvedImportsList; + + const cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } + + // update builder only if language service is enabled + // otherwise tell it to drop its internal state + if (this.languageServiceEnabled) { + this.builder.onProjectUpdateGraph(); + } + else { + this.builder.clear(); + } + if (hasChanges) { this.projectStructureVersion++; } return !hasChanges; } - private setTypings(typings: TypingsArray): boolean { + private setTypings(typings: SortedReadonlyArray): boolean { if (arrayIsEqualTo(this.typingFiles, typings)) { return false; } @@ -389,7 +530,6 @@ namespace ts.server { } } } - this.builder.onProjectUpdateGraph(); return hasChanges; } @@ -430,18 +570,24 @@ namespace ts.server { compilerOptions.allowJs = true; } compilerOptions.allowNonTsExtensions = true; + if (changesAffectModuleResolution(this.compilerOptions, compilerOptions)) { + // reset cached unresolved imports if changes in compiler options affected module resolution + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = undefined; + } this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); this.lsHost.setCompilationSettings(compilerOptions); this.markAsDirty(); } } - reloadScript(filename: NormalizedPath): boolean { + reloadScript(filename: NormalizedPath, tempFileName?: NormalizedPath): boolean { const script = this.projectService.getScriptInfoForNormalizedPath(filename); if (script) { Debug.assert(script.isAttached(this)); - script.reloadFromFile(); + script.reloadFromFile(tempFileName); return true; } return false; @@ -454,12 +600,15 @@ namespace ts.server { projectName: this.getProjectName(), version: this.projectStructureVersion, isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions() + options: this.getCompilerOptions(), + languageServiceDisabled: !this.languageServiceEnabled }; + const updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; // check if requested version is the same that we have reported last time if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - // if current structure version is the same - return info witout any changes - if (this.projectStructureVersion == this.lastReportedVersion) { + // if current structure version is the same - return info without any changes + if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) { return { info, projectErrors: this.projectErrors }; } // compute and return the difference @@ -468,6 +617,7 @@ namespace ts.server { const added: string[] = []; const removed: string[] = []; + const updated: string[] = getOwnKeys(updatedFileNames); for (const id in currentFiles) { if (!hasProperty(lastReportedFileNames, id)) { added.push(id); @@ -480,7 +630,7 @@ namespace ts.server { } this.lastReportedFileNames = currentFiles; this.lastReportedVersion = this.projectStructureVersion; - return { info, changes: { added, removed }, projectErrors: this.projectErrors }; + return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors }; } else { // unknown version - return everything @@ -556,31 +706,27 @@ namespace ts.server { export class InferredProject extends Project { - private static NextId = 1; - - /** - * Unique name that identifies this particular inferred project - */ - private readonly inferredProjectName: string; + private static newName = (() => { + let nextId = 1; + return () => { + const id = nextId; + nextId++; + return makeInferredProjectName(id); + } + })(); // Used to keep track of what directories are watched for this project directoriesWatchedForTsconfig: string[] = []; - constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, public compileOnSaveEnabled: boolean) { - super(ProjectKind.Inferred, + constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions) { + super(InferredProject.newName(), + ProjectKind.Inferred, projectService, documentRegistry, /*files*/ undefined, - languageServiceEnabled, + /*languageServiceEnabled*/ true, compilerOptions, - compileOnSaveEnabled); - - this.inferredProjectName = makeInferredProjectName(InferredProject.NextId); - InferredProject.NextId++; - } - - getProjectName() { - return this.inferredProjectName; + /*compileOnSaveEnabled*/ false); } getProjectRootPath() { @@ -600,9 +746,9 @@ namespace ts.server { } } - getTypingOptions(): TypingOptions { + getTypeAcquisition(): TypeAcquisition { return { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), + enable: allRootFilesAreJsOrDts(this), include: [], exclude: [] }; @@ -610,16 +756,17 @@ namespace ts.server { } export class ConfiguredProject extends Project { - private typingOptions: TypingOptions; + private typeAcquisition: TypeAcquisition; private projectFileWatcher: FileWatcher; private directoryWatcher: FileWatcher; private directoriesWatchedForWildcards: Map; private typeRootsWatchers: FileWatcher[]; + readonly canonicalConfigFilePath: NormalizedPath; /** Used for configured projects which may have multiple open roots */ openRefCount = 0; - constructor(readonly configFileName: NormalizedPath, + constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, @@ -627,31 +774,32 @@ namespace ts.server { private wildcardDirectories: Map, languageServiceEnabled: boolean, public compileOnSaveEnabled: boolean) { - super(ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); + super(configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); + this.canonicalConfigFilePath = asNormalizedPath(projectService.toCanonicalFileName(configFileName)); + } + + getConfigFilePath() { + return this.getProjectName(); } getProjectRootPath() { - return getDirectoryPath(this.configFileName); + return getDirectoryPath(this.getConfigFilePath()); } setProjectErrors(projectErrors: Diagnostic[]) { this.projectErrors = projectErrors; } - setTypingOptions(newTypingOptions: TypingOptions): void { - this.typingOptions = newTypingOptions; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void { + this.typeAcquisition = newTypeAcquisition; } - getTypingOptions() { - return this.typingOptions; - } - - getProjectName() { - return this.configFileName; + getTypeAcquisition() { + return this.typeAcquisition; } watchConfigFile(callback: (project: ConfiguredProject) => void) { - this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, _ => callback(this)); + this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), _ => callback(this)); } watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void) { @@ -669,7 +817,7 @@ namespace ts.server { return; } - const directoryToWatch = getDirectoryPath(this.configFileName); + const directoryToWatch = getDirectoryPath(this.getConfigFilePath()); this.projectService.logger.info(`Add recursive watcher for: ${directoryToWatch}`); this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, path => callback(this, path), /*recursive*/ true); } @@ -678,7 +826,7 @@ namespace ts.server { if (!this.wildcardDirectories) { return; } - const configDirectoryPath = getDirectoryPath(this.configFileName); + const configDirectoryPath = getDirectoryPath(this.getConfigFilePath()); this.directoriesWatchedForWildcards = reduceProperties(this.wildcardDirectories, (watchers, flag, directory) => { if (comparePaths(configDirectoryPath, directory, ".", !this.projectService.host.useCaseSensitiveFileNames) !== Comparison.EqualTo) { const recursive = (flag & WatchDirectoryFlags.Recursive) !== 0; @@ -737,15 +885,15 @@ namespace ts.server { } export class ExternalProject extends Project { - private typingOptions: TypingOptions; - constructor(readonly externalProjectName: string, + private typeAcquisition: TypeAcquisition; + constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, public compileOnSaveEnabled: boolean, private readonly projectFilePath?: string) { - super(ProjectKind.External, projectService, documentRegistry, /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); + super(externalProjectName, ProjectKind.External, projectService, documentRegistry, /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); } getProjectRootPath() { @@ -755,43 +903,39 @@ namespace ts.server { // if the projectFilePath is not given, we make the assumption that the project name // is the path of the project file. AS the project name is provided by VS, we need to // normalize slashes before using it as a file name. - return getDirectoryPath(normalizeSlashes(this.externalProjectName)); + return getDirectoryPath(normalizeSlashes(this.getProjectName())); } - getTypingOptions() { - return this.typingOptions; + getTypeAcquisition() { + return this.typeAcquisition; } setProjectErrors(projectErrors: Diagnostic[]) { this.projectErrors = projectErrors; } - setTypingOptions(newTypingOptions: TypingOptions): void { - if (!newTypingOptions) { + setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void { + if (!newTypeAcquisition) { // set default typings options - newTypingOptions = { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), + newTypeAcquisition = { + enable: allRootFilesAreJsOrDts(this), include: [], exclude: [] }; } else { - if (newTypingOptions.enableAutoDiscovery === undefined) { + if (newTypeAcquisition.enable === undefined) { // if autoDiscovery was not specified by the caller - set it based on the content of the project - newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); + newTypeAcquisition.enable = allRootFilesAreJsOrDts(this); } - if (!newTypingOptions.include) { - newTypingOptions.include = []; + if (!newTypeAcquisition.include) { + newTypeAcquisition.include = []; } - if (!newTypingOptions.exclude) { - newTypingOptions.exclude = []; + if (!newTypeAcquisition.exclude) { + newTypeAcquisition.exclude = []; } } - this.typingOptions = newTypingOptions; - } - - getProjectName() { - return this.externalProjectName; + this.typeAcquisition = newTypeAcquisition; } } } \ No newline at end of file diff --git a/src/server/protocol.d.ts b/src/server/protocol.ts similarity index 71% rename from src/server/protocol.d.ts rename to src/server/protocol.ts index 2f447934040..680b81dff99 100644 --- a/src/server/protocol.d.ts +++ b/src/server/protocol.ts @@ -1,7 +1,102 @@ -/** +/** * Declaration module describing the TypeScript Server protocol */ -declare namespace ts.server.protocol { +namespace ts.server.protocol { + export namespace CommandTypes { + export type Brace = "brace"; + /* @internal */ + export type BraceFull = "brace-full"; + export type BraceCompletion = "braceCompletion"; + export type Change = "change"; + export type Close = "close"; + export type Completions = "completions"; + /* @internal */ + export type CompletionsFull = "completions-full"; + export type CompletionDetails = "completionEntryDetails"; + export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + export type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + export type Configure = "configure"; + export type Definition = "definition"; + /* @internal */ + export type DefinitionFull = "definition-full"; + export type Implementation = "implementation"; + /* @internal */ + export type ImplementationFull = "implementation-full"; + export type Exit = "exit"; + export type Format = "format"; + export type Formatonkey = "formatonkey"; + /* @internal */ + export type FormatFull = "format-full"; + /* @internal */ + export type FormatonkeyFull = "formatonkey-full"; + /* @internal */ + export type FormatRangeFull = "formatRange-full"; + export type Geterr = "geterr"; + export type GeterrForProject = "geterrForProject"; + export type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + export type NavBar = "navbar"; + /* @internal */ + export type NavBarFull = "navbar-full"; + export type Navto = "navto"; + /* @internal */ + export type NavtoFull = "navto-full"; + export type NavTree = "navtree"; + export type NavTreeFull = "navtree-full"; + export type Occurrences = "occurrences"; + export type DocumentHighlights = "documentHighlights"; + /* @internal */ + export type DocumentHighlightsFull = "documentHighlights-full"; + export type Open = "open"; + export type Quickinfo = "quickinfo"; + /* @internal */ + export type QuickinfoFull = "quickinfo-full"; + export type References = "references"; + /* @internal */ + export type ReferencesFull = "references-full"; + export type Reload = "reload"; + export type Rename = "rename"; + /* @internal */ + export type RenameInfoFull = "rename-full"; + /* @internal */ + export type RenameLocationsFull = "renameLocations-full"; + export type Saveto = "saveto"; + export type SignatureHelp = "signatureHelp"; + /* @internal */ + export type SignatureHelpFull = "signatureHelp-full"; + export type TypeDefinition = "typeDefinition"; + export type ProjectInfo = "projectInfo"; + export type ReloadProjects = "reloadProjects"; + export type Unknown = "unknown"; + export type OpenExternalProject = "openExternalProject"; + export type OpenExternalProjects = "openExternalProjects"; + export type CloseExternalProject = "closeExternalProject"; + /* @internal */ + export type SynchronizeProjectList = "synchronizeProjectList"; + /* @internal */ + export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + /* @internal */ + export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + /* @internal */ + export type Cleanup = "cleanup"; + /* @internal */ + export type OutliningSpans = "outliningSpans"; + export type TodoComments = "todoComments"; + export type Indentation = "indentation"; + export type DocCommentTemplate = "docCommentTemplate"; + /* @internal */ + export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + /* @internal */ + export type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + /* @internal */ + export type BreakpointStatement = "breakpointStatement"; + export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + export type GetCodeFixes = "getCodeFixes"; + /* @internal */ + export type GetCodeFixesFull = "getCodeFixes-full"; + export type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + /** * A TypeScript Server message */ @@ -14,7 +109,7 @@ declare namespace ts.server.protocol { /** * One of "request", "response", or "event" */ - type: string; + type: "request" | "response" | "event"; } /** @@ -36,6 +131,7 @@ declare namespace ts.server.protocol { * Request to reload the project structure for all the opened files */ export interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; } /** @@ -98,10 +194,25 @@ declare namespace ts.server.protocol { projectFileName?: string; } + /** + * Requests a JS Doc comment template for a given position + */ + export interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + + /** + * Response to DocCommentTemplateRequest + */ + export interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** * A request to get TODO comments from the file */ export interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; arguments: TodoCommentRequestArgs; } @@ -115,13 +226,58 @@ declare namespace ts.server.protocol { descriptors: TodoCommentDescriptor[]; } + /** + * Response for TodoCommentRequest request. + */ + export interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + + /** + * Request to obtain outlining spans in file. + */ + /* @internal */ + export interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + + /** + * Response to OutliningSpansRequest request. + */ + /* @internal */ + export interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** * A request to get indentation for a location in file */ export interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; arguments: IndentationRequestArgs; } + /** + * Response for IndentationRequest request. + */ + export interface IndentationResponse extends Response { + body?: IndentationResult; + } + + /** + * Indentation result representing where indentation should be placed + */ + export interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** * Arguments for IndentationRequest request. */ @@ -147,6 +303,7 @@ declare namespace ts.server.protocol { * A request to get the project information of the current file. */ export interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; arguments: ProjectInfoRequestArgs; } @@ -223,16 +380,17 @@ declare namespace ts.server.protocol { /** * The line number for the request (1-based). */ - line?: number; + line: number; /** * The character offset (on the line) for the request (1-based). */ - offset?: number; + offset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ position?: number; } @@ -240,6 +398,7 @@ declare namespace ts.server.protocol { * Request for the available codefixes at a specific position. */ export interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } @@ -250,31 +409,33 @@ declare namespace ts.server.protocol { /** * The line number for the request (1-based). */ - startLine?: number; + startLine: number; /** * The character offset (on the line) for the request (1-based). */ - startOffset?: number; + startOffset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ startPosition?: number; /** * The line number for the request (1-based). */ - endLine?: number; + endLine: number; /** * The character offset (on the line) for the request (1-based). */ - endOffset?: number; + endOffset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ endPosition?: number; /** @@ -283,6 +444,13 @@ declare namespace ts.server.protocol { errorCodes?: number[]; } + /** + * Response for GetCodeFixes request. + */ + export interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** * A request whose arguments specify a file location (file, line, col). */ @@ -291,16 +459,34 @@ declare namespace ts.server.protocol { } /** - * A request to get semantic diagnostics for a span in the file + * A request to get codes of supported code fixes. */ - export interface SemanticDiagnosticsRequest extends FileRequest { - arguments: SemanticDiagnosticsRequestArgs; + export interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; } /** - * Arguments for SemanticDiagnosticsRequest request. + * A response for GetSupportedCodeFixesRequest request. */ - export interface SemanticDiagnosticsRequestArgs extends FileRequestArgs { + export interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + + /** + * A request to get encoded semantic classifications for a span in the file + */ + /** @internal */ + export interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + export interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { /** * Start position of the span. */ @@ -328,6 +514,7 @@ declare namespace ts.server.protocol { * define the symbol found in file at location line, col. */ export interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; } /** @@ -336,6 +523,7 @@ declare namespace ts.server.protocol { * define the type for the symbol found in file at location line, col. */ export interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; } /** @@ -344,6 +532,7 @@ declare namespace ts.server.protocol { * implement the symbol found in file at location line, col. */ export interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; } /** @@ -404,6 +593,7 @@ declare namespace ts.server.protocol { * Request to get brace completion for a location in the file. */ export interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; arguments: BraceCompletionRequestArgs; } @@ -423,6 +613,7 @@ declare namespace ts.server.protocol { * in the file at a given line and column. */ export interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; } export interface OccurrencesResponseItem extends FileSpan { @@ -442,6 +633,7 @@ declare namespace ts.server.protocol { * in the file at a given line and column. */ export interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; arguments: DocumentHighlightsRequestArgs; } @@ -481,6 +673,7 @@ declare namespace ts.server.protocol { * reference the symbol found in file at location line, col. */ export interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; } export interface ReferencesResponseItem extends FileSpan { @@ -555,6 +748,7 @@ declare namespace ts.server.protocol { * name of the symbol so that client can print it unambiguously. */ export interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; arguments: RenameRequestArgs; } @@ -639,7 +833,7 @@ declare namespace ts.server.protocol { /** * Script kind of the file */ - scriptKind?: ScriptKind; + scriptKind?: ScriptKindName | ts.ScriptKind; /** * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) */ @@ -667,25 +861,32 @@ declare namespace ts.server.protocol { */ options: ExternalProjectCompilerOptions; /** - * Explicitly specified typing options for the project + * @deprecated typingOptions. Use typeAcquisition instead */ - typingOptions?: TypingOptions; + typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; } - /** - * For external projects, some of the project settings are sent together with - * compiler settings. - */ - export interface ExternalProjectCompilerOptions extends CompilerOptions { + export interface CompileOnSaveMixin { /** * If compile on save is enabled for the project */ compileOnSave?: boolean; } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + export type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** * Contains information about current project version */ + /* @internal */ export interface ProjectVersionInfo { /** * Project name @@ -702,7 +903,12 @@ declare namespace ts.server.protocol { /** * Current set of compiler options for project */ - options: CompilerOptions; + options: ts.CompilerOptions; + + /** + * true if project language service is disabled + */ + languageServiceDisabled: boolean; } /** @@ -717,6 +923,10 @@ declare namespace ts.server.protocol { * List of removed files */ removed: string[]; + /** + * List of updated files + */ + updated: string[]; } /** @@ -726,6 +936,7 @@ declare namespace ts.server.protocol { * if changes is set - then this is the set of changes that should be applied to existing project * otherwise - assume that nothing is changed */ + /* @internal */ export interface ProjectFiles { /** * Information abount project verison @@ -744,6 +955,7 @@ declare namespace ts.server.protocol { /** * Combines project information with project level errors. */ + /* @internal */ export interface ProjectFilesWithDiagnostics extends ProjectFiles { /** * List of errors in project @@ -754,6 +966,7 @@ declare namespace ts.server.protocol { /** * Represents set of changes in open file */ + /* @internal */ export interface ChangedOpenFile { /** * Name of file @@ -765,65 +978,6 @@ declare namespace ts.server.protocol { changes: ts.TextChange[]; } - /** - * Editor options - */ - export interface EditorOptions { - - /** Number of spaces for each tab. Default value is 4. */ - tabSize?: number; - - /** Number of spaces to indent during formatting. Default value is 4. */ - indentSize?: number; - - /** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */ - baseIndentSize?: number; - - /** The new line character to be used. Default value is the OS line delimiter. */ - newLineCharacter?: string; - - /** Whether tabs should be converted to spaces. Default value is true. */ - convertTabsToSpaces?: boolean; - } - - /** - * Format options - */ - export interface FormatOptions extends EditorOptions { - - /** Defines space handling after a comma delimiter. Default value is true. */ - insertSpaceAfterCommaDelimiter?: boolean; - - /** Defines space handling after a semicolon in a for statement. Default value is true */ - insertSpaceAfterSemicolonInForStatements?: boolean; - - /** Defines space handling after a binary operator. Default value is true. */ - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - - /** Defines space handling after keywords in control flow statement. Default value is true. */ - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - - /** Defines space handling after function keyword for anonymous functions. Default value is false. */ - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - - /** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - - /** Defines space handling after opening and before closing non empty brackets. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - - /** Defines space handling before and after template string braces. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - - /** Defines space handling before and after JSX expression braces. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - - /** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */ - placeOpenBraceOnNewLineForFunctions?: boolean; - - /** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */ - placeOpenBraceOnNewLineForControlBlocks?: boolean; - } /** * Information found in a configure request. @@ -844,12 +998,12 @@ declare namespace ts.server.protocol { /** * The format options to use during formatting and other code editing features. */ - formatOptions?: FormatOptions; + formatOptions?: FormatCodeSettings; /** - * If set to true - then all loose files will land into one inferred project + * The host's additional supported file extensions */ - useOneInferredProject?: boolean; + extraFileExtensions?: FileExtensionInfo[]; } /** @@ -857,6 +1011,7 @@ declare namespace ts.server.protocol { * host information, such as host type, tab size, and indent size. */ export interface ConfigureRequest extends Request { + command: CommandTypes.Configure; arguments: ConfigureRequestArguments; } @@ -880,9 +1035,11 @@ declare namespace ts.server.protocol { * Used to specify the script kind of the file explicitly. It could be one of the following: * "TS", "JS", "TSX", "JSX" */ - scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; + scriptKindName?: ScriptKindName; } + export type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** * Open request; value of command field is "open". Notify the * server that the client has file open. The server will not @@ -892,6 +1049,7 @@ declare namespace ts.server.protocol { * send a response to an open request. */ export interface OpenRequest extends Request { + command: CommandTypes.Open; arguments: OpenRequestArgs; } @@ -899,18 +1057,20 @@ declare namespace ts.server.protocol { * Request to open or update external project */ export interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; arguments: OpenExternalProjectArgs; } /** * Arguments to OpenExternalProjectRequest request */ - type OpenExternalProjectArgs = ExternalProject; + export type OpenExternalProjectArgs = ExternalProject; /** * Request to open multiple external projects */ export interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; arguments: OpenExternalProjectsArgs; } @@ -924,10 +1084,25 @@ declare namespace ts.server.protocol { projects: ExternalProject[]; } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface OpenExternalProjectResponse extends Response { + } + + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface OpenExternalProjectsResponse extends Response { + } + /** * Request to close external project. */ export interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; arguments: CloseExternalProjectRequestArgs; } @@ -941,9 +1116,17 @@ declare namespace ts.server.protocol { projectFileName: string; } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface CloseExternalProjectResponse extends Response { + } + /** * Request to check if given list of projects is up-to-date and synchronize them if necessary */ + /* @internal */ export interface SynchronizeProjectListRequest extends Request { arguments: SynchronizeProjectListRequestArgs; } @@ -951,6 +1134,7 @@ declare namespace ts.server.protocol { /** * Arguments to SynchronizeProjectListRequest */ + /* @internal */ export interface SynchronizeProjectListRequestArgs { /** * List of last known projects @@ -961,6 +1145,7 @@ declare namespace ts.server.protocol { /** * Request to synchronize list of open files with the client */ + /* @internal */ export interface ApplyChangedToOpenFilesRequest extends Request { arguments: ApplyChangedToOpenFilesRequestArgs; } @@ -968,6 +1153,7 @@ declare namespace ts.server.protocol { /** * Arguments to ApplyChangedToOpenFilesRequest */ + /* @internal */ export interface ApplyChangedToOpenFilesRequestArgs { /** * List of newly open files @@ -993,6 +1179,7 @@ declare namespace ts.server.protocol { * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. */ export interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; arguments: SetCompilerOptionsForInferredProjectsArgs; } @@ -1006,11 +1193,19 @@ declare namespace ts.server.protocol { options: ExternalProjectCompilerOptions; } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + export interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** * Exit request; value of command field is "exit". Ask the server process * to exit. */ export interface ExitRequest extends Request { + command: CommandTypes.Exit; } /** @@ -1021,6 +1216,7 @@ declare namespace ts.server.protocol { * currently send a response to a close request. */ export interface CloseRequest extends FileRequest { + command: CommandTypes.Close; } /** @@ -1028,6 +1224,7 @@ declare namespace ts.server.protocol { * NOTE: this us query-only operation and does not generate any output on disk. */ export interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; } /** @@ -1055,7 +1252,8 @@ declare namespace ts.server.protocol { * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. */ export interface CompileOnSaveEmitFileRequest extends FileRequest { - args: CompileOnSaveEmitFileRequestArgs; + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; } /** @@ -1075,6 +1273,7 @@ declare namespace ts.server.protocol { * line, col. */ export interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; } /** @@ -1136,12 +1335,12 @@ declare namespace ts.server.protocol { /** * End position of the range for which to format text in file. */ + /* @internal */ endPosition?: number; - /** * Format options to be used. */ - options?: ts.FormatCodeOptions; + options?: FormatCodeSettings; } /** @@ -1152,6 +1351,7 @@ declare namespace ts.server.protocol { * reformatted text. */ export interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; arguments: FormatRequestArgs; } @@ -1213,7 +1413,7 @@ declare namespace ts.server.protocol { */ key: string; - options?: ts.FormatCodeOptions; + options?: FormatCodeSettings; } /** @@ -1225,6 +1425,7 @@ declare namespace ts.server.protocol { * reformatted text. */ export interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } @@ -1245,6 +1446,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ export interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; arguments: CompletionsRequestArgs; } @@ -1265,6 +1467,7 @@ declare namespace ts.server.protocol { * detailed information for each completion entry. */ export interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; arguments: CompletionDetailsRequestArgs; } @@ -1451,6 +1654,7 @@ declare namespace ts.server.protocol { * help. */ export interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; arguments: SignatureHelpRequestArgs; } @@ -1465,6 +1669,7 @@ declare namespace ts.server.protocol { * Synchronous request for semantic diagnostics of one file. */ export interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; arguments: SemanticDiagnosticsSyncRequestArgs; } @@ -1483,6 +1688,7 @@ declare namespace ts.server.protocol { * Synchronous request for syntactic diagnostics of one file. */ export interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; arguments: SyntacticDiagnosticsSyncRequestArgs; } @@ -1519,6 +1725,7 @@ declare namespace ts.server.protocol { * it request for every file in this project. */ export interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; arguments: GeterrForProjectRequestArgs; } @@ -1550,6 +1757,7 @@ declare namespace ts.server.protocol { * file that is currently visible, in most-recently-used order. */ export interface GeterrRequest extends Request { + command: CommandTypes.Geterr; arguments: GeterrRequestArgs; } @@ -1624,6 +1832,27 @@ declare namespace ts.server.protocol { event: "configFileDiag"; } + export type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + export interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + + export interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + /** * Arguments for reload request. */ @@ -1642,11 +1871,12 @@ declare namespace ts.server.protocol { * The two names can be identical. */ export interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; arguments: ReloadRequestArgs; } /** - * Response to "reload" request. This is just an acknowledgement, so + * Response to "reload" request. This is just an acknowledgement, so * no body field is required. */ export interface ReloadResponse extends Response { @@ -1671,6 +1901,7 @@ declare namespace ts.server.protocol { * "saveto" request. */ export interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; arguments: SavetoRequestArgs; } @@ -1703,6 +1934,7 @@ declare namespace ts.server.protocol { * context for the search is given by the named file. */ export interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; arguments: NavtoRequestArgs; } @@ -1786,6 +2018,7 @@ declare namespace ts.server.protocol { * Server does not currently send a response to a change request. */ export interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; arguments: ChangeRequestArgs; } @@ -1802,6 +2035,7 @@ declare namespace ts.server.protocol { * found in file at location line, offset. */ export interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; } /** @@ -1810,6 +2044,7 @@ declare namespace ts.server.protocol { * extracted from the requested file. */ export interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; } /** @@ -1817,6 +2052,7 @@ declare namespace ts.server.protocol { * Return response giving the navigation tree of the requested file. */ export interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; } export interface NavigationBarItem { @@ -1860,6 +2096,75 @@ declare namespace ts.server.protocol { childItems?: NavigationTree[]; } + export type TelemetryEventName = "telemetry"; + + export interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + + export interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + + export type TypingsInstalledTelemetryEventName = "typingsInstalled"; + + export interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + + export interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + + export type BeginInstallTypesEventName = "beginInstallTypes"; + export type EndInstallTypesEventName = "endInstallTypes"; + + export interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + + export interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + + export interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: ReadonlyArray; + } + + export interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + + export interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + export interface NavBarResponse extends Response { body?: NavigationBarItem[]; } @@ -1867,4 +2172,143 @@ declare namespace ts.server.protocol { export interface NavTreeResponse extends Response { body?: NavigationTree; } + + export namespace IndentStyle { + export type None = "None"; + export type Block = "Block"; + export type Smart = "Smart"; + } + + export type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; + + export interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + + export interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } + + export interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + + export namespace JsxEmit { + export type None = "None"; + export type Preserve = "Preserve"; + export type React = "React"; + } + + export type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React; + + export namespace ModuleKind { + export type None = "None"; + export type CommonJS = "CommonJS"; + export type AMD = "AMD"; + export type UMD = "UMD"; + export type System = "System"; + export type ES6 = "ES6"; + export type ES2015 = "ES2015"; + } + + export type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; + + export namespace ModuleResolutionKind { + export type Classic = "Classic"; + export type Node = "Node"; + } + + export type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; + + export namespace NewLineKind { + export type Crlf = "Crlf"; + export type Lf = "Lf"; + } + + export type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; + + export namespace ScriptTarget { + export type ES3 = "ES3"; + export type ES5 = "ES5"; + export type ES6 = "ES6"; + export type ES2015 = "ES2015"; + } + + export type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; } diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index ee5122ff4e1..0acd45d0287 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -2,6 +2,161 @@ namespace ts.server { + /* @internal */ + export class TextStorage { + private svc: ScriptVersionCache | undefined; + private svcVersion = 0; + + private text: string; + private lineMap: number[]; + private textVersion = 0; + + constructor(private readonly host: ServerHost, private readonly fileName: NormalizedPath) { + } + + public getVersion() { + return this.svc + ? `SVC-${this.svcVersion}-${this.svc.getSnapshot().version}` + : `Text-${this.textVersion}`; + } + + public hasScriptVersionCache() { + return this.svc !== undefined; + } + + public useScriptVersionCache(newText?: string) { + this.switchToScriptVersionCache(newText); + } + + public useText(newText?: string) { + this.svc = undefined; + this.setText(newText); + } + + public edit(start: number, end: number, newText: string) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + } + + public reload(text: string) { + if (this.svc) { + this.svc.reload(text); + } + else { + this.setText(text); + } + } + + public reloadFromFile(tempFileName?: string) { + if (this.svc || (tempFileName !== this.fileName)) { + this.reload(this.getFileText(tempFileName)) + } + else { + this.setText(undefined); + } + } + + public getSnapshot(): IScriptSnapshot { + return this.svc + ? this.svc.getSnapshot() + : ScriptSnapshot.fromString(this.getOrLoadText()); + } + + public getLineInfo(line: number) { + return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + } + /** + * @param line 0 based index + */ + lineToTextSpan(line: number) { + if (!this.svc) { + const lineMap = this.getLineMap(); + const start = lineMap[line]; // -1 since line is 1-based + const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + const index = this.svc.getSnapshot().index; + const lineInfo = index.lineNumberToInfo(line + 1); + let len: number; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + const nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + } + + /** + * @param line 1 based index + * @param offset 1 based index + */ + lineOffsetToPosition(line: number, offset: number): number { + if (!this.svc) { + return computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + } + const index = this.svc.getSnapshot().index; + + const lineInfo = index.lineNumberToInfo(line); + // TODO: assert this offset is actually on the line + return (lineInfo.offset + offset - 1); + } + + /** + * @param line 1-based index + * @param offset 1-based index + */ + positionToLineOffset(position: number): ILineInfo { + if (!this.svc) { + const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position); + return { line: line + 1, offset: character + 1 }; + } + const index = this.svc.getSnapshot().index; + const lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + } + + private getFileText(tempFileName?: string) { + return this.host.readFile(tempFileName || this.fileName) || ""; + } + + private ensureNoScriptVersionCache() { + Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + } + + private switchToScriptVersionCache(newText?: string): ScriptVersionCache { + if (!this.svc) { + this.svc = ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svcVersion++; + this.text = undefined; + } + return this.svc; + } + + private getOrLoadText() { + this.ensureNoScriptVersionCache(); + if (this.text === undefined) { + this.setText(this.getFileText()); + } + return this.text; + } + + private getLineMap() { + this.ensureNoScriptVersionCache(); + return this.lineMap || (this.lineMap = computeLineStarts(this.getOrLoadText())); + } + + private setText(newText: string) { + this.ensureNoScriptVersionCache(); + if (newText === undefined || this.text !== newText) { + this.text = newText; + this.lineMap = undefined; + this.textVersion++; + } + } + } + + export class ScriptInfo { /** * All projects that include this file @@ -11,24 +166,46 @@ namespace ts.server { readonly path: Path; private fileWatcher: FileWatcher; - private svc: ScriptVersionCache; + private textStorage: TextStorage; + + private isOpen: boolean; - // TODO: allow to update hasMixedContent from the outside constructor( private readonly host: ServerHost, readonly fileName: NormalizedPath, - content: string, readonly scriptKind: ScriptKind, - public isOpen = false, public hasMixedContent = false) { this.path = toPath(fileName, host.getCurrentDirectory(), createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); + this.textStorage = new TextStorage(host, fileName); + if (hasMixedContent) { + this.textStorage.reload(""); + } this.scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); } + public isScriptOpen() { + return this.isOpen; + } + + public open(newText: string) { + this.isOpen = true; + this.textStorage.useScriptVersionCache(newText); + this.markContainingProjectsAsDirty(); + } + + public close() { + this.isOpen = false; + this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.markContainingProjectsAsDirty(); + } + + public getSnapshot() { + return this.textStorage.getSnapshot(); + } + getFormatCodeSettings() { return this.formatCodeSettings; } @@ -87,11 +264,16 @@ namespace ts.server { if (this.containingProjects.length === 0) { return Errors.ThrowNoProject(); } - Debug.assert(this.containingProjects.length !== 0); return this.containingProjects[0]; } - setFormatOptions(formatSettings: protocol.FormatOptions): void { + registerFileUpdate(): void { + for (const p of this.containingProjects) { + p.registerFileUpdate(this.path); + } + } + + setFormatOptions(formatSettings: FormatCodeSettings): void { if (formatSettings) { if (!this.formatCodeSettings) { this.formatCodeSettings = getDefaultFormatCodeSettings(this.host); @@ -113,40 +295,35 @@ namespace ts.server { } getLatestVersion() { - return this.svc.latestVersion().toString(); + return this.textStorage.getVersion(); } reload(script: string) { - this.svc.reload(script); + this.textStorage.reload(script); this.markContainingProjectsAsDirty(); } saveTo(fileName: string) { - const snap = this.snap(); + const snap = this.textStorage.getSnapshot(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); } - reloadFromFile() { + reloadFromFile(tempFileName?: NormalizedPath) { if (this.hasMixedContent) { this.reload(""); } else { - this.svc.reloadFromFile(this.fileName); + this.textStorage.reloadFromFile(tempFileName); this.markContainingProjectsAsDirty(); } } - snap() { - return this.svc.getSnapshot(); - } - getLineInfo(line: number) { - const snap = this.snap(); - return snap.index.lineNumberToInfo(line); + return this.textStorage.getLineInfo(line); } editContent(start: number, end: number, newText: string): void { - this.svc.edit(start, end - start, newText); + this.textStorage.edit(start, end, newText); this.markContainingProjectsAsDirty(); } @@ -160,17 +337,7 @@ namespace ts.server { * @param line 1 based index */ lineToTextSpan(line: number) { - const index = this.snap().index; - const lineInfo = index.lineNumberToInfo(line + 1); - let len: number; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - const nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); + return this.textStorage.lineToTextSpan(line); } /** @@ -178,11 +345,7 @@ namespace ts.server { * @param offset 1 based index */ lineOffsetToPosition(line: number, offset: number): number { - const index = this.snap().index; - - const lineInfo = index.lineNumberToInfo(line); - // TODO: assert this offset is actually on the line - return (lineInfo.offset + offset - 1); + return this.textStorage.lineOffsetToPosition(line, offset); } /** @@ -190,9 +353,7 @@ namespace ts.server { * @param offset 1-based index */ positionToLineOffset(position: number): ILineInfo { - const index = this.snap().index; - const lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return this.textStorage.positionToLineOffset(position); } } } \ No newline at end of file diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index 1508187c13e..e087c3b6dde 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -1,6 +1,5 @@ /// /// -/// /// namespace ts.server { @@ -42,7 +41,7 @@ namespace ts.server { class BaseLineIndexWalker implements ILineIndexWalker { goSubtree = true; done = false; - leaf(rangeStart: number, rangeLength: number, ll: LineLeaf) { + leaf(_rangeStart: number, _rangeLength: number, _ll: LineLeaf) { } } @@ -151,7 +150,7 @@ namespace ts.server { return this.lineIndex; } - post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection { + post(_relativeStart: number, _relativeLength: number, lineCollection: LineCollection): LineCollection { // have visited the path for start of range, now looking for end // if range is on single line, we will never make this state transition if (lineCollection === this.lineCollectionAtBranch) { @@ -162,7 +161,7 @@ namespace ts.server { return undefined; } - pre(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection) { + pre(_relativeStart: number, _relativeLength: number, lineCollection: LineCollection, _parent: LineCollection, nodeType: CharRangeSection) { // currentNode corresponds to parent, but in the new tree const currentNode = this.stack[this.stack.length - 1]; @@ -399,7 +398,7 @@ namespace ts.server { index: LineIndex; changesSincePreviousVersion: TextChange[] = []; - constructor(public version: number, public cache: ScriptVersionCache) { + constructor(readonly version: number, readonly cache: ScriptVersionCache) { } getText(rangeStart: number, rangeEnd: number) { @@ -415,7 +414,7 @@ namespace ts.server { const starts: number[] = [-1]; let count = 1; let pos = 0; - this.index.every((ll, s, len) => { + this.index.every(ll => { starts[count] = pos; count++; pos += ll.text.length; @@ -439,8 +438,9 @@ namespace ts.server { } } getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange { - const oldSnap = oldSnapshot; - return this.getTextChangeRangeSinceVersion(oldSnap.version); + if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { + return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + } } } diff --git a/src/server/server.ts b/src/server/server.ts index d59100bb57c..a020ef210fe 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -1,4 +1,5 @@ /// +/// /// // used in fs.writeSync /* tslint:disable:no-null-keyword */ @@ -14,32 +15,53 @@ namespace ts.server { } = require("child_process"); const os: { - homedir(): string + homedir?(): string; + tmpdir(): string; } = require("os"); - function getGlobalTypingsCacheLocation() { - let basePath: string; switch (process.platform) { - case "win32": - basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir(); - break; - case "linux": - basePath = os.homedir(); - break; + case "win32": { + const basePath = process.env.LOCALAPPDATA || + process.env.APPDATA || + (os.homedir && os.homedir()) || + process.env.USERPROFILE || + (process.env.HOMEDRIVE && process.env.HOMEPATH && normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) || + os.tmpdir(); + return combinePaths(normalizeSlashes(basePath), "Microsoft/TypeScript"); + } case "darwin": - basePath = combinePaths(os.homedir(), "Library/Application Support/"); - break; + case "linux": + case "android": { + const cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); + return combinePaths(cacheLocation, "typescript"); + } + default: + Debug.fail(`unsupported platform '${process.platform}'`); + return; } + } - Debug.assert(basePath !== undefined); - return combinePaths(normalizeSlashes(basePath), "Microsoft/TypeScript"); + function getNonWindowsCacheLocation(platformIsDarwin: boolean) { + if (process.env.XDG_CACHE_HOME) { + return process.env.XDG_CACHE_HOME; + } + const usersDir = platformIsDarwin ? "Users" : "home" + const homePath = (os.homedir && os.homedir()) || + process.env.HOME || + ((process.env.LOGNAME || process.env.USER) && `/${usersDir}/${process.env.LOGNAME || process.env.USER}`) || + os.tmpdir(); + const cacheFolder = platformIsDarwin + ? "Library/Caches" + : ".cache" + return combinePaths(normalizeSlashes(homePath), cacheFolder); } interface NodeChildProcess { send(message: any, sendHandle?: any): void; on(message: "message", f: (m: any) => void): void; kill(): void; + pid: number; } interface NodeSocket { @@ -53,14 +75,6 @@ namespace ts.server { historySize?: number; } - interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - interface Stats { isFile(): boolean; isDirectory(): boolean; @@ -187,30 +201,58 @@ namespace ts.server { class NodeTypingsInstaller implements ITypingsInstaller { private installer: NodeChildProcess; + private installerPidReported = false; private socket: NodeSocket; private projectService: ProjectService; + private throttledOperations: ThrottledOperations; + private eventSender: EventSender; constructor( + private readonly telemetryEnabled: boolean, private readonly logger: server.Logger, - private readonly eventPort: number, + host: ServerHost, + eventPort: number, readonly globalTypingsCacheLocation: string, private newLine: string) { + this.throttledOperations = new ThrottledOperations(host); if (eventPort) { const s = net.connect({ port: eventPort }, () => { this.socket = s; + this.reportInstallerProcessId(); }); } } + private reportInstallerProcessId() { + if (this.installerPidReported) { + return; + } + if (this.socket && this.installer) { + this.sendEvent(0, "typingsInstallerPid", { pid: this.installer.pid }); + this.installerPidReported = true; + } + } + + private sendEvent(seq: number, event: string, body: any): void { + this.socket.write(formatMessage({ seq, type: "event", event, body }, this.logger, Buffer.byteLength, this.newLine), "utf8"); + } + + setTelemetrySender(telemetrySender: EventSender) { + this.eventSender = telemetrySender; + } + attach(projectService: ProjectService) { this.projectService = projectService; if (this.logger.hasLevel(LogLevel.requestTime)) { this.logger.info("Binding..."); } - const args: string[] = ["--globalTypingsCacheLocation", this.globalTypingsCacheLocation]; + const args: string[] = [Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + if (this.telemetryEnabled) { + args.push(Arguments.EnableTelemetry); + } if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { - args.push("--logFile", combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName())), `ti-${process.pid}.log`)); + args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName())), `ti-${process.pid}.log`)); } const execArgv: string[] = []; { @@ -218,7 +260,7 @@ namespace ts.server { const match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); if (match) { // if port is specified - use port + 1 - // otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1 + // otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1 const currentPort = match[3] !== undefined ? +match[3] : match[1] === "debug" ? 5858 : 9229; @@ -230,6 +272,8 @@ namespace ts.server { this.installer = childProcess.fork(combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv }); this.installer.on("message", m => this.handleMessage(m)); + this.reportInstallerProcessId(); + process.on("exit", () => { this.installer.kill(); }); @@ -239,21 +283,70 @@ namespace ts.server { this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); } - enqueueInstallTypingsRequest(project: Project, typingOptions: TypingOptions): void { - const request = createInstallTypingsRequest(project, typingOptions); + enqueueInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void { + const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); if (this.logger.hasLevel(LogLevel.verbose)) { - this.logger.info(`Sending request: ${JSON.stringify(request)}`); + if (this.logger.hasLevel(LogLevel.verbose)) { + this.logger.info(`Scheduling throttled operation: ${JSON.stringify(request)}`); + } } - this.installer.send(request); + this.throttledOperations.schedule(project.getProjectName(), /*ms*/ 250, () => { + if (this.logger.hasLevel(LogLevel.verbose)) { + this.logger.info(`Sending request: ${JSON.stringify(request)}`); + } + this.installer.send(request); + }); } - private handleMessage(response: SetTypings | InvalidateCachedTypings) { + private handleMessage(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Received response: ${JSON.stringify(response)}`); } + + if (response.kind === EventBeginInstallTypes) { + if (!this.eventSender) { + return; + } + const body: protocol.BeginInstallTypesEventBody = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + const eventName: protocol.BeginInstallTypesEventName = "beginInstallTypes"; + this.eventSender.event(body, eventName); + + return; + } + + if (response.kind === EventEndInstallTypes) { + if (!this.eventSender) { + return; + } + if (this.telemetryEnabled) { + const body: protocol.TypingsInstalledTelemetryEventBody = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion + } + }; + const eventName: protocol.TelemetryEventName = "telemetry"; + this.eventSender.event(body, eventName); + } + + const body: protocol.EndInstallTypesEventBody = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + const eventName: protocol.EndInstallTypesEventName = "endInstallTypes"; + this.eventSender.event(body, eventName); + return; + } + this.projectService.updateTypingsForProject(response); - if (response.kind == "set" && this.socket) { - this.socket.write(formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8"); + if (response.kind == ActionSet && this.socket) { + this.sendEvent(0, "setTypings", response); } } } @@ -265,17 +358,27 @@ namespace ts.server { installerEventPort: number, canUseEvents: boolean, useSingleInferredProject: boolean, + disableAutomaticTypingAcquisition: boolean, globalTypingsCacheLocation: string, + telemetryEnabled: boolean, logger: server.Logger) { - super( - host, - cancellationToken, - useSingleInferredProject, - new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), - Buffer.byteLength, - process.hrtime, - logger, - canUseEvents); + const typingsInstaller = disableAutomaticTypingAcquisition + ? undefined + : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, host.newLine); + + super( + host, + cancellationToken, + useSingleInferredProject, + typingsInstaller || nullTypingsInstaller, + Buffer.byteLength, + process.hrtime, + logger, + canUseEvents); + + if (telemetryEnabled && typingsInstaller) { + typingsInstaller.setTelemetrySender(this); + } } exit() { @@ -502,23 +605,31 @@ namespace ts.server { let eventPort: number; { - const index = sys.args.indexOf("--eventPort"); - if (index >= 0 && index < sys.args.length - 1) { - const v = parseInt(sys.args[index + 1]); - if (!isNaN(v)) { - eventPort = v; - } + const str = findArgument("--eventPort"); + const v = str && parseInt(str); + if (!isNaN(v)) { + eventPort = v; } } - const useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; + const localeStr = findArgument("--locale"); + if (localeStr) { + validateLocaleAndSetLanguage(localeStr, sys); + } + + const useSingleInferredProject = hasArgument("--useSingleInferredProject"); + const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition"); + const telemetryEnabled = hasArgument(Arguments.EnableTelemetry); + const ioSession = new IOSession( sys, cancellationToken, eventPort, /*canUseEvents*/ eventPort === undefined, useSingleInferredProject, + disableAutomaticTypingAcquisition, getGlobalTypingsCacheLocation(), + telemetryEnabled, logger); process.on("uncaughtException", function (err: Error) { ioSession.logError(err, "unknown"); @@ -527,4 +638,4 @@ namespace ts.server { (process as any).noAsar = true; // Start listening ioSession.listen(); -} \ No newline at end of file +} diff --git a/src/server/session.ts b/src/server/session.ts index 172ae70d95a..5c382aae7d3 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// namespace ts.server { @@ -73,6 +73,10 @@ namespace ts.server { project: Project; } + export interface EventSender { + event(payload: any, eventName: string): void; + } + function allEditsBeforePos(edits: ts.TextChange[], pos: number) { for (const edit of edits) { if (textSpanEnd(edit.span) >= pos) { @@ -83,74 +87,74 @@ namespace ts.server { } export namespace CommandNames { - export const Brace = "brace"; - export const BraceFull = "brace-full"; - export const BraceCompletion = "braceCompletion"; - export const Change = "change"; - export const Close = "close"; - export const Completions = "completions"; - export const CompletionsFull = "completions-full"; - export const CompletionDetails = "completionEntryDetails"; - export const CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export const CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export const Configure = "configure"; - export const Definition = "definition"; - export const DefinitionFull = "definition-full"; - export const Exit = "exit"; - export const Format = "format"; - export const Formatonkey = "formatonkey"; - export const FormatFull = "format-full"; - export const FormatonkeyFull = "formatonkey-full"; - export const FormatRangeFull = "formatRange-full"; - export const Geterr = "geterr"; - export const GeterrForProject = "geterrForProject"; - export const Implementation = "implementation"; - export const ImplementationFull = "implementation-full"; - export const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export const NavBar = "navbar"; - export const NavBarFull = "navbar-full"; - export const NavTree = "navtree"; - export const NavTreeFull = "navtree-full"; - export const Navto = "navto"; - export const NavtoFull = "navto-full"; - export const Occurrences = "occurrences"; - export const DocumentHighlights = "documentHighlights"; - export const DocumentHighlightsFull = "documentHighlights-full"; - export const Open = "open"; - export const Quickinfo = "quickinfo"; - export const QuickinfoFull = "quickinfo-full"; - export const References = "references"; - export const ReferencesFull = "references-full"; - export const Reload = "reload"; - export const Rename = "rename"; - export const RenameInfoFull = "rename-full"; - export const RenameLocationsFull = "renameLocations-full"; - export const Saveto = "saveto"; - export const SignatureHelp = "signatureHelp"; - export const SignatureHelpFull = "signatureHelp-full"; - export const TypeDefinition = "typeDefinition"; - export const ProjectInfo = "projectInfo"; - export const ReloadProjects = "reloadProjects"; - export const Unknown = "unknown"; - export const OpenExternalProject = "openExternalProject"; - export const OpenExternalProjects = "openExternalProjects"; - export const CloseExternalProject = "closeExternalProject"; - export const SynchronizeProjectList = "synchronizeProjectList"; - export const ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - export const EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - export const Cleanup = "cleanup"; - export const OutliningSpans = "outliningSpans"; - export const TodoComments = "todoComments"; - export const Indentation = "indentation"; - export const DocCommentTemplate = "docCommentTemplate"; - export const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - export const NameOrDottedNameSpan = "nameOrDottedNameSpan"; - export const BreakpointStatement = "breakpointStatement"; - export const CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export const GetCodeFixes = "getCodeFixes"; - export const GetCodeFixesFull = "getCodeFixes-full"; - export const GetSupportedCodeFixes = "getSupportedCodeFixes"; + export const Brace: protocol.CommandTypes.Brace = "brace"; + export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full"; + export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion"; + export const Change: protocol.CommandTypes.Change = "change"; + export const Close: protocol.CommandTypes.Close = "close"; + export const Completions: protocol.CommandTypes.Completions = "completions"; + export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full"; + export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails"; + export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + export const Configure: protocol.CommandTypes.Configure = "configure"; + export const Definition: protocol.CommandTypes.Definition = "definition"; + export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full"; + export const Exit: protocol.CommandTypes.Exit = "exit"; + export const Format: protocol.CommandTypes.Format = "format"; + export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey"; + export const FormatFull: protocol.CommandTypes.FormatFull = "format-full"; + export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full"; + export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full"; + export const Geterr: protocol.CommandTypes.Geterr = "geterr"; + export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject"; + export const Implementation: protocol.CommandTypes.Implementation = "implementation"; + export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full"; + export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + export const NavBar: protocol.CommandTypes.NavBar = "navbar"; + export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full"; + export const NavTree: protocol.CommandTypes.NavTree = "navtree"; + export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full"; + export const Navto: protocol.CommandTypes.Navto = "navto"; + export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full"; + export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences"; + export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights"; + export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full"; + export const Open: protocol.CommandTypes.Open = "open"; + export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo"; + export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full"; + export const References: protocol.CommandTypes.References = "references"; + export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full"; + export const Reload: protocol.CommandTypes.Reload = "reload"; + export const Rename: protocol.CommandTypes.Rename = "rename"; + export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full"; + export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full"; + export const Saveto: protocol.CommandTypes.Saveto = "saveto"; + export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp"; + export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full"; + export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition"; + export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo"; + export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects"; + export const Unknown: protocol.CommandTypes.Unknown = "unknown"; + export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject"; + export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects"; + export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject"; + export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList"; + export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup"; + export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans"; + export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments"; + export const Indentation: protocol.CommandTypes.Indentation = "indentation"; + export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate"; + export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement"; + export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes"; + export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full"; + export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes"; } export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { @@ -165,7 +169,7 @@ namespace ts.server { return `Content-Length: ${1 + len}\r\n\r\n${json}${newLine}`; } - export class Session { + export class Session implements EventSender { private readonly gcTimer: GcTimer; protected projectService: ProjectService; private errorTimer: any; /*NodeJS.Timer | number*/ @@ -195,15 +199,23 @@ namespace ts.server { private defaultEventHandler(event: ProjectServiceEvent) { switch (event.eventName) { - case "context": + case ContextEvent: const { project, fileName } = event.data; this.projectService.logger.info(`got context event, updating diagnostics for ${fileName}`); this.updateErrorCheck([{ fileName, project }], this.changeSeq, (n) => n === this.changeSeq, 100); break; - case "configFileDiag": + case ConfigFileDiagEvent: const { triggerFile, configFileName, diagnostics } = event.data; this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + break; + case ProjectLanguageServiceStateEvent: + const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, eventName); + break; } } @@ -363,7 +375,7 @@ namespace ts.server { } } - private getEncodedSemanticClassifications(args: protocol.SemanticDiagnosticsRequestArgs) { + private getEncodedSemanticClassifications(args: protocol.EncodedSemanticClassificationsRequestArgs) { const { file, project } = this.getFileAndProject(args); return project.getLanguageService().getEncodedSemanticClassifications(file, args); } @@ -389,9 +401,9 @@ namespace ts.server { }); } - private getDiagnosticsWorker(args: protocol.FileRequestArgs, selector: (project: Project, file: string) => Diagnostic[], includeLinePosition: boolean) { + private getDiagnosticsWorker(args: protocol.FileRequestArgs, isSemantic: boolean, selector: (project: Project, file: string) => Diagnostic[], includeLinePosition: boolean) { const { project, file } = this.getFileAndProject(args); - if (shouldSkipSematicCheck(project)) { + if (isSemantic && shouldSkipSematicCheck(project)) { return []; } const scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -492,11 +504,11 @@ namespace ts.server { } private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs): protocol.Diagnostic[] | protocol.DiagnosticWithLinePosition[] { - return this.getDiagnosticsWorker(args, (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ false, (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), args.includeLinePosition); } private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs): protocol.Diagnostic[] | protocol.DiagnosticWithLinePosition[] { - return this.getDiagnosticsWorker(args, (project, file) => project.getLanguageService().getSemanticDiagnostics(file), args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, (project, file) => project.getLanguageService().getSemanticDiagnostics(file), args.includeLinePosition); } private getDocumentHighlights(args: protocol.DocumentHighlightsRequestArgs, simplifiedResult: boolean): protocol.DocumentHighlightsItem[] | DocumentHighlights[] { @@ -697,7 +709,7 @@ namespace ts.server { const displayString = ts.displayPartsToString(nameInfo.displayParts); const nameSpan = nameInfo.textSpan; const nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; - const nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + const nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); const refs = combineProjectOutput( projects, (project: Project) => { @@ -710,7 +722,7 @@ namespace ts.server { const refScriptInfo = project.getScriptInfo(ref.fileName); const start = refScriptInfo.positionToLineOffset(ref.textSpan.start); const refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - const lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + const lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, @@ -761,7 +773,7 @@ namespace ts.server { if (this.eventHander) { this.eventHander({ eventName: "configFileDiag", - data: { fileName, configFileName, diagnostics: configFileErrors || [] } + data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || [] } }); } } @@ -807,7 +819,7 @@ namespace ts.server { private getIndentation(args: protocol.IndentationRequestArgs) { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); const position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - const options = args.options || this.projectService.getFormatCodeOptions(file); + const options = args.options ? convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); const indentation = project.getLanguageService(/*ensureSynchronized*/ false).getIndentationAtPosition(file, position, options); return { position, indentation }; } @@ -874,19 +886,19 @@ namespace ts.server { private getFormattingEditsForRangeFull(args: protocol.FormatRequestArgs) { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); - const options = args.options || this.projectService.getFormatCodeOptions(file); + const options = args.options ? convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(/*ensureSynchronized*/ false).getFormattingEditsForRange(file, args.position, args.endPosition, options); } private getFormattingEditsForDocumentFull(args: protocol.FormatRequestArgs) { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); - const options = args.options || this.projectService.getFormatCodeOptions(file); + const options = args.options ? convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(/*ensureSynchronized*/ false).getFormattingEditsForDocument(file, options); } private getFormattingEditsAfterKeystrokeFull(args: protocol.FormatOnKeyRequestArgs) { const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args); - const options = args.options || this.projectService.getFormatCodeOptions(file); + const options = args.options ? convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(/*ensureSynchronized*/ false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); } @@ -967,7 +979,7 @@ namespace ts.server { result.push({ name, kind, kindModifiers, sortText, replacementSpan: convertedSpan }); } return result; - }, []).sort((a, b) => a.name.localeCompare(b.name)); + }, []).sort((a, b) => ts.compareStrings(a.name, b.name)); } else { return completions; @@ -1014,6 +1026,9 @@ namespace ts.server { if (!project) { Errors.ThrowNoProject(); } + if (!project.languageServiceEnabled) { + return false; + } const scriptInfo = project.getScriptInfo(file); return project.builder.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark)); } @@ -1076,11 +1091,12 @@ namespace ts.server { private reload(args: protocol.ReloadRequestArgs, reqSeq: number) { const file = toNormalizedPath(args.file); + const tempFileName = args.tmpfile && toNormalizedPath(args.tmpfile); const project = this.projectService.getDefaultProjectForFile(file, /*refreshInferredProjects*/ true); if (project) { this.changeSeq++; // make sure no changes happen before this one is finished - if (project.reloadScript(file)) { + if (project.reloadScript(file, tempFileName)) { this.output(undefined, CommandNames.Reload, reqSeq); } } @@ -1299,7 +1315,7 @@ namespace ts.server { } // No need to analyze lib.d.ts - let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0); + let fileNamesInProject = fileNames.filter(value => value.indexOf("lib.d.ts") < 0); // Sort the file name list to make the recently touched files come first const highPriorityFiles: NormalizedPath[] = []; @@ -1313,7 +1329,7 @@ namespace ts.server { highPriorityFiles.push(fileNameInProject); else { const info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isOpen) { + if (!info.isScriptOpen()) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else @@ -1352,14 +1368,12 @@ namespace ts.server { private handlers = createMap<(request: protocol.Request) => { response?: any, responseRequired?: boolean }>({ [CommandNames.OpenExternalProject]: (request: protocol.OpenExternalProjectRequest) => { - this.projectService.openExternalProject(request.arguments); + this.projectService.openExternalProject(request.arguments, /*suppressRefreshOfInferredProjects*/ false); // TODO: report errors return this.requiredResponse(true); }, [CommandNames.OpenExternalProjects]: (request: protocol.OpenExternalProjectsRequest) => { - for (const proj of request.arguments.projects) { - this.projectService.openExternalProject(proj); - } + this.projectService.openExternalProjects(request.arguments.projects); // TODO: report errors return this.requiredResponse(true); }, @@ -1426,24 +1440,8 @@ namespace ts.server { [CommandNames.RenameInfoFull]: (request: protocol.FileLocationRequest) => { return this.requiredResponse(this.getRenameInfo(request.arguments)); }, - [CommandNames.Open]: (request: protocol.Request) => { - const openArgs = request.arguments; - let scriptKind: ScriptKind; - switch (openArgs.scriptKindName) { - case "TS": - scriptKind = ScriptKind.TS; - break; - case "JS": - scriptKind = ScriptKind.JS; - break; - case "TSX": - scriptKind = ScriptKind.TSX; - break; - case "JSX": - scriptKind = ScriptKind.JSX; - break; - } - this.openClientFile(toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + [CommandNames.Open]: (request: protocol.OpenRequest) => { + this.openClientFile(toNormalizedPath(request.arguments.file), request.arguments.fileContent, convertScriptKindName(request.arguments.scriptKindName)); return this.notRequired(); }, [CommandNames.Quickinfo]: (request: protocol.QuickInfoRequest) => { @@ -1470,7 +1468,7 @@ namespace ts.server { [CommandNames.BraceCompletion]: (request: protocol.BraceCompletionRequest) => { return this.requiredResponse(this.isValidBraceCompletion(request.arguments)); }, - [CommandNames.DocCommentTemplate]: (request: protocol.FileLocationRequest) => { + [CommandNames.DocCommentTemplate]: (request: protocol.DocCommentTemplateRequest) => { return this.requiredResponse(this.getDocCommentTemplate(request.arguments)); }, [CommandNames.Format]: (request: protocol.FormatRequest) => { @@ -1512,10 +1510,10 @@ namespace ts.server { [CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.CompilerOptionsDiagnosticsRequest) => { return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); }, - [CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.SemanticDiagnosticsRequest) => { + [CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.EncodedSemanticClassificationsRequest) => { return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments)); }, - [CommandNames.Cleanup]: (request: protocol.Request) => { + [CommandNames.Cleanup]: () => { this.cleanup(); return this.requiredResponse(true); }, @@ -1590,12 +1588,13 @@ namespace ts.server { return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false)); }, [CommandNames.CompilerOptionsForInferredProjects]: (request: protocol.SetCompilerOptionsForInferredProjectsRequest) => { - return this.requiredResponse(this.setCompilerOptionsForInferredProjects(request.arguments)); + this.setCompilerOptionsForInferredProjects(request.arguments); + return this.requiredResponse(true); }, [CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => { return this.requiredResponse(this.getProjectInfo(request.arguments)); }, - [CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => { + [CommandNames.ReloadProjects]: () => { this.projectService.reloadProjects(); return this.notRequired(); }, @@ -1605,7 +1604,7 @@ namespace ts.server { [CommandNames.GetCodeFixesFull]: (request: protocol.CodeFixRequest) => { return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); }, - [CommandNames.GetSupportedCodeFixes]: (request: protocol.Request) => { + [CommandNames.GetSupportedCodeFixes]: () => { return this.requiredResponse(this.getSupportedCodeFixes()); } }); diff --git a/src/server/shared.ts b/src/server/shared.ts new file mode 100644 index 00000000000..c56d4098e75 --- /dev/null +++ b/src/server/shared.ts @@ -0,0 +1,25 @@ +/// + +namespace ts.server { + export const ActionSet: ActionSet = "action::set"; + export const ActionInvalidate: ActionInvalidate = "action::invalidate"; + export const EventBeginInstallTypes: EventBeginInstallTypes = "event::beginInstallTypes"; + export const EventEndInstallTypes: EventEndInstallTypes = "event::endInstallTypes"; + + export namespace Arguments { + export const GlobalCacheLocation = "--globalTypingsCacheLocation"; + export const LogFile = "--logFile"; + export const EnableTelemetry = "--enableTelemetry"; + } + + export function hasArgument(argumentName: string) { + return sys.args.indexOf(argumentName) >= 0; + } + + export function findArgument(argumentName: string) { + const index = sys.args.indexOf(argumentName); + return index >= 0 && index < sys.args.length - 1 + ? sys.args[index + 1] + : undefined; + } +} \ No newline at end of file diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 7eb8c28f383..85c88679164 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -10,11 +10,15 @@ "stripInternal": true, "types": [ "node" - ] + ], + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true }, "files": [ "../services/shims.ts", "../services/utilities.ts", + "shared.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", @@ -22,7 +26,7 @@ "typingsCache.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", + "protocol.ts", "session.ts", "server.ts" ] diff --git a/src/server/tsconfig.library.json b/src/server/tsconfig.library.json index a450b591a7e..5483cc8ec28 100644 --- a/src/server/tsconfig.library.json +++ b/src/server/tsconfig.library.json @@ -7,11 +7,15 @@ "sourceMap": true, "stripInternal": true, "declaration": true, - "types": [] + "types": [], + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true }, "files": [ "../services/shims.ts", "../services/utilities.ts", + "shared.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", diff --git a/src/server/types.d.ts b/src/server/types.d.ts index 14af59d5cd3..9f53fa8def1 100644 --- a/src/server/types.d.ts +++ b/src/server/types.d.ts @@ -18,6 +18,10 @@ declare namespace ts.server { trace?(s: string): void; } + export interface SortedReadonlyArray extends ReadonlyArray { + " __sortedReadonlyArrayBrand": any; + } + export interface TypingInstallerRequest { readonly projectName: string; readonly kind: "discover" | "closeProject"; @@ -26,8 +30,9 @@ declare namespace ts.server { export interface DiscoverTypings extends TypingInstallerRequest { readonly fileNames: string[]; readonly projectRootPath: ts.Path; - readonly typingOptions: ts.TypingOptions; readonly compilerOptions: ts.CompilerOptions; + readonly typeAcquisition: ts.TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; readonly cachePath?: string; readonly kind: "discover"; } @@ -36,25 +41,50 @@ declare namespace ts.server { readonly kind: "closeProject"; } + export type ActionSet = "action::set"; + export type ActionInvalidate = "action::invalidate"; + export type EventBeginInstallTypes = "event::beginInstallTypes"; + export type EventEndInstallTypes = "event::endInstallTypes"; + export interface TypingInstallerResponse { - readonly projectName: string; - readonly kind: "set" | "invalidate"; + readonly kind: ActionSet | ActionInvalidate | EventBeginInstallTypes | EventEndInstallTypes; } - export interface SetTypings extends TypingInstallerResponse { - readonly typingOptions: ts.TypingOptions; + export interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + + export interface SetTypings extends ProjectResponse { + readonly typeAcquisition: ts.TypeAcquisition; readonly compilerOptions: ts.CompilerOptions; readonly typings: string[]; - readonly kind: "set"; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; } - export interface InvalidateCachedTypings extends TypingInstallerResponse { - readonly kind: "invalidate"; + export interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + + export interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + + export interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + + export interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; } export interface InstallTypingHost extends JsTyping.TypingResolutionHost { writeFile(path: string, content: string): void; createDirectory(path: string): void; - watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; } } \ No newline at end of file diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index 889cfe1fb8f..8b03d59003c 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -2,23 +2,25 @@ namespace ts.server { export interface ITypingsInstaller { - enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void; + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; readonly globalTypingsCacheLocation: string; } export const nullTypingsInstaller: ITypingsInstaller = { - enqueueInstallTypingsRequest: () => {}, - attach: (projectService: ProjectService) => {}, - onProjectClosed: (p: Project) => {}, + enqueueInstallTypingsRequest: noop, + attach: noop, + onProjectClosed: noop, globalTypingsCacheLocation: undefined }; class TypingsCacheEntry { - readonly typingOptions: TypingOptions; + readonly typeAcquisition: TypeAcquisition; readonly compilerOptions: CompilerOptions; - readonly typings: TypingsArray; + readonly typings: SortedReadonlyArray; + readonly unresolvedImports: SortedReadonlyArray; + /* mainly useful for debugging */ poisoned: boolean; } @@ -50,8 +52,8 @@ namespace ts.server { return unique === 0; } - function typingOptionsChanged(opt1: TypingOptions, opt2: TypingOptions): boolean { - return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || + function typeAcquisitionChanged(opt1: TypeAcquisition, opt2: TypeAcquisition): boolean { + return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude); } @@ -61,13 +63,11 @@ namespace ts.server { return opt1.allowJs != opt2.allowJs; } - export interface TypingsArray extends ReadonlyArray { - " __typingsArrayBrand": any; - } - - function toTypingsArray(arr: string[]): TypingsArray { - arr.sort(); - return arr; + function unresolvedImportsChanged(imports1: SortedReadonlyArray, imports2: SortedReadonlyArray): boolean { + if (imports1 === imports2) { + return false; + } + return !arrayIsEqualTo(imports1, imports2); } export class TypingsCache { @@ -76,47 +76,49 @@ namespace ts.server { constructor(private readonly installer: ITypingsInstaller) { } - getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray { - const typingOptions = project.getTypingOptions(); + getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray, forceRefresh: boolean): SortedReadonlyArray { + const typeAcquisition = project.getTypeAcquisition(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { + if (!typeAcquisition || !typeAcquisition.enable) { return emptyArray; } const entry = this.perProjectCache[project.getProjectName()]; - const result: TypingsArray = entry ? entry.typings : emptyArray; - if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { + const result: SortedReadonlyArray = entry ? entry.typings : emptyArray; + if (forceRefresh || + !entry || + typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || + compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) || + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options. // instead it acts as a placeholder to prevent issuing multiple requests this.perProjectCache[project.getProjectName()] = { compilerOptions: project.getCompilerOptions(), - typingOptions, + typeAcquisition, typings: result, + unresolvedImports, poisoned: true }; // something has been changed, issue a request to update typings - this.installer.enqueueInstallTypingsRequest(project, typingOptions); + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } return result; } - invalidateCachedTypingsForProject(project: Project) { - const typingOptions = project.getTypingOptions(); - if (!typingOptions.enableAutoDiscovery) { - return; - } - this.installer.enqueueInstallTypingsRequest(project, typingOptions); - } - - updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]) { + updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]) { this.perProjectCache[projectName] = { compilerOptions, - typingOptions, - typings: toTypingsArray(newTypings), + typeAcquisition, + typings: toSortedReadonlyArray(newTypings), + unresolvedImports, poisoned: false }; } + deleteTypingsForProject(projectName: string) { + delete this.perProjectCache[projectName]; + } + onProjectClosed(project: Project) { delete this.perProjectCache[project.getProjectName()]; this.installer.onProjectClosed(project); diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index b73a8e4e79d..19f794ad57c 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -33,27 +33,74 @@ namespace ts.server.typingsInstaller { } } - export class NodeTypingsInstaller extends TypingsInstaller { - private readonly exec: { (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any }; + interface TypesRegistryFile { + entries: MapLike; + } - readonly installTypingHost: InstallTypingHost = sys; + function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypingHost, log: Log): Map { + if (!host.fileExists(typesRegistryFilePath)) { + if (log.isEnabled()) { + log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`); + } + return createMap(); + } + try { + const content = JSON.parse(host.readFile(typesRegistryFilePath)); + return createMap(content.entries); + } + catch (e) { + if (log.isEnabled()) { + log.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${(e).message}, ${(e).stack}`); + } + return createMap(); + } + } + + const TypesRegistryPackageName = "types-registry"; + function getTypesRegistryFileLocation(globalTypingsCacheLocation: string): string { + return combinePaths(normalizeSlashes(globalTypingsCacheLocation), `node_modules/${TypesRegistryPackageName}/index.json`); + } + + type ExecSync = { + (command: string, options: { cwd: string, stdio?: "ignore" }): any + } + + export class NodeTypingsInstaller extends TypingsInstaller { + private readonly execSync: ExecSync; + private readonly npmPath: string; + readonly typesRegistry: Map; constructor(globalTypingsCacheLocation: string, throttleLimit: number, log: Log) { super( + sys, globalTypingsCacheLocation, - /*npmPath*/ getNPMLocation(process.argv[0]), toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)), throttleLimit, log); if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); } - const { exec } = require("child_process"); - this.exec = exec; + this.npmPath = getNPMLocation(process.argv[0]); + ({ execSync: this.execSync } = require("child_process")); + + this.ensurePackageDirectoryExists(globalTypingsCacheLocation); + + try { + if (this.log.isEnabled()) { + this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`); + } + this.execSync(`${this.npmPath} install ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + } + catch (e) { + if (this.log.isEnabled()) { + this.log.writeLine(`Error updating ${TypesRegistryPackageName} package: ${(e).message}`); + } + } + + this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), this.installTypingHost, this.log); } - init() { - super.init(); + listen() { process.on("message", (req: DiscoverTypings | CloseProject) => { switch (req.kind) { case "discover": @@ -65,7 +112,7 @@ namespace ts.server.typingsInstaller { }); } - protected sendResponse(response: SetTypings | InvalidateCachedTypings) { + protected sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes) { if (this.log.isEnabled()) { this.log.writeLine(`Sending response: ${JSON.stringify(response)}`); } @@ -75,29 +122,33 @@ namespace ts.server.typingsInstaller { } } - protected runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void { + protected installWorker(requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { if (this.log.isEnabled()) { - this.log.writeLine(`#${requestId} running command '${command}'.`); + this.log.writeLine(`#${requestId} with arguments'${JSON.stringify(args)}'.`); } - this.exec(command, { cwd }, (err, stdout, stderr) => { - if (this.log.isEnabled()) { - this.log.writeLine(`${requestKind} #${requestId} stdout: ${stdout}`); - this.log.writeLine(`${requestKind} #${requestId} stderr: ${stderr}`); - } - onRequestCompleted(err, stdout, stderr); - }); + const command = `${this.npmPath} install ${args.join(" ")} --save-dev --user-agent="typesInstaller/${version}"`; + const start = Date.now(); + let stdout: Buffer; + let stderr: Buffer; + let hasError = false; + try { + stdout = this.execSync(command, { cwd }); + } + catch (e) { + stdout = e.stdout; + stderr = e.stderr; + hasError = true; + } + if (this.log.isEnabled()) { + this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout && stdout.toString()}${sys.newLine}stderr: ${stderr && stderr.toString()}`); + } + onRequestCompleted(!hasError); } } - function findArgument(argumentName: string) { - const index = sys.args.indexOf(argumentName); - return index >= 0 && index < sys.args.length - 1 - ? sys.args[index + 1] - : undefined; - } + const logFilePath = findArgument(server.Arguments.LogFile); + const globalTypingsCacheLocation = findArgument(server.Arguments.GlobalCacheLocation); - const logFilePath = findArgument("--logFile"); - const globalTypingsCacheLocation = findArgument("--globalTypingsCacheLocation"); const log = new FileLog(logFilePath); if (log.isEnabled()) { process.on("uncaughtException", (e: Error) => { @@ -111,5 +162,5 @@ namespace ts.server.typingsInstaller { process.exit(0); }); const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, /*throttleLimit*/5, log); - installer.init(); + installer.listen(); } \ No newline at end of file diff --git a/src/server/typingsInstaller/tsconfig.json b/src/server/typingsInstaller/tsconfig.json index fc4b896f267..c6031b19aae 100644 --- a/src/server/typingsInstaller/tsconfig.json +++ b/src/server/typingsInstaller/tsconfig.json @@ -10,10 +10,14 @@ "stripInternal": true, "types": [ "node" - ] + ], + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true }, "files": [ "../types.d.ts", + "../shared.ts", "typingsInstaller.ts", "nodeTypingsInstaller.ts" ] diff --git a/src/server/typingsInstaller/typingsInstaller.ts b/src/server/typingsInstaller/typingsInstaller.ts index 0ed2ccce99d..7a09c1f6c21 100644 --- a/src/server/typingsInstaller/typingsInstaller.ts +++ b/src/server/typingsInstaller/typingsInstaller.ts @@ -2,6 +2,7 @@ /// /// /// +/// namespace ts.server.typingsInstaller { interface NpmConfig { @@ -15,17 +16,26 @@ namespace ts.server.typingsInstaller { const nullLog: Log = { isEnabled: () => false, - writeLine: () => {} + writeLine: noop }; - function typingToFileName(cachePath: string, packageName: string, installTypingHost: InstallTypingHost): string { - const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: ModuleResolutionKind.NodeJs }, installTypingHost); - return result.resolvedModule && result.resolvedModule.resolvedFileName; + function typingToFileName(cachePath: string, packageName: string, installTypingHost: InstallTypingHost, log: Log): string { + try { + const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: ModuleResolutionKind.NodeJs }, installTypingHost); + return result.resolvedModule && result.resolvedModule.resolvedFileName; + } + catch (e) { + if (log.isEnabled()) { + log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${(e).message}`); + } + return undefined; + } } export enum PackageNameValidationResult { Ok, ScopedPackagesNotSupported, + EmptyName, NameTooLong, NameStartsWithDot, NameStartsWithUnderscore, @@ -35,10 +45,12 @@ namespace ts.server.typingsInstaller { export const MaxPackageNameLength = 214; /** - * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json */ export function validatePackageName(packageName: string): PackageNameValidationResult { - Debug.assert(!!packageName, "Package name is not specified"); + if (!packageName) { + return PackageNameValidationResult.EmptyName; + } if (packageName.length > MaxPackageNameLength) { return PackageNameValidationResult.NameTooLong; } @@ -60,18 +72,12 @@ namespace ts.server.typingsInstaller { return PackageNameValidationResult.Ok; } - export const NpmViewRequest: "npm view" = "npm view"; - export const NpmInstallRequest: "npm install" = "npm install"; - - export type RequestKind = typeof NpmViewRequest | typeof NpmInstallRequest; - - export type RequestCompletedAction = (err: Error, stdout: string, stderr: string) => void; + export type RequestCompletedAction = (success: boolean) => void; type PendingRequest = { - requestKind: RequestKind; requestId: number; - command: string; + args: string[]; cwd: string; - onRequestCompleted: RequestCompletedAction + onRequestCompleted: RequestCompletedAction; }; export abstract class TypingsInstaller { @@ -84,20 +90,17 @@ namespace ts.server.typingsInstaller { private installRunCount = 1; private inFlightRequestCount = 0; - abstract readonly installTypingHost: InstallTypingHost; + abstract readonly typesRegistry: Map; constructor( + readonly installTypingHost: InstallTypingHost, readonly globalCachePath: string, - readonly npmPath: string, readonly safeListPath: Path, readonly throttleLimit: number, protected readonly log = nullLog) { if (this.log.isEnabled()) { this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}'`); } - } - - init() { this.processCacheLocation(this.globalCachePath); } @@ -132,7 +135,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Got install request ${JSON.stringify(req)}`); } - // load existing typing information from the cache + // load existing typing information from the cache if (req.cachePath) { if (this.log.isEnabled()) { this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`); @@ -146,8 +149,8 @@ namespace ts.server.typingsInstaller { req.projectRootPath, this.safeListPath, this.packageNameToTypingLocation, - req.typingOptions, - req.compilerOptions); + req.typeAcquisition, + req.unresolvedImports); if (this.log.isEnabled()) { this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`); @@ -196,8 +199,9 @@ namespace ts.server.typingsInstaller { if (!packageName) { continue; } - const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost); + const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log); if (!typingFile) { + this.missingTypingsSet[packageName] = true; continue; } const existingTypingFile = this.packageNameToTypingLocation[packageName]; @@ -228,18 +232,28 @@ namespace ts.server.typingsInstaller { } const result: string[] = []; for (const typing of typingsToInstall) { - if (this.missingTypingsSet[typing]) { + if (this.missingTypingsSet[typing] || this.packageNameToTypingLocation[typing]) { continue; } const validationResult = validatePackageName(typing); if (validationResult === PackageNameValidationResult.Ok) { - result.push(typing); + if (typing in this.typesRegistry) { + result.push(typing); + } + else { + if (this.log.isEnabled()) { + this.log.writeLine(`Entry for package '${typing}' does not exist in local types registry - skipping...`); + } + } } else { // add typing name to missing set so we won't process it again this.missingTypingsSet[typing] = true; if (this.log.isEnabled()) { switch (validationResult) { + case PackageNameValidationResult.EmptyName: + this.log.writeLine(`Package name '${typing}' cannot be empty`); + break; case PackageNameValidationResult.NameTooLong: this.log.writeLine(`Package name '${typing}' should be less than ${MaxPackageNameLength} characters`); break; @@ -262,19 +276,8 @@ namespace ts.server.typingsInstaller { return result; } - private installTypings(req: DiscoverTypings, cachePath: string, currentlyCachedTypings: string[], typingsToInstall: string[]) { - if (this.log.isEnabled()) { - this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`); - } - typingsToInstall = this.filterTypings(typingsToInstall); - if (typingsToInstall.length === 0) { - if (this.log.isEnabled()) { - this.log.writeLine(`All typings are known to be missing or invalid - no need to go any further`); - } - return; - } - - const npmConfigPath = combinePaths(cachePath, "package.json"); + protected ensurePackageDirectoryExists(directory: string) { + const npmConfigPath = combinePaths(directory, "package.json"); if (this.log.isEnabled()) { this.log.writeLine(`Npm config file: ${npmConfigPath}`); } @@ -282,82 +285,82 @@ namespace ts.server.typingsInstaller { if (this.log.isEnabled()) { this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`); } - this.ensureDirectoryExists(cachePath, this.installTypingHost); + this.ensureDirectoryExists(directory, this.installTypingHost); this.installTypingHost.writeFile(npmConfigPath, "{}"); } - - this.runInstall(cachePath, typingsToInstall, installedTypings => { - // TODO: watch project directory - if (this.log.isEnabled()) { - this.log.writeLine(`Requested to install typings ${JSON.stringify(typingsToInstall)}, installed typings ${JSON.stringify(installedTypings)}`); - } - const installedPackages: Map = createMap(); - const installedTypingFiles: string[] = []; - for (const t of installedTypings) { - const packageName = getBaseFileName(t); - if (!packageName) { - continue; - } - installedPackages[packageName] = true; - const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost); - if (!typingFile) { - continue; - } - if (!this.packageNameToTypingLocation[packageName]) { - this.packageNameToTypingLocation[packageName] = typingFile; - } - installedTypingFiles.push(typingFile); - } - if (this.log.isEnabled()) { - this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`); - } - for (const toInstall of typingsToInstall) { - if (!installedPackages[toInstall]) { - if (this.log.isEnabled()) { - this.log.writeLine(`New missing typing package '${toInstall}'`); - } - this.missingTypingsSet[toInstall] = true; - } - } - - this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); - }); } - private runInstall(cachePath: string, typingsToInstall: string[], postInstallAction: (installedTypings: string[]) => void): void { - const requestId = this.installRunCount; - - this.installRunCount++; - let execInstallCmdCount = 0; - const filteredTypings: string[] = []; - for (const typing of typingsToInstall) { - execNpmViewTyping(this, typing); + private installTypings(req: DiscoverTypings, cachePath: string, currentlyCachedTypings: string[], typingsToInstall: string[]) { + if (this.log.isEnabled()) { + this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`); } - - function execNpmViewTyping(self: TypingsInstaller, typing: string) { - const command = `${self.npmPath} view @types/${typing} --silent name`; - self.execAsync(NpmViewRequest, requestId, command, cachePath, (err, stdout, stderr) => { - if (stdout) { - filteredTypings.push(typing); - } - execInstallCmdCount++; - if (execInstallCmdCount === typingsToInstall.length) { - installFilteredTypings(self, filteredTypings); - } - }); - } - - function installFilteredTypings(self: TypingsInstaller, filteredTypings: string[]) { - if (filteredTypings.length === 0) { - postInstallAction([]); - return; + const filteredTypings = this.filterTypings(typingsToInstall); + const scopedTypings = filteredTypings.map(x => `@types/${x}`); + if (scopedTypings.length === 0) { + if (this.log.isEnabled()) { + this.log.writeLine(`All typings are known to be missing or invalid - no need to go any further`); } - const scopedTypings = filteredTypings.map(t => "@types/" + t); - const command = `${self.npmPath} install ${scopedTypings.join(" ")} --save-dev`; - self.execAsync(NpmInstallRequest, requestId, command, cachePath, (err, stdout, stderr) => { - postInstallAction(stdout ? scopedTypings : []); - }); + return; } + + this.ensurePackageDirectoryExists(cachePath); + + const requestId = this.installRunCount; + this.installRunCount++; + + // send progress event + this.sendResponse({ + kind: EventBeginInstallTypes, + eventId: requestId, + typingsInstallerVersion: ts.version, // qualified explicitly to prevent occasional shadowing + projectName: req.projectName + }); + + this.installTypingsAsync(requestId, scopedTypings, cachePath, ok => { + try { + if (!ok) { + if (this.log.isEnabled()) { + this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`); + } + for (const typing of filteredTypings) { + this.missingTypingsSet[typing] = true; + } + return; + } + + // TODO: watch project directory + if (this.log.isEnabled()) { + this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`); + } + const installedTypingFiles: string[] = []; + for (const packageName of filteredTypings) { + const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log); + if (!typingFile) { + this.missingTypingsSet[packageName] = true; + continue; + } + if (!this.packageNameToTypingLocation[packageName]) { + this.packageNameToTypingLocation[packageName] = typingFile; + } + installedTypingFiles.push(typingFile); + } + if (this.log.isEnabled()) { + this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`); + } + + this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); + } + finally { + this.sendResponse({ + kind: EventEndInstallTypes, + eventId: requestId, + projectName: req.projectName, + packagesToInstall: scopedTypings, + installSuccess: ok, + typingsInstallerVersion: ts.version // qualified explicitly to prevent occasional shadowing + }); + } + }); } private ensureDirectoryExists(directory: string, host: InstallTypingHost): void { @@ -385,9 +388,11 @@ namespace ts.server.typingsInstaller { if (this.log.isEnabled()) { this.log.writeLine(`Got FS notification for ${f}, handler is already invoked '${isInvoked}'`); } - this.sendResponse({ projectName: projectName, kind: "invalidate" }); - isInvoked = true; - }); + if (!isInvoked) { + this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + isInvoked = true; + } + }, /*pollingInterval*/ 2000); watchers.push(w); } this.projectWatchers[projectName] = watchers; @@ -396,15 +401,16 @@ namespace ts.server.typingsInstaller { private createSetTypings(request: DiscoverTypings, typings: string[]): SetTypings { return { projectName: request.projectName, - typingOptions: request.typingOptions, + typeAcquisition: request.typeAcquisition, compilerOptions: request.compilerOptions, typings, - kind: "set" + unresolvedImports: request.unresolvedImports, + kind: ActionSet }; } - private execAsync(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void { - this.pendingRunRequests.unshift({ requestKind, requestId, command, cwd, onRequestCompleted }); + private installTypingsAsync(requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { + this.pendingRunRequests.unshift({ requestId, args, cwd, onRequestCompleted }); this.executeWithThrottling(); } @@ -412,15 +418,15 @@ namespace ts.server.typingsInstaller { while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { this.inFlightRequestCount++; const request = this.pendingRunRequests.pop(); - this.runCommand(request.requestKind, request.requestId, request.command, request.cwd, (err, stdout, stderr) => { + this.installWorker(request.requestId, request.args, request.cwd, ok => { this.inFlightRequestCount--; - request.onRequestCompleted(err, stdout, stderr); + request.onRequestCompleted(ok); this.executeWithThrottling(); }); } } - protected abstract runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void; - protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings): void; + protected abstract installWorker(requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; + protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes): void; } } \ No newline at end of file diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 5bd3423e570..d0790b93dba 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -1,4 +1,5 @@ -/// +/// +/// namespace ts.server { export enum LogLevel { @@ -45,12 +46,13 @@ namespace ts.server { } } - export function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings { + export function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(), + fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true), compilerOptions: project.getCompilerOptions(), - typingOptions, + typeAcquisition, + unresolvedImports, projectRootPath: getProjectRootPath(project), cachePath, kind: "discover" @@ -76,6 +78,7 @@ namespace ts.server { newLineCharacter: host.newLine || "\n", convertTabsToSpaces: true, indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterConstructor: false, insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, insertSpaceBeforeAndAfterBinaryOperators: true, @@ -83,8 +86,10 @@ namespace ts.server { insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, placeOpenBraceOnNewLineForFunctions: false, placeOpenBraceOnNewLineForControlBlocks: false, }; @@ -157,64 +162,6 @@ namespace ts.server { } }; } - function throwLanguageServiceIsDisabledError(): never { - throw new Error("LanguageService is disabled"); - } - - export const nullLanguageService: LanguageService = { - cleanupSemanticCache: throwLanguageServiceIsDisabledError, - getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, - getSemanticDiagnostics: throwLanguageServiceIsDisabledError, - getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, - getSyntacticClassifications: throwLanguageServiceIsDisabledError, - getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, - getSemanticClassifications: throwLanguageServiceIsDisabledError, - getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, - getCompletionsAtPosition: throwLanguageServiceIsDisabledError, - findReferences: throwLanguageServiceIsDisabledError, - getCompletionEntryDetails: throwLanguageServiceIsDisabledError, - getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, - findRenameLocations: throwLanguageServiceIsDisabledError, - getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, - getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, - getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, - getSignatureHelpItems: throwLanguageServiceIsDisabledError, - getDefinitionAtPosition: throwLanguageServiceIsDisabledError, - getRenameInfo: throwLanguageServiceIsDisabledError, - getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, - getReferencesAtPosition: throwLanguageServiceIsDisabledError, - getDocumentHighlights: throwLanguageServiceIsDisabledError, - getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, - getNavigateToItems: throwLanguageServiceIsDisabledError, - getNavigationBarItems: throwLanguageServiceIsDisabledError, - getNavigationTree: throwLanguageServiceIsDisabledError, - getOutliningSpans: throwLanguageServiceIsDisabledError, - getTodoComments: throwLanguageServiceIsDisabledError, - getIndentationAtPosition: throwLanguageServiceIsDisabledError, - getFormattingEditsForRange: throwLanguageServiceIsDisabledError, - getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, - getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, - getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, - isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, - getEmitOutput: throwLanguageServiceIsDisabledError, - getProgram: throwLanguageServiceIsDisabledError, - getNonBoundSourceFile: throwLanguageServiceIsDisabledError, - dispose: throwLanguageServiceIsDisabledError, - getCompletionEntrySymbol: throwLanguageServiceIsDisabledError, - getImplementationAtPosition: throwLanguageServiceIsDisabledError, - getSourceFile: throwLanguageServiceIsDisabledError, - getCodeFixesAtPosition: throwLanguageServiceIsDisabledError - }; - - export interface ServerLanguageServiceHost { - setCompilationSettings(options: CompilerOptions): void; - notifyFileRemoved(info: ScriptInfo): void; - } - - export const nullLanguageServiceHost: ServerLanguageServiceHost = { - setCompilationSettings: () => undefined, - notifyFileRemoved: () => undefined - }; export interface ProjectOptions { /** @@ -227,7 +174,7 @@ namespace ts.server { files?: string[]; wildcardDirectories?: Map; compilerOptions?: CompilerOptions; - typingOptions?: TypingOptions; + typeAcquisition?: TypeAcquisition; compileOnSave?: boolean; } @@ -240,6 +187,11 @@ namespace ts.server { return `/dev/null/inferredProject${counter}*`; } + export function toSortedReadonlyArray(arr: string[]): SortedReadonlyArray { + arr.sort(); + return arr; + } + export class ThrottledOperations { private pendingTimeouts: Map = createMap(); constructor(private readonly host: ServerHost) { diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index bf7fb981daa..6825ccb6371 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -264,7 +264,7 @@ namespace ts.BreakpointResolver { // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern if ((node.kind === SyntaxKind.Identifier || - node.kind == SyntaxKind.SpreadElementExpression || + node.kind == SyntaxKind.SpreadElement || node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { diff --git a/src/services/codefixes/codeFixProvider.ts b/src/services/codefixes/codeFixProvider.ts index c61cbe1b19e..e4489fc2dca 100644 --- a/src/services/codefixes/codeFixProvider.ts +++ b/src/services/codefixes/codeFixProvider.ts @@ -1,4 +1,4 @@ -/* @internal */ +/* @internal */ namespace ts { export interface CodeFix { errorCodes: number[]; @@ -11,6 +11,8 @@ namespace ts { span: TextSpan; program: Program; newLineCharacter: string; + host: LanguageServiceHost; + cancellationToken: CancellationToken; } export namespace codefix { diff --git a/src/services/codefixes/fixes.ts b/src/services/codefixes/fixes.ts index d64a99ca1b9..a38b196cb00 100644 --- a/src/services/codefixes/fixes.ts +++ b/src/services/codefixes/fixes.ts @@ -1 +1,3 @@ /// +/// +/// diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts new file mode 100644 index 00000000000..bda310f2d33 --- /dev/null +++ b/src/services/codefixes/importFixes.ts @@ -0,0 +1,591 @@ +/* @internal */ +namespace ts.codefix { + + type ImportCodeActionKind = "CodeChange" | "InsertingIntoExistingImport" | "NewImport"; + interface ImportCodeAction extends CodeAction { + kind: ImportCodeActionKind, + moduleSpecifier?: string + } + + enum ModuleSpecifierComparison { + Better, + Equal, + Worse + } + + class ImportCodeActionMap { + private symbolIdToActionMap = createMap(); + + addAction(symbolId: number, newAction: ImportCodeAction) { + if (!newAction) { + return; + } + + if (!this.symbolIdToActionMap[symbolId]) { + this.symbolIdToActionMap[symbolId] = [newAction]; + return; + } + + if (newAction.kind === "CodeChange") { + this.symbolIdToActionMap[symbolId].push(newAction); + return; + } + + const updatedNewImports: ImportCodeAction[] = []; + for (const existingAction of this.symbolIdToActionMap[symbolId]) { + if (existingAction.kind === "CodeChange") { + // only import actions should compare + updatedNewImports.push(existingAction); + continue; + } + + switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { + case ModuleSpecifierComparison.Better: + // the new one is not worth considering if it is a new improt. + // However if it is instead a insertion into existing import, the user might want to use + // the module specifier even it is worse by our standards. So keep it. + if (newAction.kind === "NewImport") { + return; + } + case ModuleSpecifierComparison.Equal: + // the current one is safe. But it is still possible that the new one is worse + // than another existing one. For example, you may have new imports from "./foo/bar" + // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new + // one and the current one are not comparable (one relative path and one absolute path), + // but the new one is worse than the other one, so should not add to the list. + updatedNewImports.push(existingAction); + break; + case ModuleSpecifierComparison.Worse: + // the existing one is worse, remove from the list. + continue; + } + } + // if we reach here, it means the new one is better or equal to all of the existing ones. + updatedNewImports.push(newAction); + this.symbolIdToActionMap[symbolId] = updatedNewImports; + } + + addActions(symbolId: number, newActions: ImportCodeAction[]) { + for (const newAction of newActions) { + this.addAction(symbolId, newAction); + } + } + + getAllActions() { + let result: ImportCodeAction[] = []; + for (const symbolId in this.symbolIdToActionMap) { + result = concatenate(result, this.symbolIdToActionMap[symbolId]); + } + return result; + } + + private compareModuleSpecifiers(moduleSpecifier1: string, moduleSpecifier2: string): ModuleSpecifierComparison { + if (moduleSpecifier1 === moduleSpecifier2) { + return ModuleSpecifierComparison.Equal; + } + + // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better + if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { + return ModuleSpecifierComparison.Better; + } + + if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { + return ModuleSpecifierComparison.Worse; + } + + // if both are relative paths, and ms1 has fewer levels, then it is better + if (isExternalModuleNameRelative(moduleSpecifier1) && isExternalModuleNameRelative(moduleSpecifier2)) { + const regex = new RegExp(directorySeparator, "g"); + const moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; + const moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; + + return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Better + : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount + ? ModuleSpecifierComparison.Equal + : ModuleSpecifierComparison.Worse; + } + + // the equal cases include when the two specifiers are not comparable. + return ModuleSpecifierComparison.Equal; + } + } + + registerCodeFix({ + errorCodes: [Diagnostics.Cannot_find_name_0.code], + getCodeActions: (context: CodeFixContext) => { + const sourceFile = context.sourceFile; + const checker = context.program.getTypeChecker(); + const allSourceFiles = context.program.getSourceFiles(); + const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; + + const token = getTokenAtPosition(sourceFile, context.span.start); + const name = token.getText(); + const symbolIdActionMap = new ImportCodeActionMap(); + + // this is a module id -> module import declaration map + const cachedImportDeclarations = createMap<(ImportDeclaration | ImportEqualsDeclaration)[]>(); + let cachedNewImportInsertPosition: number; + + const allPotentialModules = checker.getAmbientModules(); + for (const otherSourceFile of allSourceFiles) { + if (otherSourceFile !== sourceFile && isExternalOrCommonJsModule(otherSourceFile)) { + allPotentialModules.push(otherSourceFile.symbol); + } + } + + const currentTokenMeaning = getMeaningFromLocation(token); + for (const moduleSymbol of allPotentialModules) { + context.cancellationToken.throwIfCancellationRequested(); + + // check the default export + const defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + const localSymbol = getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + const symbolId = getUniqueSymbolId(localSymbol); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + } + } + + // check exports with the same name + const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + const symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + } + } + + return symbolIdActionMap.getAllActions(); + + function getImportDeclarations(moduleSymbol: Symbol) { + const moduleSymbolId = getUniqueSymbolId(moduleSymbol); + + if (cachedImportDeclarations[moduleSymbolId]) { + return cachedImportDeclarations[moduleSymbolId]; + } + + const existingDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[] = []; + for (const importModuleSpecifier of sourceFile.imports) { + const importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); + if (importSymbol === moduleSymbol) { + existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); + } + } + cachedImportDeclarations[moduleSymbolId] = existingDeclarations; + return existingDeclarations; + + function getImportDeclaration(moduleSpecifier: LiteralExpression) { + let node: Node = moduleSpecifier; + while (node) { + if (node.kind === SyntaxKind.ImportDeclaration) { + return node; + } + if (node.kind === SyntaxKind.ImportEqualsDeclaration) { + return node; + } + node = node.parent; + } + return undefined; + } + } + + function getUniqueSymbolId(symbol: Symbol) { + if (symbol.flags & SymbolFlags.Alias) { + return getSymbolId(checker.getAliasedSymbol(symbol)); + } + return getSymbolId(symbol); + } + + function checkSymbolHasMeaning(symbol: Symbol, meaning: SemanticMeaning) { + const declarations = symbol.getDeclarations(); + return declarations ? some(symbol.declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)) : false; + } + + function getCodeActionForImport(moduleSymbol: Symbol, isDefault?: boolean): ImportCodeAction[] { + const existingDeclarations = getImportDeclarations(moduleSymbol); + if (existingDeclarations.length > 0) { + // With an existing import statement, there are more than one actions the user can do. + return getCodeActionsForExistingImport(existingDeclarations); + } + else { + return [getCodeActionForNewImport()]; + } + + + + function getCodeActionsForExistingImport(declarations: (ImportDeclaration | ImportEqualsDeclaration)[]): ImportCodeAction[] { + const actions: ImportCodeAction[] = []; + + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + let namespaceImportDeclaration: ImportDeclaration | ImportEqualsDeclaration; + let namedImportDeclaration: ImportDeclaration; + let existingModuleSpecifier: string; + for (const declaration of declarations) { + if (declaration.kind === SyntaxKind.ImportDeclaration) { + const namedBindings = declaration.importClause && declaration.importClause.namedBindings; + if (namedBindings && namedBindings.kind === SyntaxKind.NamespaceImport) { + // case: + // import * as ns from "foo" + namespaceImportDeclaration = declaration; + } + else { + // cases: + // import default from "foo" + // import { bar } from "foo" or combination with the first one + // import "foo" + namedImportDeclaration = declaration; + } + existingModuleSpecifier = declaration.moduleSpecifier.getText(); + } + else { + // case: + // import foo = require("foo") + namespaceImportDeclaration = declaration; + existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + } + } + + if (namespaceImportDeclaration) { + actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); + } + + if (namedImportDeclaration && namedImportDeclaration.importClause && + (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { + /** + * If the existing import declaration already has a named import list, just + * insert the identifier into that list. + */ + const textChange = getTextChangeForImportClause(namedImportDeclaration.importClause); + const moduleSpecifierWithoutQuotes = stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); + actions.push(createCodeAction( + Diagnostics.Add_0_to_existing_import_declaration_from_1, + [name, moduleSpecifierWithoutQuotes], + textChange.newText, + textChange.span, + sourceFile.fileName, + "InsertingIntoExistingImport", + moduleSpecifierWithoutQuotes + )); + } + else { + // we need to create a new import statement, but the existing module specifier can be reused. + actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + return actions; + + function getModuleSpecifierFromImportEqualsDeclaration(declaration: ImportEqualsDeclaration) { + if (declaration.moduleReference && declaration.moduleReference.kind === SyntaxKind.ExternalModuleReference) { + return declaration.moduleReference.expression.getText(); + } + return declaration.moduleReference.getText(); + } + + function getTextChangeForImportClause(importClause: ImportClause): TextChange { + const newImportText = isDefault ? `default as ${name}` : name; + const importList = importClause.namedBindings; + // case 1: + // original text: import default from "module" + // change to: import default, { name } from "module" + if (!importList && importClause.name) { + const start = importClause.name.getEnd(); + return { + newText: `, { ${newImportText} }`, + span: { start, length: 0 } + }; + } + + // case 2: + // original text: import {} from "module" + // change to: import { name } from "module" + if (importList.elements.length === 0) { + const start = importList.getStart(); + return { + newText: `{ ${newImportText} }`, + span: { start, length: importList.getEnd() - start } + }; + } + + // case 3: + // original text: import { foo, bar } from "module" + // change to: import { foo, bar, name } from "module" + const insertPoint = importList.elements[importList.elements.length - 1].getEnd(); + /** + * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element + * import { + * foo + * } from "./module"; + */ + const startLine = getLineOfLocalPosition(sourceFile, importList.getStart()); + const endLine = getLineOfLocalPosition(sourceFile, importList.getEnd()); + const oneImportPerLine = endLine - startLine > importList.elements.length; + + return { + newText: `,${oneImportPerLine ? context.newLineCharacter : " "}${newImportText}`, + span: { start: insertPoint, length: 0 } + }; + } + + function getCodeActionForNamespaceImport(declaration: ImportDeclaration | ImportEqualsDeclaration): ImportCodeAction { + let namespacePrefix: string; + if (declaration.kind === SyntaxKind.ImportDeclaration) { + namespacePrefix = (declaration.importClause.namedBindings).name.getText(); + } + else { + namespacePrefix = declaration.name.getText(); + } + namespacePrefix = stripQuotes(namespacePrefix); + + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction( + Diagnostics.Change_0_to_1, + [name, `${namespacePrefix}.${name}`], + `${namespacePrefix}.`, + { start: token.getStart(), length: 0 }, + sourceFile.fileName, + "CodeChange" + ); + } + } + + function getCodeActionForNewImport(moduleSpecifier?: string): ImportCodeAction { + if (!cachedNewImportInsertPosition) { + // insert after any existing imports + let lastModuleSpecifierEnd = -1; + for (const moduleSpecifier of sourceFile.imports) { + const end = moduleSpecifier.getEnd(); + if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) { + lastModuleSpecifierEnd = end; + } + } + cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart(); + } + + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); + const importStatementText = isDefault + ? `import ${name} from "${moduleSpecifierWithoutQuotes}"` + : `import { ${name} } from "${moduleSpecifierWithoutQuotes}"`; + + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + const newText = cachedNewImportInsertPosition === sourceFile.getStart() + ? `${importStatementText};${context.newLineCharacter}${context.newLineCharacter}` + : `${context.newLineCharacter}${importStatementText};`; + + return createCodeAction( + Diagnostics.Import_0_from_1, + [name, `"${moduleSpecifierWithoutQuotes}"`], + newText, + { start: cachedNewImportInsertPosition, length: 0 }, + sourceFile.fileName, + "NewImport", + moduleSpecifierWithoutQuotes + ); + + function getModuleSpecifierForNewImport() { + const fileName = sourceFile.path; + const moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path; + const sourceDirectory = getDirectoryPath(fileName); + const options = context.program.getCompilerOptions(); + + return tryGetModuleNameFromAmbientModule() || + tryGetModuleNameFromBaseUrl() || + tryGetModuleNameFromRootDirs() || + tryGetModuleNameFromTypeRoots() || + tryGetModuleNameAsNodeModule() || + removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); + + function tryGetModuleNameFromAmbientModule(): string { + if (moduleSymbol.valueDeclaration.kind !== SyntaxKind.SourceFile) { + return moduleSymbol.name; + } + } + + function tryGetModuleNameFromBaseUrl() { + if (!options.baseUrl) { + return undefined; + } + + const normalizedBaseUrl = toPath(options.baseUrl, getDirectoryPath(options.baseUrl), getCanonicalFileName); + let relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl); + if (!relativeName) { + return undefined; + } + + relativeName = removeExtensionAndIndexPostFix(relativeName); + + if (options.paths) { + for (const key in options.paths) { + for (const pattern of options.paths[key]) { + const indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + const prefix = pattern.substr(0, indexOfStar); + const suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + startsWith(relativeName, prefix) && + endsWith(relativeName, suffix)) { + const matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName) { + return key; + } + } + } + } + + return relativeName; + } + + function tryGetModuleNameFromRootDirs() { + if (options.rootDirs) { + const normalizedRootDirs = map(options.rootDirs, rootDir => toPath(rootDir, /*basePath*/ undefined, getCanonicalFileName)); + const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs); + const normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs); + if (normalizedTargetPath !== undefined) { + const relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; + return removeFileExtension(relativePath); + } + } + return undefined; + } + + function tryGetModuleNameFromTypeRoots() { + const typeRoots = getEffectiveTypeRoots(options, context.host); + if (typeRoots) { + const normalizedTypeRoots = map(typeRoots, typeRoot => toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName)); + for (const typeRoot of normalizedTypeRoots) { + if (startsWith(moduleFileName, typeRoot)) { + const relativeFileName = moduleFileName.substring(typeRoot.length + 1); + return removeExtensionAndIndexPostFix(relativeFileName); + } + } + } + } + + function tryGetModuleNameAsNodeModule() { + if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + + const indexOfNodeModules = moduleFileName.indexOf("node_modules"); + if (indexOfNodeModules < 0) { + return undefined; + } + + let relativeFileName: string; + if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) { + // if node_modules folder is in this folder or any of its parent folder, no need to keep it. + relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */); + } + else { + relativeFileName = getRelativePath(moduleFileName, sourceDirectory); + } + + relativeFileName = removeFileExtension(relativeFileName); + if (endsWith(relativeFileName, "/index")) { + relativeFileName = getDirectoryPath(relativeFileName); + } + else { + try { + const moduleDirectory = getDirectoryPath(moduleFileName); + const packageJsonContent = JSON.parse(context.host.readFile(combinePaths(moduleDirectory, "package.json"))); + if (packageJsonContent) { + const mainFile = packageJsonContent.main || packageJsonContent.typings; + if (mainFile) { + const mainExportFile = toPath(mainFile, moduleDirectory, getCanonicalFileName); + if (removeFileExtension(mainExportFile) === removeFileExtension(moduleFileName)) { + relativeFileName = getDirectoryPath(relativeFileName); + } + } + } + } + catch (e) { } + } + + return relativeFileName; + } + } + + function getPathRelativeToRootDirs(path: Path, rootDirs: Path[]) { + for (const rootDir of rootDirs) { + const relativeName = tryRemoveParentDirectoryName(path, rootDir); + if (relativeName !== undefined) { + return relativeName; + } + } + return undefined; + } + + function removeExtensionAndIndexPostFix(fileName: string) { + fileName = removeFileExtension(fileName); + if (endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6/* "/index".length */); + } + return fileName; + } + + function getRelativePath(path: string, directoryPath: string) { + const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + } + + function tryRemoveParentDirectoryName(path: Path, parentDirectory: Path) { + const index = path.indexOf(parentDirectory); + if (index === 0) { + return endsWith(parentDirectory, directorySeparator) + ? path.substring(parentDirectory.length) + : path.substring(parentDirectory.length + 1); + } + return undefined; + } + } + + } + + function createCodeAction( + description: DiagnosticMessage, + diagnosticArgs: string[], + newText: string, + span: TextSpan, + fileName: string, + kind: ImportCodeActionKind, + moduleSpecifier?: string): ImportCodeAction { + return { + description: formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: [{ fileName, textChanges: [{ newText, span }] }], + kind, + moduleSpecifier + }; + } + } + }); +} diff --git a/src/services/codefixes/unusedIdentifierFixes.ts b/src/services/codefixes/unusedIdentifierFixes.ts new file mode 100644 index 00000000000..8e14bdcb73e --- /dev/null +++ b/src/services/codefixes/unusedIdentifierFixes.ts @@ -0,0 +1,167 @@ +/* @internal */ +namespace ts.codefix { + registerCodeFix({ + errorCodes: [ + Diagnostics._0_is_declared_but_never_used.code, + Diagnostics.Property_0_is_declared_but_never_used.code + ], + getCodeActions: (context: CodeFixContext) => { + const sourceFile = context.sourceFile; + const start = context.span.start; + + let token = getTokenAtPosition(sourceFile, start); + + // this handles var ["computed"] = 12; + if (token.kind === SyntaxKind.OpenBracketToken) { + token = getTokenAtPosition(sourceFile, start + 1); + } + + switch (token.kind) { + case ts.SyntaxKind.Identifier: + switch (token.parent.kind) { + case ts.SyntaxKind.VariableDeclaration: + switch (token.parent.parent.parent.kind) { + case SyntaxKind.ForStatement: + const forStatement = token.parent.parent.parent; + const forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos); + } + else { + return removeSingleItem(forInitializer.declarations, token); + } + + case SyntaxKind.ForOfStatement: + const forOfStatement = token.parent.parent.parent; + if (forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { + const forOfInitializer = forOfStatement.initializer; + return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos); + } + break; + + case SyntaxKind.ForInStatement: + // There is no valid fix in the case of: + // for .. in + return undefined; + + case SyntaxKind.CatchClause: + const catchClause = token.parent.parent; + const parameter = catchClause.variableDeclaration.getChildren()[0]; + return createCodeFix("", parameter.pos, parameter.end - parameter.pos); + + default: + const variableStatement = token.parent.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos); + } + else { + const declarations = variableStatement.declarationList.declarations; + return removeSingleItem(declarations, token); + } + } + + case SyntaxKind.TypeParameter: + const typeParameters = (token.parent.parent).typeParameters; + if (typeParameters.length === 1) { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2); + } + else { + return removeSingleItem(typeParameters, token); + } + + case ts.SyntaxKind.Parameter: + const functionDeclaration = token.parent.parent; + if (functionDeclaration.parameters.length === 1) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else { + return removeSingleItem(functionDeclaration.parameters, token); + } + + // handle case where 'import a = A;' + case SyntaxKind.ImportEqualsDeclaration: + const importEquals = findImportDeclaration(token); + return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos); + + case SyntaxKind.ImportSpecifier: + const namedImports = token.parent.parent; + if (namedImports.elements.length === 1) { + // Only 1 import and it is unused. So the entire declaration should be removed. + const importSpec = findImportDeclaration(token); + return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos); + } + else { + return removeSingleItem(namedImports.elements, token); + } + + // handle case where "import d, * as ns from './file'" + // or "'import {a, b as ns} from './file'" + case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *' + const importClause = token.parent; + if (!importClause.namedBindings) { // |import d from './file'| or |import * as ns from './file'| + const importDecl = findImportDeclaration(importClause); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { // import |d,| * as ns from './file' + return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos); + } + + case SyntaxKind.NamespaceImport: + const namespaceImport = token.parent; + if (namespaceImport.name == token && !(namespaceImport.parent).name) { + const importDecl = findImportDeclaration(namespaceImport); + return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos); + } + else { + const start = (namespaceImport.parent).name.end; + return createCodeFix("", start, (namespaceImport.parent).namedBindings.end - start); + } + } + break; + + case SyntaxKind.PropertyDeclaration: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + + case SyntaxKind.NamespaceImport: + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + if (isDeclarationName(token)) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos); + } + else if (isLiteralComputedPropertyDeclarationName(token)) { + return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos); + } + else { + return undefined; + } + + function findImportDeclaration(token: Node): Node { + let importDecl = token; + while (importDecl.kind != SyntaxKind.ImportDeclaration && importDecl.parent) { + importDecl = importDecl.parent; + } + + return importDecl; + } + + function createCodeFix(newText: string, start: number, length: number): CodeAction[] { + return [{ + description: getLocaleSpecificMessage(Diagnostics.Remove_unused_identifiers), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ newText, span: { start, length } }] + }] + }]; + } + + function removeSingleItem(elements: NodeArray, token: T): CodeAction[] { + if (elements[0] === token.parent) { + return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1); + } + else { + return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1); + } + } + } + }); +} \ No newline at end of file diff --git a/src/services/completions.ts b/src/services/completions.ts index c8d7c019e54..b710aa8cd78 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1,3 +1,5 @@ +/// + /* @internal */ namespace ts.Completions { export function getCompletionsAtPosition(host: LanguageServiceHost, typeChecker: TypeChecker, log: (message: string) => void, compilerOptions: CompilerOptions, sourceFile: SourceFile, position: number): CompletionInfo { @@ -177,7 +179,7 @@ namespace ts.Completions { // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); } // Get completion for string literal from string literal type @@ -197,7 +199,7 @@ namespace ts.Completions { } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo, location: Node) { + function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo) { const candidates: Signature[] = []; const entries: CompletionEntry[] = []; @@ -359,7 +361,7 @@ namespace ts.Completions { /** * Multiple file entries might map to the same truncated name once we remove extensions * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * + * * both foo.ts and foo.tsx become foo */ const foundFiles = createMap(); @@ -615,7 +617,7 @@ namespace ts.Completions { if (typeRoots) { for (const root of typeRoots) { - getCompletionEntriesFromDirectories(host, options, root, span, result); + getCompletionEntriesFromDirectories(host, root, span, result); } } } @@ -624,14 +626,14 @@ namespace ts.Completions { // Also get all @types typings installed in visible node_modules directories for (const packageJson of findPackageJsons(scriptPath)) { const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); + getCompletionEntriesFromDirectories(host, typesDir, span, result); } } return result; } - function getCompletionEntriesFromDirectories(host: LanguageServiceHost, options: CompilerOptions, directory: string, span: TextSpan, result: CompletionEntry[]) { + function getCompletionEntriesFromDirectories(host: LanguageServiceHost, directory: string, span: TextSpan, result: CompletionEntry[]) { if (host.getDirectories && tryDirectoryExists(host, directory)) { const directories = tryGetDirectories(host, directory); if (directories) { @@ -951,7 +953,6 @@ namespace ts.Completions { if (!tryGetGlobalSymbols()) { return undefined; } - isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); @@ -1030,7 +1031,6 @@ namespace ts.Completions { if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); - isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (jsxContainer).attributes); @@ -1038,7 +1038,6 @@ namespace ts.Completions { isNewIdentifierLocation = false; return true; } - } } @@ -1079,6 +1078,13 @@ namespace ts.Completions { position; const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + if (scopeNode) { + isGlobalCompletion = + scopeNode.kind === SyntaxKind.SourceFile || + scopeNode.kind === SyntaxKind.TemplateExpression || + scopeNode.kind === SyntaxKind.JsxExpression || + isStatement(scopeNode); + } /// TODO filter meaning based on the current context const symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias; @@ -1584,7 +1590,9 @@ namespace ts.Completions { if (m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment && m.kind !== SyntaxKind.BindingElement && - m.kind !== SyntaxKind.MethodDeclaration) { + m.kind !== SyntaxKind.MethodDeclaration && + m.kind !== SyntaxKind.GetAccessor && + m.kind !== SyntaxKind.SetAccessor) { continue; } @@ -1702,11 +1710,11 @@ namespace ts.Completions { * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. * For example, this matches - * + * * /// node.name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (isStringOrNumericLiteral(nameExpression.kind)) { + if (isStringOrNumericLiteral(nameExpression)) { return (nameExpression).text; } return undefined; diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 16108450d2c..637bb41bad9 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -248,7 +248,7 @@ namespace ts.formatting { } }; - function rangeHasNoErrors(r: TextRange): boolean { + function rangeHasNoErrors(): boolean { return false; } } @@ -488,18 +488,32 @@ namespace ts.formatting { // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent case SyntaxKind.OpenBraceToken: case SyntaxKind.CloseBraceToken: - case SyntaxKind.OpenBracketToken: - case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.AtToken: return indentation; - default: - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + case SyntaxKind.SlashToken: + case SyntaxKind.GreaterThanToken: { + if (container.kind === SyntaxKind.JsxOpeningElement || + container.kind === SyntaxKind.JsxClosingElement || + container.kind === SyntaxKind.JsxSelfClosingElement + ) { + return indentation; + } + break; + } + case SyntaxKind.OpenBracketToken: + case SyntaxKind.CloseBracketToken: { + if (container.kind !== SyntaxKind.MappedType) { + return indentation; + } + break; + } } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; }, getIndentation: () => indentation, getDelta: child => getEffectiveDelta(delta, child), @@ -566,7 +580,7 @@ namespace ts.formatting { if (tokenInfo.token.end > node.end) { break; } - consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode( @@ -617,17 +631,18 @@ namespace ts.formatting { break; } - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); } if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (isToken(child)) { + // JSX text shouldn't affect indenting + if (isToken(child) && child.kind !== SyntaxKind.JsxText) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules const tokenInfo = formattingScanner.readTokenInfo(child); - Debug.assert(tokenInfo.token.end === child.end); + Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } @@ -672,11 +687,11 @@ namespace ts.formatting { computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation.indentation, indentation.delta); - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { // consume any tokens that precede the list as child elements of 'node' using its indentation scope - consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); } } } @@ -696,13 +711,13 @@ namespace ts.formatting { // without this check close paren will be interpreted as list end token for function expression which is wrong if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container?: Node): void { + function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container: Node): void { Debug.assert(rangeContainsRange(parent, currentTokenInfo.token)); const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); @@ -885,12 +900,25 @@ namespace ts.formatting { else { const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile); - if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { + if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } } } + function characterToColumn(startLinePosition: number, characterInLine: number): number { + let column = 0; + for (let i = 0; i < characterInLine; i++) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === CharacterCodes.tab) { + column += options.tabSize - column % options.tabSize; + } + else { + column++; + } + } + return column; + } + function indentationIsDifferent(indentationString: string, startLinePosition: number): boolean { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index 7822e4a72fc..2020352f86b 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -31,7 +31,7 @@ namespace ts.formatting { } export function getFormattingScanner(sourceFile: SourceFile, startPos: number, endPos: number): FormattingScanner { - Debug.assert(scanner === undefined); + Debug.assert(scanner === undefined, "Scanner should be undefined"); scanner = sourceFile.languageVariant === LanguageVariant.JSX ? jsxScanner : standardScanner; scanner.setText(sourceFile.text); @@ -62,7 +62,7 @@ namespace ts.formatting { }; function advance(): void { - Debug.assert(scanner !== undefined); + Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; const isStarted = scanner.getStartPos() !== startPos; diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 2095f062bd1..5b1543b79f0 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -87,6 +87,7 @@ namespace ts.formatting { public SpaceAfterLetConstInVariableDeclaration: Rule; public NoSpaceBeforeOpenParenInFuncCall: Rule; public SpaceAfterFunctionInFuncDecl: Rule; + public SpaceBeforeOpenParenInFuncDecl: Rule; public NoSpaceBeforeOpenParenInFuncDecl: Rule; public SpaceAfterVoidOperator: Rule; @@ -112,6 +113,7 @@ namespace ts.formatting { // TypeScript-specific rules // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + public SpaceAfterConstructor: Rule; public NoSpaceAfterConstructor: Rule; // Use of module as a function call. e.g.: import m2 = module("m2"); @@ -262,12 +264,12 @@ namespace ts.formatting { this.SpaceAfterSemicolon = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); // Space after }. - this.SpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), RuleAction.Space)); + this.SpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromRange(SyntaxKind.FirstToken, SyntaxKind.LastToken, [SyntaxKind.CloseParenToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), RuleAction.Space)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied this.SpaceBetweenCloseBraceAndElse = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.ElseKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); this.SpaceBetweenCloseBraceAndWhile = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.WhileKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); - this.NoSpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); + this.NoSpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); // No space for dot this.NoSpaceBeforeDot = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.DotToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); @@ -290,10 +292,10 @@ namespace ts.formatting { this.SpaceBeforeOpenBraceInControl = new Rule(RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), RuleAction.Space), RuleFlags.CanDeleteNewLines); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - this.SpaceAfterOpenBrace = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Space)); - this.SpaceBeforeCloseBrace = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Space)); - this.NoSpaceAfterOpenBrace = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Delete)); - this.NoSpaceBeforeCloseBrace = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Delete)); + this.SpaceAfterOpenBrace = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsBraceWrappedContext), RuleAction.Space)); + this.SpaceBeforeCloseBrace = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsBraceWrappedContext), RuleAction.Space)); + this.NoSpaceAfterOpenBrace = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsBraceWrappedContext), RuleAction.Delete)); + this.NoSpaceBeforeCloseBrace = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsBraceWrappedContext), RuleAction.Delete)); this.NoSpaceBetweenEmptyBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), RuleAction.Delete)); // Insert new line after { and before } in multi-line contexts. @@ -329,6 +331,7 @@ namespace ts.formatting { this.SpaceAfterLetConstInVariableDeclaration = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.LetKeyword, SyntaxKind.ConstKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), RuleAction.Space)); this.NoSpaceBeforeOpenParenInFuncCall = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), RuleAction.Delete)); this.SpaceAfterFunctionInFuncDecl = new Rule(RuleDescriptor.create3(SyntaxKind.FunctionKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space)); + this.SpaceBeforeOpenParenInFuncDecl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), RuleAction.Space)); this.NoSpaceBeforeOpenParenInFuncDecl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), RuleAction.Delete)); this.SpaceAfterVoidOperator = new Rule(RuleDescriptor.create3(SyntaxKind.VoidKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), RuleAction.Space)); @@ -352,13 +355,14 @@ namespace ts.formatting { // TypeScript-specific higher priority rules // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + this.SpaceAfterConstructor = new Rule(RuleDescriptor.create1(SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); this.NoSpaceAfterConstructor = new Rule(RuleDescriptor.create1(SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); // Use of module as a function call. e.g.: import m2 = module("m2"); this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword, SyntaxKind.TypeKeyword, SyntaxKind.FromKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); + this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadonlyKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword, SyntaxKind.TypeKeyword, SyntaxKind.FromKeyword, SyntaxKind.KeyOfKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.FromKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { @@ -437,7 +441,7 @@ namespace ts.formatting { this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, // TypeScript-specific rules - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, this.SpaceBeforeArrow, this.SpaceAfterArrow, @@ -462,7 +466,6 @@ namespace ts.formatting { this.NoSpaceBeforeOpenBracket, this.NoSpaceAfterCloseBracket, this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; @@ -575,6 +578,8 @@ namespace ts.formatting { return context.currentTokenSpan.kind === SyntaxKind.EqualsToken || context.nextTokenSpan.kind === SyntaxKind.EqualsToken; // "in" keyword in for (let x in []) { } case SyntaxKind.ForInStatement: + // "in" keyword in [P in keyof T]: T[P] + case SyntaxKind.TypeParameter: return context.currentTokenSpan.kind === SyntaxKind.InKeyword || context.nextTokenSpan.kind === SyntaxKind.InKeyword; // Technically, "of" is not a binary operator, but format it the same way as "in" case SyntaxKind.ForOfStatement: @@ -612,6 +617,10 @@ namespace ts.formatting { return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); } + static IsBraceWrappedContext(context: FormattingContext): boolean { + return context.contextNode.kind === SyntaxKind.ObjectBindingPattern || Rules.IsSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration static IsBeforeMultilineBlockContext(context: FormattingContext): boolean { return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); @@ -705,11 +714,18 @@ namespace ts.formatting { case SyntaxKind.ClassDeclaration: case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: - case SyntaxKind.Block: case SyntaxKind.CatchClause: case SyntaxKind.ModuleBlock: case SyntaxKind.SwitchStatement: return true; + case SyntaxKind.Block: { + const blockParent = context.currentTokenParent.parent; + if (blockParent.kind !== SyntaxKind.ArrowFunction && + blockParent.kind !== SyntaxKind.FunctionExpression + ) { + return true; + } + } } return false; } @@ -829,6 +845,7 @@ namespace ts.formatting { switch (parent.kind) { case SyntaxKind.TypeReference: case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index 65c30908863..cd6f2e539d6 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -35,8 +35,8 @@ namespace ts.formatting { } private GetRuleBucketIndex(row: number, column: number): number { + Debug.assert(row <= SyntaxKind.LastKeyword && column <= SyntaxKind.LastKeyword, "Must compute formatting context from tokens"); const rulesBucketIndex = (row * this.mapRowLength) + column; - // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; } diff --git a/src/services/formatting/rulesProvider.ts b/src/services/formatting/rulesProvider.ts index 4a2c9d0f155..14e08e4857a 100644 --- a/src/services/formatting/rulesProvider.ts +++ b/src/services/formatting/rulesProvider.ts @@ -38,6 +38,13 @@ namespace ts.formatting { private createActiveRules(options: ts.FormatCodeSettings): Rule[] { let rules = this.globalRules.HighPriorityCommonRules.slice(0); + if (options.insertSpaceAfterConstructor) { + rules.push(this.globalRules.SpaceAfterConstructor); + } + else { + rules.push(this.globalRules.NoSpaceAfterConstructor); + } + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } @@ -128,6 +135,13 @@ namespace ts.formatting { rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } + if (options.insertSpaceBeforeFunctionParenthesis) { + rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl); + } + else { + rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl); + } + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 84f83a9c7db..eb9e1ba04c5 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -438,6 +438,7 @@ namespace ts.formatting { case SyntaxKind.ModuleBlock: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.TypeLiteral: + case SyntaxKind.MappedType: case SyntaxKind.TupleType: case SyntaxKind.CaseBlock: case SyntaxKind.DefaultClause: diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 0e4ec4d221c..05d7369e77f 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -67,7 +67,7 @@ namespace ts.formatting { return result; } - public Contains(tokenValue: SyntaxKind): boolean { + public Contains(): boolean { return true; } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index feca406359c..0e65d3b264e 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -1,4 +1,4 @@ -/* @internal */ +/* @internal */ namespace ts.JsDoc { const jsDocTagNames = [ "augments", @@ -23,6 +23,7 @@ namespace ts.JsDoc { "lends", "link", "memberOf", + "method", "name", "namespace", "param", @@ -43,7 +44,7 @@ namespace ts.JsDoc { ]; let jsDocCompletionEntries: CompletionEntry[]; - export function getJsDocCommentsFromDeclarations(declarations: Declaration[], name: string, canUseParsedParamTagComments: boolean) { + export function getJsDocCommentsFromDeclarations(declarations: Declaration[]) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -52,7 +53,7 @@ namespace ts.JsDoc { // from Array - Array and Array const documentationComment = []; forEachUnique(declarations, declaration => { - const comments = getJSDocComments(declaration, /*checkParentVariableStatement*/ true); + const comments = getCommentsFromJSDoc(declaration); if (!comments) { return; } @@ -166,6 +167,7 @@ namespace ts.JsDoc { const lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; const indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + const isJavaScriptFile = hasJavaScriptFileExtension(sourceFile.fileName); let docParams = ""; for (let i = 0, numParams = parameters.length; i < numParams; i++) { @@ -173,8 +175,12 @@ namespace ts.JsDoc { const paramName = currentName.kind === SyntaxKind.Identifier ? (currentName).text : "param" + i; - - docParams += `${indentationStr} * @param ${paramName}${newLine}`; + if (isJavaScriptFile) { + docParams += `${indentationStr} * @param {any} ${paramName}${newLine}`; + } + else { + docParams += `${indentationStr} * @param ${paramName}${newLine}`; + } } // A doc comment consists of the following diff --git a/src/services/jsTyping.ts b/src/services/jsTyping.ts index d50e26c6194..04ac60c4e74 100644 --- a/src/services/jsTyping.ts +++ b/src/services/jsTyping.ts @@ -31,13 +31,24 @@ namespace ts.JsTyping { const EmptySafeList: Map = createMap(); + /* @internal */ + export const nodeCoreModuleList: ReadonlyArray = [ + "buffer", "querystring", "events", "http", "cluster", + "zlib", "os", "https", "punycode", "repl", "readline", + "vm", "child_process", "url", "dns", "net", + "dgram", "fs", "path", "string_decoder", "tls", + "crypto", "stream", "util", "assert", "tty", "domain", + "constants", "process", "v8", "timers", "console"]; + + const nodeCoreModules = arrayToMap(nodeCoreModuleList, x => x); + /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project * @param projectRootPath is the path to the project root directory * @param safeListPath is the path used to retrieve the safe list * @param packageNameToTypingLocation is the map of package names to their cached typing locations - * @param typingOptions are used to customize the typing inference process + * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ export function discoverTypings( @@ -46,14 +57,14 @@ namespace ts.JsTyping { projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, - typingOptions: TypingOptions, - compilerOptions: CompilerOptions): + typeAcquisition: TypeAcquisition, + unresolvedImports: ReadonlyArray): { cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } { // A typing name to typing file path mapping const inferredTypings = createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { + if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -73,11 +84,11 @@ namespace ts.JsTyping { let searchDirs: string[] = []; let exclude: string[] = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; + mergeTypings(typeAcquisition.include); + exclude = typeAcquisition.exclude || []; const possibleSearchDirs = map(fileNames, getDirectoryPath); - if (projectRootPath !== undefined) { + if (projectRootPath) { possibleSearchDirs.push(projectRootPath); } searchDirs = deduplicate(possibleSearchDirs); @@ -93,6 +104,15 @@ namespace ts.JsTyping { } getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + for (const moduleId of unresolvedImports) { + const typingName = moduleId in nodeCoreModules ? "node" : moduleId; + if (!(typingName in inferredTypings)) { + inferredTypings[typingName] = undefined; + } + } + } // Add the cached typing locations for inferred typings that are already installed for (const name in packageNameToTypingLocation) { if (name in inferredTypings && !inferredTypings[name]) { @@ -136,10 +156,12 @@ namespace ts.JsTyping { * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath: string, filesToWatch: string[]) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } const result = readConfigFile(jsonPath, (path: string) => host.readFile(path)); if (result.config) { const jsonConfig: PackageJson = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(getOwnKeys(jsonConfig.dependencies)); } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 44aa25f5005..82f4dd49f2b 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -6,9 +6,6 @@ namespace ts.NavigateTo { const patternMatcher = createPatternMatcher(searchValue); let rawItems: RawNavigateToItem[] = []; - // This means "compare in a case insensitive manner." - const baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" }; - // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] forEach(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); @@ -188,8 +185,8 @@ namespace ts.NavigateTo { // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 18881ae7660..1cbaa3d640f 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -225,8 +225,8 @@ namespace ts.NavigationBar { break; default: - forEach(node.jsDocComments, jsDocComment => { - forEach(jsDocComment.tags, tag => { + forEach(node.jsDoc, jsDoc => { + forEach(jsDoc.tags, tag => { if (tag.kind === SyntaxKind.JSDocTypedefTag) { addLeafNode(tag); } @@ -330,10 +330,8 @@ namespace ts.NavigationBar { } } - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + const localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) { // This isn't perfect, but it passes all of our tests. for (let i = 0; i < Math.min(a.length, b.length); i++) { @@ -344,7 +342,7 @@ namespace ts.NavigationBar { if (chA === "'" && chB === "\"") { return -1; } - const cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + const cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -405,6 +403,9 @@ namespace ts.NavigationBar { if (getModifierFlags(node) & ModifierFlags.Default) { return "default"; } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. return getFunctionOrClassName(node); case SyntaxKind.Constructor: return "constructor"; @@ -604,7 +605,7 @@ namespace ts.NavigationBar { // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. else if (node.parent.kind === SyntaxKind.BinaryExpression && (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - return nodeText((node.parent as BinaryExpression).left); + return nodeText((node.parent as BinaryExpression).left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name else if (node.parent.kind === SyntaxKind.PropertyAssignment && (node.parent as PropertyAssignment).name) { @@ -622,4 +623,19 @@ namespace ts.NavigationBar { function isFunctionOrClassExpression(node: Node): boolean { return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction || node.kind === SyntaxKind.ClassExpression; } + + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ + const whiteSpaceRegex = /\s+/g; } diff --git a/src/services/services.ts b/src/services/services.ts index 666644aca1b..cf6df71d45b 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1,4 +1,4 @@ -/// +/// /// /// @@ -45,10 +45,9 @@ namespace ts { public end: number; public flags: NodeFlags; public parent: Node; - public jsDocComments: JSDoc[]; + public jsDoc: JSDoc[]; public original: Node; public transformFlags: TransformFlags; - public excludeTransformFlags: TransformFlags; private _children: Node[]; constructor(kind: SyntaxKind, pos: number, end: number) { @@ -56,7 +55,6 @@ namespace ts { this.end = end; this.flags = NodeFlags.None; this.transformFlags = undefined; - this.excludeTransformFlags = undefined; this.parent = undefined; this.kind = kind; } @@ -156,8 +154,8 @@ namespace ts { pos = nodes.end; }; // jsDocComments need to be the first children - if (this.jsDocComments) { - for (const jsDocComment of this.jsDocComments) { + if (this.jsDoc) { + for (const jsDocComment of this.jsDoc) { processNode(jsDocComment); } } @@ -264,23 +262,23 @@ namespace ts { return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); } - public getChildCount(sourceFile?: SourceFile): number { + public getChildCount(): number { return 0; } - public getChildAt(index: number, sourceFile?: SourceFile): Node { + public getChildAt(): Node { return undefined; } - public getChildren(sourceFile?: SourceFile): Node[] { + public getChildren(): Node[] { return emptyArray; } - public getFirstToken(sourceFile?: SourceFile): Node { + public getFirstToken(): Node { return undefined; } - public getLastToken(sourceFile?: SourceFile): Node { + public getLastToken(): Node { return undefined; } } @@ -313,7 +311,7 @@ namespace ts { getDocumentationComment(): SymbolDisplayPart[] { if (this.documentationComment === undefined) { - this.documentationComment = JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & SymbolFlags.Property)); + this.documentationComment = JsDoc.getJsDocCommentsFromDeclarations(this.declarations); } return this.documentationComment; @@ -338,7 +336,7 @@ namespace ts { _incrementExpressionBrand: any; _unaryExpressionBrand: any; _expressionBrand: any; - constructor(kind: SyntaxKind.Identifier, pos: number, end: number) { + constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } } @@ -347,6 +345,7 @@ namespace ts { class TypeObject implements Type { checker: TypeChecker; flags: TypeFlags; + objectFlags?: ObjectFlags; id: number; symbol: Symbol; constructor(checker: TypeChecker, flags: TypeFlags) { @@ -381,7 +380,7 @@ namespace ts { return this.checker.getIndexTypeOfType(this, IndexKind.Number); } getBaseTypes(): ObjectType[] { - return this.flags & (TypeFlags.Class | TypeFlags.Interface) + return this.flags & TypeFlags.Object && this.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface) ? this.checker.getBaseTypes(this) : undefined; } @@ -423,10 +422,7 @@ namespace ts { getDocumentationComment(): SymbolDisplayPart[] { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? JsDoc.getJsDocCommentsFromDeclarations( - [this.declaration], - /*name*/ undefined, - /*canUseParsedParamTagComments*/ false) : []; + this.documentationComment = this.declaration ? JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; } return this.documentationComment; @@ -469,11 +465,12 @@ namespace ts { public languageVariant: LanguageVariant; public identifiers: Map; public nameTable: Map; - public resolvedModules: Map; + public resolvedModules: Map; public resolvedTypeReferenceDirectiveNames: Map; public imports: LiteralExpression[]; public moduleAugmentations: LiteralExpression[]; private namedDeclarations: Map; + public ambientModuleNames: string[]; constructor(kind: SyntaxKind, pos: number, end: number) { super(kind, pos, end); @@ -495,6 +492,23 @@ namespace ts { return ts.getPositionOfLineAndCharacter(this, line, character); } + public getLineEndOfPosition(pos: number): number { + const { line } = this.getLineAndCharacterOfPosition(pos); + const lineStarts = this.getLineStarts(); + + let lastCharPos: number; + if (line + 1 >= lineStarts.length) { + lastCharPos = this.getEnd(); + } + if (!lastCharPos) { + lastCharPos = lineStarts[line + 1] - 1; + } + + const fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position + return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; + } + public getNamedDeclarations(): Map { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); @@ -578,9 +592,8 @@ namespace ts { else { declarations.push(functionDeclaration); } - - forEachChild(node, visit); } + forEachChild(node, visit); break; case SyntaxKind.ClassDeclaration: @@ -802,7 +815,7 @@ namespace ts { public getRootFileNames(): string[] { const fileNames: string[] = []; - this.fileNameToEntry.forEachValue((path, value) => { + this.fileNameToEntry.forEachValue((_path, value) => { if (value) { fileNames.push(value.hostFileName); } @@ -1054,7 +1067,7 @@ namespace ts { useCaseSensitiveFileNames: () => useCaseSensitivefileNames, getNewLine: () => getNewLineOrDefaultFromHost(host), getDefaultLibFileName: (options) => host.getDefaultLibFileName(options), - writeFile: (fileName, data, writeByteOrderMark) => { }, + writeFile: noop, getCurrentDirectory: () => currentDirectory, fileExists: (fileName): boolean => { // stub missing host functionality @@ -1208,7 +1221,7 @@ namespace ts { } function cleanupSemanticCache(): void { - // TODO: Should we jettison the program (or it's type checker) here? + program = undefined; } function dispose(): void { @@ -1458,7 +1471,7 @@ namespace ts { return getNonBoundSourceFile(fileName); } - function getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan { + function getNameOrDottedNameSpan(fileName: string, startPos: number, _endPos: number): TextSpan { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location @@ -1679,7 +1692,9 @@ namespace ts { sourceFile: sourceFile, span: span, program: program, - newLineCharacter: newLineChar + newLineCharacter: newLineChar, + host: host, + cancellationToken: cancellationToken }; const fixes = codefix.getFixes(context); @@ -1709,7 +1724,7 @@ namespace ts { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion - if (isInString(sourceFile, position) || isInComment(sourceFile, position)) { + if (isInString(sourceFile, position)) { return false; } @@ -1959,9 +1974,9 @@ namespace ts { break; default: forEachChild(node, walk); - if (node.jsDocComments) { - for (const jsDocComment of node.jsDocComments) { - forEachChild(jsDocComment, walk); + if (node.jsDoc) { + for (const jsDoc of node.jsDoc) { + forEachChild(jsDoc, walk); } } } diff --git a/src/services/shims.ts b/src/services/shims.ts index 7ed1786640d..6184f1e2ff3 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -119,13 +119,13 @@ namespace ts { } export interface Shim { - dispose(dummy: any): void; + dispose(_dummy: any): void; } export interface LanguageServiceShim extends Shim { languageService: LanguageService; - dispose(dummy: any): void; + dispose(_dummy: any): void; refresh(throwOnError: boolean): void; @@ -316,7 +316,7 @@ namespace ts { private loggingEnabled = false; private tracingEnabled = false; - public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[]; + public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[]; public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; public directoryExists: (directoryName: string) => boolean; @@ -328,7 +328,7 @@ namespace ts { const resolutionsInFile = >JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); return map(moduleNames, name => { const result = getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result } : undefined; + return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -444,7 +444,7 @@ namespace ts { } public readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[], depth?: number): string[] { - const pattern = getFileMatcherPatterns(path, extensions, exclude, include, + const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory( path, @@ -509,7 +509,7 @@ namespace ts { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. try { - const pattern = getFileMatcherPatterns(rootDir, extensions, exclude, include, + const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory( rootDir, @@ -600,7 +600,7 @@ namespace ts { constructor(private factory: ShimFactory) { factory.registerShim(this); } - public dispose(dummy: any): void { + public dispose(_dummy: any): void { this.factory.unregisterShim(this); } } @@ -1060,8 +1060,15 @@ namespace ts { return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { const compilerOptions = JSON.parse(compilerOptionsJson); const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); + const resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (resolvedFileName && !compilerOptions.allowJs && fileExtensionIs(resolvedFileName, ".js")) { + return { + resolvedFileName: undefined, + failedLookupLocations: [] + }; + } return { - resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + resolvedFileName, failedLookupLocations: result.failedLookupLocations }; }); @@ -1131,7 +1138,7 @@ namespace ts { if (result.error) { return { options: {}, - typingOptions: {}, + typeAcquisition: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] @@ -1143,7 +1150,7 @@ namespace ts { return { options: configFile.options, - typingOptions: configFile.typingOptions, + typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") @@ -1168,8 +1175,8 @@ namespace ts { toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, - info.typingOptions, - info.compilerOptions); + info.typeAcquisition, + info.unresolvedImports); }); } } @@ -1261,11 +1268,8 @@ namespace TypeScript.Services { export const TypeScriptServicesFactory = ts.TypeScriptServicesFactory; } -/* tslint:disable:no-unused-variable */ // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -const toolsVersion = "2.1"; - -/* tslint:enable:no-unused-variable */ +const toolsVersion = "2.2"; \ No newline at end of file diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 211e55b23ba..44c2ede9fbb 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -557,7 +557,9 @@ namespace ts.SignatureHelp { addRange(prefixDisplayParts, callTargetDisplayParts); } + let isVariadic: boolean; if (isTypeParameterList) { + isVariadic = false; // type parameter lists are not variadic prefixDisplayParts.push(punctuationPart(SyntaxKind.LessThanToken)); const typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; @@ -567,6 +569,7 @@ namespace ts.SignatureHelp { addRange(suffixDisplayParts, parameterParts); } else { + isVariadic = candidateSignature.hasRestParameter; const typeParameterParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation)); addRange(prefixDisplayParts, typeParameterParts); @@ -582,7 +585,7 @@ namespace ts.SignatureHelp { addRange(suffixDisplayParts, returnTypeParts); return { - isVariadic: candidateSignature.hasRestParameter, + isVariadic, prefixDisplayParts, suffixDisplayParts, separatorDisplayParts: [punctuationPart(SyntaxKind.CommaToken), spacePart()], diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index c9141278b10..b32bd8f331d 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -173,7 +173,7 @@ namespace ts.SymbolDisplay { displayParts.push(keywordPart(SyntaxKind.NewKeyword)); displayParts.push(spacePart()); } - if (!(type.flags & TypeFlags.Anonymous) && type.symbol) { + if (!(type.flags & TypeFlags.Object && (type).objectFlags & ObjectFlags.Anonymous) && type.symbol) { addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments)); } addSignatureDisplayParts(signature, allSignatures, TypeFormatFlags.WriteArrowStyleSignature); @@ -272,11 +272,9 @@ namespace ts.SymbolDisplay { displayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); displayParts.push(spacePart()); addFullSymbolName(symbol); - displayParts.push(spacePart()); - displayParts.push(keywordPart(SyntaxKind.InKeyword)); - displayParts.push(spacePart()); if (symbol.parent) { // Class/Interface type parameter + addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } @@ -288,6 +286,7 @@ namespace ts.SymbolDisplay { if (declaration) { if (isFunctionLikeKind(declaration.kind)) { + addInPrefix(); const signature = typeChecker.getSignatureFromDeclaration(declaration); if (declaration.kind === SyntaxKind.ConstructSignature) { displayParts.push(keywordPart(SyntaxKind.NewKeyword)); @@ -298,10 +297,11 @@ namespace ts.SymbolDisplay { } addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature)); } - else { + else if (declaration.kind === SyntaxKind.TypeAliasDeclaration) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path + addInPrefix(); displayParts.push(keywordPart(SyntaxKind.TypeKeyword)); displayParts.push(spacePart()); addFullSymbolName(declaration.symbol); @@ -439,6 +439,12 @@ namespace ts.SymbolDisplay { } } + function addInPrefix() { + displayParts.push(spacePart()); + displayParts.push(keywordPart(SyntaxKind.InKeyword)); + displayParts.push(spacePart()); + } + function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) { const fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing); diff --git a/src/services/transpile.ts b/src/services/transpile.ts index 303ca0d4173..da54faed1a2 100644 --- a/src/services/transpile.ts +++ b/src/services/transpile.ts @@ -74,8 +74,8 @@ namespace ts { // Create a compilerHost object to allow the compiler to read and write files const compilerHost: CompilerHost = { - getSourceFile: (fileName, target) => fileName === normalizePath(inputFileName) ? sourceFile : undefined, - writeFile: (name, text, writeByteOrderMark) => { + getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : undefined, + writeFile: (name, text) => { if (fileExtensionIs(name, ".map")) { Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`); sourceMapText = text; @@ -91,9 +91,9 @@ namespace ts { getCurrentDirectory: () => "", getNewLine: () => newLine, fileExists: (fileName): boolean => fileName === inputFileName, - readFile: (fileName): string => "", - directoryExists: directoryExists => true, - getDirectories: (path: string) => [] + readFile: () => "", + directoryExists: () => true, + getDirectories: () => [] }; const program = createProgram([inputFileName], options, compilerHost); diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 0066ef94343..502381b8be8 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -1,4 +1,4 @@ -{ +{ "compilerOptions": { "noImplicitAny": true, "noImplicitThis": true, @@ -9,7 +9,11 @@ "sourceMap": true, "stripInternal": true, "noResolve": false, - "declaration": true + "declaration": true, + "target": "es5", + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": [] }, "files": [ "../compiler/core.ts", @@ -25,13 +29,17 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", - "../compiler/transformers/es7.ts", - "../compiler/transformers/es6.ts", + "../compiler/transformers/esnext.ts", + "../compiler/transformers/es2017.ts", + "../compiler/transformers/es2016.ts", + "../compiler/transformers/es2015.ts", + "../compiler/transformers/es5.ts", + "../compiler/transformers/generators.ts", "../compiler/transformers/generators.ts", "../compiler/transformers/destructuring.ts", "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", - "../compiler/transformers/module/es6.ts", + "../compiler/transformers/module/es2015.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", diff --git a/src/services/types.ts b/src/services/types.ts index 9797c07b086..88ffe2950ce 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -53,6 +53,7 @@ namespace ts { /* @internal */ getNamedDeclarations(): Map; getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineEndOfPosition(pos: number): number; getLineStarts(): number[]; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; @@ -90,14 +91,16 @@ namespace ts { } public getText(start: number, end: number): string { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); } public getLength(): number { return this.text.length; } - public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange { + public getChangeRange(): TextChangeRange { // Text-based snapshots do not support incremental parsing. Return undefined // to signal that to the caller. return undefined; @@ -403,11 +406,11 @@ namespace ts { export interface EditorSettings { baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } /* @deprecated - consider using FormatCodeSettings instead */ @@ -415,6 +418,7 @@ namespace ts { InsertSpaceAfterCommaDelimiter: boolean; InsertSpaceAfterSemicolonInForStatements: boolean; InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterConstructor?: boolean; InsertSpaceAfterKeywordsInControlFlowStatements: boolean; InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; @@ -423,24 +427,27 @@ namespace ts { InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; InsertSpaceAfterTypeAssertion?: boolean; + InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; } export interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; insertSpaceAfterTypeAssertion?: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } export interface DefinitionInfo { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index b58c4188e0d..2f52d747e23 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -530,8 +530,8 @@ namespace ts { case SyntaxKind.DeleteExpression: case SyntaxKind.VoidExpression: case SyntaxKind.YieldExpression: - case SyntaxKind.SpreadElementExpression: - const unaryWordExpression = (n); + case SyntaxKind.SpreadElement: + const unaryWordExpression = n as (TypeOfExpression | DeleteExpression | VoidExpression | YieldExpression | SpreadElement); return isCompletedNode(unaryWordExpression.expression, sourceFile); case SyntaxKind.TaggedTemplateExpression: @@ -750,7 +750,7 @@ namespace ts { return find(startNode || sourceFile); function findRightmostToken(n: Node): Node { - if (isToken(n) || n.kind === SyntaxKind.JsxText) { + if (isToken(n)) { return n; } @@ -761,7 +761,7 @@ namespace ts { } function find(n: Node): Node { - if (isToken(n) || n.kind === SyntaxKind.JsxText) { + if (isToken(n)) { return n; } @@ -951,10 +951,10 @@ namespace ts { } if (node) { - if (node.jsDocComments) { - for (const jsDocComment of node.jsDocComments) { - if (jsDocComment.tags) { - for (const tag of jsDocComment.tags) { + if (node.jsDoc) { + for (const jsDoc of node.jsDoc) { + if (jsDoc.tags) { + for (const tag of jsDoc.tags) { if (tag.pos <= position && position <= tag.end) { return tag; } @@ -1137,13 +1137,14 @@ namespace ts { writeSpace: text => writeKind(text, SymbolDisplayPartKind.space), writeStringLiteral: text => writeKind(text, SymbolDisplayPartKind.stringLiteral), writeParameter: text => writeKind(text, SymbolDisplayPartKind.parameterName), + writeProperty: text => writeKind(text, SymbolDisplayPartKind.propertyName), writeSymbol, writeLine, increaseIndent: () => { indent++; }, decreaseIndent: () => { indent--; }, clear: resetWriter, - trackSymbol: () => { }, - reportInaccessibleThisError: () => { } + trackSymbol: noop, + reportInaccessibleThisError: noop }; function writeIndent() { @@ -1179,7 +1180,7 @@ namespace ts { } export function symbolPart(text: string, symbol: Symbol) { - return displayPart(text, displayPartKind(symbol), symbol); + return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol: Symbol): SymbolDisplayPartKind { const flags = symbol.flags; @@ -1205,7 +1206,7 @@ namespace ts { } } - export function displayPart(text: string, kind: SymbolDisplayPartKind, symbol?: Symbol): SymbolDisplayPart { + export function displayPart(text: string, kind: SymbolDisplayPartKind): SymbolDisplayPart { return { text: text, kind: SymbolDisplayPartKind[kind] @@ -1282,7 +1283,7 @@ namespace ts { if (isImportOrExportSpecifierName(location)) { return location.getText(); } - else if (isStringOrNumericLiteral(location.kind) && + else if (isStringOrNumericLiteral(location) && location.parent.kind === SyntaxKind.ComputedPropertyName) { return (location).text; } @@ -1339,7 +1340,7 @@ namespace ts { const options: TranspileOptions = { fileName: "config.js", compilerOptions: { - target: ScriptTarget.ES6, + target: ScriptTarget.ES2015, removeComments: true }, reportDiagnostics: true diff --git a/tests/baselines/reference/APISample_linter.js b/tests/baselines/reference/APISample_linter.js index 4e563c7cac3..1421b53a00c 100644 --- a/tests/baselines/reference/APISample_linter.js +++ b/tests/baselines/reference/APISample_linter.js @@ -58,7 +58,7 @@ export function delint(sourceFile: ts.SourceFile) { const fileNames: string[] = process.argv.slice(2); fileNames.forEach(fileName => { // Parse a file - let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); @@ -113,7 +113,7 @@ exports.delint = delint; var fileNames = process.argv.slice(2); fileNames.forEach(function (fileName) { // Parse a file - var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); }); diff --git a/tests/baselines/reference/ES5For-of12.errors.txt b/tests/baselines/reference/ES5For-of12.errors.txt index 02ed4c335a6..180a32bddb4 100644 --- a/tests/baselines/reference/ES5For-of12.errors.txt +++ b/tests/baselines/reference/ES5For-of12.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of12.ts(1,7): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/statements/for-ofStatements/ES5For-of12.ts(1,7): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of12.ts (1 errors) ==== for ([""] of [[""]]) { } ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/ExportAssignment7.js b/tests/baselines/reference/ExportAssignment7.js index bc7cee12b1d..461631e0e7d 100644 --- a/tests/baselines/reference/ExportAssignment7.js +++ b/tests/baselines/reference/ExportAssignment7.js @@ -11,5 +11,4 @@ var C = (function () { } return C; }()); -exports.C = C; module.exports = B; diff --git a/tests/baselines/reference/ExportAssignment8.js b/tests/baselines/reference/ExportAssignment8.js index e31a38c651c..d0963008012 100644 --- a/tests/baselines/reference/ExportAssignment8.js +++ b/tests/baselines/reference/ExportAssignment8.js @@ -11,5 +11,4 @@ var C = (function () { } return C; }()); -exports.C = C; module.exports = B; diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 30ca205587e..7ef64f5a971 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -18,6 +18,12 @@ "end": 16, "text": "typedef" }, + "fullName": { + "kind": "Identifier", + "pos": 17, + "end": 23, + "text": "People" + }, "name": { "kind": "Identifier", "pos": 17, diff --git a/tests/baselines/reference/ModuleWithExportedAndNonExportedEnums.js b/tests/baselines/reference/ModuleWithExportedAndNonExportedEnums.js index 3cd522d3c2c..713d2ac7f18 100644 --- a/tests/baselines/reference/ModuleWithExportedAndNonExportedEnums.js +++ b/tests/baselines/reference/ModuleWithExportedAndNonExportedEnums.js @@ -14,11 +14,11 @@ var b = A.Day.Monday; //// [ModuleWithExportedAndNonExportedEnums.js] var A; (function (A) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Blue"] = 1] = "Blue"; - })(A.Color || (A.Color = {})); - var Color = A.Color; + })(Color = A.Color || (A.Color = {})); var Day; (function (Day) { Day[Day["Monday"] = 0] = "Monday"; diff --git a/tests/baselines/reference/abstractPropertyNegative.errors.txt b/tests/baselines/reference/abstractPropertyNegative.errors.txt index 448fb2255e0..314ab842ded 100644 --- a/tests/baselines/reference/abstractPropertyNegative.errors.txt +++ b/tests/baselines/reference/abstractPropertyNegative.errors.txt @@ -6,7 +6,7 @@ tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstra tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'readonlyProp' from class 'B'. tests/cases/compiler/abstractPropertyNegative.ts(15,5): error TS1244: Abstract methods can only appear within an abstract class. tests/cases/compiler/abstractPropertyNegative.ts(16,37): error TS1005: '{' expected. -tests/cases/compiler/abstractPropertyNegative.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/abstractPropertyNegative.ts(19,3): error TS2540: Cannot assign to 'ro' because it is a constant or a read-only property. tests/cases/compiler/abstractPropertyNegative.ts(24,7): error TS2415: Class 'WrongTypePropertyImpl' incorrectly extends base class 'WrongTypeProperty'. Types of property 'num' are incompatible. Type 'string' is not assignable to type 'number'. @@ -58,8 +58,8 @@ tests/cases/compiler/abstractPropertyNegative.ts(41,18): error TS2676: Accessors } let c = new C(); c.ro = "error: lhs of assignment can't be readonly"; - ~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~ +!!! error TS2540: Cannot assign to 'ro' because it is a constant or a read-only property. abstract class WrongTypeProperty { abstract num: number; diff --git a/tests/baselines/reference/accessorWithRestParam.js b/tests/baselines/reference/accessorWithRestParam.js index a58a7db1c52..871f3ed00ef 100644 --- a/tests/baselines/reference/accessorWithRestParam.js +++ b/tests/baselines/reference/accessorWithRestParam.js @@ -13,7 +13,7 @@ var C = (function () { set: function () { var v = []; for (var _i = 0; _i < arguments.length; _i++) { - v[_i - 0] = arguments[_i]; + v[_i] = arguments[_i]; } }, enumerable: true, @@ -23,7 +23,7 @@ var C = (function () { set: function () { var v2 = []; for (var _i = 0; _i < arguments.length; _i++) { - v2[_i - 0] = arguments[_i]; + v2[_i] = arguments[_i]; } }, enumerable: true, diff --git a/tests/baselines/reference/allowSyntheticDefaultImports10.js b/tests/baselines/reference/allowSyntheticDefaultImports10.js index 746997c4c89..396cd75b574 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports10.js +++ b/tests/baselines/reference/allowSyntheticDefaultImports10.js @@ -13,5 +13,5 @@ Foo.default.default.foo(); //// [a.js] "use strict"; var Foo = require("./b"); -Foo.default.bar(); -Foo.default.default.foo(); +Foo["default"].bar(); +Foo["default"]["default"].foo(); diff --git a/tests/baselines/reference/alwaysStrict.errors.txt b/tests/baselines/reference/alwaysStrict.errors.txt new file mode 100644 index 00000000000..d7fcfb45801 --- /dev/null +++ b/tests/baselines/reference/alwaysStrict.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/alwaysStrict.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrict.ts (1 errors) ==== + + function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrict.js b/tests/baselines/reference/alwaysStrict.js new file mode 100644 index 00000000000..bc5f9a29912 --- /dev/null +++ b/tests/baselines/reference/alwaysStrict.js @@ -0,0 +1,11 @@ +//// [alwaysStrict.ts] + +function f() { + var arguments = []; +} + +//// [alwaysStrict.js] +"use strict"; +function f() { + var arguments = []; +} diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js new file mode 100644 index 00000000000..cc3be45dedc --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js @@ -0,0 +1,11 @@ +//// [alwaysStrictAlreadyUseStrict.ts] +"use strict" +function f() { + var a = []; +} + +//// [alwaysStrictAlreadyUseStrict.js] +"use strict"; +function f() { + var a = []; +} diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols new file mode 100644 index 00000000000..143f579b94d --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols @@ -0,0 +1,8 @@ +=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts === +"use strict" +function f() { +>f : Symbol(f, Decl(alwaysStrictAlreadyUseStrict.ts, 0, 12)) + + var a = []; +>a : Symbol(a, Decl(alwaysStrictAlreadyUseStrict.ts, 2, 7)) +} diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types new file mode 100644 index 00000000000..0181b40de27 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types @@ -0,0 +1,11 @@ +=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts === +"use strict" +>"use strict" : "use strict" + +function f() { +>f : () => void + + var a = []; +>a : any[] +>[] : undefined[] +} diff --git a/tests/baselines/reference/alwaysStrictES6.errors.txt b/tests/baselines/reference/alwaysStrictES6.errors.txt new file mode 100644 index 00000000000..b775a6e4755 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictES6.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/alwaysStrictES6.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrictES6.ts (1 errors) ==== + + function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictES6.js b/tests/baselines/reference/alwaysStrictES6.js new file mode 100644 index 00000000000..2c7ad36bce2 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictES6.js @@ -0,0 +1,11 @@ +//// [alwaysStrictES6.ts] + +function f() { + var arguments = []; +} + +//// [alwaysStrictES6.js] +"use strict"; +function f() { + var arguments = []; +} diff --git a/tests/baselines/reference/alwaysStrictModule.errors.txt b/tests/baselines/reference/alwaysStrictModule.errors.txt new file mode 100644 index 00000000000..90c1a0b930a --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/alwaysStrictModule.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrictModule.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictModule.js b/tests/baselines/reference/alwaysStrictModule.js new file mode 100644 index 00000000000..f39c87ed96c --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule.js @@ -0,0 +1,17 @@ +//// [alwaysStrictModule.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [alwaysStrictModule.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); diff --git a/tests/baselines/reference/alwaysStrictModule2.errors.txt b/tests/baselines/reference/alwaysStrictModule2.errors.txt new file mode 100644 index 00000000000..3980d24abfc --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule2.errors.txt @@ -0,0 +1,22 @@ +tests/cases/compiler/a.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. +tests/cases/compiler/b.ts(3,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/a.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } + +==== tests/cases/compiler/b.ts (1 errors) ==== + module M { + export function f2() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictModule2.js b/tests/baselines/reference/alwaysStrictModule2.js new file mode 100644 index 00000000000..54f179ff10b --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule2.js @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/alwaysStrictModule2.ts] //// + +//// [a.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [b.ts] +module M { + export function f2() { + var arguments = []; + } +} + +//// [out.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); +"use strict"; +var M; +(function (M) { + function f2() { + var arguments = []; + } + M.f2 = f2; +})(M || (M = {})); diff --git a/tests/baselines/reference/alwaysStrictModule3.js b/tests/baselines/reference/alwaysStrictModule3.js new file mode 100644 index 00000000000..894bad25143 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule3.js @@ -0,0 +1,8 @@ +//// [alwaysStrictModule3.ts] + +// module ES2015 +export const a = 1; + +//// [alwaysStrictModule3.js] +// module ES2015 +export var a = 1; diff --git a/tests/baselines/reference/alwaysStrictModule3.symbols b/tests/baselines/reference/alwaysStrictModule3.symbols new file mode 100644 index 00000000000..6f053673f0e --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule3.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/alwaysStrictModule3.ts === + +// module ES2015 +export const a = 1; +>a : Symbol(a, Decl(alwaysStrictModule3.ts, 2, 12)) + diff --git a/tests/baselines/reference/alwaysStrictModule3.types b/tests/baselines/reference/alwaysStrictModule3.types new file mode 100644 index 00000000000..75b11206a4f --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule3.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/alwaysStrictModule3.ts === + +// module ES2015 +export const a = 1; +>a : 1 +>1 : 1 + diff --git a/tests/baselines/reference/alwaysStrictModule4.js b/tests/baselines/reference/alwaysStrictModule4.js new file mode 100644 index 00000000000..1444f351bbd --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule4.js @@ -0,0 +1,9 @@ +//// [alwaysStrictModule4.ts] + +// Module commonjs +export const a = 1 + +//// [alwaysStrictModule4.js] +"use strict"; +// Module commonjs +exports.a = 1; diff --git a/tests/baselines/reference/alwaysStrictModule4.symbols b/tests/baselines/reference/alwaysStrictModule4.symbols new file mode 100644 index 00000000000..4b8a968ae16 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule4.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/alwaysStrictModule4.ts === + +// Module commonjs +export const a = 1 +>a : Symbol(a, Decl(alwaysStrictModule4.ts, 2, 12)) + diff --git a/tests/baselines/reference/alwaysStrictModule4.types b/tests/baselines/reference/alwaysStrictModule4.types new file mode 100644 index 00000000000..fff87967605 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule4.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/alwaysStrictModule4.ts === + +// Module commonjs +export const a = 1 +>a : 1 +>1 : 1 + diff --git a/tests/baselines/reference/alwaysStrictModule5.js b/tests/baselines/reference/alwaysStrictModule5.js new file mode 100644 index 00000000000..74b9d72263c --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule5.js @@ -0,0 +1,8 @@ +//// [alwaysStrictModule5.ts] + +// Targeting ES6 +export const a = 1; + +//// [alwaysStrictModule5.js] +// Targeting ES6 +export const a = 1; diff --git a/tests/baselines/reference/alwaysStrictModule5.symbols b/tests/baselines/reference/alwaysStrictModule5.symbols new file mode 100644 index 00000000000..903bf3c5c98 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule5.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/alwaysStrictModule5.ts === + +// Targeting ES6 +export const a = 1; +>a : Symbol(a, Decl(alwaysStrictModule5.ts, 2, 12)) + diff --git a/tests/baselines/reference/alwaysStrictModule5.types b/tests/baselines/reference/alwaysStrictModule5.types new file mode 100644 index 00000000000..2bfa329ad7e --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule5.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/alwaysStrictModule5.ts === + +// Targeting ES6 +export const a = 1; +>a : 1 +>1 : 1 + diff --git a/tests/baselines/reference/alwaysStrictModule6.js b/tests/baselines/reference/alwaysStrictModule6.js new file mode 100644 index 00000000000..9a603926169 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule6.js @@ -0,0 +1,9 @@ +//// [alwaysStrictModule6.ts] + +// Targeting ES5 +export const a = 1; + +//// [alwaysStrictModule6.js] +"use strict"; +// Targeting ES5 +exports.a = 1; diff --git a/tests/baselines/reference/alwaysStrictModule6.symbols b/tests/baselines/reference/alwaysStrictModule6.symbols new file mode 100644 index 00000000000..59a70f3e5b5 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule6.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/alwaysStrictModule6.ts === + +// Targeting ES5 +export const a = 1; +>a : Symbol(a, Decl(alwaysStrictModule6.ts, 2, 12)) + diff --git a/tests/baselines/reference/alwaysStrictModule6.types b/tests/baselines/reference/alwaysStrictModule6.types new file mode 100644 index 00000000000..0970380911e --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule6.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/alwaysStrictModule6.ts === + +// Targeting ES5 +export const a = 1; +>a : 1 +>1 : 1 + diff --git a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt new file mode 100644 index 00000000000..8df1d76e546 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt @@ -0,0 +1,14 @@ +error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'. +tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +!!! error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'. +==== tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js new file mode 100644 index 00000000000..cfa7f69629f --- /dev/null +++ b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js @@ -0,0 +1,17 @@ +//// [alwaysStrictNoImplicitUseStrict.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [alwaysStrictNoImplicitUseStrict.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); diff --git a/tests/baselines/reference/ambientRequireFunction.js b/tests/baselines/reference/ambientRequireFunction.js new file mode 100644 index 00000000000..cd00b287c82 --- /dev/null +++ b/tests/baselines/reference/ambientRequireFunction.js @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/ambientRequireFunction.ts] //// + +//// [node.d.ts] + + +declare function require(moduleName: string): any; + +declare module "fs" { + export function readFileSync(s: string): string; +} + +//// [app.js] +/// + +const fs = require("fs"); +const text = fs.readFileSync("/a/b/c"); + +//// [app.js] +/// +var fs = require("fs"); +var text = fs.readFileSync("/a/b/c"); diff --git a/tests/baselines/reference/ambientRequireFunction.symbols b/tests/baselines/reference/ambientRequireFunction.symbols new file mode 100644 index 00000000000..6afb47e37fb --- /dev/null +++ b/tests/baselines/reference/ambientRequireFunction.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/app.js === +/// + +const fs = require("fs"); +>fs : Symbol(fs, Decl(app.js, 2, 5)) +>require : Symbol(require, Decl(node.d.ts, 0, 0)) +>"fs" : Symbol("fs", Decl(node.d.ts, 2, 50)) + +const text = fs.readFileSync("/a/b/c"); +>text : Symbol(text, Decl(app.js, 3, 5)) +>fs.readFileSync : Symbol(readFileSync, Decl(node.d.ts, 4, 21)) +>fs : Symbol(fs, Decl(app.js, 2, 5)) +>readFileSync : Symbol(readFileSync, Decl(node.d.ts, 4, 21)) + +=== tests/cases/compiler/node.d.ts === + + +declare function require(moduleName: string): any; +>require : Symbol(require, Decl(node.d.ts, 0, 0)) +>moduleName : Symbol(moduleName, Decl(node.d.ts, 2, 25)) + +declare module "fs" { + export function readFileSync(s: string): string; +>readFileSync : Symbol(readFileSync, Decl(node.d.ts, 4, 21)) +>s : Symbol(s, Decl(node.d.ts, 5, 33)) +} + diff --git a/tests/baselines/reference/ambientRequireFunction.types b/tests/baselines/reference/ambientRequireFunction.types new file mode 100644 index 00000000000..e0341d97ec3 --- /dev/null +++ b/tests/baselines/reference/ambientRequireFunction.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/app.js === +/// + +const fs = require("fs"); +>fs : typeof "fs" +>require("fs") : any +>require : (moduleName: string) => any +>"fs" : "fs" + +const text = fs.readFileSync("/a/b/c"); +>text : string +>fs.readFileSync("/a/b/c") : string +>fs.readFileSync : (s: string) => string +>fs : typeof "fs" +>readFileSync : (s: string) => string +>"/a/b/c" : "/a/b/c" + +=== tests/cases/compiler/node.d.ts === + + +declare function require(moduleName: string): any; +>require : (moduleName: string) => any +>moduleName : string + +declare module "fs" { + export function readFileSync(s: string): string; +>readFileSync : (s: string) => string +>s : string +} + diff --git a/tests/baselines/reference/amdImportAsPrimaryExpression.js b/tests/baselines/reference/amdImportAsPrimaryExpression.js index 1281b7f7f47..3c2e9c041fa 100644 --- a/tests/baselines/reference/amdImportAsPrimaryExpression.js +++ b/tests/baselines/reference/amdImportAsPrimaryExpression.js @@ -15,12 +15,12 @@ if(foo.E1.A === 0){ //// [foo_0.js] define(["require", "exports"], function (require, exports) { "use strict"; + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; E1[E1["B"] = 1] = "B"; E1[E1["C"] = 2] = "C"; - })(exports.E1 || (exports.E1 = {})); - var E1 = exports.E1; + })(E1 = exports.E1 || (exports.E1 = {})); }); //// [foo_1.js] define(["require", "exports", "./foo_0"], function (require, exports, foo) { diff --git a/tests/baselines/reference/amdImportNotAsPrimaryExpression.js b/tests/baselines/reference/amdImportNotAsPrimaryExpression.js index b8e9f5346b0..a0bd7c83d64 100644 --- a/tests/baselines/reference/amdImportNotAsPrimaryExpression.js +++ b/tests/baselines/reference/amdImportNotAsPrimaryExpression.js @@ -40,14 +40,14 @@ define(["require", "exports"], function (require, exports) { } return C1; }()); - exports.C1 = C1; C1.s1 = true; + exports.C1 = C1; + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; E1[E1["B"] = 1] = "B"; E1[E1["C"] = 2] = "C"; - })(exports.E1 || (exports.E1 = {})); - var E1 = exports.E1; + })(E1 = exports.E1 || (exports.E1 = {})); }); //// [foo_1.js] define(["require", "exports"], function (require, exports) { diff --git a/tests/baselines/reference/arithAssignTyping.errors.txt b/tests/baselines/reference/arithAssignTyping.errors.txt index 10f34e94012..12b5b52698d 100644 --- a/tests/baselines/reference/arithAssignTyping.errors.txt +++ b/tests/baselines/reference/arithAssignTyping.errors.txt @@ -1,15 +1,15 @@ -tests/cases/compiler/arithAssignTyping.ts(3,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/arithAssignTyping.ts(4,1): error TS2365: Operator '+=' cannot be applied to types 'typeof f' and '1'. -tests/cases/compiler/arithAssignTyping.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(9,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/arithAssignTyping.ts(3,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(4,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(5,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(6,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(7,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(8,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(9,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(10,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(11,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(12,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(13,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2539: Cannot assign to 'f' because it is not a variable. ==== tests/cases/compiler/arithAssignTyping.ts (12 errors) ==== @@ -17,37 +17,37 @@ tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2362: The left-hand sid f += ''; // error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f += 1; // error - ~~~~~~ -!!! error TS2365: Operator '+=' cannot be applied to types 'typeof f' and '1'. + ~ +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f -= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f *= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f /= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f %= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f &= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f |= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f <<= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f >>= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f >>>= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. f ^= 1; // error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'f' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/arrowFunctionContexts.js b/tests/baselines/reference/arrowFunctionContexts.js index 64727398f72..1af0797b41f 100644 --- a/tests/baselines/reference/arrowFunctionContexts.js +++ b/tests/baselines/reference/arrowFunctionContexts.js @@ -116,7 +116,8 @@ var Base = (function () { var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - return _super.call(this, function () { return _this; }) || this; + var _this = _super.call(this, function () { return _this; }) || this; + return _this; } return Derived; }(Base)); @@ -157,7 +158,8 @@ var M2; var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - return _super.call(this, function () { return _this; }) || this; + var _this = _super.call(this, function () { return _this; }) || this; + return _this; } return Derived; }(Base)); diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js new file mode 100644 index 00000000000..daaff29cad9 --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js @@ -0,0 +1,6 @@ +//// [arrowFunctionWithParameterNameAsync_es2017.ts] + +const x = async => async; + +//// [arrowFunctionWithParameterNameAsync_es2017.js] +var x = function (async) { return async; }; diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols new file mode 100644 index 00000000000..481697c0afd --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts === + +const x = async => async; +>x : Symbol(x, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 5)) +>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9)) +>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9)) + diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types new file mode 100644 index 00000000000..ccb8654284c --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts === + +const x = async => async; +>x : (async: any) => any +>async => async : (async: any) => any +>async : any +>async : any + diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types index c2d9213ca60..7492a698e3a 100644 --- a/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types @@ -10,10 +10,10 @@ var Foo; >Foo : any type ->type : undefined +>type : any Foo = string; ->Foo = string : undefined +>Foo = string : any >Foo : any ->string : undefined +>string : any diff --git a/tests/baselines/reference/assignAnyToEveryType.errors.txt b/tests/baselines/reference/assignAnyToEveryType.errors.txt index 9aae6efc37e..86efb0c3019 100644 --- a/tests/baselines/reference/assignAnyToEveryType.errors.txt +++ b/tests/baselines/reference/assignAnyToEveryType.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2539: Cannot assign to 'M' because it is not a variable. ==== tests/cases/conformance/types/any/assignAnyToEveryType.ts (1 errors) ==== @@ -44,7 +44,7 @@ tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2364: I M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function k(a: T) { a = x; diff --git a/tests/baselines/reference/assignEveryTypeToAny.types b/tests/baselines/reference/assignEveryTypeToAny.types index fd1dccefae0..cfc24e1da65 100644 --- a/tests/baselines/reference/assignEveryTypeToAny.types +++ b/tests/baselines/reference/assignEveryTypeToAny.types @@ -59,9 +59,9 @@ var e = undefined; >undefined : undefined x = e; ->x = e : undefined +>x = e : any >x : any ->e : undefined +>e : any var e2: typeof undefined; >e2 : any diff --git a/tests/baselines/reference/assignToEnum.errors.txt b/tests/baselines/reference/assignToEnum.errors.txt index d50daa3099f..438a002ef1e 100644 --- a/tests/baselines/reference/assignToEnum.errors.txt +++ b/tests/baselines/reference/assignToEnum.errors.txt @@ -1,22 +1,22 @@ -tests/cases/compiler/assignToEnum.ts(2,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/assignToEnum.ts(3,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/assignToEnum.ts(4,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/assignToEnum.ts(5,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/assignToEnum.ts(2,1): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/compiler/assignToEnum.ts(3,1): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/compiler/assignToEnum.ts(4,3): error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. +tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. ==== tests/cases/compiler/assignToEnum.ts (4 errors) ==== enum A { foo, bar } A = undefined; // invalid LHS ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. A = A.bar; // invalid LHS ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. A.foo = 1; // invalid LHS - ~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. A.foo = A.bar; // invalid LHS - ~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/assignToExistingClass.errors.txt b/tests/baselines/reference/assignToExistingClass.errors.txt index 6a377df5b0c..5f7faac9e64 100644 --- a/tests/baselines/reference/assignToExistingClass.errors.txt +++ b/tests/baselines/reference/assignToExistingClass.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2539: Cannot assign to 'Mocked' because it is not a variable. ==== tests/cases/compiler/assignToExistingClass.ts (1 errors) ==== @@ -11,7 +11,7 @@ tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2364: Invalid left- willThrowError() { Mocked = Mocked || function () { // => Error: Invalid left-hand side of assignment expression. ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'Mocked' because it is not a variable. return { myProp: "test" }; }; } diff --git a/tests/baselines/reference/assignToInvalidLHS.errors.txt b/tests/baselines/reference/assignToInvalidLHS.errors.txt index a39756d15f7..b338871606b 100644 --- a/tests/baselines/reference/assignToInvalidLHS.errors.txt +++ b/tests/baselines/reference/assignToInvalidLHS.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/assignToInvalidLHS.ts(4,9): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/assignToInvalidLHS.ts(4,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/compiler/assignToInvalidLHS.ts (1 errors) ==== @@ -7,4 +7,4 @@ tests/cases/compiler/assignToInvalidLHS.ts(4,9): error TS2364: Invalid left-hand // Below is actually valid JavaScript (see http://es5.github.com/#x8.7 ), even though will always fail at runtime with 'invalid left-hand side' var x = new y = 5; ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithCallSignaturesWithRestParameters.js b/tests/baselines/reference/assignmentCompatWithCallSignaturesWithRestParameters.js index f4cf5cc79e2..ec86f218ac0 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignaturesWithRestParameters.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignaturesWithRestParameters.js @@ -52,14 +52,14 @@ a = function () { return 1; }; // ok, same number of required params a = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return 1; }; // ok, same number of required params a = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return 1; }; // error, type mismatch @@ -72,7 +72,7 @@ a2 = function () { return 1; }; // ok, fewer required params a2 = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return 1; }; // ok, fewer required params diff --git a/tests/baselines/reference/assignmentLHSIsValue.errors.txt b/tests/baselines/reference/assignmentLHSIsValue.errors.txt index f97ae2bcfa5..01de8d33441 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/assignmentLHSIsValue.errors.txt @@ -1,42 +1,42 @@ -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(6,21): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7,13): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(8,21): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(11,18): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(13,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(17,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(19,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(22,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(24,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(27,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(28,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(29,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(30,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(31,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(32,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(6,21): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7,13): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(8,21): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(11,18): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(13,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(17,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(19,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(22,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(24,1): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(27,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(28,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(29,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(30,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(31,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(32,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(35,3): error TS7028: Unused label. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(35,9): error TS1128: Declaration or statement expected. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,2): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,6): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,2): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,6): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(42,36): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(44,19): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(46,27): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(50,20): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(51,11): error TS1005: ';' expected. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(54,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(57,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(58,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(59,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(60,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(61,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(62,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(63,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(64,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(65,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(66,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(67,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(68,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(69,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(70,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(54,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(57,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(58,2): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(59,2): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(60,2): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(61,2): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(62,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(63,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(64,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(65,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(66,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(67,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(68,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(69,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(70,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts (39 errors) ==== @@ -47,61 +47,61 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 class C { constructor() { this = value; } ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. foo() { this = value; } ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. static sfoo() { this = value; } ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } function foo() { this = value; } ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. this = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // identifiers: module, class, enum, function module M { export var a; } M = value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. C = value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. enum E { } E = value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. foo = value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. // literals null = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. true = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. false = value; ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. 0 = value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. '' = value; ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. /d+/ = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // object literals { a: 0} = value; @@ -113,9 +113,9 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 // array literals ['', ''] = value; ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // super class Derived extends C { @@ -143,48 +143,48 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 // function calls foo() = value; ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // parentheses, the containted expression is value (this) = value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (M) = value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'M' because it is not a variable. (C) = value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'C' because it is not a variable. (E) = value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'E' because it is not a variable. (foo) = value; - ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~~~ +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. (null) = value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (true) = value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (0) = value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ('') = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (/d+/) = value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ({}) = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ([]) = value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (function baz() { }) = value; ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (foo()) = value; ~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToFunction.errors.txt b/tests/baselines/reference/assignmentToFunction.errors.txt index b9a2f1f2675..6e9b1b3c6dd 100644 --- a/tests/baselines/reference/assignmentToFunction.errors.txt +++ b/tests/baselines/reference/assignmentToFunction.errors.txt @@ -1,12 +1,12 @@ -tests/cases/compiler/assignmentToFunction.ts(2,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/assignmentToFunction.ts(2,1): error TS2539: Cannot assign to 'fn' because it is not a variable. +tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2539: Cannot assign to 'bar' because it is not a variable. ==== tests/cases/compiler/assignmentToFunction.ts (2 errors) ==== function fn() { } fn = () => 3; ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'fn' because it is not a variable. module foo { function xyz() { @@ -14,6 +14,6 @@ tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2364: Invalid left-ha } bar = null; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'bar' because it is not a variable. } } \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToParenthesizedExpression1.errors.txt b/tests/baselines/reference/assignmentToParenthesizedExpression1.errors.txt index 0a411828bf9..ff8fa5d22b2 100644 --- a/tests/baselines/reference/assignmentToParenthesizedExpression1.errors.txt +++ b/tests/baselines/reference/assignmentToParenthesizedExpression1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/assignmentToParenthesizedExpression1.ts(2,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/assignmentToParenthesizedExpression1.ts(2,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/compiler/assignmentToParenthesizedExpression1.ts(2,2): error TS2695: Left side of comma operator is unused and has no side effects. @@ -6,6 +6,6 @@ tests/cases/compiler/assignmentToParenthesizedExpression1.ts(2,2): error TS2695: var x; (1, x)=0; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ~ !!! error TS2695: Left side of comma operator is unused and has no side effects. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt index b929704880e..907fcce4c31 100644 --- a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt +++ b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt @@ -3,9 +3,9 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(13,1): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(14,1): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(15,1): error TS2322: Type '""' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(17,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(18,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(25,5): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(17,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(18,2): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(25,5): error TS2539: Cannot assign to 'M3' because it is not a variable. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(31,1): error TS2322: Type '{ x: string; }' is not assignable to type 'typeof M3'. Types of property 'x' are incompatible. Type 'string' is not assignable to type 'number'. @@ -15,8 +15,8 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(33,1): error TS2322: Type '{ x: string; }' is not assignable to type 'typeof M3'. Types of property 'x' are incompatible. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(37,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(38,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(37,1): error TS2539: Cannot assign to 'fn' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(38,2): error TS2539: Cannot assign to 'fn' because it is not a variable. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(43,5): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(44,5): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(48,5): error TS2322: Type '""' is not assignable to type 'number'. @@ -24,10 +24,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(54,5): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(55,5): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(56,5): error TS2322: Type '""' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(62,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(63,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(69,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(70,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(62,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(63,2): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(69,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(70,2): error TS2539: Cannot assign to 'C' because it is not a variable. ==== tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts (24 errors) ==== @@ -59,10 +59,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize M = { y: 3 }; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. (M) = { y: 3 }; // Error - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'M' because it is not a variable. module M2 { export module M3 { @@ -71,7 +71,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize M3 = { x: 3 }; // Error ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M3' because it is not a variable. } M2.M3 = { x: 3 }; // OK (M2).M3 = { x: 3 }; // OK @@ -97,10 +97,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize function fn() { } fn = () => 3; // Bug 823548: Should be error (fn is not a reference) ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'fn' because it is not a variable. (fn) = () => 3; // Should be error - ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~~ +!!! error TS2539: Cannot assign to 'fn' because it is not a variable. function fn2(x: number, y: { t: number }) { x = 3; @@ -140,10 +140,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize } E = undefined; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. (E) = undefined; // Error - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'E' because it is not a variable. class C { @@ -151,8 +151,8 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize C = undefined; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. (C) = undefined; // Error - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'C' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToReferenceTypes.errors.txt b/tests/baselines/reference/assignmentToReferenceTypes.errors.txt index 56d6adc4149..7e323479d57 100644 --- a/tests/baselines/reference/assignmentToReferenceTypes.errors.txt +++ b/tests/baselines/reference/assignmentToReferenceTypes.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignmentToReferenceTypes.ts(5,1): error TS2304: Cannot find name 'M'. -tests/cases/compiler/assignmentToReferenceTypes.ts(9,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/assignmentToReferenceTypes.ts(13,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/assignmentToReferenceTypes.ts(9,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/compiler/assignmentToReferenceTypes.ts(13,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2539: Cannot assign to 'f' because it is not a variable. ==== tests/cases/compiler/assignmentToReferenceTypes.ts (4 errors) ==== @@ -17,18 +17,18 @@ tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2364: Invalid } C = null; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. enum E { } E = null; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. function f() { } f = null; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. var x = 1; x = null; diff --git a/tests/baselines/reference/assignmentTypeNarrowing.js b/tests/baselines/reference/assignmentTypeNarrowing.js index 7c10dde65cc..92fd49d9941 100644 --- a/tests/baselines/reference/assignmentTypeNarrowing.js +++ b/tests/baselines/reference/assignmentTypeNarrowing.js @@ -37,17 +37,17 @@ x = [true][0]; x; // boolean _a = [1][0], x = _a === void 0 ? "" : _a; x; // string | number -(_b = { x: true }, x = _b.x, _b); +(x = { x: true }.x); x; // boolean -(_c = { y: 1 }, x = _c.y, _c); +(x = { y: 1 }.y); x; // number -(_d = { x: true }, _e = _d.x, x = _e === void 0 ? "" : _e, _d); +(_b = { x: true }.x, x = _b === void 0 ? "" : _b); x; // string | boolean -(_f = { y: 1 }, _g = _f.y, x = _g === void 0 ? /a/ : _g, _f); +(_c = { y: 1 }.y, x = _c === void 0 ? /a/ : _c); x; // number | RegExp var a; for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { x = a_1[_i]; x; // string } -var _a, _b, _c, _d, _e, _f, _g; +var _a, _b, _c; diff --git a/tests/baselines/reference/assignments.errors.txt b/tests/baselines/reference/assignments.errors.txt index 2e637a6c720..86bbe75cd4b 100644 --- a/tests/baselines/reference/assignments.errors.txt +++ b/tests/baselines/reference/assignments.errors.txt @@ -1,8 +1,8 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(11,1): error TS2304: Cannot find name 'M'. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,3): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2539: Cannot assign to 'fn' because it is not a variable. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): error TS2693: 'I' only refers to a type, but is being used as a value here. @@ -24,20 +24,20 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): er class C { } C = null; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. enum E { A } E = null; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. E.A = null; // OK per spec, Error per implementation (509581) - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. function fn() { } fn = null; // Should be error ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'fn' because it is not a variable. var v; v = null; // OK diff --git a/tests/baselines/reference/asyncAliasReturnType_es5.errors.txt b/tests/baselines/reference/asyncAliasReturnType_es5.errors.txt new file mode 100644 index 00000000000..5e524e265e2 --- /dev/null +++ b/tests/baselines/reference/asyncAliasReturnType_es5.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es5/asyncAliasReturnType_es5.ts(3,21): error TS1055: Type 'PromiseAlias' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. + + +==== tests/cases/conformance/async/es5/asyncAliasReturnType_es5.ts (1 errors) ==== + type PromiseAlias = Promise; + + async function f(): PromiseAlias { + ~~~~~~~~~~~~~~~~~~ +!!! error TS1055: Type 'PromiseAlias' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt new file mode 100644 index 00000000000..923dbed6dad --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts(4,11): error TS2304: Cannot find name 'await'. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts (1 errors) ==== + + var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction10_es2017.js b/tests/baselines/reference/asyncArrowFunction10_es2017.js new file mode 100644 index 00000000000..3c966201bc2 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction10_es2017.js @@ -0,0 +1,13 @@ +//// [asyncArrowFunction10_es2017.ts] + +var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; +} + + +//// [asyncArrowFunction10_es2017.js] +var foo = async () => { + // Legal to use 'await' in a type context. + var v; +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.js b/tests/baselines/reference/asyncArrowFunction1_es2017.js new file mode 100644 index 00000000000..ff6a4624242 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction1_es2017.ts] + +var foo = async (): Promise => { +}; + +//// [asyncArrowFunction1_es2017.js] +var foo = async () => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.symbols b/tests/baselines/reference/asyncArrowFunction1_es2017.symbols new file mode 100644 index 00000000000..35fd033d6b4 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts === + +var foo = async (): Promise => { +>foo : Symbol(foo, Decl(asyncArrowFunction1_es2017.ts, 1, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.types b/tests/baselines/reference/asyncArrowFunction1_es2017.types new file mode 100644 index 00000000000..bdc6cacc917 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts === + +var foo = async (): Promise => { +>foo : () => Promise +>async (): Promise => {} : () => Promise +>Promise : Promise + +}; diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.js b/tests/baselines/reference/asyncArrowFunction2_es2017.js new file mode 100644 index 00000000000..d2a5d0306b1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction2_es2017.ts] +var f = (await) => { +} + +//// [asyncArrowFunction2_es2017.js] +var f = (await) => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.symbols b/tests/baselines/reference/asyncArrowFunction2_es2017.symbols new file mode 100644 index 00000000000..a56c5bb62c8 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts === +var f = (await) => { +>f : Symbol(f, Decl(asyncArrowFunction2_es2017.ts, 0, 3)) +>await : Symbol(await, Decl(asyncArrowFunction2_es2017.ts, 0, 9)) +} diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.types b/tests/baselines/reference/asyncArrowFunction2_es2017.types new file mode 100644 index 00000000000..1feb033e6ee --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts === +var f = (await) => { +>f : (await: any) => void +>(await) => {} : (await: any) => void +>await : any +} diff --git a/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt new file mode 100644 index 00000000000..1c1fd711760 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts (1 errors) ==== + function f(await = await) { + ~~~~~ +!!! error TS2372: Parameter 'await' cannot be referenced in its initializer. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction3_es2017.js b/tests/baselines/reference/asyncArrowFunction3_es2017.js new file mode 100644 index 00000000000..7ae371facc1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction3_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction3_es2017.ts] +function f(await = await) { +} + +//// [asyncArrowFunction3_es2017.js] +function f(await = await) { +} diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.js b/tests/baselines/reference/asyncArrowFunction4_es2017.js new file mode 100644 index 00000000000..ebec1e6dbd6 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction4_es2017.ts] +var await = () => { +} + +//// [asyncArrowFunction4_es2017.js] +var await = () => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.symbols b/tests/baselines/reference/asyncArrowFunction4_es2017.symbols new file mode 100644 index 00000000000..b44fc0dbdf6 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts === +var await = () => { +>await : Symbol(await, Decl(asyncArrowFunction4_es2017.ts, 0, 3)) +} diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.types b/tests/baselines/reference/asyncArrowFunction4_es2017.types new file mode 100644 index 00000000000..6af5f94c758 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts === +var await = () => { +>await : () => void +>() => {} : () => void +} diff --git a/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt new file mode 100644 index 00000000000..3df56177107 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt @@ -0,0 +1,24 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,11): error TS2304: Cannot find name 'async'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,18): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,24): error TS1005: ',' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,26): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,33): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,40): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts (6 errors) ==== + + var foo = async (await): Promise => { + ~~~~~ +!!! error TS2304: Cannot find name 'async'. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ',' expected. + ~~~~~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. + ~ +!!! error TS1005: '=' expected. + ~~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction5_es2017.js b/tests/baselines/reference/asyncArrowFunction5_es2017.js new file mode 100644 index 00000000000..0c61a141f17 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction5_es2017.js @@ -0,0 +1,9 @@ +//// [asyncArrowFunction5_es2017.ts] + +var foo = async (await): Promise => { +} + +//// [asyncArrowFunction5_es2017.js] +var foo = async(await), Promise = ; +{ +} diff --git a/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt new file mode 100644 index 00000000000..202ecb1727f --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts(2,22): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts(2,27): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts (2 errors) ==== + + var foo = async (a = await): Promise => { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction6_es2017.js b/tests/baselines/reference/asyncArrowFunction6_es2017.js new file mode 100644 index 00000000000..c36f75a180a --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction6_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction6_es2017.ts] + +var foo = async (a = await): Promise => { +} + +//// [asyncArrowFunction6_es2017.js] +var foo = async (a = await ) => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt new file mode 100644 index 00000000000..33e03624283 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts(4,24): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts(4,29): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts (2 errors) ==== + + var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction7_es2017.js b/tests/baselines/reference/asyncArrowFunction7_es2017.js new file mode 100644 index 00000000000..11d8c879eb8 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction7_es2017.js @@ -0,0 +1,14 @@ +//// [asyncArrowFunction7_es2017.ts] + +var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + } +} + +//// [asyncArrowFunction7_es2017.js] +var bar = async () => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await ) => { + }; +}; diff --git a/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt new file mode 100644 index 00000000000..75e460490bd --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts(3,19): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts (1 errors) ==== + + var foo = async (): Promise => { + var v = { [await]: foo } + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction8_es2017.js b/tests/baselines/reference/asyncArrowFunction8_es2017.js new file mode 100644 index 00000000000..1358f186ce2 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction8_es2017.js @@ -0,0 +1,10 @@ +//// [asyncArrowFunction8_es2017.ts] + +var foo = async (): Promise => { + var v = { [await]: foo } +} + +//// [asyncArrowFunction8_es2017.js] +var foo = async () => { + var v = { [await ]: foo }; +}; diff --git a/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt new file mode 100644 index 00000000000..ee94f3f9caf --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt @@ -0,0 +1,23 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,11): error TS2304: Cannot find name 'async'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,18): error TS2304: Cannot find name 'a'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,37): error TS1005: ',' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,39): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,46): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,53): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts (6 errors) ==== + var foo = async (a = await => await): Promise => { + ~~~~~ +!!! error TS2304: Cannot find name 'async'. + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS1005: ',' expected. + ~~~~~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. + ~ +!!! error TS1005: '=' expected. + ~~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction9_es2017.js b/tests/baselines/reference/asyncArrowFunction9_es2017.js new file mode 100644 index 00000000000..c1fec991ec1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction9_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction9_es2017.ts] +var foo = async (a = await => await): Promise => { +} + +//// [asyncArrowFunction9_es2017.js] +var foo = async(a = await => await), Promise = ; +{ +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js new file mode 100644 index 00000000000..f7f813ad502 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js @@ -0,0 +1,16 @@ +//// [asyncArrowFunctionCapturesArguments_es2017.ts] +class C { + method() { + function other() {} + var fn = async () => await other.apply(this, arguments); + } +} + + +//// [asyncArrowFunctionCapturesArguments_es2017.js] +class C { + method() { + function other() { } + var fn = async () => await other.apply(this, arguments); + } +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols new file mode 100644 index 00000000000..ccd9b48e400 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols @@ -0,0 +1,20 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts === +class C { +>C : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 0)) + + method() { +>method : Symbol(C.method, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 9)) + + function other() {} +>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 1, 13)) + + var fn = async () => await other.apply(this, arguments); +>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 3, 9)) +>other.apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 1, 13)) +>apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>this : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 0)) +>arguments : Symbol(arguments) + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types new file mode 100644 index 00000000000..a7a80424e19 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types @@ -0,0 +1,23 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts === +class C { +>C : C + + method() { +>method : () => void + + function other() {} +>other : () => void + + var fn = async () => await other.apply(this, arguments); +>fn : () => Promise +>async () => await other.apply(this, arguments) : () => Promise +>await other.apply(this, arguments) : any +>other.apply(this, arguments) : any +>other.apply : (this: Function, thisArg: any, argArray?: any) => any +>other : () => void +>apply : (this: Function, thisArg: any, argArray?: any) => any +>this : this +>arguments : IArguments + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js new file mode 100644 index 00000000000..13560557ffe --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js @@ -0,0 +1,14 @@ +//// [asyncArrowFunctionCapturesThis_es2017.ts] +class C { + method() { + var fn = async () => await this; + } +} + + +//// [asyncArrowFunctionCapturesThis_es2017.js] +class C { + method() { + var fn = async () => await this; + } +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols new file mode 100644 index 00000000000..bc14bafa0c5 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts === +class C { +>C : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 0)) + + method() { +>method : Symbol(C.method, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 9)) + + var fn = async () => await this; +>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 2, 9)) +>this : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 0)) + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types new file mode 100644 index 00000000000..57f59302bb5 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts === +class C { +>C : C + + method() { +>method : () => void + + var fn = async () => await this; +>fn : () => Promise +>async () => await this : () => Promise +>await this : this +>this : this + } +} + diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt new file mode 100644 index 00000000000..95927c283aa --- /dev/null +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt @@ -0,0 +1,45 @@ +tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts(1,27): error TS2307: Cannot find module 'missing'. + + +==== tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts (1 errors) ==== + import { MyPromise } from "missing"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'missing'. + + declare var p: Promise; + declare var mp: MyPromise; + + async function f0() { } + async function f1(): Promise { } + async function f3(): MyPromise { } + + let f4 = async function() { } + let f5 = async function(): Promise { } + let f6 = async function(): MyPromise { } + + let f7 = async () => { }; + let f8 = async (): Promise => { }; + let f9 = async (): MyPromise => { }; + let f10 = async () => p; + let f11 = async () => mp; + let f12 = async (): Promise => mp; + let f13 = async (): MyPromise => p; + + let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } + }; + + class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } + } + + module M { + export async function f1() { } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js new file mode 100644 index 00000000000..065aa675b6e --- /dev/null +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js @@ -0,0 +1,73 @@ +//// [asyncAwaitIsolatedModules_es2017.ts] +import { MyPromise } from "missing"; + +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} + +//// [asyncAwaitIsolatedModules_es2017.js] +async function f0() { } +async function f1() { } +async function f3() { } +let f4 = async function () { }; +let f5 = async function () { }; +let f6 = async function () { }; +let f7 = async () => { }; +let f8 = async () => { }; +let f9 = async () => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async () => mp; +let f13 = async () => p; +let o = { + async m1() { }, + async m2() { }, + async m3() { } +}; +class C { + async m1() { } + async m2() { } + async m3() { } + static async m4() { } + static async m5() { } + static async m6() { } +} +var M; +(function (M) { + async function f1() { } + M.f1 = f1; +})(M || (M = {})); diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js index fe99be204fc..49404267009 100644 --- a/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js @@ -46,7 +46,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { @@ -77,6 +77,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) { } }; var _this = this; +var missing_1 = require("missing"); function f0() { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js index 98d11d72bfb..046b74e6569 100644 --- a/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js @@ -45,7 +45,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function f0() { diff --git a/tests/baselines/reference/asyncAwaitWithCapturedBlockScopeVar.js b/tests/baselines/reference/asyncAwaitWithCapturedBlockScopeVar.js index 49566904ae1..6d167a00089 100644 --- a/tests/baselines/reference/asyncAwaitWithCapturedBlockScopeVar.js +++ b/tests/baselines/reference/asyncAwaitWithCapturedBlockScopeVar.js @@ -57,8 +57,7 @@ function fn1() { i = 0; _a.label = 1; case 1: - if (!(i < 1)) - return [3 /*break*/, 4]; + if (!(i < 1)) return [3 /*break*/, 4]; return [5 /*yield**/, _loop_1(i)]; case 2: _a.sent(); @@ -92,8 +91,7 @@ function fn2() { i = 0; _a.label = 1; case 1: - if (!(i < 1)) - return [3 /*break*/, 4]; + if (!(i < 1)) return [3 /*break*/, 4]; return [5 /*yield**/, _loop_2(i)]; case 2: state_1 = _a.sent(); @@ -129,8 +127,7 @@ function fn3() { i = 0; _a.label = 1; case 1: - if (!(i < 1)) - return [3 /*break*/, 4]; + if (!(i < 1)) return [3 /*break*/, 4]; return [5 /*yield**/, _loop_3(i)]; case 2: _a.sent(); @@ -164,8 +161,7 @@ function fn4() { i = 0; _a.label = 1; case 1: - if (!(i < 1)) - return [3 /*break*/, 4]; + if (!(i < 1)) return [3 /*break*/, 4]; return [5 /*yield**/, _loop_4(i)]; case 2: state_2 = _a.sent(); diff --git a/tests/baselines/reference/asyncAwait_es2017.js b/tests/baselines/reference/asyncAwait_es2017.js new file mode 100644 index 00000000000..314c99fa210 --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.js @@ -0,0 +1,73 @@ +//// [asyncAwait_es2017.ts] +type MyPromise = Promise; +declare var MyPromise: typeof Promise; +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} + +//// [asyncAwait_es2017.js] +async function f0() { } +async function f1() { } +async function f3() { } +let f4 = async function () { }; +let f5 = async function () { }; +let f6 = async function () { }; +let f7 = async () => { }; +let f8 = async () => { }; +let f9 = async () => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async () => mp; +let f13 = async () => p; +let o = { + async m1() { }, + async m2() { }, + async m3() { } +}; +class C { + async m1() { } + async m2() { } + async m3() { } + static async m4() { } + static async m5() { } + static async m6() { } +} +var M; +(function (M) { + async function f1() { } + M.f1 = f1; +})(M || (M = {})); diff --git a/tests/baselines/reference/asyncAwait_es2017.symbols b/tests/baselines/reference/asyncAwait_es2017.symbols new file mode 100644 index 00000000000..34dc9802a25 --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.symbols @@ -0,0 +1,118 @@ +=== tests/cases/conformance/async/es2017/asyncAwait_es2017.ts === +type MyPromise = Promise; +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>T : Symbol(T, Decl(asyncAwait_es2017.ts, 0, 15)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>T : Symbol(T, Decl(asyncAwait_es2017.ts, 0, 15)) + +declare var MyPromise: typeof Promise; +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare var p: Promise; +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare var mp: MyPromise; +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +async function f0() { } +>f0 : Symbol(f0, Decl(asyncAwait_es2017.ts, 3, 34)) + +async function f1(): Promise { } +>f1 : Symbol(f1, Decl(asyncAwait_es2017.ts, 5, 23)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +async function f3(): MyPromise { } +>f3 : Symbol(f3, Decl(asyncAwait_es2017.ts, 6, 38)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f4 = async function() { } +>f4 : Symbol(f4, Decl(asyncAwait_es2017.ts, 9, 3)) + +let f5 = async function(): Promise { } +>f5 : Symbol(f5, Decl(asyncAwait_es2017.ts, 10, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +let f6 = async function(): MyPromise { } +>f6 : Symbol(f6, Decl(asyncAwait_es2017.ts, 11, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f7 = async () => { }; +>f7 : Symbol(f7, Decl(asyncAwait_es2017.ts, 13, 3)) + +let f8 = async (): Promise => { }; +>f8 : Symbol(f8, Decl(asyncAwait_es2017.ts, 14, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +let f9 = async (): MyPromise => { }; +>f9 : Symbol(f9, Decl(asyncAwait_es2017.ts, 15, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f10 = async () => p; +>f10 : Symbol(f10, Decl(asyncAwait_es2017.ts, 16, 3)) +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) + +let f11 = async () => mp; +>f11 : Symbol(f11, Decl(asyncAwait_es2017.ts, 17, 3)) +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) + +let f12 = async (): Promise => mp; +>f12 : Symbol(f12, Decl(asyncAwait_es2017.ts, 18, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) + +let f13 = async (): MyPromise => p; +>f13 : Symbol(f13, Decl(asyncAwait_es2017.ts, 19, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) + +let o = { +>o : Symbol(o, Decl(asyncAwait_es2017.ts, 21, 3)) + + async m1() { }, +>m1 : Symbol(m1, Decl(asyncAwait_es2017.ts, 21, 9)) + + async m2(): Promise { }, +>m2 : Symbol(m2, Decl(asyncAwait_es2017.ts, 22, 16)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + async m3(): MyPromise { } +>m3 : Symbol(m3, Decl(asyncAwait_es2017.ts, 23, 31)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +}; + +class C { +>C : Symbol(C, Decl(asyncAwait_es2017.ts, 25, 2)) + + async m1() { } +>m1 : Symbol(C.m1, Decl(asyncAwait_es2017.ts, 27, 9)) + + async m2(): Promise { } +>m2 : Symbol(C.m2, Decl(asyncAwait_es2017.ts, 28, 15)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + async m3(): MyPromise { } +>m3 : Symbol(C.m3, Decl(asyncAwait_es2017.ts, 29, 30)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + + static async m4() { } +>m4 : Symbol(C.m4, Decl(asyncAwait_es2017.ts, 30, 32)) + + static async m5(): Promise { } +>m5 : Symbol(C.m5, Decl(asyncAwait_es2017.ts, 31, 22)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + static async m6(): MyPromise { } +>m6 : Symbol(C.m6, Decl(asyncAwait_es2017.ts, 32, 37)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +} + +module M { +>M : Symbol(M, Decl(asyncAwait_es2017.ts, 34, 1)) + + export async function f1() { } +>f1 : Symbol(f1, Decl(asyncAwait_es2017.ts, 36, 10)) +} diff --git a/tests/baselines/reference/asyncAwait_es2017.types b/tests/baselines/reference/asyncAwait_es2017.types new file mode 100644 index 00000000000..a1226d0cbfe --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.types @@ -0,0 +1,129 @@ +=== tests/cases/conformance/async/es2017/asyncAwait_es2017.ts === +type MyPromise = Promise; +>MyPromise : Promise +>T : T +>Promise : Promise +>T : T + +declare var MyPromise: typeof Promise; +>MyPromise : PromiseConstructor +>Promise : PromiseConstructor + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare var mp: MyPromise; +>mp : Promise +>MyPromise : Promise + +async function f0() { } +>f0 : () => Promise + +async function f1(): Promise { } +>f1 : () => Promise +>Promise : Promise + +async function f3(): MyPromise { } +>f3 : () => Promise +>MyPromise : Promise + +let f4 = async function() { } +>f4 : () => Promise +>async function() { } : () => Promise + +let f5 = async function(): Promise { } +>f5 : () => Promise +>async function(): Promise { } : () => Promise +>Promise : Promise + +let f6 = async function(): MyPromise { } +>f6 : () => Promise +>async function(): MyPromise { } : () => Promise +>MyPromise : Promise + +let f7 = async () => { }; +>f7 : () => Promise +>async () => { } : () => Promise + +let f8 = async (): Promise => { }; +>f8 : () => Promise +>async (): Promise => { } : () => Promise +>Promise : Promise + +let f9 = async (): MyPromise => { }; +>f9 : () => Promise +>async (): MyPromise => { } : () => Promise +>MyPromise : Promise + +let f10 = async () => p; +>f10 : () => Promise +>async () => p : () => Promise +>p : Promise + +let f11 = async () => mp; +>f11 : () => Promise +>async () => mp : () => Promise +>mp : Promise + +let f12 = async (): Promise => mp; +>f12 : () => Promise +>async (): Promise => mp : () => Promise +>Promise : Promise +>mp : Promise + +let f13 = async (): MyPromise => p; +>f13 : () => Promise +>async (): MyPromise => p : () => Promise +>MyPromise : Promise +>p : Promise + +let o = { +>o : { m1(): Promise; m2(): Promise; m3(): Promise; } +>{ async m1() { }, async m2(): Promise { }, async m3(): MyPromise { }} : { m1(): Promise; m2(): Promise; m3(): Promise; } + + async m1() { }, +>m1 : () => Promise + + async m2(): Promise { }, +>m2 : () => Promise +>Promise : Promise + + async m3(): MyPromise { } +>m3 : () => Promise +>MyPromise : Promise + +}; + +class C { +>C : C + + async m1() { } +>m1 : () => Promise + + async m2(): Promise { } +>m2 : () => Promise +>Promise : Promise + + async m3(): MyPromise { } +>m3 : () => Promise +>MyPromise : Promise + + static async m4() { } +>m4 : () => Promise + + static async m5(): Promise { } +>m5 : () => Promise +>Promise : Promise + + static async m6(): MyPromise { } +>m6 : () => Promise +>MyPromise : Promise +} + +module M { +>M : typeof M + + export async function f1() { } +>f1 : () => Promise +} diff --git a/tests/baselines/reference/asyncAwait_es5.js b/tests/baselines/reference/asyncAwait_es5.js index 043e68abeab..e4dc62ea1cf 100644 --- a/tests/baselines/reference/asyncAwait_es5.js +++ b/tests/baselines/reference/asyncAwait_es5.js @@ -45,7 +45,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/asyncAwait_es6.js b/tests/baselines/reference/asyncAwait_es6.js index 4ba9e096e10..d6635098aed 100644 --- a/tests/baselines/reference/asyncAwait_es6.js +++ b/tests/baselines/reference/asyncAwait_es6.js @@ -45,7 +45,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function f0() { diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt new file mode 100644 index 00000000000..d5da3432264 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt @@ -0,0 +1,26 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,20): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,30): error TS1109: Expression expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,33): error TS1138: Parameter declaration expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,33): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,38): error TS1005: ';' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,39): error TS1128: Declaration or statement expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,53): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts (7 errors) ==== + async function foo(a = await => await): Promise { + ~~~~~~~~~ +!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. + ~~ +!!! error TS1109: Expression expected. + ~~~~~ +!!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js new file mode 100644 index 00000000000..f8a22204311 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js @@ -0,0 +1,8 @@ +//// [asyncFunctionDeclaration10_es2017.ts] +async function foo(a = await => await): Promise { +} + +//// [asyncFunctionDeclaration10_es2017.js] +async function foo(a = await ) { } +await; +Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es5.js b/tests/baselines/reference/asyncFunctionDeclaration10_es5.js index 05ff9daa9da..758bdab5dc9 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration10_es5.js +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es5.js @@ -3,5 +3,11 @@ async function foo(a = await => await): Promise { } //// [asyncFunctionDeclaration10_es5.js] +function foo(a) { + if (a === void 0) { a = yield ; } + return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es6.js b/tests/baselines/reference/asyncFunctionDeclaration10_es6.js index 141c0cbab55..1f175035bf0 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration10_es6.js +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es6.js @@ -3,5 +3,8 @@ async function foo(a = await => await): Promise { } //// [asyncFunctionDeclaration10_es6.js] +function foo(a = yield ) { + return __awaiter(this, void 0, void 0, function* () { }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js new file mode 100644 index 00000000000..0ae906ebfe1 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration11_es2017.ts] +async function await(): Promise { +} + +//// [asyncFunctionDeclaration11_es2017.js] +async function await() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols new file mode 100644 index 00000000000..02c35d81d62 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts === +async function await(): Promise { +>await : Symbol(await, Decl(asyncFunctionDeclaration11_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types new file mode 100644 index 00000000000..b86601bf33d --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts === +async function await(): Promise { +>await : () => Promise +>Promise : Promise +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt new file mode 100644 index 00000000000..f951bee715c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,24): error TS1005: '(' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,29): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,33): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,47): error TS1005: '=>' expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts (4 errors) ==== + var v = async function await(): Promise { } + ~~~~~ +!!! error TS1005: '(' expected. + ~ +!!! error TS1005: '=' expected. + ~~~~~~~~~~~~~ +!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. + ~ +!!! error TS1005: '=>' expected. \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js new file mode 100644 index 00000000000..93fbb061023 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js @@ -0,0 +1,5 @@ +//// [asyncFunctionDeclaration12_es2017.ts] +var v = async function await(): Promise { } + +//// [asyncFunctionDeclaration12_es2017.js] +var v = async function () { }, await = () => { }; diff --git a/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt new file mode 100644 index 00000000000..41ea0a7cafb --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts(3,11): error TS2304: Cannot find name 'await'. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts (1 errors) ==== + async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js new file mode 100644 index 00000000000..a16236aea7f --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js @@ -0,0 +1,12 @@ +//// [asyncFunctionDeclaration13_es2017.ts] +async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; +} + + +//// [asyncFunctionDeclaration13_es2017.js] +async function foo() { + // Legal to use 'await' in a type context. + var v; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js new file mode 100644 index 00000000000..308b8f1763c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js @@ -0,0 +1,9 @@ +//// [asyncFunctionDeclaration14_es2017.ts] +async function foo(): Promise { + return; +} + +//// [asyncFunctionDeclaration14_es2017.js] +async function foo() { + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols new file mode 100644 index 00000000000..1b5bca844c0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts === +async function foo(): Promise { +>foo : Symbol(foo, Decl(asyncFunctionDeclaration14_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types new file mode 100644 index 00000000000..1e505f93a2c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts === +async function foo(): Promise { +>foo : () => Promise +>Promise : Promise + + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration15_es5.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration15_es5.errors.txt index 3ea03927aa9..5fa33233912 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration15_es5.errors.txt +++ b/tests/baselines/reference/asyncFunctionDeclaration15_es5.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(6,23): error TS1055: Type '{}' is not a valid async function return type. -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(7,23): error TS1055: Type 'any' is not a valid async function return type. -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(8,23): error TS1055: Type 'number' is not a valid async function return type. -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(9,23): error TS1055: Type 'PromiseLike' is not a valid async function return type. -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(10,23): error TS1055: Type 'typeof Thenable' is not a valid async function return type. -tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(10,23): error TS1055: Type 'typeof Thenable' is not a valid async function return type. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(6,23): error TS1055: Type '{}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(7,23): error TS1055: Type 'any' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(8,23): error TS1055: Type 'number' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(9,23): error TS1055: Type 'PromiseLike' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(10,23): error TS1055: Type 'typeof Thenable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. +tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(10,23): error TS1055: Type 'typeof Thenable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. Type 'Thenable' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '() => void' is not assignable to type '{ (onfulfilled?: (value: any) => any, onrejected?: (reason: any) => any): PromiseLike; (onfulfilled: (value: any) => any, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; (onfulfilled: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; (onfulfilled: (value: any) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; }'. @@ -20,21 +20,21 @@ tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration1 async function fn1() { } // valid: Promise async function fn2(): { } { } // error ~~~ -!!! error TS1055: Type '{}' is not a valid async function return type. +!!! error TS1055: Type '{}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. async function fn3(): any { } // error ~~~ -!!! error TS1055: Type 'any' is not a valid async function return type. +!!! error TS1055: Type 'any' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. async function fn4(): number { } // error ~~~~~~ -!!! error TS1055: Type 'number' is not a valid async function return type. +!!! error TS1055: Type 'number' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. async function fn5(): PromiseLike { } // error ~~~~~~~~~~~~~~~~~ -!!! error TS1055: Type 'PromiseLike' is not a valid async function return type. +!!! error TS1055: Type 'PromiseLike' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. async function fn6(): Thenable { } // error ~~~~~~~~ -!!! error TS1055: Type 'typeof Thenable' is not a valid async function return type. +!!! error TS1055: Type 'typeof Thenable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. ~~~~~~~~ -!!! error TS1055: Type 'typeof Thenable' is not a valid async function return type. +!!! error TS1055: Type 'typeof Thenable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value. !!! error TS1055: Type 'Thenable' is not assignable to type 'PromiseLike'. !!! error TS1055: Types of property 'then' are incompatible. !!! error TS1055: Type '() => void' is not assignable to type '{ (onfulfilled?: (value: any) => any, onrejected?: (reason: any) => any): PromiseLike; (onfulfilled: (value: any) => any, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; (onfulfilled: (value: any) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; (onfulfilled: (value: any) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; }'. diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js new file mode 100644 index 00000000000..549fd226b2f --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration1_es2017.ts] +async function foo(): Promise { +} + +//// [asyncFunctionDeclaration1_es2017.js] +async function foo() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols new file mode 100644 index 00000000000..a712df45896 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts === +async function foo(): Promise { +>foo : Symbol(foo, Decl(asyncFunctionDeclaration1_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types new file mode 100644 index 00000000000..ff97e686c43 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts === +async function foo(): Promise { +>foo : () => Promise +>Promise : Promise +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js new file mode 100644 index 00000000000..6de061456e8 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration2_es2017.ts] +function f(await) { +} + +//// [asyncFunctionDeclaration2_es2017.js] +function f(await) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols new file mode 100644 index 00000000000..aed41f50310 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts === +function f(await) { +>f : Symbol(f, Decl(asyncFunctionDeclaration2_es2017.ts, 0, 0)) +>await : Symbol(await, Decl(asyncFunctionDeclaration2_es2017.ts, 0, 11)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types new file mode 100644 index 00000000000..8413bea692a --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts === +function f(await) { +>f : (await: any) => void +>await : any +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt new file mode 100644 index 00000000000..53a85074834 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts (1 errors) ==== + function f(await = await) { + ~~~~~ +!!! error TS2372: Parameter 'await' cannot be referenced in its initializer. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js new file mode 100644 index 00000000000..d6110265fdc --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration3_es2017.ts] +function f(await = await) { +} + +//// [asyncFunctionDeclaration3_es2017.js] +function f(await = await) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js new file mode 100644 index 00000000000..6209531e549 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration4_es2017.ts] +function await() { +} + +//// [asyncFunctionDeclaration4_es2017.js] +function await() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols new file mode 100644 index 00000000000..7afbd879c59 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts === +function await() { +>await : Symbol(await, Decl(asyncFunctionDeclaration4_es2017.ts, 0, 0)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types new file mode 100644 index 00000000000..f7c4248f7c3 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts === +function await() { +>await : () => void +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt new file mode 100644 index 00000000000..ad8c0280206 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,20): error TS1138: Parameter declaration expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,20): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,25): error TS1005: ';' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,26): error TS1128: Declaration or statement expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,40): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts (5 errors) ==== + async function foo(await): Promise { + ~~~~~ +!!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js new file mode 100644 index 00000000000..904bbe62f0b --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js @@ -0,0 +1,8 @@ +//// [asyncFunctionDeclaration5_es2017.ts] +async function foo(await): Promise { +} + +//// [asyncFunctionDeclaration5_es2017.js] +async function foo() { } +await; +Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es5.js b/tests/baselines/reference/asyncFunctionDeclaration5_es5.js index 22c18ff6ad4..5f8f8f42735 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration5_es5.js +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es5.js @@ -3,5 +3,10 @@ async function foo(await): Promise { } //// [asyncFunctionDeclaration5_es5.js] +function foo() { + return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es6.js b/tests/baselines/reference/asyncFunctionDeclaration5_es6.js index 8d28c371465..9521b760415 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration5_es6.js +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es6.js @@ -3,5 +3,8 @@ async function foo(await): Promise { } //// [asyncFunctionDeclaration5_es6.js] +function foo() { + return __awaiter(this, void 0, void 0, function* () { }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt new file mode 100644 index 00000000000..b5a5ddccdce --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts(1,24): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts(1,29): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts (2 errors) ==== + async function foo(a = await): Promise { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js new file mode 100644 index 00000000000..6df02000846 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration6_es2017.ts] +async function foo(a = await): Promise { +} + +//// [asyncFunctionDeclaration6_es2017.js] +async function foo(a = await ) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt new file mode 100644 index 00000000000..ad9ec9a043a --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts(3,26): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts(3,31): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts (2 errors) ==== + async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js new file mode 100644 index 00000000000..c9aaa80b9b0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js @@ -0,0 +1,13 @@ +//// [asyncFunctionDeclaration7_es2017.ts] +async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + } +} + +//// [asyncFunctionDeclaration7_es2017.js] +async function bar() { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await ) { + } +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt new file mode 100644 index 00000000000..b82f012d694 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts(1,12): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts(1,20): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts (2 errors) ==== + var v = { [await]: foo } + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js new file mode 100644 index 00000000000..db7bfa4f9fb --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js @@ -0,0 +1,5 @@ +//// [asyncFunctionDeclaration8_es2017.ts] +var v = { [await]: foo } + +//// [asyncFunctionDeclaration8_es2017.js] +var v = { [await]: foo }; diff --git a/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt new file mode 100644 index 00000000000..27c41d8b253 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts(2,19): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts (1 errors) ==== + async function foo(): Promise { + var v = { [await]: foo } + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js new file mode 100644 index 00000000000..08cb8e44ba0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js @@ -0,0 +1,9 @@ +//// [asyncFunctionDeclaration9_es2017.ts] +async function foo(): Promise { + var v = { [await]: foo } +} + +//// [asyncFunctionDeclaration9_es2017.js] +async function foo() { + var v = { [await ]: foo }; +} diff --git a/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt b/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt index 599bf41a7f2..89a61ff648f 100644 --- a/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt +++ b/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt @@ -1,5 +1,5 @@ error TS2318: Cannot find global type 'Promise'. -tests/cases/compiler/asyncFunctionNoReturnType.ts(1,1): error TS1057: An async function or method must have a valid awaitable return type. +tests/cases/compiler/asyncFunctionNoReturnType.ts(1,1): error TS2697: An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option. tests/cases/compiler/asyncFunctionNoReturnType.ts(1,1): error TS7030: Not all code paths return a value. tests/cases/compiler/asyncFunctionNoReturnType.ts(2,9): error TS2304: Cannot find name 'window'. tests/cases/compiler/asyncFunctionNoReturnType.ts(3,9): error TS7030: Not all code paths return a value. @@ -9,7 +9,7 @@ tests/cases/compiler/asyncFunctionNoReturnType.ts(3,9): error TS7030: Not all co ==== tests/cases/compiler/asyncFunctionNoReturnType.ts (4 errors) ==== async () => { ~~~~~~~~~~~~~ -!!! error TS1057: An async function or method must have a valid awaitable return type. +!!! error TS2697: An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option. ~~~~~~~~~~~~~ !!! error TS7030: Not all code paths return a value. if (window) diff --git a/tests/baselines/reference/asyncFunctionNoReturnType.js b/tests/baselines/reference/asyncFunctionNoReturnType.js index fd39fc74d0e..b1c55416566 100644 --- a/tests/baselines/reference/asyncFunctionNoReturnType.js +++ b/tests/baselines/reference/asyncFunctionNoReturnType.js @@ -11,7 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/asyncFunctionReturnType.js b/tests/baselines/reference/asyncFunctionReturnType.js index 76f9952ab9f..dcdead47c6b 100644 --- a/tests/baselines/reference/asyncFunctionReturnType.js +++ b/tests/baselines/reference/asyncFunctionReturnType.js @@ -16,7 +16,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function fAsync() { diff --git a/tests/baselines/reference/asyncFunctionsAcrossFiles.js b/tests/baselines/reference/asyncFunctionsAcrossFiles.js index e9b5710dc07..b1a766e4e41 100644 --- a/tests/baselines/reference/asyncFunctionsAcrossFiles.js +++ b/tests/baselines/reference/asyncFunctionsAcrossFiles.js @@ -21,7 +21,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { a } from './a'; @@ -36,7 +36,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { b } from './b'; diff --git a/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js b/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js index ac9a558a53f..50ecbbb2beb 100644 --- a/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js +++ b/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js @@ -32,7 +32,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function sample(promise) { diff --git a/tests/baselines/reference/asyncIIFE.js b/tests/baselines/reference/asyncIIFE.js new file mode 100644 index 00000000000..2460dbdf26b --- /dev/null +++ b/tests/baselines/reference/asyncIIFE.js @@ -0,0 +1,28 @@ +//// [asyncIIFE.ts] + +function f1() { + (async () => { + await 10 + throw new Error(); + })(); + + var x = 1; +} + + +//// [asyncIIFE.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +function f1() { + (() => __awaiter(this, void 0, void 0, function* () { + yield 10; + throw new Error(); + }))(); + var x = 1; +} diff --git a/tests/baselines/reference/asyncIIFE.symbols b/tests/baselines/reference/asyncIIFE.symbols new file mode 100644 index 00000000000..92eb054bff0 --- /dev/null +++ b/tests/baselines/reference/asyncIIFE.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/asyncIIFE.ts === + +function f1() { +>f1 : Symbol(f1, Decl(asyncIIFE.ts, 0, 0)) + + (async () => { + await 10 + throw new Error(); +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + })(); + + var x = 1; +>x : Symbol(x, Decl(asyncIIFE.ts, 7, 7)) +} + diff --git a/tests/baselines/reference/asyncIIFE.types b/tests/baselines/reference/asyncIIFE.types new file mode 100644 index 00000000000..e49ab96681f --- /dev/null +++ b/tests/baselines/reference/asyncIIFE.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/asyncIIFE.ts === + +function f1() { +>f1 : () => void + + (async () => { +>(async () => { await 10 throw new Error(); })() : Promise +>(async () => { await 10 throw new Error(); }) : () => Promise +>async () => { await 10 throw new Error(); } : () => Promise + + await 10 +>await 10 : 10 +>10 : 10 + + throw new Error(); +>new Error() : Error +>Error : ErrorConstructor + + })(); + + var x = 1; +>x : number +>1 : 1 +} + diff --git a/tests/baselines/reference/asyncImportedPromise_es5.js b/tests/baselines/reference/asyncImportedPromise_es5.js index e5c28eb2dc1..641b8e0381f 100644 --- a/tests/baselines/reference/asyncImportedPromise_es5.js +++ b/tests/baselines/reference/asyncImportedPromise_es5.js @@ -31,7 +31,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/asyncImportedPromise_es6.js b/tests/baselines/reference/asyncImportedPromise_es6.js index 17c9de51ee6..6c6e34e7b1d 100644 --- a/tests/baselines/reference/asyncImportedPromise_es6.js +++ b/tests/baselines/reference/asyncImportedPromise_es6.js @@ -21,7 +21,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class Test { diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.js b/tests/baselines/reference/asyncMethodWithSuper_es2017.js new file mode 100644 index 00000000000..b6925793163 --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.js @@ -0,0 +1,90 @@ +//// [asyncMethodWithSuper_es2017.ts] +class A { + x() { + } +} + +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => {}; + + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + + // property access (assign) + super.x = f; + + // element access (assign) + super["x"] = f; + + // destructuring assign with property access + ({ f: super.x } = { f }); + + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} + +//// [asyncMethodWithSuper_es2017.js] +class A { + x() { + } +} +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + // call with element access + super["x"](); + // property access (read) + const a = super.x; + // element access (read) + const b = super["x"]; + } + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => { }; + // call with property access + super.x(); + // call with element access + super["x"](); + // property access (read) + const a = super.x; + // element access (read) + const b = super["x"]; + // property access (assign) + super.x = f; + // element access (assign) + super["x"] = f; + // destructuring assign with property access + ({ f: super.x } = { f }); + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols new file mode 100644 index 00000000000..39ed91d7acb --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols @@ -0,0 +1,102 @@ +=== tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts === +class A { +>A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) + + x() { +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + } +} + +class B extends A { +>B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 3, 1)) +>A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) + + // async method with only call/get on 'super' does not require a binding + async simple() { +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 5, 19)) + + // call with property access + super.x(); +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // call with element access + super["x"](); +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (read) + const a = super.x; +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 15, 13)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // element access (read) + const b = super["x"]; +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 18, 13)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 19, 5)) + + const f = () => {}; +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // call with property access + super.x(); +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // call with element access + super["x"](); +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (read) + const a = super.x; +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 32, 13)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // element access (read) + const b = super["x"]; +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 35, 13)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (assign) + super.x = f; +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // element access (assign) + super["x"] = f; +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // destructuring assign with property access + ({ f: super.x } = { f }); +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 10)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 27)) + + // destructuring assign with element access + ({ f: super["x"] } = { f }); +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 10)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 30)) + } +} diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.types b/tests/baselines/reference/asyncMethodWithSuper_es2017.types new file mode 100644 index 00000000000..b2678e8b837 --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.types @@ -0,0 +1,123 @@ +=== tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts === +class A { +>A : A + + x() { +>x : () => void + } +} + +class B extends A { +>B : B +>A : A + + // async method with only call/get on 'super' does not require a binding + async simple() { +>simple : () => Promise + + // call with property access + super.x(); +>super.x() : void +>super.x : () => void +>super : A +>x : () => void + + // call with element access + super["x"](); +>super["x"]() : void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (read) + const a = super.x; +>a : () => void +>super.x : () => void +>super : A +>x : () => void + + // element access (read) + const b = super["x"]; +>b : () => void +>super["x"] : () => void +>super : A +>"x" : "x" + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { +>advanced : () => Promise + + const f = () => {}; +>f : () => void +>() => {} : () => void + + // call with property access + super.x(); +>super.x() : void +>super.x : () => void +>super : A +>x : () => void + + // call with element access + super["x"](); +>super["x"]() : void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (read) + const a = super.x; +>a : () => void +>super.x : () => void +>super : A +>x : () => void + + // element access (read) + const b = super["x"]; +>b : () => void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (assign) + super.x = f; +>super.x = f : () => void +>super.x : () => void +>super : A +>x : () => void +>f : () => void + + // element access (assign) + super["x"] = f; +>super["x"] = f : () => void +>super["x"] : () => void +>super : A +>"x" : "x" +>f : () => void + + // destructuring assign with property access + ({ f: super.x } = { f }); +>({ f: super.x } = { f }) : { f: () => void; } +>{ f: super.x } = { f } : { f: () => void; } +>{ f: super.x } : { f: () => void; } +>f : () => void +>super.x : () => void +>super : A +>x : () => void +>{ f } : { f: () => void; } +>f : () => void + + // destructuring assign with element access + ({ f: super["x"] } = { f }); +>({ f: super["x"] } = { f }) : { f: () => void; } +>{ f: super["x"] } = { f } : { f: () => void; } +>{ f: super["x"] } : { f: () => void; } +>f : () => void +>super["x"] : () => void +>super : A +>"x" : "x" +>{ f } : { f: () => void; } +>f : () => void + } +} diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.js b/tests/baselines/reference/asyncMethodWithSuper_es5.js index 9ceff6bab4e..235f2763f9f 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.js @@ -81,8 +81,8 @@ var B = (function (_super) { // async method with assignment/destructuring on 'super' requires a binding B.prototype.advanced = function () { return __awaiter(this, void 0, void 0, function () { - var f, a, b, _a, _b; - return __generator(this, function (_c) { + var f, a, b; + return __generator(this, function (_a) { f = function () { }; // call with property access _super.prototype.x.call(this); @@ -95,9 +95,9 @@ var B = (function (_super) { // element access (assign) _super.prototype["x"] = f; // destructuring assign with property access - (_a = { f: f }, super.x = _a.f, _a); + (_super.prototype.x = { f: f }.f); // destructuring assign with element access - (_b = { f: f }, super["x"] = _b.f, _b); + (_super.prototype["x"] = { f: f }.f); return [2 /*return*/]; }); }); diff --git a/tests/baselines/reference/asyncMultiFile_es5.js b/tests/baselines/reference/asyncMultiFile_es5.js index 6b44f5393fc..547135e5c19 100644 --- a/tests/baselines/reference/asyncMultiFile_es5.js +++ b/tests/baselines/reference/asyncMultiFile_es5.js @@ -11,7 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/asyncMultiFile_es6.js b/tests/baselines/reference/asyncMultiFile_es6.js index 0c45aa6c8a3..e7dd854b95b 100644 --- a/tests/baselines/reference/asyncMultiFile_es6.js +++ b/tests/baselines/reference/asyncMultiFile_es6.js @@ -11,7 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function f() { diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js new file mode 100644 index 00000000000..c97fda43011 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js @@ -0,0 +1,9 @@ +//// [asyncUnParenthesizedArrowFunction_es2017.ts] + +declare function someOtherFunction(i: any): Promise; +const x = async i => await someOtherFunction(i) +const x1 = async (i) => await someOtherFunction(i); + +//// [asyncUnParenthesizedArrowFunction_es2017.js] +const x = async (i) => await someOtherFunction(i); +const x1 = async (i) => await someOtherFunction(i); diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols new file mode 100644 index 00000000000..b5f83de6021 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts === + +declare function someOtherFunction(i: any): Promise; +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 1, 35)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +const x = async i => await someOtherFunction(i) +>x : Symbol(x, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 5)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 15)) +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 15)) + +const x1 = async (i) => await someOtherFunction(i); +>x1 : Symbol(x1, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 5)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 18)) +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 18)) + diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types new file mode 100644 index 00000000000..ff573e29ed3 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts === + +declare function someOtherFunction(i: any): Promise; +>someOtherFunction : (i: any) => Promise +>i : any +>Promise : Promise + +const x = async i => await someOtherFunction(i) +>x : (i: any) => Promise +>async i => await someOtherFunction(i) : (i: any) => Promise +>i : any +>await someOtherFunction(i) : void +>someOtherFunction(i) : Promise +>someOtherFunction : (i: any) => Promise +>i : any + +const x1 = async (i) => await someOtherFunction(i); +>x1 : (i: any) => Promise +>async (i) => await someOtherFunction(i) : (i: any) => Promise +>i : any +>await someOtherFunction(i) : void +>someOtherFunction(i) : Promise +>someOtherFunction : (i: any) => Promise +>i : any + diff --git a/tests/baselines/reference/asyncUseStrict_es2017.js b/tests/baselines/reference/asyncUseStrict_es2017.js new file mode 100644 index 00000000000..1b9d1dc7f20 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.js @@ -0,0 +1,13 @@ +//// [asyncUseStrict_es2017.ts] +declare var a: boolean; +declare var p: Promise; +async function func(): Promise { + "use strict"; + var b = await p || a; +} + +//// [asyncUseStrict_es2017.js] +async function func() { + "use strict"; + var b = await p || a; +} diff --git a/tests/baselines/reference/asyncUseStrict_es2017.symbols b/tests/baselines/reference/asyncUseStrict_es2017.symbols new file mode 100644 index 00000000000..23fd654ca29 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.symbols @@ -0,0 +1,18 @@ +=== tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(asyncUseStrict_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(asyncUseStrict_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +async function func(): Promise { +>func : Symbol(func, Decl(asyncUseStrict_es2017.ts, 1, 32)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + "use strict"; + var b = await p || a; +>b : Symbol(b, Decl(asyncUseStrict_es2017.ts, 4, 7)) +>p : Symbol(p, Decl(asyncUseStrict_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(asyncUseStrict_es2017.ts, 0, 11)) +} diff --git a/tests/baselines/reference/asyncUseStrict_es2017.types b/tests/baselines/reference/asyncUseStrict_es2017.types new file mode 100644 index 00000000000..267eda83525 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + "use strict"; +>"use strict" : "use strict" + + var b = await p || a; +>b : boolean +>await p || a : boolean +>await p : boolean +>p : Promise +>a : boolean +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.js b/tests/baselines/reference/awaitBinaryExpression1_es2017.js new file mode 100644 index 00000000000..9016a2b5826 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression1_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p || a; + after(); +} + +//// [awaitBinaryExpression1_es2017.js] +async function func() { + before(); + var b = await p || a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols new file mode 100644 index 00000000000..827769b3db5 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression1_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression1_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression1_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression1_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression1_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression1_es2017.ts, 1, 32)) + + var b = await p || a; +>b : Symbol(b, Decl(awaitBinaryExpression1_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression1_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression1_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression1_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.types b/tests/baselines/reference/awaitBinaryExpression1_es2017.types new file mode 100644 index 00000000000..c86631804c5 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p || a; +>b : boolean +>await p || a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.js b/tests/baselines/reference/awaitBinaryExpression2_es2017.js new file mode 100644 index 00000000000..1d5ad324fda --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression2_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p && a; + after(); +} + +//// [awaitBinaryExpression2_es2017.js] +async function func() { + before(); + var b = await p && a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols new file mode 100644 index 00000000000..549eb49cf92 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression2_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression2_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression2_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression2_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression2_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression2_es2017.ts, 1, 32)) + + var b = await p && a; +>b : Symbol(b, Decl(awaitBinaryExpression2_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression2_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression2_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression2_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.types b/tests/baselines/reference/awaitBinaryExpression2_es2017.types new file mode 100644 index 00000000000..f803b1ac840 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p && a; +>b : boolean +>await p && a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.js b/tests/baselines/reference/awaitBinaryExpression3_es2017.js new file mode 100644 index 00000000000..c752ec3be4a --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression3_es2017.ts] +declare var a: number; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p + a; + after(); +} + +//// [awaitBinaryExpression3_es2017.js] +async function func() { + before(); + var b = await p + a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols new file mode 100644 index 00000000000..29c8fb7f398 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts === +declare var a: number; +>a : Symbol(a, Decl(awaitBinaryExpression3_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression3_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression3_es2017.ts, 1, 31)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression3_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression3_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression3_es2017.ts, 1, 31)) + + var b = await p + a; +>b : Symbol(b, Decl(awaitBinaryExpression3_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression3_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression3_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression3_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.types b/tests/baselines/reference/awaitBinaryExpression3_es2017.types new file mode 100644 index 00000000000..623d0695237 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts === +declare var a: number; +>a : number + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p + a; +>b : number +>await p + a : number +>await p : number +>p : Promise +>a : number + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.js b/tests/baselines/reference/awaitBinaryExpression4_es2017.js new file mode 100644 index 00000000000..3fc296ea142 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression4_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await p, a); + after(); +} + +//// [awaitBinaryExpression4_es2017.js] +async function func() { + before(); + var b = (await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols new file mode 100644 index 00000000000..0db5a20e0c1 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression4_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression4_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression4_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression4_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression4_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression4_es2017.ts, 1, 32)) + + var b = (await p, a); +>b : Symbol(b, Decl(awaitBinaryExpression4_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression4_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression4_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression4_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.types b/tests/baselines/reference/awaitBinaryExpression4_es2017.types new file mode 100644 index 00000000000..714b6b1ea3a --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.types @@ -0,0 +1,34 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await p, a); +>b : boolean +>(await p, a) : boolean +>await p, a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.js b/tests/baselines/reference/awaitBinaryExpression5_es2017.js new file mode 100644 index 00000000000..b6c5e12ce76 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.js @@ -0,0 +1,19 @@ +//// [awaitBinaryExpression5_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var o: { a: boolean; }; + o.a = await p; + after(); +} + +//// [awaitBinaryExpression5_es2017.js] +async function func() { + before(); + var o; + o.a = await p; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols new file mode 100644 index 00000000000..e2d30c658f7 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression5_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression5_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression5_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression5_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression5_es2017.ts, 1, 32)) + + var o: { a: boolean; }; +>o : Symbol(o, Decl(awaitBinaryExpression5_es2017.ts, 6, 7)) +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) + + o.a = await p; +>o.a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) +>o : Symbol(o, Decl(awaitBinaryExpression5_es2017.ts, 6, 7)) +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) +>p : Symbol(p, Decl(awaitBinaryExpression5_es2017.ts, 1, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression5_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.types b/tests/baselines/reference/awaitBinaryExpression5_es2017.types new file mode 100644 index 00000000000..763f9e50862 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var o: { a: boolean; }; +>o : { a: boolean; } +>a : boolean + + o.a = await p; +>o.a = await p : boolean +>o.a : boolean +>o : { a: boolean; } +>a : boolean +>await p : boolean +>p : Promise + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.js b/tests/baselines/reference/awaitCallExpression1_es2017.js new file mode 100644 index 00000000000..89fe7dfd912 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression1_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, a, a); + after(); +} + +//// [awaitCallExpression1_es2017.js] +async function func() { + before(); + var b = fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.symbols b/tests/baselines/reference/awaitCallExpression1_es2017.symbols new file mode 100644 index 00000000000..68c28d15350 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression1_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression1_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression1_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression1_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression1_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression1_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression1_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression1_es2017.ts, 5, 84)) + + var b = fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression1_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 1, 32)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression1_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.types b/tests/baselines/reference/awaitCallExpression1_es2017.types new file mode 100644 index 00000000000..c5cea091878 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.types @@ -0,0 +1,62 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(a, a, a); +>b : void +>fn(a, a, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.js b/tests/baselines/reference/awaitCallExpression2_es2017.js new file mode 100644 index 00000000000..24b3012f85d --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression2_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(await p, a, a); + after(); +} + +//// [awaitCallExpression2_es2017.js] +async function func() { + before(); + var b = fn(await p, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.symbols b/tests/baselines/reference/awaitCallExpression2_es2017.symbols new file mode 100644 index 00000000000..4528ae4c074 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression2_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression2_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression2_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression2_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression2_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression2_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression2_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression2_es2017.ts, 5, 84)) + + var b = fn(await p, a, a); +>b : Symbol(b, Decl(awaitCallExpression2_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 1, 32)) +>p : Symbol(p, Decl(awaitCallExpression2_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression2_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.types b/tests/baselines/reference/awaitCallExpression2_es2017.types new file mode 100644 index 00000000000..a15609a4078 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.types @@ -0,0 +1,63 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(await p, a, a); +>b : void +>fn(await p, a, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await p : boolean +>p : Promise +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.js b/tests/baselines/reference/awaitCallExpression3_es2017.js new file mode 100644 index 00000000000..6b432851b00 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression3_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, await p, a); + after(); +} + +//// [awaitCallExpression3_es2017.js] +async function func() { + before(); + var b = fn(a, await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.symbols b/tests/baselines/reference/awaitCallExpression3_es2017.symbols new file mode 100644 index 00000000000..a1120103fb0 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression3_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression3_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression3_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression3_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression3_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression3_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression3_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression3_es2017.ts, 5, 84)) + + var b = fn(a, await p, a); +>b : Symbol(b, Decl(awaitCallExpression3_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 1, 32)) +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) +>p : Symbol(p, Decl(awaitCallExpression3_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression3_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.types b/tests/baselines/reference/awaitCallExpression3_es2017.types new file mode 100644 index 00000000000..a491836fa06 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.types @@ -0,0 +1,63 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(a, await p, a); +>b : void +>fn(a, await p, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.js b/tests/baselines/reference/awaitCallExpression4_es2017.js new file mode 100644 index 00000000000..9243ac58f82 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression4_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await pfn)(a, a, a); + after(); +} + +//// [awaitCallExpression4_es2017.js] +async function func() { + before(); + var b = (await pfn)(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.symbols b/tests/baselines/reference/awaitCallExpression4_es2017.symbols new file mode 100644 index 00000000000..fb607d9841f --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression4_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression4_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression4_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression4_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression4_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression4_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression4_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression4_es2017.ts, 5, 84)) + + var b = (await pfn)(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression4_es2017.ts, 10, 7)) +>pfn : Symbol(pfn, Decl(awaitCallExpression4_es2017.ts, 4, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression4_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.types b/tests/baselines/reference/awaitCallExpression4_es2017.types new file mode 100644 index 00000000000..3f1b478e669 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.types @@ -0,0 +1,64 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await pfn)(a, a, a); +>b : void +>(await pfn)(a, a, a) : void +>(await pfn) : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await pfn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.js b/tests/baselines/reference/awaitCallExpression5_es2017.js new file mode 100644 index 00000000000..d08823ac5a3 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression5_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, a, a); + after(); +} + +//// [awaitCallExpression5_es2017.js] +async function func() { + before(); + var b = o.fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.symbols b/tests/baselines/reference/awaitCallExpression5_es2017.symbols new file mode 100644 index 00000000000..3854353314a --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression5_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression5_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression5_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression5_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression5_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression5_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression5_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression5_es2017.ts, 5, 84)) + + var b = o.fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression5_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression5_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression5_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.types b/tests/baselines/reference/awaitCallExpression5_es2017.types new file mode 100644 index 00000000000..f31320e44f7 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.types @@ -0,0 +1,64 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(a, a, a); +>b : void +>o.fn(a, a, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.js b/tests/baselines/reference/awaitCallExpression6_es2017.js new file mode 100644 index 00000000000..77a47ba8065 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression6_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(await p, a, a); + after(); +} + +//// [awaitCallExpression6_es2017.js] +async function func() { + before(); + var b = o.fn(await p, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.symbols b/tests/baselines/reference/awaitCallExpression6_es2017.symbols new file mode 100644 index 00000000000..6a651510328 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression6_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression6_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression6_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression6_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression6_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression6_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression6_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression6_es2017.ts, 5, 84)) + + var b = o.fn(await p, a, a); +>b : Symbol(b, Decl(awaitCallExpression6_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression6_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>p : Symbol(p, Decl(awaitCallExpression6_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression6_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.types b/tests/baselines/reference/awaitCallExpression6_es2017.types new file mode 100644 index 00000000000..ccce4cad366 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.types @@ -0,0 +1,65 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(await p, a, a); +>b : void +>o.fn(await p, a, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await p : boolean +>p : Promise +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.js b/tests/baselines/reference/awaitCallExpression7_es2017.js new file mode 100644 index 00000000000..b3391ced6b6 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression7_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, await p, a); + after(); +} + +//// [awaitCallExpression7_es2017.js] +async function func() { + before(); + var b = o.fn(a, await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.symbols b/tests/baselines/reference/awaitCallExpression7_es2017.symbols new file mode 100644 index 00000000000..e95078c6850 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression7_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression7_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression7_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression7_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression7_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression7_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression7_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression7_es2017.ts, 5, 84)) + + var b = o.fn(a, await p, a); +>b : Symbol(b, Decl(awaitCallExpression7_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression7_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) +>p : Symbol(p, Decl(awaitCallExpression7_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression7_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.types b/tests/baselines/reference/awaitCallExpression7_es2017.types new file mode 100644 index 00000000000..aefe7916852 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.types @@ -0,0 +1,65 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(a, await p, a); +>b : void +>o.fn(a, await p, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.js b/tests/baselines/reference/awaitCallExpression8_es2017.js new file mode 100644 index 00000000000..7e04402e90a --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression8_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await po).fn(a, a, a); + after(); +} + +//// [awaitCallExpression8_es2017.js] +async function func() { + before(); + var b = (await po).fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.symbols b/tests/baselines/reference/awaitCallExpression8_es2017.symbols new file mode 100644 index 00000000000..e3fd465c120 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression8_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression8_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression8_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression8_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression8_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression8_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression8_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression8_es2017.ts, 5, 84)) + + var b = (await po).fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression8_es2017.ts, 10, 7)) +>(await po).fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>po : Symbol(po, Decl(awaitCallExpression8_es2017.ts, 5, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression8_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.types b/tests/baselines/reference/awaitCallExpression8_es2017.types new file mode 100644 index 00000000000..a9a115d39f2 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.types @@ -0,0 +1,66 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await po).fn(a, a, a); +>b : void +>(await po).fn(a, a, a) : void +>(await po).fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>(await po) : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>await po : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.js b/tests/baselines/reference/awaitClassExpression_es2017.js new file mode 100644 index 00000000000..d84f01f61cf --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.js @@ -0,0 +1,14 @@ +//// [awaitClassExpression_es2017.ts] +declare class C { } +declare var p: Promise; + +async function func(): Promise { + class D extends (await p) { + } +} + +//// [awaitClassExpression_es2017.js] +async function func() { + class D extends (await p) { + } +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.symbols b/tests/baselines/reference/awaitClassExpression_es2017.symbols new file mode 100644 index 00000000000..bebffa2bbad --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.symbols @@ -0,0 +1,18 @@ +=== tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts === +declare class C { } +>C : Symbol(C, Decl(awaitClassExpression_es2017.ts, 0, 0)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitClassExpression_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>C : Symbol(C, Decl(awaitClassExpression_es2017.ts, 0, 0)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitClassExpression_es2017.ts, 1, 33)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + class D extends (await p) { +>D : Symbol(D, Decl(awaitClassExpression_es2017.ts, 3, 38)) +>p : Symbol(p, Decl(awaitClassExpression_es2017.ts, 1, 11)) + } +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.types b/tests/baselines/reference/awaitClassExpression_es2017.types new file mode 100644 index 00000000000..39d17b1cc50 --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.types @@ -0,0 +1,20 @@ +=== tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts === +declare class C { } +>C : C + +declare var p: Promise; +>p : Promise +>Promise : Promise +>C : typeof C + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + class D extends (await p) { +>D : D +>(await p) : C +>await p : typeof C +>p : Promise + } +} diff --git a/tests/baselines/reference/awaitInheritedPromise_es2017.js b/tests/baselines/reference/awaitInheritedPromise_es2017.js new file mode 100644 index 00000000000..e973d0b166a --- /dev/null +++ b/tests/baselines/reference/awaitInheritedPromise_es2017.js @@ -0,0 +1,11 @@ +//// [awaitInheritedPromise_es2017.ts] +interface A extends Promise {} +declare var a: A; +async function f() { + await a; +} + +//// [awaitInheritedPromise_es2017.js] +async function f() { + await a; +} diff --git a/tests/baselines/reference/awaitInheritedPromise_es2017.symbols b/tests/baselines/reference/awaitInheritedPromise_es2017.symbols new file mode 100644 index 00000000000..ef68d16b678 --- /dev/null +++ b/tests/baselines/reference/awaitInheritedPromise_es2017.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/async/es2017/awaitInheritedPromise_es2017.ts === +interface A extends Promise {} +>A : Symbol(A, Decl(awaitInheritedPromise_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare var a: A; +>a : Symbol(a, Decl(awaitInheritedPromise_es2017.ts, 1, 11)) +>A : Symbol(A, Decl(awaitInheritedPromise_es2017.ts, 0, 0)) + +async function f() { +>f : Symbol(f, Decl(awaitInheritedPromise_es2017.ts, 1, 17)) + + await a; +>a : Symbol(a, Decl(awaitInheritedPromise_es2017.ts, 1, 11)) +} diff --git a/tests/baselines/reference/awaitInheritedPromise_es2017.types b/tests/baselines/reference/awaitInheritedPromise_es2017.types new file mode 100644 index 00000000000..bed681181b0 --- /dev/null +++ b/tests/baselines/reference/awaitInheritedPromise_es2017.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/async/es2017/awaitInheritedPromise_es2017.ts === +interface A extends Promise {} +>A : A +>Promise : Promise + +declare var a: A; +>a : A +>A : A + +async function f() { +>f : () => Promise + + await a; +>await a : string +>a : A +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.js b/tests/baselines/reference/await_unaryExpression_es2017.js new file mode 100644 index 00000000000..83fce6588e6 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.js @@ -0,0 +1,31 @@ +//// [await_unaryExpression_es2017.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} + +//// [await_unaryExpression_es2017.js] +async function bar() { + !await 42; // OK +} +async function bar1() { + +await 42; // OK +} +async function bar3() { + -await 42; // OK +} +async function bar4() { + ~await 42; // OK +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.symbols b/tests/baselines/reference/await_unaryExpression_es2017.symbols new file mode 100644 index 00000000000..1aa31031177 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.symbols @@ -0,0 +1,25 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es2017.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017.ts, 3, 1)) + + +await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017.ts, 7, 1)) + + -await 42; // OK +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es2017.ts, 11, 1)) + + ~await 42; // OK +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.types b/tests/baselines/reference/await_unaryExpression_es2017.types new file mode 100644 index 00000000000..4f4254df318 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar1() { +>bar1 : () => Promise + + +await 42; // OK +>+await 42 : number +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + -await 42; // OK +>-await 42 : number +>await 42 : 42 +>42 : 42 +} + +async function bar4() { +>bar4 : () => Promise + + ~await 42; // OK +>~await 42 : number +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.js b/tests/baselines/reference/await_unaryExpression_es2017_1.js new file mode 100644 index 00000000000..f863fb19a7e --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.js @@ -0,0 +1,38 @@ +//// [await_unaryExpression_es2017_1.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} + +//// [await_unaryExpression_es2017_1.js] +async function bar() { + !await 42; // OK +} +async function bar1() { + delete await 42; // OK +} +async function bar2() { + delete await 42; // OK +} +async function bar3() { + void await 42; +} +async function bar4() { + +await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.symbols b/tests/baselines/reference/await_unaryExpression_es2017_1.symbols new file mode 100644 index 00000000000..81bb31a7efd --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es2017_1.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017_1.ts, 3, 1)) + + delete await 42; // OK +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es2017_1.ts, 7, 1)) + + delete await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017_1.ts, 11, 1)) + + void await 42; +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es2017_1.ts, 15, 1)) + + +await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.types b/tests/baselines/reference/await_unaryExpression_es2017_1.types new file mode 100644 index 00000000000..7afa4fe9001 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.types @@ -0,0 +1,46 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar1() { +>bar1 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : 42 +>42 : 42 +} + +async function bar4() { +>bar4 : () => Promise + + +await 42; +>+await 42 : number +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.js b/tests/baselines/reference/await_unaryExpression_es2017_2.js new file mode 100644 index 00000000000..b982b20245c --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.js @@ -0,0 +1,24 @@ +//// [await_unaryExpression_es2017_2.ts] + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} + +//// [await_unaryExpression_es2017_2.js] +async function bar1() { + delete await 42; +} +async function bar2() { + delete await 42; +} +async function bar3() { + void await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.symbols b/tests/baselines/reference/await_unaryExpression_es2017_2.symbols new file mode 100644 index 00000000000..d4b8a7493d9 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts === + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017_2.ts, 0, 0)) + + delete await 42; +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es2017_2.ts, 3, 1)) + + delete await 42; +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017_2.ts, 7, 1)) + + void await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.types b/tests/baselines/reference/await_unaryExpression_es2017_2.types new file mode 100644 index 00000000000..acaa76d2d67 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts === + +async function bar1() { +>bar1 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt b/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt new file mode 100644 index 00000000000..5d11c4bbb20 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt @@ -0,0 +1,27 @@ +tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts(3,7): error TS1109: Expression expected. +tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts(7,7): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts (2 errors) ==== + + async function bar1() { + ++await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar2() { + --await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis + } + + async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis + } \ No newline at end of file diff --git a/tests/baselines/reference/await_unaryExpression_es2017_3.js b/tests/baselines/reference/await_unaryExpression_es2017_3.js new file mode 100644 index 00000000000..5e3c3c3a4bf --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_3.js @@ -0,0 +1,37 @@ +//// [await_unaryExpression_es2017_3.ts] + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} + +//// [await_unaryExpression_es2017_3.js] +async function bar1() { + ++; + await 42; // Error +} +async function bar2() { + --; + await 42; // Error +} +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} diff --git a/tests/baselines/reference/await_unaryExpression_es6.js b/tests/baselines/reference/await_unaryExpression_es6.js index 6609cc6f3f4..f9183f7af3e 100644 --- a/tests/baselines/reference/await_unaryExpression_es6.js +++ b/tests/baselines/reference/await_unaryExpression_es6.js @@ -22,7 +22,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function bar() { diff --git a/tests/baselines/reference/await_unaryExpression_es6_1.js b/tests/baselines/reference/await_unaryExpression_es6_1.js index 48f50d76f4a..948e537cb01 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_1.js +++ b/tests/baselines/reference/await_unaryExpression_es6_1.js @@ -26,7 +26,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function bar() { diff --git a/tests/baselines/reference/await_unaryExpression_es6_2.js b/tests/baselines/reference/await_unaryExpression_es6_2.js index 5e9d63a21d2..4b4c1cd6513 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_2.js +++ b/tests/baselines/reference/await_unaryExpression_es6_2.js @@ -18,7 +18,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function bar1() { diff --git a/tests/baselines/reference/await_unaryExpression_es6_3.js b/tests/baselines/reference/await_unaryExpression_es6_3.js index 469c8ea3ee9..6db5d5a7c31 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_3.js +++ b/tests/baselines/reference/await_unaryExpression_es6_3.js @@ -24,7 +24,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function bar1() { diff --git a/tests/baselines/reference/baseTypeAfterDerivedType.js b/tests/baselines/reference/baseTypeAfterDerivedType.js index b80b62712f5..c4ca7cf7b33 100644 --- a/tests/baselines/reference/baseTypeAfterDerivedType.js +++ b/tests/baselines/reference/baseTypeAfterDerivedType.js @@ -23,7 +23,7 @@ var Derived2 = (function () { Derived2.prototype.method = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } }; return Derived2; diff --git a/tests/baselines/reference/bluebirdStaticThis.js b/tests/baselines/reference/bluebirdStaticThis.js index 301f32319a7..606f778323f 100644 --- a/tests/baselines/reference/bluebirdStaticThis.js +++ b/tests/baselines/reference/bluebirdStaticThis.js @@ -146,12 +146,12 @@ var x; var arr; var foo; var fooProm; -fooProm = Promise.try(Promise, function () { +fooProm = Promise["try"](Promise, function () { return foo; }); -fooProm = Promise.try(Promise, function () { +fooProm = Promise["try"](Promise, function () { return foo; }, arr); -fooProm = Promise.try(Promise, function () { +fooProm = Promise["try"](Promise, function () { return foo; }, arr, x); diff --git a/tests/baselines/reference/cacheResolutions.js b/tests/baselines/reference/cacheResolutions.js new file mode 100644 index 00000000000..1d0f918bf98 --- /dev/null +++ b/tests/baselines/reference/cacheResolutions.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/cacheResolutions.ts] //// + +//// [app.ts] + +export let x = 1; + +//// [lib1.ts] +export let x = 1; + +//// [lib2.ts] +export let x = 1; + +//// [app.js] +define(["require", "exports"], function (require, exports) { + "use strict"; + exports.x = 1; +}); +//// [lib1.js] +define(["require", "exports"], function (require, exports) { + "use strict"; + exports.x = 1; +}); +//// [lib2.js] +define(["require", "exports"], function (require, exports) { + "use strict"; + exports.x = 1; +}); diff --git a/tests/baselines/reference/cacheResolutions.symbols b/tests/baselines/reference/cacheResolutions.symbols new file mode 100644 index 00000000000..362ce5c308c --- /dev/null +++ b/tests/baselines/reference/cacheResolutions.symbols @@ -0,0 +1,13 @@ +=== /a/b/c/app.ts === + +export let x = 1; +>x : Symbol(x, Decl(app.ts, 1, 10)) + +=== /a/b/c/lib1.ts === +export let x = 1; +>x : Symbol(x, Decl(lib1.ts, 0, 10)) + +=== /a/b/c/lib2.ts === +export let x = 1; +>x : Symbol(x, Decl(lib2.ts, 0, 10)) + diff --git a/tests/baselines/reference/cacheResolutions.trace.json b/tests/baselines/reference/cacheResolutions.trace.json new file mode 100644 index 00000000000..8e7adfb9898 --- /dev/null +++ b/tests/baselines/reference/cacheResolutions.trace.json @@ -0,0 +1,43 @@ +[ + "======== Resolving module 'tslib' from '/a/b/c/app.ts'. ========", + "Module resolution kind is not specified, using 'Classic'.", + "File '/a/b/c/tslib.ts' does not exist.", + "File '/a/b/c/tslib.tsx' does not exist.", + "File '/a/b/c/tslib.d.ts' does not exist.", + "File '/a/b/tslib.ts' does not exist.", + "File '/a/b/tslib.tsx' does not exist.", + "File '/a/b/tslib.d.ts' does not exist.", + "File '/a/tslib.ts' does not exist.", + "File '/a/tslib.tsx' does not exist.", + "File '/a/tslib.d.ts' does not exist.", + "File '/tslib.ts' does not exist.", + "File '/tslib.tsx' does not exist.", + "File '/tslib.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/tslib.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/tslib/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/tslib/index.d.ts' does not exist.", + "File '/a/b/node_modules/@types/tslib.d.ts' does not exist.", + "File '/a/b/node_modules/@types/tslib/package.json' does not exist.", + "File '/a/b/node_modules/@types/tslib/index.d.ts' does not exist.", + "File '/a/node_modules/@types/tslib.d.ts' does not exist.", + "File '/a/node_modules/@types/tslib/package.json' does not exist.", + "File '/a/node_modules/@types/tslib/index.d.ts' does not exist.", + "File '/node_modules/@types/tslib.d.ts' does not exist.", + "File '/node_modules/@types/tslib/package.json' does not exist.", + "File '/node_modules/@types/tslib/index.d.ts' does not exist.", + "File '/a/b/c/tslib.js' does not exist.", + "File '/a/b/c/tslib.jsx' does not exist.", + "File '/a/b/tslib.js' does not exist.", + "File '/a/b/tslib.jsx' does not exist.", + "File '/a/tslib.js' does not exist.", + "File '/a/tslib.jsx' does not exist.", + "File '/tslib.js' does not exist.", + "File '/tslib.jsx' does not exist.", + "======== Module name 'tslib' was not resolved. ========", + "======== Resolving module 'tslib' from '/a/b/c/lib1.ts'. ========", + "Resolution for module 'tslib' was found in cache", + "======== Module name 'tslib' was not resolved. ========", + "======== Resolving module 'tslib' from '/a/b/c/lib2.ts'. ========", + "Resolution for module 'tslib' was found in cache", + "======== Module name 'tslib' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cacheResolutions.types b/tests/baselines/reference/cacheResolutions.types new file mode 100644 index 00000000000..fdcc0a6c46c --- /dev/null +++ b/tests/baselines/reference/cacheResolutions.types @@ -0,0 +1,16 @@ +=== /a/b/c/app.ts === + +export let x = 1; +>x : number +>1 : 1 + +=== /a/b/c/lib1.ts === +export let x = 1; +>x : number +>1 : 1 + +=== /a/b/c/lib2.ts === +export let x = 1; +>x : number +>1 : 1 + diff --git a/tests/baselines/reference/cachedModuleResolution1.js b/tests/baselines/reference/cachedModuleResolution1.js new file mode 100644 index 00000000000..9071b60d6c1 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution1.js @@ -0,0 +1,16 @@ +//// [tests/cases/compiler/cachedModuleResolution1.ts] //// + +//// [foo.d.ts] + +export declare let x: number + +//// [app.ts] +import {x} from "foo"; + +//// [lib.ts] +import {x} from "foo"; + +//// [app.js] +"use strict"; +//// [lib.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution1.symbols b/tests/baselines/reference/cachedModuleResolution1.symbols new file mode 100644 index 00000000000..f7d3c474a56 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution1.symbols @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : Symbol(x, Decl(foo.d.ts, 1, 18)) + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(lib.ts, 0, 8)) + diff --git a/tests/baselines/reference/cachedModuleResolution1.trace.json b/tests/baselines/reference/cachedModuleResolution1.trace.json new file mode 100644 index 00000000000..dbb0e6068be --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution1.trace.json @@ -0,0 +1,46 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo.ts' does not exist.", + "File '/a/b/c/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/foo.ts' does not exist.", + "File '/a/b/node_modules/foo.tsx' does not exist.", + "File '/a/b/node_modules/foo.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========", + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "Resolution for module 'foo' was found in cache", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution1.types b/tests/baselines/reference/cachedModuleResolution1.types new file mode 100644 index 00000000000..c041e8cc340 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution1.types @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : number + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : number + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : number + diff --git a/tests/baselines/reference/cachedModuleResolution2.js b/tests/baselines/reference/cachedModuleResolution2.js new file mode 100644 index 00000000000..7c84a92abaf --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution2.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/cachedModuleResolution2.ts] //// + +//// [foo.d.ts] + +export declare let x: number + +//// [lib.ts] +import {x} from "foo"; + +//// [app.ts] +import {x} from "foo"; + + +//// [lib.js] +"use strict"; +//// [app.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution2.symbols b/tests/baselines/reference/cachedModuleResolution2.symbols new file mode 100644 index 00000000000..c8356eadb11 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution2.symbols @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : Symbol(x, Decl(foo.d.ts, 1, 18)) + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(lib.ts, 0, 8)) + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + diff --git a/tests/baselines/reference/cachedModuleResolution2.trace.json b/tests/baselines/reference/cachedModuleResolution2.trace.json new file mode 100644 index 00000000000..1d4b40bbc08 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution2.trace.json @@ -0,0 +1,46 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/node_modules/foo.ts' does not exist.", + "File '/a/b/c/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/foo.ts' does not exist.", + "File '/a/b/node_modules/foo.tsx' does not exist.", + "File '/a/b/node_modules/foo.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========", + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "Resolution for module 'foo' was found in cache", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution2.types b/tests/baselines/reference/cachedModuleResolution2.types new file mode 100644 index 00000000000..c5069e681c4 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution2.types @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : number + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : number + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : number + diff --git a/tests/baselines/reference/cachedModuleResolution3.js b/tests/baselines/reference/cachedModuleResolution3.js new file mode 100644 index 00000000000..032c1afee0e --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution3.js @@ -0,0 +1,16 @@ +//// [tests/cases/compiler/cachedModuleResolution3.ts] //// + +//// [foo.d.ts] + +export declare let x: number + +//// [app.ts] +import {x} from "foo"; + +//// [lib.ts] +import {x} from "foo"; + +//// [app.js] +"use strict"; +//// [lib.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution3.symbols b/tests/baselines/reference/cachedModuleResolution3.symbols new file mode 100644 index 00000000000..799ac6d8d84 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution3.symbols @@ -0,0 +1,13 @@ +=== /a/b/foo.d.ts === + +export declare let x: number +>x : Symbol(x, Decl(foo.d.ts, 1, 18)) + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(lib.ts, 0, 8)) + diff --git a/tests/baselines/reference/cachedModuleResolution3.trace.json b/tests/baselines/reference/cachedModuleResolution3.trace.json new file mode 100644 index 00000000000..2dbaea53f47 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution3.trace.json @@ -0,0 +1,21 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/d/e/foo.ts' does not exist.", + "File '/a/b/c/d/e/foo.tsx' does not exist.", + "File '/a/b/c/d/e/foo.d.ts' does not exist.", + "File '/a/b/c/d/foo.ts' does not exist.", + "File '/a/b/c/d/foo.tsx' does not exist.", + "File '/a/b/c/d/foo.d.ts' does not exist.", + "File '/a/b/c/foo.ts' does not exist.", + "File '/a/b/c/foo.tsx' does not exist.", + "File '/a/b/c/foo.d.ts' does not exist.", + "File '/a/b/foo.ts' does not exist.", + "File '/a/b/foo.tsx' does not exist.", + "File '/a/b/foo.d.ts' exist - use it as a name resolution result.", + "======== Module name 'foo' was successfully resolved to '/a/b/foo.d.ts'. ========", + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was successfully resolved to '/a/b/foo.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution3.types b/tests/baselines/reference/cachedModuleResolution3.types new file mode 100644 index 00000000000..f87abf1519e --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution3.types @@ -0,0 +1,13 @@ +=== /a/b/foo.d.ts === + +export declare let x: number +>x : number + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : number + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : number + diff --git a/tests/baselines/reference/cachedModuleResolution4.js b/tests/baselines/reference/cachedModuleResolution4.js new file mode 100644 index 00000000000..6089de9706b --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution4.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/cachedModuleResolution4.ts] //// + +//// [foo.d.ts] + +export declare let x: number + +//// [lib.ts] +import {x} from "foo"; + +//// [app.ts] +import {x} from "foo"; + + +//// [lib.js] +"use strict"; +//// [app.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution4.symbols b/tests/baselines/reference/cachedModuleResolution4.symbols new file mode 100644 index 00000000000..a30e6bf74e5 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution4.symbols @@ -0,0 +1,13 @@ +=== /a/b/foo.d.ts === + +export declare let x: number +>x : Symbol(x, Decl(foo.d.ts, 1, 18)) + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(lib.ts, 0, 8)) + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + diff --git a/tests/baselines/reference/cachedModuleResolution4.trace.json b/tests/baselines/reference/cachedModuleResolution4.trace.json new file mode 100644 index 00000000000..7249d948e1c --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution4.trace.json @@ -0,0 +1,21 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/foo.ts' does not exist.", + "File '/a/b/c/foo.tsx' does not exist.", + "File '/a/b/c/foo.d.ts' does not exist.", + "File '/a/b/foo.ts' does not exist.", + "File '/a/b/foo.tsx' does not exist.", + "File '/a/b/foo.d.ts' exist - use it as a name resolution result.", + "======== Module name 'foo' was successfully resolved to '/a/b/foo.d.ts'. ========", + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/d/e/foo.ts' does not exist.", + "File '/a/b/c/d/e/foo.tsx' does not exist.", + "File '/a/b/c/d/e/foo.d.ts' does not exist.", + "File '/a/b/c/d/foo.ts' does not exist.", + "File '/a/b/c/d/foo.tsx' does not exist.", + "File '/a/b/c/d/foo.d.ts' does not exist.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was successfully resolved to '/a/b/foo.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution4.types b/tests/baselines/reference/cachedModuleResolution4.types new file mode 100644 index 00000000000..3689e57ca6d --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution4.types @@ -0,0 +1,13 @@ +=== /a/b/foo.d.ts === + +export declare let x: number +>x : number + +=== /a/b/c/lib.ts === +import {x} from "foo"; +>x : number + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : number + diff --git a/tests/baselines/reference/cachedModuleResolution5.js b/tests/baselines/reference/cachedModuleResolution5.js new file mode 100644 index 00000000000..33561e8eae2 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution5.js @@ -0,0 +1,16 @@ +//// [tests/cases/compiler/cachedModuleResolution5.ts] //// + +//// [foo.d.ts] + +export declare let x: number + +//// [app.ts] +import {x} from "foo"; + +//// [lib.ts] +import {x} from "foo"; + +//// [app.js] +"use strict"; +//// [lib.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution5.symbols b/tests/baselines/reference/cachedModuleResolution5.symbols new file mode 100644 index 00000000000..eb72f0c7a27 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution5.symbols @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : Symbol(x, Decl(foo.d.ts, 1, 18)) + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + +=== /a/b/lib.ts === +import {x} from "foo"; +>x : Symbol(x, Decl(lib.ts, 0, 8)) + diff --git a/tests/baselines/reference/cachedModuleResolution5.trace.json b/tests/baselines/reference/cachedModuleResolution5.trace.json new file mode 100644 index 00000000000..d263465ff12 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution5.trace.json @@ -0,0 +1,46 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo.ts' does not exist.", + "File '/a/b/c/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/foo.ts' does not exist.", + "File '/a/b/node_modules/foo.tsx' does not exist.", + "File '/a/b/node_modules/foo.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========", + "======== Resolving module 'foo' from '/a/b/lib.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "Resolution for module 'foo' was found in cache", + "Resolving real path for '/a/b/node_modules/foo.d.ts', result '/a/b/node_modules/foo.d.ts'", + "======== Module name 'foo' was successfully resolved to '/a/b/node_modules/foo.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution5.types b/tests/baselines/reference/cachedModuleResolution5.types new file mode 100644 index 00000000000..ad2640402f7 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution5.types @@ -0,0 +1,13 @@ +=== /a/b/node_modules/foo.d.ts === + +export declare let x: number +>x : number + +=== /a/b/c/d/e/app.ts === +import {x} from "foo"; +>x : number + +=== /a/b/lib.ts === +import {x} from "foo"; +>x : number + diff --git a/tests/baselines/reference/cachedModuleResolution6.errors.txt b/tests/baselines/reference/cachedModuleResolution6.errors.txt new file mode 100644 index 00000000000..b272ff29b9d --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution6.errors.txt @@ -0,0 +1,14 @@ +/a/b/c/d/e/app.ts(2,17): error TS2307: Cannot find module 'foo'. +/a/b/c/lib.ts(1,17): error TS2307: Cannot find module 'foo'. + + +==== /a/b/c/d/e/app.ts (1 errors) ==== + + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + +==== /a/b/c/lib.ts (1 errors) ==== + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution6.js b/tests/baselines/reference/cachedModuleResolution6.js new file mode 100644 index 00000000000..f21f491a921 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution6.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/cachedModuleResolution6.ts] //// + +//// [app.ts] + +import {x} from "foo"; + +//// [lib.ts] +import {x} from "foo"; + +//// [app.js] +"use strict"; +//// [lib.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution6.trace.json b/tests/baselines/reference/cachedModuleResolution6.trace.json new file mode 100644 index 00000000000..02d52befc94 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution6.trace.json @@ -0,0 +1,102 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo.ts' does not exist.", + "File '/a/b/c/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/foo.ts' does not exist.", + "File '/a/b/node_modules/foo.tsx' does not exist.", + "File '/a/b/node_modules/foo.d.ts' does not exist.", + "File '/a/b/node_modules/foo/package.json' does not exist.", + "File '/a/b/node_modules/foo/index.ts' does not exist.", + "File '/a/b/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/node_modules/foo.ts' does not exist.", + "File '/a/node_modules/foo.tsx' does not exist.", + "File '/a/node_modules/foo.d.ts' does not exist.", + "File '/a/node_modules/foo/package.json' does not exist.", + "File '/a/node_modules/foo/index.ts' does not exist.", + "File '/a/node_modules/foo/index.tsx' does not exist.", + "File '/a/node_modules/foo/index.d.ts' does not exist.", + "File '/a/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/node_modules/@types/foo/package.json' does not exist.", + "File '/a/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/node_modules/foo.ts' does not exist.", + "File '/node_modules/foo.tsx' does not exist.", + "File '/node_modules/foo.d.ts' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.ts' does not exist.", + "File '/node_modules/foo/index.tsx' does not exist.", + "File '/node_modules/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.js' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.jsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.js' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.jsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.js' does not exist.", + "File '/a/b/c/d/node_modules/foo.jsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.js' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.jsx' does not exist.", + "File '/a/b/c/node_modules/foo.js' does not exist.", + "File '/a/b/c/node_modules/foo.jsx' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.js' does not exist.", + "File '/a/b/c/node_modules/foo/index.jsx' does not exist.", + "File '/a/b/node_modules/foo.js' does not exist.", + "File '/a/b/node_modules/foo.jsx' does not exist.", + "File '/a/b/node_modules/foo/package.json' does not exist.", + "File '/a/b/node_modules/foo/index.js' does not exist.", + "File '/a/b/node_modules/foo/index.jsx' does not exist.", + "File '/a/node_modules/foo.js' does not exist.", + "File '/a/node_modules/foo.jsx' does not exist.", + "File '/a/node_modules/foo/package.json' does not exist.", + "File '/a/node_modules/foo/index.js' does not exist.", + "File '/a/node_modules/foo/index.jsx' does not exist.", + "File '/node_modules/foo.js' does not exist.", + "File '/node_modules/foo.jsx' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.js' does not exist.", + "File '/node_modules/foo/index.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========", + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution7.errors.txt b/tests/baselines/reference/cachedModuleResolution7.errors.txt new file mode 100644 index 00000000000..670c4a665a6 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution7.errors.txt @@ -0,0 +1,15 @@ +/a/b/c/d/e/app.ts(1,17): error TS2307: Cannot find module 'foo'. +/a/b/c/lib.ts(2,17): error TS2307: Cannot find module 'foo'. + + +==== /a/b/c/lib.ts (1 errors) ==== + + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + +==== /a/b/c/d/e/app.ts (1 errors) ==== + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution7.js b/tests/baselines/reference/cachedModuleResolution7.js new file mode 100644 index 00000000000..8b86dcd55af --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution7.js @@ -0,0 +1,14 @@ +//// [tests/cases/compiler/cachedModuleResolution7.ts] //// + +//// [lib.ts] + +import {x} from "foo"; + +//// [app.ts] +import {x} from "foo"; + + +//// [lib.js] +"use strict"; +//// [app.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution7.trace.json b/tests/baselines/reference/cachedModuleResolution7.trace.json new file mode 100644 index 00000000000..ce5bf08861d --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution7.trace.json @@ -0,0 +1,92 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/node_modules/foo.ts' does not exist.", + "File '/a/b/c/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/foo.ts' does not exist.", + "File '/a/b/node_modules/foo.tsx' does not exist.", + "File '/a/b/node_modules/foo.d.ts' does not exist.", + "File '/a/b/node_modules/foo/package.json' does not exist.", + "File '/a/b/node_modules/foo/index.ts' does not exist.", + "File '/a/b/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/node_modules/foo.ts' does not exist.", + "File '/a/node_modules/foo.tsx' does not exist.", + "File '/a/node_modules/foo.d.ts' does not exist.", + "File '/a/node_modules/foo/package.json' does not exist.", + "File '/a/node_modules/foo/index.ts' does not exist.", + "File '/a/node_modules/foo/index.tsx' does not exist.", + "File '/a/node_modules/foo/index.d.ts' does not exist.", + "File '/a/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/node_modules/@types/foo/package.json' does not exist.", + "File '/a/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/node_modules/foo.ts' does not exist.", + "File '/node_modules/foo.tsx' does not exist.", + "File '/node_modules/foo.d.ts' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.ts' does not exist.", + "File '/node_modules/foo/index.tsx' does not exist.", + "File '/node_modules/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/node_modules/foo.js' does not exist.", + "File '/a/b/c/node_modules/foo.jsx' does not exist.", + "File '/a/b/c/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/foo/index.js' does not exist.", + "File '/a/b/c/node_modules/foo/index.jsx' does not exist.", + "File '/a/b/node_modules/foo.js' does not exist.", + "File '/a/b/node_modules/foo.jsx' does not exist.", + "File '/a/b/node_modules/foo/package.json' does not exist.", + "File '/a/b/node_modules/foo/index.js' does not exist.", + "File '/a/b/node_modules/foo/index.jsx' does not exist.", + "File '/a/node_modules/foo.js' does not exist.", + "File '/a/node_modules/foo.jsx' does not exist.", + "File '/a/node_modules/foo/package.json' does not exist.", + "File '/a/node_modules/foo/index.js' does not exist.", + "File '/a/node_modules/foo/index.jsx' does not exist.", + "File '/node_modules/foo.js' does not exist.", + "File '/node_modules/foo.jsx' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.js' does not exist.", + "File '/node_modules/foo/index.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========", + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/a/b/c/d/e/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/e/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.ts' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.tsx' does not exist.", + "File '/a/b/c/d/node_modules/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution8.errors.txt b/tests/baselines/reference/cachedModuleResolution8.errors.txt new file mode 100644 index 00000000000..b272ff29b9d --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution8.errors.txt @@ -0,0 +1,14 @@ +/a/b/c/d/e/app.ts(2,17): error TS2307: Cannot find module 'foo'. +/a/b/c/lib.ts(1,17): error TS2307: Cannot find module 'foo'. + + +==== /a/b/c/d/e/app.ts (1 errors) ==== + + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + +==== /a/b/c/lib.ts (1 errors) ==== + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution8.js b/tests/baselines/reference/cachedModuleResolution8.js new file mode 100644 index 00000000000..1c00b171f21 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution8.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/cachedModuleResolution8.ts] //// + +//// [app.ts] + +import {x} from "foo"; + +//// [lib.ts] +import {x} from "foo"; + +//// [app.js] +"use strict"; +//// [lib.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution8.trace.json b/tests/baselines/reference/cachedModuleResolution8.trace.json new file mode 100644 index 00000000000..f833f56d819 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution8.trace.json @@ -0,0 +1,57 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/d/e/foo.ts' does not exist.", + "File '/a/b/c/d/e/foo.tsx' does not exist.", + "File '/a/b/c/d/e/foo.d.ts' does not exist.", + "File '/a/b/c/d/foo.ts' does not exist.", + "File '/a/b/c/d/foo.tsx' does not exist.", + "File '/a/b/c/d/foo.d.ts' does not exist.", + "File '/a/b/c/foo.ts' does not exist.", + "File '/a/b/c/foo.tsx' does not exist.", + "File '/a/b/c/foo.d.ts' does not exist.", + "File '/a/b/foo.ts' does not exist.", + "File '/a/b/foo.tsx' does not exist.", + "File '/a/b/foo.d.ts' does not exist.", + "File '/a/foo.ts' does not exist.", + "File '/a/foo.tsx' does not exist.", + "File '/a/foo.d.ts' does not exist.", + "File '/foo.ts' does not exist.", + "File '/foo.tsx' does not exist.", + "File '/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/e/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/d/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/node_modules/@types/foo/package.json' does not exist.", + "File '/a/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/d/e/foo.js' does not exist.", + "File '/a/b/c/d/e/foo.jsx' does not exist.", + "File '/a/b/c/d/foo.js' does not exist.", + "File '/a/b/c/d/foo.jsx' does not exist.", + "File '/a/b/c/foo.js' does not exist.", + "File '/a/b/c/foo.jsx' does not exist.", + "File '/a/b/foo.js' does not exist.", + "File '/a/b/foo.jsx' does not exist.", + "File '/a/foo.js' does not exist.", + "File '/a/foo.jsx' does not exist.", + "File '/foo.js' does not exist.", + "File '/foo.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========", + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution9.errors.txt b/tests/baselines/reference/cachedModuleResolution9.errors.txt new file mode 100644 index 00000000000..aeec41f0048 --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution9.errors.txt @@ -0,0 +1,16 @@ +/a/b/c/d/e/app.ts(1,17): error TS2307: Cannot find module 'foo'. +/a/b/c/lib.ts(2,17): error TS2307: Cannot find module 'foo'. + + +==== /a/b/c/lib.ts (1 errors) ==== + + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + + +==== /a/b/c/d/e/app.ts (1 errors) ==== + import {x} from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + \ No newline at end of file diff --git a/tests/baselines/reference/cachedModuleResolution9.js b/tests/baselines/reference/cachedModuleResolution9.js new file mode 100644 index 00000000000..32f8848736c --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution9.js @@ -0,0 +1,15 @@ +//// [tests/cases/compiler/cachedModuleResolution9.ts] //// + +//// [lib.ts] + +import {x} from "foo"; + + +//// [app.ts] +import {x} from "foo"; + + +//// [lib.js] +"use strict"; +//// [app.js] +"use strict"; diff --git a/tests/baselines/reference/cachedModuleResolution9.trace.json b/tests/baselines/reference/cachedModuleResolution9.trace.json new file mode 100644 index 00000000000..10a79576bfc --- /dev/null +++ b/tests/baselines/reference/cachedModuleResolution9.trace.json @@ -0,0 +1,47 @@ +[ + "======== Resolving module 'foo' from '/a/b/c/lib.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/foo.ts' does not exist.", + "File '/a/b/c/foo.tsx' does not exist.", + "File '/a/b/c/foo.d.ts' does not exist.", + "File '/a/b/foo.ts' does not exist.", + "File '/a/b/foo.tsx' does not exist.", + "File '/a/b/foo.d.ts' does not exist.", + "File '/a/foo.ts' does not exist.", + "File '/a/foo.tsx' does not exist.", + "File '/a/foo.d.ts' does not exist.", + "File '/foo.ts' does not exist.", + "File '/foo.tsx' does not exist.", + "File '/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/c/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/c/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/b/node_modules/@types/foo/package.json' does not exist.", + "File '/a/b/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/node_modules/@types/foo.d.ts' does not exist.", + "File '/a/node_modules/@types/foo/package.json' does not exist.", + "File '/a/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "File '/a/b/c/foo.js' does not exist.", + "File '/a/b/c/foo.jsx' does not exist.", + "File '/a/b/foo.js' does not exist.", + "File '/a/b/foo.jsx' does not exist.", + "File '/a/foo.js' does not exist.", + "File '/a/foo.jsx' does not exist.", + "File '/foo.js' does not exist.", + "File '/foo.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========", + "======== Resolving module 'foo' from '/a/b/c/d/e/app.ts'. ========", + "Explicitly specified module resolution kind: 'Classic'.", + "File '/a/b/c/d/e/foo.ts' does not exist.", + "File '/a/b/c/d/e/foo.tsx' does not exist.", + "File '/a/b/c/d/e/foo.d.ts' does not exist.", + "File '/a/b/c/d/foo.ts' does not exist.", + "File '/a/b/c/d/foo.tsx' does not exist.", + "File '/a/b/c/d/foo.d.ts' does not exist.", + "Resolution for module 'foo' was found in cache", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread.js b/tests/baselines/reference/callWithSpread.js index 161eb36dbcf..69f7e4e30b0 100644 --- a/tests/baselines/reference/callWithSpread.js +++ b/tests/baselines/reference/callWithSpread.js @@ -1,6 +1,6 @@ //// [callWithSpread.ts] interface X { - foo(x: number, y: number, ...z: string[]); + foo(x: number, y: number, ...z: string[]): X; } function foo(x: number, y: number, ...z: string[]) { @@ -19,10 +19,18 @@ obj.foo(1, 2, "abc"); obj.foo(1, 2, ...a); obj.foo(1, 2, ...a, "abc"); +obj.foo(1, 2, ...a).foo(1, 2, "abc"); +obj.foo(1, 2, ...a).foo(1, 2, ...a); +obj.foo(1, 2, ...a).foo(1, 2, ...a, "abc"); + (obj.foo)(1, 2, "abc"); (obj.foo)(1, 2, ...a); (obj.foo)(1, 2, ...a, "abc"); +((obj.foo)(1, 2, ...a).foo)(1, 2, "abc"); +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a); +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a, "abc"); + xa[1].foo(1, 2, "abc"); xa[1].foo(1, 2, ...a); xa[1].foo(1, 2, ...a, "abc"); @@ -72,13 +80,19 @@ foo.apply(void 0, [1, 2].concat(a, ["abc"])); obj.foo(1, 2, "abc"); obj.foo.apply(obj, [1, 2].concat(a)); obj.foo.apply(obj, [1, 2].concat(a, ["abc"])); +obj.foo.apply(obj, [1, 2].concat(a)).foo(1, 2, "abc"); +(_a = obj.foo.apply(obj, [1, 2].concat(a))).foo.apply(_a, [1, 2].concat(a)); +(_b = obj.foo.apply(obj, [1, 2].concat(a))).foo.apply(_b, [1, 2].concat(a, ["abc"])); (obj.foo)(1, 2, "abc"); obj.foo.apply(obj, [1, 2].concat(a)); obj.foo.apply(obj, [1, 2].concat(a, ["abc"])); +(obj.foo.apply(obj, [1, 2].concat(a)).foo)(1, 2, "abc"); +(_c = obj.foo.apply(obj, [1, 2].concat(a))).foo.apply(_c, [1, 2].concat(a)); +(_d = obj.foo.apply(obj, [1, 2].concat(a))).foo.apply(_d, [1, 2].concat(a, ["abc"])); xa[1].foo(1, 2, "abc"); -(_a = xa[1]).foo.apply(_a, [1, 2].concat(a)); -(_b = xa[1]).foo.apply(_b, [1, 2].concat(a, ["abc"])); -(_c = xa[1]).foo.apply(_c, [1, 2, "abc"]); +(_e = xa[1]).foo.apply(_e, [1, 2].concat(a)); +(_f = xa[1]).foo.apply(_f, [1, 2].concat(a, ["abc"])); +(_g = xa[1]).foo.apply(_g, [1, 2, "abc"]); var C = (function () { function C(x, y) { var z = []; @@ -109,4 +123,4 @@ var D = (function (_super) { }; return D; }(C)); -var _a, _b, _c; +var _a, _b, _c, _d, _e, _f, _g; diff --git a/tests/baselines/reference/callWithSpread.symbols b/tests/baselines/reference/callWithSpread.symbols index bc2d9bfebd9..42331422df7 100644 --- a/tests/baselines/reference/callWithSpread.symbols +++ b/tests/baselines/reference/callWithSpread.symbols @@ -2,11 +2,12 @@ interface X { >X : Symbol(X, Decl(callWithSpread.ts, 0, 0)) - foo(x: number, y: number, ...z: string[]); + foo(x: number, y: number, ...z: string[]): X; >foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) >x : Symbol(x, Decl(callWithSpread.ts, 1, 8)) >y : Symbol(y, Decl(callWithSpread.ts, 1, 18)) >z : Symbol(z, Decl(callWithSpread.ts, 1, 29)) +>X : Symbol(X, Decl(callWithSpread.ts, 0, 0)) } function foo(x: number, y: number, ...z: string[]) { @@ -58,6 +59,32 @@ obj.foo(1, 2, ...a, "abc"); >foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) >a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +obj.foo(1, 2, ...a).foo(1, 2, "abc"); +>obj.foo(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) + +obj.foo(1, 2, ...a).foo(1, 2, ...a); +>obj.foo(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) + +obj.foo(1, 2, ...a).foo(1, 2, ...a, "abc"); +>obj.foo(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) + (obj.foo)(1, 2, "abc"); >obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) >obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) @@ -75,6 +102,32 @@ obj.foo(1, 2, ...a, "abc"); >foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) >a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +((obj.foo)(1, 2, ...a).foo)(1, 2, "abc"); +>(obj.foo)(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) + +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a); +>(obj.foo)(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) + +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a, "abc"); +>(obj.foo)(1, 2, ...a).foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj.foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>obj : Symbol(obj, Decl(callWithSpread.ts, 9, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) +>foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) +>a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) + xa[1].foo(1, 2, "abc"); >xa[1].foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) >xa : Symbol(xa, Decl(callWithSpread.ts, 10, 3)) @@ -99,60 +152,60 @@ xa[1].foo(1, 2, ...a, "abc"); >foo : Symbol(X.foo, Decl(callWithSpread.ts, 0, 13)) class C { ->C : Symbol(C, Decl(callWithSpread.ts, 28, 40)) +>C : Symbol(C, Decl(callWithSpread.ts, 36, 40)) constructor(x: number, y: number, ...z: string[]) { ->x : Symbol(x, Decl(callWithSpread.ts, 31, 16)) ->y : Symbol(y, Decl(callWithSpread.ts, 31, 26)) ->z : Symbol(z, Decl(callWithSpread.ts, 31, 37)) +>x : Symbol(x, Decl(callWithSpread.ts, 39, 16)) +>y : Symbol(y, Decl(callWithSpread.ts, 39, 26)) +>z : Symbol(z, Decl(callWithSpread.ts, 39, 37)) this.foo(x, y); ->this.foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->this : Symbol(C, Decl(callWithSpread.ts, 28, 40)) ->foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->x : Symbol(x, Decl(callWithSpread.ts, 31, 16)) ->y : Symbol(y, Decl(callWithSpread.ts, 31, 26)) +>this.foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>this : Symbol(C, Decl(callWithSpread.ts, 36, 40)) +>foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>x : Symbol(x, Decl(callWithSpread.ts, 39, 16)) +>y : Symbol(y, Decl(callWithSpread.ts, 39, 26)) this.foo(x, y, ...z); ->this.foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->this : Symbol(C, Decl(callWithSpread.ts, 28, 40)) ->foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->x : Symbol(x, Decl(callWithSpread.ts, 31, 16)) ->y : Symbol(y, Decl(callWithSpread.ts, 31, 26)) ->z : Symbol(z, Decl(callWithSpread.ts, 31, 37)) +>this.foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>this : Symbol(C, Decl(callWithSpread.ts, 36, 40)) +>foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>x : Symbol(x, Decl(callWithSpread.ts, 39, 16)) +>y : Symbol(y, Decl(callWithSpread.ts, 39, 26)) +>z : Symbol(z, Decl(callWithSpread.ts, 39, 37)) } foo(x: number, y: number, ...z: string[]) { ->foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->x : Symbol(x, Decl(callWithSpread.ts, 35, 8)) ->y : Symbol(y, Decl(callWithSpread.ts, 35, 18)) ->z : Symbol(z, Decl(callWithSpread.ts, 35, 29)) +>foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>x : Symbol(x, Decl(callWithSpread.ts, 43, 8)) +>y : Symbol(y, Decl(callWithSpread.ts, 43, 18)) +>z : Symbol(z, Decl(callWithSpread.ts, 43, 29)) } } class D extends C { ->D : Symbol(D, Decl(callWithSpread.ts, 37, 1)) ->C : Symbol(C, Decl(callWithSpread.ts, 28, 40)) +>D : Symbol(D, Decl(callWithSpread.ts, 45, 1)) +>C : Symbol(C, Decl(callWithSpread.ts, 36, 40)) constructor() { super(1, 2); ->super : Symbol(C, Decl(callWithSpread.ts, 28, 40)) +>super : Symbol(C, Decl(callWithSpread.ts, 36, 40)) super(1, 2, ...a); ->super : Symbol(C, Decl(callWithSpread.ts, 28, 40)) +>super : Symbol(C, Decl(callWithSpread.ts, 36, 40)) >a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) } foo() { ->foo : Symbol(D.foo, Decl(callWithSpread.ts, 43, 5)) +>foo : Symbol(D.foo, Decl(callWithSpread.ts, 51, 5)) super.foo(1, 2); ->super.foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->super : Symbol(C, Decl(callWithSpread.ts, 28, 40)) ->foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) +>super.foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>super : Symbol(C, Decl(callWithSpread.ts, 36, 40)) +>foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) super.foo(1, 2, ...a); ->super.foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) ->super : Symbol(C, Decl(callWithSpread.ts, 28, 40)) ->foo : Symbol(C.foo, Decl(callWithSpread.ts, 34, 5)) +>super.foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) +>super : Symbol(C, Decl(callWithSpread.ts, 36, 40)) +>foo : Symbol(C.foo, Decl(callWithSpread.ts, 42, 5)) >a : Symbol(a, Decl(callWithSpread.ts, 7, 3)) } } diff --git a/tests/baselines/reference/callWithSpread.types b/tests/baselines/reference/callWithSpread.types index c9403f1bb69..5af9d2fef84 100644 --- a/tests/baselines/reference/callWithSpread.types +++ b/tests/baselines/reference/callWithSpread.types @@ -2,11 +2,12 @@ interface X { >X : X - foo(x: number, y: number, ...z: string[]); ->foo : (x: number, y: number, ...z: string[]) => any + foo(x: number, y: number, ...z: string[]): X; +>foo : (x: number, y: number, ...z: string[]) => X >x : number >y : number >z : string[] +>X : X } function foo(x: number, y: number, ...z: string[]) { @@ -55,29 +56,80 @@ foo(1, 2, ...a, "abc"); >"abc" : "abc" obj.foo(1, 2, "abc"); ->obj.foo(1, 2, "abc") : any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>obj.foo(1, 2, "abc") : X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >"abc" : "abc" obj.foo(1, 2, ...a); ->obj.foo(1, 2, ...a) : any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>obj.foo(1, 2, ...a) : X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string >a : string[] obj.foo(1, 2, ...a, "abc"); ->obj.foo(1, 2, ...a, "abc") : any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>obj.foo(1, 2, ...a, "abc") : X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>"abc" : "abc" + +obj.foo(1, 2, ...a).foo(1, 2, "abc"); +>obj.foo(1, 2, ...a).foo(1, 2, "abc") : X +>obj.foo(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>obj.foo(1, 2, ...a) : X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>"abc" : "abc" + +obj.foo(1, 2, ...a).foo(1, 2, ...a); +>obj.foo(1, 2, ...a).foo(1, 2, ...a) : X +>obj.foo(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>obj.foo(1, 2, ...a) : X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] + +obj.foo(1, 2, ...a).foo(1, 2, ...a, "abc"); +>obj.foo(1, 2, ...a).foo(1, 2, ...a, "abc") : X +>obj.foo(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>obj.foo(1, 2, ...a) : X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string @@ -85,32 +137,89 @@ obj.foo(1, 2, ...a, "abc"); >"abc" : "abc" (obj.foo)(1, 2, "abc"); ->(obj.foo)(1, 2, "abc") : any ->(obj.foo) : (x: number, y: number, ...z: string[]) => any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>(obj.foo)(1, 2, "abc") : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >"abc" : "abc" (obj.foo)(1, 2, ...a); ->(obj.foo)(1, 2, ...a) : any ->(obj.foo) : (x: number, y: number, ...z: string[]) => any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>(obj.foo)(1, 2, ...a) : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string >a : string[] (obj.foo)(1, 2, ...a, "abc"); ->(obj.foo)(1, 2, ...a, "abc") : any ->(obj.foo) : (x: number, y: number, ...z: string[]) => any ->obj.foo : (x: number, y: number, ...z: string[]) => any +>(obj.foo)(1, 2, ...a, "abc") : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X >obj : X ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>"abc" : "abc" + +((obj.foo)(1, 2, ...a).foo)(1, 2, "abc"); +>((obj.foo)(1, 2, ...a).foo)(1, 2, "abc") : X +>((obj.foo)(1, 2, ...a).foo) : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a) : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>"abc" : "abc" + +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a); +>((obj.foo)(1, 2, ...a).foo)(1, 2, ...a) : X +>((obj.foo)(1, 2, ...a).foo) : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a) : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] + +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a, "abc"); +>((obj.foo)(1, 2, ...a).foo)(1, 2, ...a, "abc") : X +>((obj.foo)(1, 2, ...a).foo) : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a).foo : (x: number, y: number, ...z: string[]) => X +>(obj.foo)(1, 2, ...a) : X +>(obj.foo) : (x: number, y: number, ...z: string[]) => X +>obj.foo : (x: number, y: number, ...z: string[]) => X +>obj : X +>foo : (x: number, y: number, ...z: string[]) => X +>1 : 1 +>2 : 2 +>...a : string +>a : string[] +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string @@ -118,35 +227,35 @@ obj.foo(1, 2, ...a, "abc"); >"abc" : "abc" xa[1].foo(1, 2, "abc"); ->xa[1].foo(1, 2, "abc") : any ->xa[1].foo : (x: number, y: number, ...z: string[]) => any +>xa[1].foo(1, 2, "abc") : X +>xa[1].foo : (x: number, y: number, ...z: string[]) => X >xa[1] : X >xa : X[] >1 : 1 ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >"abc" : "abc" xa[1].foo(1, 2, ...a); ->xa[1].foo(1, 2, ...a) : any ->xa[1].foo : (x: number, y: number, ...z: string[]) => any +>xa[1].foo(1, 2, ...a) : X +>xa[1].foo : (x: number, y: number, ...z: string[]) => X >xa[1] : X >xa : X[] >1 : 1 ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string >a : string[] xa[1].foo(1, 2, ...a, "abc"); ->xa[1].foo(1, 2, ...a, "abc") : any ->xa[1].foo : (x: number, y: number, ...z: string[]) => any +>xa[1].foo(1, 2, ...a, "abc") : X +>xa[1].foo : (x: number, y: number, ...z: string[]) => X >xa[1] : X >xa : X[] >1 : 1 ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >1 : 1 >2 : 2 >...a : string @@ -158,11 +267,11 @@ xa[1].foo(1, 2, ...a, "abc"); >(xa[1].foo) : Function >xa[1].foo : Function >Function : Function ->xa[1].foo : (x: number, y: number, ...z: string[]) => any +>xa[1].foo : (x: number, y: number, ...z: string[]) => X >xa[1] : X >xa : X[] >1 : 1 ->foo : (x: number, y: number, ...z: string[]) => any +>foo : (x: number, y: number, ...z: string[]) => X >...[1, 2, "abc"] : string | number >[1, 2, "abc"] : (string | number)[] >1 : 1 diff --git a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.errors.txt b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.errors.txt new file mode 100644 index 00000000000..6e2b7ef5787 --- /dev/null +++ b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/captureSuperPropertyAccessInSuperCall01.ts(9,24): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + + +==== tests/cases/compiler/captureSuperPropertyAccessInSuperCall01.ts (1 errors) ==== + class A { + constructor(f: () => string) { + } + public blah(): string { return ""; } + } + + class B extends A { + constructor() { + super(() => { return super.blah(); }) + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js new file mode 100644 index 00000000000..7fde44106c6 --- /dev/null +++ b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js @@ -0,0 +1,33 @@ +//// [captureSuperPropertyAccessInSuperCall01.ts] +class A { + constructor(f: () => string) { + } + public blah(): string { return ""; } +} + +class B extends A { + constructor() { + super(() => { return super.blah(); }) + } +} + +//// [captureSuperPropertyAccessInSuperCall01.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var A = (function () { + function A(f) { + } + A.prototype.blah = function () { return ""; }; + return A; +}()); +var B = (function (_super) { + __extends(B, _super); + function B() { + var _this = _super.call(this, function () { return _super.blah.call(_this); }) || this; + return _this; + } + return B; +}(A)); diff --git a/tests/baselines/reference/captureThisInSuperCall.js b/tests/baselines/reference/captureThisInSuperCall.js index 2c4df5db961..069871f598e 100644 --- a/tests/baselines/reference/captureThisInSuperCall.js +++ b/tests/baselines/reference/captureThisInSuperCall.js @@ -22,7 +22,8 @@ var A = (function () { var B = (function (_super) { __extends(B, _super); function B() { - return _super.call(this, { test: function () { return _this.someMethod(); } }) || this; + var _this = _super.call(this, { test: function () { return _this.someMethod(); } }) || this; + return _this; } B.prototype.someMethod = function () { }; return B; diff --git a/tests/baselines/reference/capturedLetConstInLoop1.errors.txt b/tests/baselines/reference/capturedLetConstInLoop1.errors.txt deleted file mode 100644 index a10b380bcf9..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop1.errors.txt +++ /dev/null @@ -1,128 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop1.ts(69,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1.ts(86,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1.ts(92,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1.ts(109,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop1.ts (4 errors) ==== - //==== let - for (let x in {}) { - (function() { return x}); - (() => x); - } - - for (let x of []) { - (function() { return x}); - (() => x); - } - - for (let x = 0; x < 1; ++x) { - (function() { return x}); - (() => x); - } - - while (1 === 1) { - let x; - (function() { return x}); - (() => x); - } - - do { - let x; - (function() { return x}); - (() => x); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - (function() { return x}); - (() => x); - } - - for (let x = 0, y = 1; x < 1; ++x) { - (function() { return x + y}); - (() => x + y); - } - - while (1 === 1) { - let x, y; - (function() { return x + y}); - (() => x + y); - } - - do { - let x, y; - (function() { return x + y}); - (() => x + y); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - (function() { return x + y}); - (() => x + y); - } - - //=========const - for (const x in {}) { - (function() { return x}); - (() => x); - } - - for (const x of []) { - (function() { return x}); - (() => x); - } - - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - (function() { return x}); - (() => x); - } - - while (1 === 1) { - const x = 1; - (function() { return x}); - (() => x); - } - - do { - const x = 1; - (function() { return x}); - (() => x); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - (function() { return x}); - (() => x); - } - - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - (function() { return x + y}); - (() => x + y); - } - - while (1 === 1) { - const x = 1, y = 1; - (function() { return x + y}); - (() => x + y); - } - - do { - const x = 1, y = 1; - (function() { return x + y}); - (() => x + y); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - (function() { return x + y}); - (() => x + y); - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop1.types b/tests/baselines/reference/capturedLetConstInLoop1.types index c60ac25ce1f..45d4a1c9368 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.types +++ b/tests/baselines/reference/capturedLetConstInLoop1.types @@ -32,10 +32,10 @@ for (let x of []) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -90,16 +90,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x}); >(function() { return x}) : () => number @@ -114,12 +114,12 @@ for (let y = 0; y < 1; ++y) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -188,16 +188,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number @@ -246,21 +246,21 @@ for (const x of []) { } for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 0 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 0 } while (1 === 1) { @@ -269,34 +269,34 @@ while (1 === 1) { >1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } while (1 === 1) >1 === 1 : boolean @@ -304,49 +304,49 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 } while (1 === 1) { @@ -355,46 +355,46 @@ while (1 === 1) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } while (1 === 1) >1 === 1 : boolean @@ -402,27 +402,27 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 } diff --git a/tests/baselines/reference/capturedLetConstInLoop1_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop1_ES6.errors.txt deleted file mode 100644 index 24c5ddf17b6..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop1_ES6.errors.txt +++ /dev/null @@ -1,128 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop1_ES6.ts(69,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1_ES6.ts(86,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1_ES6.ts(92,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop1_ES6.ts(109,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop1_ES6.ts (4 errors) ==== - //==== let - for (let x in {}) { - (function() { return x}); - (() => x); - } - - for (let x of []) { - (function() { return x}); - (() => x); - } - - for (let x = 0; x < 1; ++x) { - (function() { return x}); - (() => x); - } - - while (1 === 1) { - let x; - (function() { return x}); - (() => x); - } - - do { - let x; - (function() { return x}); - (() => x); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - (function() { return x}); - (() => x); - } - - for (let x = 0, y = 1; x < 1; ++x) { - (function() { return x + y}); - (() => x + y); - } - - while (1 === 1) { - let x, y; - (function() { return x + y}); - (() => x + y); - } - - do { - let x, y; - (function() { return x + y}); - (() => x + y); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - (function() { return x + y}); - (() => x + y); - } - - //=========const - for (const x in {}) { - (function() { return x}); - (() => x); - } - - for (const x of []) { - (function() { return x}); - (() => x); - } - - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - (function() { return x}); - (() => x); - } - - while (1 === 1) { - const x = 1; - (function() { return x}); - (() => x); - } - - do { - const x = 1; - (function() { return x}); - (() => x); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - (function() { return x}); - (() => x); - } - - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - (function() { return x + y}); - (() => x + y); - } - - while (1 === 1) { - const x = 1, y = 1; - (function() { return x + y}); - (() => x + y); - } - - do { - const x = 1, y = 1; - (function() { return x + y}); - (() => x + y); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - (function() { return x + y}); - (() => x + y); - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop1_ES6.types b/tests/baselines/reference/capturedLetConstInLoop1_ES6.types index cee71c0d5cd..5e803b35863 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1_ES6.types +++ b/tests/baselines/reference/capturedLetConstInLoop1_ES6.types @@ -32,10 +32,10 @@ for (let x of []) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -90,16 +90,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x}); >(function() { return x}) : () => number @@ -114,12 +114,12 @@ for (let y = 0; y < 1; ++y) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -188,16 +188,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number @@ -246,21 +246,21 @@ for (const x of []) { } for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 0 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 0 } while (1 === 1) { @@ -269,34 +269,34 @@ while (1 === 1) { >1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } while (1 === 1) >1 === 1 : boolean @@ -304,49 +304,49 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x}); >(function() { return x}) : () => number >function() { return x} : () => number ->x : number +>x : 1 (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 } while (1 === 1) { @@ -355,46 +355,46 @@ while (1 === 1) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } while (1 === 1) >1 === 1 : boolean @@ -402,27 +402,27 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + y}); >(function() { return x + y}) : () => number >function() { return x + y} : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 } diff --git a/tests/baselines/reference/capturedLetConstInLoop2.errors.txt b/tests/baselines/reference/capturedLetConstInLoop2.errors.txt deleted file mode 100644 index 9125a87ecfe..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop2.errors.txt +++ /dev/null @@ -1,191 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop2.ts(108,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2.ts(133,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2.ts(142,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2.ts(170,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop2.ts (4 errors) ==== - - - // ========let - function foo0(x) { - for (let x of []) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo0_1(x) { - for (let x in []) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo1(x) { - for (let x = 0; x < 1; ++x) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo2(x) { - while (1 === 1) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo3(x) { - do { - let x; - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } while (1 === 1) - } - - function foo4(x) { - for (let y = 0; y < 1; ++y) { - let a = arguments.length; - let x = 1; - (function() { return x + a }); - (() => x + a); - } - } - - function foo5(x) { - for (let x = 0, y = 1; x < 1; ++x) { - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - - function foo6(x) { - while (1 === 1) { - let x, y; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - function foo7(x) { - do { - let x, y; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } while (1 === 1) - } - - - function foo8(x) { - for (let y = 0; y < 1; ++y) { - let x = 1; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - ///=======const - function foo0_c(x) { - for (const x of []) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo0_1_c(x) { - for (const x in []) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo1_c(x) { - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo2_c(x) { - while (1 === 1) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo3_c(x) { - do { - const x = 1; - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } while (1 === 1) - } - - function foo4_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - const x = 1; - (function() { return x + a }); - (() => x + a); - } - } - - function foo5_c(x) { - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - - function foo6_c(x) { - while (1 === 1) { - const x = 1, y =1 ; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - function foo7_c(x) { - do { - const x = 1, y = 1; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } while (1 === 1) - } - - - function foo8_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop2.types b/tests/baselines/reference/capturedLetConstInLoop2.types index f4f7a926f89..4f819d3c3f9 100644 --- a/tests/baselines/reference/capturedLetConstInLoop2.types +++ b/tests/baselines/reference/capturedLetConstInLoop2.types @@ -68,10 +68,10 @@ function foo1(x) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -168,10 +168,10 @@ function foo4(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number @@ -183,7 +183,7 @@ function foo4(x) { let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + a }); >(function() { return x + a }) : () => number @@ -207,12 +207,12 @@ function foo5(x) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -328,16 +328,16 @@ function foo8(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 let a = arguments.length; >a : number @@ -430,11 +430,11 @@ function foo1_c(x) { >x : any for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 const a = arguments.length; >a : number @@ -446,14 +446,14 @@ function foo1_c(x) { >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 0 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 0 >a : number } } @@ -495,8 +495,8 @@ function foo3_c(x) { do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 const a = arguments.length; >a : number @@ -508,14 +508,14 @@ function foo3_c(x) { >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 1 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 1 >a : number } while (1 === 1) @@ -529,11 +529,11 @@ function foo4_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const a = arguments.length; >a : number @@ -542,21 +542,21 @@ function foo4_c(x) { >length : number const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + a }); >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 1 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 1 >a : number } } @@ -566,13 +566,13 @@ function foo5_c(x) { >x : any for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 const a = arguments.length; >a : number @@ -585,8 +585,8 @@ function foo5_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >a : number (() => x + y + a); @@ -594,8 +594,8 @@ function foo5_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >a : number } } @@ -611,10 +611,10 @@ function foo6_c(x) { >1 : 1 const x = 1, y =1 ; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 const a = arguments.length; >a : number @@ -627,8 +627,8 @@ function foo6_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number (() => x + y + a); @@ -636,8 +636,8 @@ function foo6_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number } } @@ -648,10 +648,10 @@ function foo7_c(x) { do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 const a = arguments.length; >a : number @@ -664,8 +664,8 @@ function foo7_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number (() => x + y + a); @@ -673,8 +673,8 @@ function foo7_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number } while (1 === 1) @@ -689,15 +689,15 @@ function foo8_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 const a = arguments.length; >a : number @@ -710,8 +710,8 @@ function foo8_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >a : number (() => x + y + a); @@ -719,8 +719,8 @@ function foo8_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >a : number } } diff --git a/tests/baselines/reference/capturedLetConstInLoop2_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop2_ES6.errors.txt deleted file mode 100644 index d61bf3619c7..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop2_ES6.errors.txt +++ /dev/null @@ -1,190 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop2_ES6.ts(107,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2_ES6.ts(132,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2_ES6.ts(141,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop2_ES6.ts(169,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop2_ES6.ts (4 errors) ==== - - // ========let - function foo0(x) { - for (let x of []) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo0_1(x) { - for (let x in []) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo1(x) { - for (let x = 0; x < 1; ++x) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo2(x) { - while (1 === 1) { - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo3(x) { - do { - let x; - let a = arguments.length; - (function() { return x + a }); - (() => x + a); - } while (1 === 1) - } - - function foo4(x) { - for (let y = 0; y < 1; ++y) { - let a = arguments.length; - let x = 1; - (function() { return x + a }); - (() => x + a); - } - } - - function foo5(x) { - for (let x = 0, y = 1; x < 1; ++x) { - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - - function foo6(x) { - while (1 === 1) { - let x, y; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - function foo7(x) { - do { - let x, y; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } while (1 === 1) - } - - - function foo8(x) { - for (let y = 0; y < 1; ++y) { - let x = 1; - let a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - ///=======const - function foo0_c(x) { - for (const x of []) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo0_1_c(x) { - for (const x in []) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo1_c(x) { - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo2_c(x) { - while (1 === 1) { - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } - } - - function foo3_c(x) { - do { - const x = 1; - const a = arguments.length; - (function() { return x + a }); - (() => x + a); - } while (1 === 1) - } - - function foo4_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - const x = 1; - (function() { return x + a }); - (() => x + a); - } - } - - function foo5_c(x) { - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - - function foo6_c(x) { - while (1 === 1) { - const x = 1, y =1 ; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } - - function foo7_c(x) { - do { - const x = 1, y = 1; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } while (1 === 1) - } - - - function foo8_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - const a = arguments.length; - (function() { return x + y + a }); - (() => x + y + a); - } - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop2_ES6.types b/tests/baselines/reference/capturedLetConstInLoop2_ES6.types index 80e455e44ce..e72221d85cd 100644 --- a/tests/baselines/reference/capturedLetConstInLoop2_ES6.types +++ b/tests/baselines/reference/capturedLetConstInLoop2_ES6.types @@ -67,10 +67,10 @@ function foo1(x) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -167,10 +167,10 @@ function foo4(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number @@ -182,7 +182,7 @@ function foo4(x) { let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + a }); >(function() { return x + a }) : () => number @@ -206,12 +206,12 @@ function foo5(x) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -327,16 +327,16 @@ function foo8(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 let a = arguments.length; >a : number @@ -429,11 +429,11 @@ function foo1_c(x) { >x : any for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 const a = arguments.length; >a : number @@ -445,14 +445,14 @@ function foo1_c(x) { >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 0 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 0 >a : number } } @@ -494,8 +494,8 @@ function foo3_c(x) { do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 const a = arguments.length; >a : number @@ -507,14 +507,14 @@ function foo3_c(x) { >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 1 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 1 >a : number } while (1 === 1) @@ -528,11 +528,11 @@ function foo4_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const a = arguments.length; >a : number @@ -541,21 +541,21 @@ function foo4_c(x) { >length : number const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + a }); >(function() { return x + a }) : () => number >function() { return x + a } : () => number >x + a : number ->x : number +>x : 1 >a : number (() => x + a); >(() => x + a) : () => number >() => x + a : () => number >x + a : number ->x : number +>x : 1 >a : number } } @@ -565,13 +565,13 @@ function foo5_c(x) { >x : any for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 const a = arguments.length; >a : number @@ -584,8 +584,8 @@ function foo5_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >a : number (() => x + y + a); @@ -593,8 +593,8 @@ function foo5_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >a : number } } @@ -610,10 +610,10 @@ function foo6_c(x) { >1 : 1 const x = 1, y =1 ; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 const a = arguments.length; >a : number @@ -626,8 +626,8 @@ function foo6_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number (() => x + y + a); @@ -635,8 +635,8 @@ function foo6_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number } } @@ -647,10 +647,10 @@ function foo7_c(x) { do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 const a = arguments.length; >a : number @@ -663,8 +663,8 @@ function foo7_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number (() => x + y + a); @@ -672,8 +672,8 @@ function foo7_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >a : number } while (1 === 1) @@ -688,15 +688,15 @@ function foo8_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 const a = arguments.length; >a : number @@ -709,8 +709,8 @@ function foo8_c(x) { >function() { return x + y + a } : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >a : number (() => x + y + a); @@ -718,8 +718,8 @@ function foo8_c(x) { >() => x + y + a : () => number >x + y + a : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >a : number } } diff --git a/tests/baselines/reference/capturedLetConstInLoop3.errors.txt b/tests/baselines/reference/capturedLetConstInLoop3.errors.txt deleted file mode 100644 index ecc9dbcccc5..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop3.errors.txt +++ /dev/null @@ -1,232 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop3.ts(132,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3.ts(164,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3.ts(175,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3.ts(209,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop3.ts (4 errors) ==== - ///=========let - declare function use(a: any); - function foo0(x) { - for (let x of []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo0_1(x) { - for (let x in []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo1(x) { - for (let x = 0; x < 1; ++x) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo2(x) { - while (1 === 1) { - let x = 1; - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo3(x) { - do { - let x; - var v; - (function() { return x + v }); - (() => x + v); - } while (1 === 1); - - use(v); - } - - function foo4(x) { - for (let y = 0; y < 1; ++y) { - var v = y; - let x = 1; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo5(x) { - for (let x = 0, y = 1; x < 1; ++x) { - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - - - function foo6(x) { - while (1 === 1) { - let x, y; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v) - } - - function foo7(x) { - do { - let x, y; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } while (1 === 1); - - use(v); - } - - - function foo8(x) { - for (let y = 0; y < 1; ++y) { - let x = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - //===const - function foo0_c(x) { - for (const x of []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo0_1_c(x) { - for (const x in []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo1_c(x) { - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo2_c(x) { - while (1 === 1) { - const x = 1; - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo3_c(x) { - do { - const x = 1; - var v; - (function() { return x + v }); - (() => x + v); - } while (1 === 1); - - use(v); - } - - function foo4_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = y; - const x = 1; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo5_c(x) { - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - - - function foo6_c(x) { - while (1 === 1) { - const x = 1, y = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v) - } - - function foo7_c(x) { - do { - const x = 1, y = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } while (1 === 1); - - use(v); - } - - - function foo8_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop3.types b/tests/baselines/reference/capturedLetConstInLoop3.types index 3f35072fdb2..8ce40ab5f1b 100644 --- a/tests/baselines/reference/capturedLetConstInLoop3.types +++ b/tests/baselines/reference/capturedLetConstInLoop3.types @@ -76,10 +76,10 @@ function foo1(x) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -119,7 +119,7 @@ function foo2(x) { let x = 1; >x : number ->1 : number +>1 : 1 var v = x; >v : number @@ -188,10 +188,10 @@ function foo4(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number @@ -201,7 +201,7 @@ function foo4(x) { let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + v }); >(function() { return x + v }) : () => number @@ -230,12 +230,12 @@ function foo5(x) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -360,16 +360,16 @@ function foo8(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v = x; >v : number @@ -471,28 +471,28 @@ function foo1_c(x) { >x : any for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v = x; >v : number ->x : number +>x : 0 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 0 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 0 >v : number } @@ -512,25 +512,25 @@ function foo2_c(x) { >1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 1 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 1 >v : number } @@ -546,8 +546,8 @@ function foo3_c(x) { do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v; >v : any @@ -556,14 +556,14 @@ function foo3_c(x) { >(function() { return x + v }) : () => any >function() { return x + v } : () => any >x + v : any ->x : number +>x : 1 >v : any (() => x + v); >(() => x + v) : () => any >() => x + v : () => any >x + v : any ->x : number +>x : 1 >v : any } while (1 === 1); @@ -582,32 +582,32 @@ function foo4_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 var v = y; >v : number ->y : number +>y : 0 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 1 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 1 >v : number } @@ -622,25 +622,25 @@ function foo5_c(x) { >x : any for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v = x; >v : number ->x : number +>x : 0 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v : number (() => x + y + v); @@ -648,8 +648,8 @@ function foo5_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v : number } @@ -670,22 +670,22 @@ function foo6_c(x) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number (() => x + y + v); @@ -693,8 +693,8 @@ function foo6_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number } @@ -710,22 +710,22 @@ function foo7_c(x) { do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number (() => x + y + v); @@ -733,8 +733,8 @@ function foo7_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number } while (1 === 1); @@ -754,27 +754,27 @@ function foo8_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v : number (() => x + y + v); @@ -782,8 +782,8 @@ function foo8_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v : number } diff --git a/tests/baselines/reference/capturedLetConstInLoop3_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop3_ES6.errors.txt deleted file mode 100644 index 487c47e32a5..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop3_ES6.errors.txt +++ /dev/null @@ -1,233 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop3_ES6.ts(133,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3_ES6.ts(165,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3_ES6.ts(176,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop3_ES6.ts(210,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop3_ES6.ts (4 errors) ==== - - ///=========let - declare function use(a: any); - function foo0(x) { - for (let x of []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo0_1(x) { - for (let x in []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo1(x) { - for (let x = 0; x < 1; ++x) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo2(x) { - while (1 === 1) { - let x = 1; - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo3(x) { - do { - let x; - var v; - (function() { return x + v }); - (() => x + v); - } while (1 === 1); - - use(v); - } - - function foo4(x) { - for (let y = 0; y < 1; ++y) { - var v = y; - let x = 1; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo5(x) { - for (let x = 0, y = 1; x < 1; ++x) { - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - - - function foo6(x) { - while (1 === 1) { - let x, y; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v) - } - - function foo7(x) { - do { - let x, y; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } while (1 === 1); - - use(v); - } - - - function foo8(x) { - for (let y = 0; y < 1; ++y) { - let x = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - //===const - function foo0_c(x) { - for (const x of []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo0_1_c(x) { - for (const x in []) { - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo1_c(x) { - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo2_c(x) { - while (1 === 1) { - const x = 1; - var v = x; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo3_c(x) { - do { - const x = 1; - var v; - (function() { return x + v }); - (() => x + v); - } while (1 === 1); - - use(v); - } - - function foo4_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = y; - const x = 1; - (function() { return x + v }); - (() => x + v); - } - - use(v); - } - - function foo5_c(x) { - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } - - - function foo6_c(x) { - while (1 === 1) { - const x = 1, y = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v) - } - - function foo7_c(x) { - do { - const x = 1, y = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } while (1 === 1); - - use(v); - } - - - function foo8_c(x) { - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v = x; - (function() { return x + y + v }); - (() => x + y + v); - } - - use(v); - } \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop3_ES6.types b/tests/baselines/reference/capturedLetConstInLoop3_ES6.types index 3c7776a6651..9c11ae62574 100644 --- a/tests/baselines/reference/capturedLetConstInLoop3_ES6.types +++ b/tests/baselines/reference/capturedLetConstInLoop3_ES6.types @@ -77,10 +77,10 @@ function foo1(x) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -120,7 +120,7 @@ function foo2(x) { let x = 1; >x : number ->1 : number +>1 : 1 var v = x; >v : number @@ -189,10 +189,10 @@ function foo4(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number @@ -202,7 +202,7 @@ function foo4(x) { let x = 1; >x : number ->1 : number +>1 : 1 (function() { return x + v }); >(function() { return x + v }) : () => number @@ -231,12 +231,12 @@ function foo5(x) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -361,16 +361,16 @@ function foo8(x) { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v = x; >v : number @@ -472,28 +472,28 @@ function foo1_c(x) { >x : any for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v = x; >v : number ->x : number +>x : 0 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 0 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 0 >v : number } @@ -513,25 +513,25 @@ function foo2_c(x) { >1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 1 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 1 >v : number } @@ -547,8 +547,8 @@ function foo3_c(x) { do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v; >v : any @@ -557,14 +557,14 @@ function foo3_c(x) { >(function() { return x + v }) : () => any >function() { return x + v } : () => any >x + v : any ->x : number +>x : 1 >v : any (() => x + v); >(() => x + v) : () => any >() => x + v : () => any >x + v : any ->x : number +>x : 1 >v : any } while (1 === 1); @@ -583,32 +583,32 @@ function foo4_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 var v = y; >v : number ->y : number +>y : 0 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 (function() { return x + v }); >(function() { return x + v }) : () => number >function() { return x + v } : () => number >x + v : number ->x : number +>x : 1 >v : number (() => x + v); >(() => x + v) : () => number >() => x + v : () => number >x + v : number ->x : number +>x : 1 >v : number } @@ -623,25 +623,25 @@ function foo5_c(x) { >x : any for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v = x; >v : number ->x : number +>x : 0 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v : number (() => x + y + v); @@ -649,8 +649,8 @@ function foo5_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v : number } @@ -671,22 +671,22 @@ function foo6_c(x) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number (() => x + y + v); @@ -694,8 +694,8 @@ function foo6_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number } @@ -711,22 +711,22 @@ function foo7_c(x) { do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number (() => x + y + v); @@ -734,8 +734,8 @@ function foo7_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v : number } while (1 === 1); @@ -755,27 +755,27 @@ function foo8_c(x) { >x : any for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v = x; >v : number ->x : number +>x : 1 (function() { return x + y + v }); >(function() { return x + y + v }) : () => number >function() { return x + y + v } : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v : number (() => x + y + v); @@ -783,8 +783,8 @@ function foo8_c(x) { >() => x + y + v : () => number >x + y + v : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v : number } diff --git a/tests/baselines/reference/capturedLetConstInLoop4.errors.txt b/tests/baselines/reference/capturedLetConstInLoop4.errors.txt deleted file mode 100644 index 000286537b8..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop4.errors.txt +++ /dev/null @@ -1,158 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop4.ts(90,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4.ts(110,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4.ts(117,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4.ts(137,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop4.ts (4 errors) ==== - - //======let - export function exportedFoo() { - return v0 + v00 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8; - } - - for (let x of []) { - var v0 = x; - (function() { return x + v0}); - (() => x); - } - - for (let x in []) { - var v00 = x; - (function() { return x + v00}); - (() => x); - } - - for (let x = 0; x < 1; ++x) { - var v1 = x; - (function() { return x + v1}); - (() => x); - } - - while (1 === 1) { - let x; - var v2 = x; - (function() { return x + v2}); - (() => x); - } - - do { - let x; - var v3 = x; - (function() { return x + v3}); - (() => x); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - var v4 = x; - (function() { return x + v4}); - (() => x); - } - - for (let x = 0, y = 1; x < 1; ++x) { - var v5 = x; - (function() { return x + y + v5}); - (() => x + y); - } - - while (1 === 1) { - let x, y; - var v6 = x; - (function() { return x + y + v6}); - (() => x + y); - } - - do { - let x, y; - var v7 = x; - (function() { return x + y + v7}); - (() => x + y); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - var v8 = x; - (function() { return x + y + v8}); - (() => x + y); - } - - //======const - export function exportedFoo2() { - return v0_c + v00_c + v1_c + v2_c + v3_c + v4_c + v5_c + v6_c + v7_c + v8_c; - } - - for (const x of []) { - var v0_c = x; - (function() { return x + v0_c}); - (() => x); - } - - for (const x in []) { - var v00_c = x; - (function() { return x + v00}); - (() => x); - } - - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v1_c = x; - (function() { return x + v1_c}); - (() => x); - } - - while (1 === 1) { - const x =1; - var v2_c = x; - (function() { return x + v2_c}); - (() => x); - } - - do { - const x = 1; - var v3_c = x; - (function() { return x + v3_c}); - (() => x); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v4_c = x; - (function() { return x + v4_c}); - (() => x); - } - - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v5_c = x; - (function() { return x + y + v5_c}); - (() => x + y); - } - - while (1 === 1) { - const x = 1, y = 1; - var v6_c = x; - (function() { return x + y + v6_c}); - (() => x + y); - } - - do { - const x = 1, y = 1; - var v7_c = x; - (function() { return x + y + v7_c}); - (() => x + y); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v8_c = x; - (function() { return x + y + v8_c}); - (() => x + y); - } - \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop4.js b/tests/baselines/reference/capturedLetConstInLoop4.js index e3587ad64c6..2cade08f0a6 100644 --- a/tests/baselines/reference/capturedLetConstInLoop4.js +++ b/tests/baselines/reference/capturedLetConstInLoop4.js @@ -151,13 +151,13 @@ System.register([], function (exports_1, context_1) { function exportedFoo() { return v0 + v00 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8; } + exports_1("exportedFoo", exportedFoo); //======const function exportedFoo2() { return v0_c + v00_c + v1_c + v2_c + v3_c + v4_c + v5_c + v6_c + v7_c + v8_c; } - var v0, v00, v1, v2, v3, v4, v5, v6, v7, v8, v0_c, v00_c, v1_c, v2_c, v3_c, v4_c, v5_c, v6_c, v7_c, v8_c; - exports_1("exportedFoo", exportedFoo); exports_1("exportedFoo2", exportedFoo2); + var v0, v00, v1, v2, v3, v4, v5, v6, v7, v8, v0_c, v00_c, v1_c, v2_c, v3_c, v4_c, v5_c, v6_c, v7_c, v8_c; return { setters: [], execute: function () { diff --git a/tests/baselines/reference/capturedLetConstInLoop4.types b/tests/baselines/reference/capturedLetConstInLoop4.types index 16226243c53..2c48463adec 100644 --- a/tests/baselines/reference/capturedLetConstInLoop4.types +++ b/tests/baselines/reference/capturedLetConstInLoop4.types @@ -70,10 +70,10 @@ for (let x in []) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -146,16 +146,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v4 = x; >v4 : number @@ -176,12 +176,12 @@ for (let y = 0; y < 1; ++y) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -268,16 +268,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v8 = x; >v8 : number @@ -369,27 +369,27 @@ for (const x in []) { } for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v1_c = x; >v1_c : number ->x : number +>x : 0 (function() { return x + v1_c}); >(function() { return x + v1_c}) : () => number >function() { return x + v1_c} : () => number >x + v1_c : number ->x : number +>x : 0 >v1_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 0 } while (1 === 1) { @@ -398,46 +398,46 @@ while (1 === 1) { >1 : 1 const x =1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v2_c = x; >v2_c : number ->x : number +>x : 1 (function() { return x + v2_c}); >(function() { return x + v2_c}) : () => number >function() { return x + v2_c} : () => number >x + v2_c : number ->x : number +>x : 1 >v2_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v3_c = x; >v3_c : number ->x : number +>x : 1 (function() { return x + v3_c}); >(function() { return x + v3_c}) : () => number >function() { return x + v3_c} : () => number >x + v3_c : number ->x : number +>x : 1 >v3_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } while (1 === 1) >1 === 1 : boolean @@ -445,61 +445,61 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v4_c = x; >v4_c : number ->x : number +>x : 1 (function() { return x + v4_c}); >(function() { return x + v4_c}) : () => number >function() { return x + v4_c} : () => number >x + v4_c : number ->x : number +>x : 1 >v4_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v5_c = x; >v5_c : number ->x : number +>x : 0 (function() { return x + y + v5_c}); >(function() { return x + y + v5_c}) : () => number >function() { return x + y + v5_c} : () => number >x + y + v5_c : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v5_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 } while (1 === 1) { @@ -508,58 +508,58 @@ while (1 === 1) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v6_c = x; >v6_c : number ->x : number +>x : 1 (function() { return x + y + v6_c}); >(function() { return x + y + v6_c}) : () => number >function() { return x + y + v6_c} : () => number >x + y + v6_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v6_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v7_c = x; >v7_c : number ->x : number +>x : 1 (function() { return x + y + v7_c}); >(function() { return x + y + v7_c}) : () => number >function() { return x + y + v7_c} : () => number >x + y + v7_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v7_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } while (1 === 1) >1 === 1 : boolean @@ -567,34 +567,34 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v8_c = x; >v8_c : number ->x : number +>x : 1 (function() { return x + y + v8_c}); >(function() { return x + y + v8_c}) : () => number >function() { return x + y + v8_c} : () => number >x + y + v8_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v8_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 } diff --git a/tests/baselines/reference/capturedLetConstInLoop4_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop4_ES6.errors.txt deleted file mode 100644 index a83bb1d414f..00000000000 --- a/tests/baselines/reference/capturedLetConstInLoop4_ES6.errors.txt +++ /dev/null @@ -1,158 +0,0 @@ -tests/cases/compiler/capturedLetConstInLoop4_ES6.ts(90,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4_ES6.ts(110,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4_ES6.ts(117,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop4_ES6.ts(137,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. - - -==== tests/cases/compiler/capturedLetConstInLoop4_ES6.ts (4 errors) ==== - - //======let - export function exportedFoo() { - return v0 + v00 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8; - } - - for (let x of []) { - var v0 = x; - (function() { return x + v0}); - (() => x); - } - - for (let x in []) { - var v00 = x; - (function() { return x + v00}); - (() => x); - } - - for (let x = 0; x < 1; ++x) { - var v1 = x; - (function() { return x + v1}); - (() => x); - } - - while (1 === 1) { - let x; - var v2 = x; - (function() { return x + v2}); - (() => x); - } - - do { - let x; - var v3 = x; - (function() { return x + v3}); - (() => x); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - var v4 = x; - (function() { return x + v4}); - (() => x); - } - - for (let x = 0, y = 1; x < 1; ++x) { - var v5 = x; - (function() { return x + y + v5}); - (() => x + y); - } - - while (1 === 1) { - let x, y; - var v6 = x; - (function() { return x + y + v6}); - (() => x + y); - } - - do { - let x, y; - var v7 = x; - (function() { return x + y + v7}); - (() => x + y); - } while (1 === 1) - - for (let y = 0; y < 1; ++y) { - let x = 1; - var v8 = x; - (function() { return x + y + v8}); - (() => x + y); - } - - //======const - export function exportedFoo2() { - return v0_c + v00_c + v1_c + v2_c + v3_c + v4_c + v5_c + v6_c + v7_c + v8_c; - } - - for (const x of []) { - var v0_c = x; - (function() { return x + v0_c}); - (() => x); - } - - for (const x in []) { - var v00_c = x; - (function() { return x + v00}); - (() => x); - } - - for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v1_c = x; - (function() { return x + v1_c}); - (() => x); - } - - while (1 === 1) { - const x =1; - var v2_c = x; - (function() { return x + v2_c}); - (() => x); - } - - do { - const x = 1; - var v3_c = x; - (function() { return x + v3_c}); - (() => x); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v4_c = x; - (function() { return x + v4_c}); - (() => x); - } - - for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - var v5_c = x; - (function() { return x + y + v5_c}); - (() => x + y); - } - - while (1 === 1) { - const x = 1, y = 1; - var v6_c = x; - (function() { return x + y + v6_c}); - (() => x + y); - } - - do { - const x = 1, y = 1; - var v7_c = x; - (function() { return x + y + v7_c}); - (() => x + y); - } while (1 === 1) - - for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. - const x = 1; - var v8_c = x; - (function() { return x + y + v8_c}); - (() => x + y); - } - \ No newline at end of file diff --git a/tests/baselines/reference/capturedLetConstInLoop4_ES6.types b/tests/baselines/reference/capturedLetConstInLoop4_ES6.types index fba7d88ec48..32af60f24e4 100644 --- a/tests/baselines/reference/capturedLetConstInLoop4_ES6.types +++ b/tests/baselines/reference/capturedLetConstInLoop4_ES6.types @@ -70,10 +70,10 @@ for (let x in []) { for (let x = 0; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -146,16 +146,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v4 = x; >v4 : number @@ -176,12 +176,12 @@ for (let y = 0; y < 1; ++y) { for (let x = 0, y = 1; x < 1; ++x) { >x : number ->0 : number +>0 : 0 >y : number ->1 : number +>1 : 1 >x < 1 : boolean >x : number ->1 : number +>1 : 1 >++x : number >x : number @@ -268,16 +268,16 @@ do { for (let y = 0; y < 1; ++y) { >y : number ->0 : number +>0 : 0 >y < 1 : boolean >y : number ->1 : number +>1 : 1 >++y : number >y : number let x = 1; >x : number ->1 : number +>1 : 1 var v8 = x; >v8 : number @@ -369,27 +369,27 @@ for (const x in []) { } for (const x = 0; x < 1;) { ->x : number ->0 : number +>x : 0 +>0 : 0 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v1_c = x; >v1_c : number ->x : number +>x : 0 (function() { return x + v1_c}); >(function() { return x + v1_c}) : () => number >function() { return x + v1_c} : () => number >x + v1_c : number ->x : number +>x : 0 >v1_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 0 } while (1 === 1) { @@ -398,46 +398,46 @@ while (1 === 1) { >1 : 1 const x =1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v2_c = x; >v2_c : number ->x : number +>x : 1 (function() { return x + v2_c}); >(function() { return x + v2_c}) : () => number >function() { return x + v2_c} : () => number >x + v2_c : number ->x : number +>x : 1 >v2_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } do { const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v3_c = x; >v3_c : number ->x : number +>x : 1 (function() { return x + v3_c}); >(function() { return x + v3_c}) : () => number >function() { return x + v3_c} : () => number >x + v3_c : number ->x : number +>x : 1 >v3_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } while (1 === 1) >1 === 1 : boolean @@ -445,61 +445,61 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v4_c = x; >v4_c : number ->x : number +>x : 1 (function() { return x + v4_c}); >(function() { return x + v4_c}) : () => number >function() { return x + v4_c} : () => number >x + v4_c : number ->x : number +>x : 1 >v4_c : number (() => x); >(() => x) : () => number >() => x : () => number ->x : number +>x : 1 } for (const x = 0, y = 1; x < 1;) { ->x : number ->0 : number ->y : number ->1 : number +>x : 0 +>0 : 0 +>y : 1 +>1 : 1 >x < 1 : boolean ->x : number ->1 : number +>x : 0 +>1 : 1 var v5_c = x; >v5_c : number ->x : number +>x : 0 (function() { return x + y + v5_c}); >(function() { return x + y + v5_c}) : () => number >function() { return x + y + v5_c} : () => number >x + y + v5_c : number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 >v5_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 0 +>y : 1 } while (1 === 1) { @@ -508,58 +508,58 @@ while (1 === 1) { >1 : 1 const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v6_c = x; >v6_c : number ->x : number +>x : 1 (function() { return x + y + v6_c}); >(function() { return x + y + v6_c}) : () => number >function() { return x + y + v6_c} : () => number >x + y + v6_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v6_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } do { const x = 1, y = 1; ->x : number ->1 : number ->y : number ->1 : number +>x : 1 +>1 : 1 +>y : 1 +>1 : 1 var v7_c = x; >v7_c : number ->x : number +>x : 1 (function() { return x + y + v7_c}); >(function() { return x + y + v7_c}) : () => number >function() { return x + y + v7_c} : () => number >x + y + v7_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 >v7_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 1 } while (1 === 1) >1 === 1 : boolean @@ -567,34 +567,34 @@ do { >1 : 1 for (const y = 0; y < 1;) { ->y : number ->0 : number +>y : 0 +>0 : 0 >y < 1 : boolean ->y : number ->1 : number +>y : 0 +>1 : 1 const x = 1; ->x : number ->1 : number +>x : 1 +>1 : 1 var v8_c = x; >v8_c : number ->x : number +>x : 1 (function() { return x + y + v8_c}); >(function() { return x + y + v8_c}) : () => number >function() { return x + y + v8_c} : () => number >x + y + v8_c : number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 >v8_c : number (() => x + y); >(() => x + y) : () => number >() => x + y : () => number >x + y : number ->x : number ->y : number +>x : 1 +>y : 0 } diff --git a/tests/baselines/reference/capturedLetConstInLoop5.errors.txt b/tests/baselines/reference/capturedLetConstInLoop5.errors.txt index b182d8347de..cb641af478d 100644 --- a/tests/baselines/reference/capturedLetConstInLoop5.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop5.errors.txt @@ -1,12 +1,8 @@ -tests/cases/compiler/capturedLetConstInLoop5.ts(170,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop5.ts(174,13): error TS2365: Operator '==' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5.ts(211,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5.ts(225,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop5.ts(229,13): error TS2365: Operator '==' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5.ts(268,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop5.ts (6 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop5.ts (2 errors) ==== declare function use(a: any); //====let @@ -177,8 +173,6 @@ tests/cases/compiler/capturedLetConstInLoop5.ts(268,23): error TS2365: Operator function foo1_c(x) { for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = x; (function() { return x + v }); (() => x + v); @@ -222,8 +216,6 @@ tests/cases/compiler/capturedLetConstInLoop5.ts(268,23): error TS2365: Operator function foo4_c(x) { for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = y; let x = 1; (function() { return x + v }); @@ -238,8 +230,6 @@ tests/cases/compiler/capturedLetConstInLoop5.ts(268,23): error TS2365: Operator function foo5_c(x) { for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = x; (function() { return x + y + v }); (() => x + y + v); @@ -285,8 +275,6 @@ tests/cases/compiler/capturedLetConstInLoop5.ts(268,23): error TS2365: Operator function foo8_c(x) { for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; var v = x; (function() { return x + y + v }); diff --git a/tests/baselines/reference/capturedLetConstInLoop5_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop5_ES6.errors.txt index 05eb0626e2d..a9a4742631a 100644 --- a/tests/baselines/reference/capturedLetConstInLoop5_ES6.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop5_ES6.errors.txt @@ -1,12 +1,8 @@ -tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(171,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(175,13): error TS2365: Operator '==' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(212,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(226,30): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(230,13): error TS2365: Operator '==' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(269,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop5_ES6.ts (6 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop5_ES6.ts (2 errors) ==== declare function use(a: any); @@ -178,8 +174,6 @@ tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(269,23): error TS2365: Opera function foo1_c(x) { for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = x; (function() { return x + v }); (() => x + v); @@ -223,8 +217,6 @@ tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(269,23): error TS2365: Opera function foo4_c(x) { for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = y; let x = 1; (function() { return x + v }); @@ -239,8 +231,6 @@ tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(269,23): error TS2365: Opera function foo5_c(x) { for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. var v = x; (function() { return x + y + v }); (() => x + y + v); @@ -286,8 +276,6 @@ tests/cases/compiler/capturedLetConstInLoop5_ES6.ts(269,23): error TS2365: Opera function foo8_c(x) { for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; var v = x; (function() { return x + y + v }); diff --git a/tests/baselines/reference/capturedLetConstInLoop6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop6.errors.txt index c332c5b7323..cc5d238e7af 100644 --- a/tests/baselines/reference/capturedLetConstInLoop6.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop6.errors.txt @@ -1,14 +1,10 @@ -tests/cases/compiler/capturedLetConstInLoop6.ts(144,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6.ts(147,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6.ts(150,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop6.ts(179,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop6.ts(191,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6.ts(194,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6.ts(197,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop6.ts(226,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop6.ts (8 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop6.ts (4 errors) ==== // ====let for (let x of []) { (function() { return x}); @@ -153,8 +149,6 @@ tests/cases/compiler/capturedLetConstInLoop6.ts(226,19): error TS2365: Operator for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x}); (() => x); if (x == 1) { @@ -194,8 +188,6 @@ tests/cases/compiler/capturedLetConstInLoop6.ts(226,19): error TS2365: Operator } while (1 === 1) for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x}); (() => x); @@ -208,8 +200,6 @@ tests/cases/compiler/capturedLetConstInLoop6.ts(226,19): error TS2365: Operator } for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y}); (() => x + y); if (x == 1) { @@ -249,8 +239,6 @@ tests/cases/compiler/capturedLetConstInLoop6.ts(226,19): error TS2365: Operator } while (1 === 1) for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x + y}); (() => x + y); diff --git a/tests/baselines/reference/capturedLetConstInLoop6_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop6_ES6.errors.txt index 18ecfe7c666..4e563153ac9 100644 --- a/tests/baselines/reference/capturedLetConstInLoop6_ES6.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop6_ES6.errors.txt @@ -1,14 +1,10 @@ -tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(144,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(147,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(150,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(179,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(191,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(194,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(197,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(226,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop6_ES6.ts (8 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop6_ES6.ts (4 errors) ==== // ====let for (let x of []) { (function() { return x}); @@ -153,8 +149,6 @@ tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(226,19): error TS2365: Opera for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x}); (() => x); if (x == 1) { @@ -194,8 +188,6 @@ tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(226,19): error TS2365: Opera } while (1 === 1) for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x}); (() => x); @@ -208,8 +200,6 @@ tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(226,19): error TS2365: Opera } for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y}); (() => x + y); if (x == 1) { @@ -249,8 +239,6 @@ tests/cases/compiler/capturedLetConstInLoop6_ES6.ts(226,19): error TS2365: Opera } while (1 === 1) for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x + y}); (() => x + y); diff --git a/tests/baselines/reference/capturedLetConstInLoop7.errors.txt b/tests/baselines/reference/capturedLetConstInLoop7.errors.txt index 29e6fbca6cd..4b8e512f41a 100644 --- a/tests/baselines/reference/capturedLetConstInLoop7.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop7.errors.txt @@ -1,18 +1,14 @@ -tests/cases/compiler/capturedLetConstInLoop7.ts(227,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(230,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(233,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(236,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. tests/cases/compiler/capturedLetConstInLoop7.ts(239,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop7.ts(283,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop7.ts(302,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(305,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(308,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7.ts(311,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. tests/cases/compiler/capturedLetConstInLoop7.ts(314,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop7.ts(359,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop7.ts (12 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop7.ts (8 errors) ==== //===let l0: for (let x of []) { @@ -240,8 +236,6 @@ tests/cases/compiler/capturedLetConstInLoop7.ts(359,19): error TS2365: Operator l1_c: for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x}); (() => x); if (x == 1) { @@ -306,8 +300,6 @@ tests/cases/compiler/capturedLetConstInLoop7.ts(359,19): error TS2365: Operator l4_c: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x}); (() => x); @@ -327,8 +319,6 @@ tests/cases/compiler/capturedLetConstInLoop7.ts(359,19): error TS2365: Operator l5_c: for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y}); (() => x + y); if (x == 1) { @@ -394,8 +384,6 @@ tests/cases/compiler/capturedLetConstInLoop7.ts(359,19): error TS2365: Operator l8_c: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x + y}); (() => x + y); diff --git a/tests/baselines/reference/capturedLetConstInLoop7_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop7_ES6.errors.txt index a2001dc09b3..30e2db6a253 100644 --- a/tests/baselines/reference/capturedLetConstInLoop7_ES6.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop7_ES6.errors.txt @@ -1,18 +1,14 @@ -tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(227,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(230,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(233,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(236,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(239,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(283,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(302,26): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(305,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(308,9): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(311,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(314,9): error TS2365: Operator '==' cannot be applied to types '0' and '2'. -tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(359,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/capturedLetConstInLoop7_ES6.ts (12 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop7_ES6.ts (8 errors) ==== //===let l0: for (let x of []) { @@ -240,8 +236,6 @@ tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(359,19): error TS2365: Opera l1_c: for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x}); (() => x); if (x == 1) { @@ -306,8 +300,6 @@ tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(359,19): error TS2365: Opera l4_c: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x}); (() => x); @@ -327,8 +319,6 @@ tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(359,19): error TS2365: Opera l5_c: for (const x = 0, y = 1; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y}); (() => x + y); if (x == 1) { @@ -394,8 +384,6 @@ tests/cases/compiler/capturedLetConstInLoop7_ES6.ts(359,19): error TS2365: Opera l8_c: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. const x = 1; (function() { return x + y}); (() => x + y); diff --git a/tests/baselines/reference/capturedLetConstInLoop8.errors.txt b/tests/baselines/reference/capturedLetConstInLoop8.errors.txt index c3743feaf90..d54c79dfebb 100644 --- a/tests/baselines/reference/capturedLetConstInLoop8.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop8.errors.txt @@ -1,6 +1,3 @@ -tests/cases/compiler/capturedLetConstInLoop8.ts(66,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop8.ts(68,27): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop8.ts(70,31): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8.ts(73,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8.ts(76,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8.ts(79,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. @@ -19,7 +16,7 @@ tests/cases/compiler/capturedLetConstInLoop8.ts(117,17): error TS2365: Operator tests/cases/compiler/capturedLetConstInLoop8.ts(120,17): error TS2365: Operator '==' cannot be applied to types '0' and '3'. -==== tests/cases/compiler/capturedLetConstInLoop8.ts (19 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop8.ts (16 errors) ==== function foo() { l0: for (let z = 0; z < 1; ++z) { @@ -86,16 +83,10 @@ tests/cases/compiler/capturedLetConstInLoop8.ts(120,17): error TS2365: Operator function foo_c() { l0: for (const z = 0; z < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. l1: for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. ll1: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y }); (() => x + y); if (y == 1) { diff --git a/tests/baselines/reference/capturedLetConstInLoop8_ES6.errors.txt b/tests/baselines/reference/capturedLetConstInLoop8_ES6.errors.txt index da6947884fa..b8e856b66bf 100644 --- a/tests/baselines/reference/capturedLetConstInLoop8_ES6.errors.txt +++ b/tests/baselines/reference/capturedLetConstInLoop8_ES6.errors.txt @@ -1,6 +1,3 @@ -tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(66,23): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(68,27): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(70,31): error TS2365: Operator '<' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(73,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(76,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(79,21): error TS2365: Operator '==' cannot be applied to types '0' and '1'. @@ -19,7 +16,7 @@ tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(117,17): error TS2365: Opera tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(120,17): error TS2365: Operator '==' cannot be applied to types '0' and '3'. -==== tests/cases/compiler/capturedLetConstInLoop8_ES6.ts (19 errors) ==== +==== tests/cases/compiler/capturedLetConstInLoop8_ES6.ts (16 errors) ==== function foo() { l0: for (let z = 0; z < 1; ++z) { @@ -86,16 +83,10 @@ tests/cases/compiler/capturedLetConstInLoop8_ES6.ts(120,17): error TS2365: Opera function foo_c() { l0: for (const z = 0; z < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. l1: for (const x = 0; x < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. ll1: for (const y = 0; y < 1;) { - ~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. (function() { return x + y }); (() => x + y); if (y == 1) { diff --git a/tests/baselines/reference/capturedLetConstInLoop9.js b/tests/baselines/reference/capturedLetConstInLoop9.js index 84f9a021054..8f88855a9ad 100644 --- a/tests/baselines/reference/capturedLetConstInLoop9.js +++ b/tests/baselines/reference/capturedLetConstInLoop9.js @@ -208,6 +208,7 @@ function foo() { } (function () { return b; }); return { value: 100 }; + var _a; }; for (var _c = 0, _d = []; _c < _d.length; _c++) { var b = _d[_c]; @@ -221,6 +222,7 @@ function foo() { } } (function () { return a; }); + var _b; }; var arguments_1 = arguments, x, z, x1, z1; l0: for (var _i = 0, _a = []; _i < _a.length; _i++) { @@ -238,7 +240,6 @@ function foo() { use(z); use(x1); use(z1); - var _b, _a; } function foo2() { for (var _i = 0, _a = []; _i < _a.length; _i++) { diff --git a/tests/baselines/reference/capturedLetConstInLoop9.types b/tests/baselines/reference/capturedLetConstInLoop9.types index 453176a40c9..486697b8d84 100644 --- a/tests/baselines/reference/capturedLetConstInLoop9.types +++ b/tests/baselines/reference/capturedLetConstInLoop9.types @@ -39,7 +39,7 @@ for (let x = 0; x < 1; ++x) { } switch (x) { ->x : undefined +>x : any case 1: >1 : 1 diff --git a/tests/baselines/reference/capturedLetConstInLoop9_ES6.types b/tests/baselines/reference/capturedLetConstInLoop9_ES6.types index df118279f30..be4457315ee 100644 --- a/tests/baselines/reference/capturedLetConstInLoop9_ES6.types +++ b/tests/baselines/reference/capturedLetConstInLoop9_ES6.types @@ -40,7 +40,7 @@ for (let x = 0; x < 1; ++x) { } switch (x) { ->x : undefined +>x : any case 1: >1 : 1 diff --git a/tests/baselines/reference/castOfAwait.js b/tests/baselines/reference/castOfAwait.js index 1f66d49e0f3..9f67f74b11b 100644 --- a/tests/baselines/reference/castOfAwait.js +++ b/tests/baselines/reference/castOfAwait.js @@ -14,7 +14,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function f() { diff --git a/tests/baselines/reference/catchClauseWithBindingPattern1.errors.txt b/tests/baselines/reference/catchClauseWithBindingPattern1.errors.txt deleted file mode 100644 index 0b7482850e5..00000000000 --- a/tests/baselines/reference/catchClauseWithBindingPattern1.errors.txt +++ /dev/null @@ -1,10 +0,0 @@ -tests/cases/compiler/catchClauseWithBindingPattern1.ts(3,8): error TS1195: Catch clause variable name must be an identifier. - - -==== tests/cases/compiler/catchClauseWithBindingPattern1.ts (1 errors) ==== - try { - } - catch ({a}) { - ~ -!!! error TS1195: Catch clause variable name must be an identifier. - } \ No newline at end of file diff --git a/tests/baselines/reference/catchClauseWithBindingPattern1.js b/tests/baselines/reference/catchClauseWithBindingPattern1.js deleted file mode 100644 index bbdc259946c..00000000000 --- a/tests/baselines/reference/catchClauseWithBindingPattern1.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [catchClauseWithBindingPattern1.ts] -try { -} -catch ({a}) { -} - -//// [catchClauseWithBindingPattern1.js] -try { -} -catch (a = (void 0).a) { -} diff --git a/tests/baselines/reference/checkSuperCallBeforeThisAccessing5.js b/tests/baselines/reference/checkSuperCallBeforeThisAccessing5.js index 8c7f18b77f6..ded73f57baf 100644 --- a/tests/baselines/reference/checkSuperCallBeforeThisAccessing5.js +++ b/tests/baselines/reference/checkSuperCallBeforeThisAccessing5.js @@ -17,7 +17,7 @@ var Based = (function () { function Based() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } return Based; @@ -25,7 +25,8 @@ var Based = (function () { var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - return _super.call(this, this.x) || this; + var _this = _super.call(this, _this.x) || this; + return _this; } return Derived; }(Based)); diff --git a/tests/baselines/reference/checkSuperCallBeforeThisAccessing6.js b/tests/baselines/reference/checkSuperCallBeforeThisAccessing6.js index cc8912230ab..782e3236271 100644 --- a/tests/baselines/reference/checkSuperCallBeforeThisAccessing6.js +++ b/tests/baselines/reference/checkSuperCallBeforeThisAccessing6.js @@ -20,7 +20,7 @@ var Base = (function () { function Base() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } return Base; diff --git a/tests/baselines/reference/checkSuperCallBeforeThisAccessing7.js b/tests/baselines/reference/checkSuperCallBeforeThisAccessing7.js index ca12c16e047..364aed4d4b0 100644 --- a/tests/baselines/reference/checkSuperCallBeforeThisAccessing7.js +++ b/tests/baselines/reference/checkSuperCallBeforeThisAccessing7.js @@ -23,7 +23,8 @@ var Base = (function () { var Super = (function (_super) { __extends(Super, _super); function Super() { - return _super.call(this, (function () { return _this; })) || this; + var _this = _super.call(this, (function () { return _this; })) || this; + return _this; } return Super; }(Base)); diff --git a/tests/baselines/reference/checkSuperCallBeforeThisAccessing8.js b/tests/baselines/reference/checkSuperCallBeforeThisAccessing8.js index 25a480b9b57..5dd3708a3bb 100644 --- a/tests/baselines/reference/checkSuperCallBeforeThisAccessing8.js +++ b/tests/baselines/reference/checkSuperCallBeforeThisAccessing8.js @@ -20,7 +20,7 @@ var Base = (function () { function Base() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } return Base; diff --git a/tests/baselines/reference/circularIndexedAccessErrors.errors.txt b/tests/baselines/reference/circularIndexedAccessErrors.errors.txt new file mode 100644 index 00000000000..e3076e08b7e --- /dev/null +++ b/tests/baselines/reference/circularIndexedAccessErrors.errors.txt @@ -0,0 +1,57 @@ +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(3,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(7,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(15,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(19,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(23,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(27,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(28,5): error TS2502: 'y' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts(29,5): error TS2502: 'z' is referenced directly or indirectly in its own type annotation. + + +==== tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts (8 errors) ==== + + type T1 = { + x: T1["x"]; // Error + ~~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + }; + + type T2 = { + x: T2[K]; // Error + ~~~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + y: number; + } + + declare let x2: T2<"x">; + let x2x = x2.x; + + interface T3> { + x: T["x"]; // Error + ~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + } + + interface T4> { + x: T4["x"]; // Error + ~~~~~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + } + + class C1 { + x: C1["x"]; // Error + ~~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + } + + class C2 { + x: this["y"]; // Error + ~~~~~~~~~~~~~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. + y: this["z"]; // Error + ~~~~~~~~~~~~~ +!!! error TS2502: 'y' is referenced directly or indirectly in its own type annotation. + z: this["x"]; // Error + ~~~~~~~~~~~~~ +!!! error TS2502: 'z' is referenced directly or indirectly in its own type annotation. + } \ No newline at end of file diff --git a/tests/baselines/reference/circularIndexedAccessErrors.js b/tests/baselines/reference/circularIndexedAccessErrors.js new file mode 100644 index 00000000000..46784ae8d18 --- /dev/null +++ b/tests/baselines/reference/circularIndexedAccessErrors.js @@ -0,0 +1,70 @@ +//// [circularIndexedAccessErrors.ts] + +type T1 = { + x: T1["x"]; // Error +}; + +type T2 = { + x: T2[K]; // Error + y: number; +} + +declare let x2: T2<"x">; +let x2x = x2.x; + +interface T3> { + x: T["x"]; // Error +} + +interface T4> { + x: T4["x"]; // Error +} + +class C1 { + x: C1["x"]; // Error +} + +class C2 { + x: this["y"]; // Error + y: this["z"]; // Error + z: this["x"]; // Error +} + +//// [circularIndexedAccessErrors.js] +var x2x = x2.x; +var C1 = (function () { + function C1() { + } + return C1; +}()); +var C2 = (function () { + function C2() { + } + return C2; +}()); + + +//// [circularIndexedAccessErrors.d.ts] +declare type T1 = { + x: T1["x"]; +}; +declare type T2 = { + x: T2[K]; + y: number; +}; +declare let x2: T2<"x">; +declare let x2x: any; +interface T3> { + x: T["x"]; +} +interface T4> { + x: T4["x"]; +} +declare class C1 { + x: C1["x"]; +} +declare class C2 { + x: this["y"]; + y: this["z"]; + z: this["x"]; +} diff --git a/tests/baselines/reference/circularReferenceInImport.js b/tests/baselines/reference/circularReferenceInImport.js new file mode 100644 index 00000000000..a9cf0925c34 --- /dev/null +++ b/tests/baselines/reference/circularReferenceInImport.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/circularReferenceInImport.ts] //// + +//// [db.d.ts] + +declare namespace Db { + export import Types = Db; +} + +export = Db; + +//// [app.ts] +import * as Db from "./db" + +export function foo() { + return new Object() +} + +//// [app.js] +"use strict"; +function foo() { + return new Object(); +} +exports.foo = foo; + + +//// [app.d.ts] +export declare function foo(): Object; diff --git a/tests/baselines/reference/circularReferenceInImport.symbols b/tests/baselines/reference/circularReferenceInImport.symbols new file mode 100644 index 00000000000..b74ac14b5ab --- /dev/null +++ b/tests/baselines/reference/circularReferenceInImport.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/db.d.ts === + +declare namespace Db { +>Db : Symbol(Types, Decl(db.d.ts, 0, 0)) + + export import Types = Db; +>Types : Symbol(Types, Decl(db.d.ts, 1, 22)) +>Db : Symbol(Types, Decl(db.d.ts, 0, 0)) +} + +export = Db; +>Db : Symbol(Db, Decl(db.d.ts, 0, 0)) + +=== tests/cases/compiler/app.ts === +import * as Db from "./db" +>Db : Symbol(Db, Decl(app.ts, 0, 6)) + +export function foo() { +>foo : Symbol(foo, Decl(app.ts, 0, 26)) + + return new Object() +>Object : Symbol(Object, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} diff --git a/tests/baselines/reference/circularReferenceInImport.types b/tests/baselines/reference/circularReferenceInImport.types new file mode 100644 index 00000000000..d8db7f56231 --- /dev/null +++ b/tests/baselines/reference/circularReferenceInImport.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/db.d.ts === + +declare namespace Db { +>Db : typeof Types + + export import Types = Db; +>Types : typeof Types +>Db : typeof Types +} + +export = Db; +>Db : typeof Db + +=== tests/cases/compiler/app.ts === +import * as Db from "./db" +>Db : typeof Db + +export function foo() { +>foo : () => Object + + return new Object() +>new Object() : Object +>Object : ObjectConstructor +} diff --git a/tests/baselines/reference/classAbstractAccessor.errors.txt b/tests/baselines/reference/classAbstractAccessor.errors.txt new file mode 100644 index 00000000000..b43cfa9d7f1 --- /dev/null +++ b/tests/baselines/reference/classAbstractAccessor.errors.txt @@ -0,0 +1,17 @@ +tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts(4,17): error TS1318: An abstract accessor cannot have an implementation. +tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts(6,17): error TS1318: An abstract accessor cannot have an implementation. + + +==== tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts (2 errors) ==== + + abstract class A { + abstract get a(); + abstract get aa() { return 1; } // error + ~~ +!!! error TS1318: An abstract accessor cannot have an implementation. + abstract set b(x: string); + abstract set bb(x: string) {} // error + ~~ +!!! error TS1318: An abstract accessor cannot have an implementation. + } + \ No newline at end of file diff --git a/tests/baselines/reference/classAbstractAccessor.js b/tests/baselines/reference/classAbstractAccessor.js new file mode 100644 index 00000000000..a1edf0cb88d --- /dev/null +++ b/tests/baselines/reference/classAbstractAccessor.js @@ -0,0 +1,28 @@ +//// [classAbstractAccessor.ts] + +abstract class A { + abstract get a(); + abstract get aa() { return 1; } // error + abstract set b(x: string); + abstract set bb(x: string) {} // error +} + + +//// [classAbstractAccessor.js] +var A = (function () { + function A() { + } + Object.defineProperty(A.prototype, "aa", { + get: function () { return 1; } // error + , + enumerable: true, + configurable: true + }); + Object.defineProperty(A.prototype, "bb", { + set: function (x) { } // error + , + enumerable: true, + configurable: true + }); + return A; +}()); diff --git a/tests/baselines/reference/classDeclaredBeforeClassFactory.js b/tests/baselines/reference/classDeclaredBeforeClassFactory.js new file mode 100644 index 00000000000..3dd1e7a4aaf --- /dev/null +++ b/tests/baselines/reference/classDeclaredBeforeClassFactory.js @@ -0,0 +1,30 @@ +//// [classDeclaredBeforeClassFactory.ts] +// Should be OK due to hoisting +class Derived extends makeBaseClass() {} + +function makeBaseClass() { + return class Base {}; +} + + +//// [classDeclaredBeforeClassFactory.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +// Should be OK due to hoisting +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + return _super.apply(this, arguments) || this; + } + return Derived; +}(makeBaseClass())); +function makeBaseClass() { + return (function () { + function Base() { + } + return Base; + }()); +} diff --git a/tests/baselines/reference/classDeclaredBeforeClassFactory.symbols b/tests/baselines/reference/classDeclaredBeforeClassFactory.symbols new file mode 100644 index 00000000000..cf23402c3b4 --- /dev/null +++ b/tests/baselines/reference/classDeclaredBeforeClassFactory.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/classDeclaredBeforeClassFactory.ts === +// Should be OK due to hoisting +class Derived extends makeBaseClass() {} +>Derived : Symbol(Derived, Decl(classDeclaredBeforeClassFactory.ts, 0, 0)) +>makeBaseClass : Symbol(makeBaseClass, Decl(classDeclaredBeforeClassFactory.ts, 1, 40)) + +function makeBaseClass() { +>makeBaseClass : Symbol(makeBaseClass, Decl(classDeclaredBeforeClassFactory.ts, 1, 40)) + + return class Base {}; +>Base : Symbol(Base, Decl(classDeclaredBeforeClassFactory.ts, 4, 10)) +} + diff --git a/tests/baselines/reference/classDeclaredBeforeClassFactory.types b/tests/baselines/reference/classDeclaredBeforeClassFactory.types new file mode 100644 index 00000000000..0fc2437381f --- /dev/null +++ b/tests/baselines/reference/classDeclaredBeforeClassFactory.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/classDeclaredBeforeClassFactory.ts === +// Should be OK due to hoisting +class Derived extends makeBaseClass() {} +>Derived : Derived +>makeBaseClass() : Base +>makeBaseClass : () => typeof Base + +function makeBaseClass() { +>makeBaseClass : () => typeof Base + + return class Base {}; +>class Base {} : typeof Base +>Base : typeof Base +} + diff --git a/tests/baselines/reference/classExpression3.errors.txt b/tests/baselines/reference/classExpression3.errors.txt deleted file mode 100644 index 2a7a2e160f1..00000000000 --- a/tests/baselines/reference/classExpression3.errors.txt +++ /dev/null @@ -1,15 +0,0 @@ -tests/cases/conformance/classes/classExpressions/classExpression3.ts(1,23): error TS2690: A class must be declared after its base class. -tests/cases/conformance/classes/classExpressions/classExpression3.ts(1,37): error TS2690: A class must be declared after its base class. - - -==== tests/cases/conformance/classes/classExpressions/classExpression3.ts (2 errors) ==== - let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2690: A class must be declared after its base class. - ~~~~~~~~~~~~~~~ -!!! error TS2690: A class must be declared after its base class. - let c = new C(); - c.a; - c.b; - c.c; - \ No newline at end of file diff --git a/tests/baselines/reference/classExpression3.symbols b/tests/baselines/reference/classExpression3.symbols new file mode 100644 index 00000000000..bc1b263a000 --- /dev/null +++ b/tests/baselines/reference/classExpression3.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression3.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : Symbol(C, Decl(classExpression3.ts, 0, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) +>b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) +>c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) + +let c = new C(); +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>C : Symbol(C, Decl(classExpression3.ts, 0, 3)) + +c.a; +>c.a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) + +c.b; +>c.b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) + +c.c; +>c.c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) + diff --git a/tests/baselines/reference/classExpression3.types b/tests/baselines/reference/classExpression3.types new file mode 100644 index 00000000000..51798f300d4 --- /dev/null +++ b/tests/baselines/reference/classExpression3.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression3.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : typeof (Anonymous class) +>class extends class extends class { a = 1 } { b = 2 } { c = 3 } : typeof (Anonymous class) +>class extends class { a = 1 } { b = 2 } : (Anonymous class) +>class { a = 1 } : (Anonymous class) +>a : number +>1 : 1 +>b : number +>2 : 2 +>c : number +>3 : 3 + +let c = new C(); +>c : (Anonymous class) +>new C() : (Anonymous class) +>C : typeof (Anonymous class) + +c.a; +>c.a : number +>c : (Anonymous class) +>a : number + +c.b; +>c.b : number +>c : (Anonymous class) +>b : number + +c.c; +>c.c : number +>c : (Anonymous class) +>c : number + diff --git a/tests/baselines/reference/classExpressionES63.errors.txt b/tests/baselines/reference/classExpressionES63.errors.txt deleted file mode 100644 index 9463162e4a6..00000000000 --- a/tests/baselines/reference/classExpressionES63.errors.txt +++ /dev/null @@ -1,15 +0,0 @@ -tests/cases/conformance/es6/classExpressions/classExpressionES63.ts(1,23): error TS2690: A class must be declared after its base class. -tests/cases/conformance/es6/classExpressions/classExpressionES63.ts(1,37): error TS2690: A class must be declared after its base class. - - -==== tests/cases/conformance/es6/classExpressions/classExpressionES63.ts (2 errors) ==== - let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2690: A class must be declared after its base class. - ~~~~~~~~~~~~~~~ -!!! error TS2690: A class must be declared after its base class. - let c = new C(); - c.a; - c.b; - c.c; - \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionES63.symbols b/tests/baselines/reference/classExpressionES63.symbols new file mode 100644 index 00000000000..4e52d5ee9dd --- /dev/null +++ b/tests/baselines/reference/classExpressionES63.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES63.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : Symbol(C, Decl(classExpressionES63.ts, 0, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) +>b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) +>c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) + +let c = new C(); +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>C : Symbol(C, Decl(classExpressionES63.ts, 0, 3)) + +c.a; +>c.a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) + +c.b; +>c.b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) + +c.c; +>c.c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) + diff --git a/tests/baselines/reference/classExpressionES63.types b/tests/baselines/reference/classExpressionES63.types new file mode 100644 index 00000000000..c5c8de91c17 --- /dev/null +++ b/tests/baselines/reference/classExpressionES63.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES63.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : typeof (Anonymous class) +>class extends class extends class { a = 1 } { b = 2 } { c = 3 } : typeof (Anonymous class) +>class extends class { a = 1 } { b = 2 } : (Anonymous class) +>class { a = 1 } : (Anonymous class) +>a : number +>1 : 1 +>b : number +>2 : 2 +>c : number +>3 : 3 + +let c = new C(); +>c : (Anonymous class) +>new C() : (Anonymous class) +>C : typeof (Anonymous class) + +c.a; +>c.a : number +>c : (Anonymous class) +>a : number + +c.b; +>c.b : number +>c : (Anonymous class) +>b : number + +c.c; +>c.c : number +>c : (Anonymous class) +>c : number + diff --git a/tests/baselines/reference/classExpressions.js b/tests/baselines/reference/classExpressions.js new file mode 100644 index 00000000000..3932fa5045b --- /dev/null +++ b/tests/baselines/reference/classExpressions.js @@ -0,0 +1,20 @@ +//// [classExpressions.ts] +interface A {} +let x = class B implements A { + prop: number; + onStart(): void { + } + func = () => { + } +}; + +//// [classExpressions.js] +var x = (function () { + function B() { + this.func = function () { + }; + } + B.prototype.onStart = function () { + }; + return B; +}()); diff --git a/tests/baselines/reference/classExpressions.symbols b/tests/baselines/reference/classExpressions.symbols new file mode 100644 index 00000000000..038b1b81116 --- /dev/null +++ b/tests/baselines/reference/classExpressions.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/classExpressions.ts === +interface A {} +>A : Symbol(A, Decl(classExpressions.ts, 0, 0)) + +let x = class B implements A { +>x : Symbol(x, Decl(classExpressions.ts, 1, 3)) +>B : Symbol(B, Decl(classExpressions.ts, 1, 7)) +>A : Symbol(A, Decl(classExpressions.ts, 0, 0)) + + prop: number; +>prop : Symbol(B.prop, Decl(classExpressions.ts, 1, 30)) + + onStart(): void { +>onStart : Symbol(B.onStart, Decl(classExpressions.ts, 2, 17)) + } + func = () => { +>func : Symbol(B.func, Decl(classExpressions.ts, 4, 5)) + } +}; diff --git a/tests/baselines/reference/classExpressions.types b/tests/baselines/reference/classExpressions.types new file mode 100644 index 00000000000..3fcff32c4a4 --- /dev/null +++ b/tests/baselines/reference/classExpressions.types @@ -0,0 +1,21 @@ +=== tests/cases/compiler/classExpressions.ts === +interface A {} +>A : A + +let x = class B implements A { +>x : typeof B +>class B implements A { prop: number; onStart(): void { } func = () => { }} : typeof B +>B : typeof B +>A : A + + prop: number; +>prop : number + + onStart(): void { +>onStart : () => void + } + func = () => { +>func : () => void +>() => { } : () => void + } +}; diff --git a/tests/baselines/reference/classMethodWithKeywordName1.js b/tests/baselines/reference/classMethodWithKeywordName1.js index 6e1faee005c..a7cb994bfb3 100644 --- a/tests/baselines/reference/classMethodWithKeywordName1.js +++ b/tests/baselines/reference/classMethodWithKeywordName1.js @@ -7,6 +7,6 @@ class C { var C = (function () { function C() { } - C.try = function () { }; + C["try"] = function () { }; return C; }()); diff --git a/tests/baselines/reference/collisionArgumentsArrowFunctions.js b/tests/baselines/reference/collisionArgumentsArrowFunctions.js index 0aa939e1a2d..3e56b8b2f9c 100644 --- a/tests/baselines/reference/collisionArgumentsArrowFunctions.js +++ b/tests/baselines/reference/collisionArgumentsArrowFunctions.js @@ -37,7 +37,7 @@ var f1NoError = function (arguments) { var f2 = function () { var restParameters = []; for (var _i = 0; _i < arguments.length; _i++) { - restParameters[_i - 0] = arguments[_i]; + restParameters[_i] = arguments[_i]; } var arguments = 10; // No Error }; diff --git a/tests/baselines/reference/collisionArgumentsClassConstructor.js b/tests/baselines/reference/collisionArgumentsClassConstructor.js index 570b10d39d3..57ffa88f4e1 100644 --- a/tests/baselines/reference/collisionArgumentsClassConstructor.js +++ b/tests/baselines/reference/collisionArgumentsClassConstructor.js @@ -118,7 +118,7 @@ var c2 = (function () { function c2() { var restParameters = []; for (var _i = 0; _i < arguments.length; _i++) { - restParameters[_i - 0] = arguments[_i]; + restParameters[_i] = arguments[_i]; } var arguments = 10; // no error } diff --git a/tests/baselines/reference/collisionArgumentsClassMethod.js b/tests/baselines/reference/collisionArgumentsClassMethod.js index a20e0385e6a..85610926e35 100644 --- a/tests/baselines/reference/collisionArgumentsClassMethod.js +++ b/tests/baselines/reference/collisionArgumentsClassMethod.js @@ -94,7 +94,7 @@ var c3 = (function () { c3.prototype.foo = function () { var restParameters = []; for (var _i = 0; _i < arguments.length; _i++) { - restParameters[_i - 0] = arguments[_i]; + restParameters[_i] = arguments[_i]; } var arguments = 10; // no error }; diff --git a/tests/baselines/reference/collisionArgumentsFunction.js b/tests/baselines/reference/collisionArgumentsFunction.js index 9ce4a5ab0e2..c6a26baa495 100644 --- a/tests/baselines/reference/collisionArgumentsFunction.js +++ b/tests/baselines/reference/collisionArgumentsFunction.js @@ -66,7 +66,7 @@ function f1NoError(arguments) { function f3() { var restParameters = []; for (var _i = 0; _i < arguments.length; _i++) { - restParameters[_i - 0] = arguments[_i]; + restParameters[_i] = arguments[_i]; } var arguments = 10; // no error } diff --git a/tests/baselines/reference/collisionArgumentsFunctionExpressions.js b/tests/baselines/reference/collisionArgumentsFunctionExpressions.js index 405ceb625c3..b3389ddbf4a 100644 --- a/tests/baselines/reference/collisionArgumentsFunctionExpressions.js +++ b/tests/baselines/reference/collisionArgumentsFunctionExpressions.js @@ -56,7 +56,7 @@ function foo() { function f3() { var restParameters = []; for (var _i = 0; _i < arguments.length; _i++) { - restParameters[_i - 0] = arguments[_i]; + restParameters[_i] = arguments[_i]; } var arguments = 10; // no error } diff --git a/tests/baselines/reference/collisionExportsRequireAndEnum.js b/tests/baselines/reference/collisionExportsRequireAndEnum.js index 3935ee312fb..47d127e8a67 100644 --- a/tests/baselines/reference/collisionExportsRequireAndEnum.js +++ b/tests/baselines/reference/collisionExportsRequireAndEnum.js @@ -63,16 +63,16 @@ module m4 { //// [collisionExportsRequireAndEnum_externalmodule.js] define(["require", "exports"], function (require, exports) { "use strict"; + var require; (function (require) { require[require["_thisVal1"] = 0] = "_thisVal1"; require[require["_thisVal2"] = 1] = "_thisVal2"; - })(exports.require || (exports.require = {})); - var require = exports.require; + })(require = exports.require || (exports.require = {})); + var exports; (function (exports) { exports[exports["_thisVal1"] = 0] = "_thisVal1"; exports[exports["_thisVal2"] = 1] = "_thisVal2"; - })(exports.exports || (exports.exports = {})); - var exports = exports.exports; + })(exports = exports.exports || (exports.exports = {})); var m1; (function (m1) { var require; @@ -88,16 +88,16 @@ define(["require", "exports"], function (require, exports) { })(m1 || (m1 = {})); var m2; (function (m2) { + var require; (function (require) { require[require["_thisVal1"] = 0] = "_thisVal1"; require[require["_thisVal2"] = 1] = "_thisVal2"; - })(m2.require || (m2.require = {})); - var require = m2.require; + })(require = m2.require || (m2.require = {})); + var exports; (function (exports) { exports[exports["_thisVal1"] = 0] = "_thisVal1"; exports[exports["_thisVal2"] = 1] = "_thisVal2"; - })(m2.exports || (m2.exports = {})); - var exports = m2.exports; + })(exports = m2.exports || (m2.exports = {})); })(m2 || (m2 = {})); }); //// [collisionExportsRequireAndEnum_globalFile.js] @@ -126,14 +126,14 @@ var m3; })(m3 || (m3 = {})); var m4; (function (m4) { + var require; (function (require) { require[require["_thisVal1"] = 0] = "_thisVal1"; require[require["_thisVal2"] = 1] = "_thisVal2"; - })(m4.require || (m4.require = {})); - var require = m4.require; + })(require = m4.require || (m4.require = {})); + var exports; (function (exports) { exports[exports["_thisVal1"] = 0] = "_thisVal1"; exports[exports["_thisVal2"] = 1] = "_thisVal2"; - })(m4.exports || (m4.exports = {})); - var exports = m4.exports; + })(exports = m4.exports || (m4.exports = {})); })(m4 || (m4 = {})); diff --git a/tests/baselines/reference/collisionRestParameterArrowFunctions.js b/tests/baselines/reference/collisionRestParameterArrowFunctions.js index 39d449555db..3e20f48a4d0 100644 --- a/tests/baselines/reference/collisionRestParameterArrowFunctions.js +++ b/tests/baselines/reference/collisionRestParameterArrowFunctions.js @@ -27,7 +27,7 @@ var f1NoError = function (_i) { var f2 = function () { var restParameters = []; for (var _a = 0; _a < arguments.length; _a++) { - restParameters[_a - 0] = arguments[_a]; + restParameters[_a] = arguments[_a]; } var _i = 10; // No Error }; diff --git a/tests/baselines/reference/collisionRestParameterClassConstructor.js b/tests/baselines/reference/collisionRestParameterClassConstructor.js index 82d2ddc0896..f97e49531f6 100644 --- a/tests/baselines/reference/collisionRestParameterClassConstructor.js +++ b/tests/baselines/reference/collisionRestParameterClassConstructor.js @@ -88,7 +88,7 @@ var c2 = (function () { function c2() { var restParameters = []; for (var _a = 0; _a < arguments.length; _a++) { - restParameters[_a - 0] = arguments[_a]; + restParameters[_a] = arguments[_a]; } var _i = 10; // no error } diff --git a/tests/baselines/reference/collisionRestParameterClassMethod.js b/tests/baselines/reference/collisionRestParameterClassMethod.js index eb92faa7b2a..cda717c79ab 100644 --- a/tests/baselines/reference/collisionRestParameterClassMethod.js +++ b/tests/baselines/reference/collisionRestParameterClassMethod.js @@ -70,7 +70,7 @@ var c3 = (function () { c3.prototype.foo = function () { var restParameters = []; for (var _a = 0; _a < arguments.length; _a++) { - restParameters[_a - 0] = arguments[_a]; + restParameters[_a] = arguments[_a]; } var _i = 10; // no error }; diff --git a/tests/baselines/reference/collisionRestParameterFunction.js b/tests/baselines/reference/collisionRestParameterFunction.js index 8660e8f5db0..651062a696c 100644 --- a/tests/baselines/reference/collisionRestParameterFunction.js +++ b/tests/baselines/reference/collisionRestParameterFunction.js @@ -48,7 +48,7 @@ function f1NoError(_i) { function f3() { var restParameters = []; for (var _a = 0; _a < arguments.length; _a++) { - restParameters[_a - 0] = arguments[_a]; + restParameters[_a] = arguments[_a]; } var _i = 10; // no error } diff --git a/tests/baselines/reference/collisionRestParameterFunctionExpressions.js b/tests/baselines/reference/collisionRestParameterFunctionExpressions.js index 22709b087eb..87bafea09bd 100644 --- a/tests/baselines/reference/collisionRestParameterFunctionExpressions.js +++ b/tests/baselines/reference/collisionRestParameterFunctionExpressions.js @@ -39,7 +39,7 @@ function foo() { function f3() { var restParameters = []; for (var _a = 0; _a < arguments.length; _a++) { - restParameters[_a - 0] = arguments[_a]; + restParameters[_a] = arguments[_a]; } var _i = 10; // no error } diff --git a/tests/baselines/reference/collisionRestParameterUnderscoreIUsage.js b/tests/baselines/reference/collisionRestParameterUnderscoreIUsage.js index 97e82a1523f..1d7f9f43f7c 100644 --- a/tests/baselines/reference/collisionRestParameterUnderscoreIUsage.js +++ b/tests/baselines/reference/collisionRestParameterUnderscoreIUsage.js @@ -14,7 +14,7 @@ var Foo = (function () { function Foo() { var args = []; for (var _a = 0; _a < arguments.length; _a++) { - args[_a - 0] = arguments[_a]; + args[_a] = arguments[_a]; } console.log(_i); // This should result in error } diff --git a/tests/baselines/reference/commaOperatorInConditionalExpression.js b/tests/baselines/reference/commaOperatorInConditionalExpression.js new file mode 100644 index 00000000000..be1705936e4 --- /dev/null +++ b/tests/baselines/reference/commaOperatorInConditionalExpression.js @@ -0,0 +1,14 @@ +//// [commaOperatorInConditionalExpression.ts] +function f (m: string) { + [1, 2, 3].map(i => { + return true? { [m]: i } : { [m]: i + 1 } + }) +} + +//// [commaOperatorInConditionalExpression.js] +function f(m) { + [1, 2, 3].map(function (i) { + return true ? (_a = {}, _a[m] = i, _a) : (_b = {}, _b[m] = i + 1, _b); + var _a, _b; + }); +} diff --git a/tests/baselines/reference/commaOperatorInConditionalExpression.symbols b/tests/baselines/reference/commaOperatorInConditionalExpression.symbols new file mode 100644 index 00000000000..18f749c5c5c --- /dev/null +++ b/tests/baselines/reference/commaOperatorInConditionalExpression.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/commaOperatorInConditionalExpression.ts === +function f (m: string) { +>f : Symbol(f, Decl(commaOperatorInConditionalExpression.ts, 0, 0)) +>m : Symbol(m, Decl(commaOperatorInConditionalExpression.ts, 0, 12)) + + [1, 2, 3].map(i => { +>[1, 2, 3].map : Symbol(Array.map, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>map : Symbol(Array.map, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>i : Symbol(i, Decl(commaOperatorInConditionalExpression.ts, 1, 18)) + + return true? { [m]: i } : { [m]: i + 1 } +>m : Symbol(m, Decl(commaOperatorInConditionalExpression.ts, 0, 12)) +>i : Symbol(i, Decl(commaOperatorInConditionalExpression.ts, 1, 18)) +>m : Symbol(m, Decl(commaOperatorInConditionalExpression.ts, 0, 12)) +>i : Symbol(i, Decl(commaOperatorInConditionalExpression.ts, 1, 18)) + + }) +} diff --git a/tests/baselines/reference/commaOperatorInConditionalExpression.types b/tests/baselines/reference/commaOperatorInConditionalExpression.types new file mode 100644 index 00000000000..f46282f9b6b --- /dev/null +++ b/tests/baselines/reference/commaOperatorInConditionalExpression.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/commaOperatorInConditionalExpression.ts === +function f (m: string) { +>f : (m: string) => void +>m : string + + [1, 2, 3].map(i => { +>[1, 2, 3].map(i => { return true? { [m]: i } : { [m]: i + 1 } }) : { [x: string]: number; }[] +>[1, 2, 3].map : { (this: [number, number, number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [number, number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U, U]; (this: [number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U]; (this: [number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): U[]; } +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 +>map : { (this: [number, number, number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [number, number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U, U]; (this: [number, number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U, U]; (this: [number, number], callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any): U[]; } +>i => { return true? { [m]: i } : { [m]: i + 1 } } : (i: number) => { [x: string]: number; } +>i : number + + return true? { [m]: i } : { [m]: i + 1 } +>true? { [m]: i } : { [m]: i + 1 } : { [x: string]: number; } +>true : true +>{ [m]: i } : { [x: string]: number; } +>m : string +>i : number +>{ [m]: i + 1 } : { [x: string]: number; } +>m : string +>i + 1 : number +>i : number +>1 : 1 + + }) +} diff --git a/tests/baselines/reference/commentOnExportEnumDeclaration.js b/tests/baselines/reference/commentOnExportEnumDeclaration.js index 6ded51456d8..61307b95b1c 100644 --- a/tests/baselines/reference/commentOnExportEnumDeclaration.js +++ b/tests/baselines/reference/commentOnExportEnumDeclaration.js @@ -11,9 +11,9 @@ export enum Color { /** * comment */ +var Color; (function (Color) { Color[Color["r"] = 0] = "r"; Color[Color["g"] = 1] = "g"; Color[Color["b"] = 2] = "b"; -})(exports.Color || (exports.Color = {})); -var Color = exports.Color; +})(Color = exports.Color || (exports.Color = {})); diff --git a/tests/baselines/reference/commentsArgumentsOfCallExpression2.types b/tests/baselines/reference/commentsArgumentsOfCallExpression2.types index bc6bf5baa90..7ec29aa9124 100644 --- a/tests/baselines/reference/commentsArgumentsOfCallExpression2.types +++ b/tests/baselines/reference/commentsArgumentsOfCallExpression2.types @@ -17,7 +17,7 @@ foo(/*c2*/ 1, /*d2*/ 1 + 2, /*e1*/ a + b); >1 : 1 >2 : 2 >a + b : any ->a : undefined +>a : any >b : any foo(/*c3*/ function () { }, /*d2*/() => { }, /*e2*/ a + /*e3*/ b); @@ -26,7 +26,7 @@ foo(/*c3*/ function () { }, /*d2*/() => { }, /*e2*/ a + /*e3*/ b); >function () { } : () => void >() => { } : () => void >a + /*e3*/ b : any ->a : undefined +>a : any >b : any foo(/*c3*/ function () { }, /*d3*/() => { }, /*e3*/(a + b)); @@ -36,7 +36,7 @@ foo(/*c3*/ function () { }, /*d3*/() => { }, /*e3*/(a + b)); >() => { } : () => void >(a + b) : any >a + b : any ->a : undefined +>a : any >b : any foo( diff --git a/tests/baselines/reference/commonJSImportAsPrimaryExpression.js b/tests/baselines/reference/commonJSImportAsPrimaryExpression.js index d22b5b2855b..b8cf42ea762 100644 --- a/tests/baselines/reference/commonJSImportAsPrimaryExpression.js +++ b/tests/baselines/reference/commonJSImportAsPrimaryExpression.js @@ -21,8 +21,8 @@ var C1 = (function () { } return C1; }()); -exports.C1 = C1; C1.s1 = true; +exports.C1 = C1; //// [foo_1.js] "use strict"; var foo = require("./foo_0"); diff --git a/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js b/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js index e7496f3445f..eb77d1baa3c 100644 --- a/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js +++ b/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js @@ -39,14 +39,14 @@ var C1 = (function () { } return C1; }()); -exports.C1 = C1; C1.s1 = true; +exports.C1 = C1; +var E1; (function (E1) { E1[E1["A"] = 0] = "A"; E1[E1["B"] = 1] = "B"; E1[E1["C"] = 2] = "C"; -})(exports.E1 || (exports.E1 = {})); -var E1 = exports.E1; +})(E1 = exports.E1 || (exports.E1 = {})); //// [foo_1.js] "use strict"; var i; diff --git a/tests/baselines/reference/commonSourceDirectory.js b/tests/baselines/reference/commonSourceDirectory.js new file mode 100644 index 00000000000..1a863dbecbd --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory.js @@ -0,0 +1,29 @@ +//// [tests/cases/compiler/commonSourceDirectory.ts] //// + +//// [index.ts] +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +export const x = 0; + +//// [bar.d.ts] +declare module "bar" { + export const y = 0; +} + +//// [index.ts] +/// +import { x } from "foo"; +import { y } from "bar"; +x + y; + + +//// [/app/bin/index.js] +"use strict"; +/// +var foo_1 = require("foo"); +var bar_1 = require("bar"); +foo_1.x + bar_1.y; +//# sourceMappingURL=/app/myMapRoot/index.js.map + +//// [/app/bin/index.d.ts] +/// diff --git a/tests/baselines/reference/commonSourceDirectory.js.map b/tests/baselines/reference/commonSourceDirectory.js.map new file mode 100644 index 00000000000..8e3f925eee9 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory.js.map @@ -0,0 +1,2 @@ +//// [/app/bin/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"/app/mySourceRoot/","sources":["index.ts"],"names":[],"mappings":";AAAA,yCAAyC;AACzC,2BAAwB;AACxB,2BAAwB;AACxB,OAAC,GAAG,OAAC,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/commonSourceDirectory.sourcemap.txt b/tests/baselines/reference/commonSourceDirectory.sourcemap.txt new file mode 100644 index 00000000000..ac198eaf02c --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory.sourcemap.txt @@ -0,0 +1,58 @@ +=================================================================== +JsFile: index.js +mapUrl: /app/myMapRoot/index.js.map +sourceRoot: /app/mySourceRoot/ +sources: index.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:/app/bin/index.js +sourceFile:index.ts +------------------------------------------------------------------- +>>>"use strict"; +>>>/// +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1 > +2 >/// +1 >Emitted(2, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(2, 42) Source(1, 42) + SourceIndex(0) +--- +>>>var foo_1 = require("foo"); +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^-> +1 > + > +2 >import { x } from "foo"; +1 >Emitted(3, 1) Source(2, 1) + SourceIndex(0) +2 >Emitted(3, 28) Source(2, 25) + SourceIndex(0) +--- +>>>var bar_1 = require("bar"); +1-> +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1-> + > +2 >import { y } from "bar"; +1->Emitted(4, 1) Source(3, 1) + SourceIndex(0) +2 >Emitted(4, 28) Source(3, 25) + SourceIndex(0) +--- +>>>foo_1.x + bar_1.y; +1 > +2 >^^^^^^^ +3 > ^^^ +4 > ^^^^^^^ +5 > ^ +6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 >x +3 > + +4 > y +5 > ; +1 >Emitted(5, 1) Source(4, 1) + SourceIndex(0) +2 >Emitted(5, 8) Source(4, 2) + SourceIndex(0) +3 >Emitted(5, 11) Source(4, 5) + SourceIndex(0) +4 >Emitted(5, 18) Source(4, 6) + SourceIndex(0) +5 >Emitted(5, 19) Source(4, 7) + SourceIndex(0) +--- +>>>//# sourceMappingURL=/app/myMapRoot/index.js.map \ No newline at end of file diff --git a/tests/baselines/reference/commonSourceDirectory.symbols b/tests/baselines/reference/commonSourceDirectory.symbols new file mode 100644 index 00000000000..5409286ede5 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory.symbols @@ -0,0 +1,24 @@ +=== /app/index.ts === +/// +import { x } from "foo"; +>x : Symbol(x, Decl(index.ts, 1, 8)) + +import { y } from "bar"; +>y : Symbol(y, Decl(index.ts, 2, 8)) + +x + y; +>x : Symbol(x, Decl(index.ts, 1, 8)) +>y : Symbol(y, Decl(index.ts, 2, 8)) + +=== /node_modules/foo/index.ts === +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +export const x = 0; +>x : Symbol(x, Decl(index.ts, 2, 12)) + +=== /types/bar.d.ts === +declare module "bar" { + export const y = 0; +>y : Symbol(y, Decl(bar.d.ts, 1, 16)) +} + diff --git a/tests/baselines/reference/commonSourceDirectory.types b/tests/baselines/reference/commonSourceDirectory.types new file mode 100644 index 00000000000..ce0169582d7 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory.types @@ -0,0 +1,27 @@ +=== /app/index.ts === +/// +import { x } from "foo"; +>x : 0 + +import { y } from "bar"; +>y : 0 + +x + y; +>x + y : number +>x : 0 +>y : 0 + +=== /node_modules/foo/index.ts === +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +export const x = 0; +>x : 0 +>0 : 0 + +=== /types/bar.d.ts === +declare module "bar" { + export const y = 0; +>y : 0 +>0 : 0 +} + diff --git a/tests/baselines/reference/commonSourceDirectory_dts.js b/tests/baselines/reference/commonSourceDirectory_dts.js new file mode 100644 index 00000000000..8aa0bd04e11 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory_dts.js @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/commonSourceDirectory_dts.ts] //// + +//// [bar.d.ts] +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +declare const y: number; + +//// [index.ts] +/// +export const x = y; + + +//// [/app/bin/index.js] +"use strict"; +/// +exports.x = y; +//# sourceMappingURL=/app/myMapRoot/index.js.map + +//// [/app/bin/index.d.ts] +/// +export declare const x: number; diff --git a/tests/baselines/reference/commonSourceDirectory_dts.js.map b/tests/baselines/reference/commonSourceDirectory_dts.js.map new file mode 100644 index 00000000000..b33518dd04c --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory_dts.js.map @@ -0,0 +1,2 @@ +//// [/app/bin/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"/app/mySourceRoot/","sources":["index.ts"],"names":[],"mappings":";AAAA,wCAAwC;AAC3B,QAAA,CAAC,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/commonSourceDirectory_dts.sourcemap.txt b/tests/baselines/reference/commonSourceDirectory_dts.sourcemap.txt new file mode 100644 index 00000000000..90603ae3652 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory_dts.sourcemap.txt @@ -0,0 +1,42 @@ +=================================================================== +JsFile: index.js +mapUrl: /app/myMapRoot/index.js.map +sourceRoot: /app/mySourceRoot/ +sources: index.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:/app/bin/index.js +sourceFile:index.ts +------------------------------------------------------------------- +>>>"use strict"; +>>>/// +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1 > +2 >/// +1 >Emitted(2, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(2, 41) Source(1, 41) + SourceIndex(0) +--- +>>>exports.x = y; +1 > +2 >^^^^^^^^ +3 > ^ +4 > ^^^ +5 > ^ +6 > ^ +7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >export const +2 > +3 > x +4 > = +5 > y +6 > ; +1 >Emitted(3, 1) Source(2, 14) + SourceIndex(0) +2 >Emitted(3, 9) Source(2, 14) + SourceIndex(0) +3 >Emitted(3, 10) Source(2, 15) + SourceIndex(0) +4 >Emitted(3, 13) Source(2, 18) + SourceIndex(0) +5 >Emitted(3, 14) Source(2, 19) + SourceIndex(0) +6 >Emitted(3, 15) Source(2, 20) + SourceIndex(0) +--- +>>>//# sourceMappingURL=/app/myMapRoot/index.js.map \ No newline at end of file diff --git a/tests/baselines/reference/commonSourceDirectory_dts.symbols b/tests/baselines/reference/commonSourceDirectory_dts.symbols new file mode 100644 index 00000000000..740a8aef921 --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory_dts.symbols @@ -0,0 +1,12 @@ +=== /app/src/index.ts === +/// +export const x = y; +>x : Symbol(x, Decl(index.ts, 1, 12)) +>y : Symbol(y, Decl(bar.d.ts, 2, 13)) + +=== /app/lib/bar.d.ts === +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +declare const y: number; +>y : Symbol(y, Decl(bar.d.ts, 2, 13)) + diff --git a/tests/baselines/reference/commonSourceDirectory_dts.types b/tests/baselines/reference/commonSourceDirectory_dts.types new file mode 100644 index 00000000000..b41b91c978f --- /dev/null +++ b/tests/baselines/reference/commonSourceDirectory_dts.types @@ -0,0 +1,12 @@ +=== /app/src/index.ts === +/// +export const x = y; +>x : number +>y : number + +=== /app/lib/bar.d.ts === +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. + +declare const y: number; +>y : number + diff --git a/tests/baselines/reference/comparisonOperatorWithNumericLiteral.js b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.js new file mode 100644 index 00000000000..6f28423d166 --- /dev/null +++ b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.js @@ -0,0 +1,79 @@ +//// [comparisonOperatorWithNumericLiteral.ts] +type BrandedNum = number & { __numberBrand: any }; +var x : BrandedNum; + +// operator > +x > 0; +x > 0; +x > 0; + +// operator < +x < 0; +x < 0; +x < 0; + +// operator >= +x >= 0; +x >= 0; +x >= 0; + +// operator <= +x <= 0; +x <= 0; +x <= 0; + +// operator == +x == 0; +x == 0; +x == 0; + +// operator != +x != 0; +x != 0; +x != 0; + +// operator === +x === 0; +x === 0; +x === 0; + +// operator !== +x !== 0; +x !== 0; +x !== 0; + + +//// [comparisonOperatorWithNumericLiteral.js] +var x; +// operator > +x > 0; +x > 0; +x > 0; +// operator < +x < 0; +x < 0; +x < 0; +// operator >= +x >= 0; +x >= 0; +x >= 0; +// operator <= +x <= 0; +x <= 0; +x <= 0; +// operator == +x == 0; +x == 0; +x == 0; +// operator != +x != 0; +x != 0; +x != 0; +// operator === +x === 0; +x === 0; +x === 0; +// operator !== +x !== 0; +x !== 0; +x !== 0; diff --git a/tests/baselines/reference/comparisonOperatorWithNumericLiteral.symbols b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.symbols new file mode 100644 index 00000000000..0511f88b2a8 --- /dev/null +++ b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.symbols @@ -0,0 +1,97 @@ +=== tests/cases/conformance/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithNumericLiteral.ts === +type BrandedNum = number & { __numberBrand: any }; +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) +>__numberBrand : Symbol(__numberBrand, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 28)) + +var x : BrandedNum; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator > +x > 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x > 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x > 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator < +x < 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x < 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x < 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator >= +x >= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x >= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x >= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator <= +x <= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x <= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x <= 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator == +x == 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x == 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x == 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator != +x != 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x != 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x != 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator === +x === 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x === 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x === 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + +// operator !== +x !== 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x !== 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) + +x !== 0; +>x : Symbol(x, Decl(comparisonOperatorWithNumericLiteral.ts, 1, 3)) +>BrandedNum : Symbol(BrandedNum, Decl(comparisonOperatorWithNumericLiteral.ts, 0, 0)) + diff --git a/tests/baselines/reference/comparisonOperatorWithNumericLiteral.types b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.types new file mode 100644 index 00000000000..31f7aadfec2 --- /dev/null +++ b/tests/baselines/reference/comparisonOperatorWithNumericLiteral.types @@ -0,0 +1,161 @@ +=== tests/cases/conformance/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithNumericLiteral.ts === +type BrandedNum = number & { __numberBrand: any }; +>BrandedNum : BrandedNum +>__numberBrand : any + +var x : BrandedNum; +>x : BrandedNum +>BrandedNum : BrandedNum + +// operator > +x > 0; +>x > 0 : boolean +>x : BrandedNum +>0 : 0 + +x > 0; +>x > 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x > 0; +>x > 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator < +x < 0; +>x < 0 : boolean +>x : BrandedNum +>0 : 0 + +x < 0; +>x < 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x < 0; +>x < 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator >= +x >= 0; +>x >= 0 : boolean +>x : BrandedNum +>0 : 0 + +x >= 0; +>x >= 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x >= 0; +>x >= 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator <= +x <= 0; +>x <= 0 : boolean +>x : BrandedNum +>0 : 0 + +x <= 0; +>x <= 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x <= 0; +>x <= 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator == +x == 0; +>x == 0 : boolean +>x : BrandedNum +>0 : 0 + +x == 0; +>x == 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x == 0; +>x == 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator != +x != 0; +>x != 0 : boolean +>x : BrandedNum +>0 : 0 + +x != 0; +>x != 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x != 0; +>x != 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator === +x === 0; +>x === 0 : boolean +>x : BrandedNum +>0 : 0 + +x === 0; +>x === 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x === 0; +>x === 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + +// operator !== +x !== 0; +>x !== 0 : boolean +>x : BrandedNum +>0 : 0 + +x !== 0; +>x !== 0 : boolean +>x : BrandedNum +>0 : number +>0 : 0 + +x !== 0; +>x !== 0 : boolean +>x : BrandedNum +>0 : BrandedNum +>BrandedNum : BrandedNum +>0 : 0 + diff --git a/tests/baselines/reference/compileOnSaveWorksWhenEmitBlockingErrorOnOtherFile.baseline b/tests/baselines/reference/compileOnSaveWorksWhenEmitBlockingErrorOnOtherFile.baseline index a088006d145..f8b479e6d7b 100644 --- a/tests/baselines/reference/compileOnSaveWorksWhenEmitBlockingErrorOnOtherFile.baseline +++ b/tests/baselines/reference/compileOnSaveWorksWhenEmitBlockingErrorOnOtherFile.baseline @@ -1,6 +1,7 @@ EmitSkipped: true Diagnostics: - Cannot write file '/tests/cases/fourslash/b.js' because it would overwrite input file. + Cannot write file '/tests/cases/fourslash/b.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig EmitSkipped: false FileName : /tests/cases/fourslash/a.js diff --git a/tests/baselines/reference/compoundAssignmentLHSIsReference.types b/tests/baselines/reference/compoundAssignmentLHSIsReference.types index a82eb17426d..4816307f508 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsReference.types +++ b/tests/baselines/reference/compoundAssignmentLHSIsReference.types @@ -9,12 +9,12 @@ var x1: number; x1 *= value; >x1 *= value : number >x1 : number ->value : undefined +>value : any x1 += value; ->x1 += value : number +>x1 += value : any >x1 : number ->value : undefined +>value : any function fn1(x2: number) { >fn1 : (x2: number) => void @@ -41,41 +41,41 @@ x3.a *= value; >x3.a : number >x3 : { a: number; } >a : number ->value : undefined +>value : any x3.a += value; ->x3.a += value : number +>x3.a += value : any >x3.a : number >x3 : { a: number; } >a : number ->value : undefined +>value : any x3['a'] *= value; >x3['a'] *= value : number >x3['a'] : number >x3 : { a: number; } >'a' : "a" ->value : undefined +>value : any x3['a'] += value; ->x3['a'] += value : number +>x3['a'] += value : any >x3['a'] : number >x3 : { a: number; } >'a' : "a" ->value : undefined +>value : any // parentheses, the contained expression is reference (x1) *= value; >(x1) *= value : number >(x1) : number >x1 : number ->value : undefined +>value : any (x1) += value; ->(x1) += value : number +>(x1) += value : any >(x1) : number >x1 : number ->value : undefined +>value : any function fn2(x4: number) { >fn2 : (x4: number) => void @@ -100,15 +100,15 @@ function fn2(x4: number) { >x3.a : number >x3 : { a: number; } >a : number ->value : undefined +>value : any (x3.a) += value; ->(x3.a) += value : number +>(x3.a) += value : any >(x3.a) : number >x3.a : number >x3 : { a: number; } >a : number ->value : undefined +>value : any (x3['a']) *= value; >(x3['a']) *= value : number @@ -116,13 +116,13 @@ function fn2(x4: number) { >x3['a'] : number >x3 : { a: number; } >'a' : "a" ->value : undefined +>value : any (x3['a']) += value; ->(x3['a']) += value : number +>(x3['a']) += value : any >(x3['a']) : number >x3['a'] : number >x3 : { a: number; } >'a' : "a" ->value : undefined +>value : any diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt index 61f893ba88f..bc6bb41b27f 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt @@ -1,37 +1,37 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(9,9): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(9,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(12,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(13,9): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(13,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(16,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(17,9): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(22,5): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(23,5): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(26,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(27,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(32,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(34,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(35,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(38,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(39,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(41,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(42,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(45,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(46,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(17,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(22,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(23,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(26,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(27,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(31,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(32,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(34,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(35,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(38,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(39,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(41,1): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(42,1): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(45,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(46,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(47,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(48,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(48,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(49,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(50,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(51,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(52,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(50,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(51,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(52,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(53,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(54,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(54,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(55,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(56,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(56,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(59,9): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(60,9): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(63,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(64,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(64,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(70,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(71,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(75,15): error TS1034: 'super' must be followed by an argument list or member access. @@ -43,35 +43,35 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(88,11): error TS1005: ';' expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(89,11): error TS1005: ';' expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(92,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(93,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(96,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(97,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(98,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(99,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(100,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(101,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(102,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(103,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(104,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(105,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(106,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(107,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(93,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(96,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(97,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(98,2): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(99,2): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(100,2): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(101,2): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(102,2): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(103,2): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(104,2): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(105,2): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(106,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(107,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(108,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(109,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(110,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(111,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(109,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(110,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(111,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(112,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(113,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(113,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(114,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(115,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(115,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(116,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(117,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(117,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(118,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(119,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(119,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(120,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(121,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(121,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(122,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(123,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(123,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts (74 errors) ==== @@ -87,7 +87,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. this += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } foo() { this *= value; @@ -95,7 +95,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. this += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } static sfoo() { this *= value; @@ -103,94 +103,94 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. this += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } } function foo() { this *= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. this += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } this *= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. this += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // identifiers: module, class, enum, function module M { export var a; } M *= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. M += value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. C *= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. C += value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. enum E { } E *= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. E += value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. foo *= value; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. foo += value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. // literals null *= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. null += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. true *= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. true += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. false *= value; ~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. false += value; ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. 0 *= value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. 0 += value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. '' *= value; ~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. '' += value; ~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. /d+/ *= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. /d+/ += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // object literals { a: 0} *= value; @@ -206,7 +206,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ['', ''] += value; ~~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // super class Derived extends C { @@ -259,90 +259,90 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. foo() += value; ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // parentheses, the containted expression is value (this) *= value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (this) += value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (M) *= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'M' because it is not a variable. (M) += value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'M' because it is not a variable. (C) *= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'C' because it is not a variable. (C) += value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'C' because it is not a variable. (E) *= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'E' because it is not a variable. (E) += value; - ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~ +!!! error TS2539: Cannot assign to 'E' because it is not a variable. (foo) *= value; - ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~~~ +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. (foo) += value; - ~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. + ~~~ +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. (null) *= value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (null) += value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (true) *= value; ~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. (true) += value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (0) *= value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (0) += value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ('') *= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ('') += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (/d+/) *= value; ~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. (/d+/) += value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ({}) *= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ({}) += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ([]) *= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. ([]) += value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (function baz1() { }) *= value; ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. (function baz2() { }) += value; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (foo()) *= value; ~~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. (foo()) += value; ~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt index 0d9bab910ef..22eeb18ac4a 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt @@ -1,16 +1,16 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(10,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(18,5): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(21,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(27,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(32,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(35,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(18,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(21,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(25,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(27,1): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(30,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(32,1): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(35,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(38,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(38,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(39,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(43,3): error TS7028: Unused label. @@ -22,14 +22,14 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(65,21): error TS1128: Declaration or statement expected. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(66,11): error TS1005: ';' expected. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(69,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(72,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(73,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(74,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(75,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(76,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(77,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(72,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(73,2): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(74,2): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(75,2): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(76,2): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(77,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(78,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(79,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(79,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(80,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(81,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(82,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -64,36 +64,36 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm function foo() { this **= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. } this **= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // identifiers: module, class, enum, function module M { export var a; } M **= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. C **= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. enum E { } E **= value; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. foo **= value; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. // literals null **= value; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. true **= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -102,7 +102,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. 0 **= value; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. '' **= value; ~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -160,28 +160,28 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm // parentheses, the containted expression is value (this) **= value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (M) **= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'M' because it is not a variable. (C) **= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'C' because it is not a variable. (E) **= value; - ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~ +!!! error TS2539: Cannot assign to 'E' because it is not a variable. (foo) **= value; - ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + ~~~ +!!! error TS2539: Cannot assign to 'foo' because it is not a variable. (null) **= value; ~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (true) **= value; ~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. (0) **= value; ~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ('') **= value; ~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. diff --git a/tests/baselines/reference/computedPropertiesInDestructuring1.js b/tests/baselines/reference/computedPropertiesInDestructuring1.js index 0bc4286ed7b..e4f15e6b8bf 100644 --- a/tests/baselines/reference/computedPropertiesInDestructuring1.js +++ b/tests/baselines/reference/computedPropertiesInDestructuring1.js @@ -41,13 +41,13 @@ let [{[foo.toExponential()]: bar7}] = [{bar: "bar"}]; // destructuring in variable declarations var foo = "bar"; var _a = foo, bar = { bar: "bar" }[_a]; -var _b = "bar", bar2 = { bar: "bar" }[_b]; +var bar2 = { bar: "bar" }["bar"]; var foo2 = function () { return "bar"; }; -var _c = foo2(), bar3 = { bar: "bar" }[_c]; -var _d = foo, bar4 = [{ bar: "bar" }][0][_d]; -var _e = foo2(), bar5 = [{ bar: "bar" }][0][_e]; +var _b = foo2(), bar3 = { bar: "bar" }[_b]; +var _c = foo, bar4 = [{ bar: "bar" }][0][_c]; +var _d = foo2(), bar5 = [{ bar: "bar" }][0][_d]; function f1(_a) { - var _b = "bar", x = _a[_b]; + var x = _a["bar"]; } function f2(_a) { var _b = foo, x = _a[_b]; @@ -62,14 +62,14 @@ function f5(_a) { var _b = foo2(), x = _a[0][_b]; } // report errors on type errors in computed properties used in destructuring -var _f = foo(), bar6 = [{ bar: "bar" }][0][_f]; -var _g = foo.toExponential(), bar7 = [{ bar: "bar" }][0][_g]; +var _e = foo(), bar6 = [{ bar: "bar" }][0][_e]; +var _f = foo.toExponential(), bar7 = [{ bar: "bar" }][0][_f]; // destructuring assignment -(_h = { bar: "bar" }, _j = foo, bar = _h[_j], _h); -(_k = { bar: "bar" }, _l = "bar", bar2 = _k[_l], _k); -(_m = { bar: "bar" }, _o = foo2(), bar3 = _m[_o], _m); -_p = foo, bar4 = [{ bar: "bar" }][0][_p]; -_q = foo2(), bar5 = [{ bar: "bar" }][0][_q]; -_r = foo(), bar4 = [{ bar: "bar" }][0][_r]; -_s = (1 + {}), bar4 = [{ bar: "bar" }][0][_s]; -var _h, _j, _k, _l, _m, _o, _p, _q, _r, _s; +(_g = foo, bar = { bar: "bar" }[_g]); +(bar2 = { bar: "bar" }["bar"]); +(_h = foo2(), bar3 = { bar: "bar" }[_h]); +_j = foo, bar4 = [{ bar: "bar" }][0][_j]; +_k = foo2(), bar5 = [{ bar: "bar" }][0][_k]; +_l = foo(), bar4 = [{ bar: "bar" }][0][_l]; +_m = (1 + {}), bar4 = [{ bar: "bar" }][0][_m]; +var _g, _h, _j, _k, _l, _m; diff --git a/tests/baselines/reference/concatClassAndString.errors.txt b/tests/baselines/reference/concatClassAndString.errors.txt index 623c213181f..b0cb54b31c0 100644 --- a/tests/baselines/reference/concatClassAndString.errors.txt +++ b/tests/baselines/reference/concatClassAndString.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/concatClassAndString.ts(4,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/concatClassAndString.ts(4,1): error TS2539: Cannot assign to 'f' because it is not a variable. ==== tests/cases/compiler/concatClassAndString.ts (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/concatClassAndString.ts(4,1): error TS2364: Invalid left-ha f += ''; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'f' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.errors.txt b/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.errors.txt deleted file mode 100644 index 25153c1ba15..00000000000 --- a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.errors.txt +++ /dev/null @@ -1,71 +0,0 @@ -tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts(35,1): error TS2365: Operator '>' cannot be applied to types '2' and '1'. -tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts(58,23): error TS2365: Operator '>' cannot be applied to types '2' and '1'. - - -==== tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts (2 errors) ==== - //Cond ? Expr1 : Expr2, Cond is of boolean type, Expr1 and Expr2 have the same type - var condBoolean: boolean; - - var exprAny1: any; - var exprBoolean1: boolean; - var exprNumber1: number; - var exprString1: string; - var exprIsObject1: Object; - - var exprAny2: any; - var exprBoolean2: boolean; - var exprNumber2: number; - var exprString2: string; - var exprIsObject2: Object; - - //Cond is a boolean type variable - condBoolean ? exprAny1 : exprAny2; - condBoolean ? exprBoolean1 : exprBoolean2; - condBoolean ? exprNumber1 : exprNumber2; - condBoolean ? exprString1 : exprString2; - condBoolean ? exprIsObject1 : exprIsObject2; - condBoolean ? exprString1 : exprBoolean1; // union - - //Cond is a boolean type literal - true ? exprAny1 : exprAny2; - false ? exprBoolean1 : exprBoolean2; - true ? exprNumber1 : exprNumber2; - false ? exprString1 : exprString2; - true ? exprIsObject1 : exprIsObject2; - true ? exprString1 : exprBoolean1; // union - - //Cond is a boolean type expression - !true ? exprAny1 : exprAny2; - typeof "123" == "string" ? exprBoolean1 : exprBoolean2; - 2 > 1 ? exprNumber1 : exprNumber2; - ~~~~~ -!!! error TS2365: Operator '>' cannot be applied to types '2' and '1'. - null === undefined ? exprString1 : exprString2; - true || false ? exprIsObject1 : exprIsObject2; - null === undefined ? exprString1 : exprBoolean1; // union - - //Results shoud be same as Expr1 and Expr2 - var resultIsAny1 = condBoolean ? exprAny1 : exprAny2; - var resultIsBoolean1 = condBoolean ? exprBoolean1 : exprBoolean2; - var resultIsNumber1 = condBoolean ? exprNumber1 : exprNumber2; - var resultIsString1 = condBoolean ? exprString1 : exprString2; - var resultIsObject1 = condBoolean ? exprIsObject1 : exprIsObject2; - var resultIsStringOrBoolean1 = condBoolean ? exprString1 : exprBoolean1; // union - - var resultIsAny2 = true ? exprAny1 : exprAny2; - var resultIsBoolean2 = false ? exprBoolean1 : exprBoolean2; - var resultIsNumber2 = true ? exprNumber1 : exprNumber2; - var resultIsString2 = false ? exprString1 : exprString2; - var resultIsObject2 = true ? exprIsObject1 : exprIsObject2; - var resultIsStringOrBoolean2 = true ? exprString1 : exprBoolean1; // union - var resultIsStringOrBoolean3 = false ? exprString1 : exprBoolean1; // union - - var resultIsAny3 = !true ? exprAny1 : exprAny2; - var resultIsBoolean3 = typeof "123" == "string" ? exprBoolean1 : exprBoolean2; - var resultIsNumber3 = 2 > 1 ? exprNumber1 : exprNumber2; - ~~~~~ -!!! error TS2365: Operator '>' cannot be applied to types '2' and '1'. - var resultIsString3 = null === undefined ? exprString1 : exprString2; - var resultIsObject3 = true || false ? exprIsObject1 : exprIsObject2; - var resultIsStringOrBoolean4 = typeof "123" === "string" ? exprString1 : exprBoolean1; // union - \ No newline at end of file diff --git a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types b/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types index 7733b80f69b..f19769b1c58 100644 --- a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types +++ b/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types @@ -75,37 +75,37 @@ condBoolean ? exprString1 : exprBoolean1; // union //Cond is a boolean type literal true ? exprAny1 : exprAny2; >true ? exprAny1 : exprAny2 : any ->true : boolean +>true : true >exprAny1 : any >exprAny2 : any false ? exprBoolean1 : exprBoolean2; >false ? exprBoolean1 : exprBoolean2 : boolean ->false : boolean +>false : false >exprBoolean1 : boolean >exprBoolean2 : boolean true ? exprNumber1 : exprNumber2; >true ? exprNumber1 : exprNumber2 : number ->true : boolean +>true : true >exprNumber1 : number >exprNumber2 : number false ? exprString1 : exprString2; >false ? exprString1 : exprString2 : string ->false : boolean +>false : false >exprString1 : string >exprString2 : string true ? exprIsObject1 : exprIsObject2; >true ? exprIsObject1 : exprIsObject2 : Object ->true : boolean +>true : true >exprIsObject1 : Object >exprIsObject2 : Object true ? exprString1 : exprBoolean1; // union >true ? exprString1 : exprBoolean1 : string | boolean ->true : boolean +>true : true >exprString1 : string >exprBoolean1 : boolean @@ -113,7 +113,7 @@ true ? exprString1 : exprBoolean1; // union !true ? exprAny1 : exprAny2; >!true ? exprAny1 : exprAny2 : any >!true : boolean ->true : boolean +>true : true >exprAny1 : any >exprAny2 : any @@ -121,7 +121,7 @@ typeof "123" == "string" ? exprBoolean1 : exprBoolean2; >typeof "123" == "string" ? exprBoolean1 : exprBoolean2 : boolean >typeof "123" == "string" : boolean >typeof "123" : string ->"123" : string +>"123" : "123" >"string" : "string" >exprBoolean1 : boolean >exprBoolean2 : boolean @@ -129,8 +129,8 @@ typeof "123" == "string" ? exprBoolean1 : exprBoolean2; 2 > 1 ? exprNumber1 : exprNumber2; >2 > 1 ? exprNumber1 : exprNumber2 : number >2 > 1 : boolean ->2 : number ->1 : number +>2 : 2 +>1 : 1 >exprNumber1 : number >exprNumber2 : number @@ -145,7 +145,7 @@ null === undefined ? exprString1 : exprString2; true || false ? exprIsObject1 : exprIsObject2; >true || false ? exprIsObject1 : exprIsObject2 : Object >true || false : boolean ->true : boolean +>true : true >false : false >exprIsObject1 : Object >exprIsObject2 : Object @@ -204,49 +204,49 @@ var resultIsStringOrBoolean1 = condBoolean ? exprString1 : exprBoolean1; // unio var resultIsAny2 = true ? exprAny1 : exprAny2; >resultIsAny2 : any >true ? exprAny1 : exprAny2 : any ->true : boolean +>true : true >exprAny1 : any >exprAny2 : any var resultIsBoolean2 = false ? exprBoolean1 : exprBoolean2; >resultIsBoolean2 : boolean >false ? exprBoolean1 : exprBoolean2 : boolean ->false : boolean +>false : false >exprBoolean1 : boolean >exprBoolean2 : boolean var resultIsNumber2 = true ? exprNumber1 : exprNumber2; >resultIsNumber2 : number >true ? exprNumber1 : exprNumber2 : number ->true : boolean +>true : true >exprNumber1 : number >exprNumber2 : number var resultIsString2 = false ? exprString1 : exprString2; >resultIsString2 : string >false ? exprString1 : exprString2 : string ->false : boolean +>false : false >exprString1 : string >exprString2 : string var resultIsObject2 = true ? exprIsObject1 : exprIsObject2; >resultIsObject2 : Object >true ? exprIsObject1 : exprIsObject2 : Object ->true : boolean +>true : true >exprIsObject1 : Object >exprIsObject2 : Object var resultIsStringOrBoolean2 = true ? exprString1 : exprBoolean1; // union >resultIsStringOrBoolean2 : string | boolean >true ? exprString1 : exprBoolean1 : string | boolean ->true : boolean +>true : true >exprString1 : string >exprBoolean1 : boolean var resultIsStringOrBoolean3 = false ? exprString1 : exprBoolean1; // union >resultIsStringOrBoolean3 : string | boolean >false ? exprString1 : exprBoolean1 : string | boolean ->false : boolean +>false : false >exprString1 : string >exprBoolean1 : boolean @@ -254,7 +254,7 @@ var resultIsAny3 = !true ? exprAny1 : exprAny2; >resultIsAny3 : any >!true ? exprAny1 : exprAny2 : any >!true : boolean ->true : boolean +>true : true >exprAny1 : any >exprAny2 : any @@ -263,7 +263,7 @@ var resultIsBoolean3 = typeof "123" == "string" ? exprBoolean1 : exprBoolean2; >typeof "123" == "string" ? exprBoolean1 : exprBoolean2 : boolean >typeof "123" == "string" : boolean >typeof "123" : string ->"123" : string +>"123" : "123" >"string" : "string" >exprBoolean1 : boolean >exprBoolean2 : boolean @@ -272,8 +272,8 @@ var resultIsNumber3 = 2 > 1 ? exprNumber1 : exprNumber2; >resultIsNumber3 : number >2 > 1 ? exprNumber1 : exprNumber2 : number >2 > 1 : boolean ->2 : number ->1 : number +>2 : 2 +>1 : 1 >exprNumber1 : number >exprNumber2 : number @@ -290,7 +290,7 @@ var resultIsObject3 = true || false ? exprIsObject1 : exprIsObject2; >resultIsObject3 : Object >true || false ? exprIsObject1 : exprIsObject2 : Object >true || false : boolean ->true : boolean +>true : true >false : false >exprIsObject1 : Object >exprIsObject2 : Object @@ -300,7 +300,7 @@ var resultIsStringOrBoolean4 = typeof "123" === "string" ? exprString1 : exprBoo >typeof "123" === "string" ? exprString1 : exprBoolean1 : string | boolean >typeof "123" === "string" : boolean >typeof "123" : string ->"123" : string +>"123" : "123" >"string" : "string" >exprString1 : string >exprBoolean1 : boolean diff --git a/tests/baselines/reference/constDeclarations-access.errors.txt b/tests/baselines/reference/constDeclarations-access.errors.txt index 3c748cc4a5f..81121b6fe5c 100644 --- a/tests/baselines/reference/constDeclarations-access.errors.txt +++ b/tests/baselines/reference/constDeclarations-access.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/file2.ts(1,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +tests/cases/compiler/file2.ts(1,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ==== tests/cases/compiler/file1.ts (0 errors) ==== @@ -8,4 +8,4 @@ tests/cases/compiler/file2.ts(1,1): error TS2449: The operand of an increment or ==== tests/cases/compiler/file2.ts (1 errors) ==== x++; ~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. \ No newline at end of file +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/constDeclarations-access2.errors.txt b/tests/baselines/reference/constDeclarations-access2.errors.txt index 667f490a374..16335bfa59c 100644 --- a/tests/baselines/reference/constDeclarations-access2.errors.txt +++ b/tests/baselines/reference/constDeclarations-access2.errors.txt @@ -1,20 +1,20 @@ -tests/cases/compiler/constDeclarations-access2.ts(5,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(6,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(7,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(9,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(10,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(11,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(12,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(13,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(14,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(15,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(16,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(18,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(19,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(20,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(21,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access2.ts(23,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(5,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(6,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(7,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(8,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(9,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(10,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(11,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(12,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(13,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(14,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(15,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(16,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(18,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(19,1): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(20,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(21,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access2.ts(23,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ==== tests/cases/compiler/constDeclarations-access2.ts (17 errors) ==== @@ -24,57 +24,57 @@ tests/cases/compiler/constDeclarations-access2.ts(23,3): error TS2449: The opera // Errors x = 1; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x += 2; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x -= 3; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x *= 4; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x /= 5; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x %= 6; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x <<= 7; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x >>= 8; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x >>>= 9; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x &= 10; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x |= 11; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x ^= 12; ~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x++; ~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. x--; ~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++x; ~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. --x; ~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++((x)); - ~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. // OK var a = x + 1; diff --git a/tests/baselines/reference/constDeclarations-access3.errors.txt b/tests/baselines/reference/constDeclarations-access3.errors.txt index a6cb124d28c..03ea2d29bba 100644 --- a/tests/baselines/reference/constDeclarations-access3.errors.txt +++ b/tests/baselines/reference/constDeclarations-access3.errors.txt @@ -1,21 +1,21 @@ -tests/cases/compiler/constDeclarations-access3.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(9,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(10,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(11,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(12,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(13,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(14,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(15,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(16,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(18,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(21,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(22,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(23,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(24,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(26,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access3.ts(28,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(8,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(9,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(10,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(11,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(12,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(13,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(14,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(15,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(16,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(17,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(18,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(19,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(21,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(22,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(23,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(24,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(26,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access3.ts(28,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ==== tests/cases/compiler/constDeclarations-access3.ts (18 errors) ==== @@ -27,62 +27,62 @@ tests/cases/compiler/constDeclarations-access3.ts(28,1): error TS2450: Left-hand // Errors M.x = 1; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x += 2; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x -= 3; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x *= 4; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x /= 5; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x %= 6; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x <<= 7; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x >>= 8; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x >>>= 9; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x &= 10; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x |= 11; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x ^= 12; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x++; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x--; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++M.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. --M.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++((M.x)); - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M["x"] = 0; - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. // OK var a = M.x + 1; diff --git a/tests/baselines/reference/constDeclarations-access4.errors.txt b/tests/baselines/reference/constDeclarations-access4.errors.txt index 3d7d4a704a8..a4111c2d702 100644 --- a/tests/baselines/reference/constDeclarations-access4.errors.txt +++ b/tests/baselines/reference/constDeclarations-access4.errors.txt @@ -1,21 +1,21 @@ -tests/cases/compiler/constDeclarations-access4.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(9,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(10,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(11,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(12,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(13,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(14,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(15,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(16,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(18,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(21,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(22,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(23,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(24,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(26,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations-access4.ts(28,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(8,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(9,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(10,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(11,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(12,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(13,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(14,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(15,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(16,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(17,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(18,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(19,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(21,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(22,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(23,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(24,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(26,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations-access4.ts(28,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ==== tests/cases/compiler/constDeclarations-access4.ts (18 errors) ==== @@ -27,62 +27,62 @@ tests/cases/compiler/constDeclarations-access4.ts(28,1): error TS2450: Left-hand // Errors M.x = 1; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x += 2; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x -= 3; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x *= 4; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x /= 5; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x %= 6; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x <<= 7; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x >>= 8; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x >>>= 9; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x &= 10; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x |= 11; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x ^= 12; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x++; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M.x--; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++M.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. --M.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++((M.x)); - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. M["x"] = 0; - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. // OK var a = M.x + 1; diff --git a/tests/baselines/reference/constDeclarations-access5.errors.txt b/tests/baselines/reference/constDeclarations-access5.errors.txt index 45160bbc7ce..316465e80b8 100644 --- a/tests/baselines/reference/constDeclarations-access5.errors.txt +++ b/tests/baselines/reference/constDeclarations-access5.errors.txt @@ -1,21 +1,21 @@ -tests/cases/compiler/constDeclarations_access_2.ts(4,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(5,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(6,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(7,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(9,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(10,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(11,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(12,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(13,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(14,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(15,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(17,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(18,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(19,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(20,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(22,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/constDeclarations_access_2.ts(24,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(4,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(5,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(6,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(7,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(8,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(9,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(10,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(11,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(12,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(13,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(14,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(15,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(17,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(18,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(19,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(20,5): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(22,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/constDeclarations_access_2.ts(24,3): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ==== tests/cases/compiler/constDeclarations_access_2.ts (18 errors) ==== @@ -23,62 +23,62 @@ tests/cases/compiler/constDeclarations_access_2.ts(24,1): error TS2450: Left-han import m = require('constDeclarations_access_1'); // Errors m.x = 1; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x += 2; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x -= 3; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x *= 4; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x /= 5; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x %= 6; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x <<= 7; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x >>= 8; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x >>>= 9; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x &= 10; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x |= 11; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x ^= 12; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m m.x++; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m.x--; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++m.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. --m.x; - ~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. ++((m.x)); - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. m["x"] = 0; - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. // OK var a = m.x + 1; diff --git a/tests/baselines/reference/constDeclarations-errors.errors.txt b/tests/baselines/reference/constDeclarations-errors.errors.txt index 2c9c17cc102..83031e0aa79 100644 --- a/tests/baselines/reference/constDeclarations-errors.errors.txt +++ b/tests/baselines/reference/constDeclarations-errors.errors.txt @@ -4,14 +4,12 @@ tests/cases/compiler/constDeclarations-errors.ts(5,7): error TS1155: 'const' dec tests/cases/compiler/constDeclarations-errors.ts(5,11): error TS1155: 'const' declarations must be initialized tests/cases/compiler/constDeclarations-errors.ts(5,15): error TS1155: 'const' declarations must be initialized tests/cases/compiler/constDeclarations-errors.ts(5,27): error TS1155: 'const' declarations must be initialized -tests/cases/compiler/constDeclarations-errors.ts(10,19): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -tests/cases/compiler/constDeclarations-errors.ts(10,27): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +tests/cases/compiler/constDeclarations-errors.ts(10,27): error TS2540: Cannot assign to 'c8' because it is a constant or a read-only property. tests/cases/compiler/constDeclarations-errors.ts(13,11): error TS1155: 'const' declarations must be initialized tests/cases/compiler/constDeclarations-errors.ts(16,20): error TS1155: 'const' declarations must be initialized -tests/cases/compiler/constDeclarations-errors.ts(16,25): error TS2365: Operator '<' cannot be applied to types '0' and '1'. -==== tests/cases/compiler/constDeclarations-errors.ts (11 errors) ==== +==== tests/cases/compiler/constDeclarations-errors.ts (9 errors) ==== // error, missing intialicer const c1; @@ -34,10 +32,8 @@ tests/cases/compiler/constDeclarations-errors.ts(16,25): error TS2365: Operator // error, assigning to a const for(const c8 = 0; c8 < 1; c8++) { } - ~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. ~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +!!! error TS2540: Cannot assign to 'c8' because it is a constant or a read-only property. // error, can not be unintalized for(const c9; c9 < 1;) { } @@ -47,6 +43,4 @@ tests/cases/compiler/constDeclarations-errors.ts(16,25): error TS2365: Operator // error, can not be unintalized for(const c10 = 0, c11; c10 < 1;) { } ~~~ -!!! error TS1155: 'const' declarations must be initialized - ~~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '1'. \ No newline at end of file +!!! error TS1155: 'const' declarations must be initialized \ No newline at end of file diff --git a/tests/baselines/reference/constDeclarations-scopes2.errors.txt b/tests/baselines/reference/constDeclarations-scopes2.errors.txt deleted file mode 100644 index b998f3a9980..00000000000 --- a/tests/baselines/reference/constDeclarations-scopes2.errors.txt +++ /dev/null @@ -1,21 +0,0 @@ -tests/cases/compiler/constDeclarations-scopes2.ts(9,19): error TS2365: Operator '<' cannot be applied to types '0' and '10'. - - -==== tests/cases/compiler/constDeclarations-scopes2.ts (1 errors) ==== - - // global - const c = "string"; - - var n: number; - var b: boolean; - - // for scope - for (const c = 0; c < 10; n = c ) { - ~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '10'. - // for block - const c = false; - b = c; - } - - \ No newline at end of file diff --git a/tests/baselines/reference/constDeclarations-scopes2.types b/tests/baselines/reference/constDeclarations-scopes2.types index a6bbdee7612..9834c6bb16e 100644 --- a/tests/baselines/reference/constDeclarations-scopes2.types +++ b/tests/baselines/reference/constDeclarations-scopes2.types @@ -2,8 +2,8 @@ // global const c = "string"; ->c : string ->"string" : string +>c : "string" +>"string" : "string" var n: number; >n : number @@ -13,24 +13,24 @@ var b: boolean; // for scope for (const c = 0; c < 10; n = c ) { ->c : number ->0 : number +>c : 0 +>0 : 0 >c < 10 : boolean ->c : number ->10 : number ->n = c : number +>c : 0 +>10 : 10 +>n = c : 0 >n : number ->c : number +>c : 0 // for block const c = false; ->c : boolean ->false : boolean +>c : false +>false : false b = c; ->b = c : boolean +>b = c : false >b : boolean ->c : boolean +>c : false } diff --git a/tests/baselines/reference/constDeclarations.errors.txt b/tests/baselines/reference/constDeclarations.errors.txt deleted file mode 100644 index 1642610eec2..00000000000 --- a/tests/baselines/reference/constDeclarations.errors.txt +++ /dev/null @@ -1,17 +0,0 @@ -tests/cases/compiler/constDeclarations.ts(8,19): error TS2365: Operator '<' cannot be applied to types '0' and '9'. - - -==== tests/cases/compiler/constDeclarations.ts (1 errors) ==== - - // No error - const c1 = false; - const c2: number = 23; - const c3 = 0, c4 :string = "", c5 = null; - - - for(const c4 = 0; c4 < 9; ) { break; } - ~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '0' and '9'. - - - for(const c5 = 0, c6 = 0; c5 < c6; ) { break; } \ No newline at end of file diff --git a/tests/baselines/reference/constDeclarations.types b/tests/baselines/reference/constDeclarations.types index efdc534ef1c..0fa7893529f 100644 --- a/tests/baselines/reference/constDeclarations.types +++ b/tests/baselines/reference/constDeclarations.types @@ -2,36 +2,36 @@ // No error const c1 = false; ->c1 : boolean ->false : boolean +>c1 : false +>false : false const c2: number = 23; >c2 : number ->23 : number +>23 : 23 const c3 = 0, c4 :string = "", c5 = null; ->c3 : number ->0 : number +>c3 : 0 +>0 : 0 >c4 : string ->"" : string +>"" : "" >c5 : any >null : null for(const c4 = 0; c4 < 9; ) { break; } ->c4 : number ->0 : number +>c4 : 0 +>0 : 0 >c4 < 9 : boolean ->c4 : number ->9 : number +>c4 : 0 +>9 : 9 for(const c5 = 0, c6 = 0; c5 < c6; ) { break; } ->c5 : number ->0 : number ->c6 : number ->0 : number +>c5 : 0 +>0 : 0 +>c6 : 0 +>0 : 0 >c5 < c6 : boolean ->c5 : number ->c6 : number +>c5 : 0 +>c6 : 0 diff --git a/tests/baselines/reference/constEnumBadPropertyNames.errors.txt b/tests/baselines/reference/constEnumBadPropertyNames.errors.txt index f2330617dea..09610ca24e5 100644 --- a/tests/baselines/reference/constEnumBadPropertyNames.errors.txt +++ b/tests/baselines/reference/constEnumBadPropertyNames.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/constEnumBadPropertyNames.ts(2,11): error TS2479: Property 'B' does not exist on 'const' enum 'E'. +tests/cases/compiler/constEnumBadPropertyNames.ts(2,11): error TS2339: Property 'B' does not exist on type 'typeof E'. ==== tests/cases/compiler/constEnumBadPropertyNames.ts (1 errors) ==== const enum E { A } var x = E["B"] ~~~ -!!! error TS2479: Property 'B' does not exist on 'const' enum 'E'. \ No newline at end of file +!!! error TS2339: Property 'B' does not exist on type 'typeof E'. \ No newline at end of file diff --git a/tests/baselines/reference/constEnumPropertyAccess2.errors.txt b/tests/baselines/reference/constEnumPropertyAccess2.errors.txt index ef5dd331d32..9f16059ff2f 100644 --- a/tests/baselines/reference/constEnumPropertyAccess2.errors.txt +++ b/tests/baselines/reference/constEnumPropertyAccess2.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(14,9): error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment. tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(15,12): error TS2476: A const enum member can only be accessed using a string literal. tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(17,1): error TS2322: Type '"string"' is not assignable to type 'G'. -tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(19,3): error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. ==== tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts (4 errors) ==== @@ -30,6 +30,6 @@ tests/cases/conformance/constEnums/constEnumPropertyAccess2.ts(19,1): error TS24 !!! error TS2322: Type '"string"' is not assignable to type 'G'. function foo(x: G) { } G.B = 3; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/constIndexedAccess.types b/tests/baselines/reference/constIndexedAccess.types index 0740a6efc67..9e08cf08f49 100644 --- a/tests/baselines/reference/constIndexedAccess.types +++ b/tests/baselines/reference/constIndexedAccess.types @@ -76,16 +76,16 @@ enum numbersNotConst { } let s3 = test[numbersNotConst.zero]; ->s3 : any ->test[numbersNotConst.zero] : any +>s3 : string +>test[numbersNotConst.zero] : string >test : indexAccess >numbersNotConst.zero : numbersNotConst.zero >numbersNotConst : typeof numbersNotConst >zero : numbersNotConst.zero let n3 = test[numbersNotConst.one]; ->n3 : any ->test[numbersNotConst.one] : any +>n3 : number +>test[numbersNotConst.one] : number >test : indexAccess >numbersNotConst.one : numbersNotConst.one >numbersNotConst : typeof numbersNotConst diff --git a/tests/baselines/reference/constraintSatisfactionWithAny.types b/tests/baselines/reference/constraintSatisfactionWithAny.types index 2f9c7553288..f3363fe1a90 100644 --- a/tests/baselines/reference/constraintSatisfactionWithAny.types +++ b/tests/baselines/reference/constraintSatisfactionWithAny.types @@ -35,20 +35,20 @@ var a; >a : any foo(a); ->foo(a) : undefined +>foo(a) : any >foo : (x: T) => T ->a : undefined +>a : any foo2(a); ->foo2(a) : undefined +>foo2(a) : any >foo2 : (x: T) => T ->a : undefined +>a : any //foo3(a); foo4(a); ->foo4(a) : undefined +>foo4(a) : any >foo4 : (x: T) => void>(x: T) => T ->a : undefined +>a : any var b: number; >b : number @@ -84,10 +84,10 @@ class C { } var c1 = new C(a); ->c1 : C ->new C(a) : C +>c1 : C +>new C(a) : C >C : typeof C ->a : undefined +>a : any var c2 = new C(b); >c2 : C @@ -106,10 +106,10 @@ class C2 { } var c3 = new C2(a); ->c3 : C2 ->new C2(a) : C2 +>c3 : C2 +>new C2(a) : C2 >C2 : typeof C2 ->a : undefined +>a : any var c4 = new C2(b); >c4 : C2 @@ -138,10 +138,10 @@ class C4(x:T) => T> { } var c7 = new C4(a); ->c7 : C4 ->new C4(a) : C4 +>c7 : C4 +>new C4(a) : C4 >C4 : typeof C4 ->a : undefined +>a : any var c8 = new C4(b); >c8 : C4 diff --git a/tests/baselines/reference/constructorArgsErrors1.js b/tests/baselines/reference/constructorArgsErrors1.js index 15c5e64952b..bb0725ab8b9 100644 --- a/tests/baselines/reference/constructorArgsErrors1.js +++ b/tests/baselines/reference/constructorArgsErrors1.js @@ -6,7 +6,7 @@ class foo { //// [constructorArgsErrors1.js] var foo = (function () { - function foo(static a) { + function foo(a) { } return foo; }()); diff --git a/tests/baselines/reference/constructorArgsErrors5.js b/tests/baselines/reference/constructorArgsErrors5.js index 6ba68cb88b4..c481d6f323c 100644 --- a/tests/baselines/reference/constructorArgsErrors5.js +++ b/tests/baselines/reference/constructorArgsErrors5.js @@ -7,7 +7,7 @@ class foo { //// [constructorArgsErrors5.js] var foo = (function () { - function foo(export a) { + function foo(a) { } return foo; }()); diff --git a/tests/baselines/reference/constructorWithCapturedSuper.js b/tests/baselines/reference/constructorWithCapturedSuper.js new file mode 100644 index 00000000000..895f78eb04b --- /dev/null +++ b/tests/baselines/reference/constructorWithCapturedSuper.js @@ -0,0 +1,123 @@ +//// [constructorWithCapturedSuper.ts] +let oneA: A; + +class A { + constructor() { + return oneA; + } +} + +class B extends A { + constructor(x: number) { + super(); + if (x === 1) { + return; + } + while (x < 2) { + return; + } + try { + return + } + catch (e) { + return; + } + finally { + return; + } + } +} + +class C extends A { + constructor(x: number) { + super(); + for (let i = 0; i < 10; ++i) { + () => i + x; + if (x === 1) { + return; + } + } + } +} + +class D extends A { + constructor(x: number) { + super(); + () => { + return; + } + function foo() { + return; + } + } +} + +//// [constructorWithCapturedSuper.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var oneA; +var A = (function () { + function A() { + return oneA; + } + return A; +}()); +var B = (function (_super) { + __extends(B, _super); + function B(x) { + var _this = _super.call(this) || this; + if (x === 1) { + return _this; + } + while (x < 2) { + return _this; + } + try { + return _this; + } + catch (e) { + return _this; + } + finally { + return _this; + } + return _this; + } + return B; +}(A)); +var C = (function (_super) { + __extends(C, _super); + function C(x) { + var _this = _super.call(this) || this; + var _loop_1 = function (i) { + (function () { return i + x; }); + if (x === 1) { + return { value: _this }; + } + }; + for (var i = 0; i < 10; ++i) { + var state_1 = _loop_1(i); + if (typeof state_1 === "object") + return state_1.value; + } + return _this; + } + return C; +}(A)); +var D = (function (_super) { + __extends(D, _super); + function D(x) { + var _this = _super.call(this) || this; + (function () { + return; + }); + function foo() { + return; + } + return _this; + } + return D; +}(A)); diff --git a/tests/baselines/reference/constructorWithCapturedSuper.symbols b/tests/baselines/reference/constructorWithCapturedSuper.symbols new file mode 100644 index 00000000000..1743ee61612 --- /dev/null +++ b/tests/baselines/reference/constructorWithCapturedSuper.symbols @@ -0,0 +1,96 @@ +=== tests/cases/compiler/constructorWithCapturedSuper.ts === +let oneA: A; +>oneA : Symbol(oneA, Decl(constructorWithCapturedSuper.ts, 0, 3)) +>A : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + +class A { +>A : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + constructor() { + return oneA; +>oneA : Symbol(oneA, Decl(constructorWithCapturedSuper.ts, 0, 3)) + } +} + +class B extends A { +>B : Symbol(B, Decl(constructorWithCapturedSuper.ts, 6, 1)) +>A : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + constructor(x: number) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 9, 16)) + + super(); +>super : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + if (x === 1) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 9, 16)) + + return; + } + while (x < 2) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 9, 16)) + + return; + } + try { + return + } + catch (e) { +>e : Symbol(e, Decl(constructorWithCapturedSuper.ts, 20, 15)) + + return; + } + finally { + return; + } + } +} + +class C extends A { +>C : Symbol(C, Decl(constructorWithCapturedSuper.ts, 27, 1)) +>A : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + constructor(x: number) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 30, 16)) + + super(); +>super : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + for (let i = 0; i < 10; ++i) { +>i : Symbol(i, Decl(constructorWithCapturedSuper.ts, 32, 16)) +>i : Symbol(i, Decl(constructorWithCapturedSuper.ts, 32, 16)) +>i : Symbol(i, Decl(constructorWithCapturedSuper.ts, 32, 16)) + + () => i + x; +>i : Symbol(i, Decl(constructorWithCapturedSuper.ts, 32, 16)) +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 30, 16)) + + if (x === 1) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 30, 16)) + + return; + } + } + } +} + +class D extends A { +>D : Symbol(D, Decl(constructorWithCapturedSuper.ts, 39, 1)) +>A : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + constructor(x: number) { +>x : Symbol(x, Decl(constructorWithCapturedSuper.ts, 42, 16)) + + super(); +>super : Symbol(A, Decl(constructorWithCapturedSuper.ts, 0, 12)) + + () => { + return; + } + function foo() { +>foo : Symbol(foo, Decl(constructorWithCapturedSuper.ts, 46, 9)) + + return; + } + } +} diff --git a/tests/baselines/reference/constructorWithCapturedSuper.types b/tests/baselines/reference/constructorWithCapturedSuper.types new file mode 100644 index 00000000000..13696029d53 --- /dev/null +++ b/tests/baselines/reference/constructorWithCapturedSuper.types @@ -0,0 +1,113 @@ +=== tests/cases/compiler/constructorWithCapturedSuper.ts === +let oneA: A; +>oneA : A +>A : A + +class A { +>A : A + + constructor() { + return oneA; +>oneA : A + } +} + +class B extends A { +>B : B +>A : A + + constructor(x: number) { +>x : number + + super(); +>super() : void +>super : typeof A + + if (x === 1) { +>x === 1 : boolean +>x : number +>1 : 1 + + return; + } + while (x < 2) { +>x < 2 : boolean +>x : number +>2 : 2 + + return; + } + try { + return + } + catch (e) { +>e : any + + return; + } + finally { + return; + } + } +} + +class C extends A { +>C : C +>A : A + + constructor(x: number) { +>x : number + + super(); +>super() : void +>super : typeof A + + for (let i = 0; i < 10; ++i) { +>i : number +>0 : 0 +>i < 10 : boolean +>i : number +>10 : 10 +>++i : number +>i : number + + () => i + x; +>() => i + x : () => number +>i + x : number +>i : number +>x : number + + if (x === 1) { +>x === 1 : boolean +>x : number +>1 : 1 + + return; + } + } + } +} + +class D extends A { +>D : D +>A : A + + constructor(x: number) { +>x : number + + super(); +>super() : void +>super : typeof A + + () => { +>() => { return; } : () => void + + return; + } + function foo() { +>foo : () => void + + return; + } + } +} diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 49d3e378855..2854e73d935 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -25,7 +25,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(59,5): error TS1 tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(70,13): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(73,37): error TS1127: Invalid character. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(82,13): error TS1109: Expression expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(90,23): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(90,23): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(91,13): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(106,29): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(107,13): error TS1109: Expression expected. @@ -236,7 +236,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(262,1): error TS // var any = 0 ^= ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. var bool = 0; ~~~ !!! error TS1109: Expression expected. diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js index 2e3190c15c8..d4cd737ab46 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js @@ -292,12 +292,12 @@ var TypeScriptAllInOne; (function (TypeScriptAllInOne) { var Program = (function () { function Program() { - this.case = bfs.STATEMENTS(4); + this["case"] = bfs.STATEMENTS(4); } Program.Main = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } try { var bfs = new BasicFeatures(); @@ -305,13 +305,13 @@ var TypeScriptAllInOne; retValue = bfs.VARIABLES(); if (retValue != 0) ^= { - return: 1 + "return": 1 }; } finally { } }; - Program.prototype.if = function (retValue) { + Program.prototype["if"] = function (retValue) { if (retValue === void 0) { retValue = != 0; } return 1; ^ @@ -327,7 +327,7 @@ var TypeScriptAllInOne; return 1; } }; - Program.prototype.catch = function (e) { + Program.prototype["catch"] = function (e) { console.log(e); }; return Program; @@ -364,7 +364,7 @@ var BasicFeatures = (function () { ; var quoted = '"', quoted2 = "'"; var reg = /\w*/; - var objLit = { "var": number = 42, equals: function (x) { return x["var"] === 42; }, instanceof: function () { return 'objLit{42}'; } }; + var objLit = { "var": number = 42, equals: function (x) { return x["var"] === 42; }, "instanceof": function () { return 'objLit{42}'; } }; var weekday = Weekdays.Monday; var con = char + f + hexchar + float.toString() + float2.toString() + reg.toString() + objLit + weekday; // diff --git a/tests/baselines/reference/contextualTypingOfTooShortOverloads.js b/tests/baselines/reference/contextualTypingOfTooShortOverloads.js new file mode 100644 index 00000000000..55f1361f5a8 --- /dev/null +++ b/tests/baselines/reference/contextualTypingOfTooShortOverloads.js @@ -0,0 +1,59 @@ +//// [contextualTypingOfTooShortOverloads.ts] +// small repro from #11875 +var use: Overload; +use((req, res) => {}); + +interface Overload { + (handler1: (req1: string) => void): void; + (handler2: (req2: number, res2: number) => void): void; +} +// larger repro from #11875 +let app: MyApp; +app.use((err: any, req, res, next) => { return; }); + + +interface MyApp { + use: IRouterHandler & IRouterMatcher; +} + +interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; +} + +interface IRouterMatcher { + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +} + +type PathParams = string | RegExp | (string | RegExp)[]; +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + +interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; +} + +interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; +} + +interface Request { + method: string; +} + +interface Response { + statusCode: number; +} + +interface NextFunction { + (err?: any): void; +} + + +//// [contextualTypingOfTooShortOverloads.js] +// small repro from #11875 +var use; +use(function (req, res) { }); +// larger repro from #11875 +var app; +app.use(function (err, req, res, next) { return; }); diff --git a/tests/baselines/reference/contextualTypingOfTooShortOverloads.symbols b/tests/baselines/reference/contextualTypingOfTooShortOverloads.symbols new file mode 100644 index 00000000000..8f196cf4825 --- /dev/null +++ b/tests/baselines/reference/contextualTypingOfTooShortOverloads.symbols @@ -0,0 +1,139 @@ +=== tests/cases/compiler/contextualTypingOfTooShortOverloads.ts === +// small repro from #11875 +var use: Overload; +>use : Symbol(use, Decl(contextualTypingOfTooShortOverloads.ts, 1, 3)) +>Overload : Symbol(Overload, Decl(contextualTypingOfTooShortOverloads.ts, 2, 22)) + +use((req, res) => {}); +>use : Symbol(use, Decl(contextualTypingOfTooShortOverloads.ts, 1, 3)) +>req : Symbol(req, Decl(contextualTypingOfTooShortOverloads.ts, 2, 5)) +>res : Symbol(res, Decl(contextualTypingOfTooShortOverloads.ts, 2, 9)) + +interface Overload { +>Overload : Symbol(Overload, Decl(contextualTypingOfTooShortOverloads.ts, 2, 22)) + + (handler1: (req1: string) => void): void; +>handler1 : Symbol(handler1, Decl(contextualTypingOfTooShortOverloads.ts, 5, 5)) +>req1 : Symbol(req1, Decl(contextualTypingOfTooShortOverloads.ts, 5, 16)) + + (handler2: (req2: number, res2: number) => void): void; +>handler2 : Symbol(handler2, Decl(contextualTypingOfTooShortOverloads.ts, 6, 5)) +>req2 : Symbol(req2, Decl(contextualTypingOfTooShortOverloads.ts, 6, 16)) +>res2 : Symbol(res2, Decl(contextualTypingOfTooShortOverloads.ts, 6, 29)) +} +// larger repro from #11875 +let app: MyApp; +>app : Symbol(app, Decl(contextualTypingOfTooShortOverloads.ts, 9, 3)) +>MyApp : Symbol(MyApp, Decl(contextualTypingOfTooShortOverloads.ts, 10, 51)) + +app.use((err: any, req, res, next) => { return; }); +>app.use : Symbol(MyApp.use, Decl(contextualTypingOfTooShortOverloads.ts, 13, 17)) +>app : Symbol(app, Decl(contextualTypingOfTooShortOverloads.ts, 9, 3)) +>use : Symbol(MyApp.use, Decl(contextualTypingOfTooShortOverloads.ts, 13, 17)) +>err : Symbol(err, Decl(contextualTypingOfTooShortOverloads.ts, 10, 9)) +>req : Symbol(req, Decl(contextualTypingOfTooShortOverloads.ts, 10, 18)) +>res : Symbol(res, Decl(contextualTypingOfTooShortOverloads.ts, 10, 23)) +>next : Symbol(next, Decl(contextualTypingOfTooShortOverloads.ts, 10, 28)) + + +interface MyApp { +>MyApp : Symbol(MyApp, Decl(contextualTypingOfTooShortOverloads.ts, 10, 51)) + + use: IRouterHandler & IRouterMatcher; +>use : Symbol(MyApp.use, Decl(contextualTypingOfTooShortOverloads.ts, 13, 17)) +>IRouterHandler : Symbol(IRouterHandler, Decl(contextualTypingOfTooShortOverloads.ts, 15, 1)) +>IRouterMatcher : Symbol(IRouterMatcher, Decl(contextualTypingOfTooShortOverloads.ts, 20, 1)) +} + +interface IRouterHandler { +>IRouterHandler : Symbol(IRouterHandler, Decl(contextualTypingOfTooShortOverloads.ts, 15, 1)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 17, 25)) + + (...handlers: RequestHandler[]): T; +>handlers : Symbol(handlers, Decl(contextualTypingOfTooShortOverloads.ts, 18, 5)) +>RequestHandler : Symbol(RequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 28, 108)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 17, 25)) + + (...handlers: RequestHandlerParams[]): T; +>handlers : Symbol(handlers, Decl(contextualTypingOfTooShortOverloads.ts, 19, 5)) +>RequestHandlerParams : Symbol(RequestHandlerParams, Decl(contextualTypingOfTooShortOverloads.ts, 27, 56)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 17, 25)) +} + +interface IRouterMatcher { +>IRouterMatcher : Symbol(IRouterMatcher, Decl(contextualTypingOfTooShortOverloads.ts, 20, 1)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 22, 25)) + + (path: PathParams, ...handlers: RequestHandler[]): T; +>path : Symbol(path, Decl(contextualTypingOfTooShortOverloads.ts, 23, 5)) +>PathParams : Symbol(PathParams, Decl(contextualTypingOfTooShortOverloads.ts, 25, 1)) +>handlers : Symbol(handlers, Decl(contextualTypingOfTooShortOverloads.ts, 23, 22)) +>RequestHandler : Symbol(RequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 28, 108)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 22, 25)) + + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +>path : Symbol(path, Decl(contextualTypingOfTooShortOverloads.ts, 24, 5)) +>PathParams : Symbol(PathParams, Decl(contextualTypingOfTooShortOverloads.ts, 25, 1)) +>handlers : Symbol(handlers, Decl(contextualTypingOfTooShortOverloads.ts, 24, 22)) +>RequestHandlerParams : Symbol(RequestHandlerParams, Decl(contextualTypingOfTooShortOverloads.ts, 27, 56)) +>T : Symbol(T, Decl(contextualTypingOfTooShortOverloads.ts, 22, 25)) +} + +type PathParams = string | RegExp | (string | RegExp)[]; +>PathParams : Symbol(PathParams, Decl(contextualTypingOfTooShortOverloads.ts, 25, 1)) +>RegExp : Symbol(RegExp, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>RegExp : Symbol(RegExp, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; +>RequestHandlerParams : Symbol(RequestHandlerParams, Decl(contextualTypingOfTooShortOverloads.ts, 27, 56)) +>RequestHandler : Symbol(RequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 28, 108)) +>ErrorRequestHandler : Symbol(ErrorRequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 32, 1)) +>RequestHandler : Symbol(RequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 28, 108)) +>ErrorRequestHandler : Symbol(ErrorRequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 32, 1)) + +interface RequestHandler { +>RequestHandler : Symbol(RequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 28, 108)) + + (req: Request, res: Response, next: NextFunction): any; +>req : Symbol(req, Decl(contextualTypingOfTooShortOverloads.ts, 31, 5)) +>Request : Symbol(Request, Decl(contextualTypingOfTooShortOverloads.ts, 36, 1)) +>res : Symbol(res, Decl(contextualTypingOfTooShortOverloads.ts, 31, 18)) +>Response : Symbol(Response, Decl(contextualTypingOfTooShortOverloads.ts, 40, 1)) +>next : Symbol(next, Decl(contextualTypingOfTooShortOverloads.ts, 31, 33)) +>NextFunction : Symbol(NextFunction, Decl(contextualTypingOfTooShortOverloads.ts, 44, 1)) +} + +interface ErrorRequestHandler { +>ErrorRequestHandler : Symbol(ErrorRequestHandler, Decl(contextualTypingOfTooShortOverloads.ts, 32, 1)) + + (err: any, req: Request, res: Response, next: NextFunction): any; +>err : Symbol(err, Decl(contextualTypingOfTooShortOverloads.ts, 35, 5)) +>req : Symbol(req, Decl(contextualTypingOfTooShortOverloads.ts, 35, 14)) +>Request : Symbol(Request, Decl(contextualTypingOfTooShortOverloads.ts, 36, 1)) +>res : Symbol(res, Decl(contextualTypingOfTooShortOverloads.ts, 35, 28)) +>Response : Symbol(Response, Decl(contextualTypingOfTooShortOverloads.ts, 40, 1)) +>next : Symbol(next, Decl(contextualTypingOfTooShortOverloads.ts, 35, 43)) +>NextFunction : Symbol(NextFunction, Decl(contextualTypingOfTooShortOverloads.ts, 44, 1)) +} + +interface Request { +>Request : Symbol(Request, Decl(contextualTypingOfTooShortOverloads.ts, 36, 1)) + + method: string; +>method : Symbol(Request.method, Decl(contextualTypingOfTooShortOverloads.ts, 38, 19)) +} + +interface Response { +>Response : Symbol(Response, Decl(contextualTypingOfTooShortOverloads.ts, 40, 1)) + + statusCode: number; +>statusCode : Symbol(Response.statusCode, Decl(contextualTypingOfTooShortOverloads.ts, 42, 20)) +} + +interface NextFunction { +>NextFunction : Symbol(NextFunction, Decl(contextualTypingOfTooShortOverloads.ts, 44, 1)) + + (err?: any): void; +>err : Symbol(err, Decl(contextualTypingOfTooShortOverloads.ts, 47, 5)) +} + diff --git a/tests/baselines/reference/contextualTypingOfTooShortOverloads.types b/tests/baselines/reference/contextualTypingOfTooShortOverloads.types new file mode 100644 index 00000000000..769bd55d4b5 --- /dev/null +++ b/tests/baselines/reference/contextualTypingOfTooShortOverloads.types @@ -0,0 +1,143 @@ +=== tests/cases/compiler/contextualTypingOfTooShortOverloads.ts === +// small repro from #11875 +var use: Overload; +>use : Overload +>Overload : Overload + +use((req, res) => {}); +>use((req, res) => {}) : void +>use : Overload +>(req, res) => {} : (req: any, res: any) => void +>req : any +>res : any + +interface Overload { +>Overload : Overload + + (handler1: (req1: string) => void): void; +>handler1 : (req1: string) => void +>req1 : string + + (handler2: (req2: number, res2: number) => void): void; +>handler2 : (req2: number, res2: number) => void +>req2 : number +>res2 : number +} +// larger repro from #11875 +let app: MyApp; +>app : MyApp +>MyApp : MyApp + +app.use((err: any, req, res, next) => { return; }); +>app.use((err: any, req, res, next) => { return; }) : MyApp +>app.use : IRouterHandler & IRouterMatcher +>app : MyApp +>use : IRouterHandler & IRouterMatcher +>(err: any, req, res, next) => { return; } : (err: any, req: any, res: any, next: any) => void +>err : any +>req : any +>res : any +>next : any + + +interface MyApp { +>MyApp : MyApp + + use: IRouterHandler & IRouterMatcher; +>use : IRouterHandler & IRouterMatcher +>IRouterHandler : IRouterHandler +>IRouterMatcher : IRouterMatcher +} + +interface IRouterHandler { +>IRouterHandler : IRouterHandler +>T : T + + (...handlers: RequestHandler[]): T; +>handlers : RequestHandler[] +>RequestHandler : RequestHandler +>T : T + + (...handlers: RequestHandlerParams[]): T; +>handlers : RequestHandlerParams[] +>RequestHandlerParams : RequestHandlerParams +>T : T +} + +interface IRouterMatcher { +>IRouterMatcher : IRouterMatcher +>T : T + + (path: PathParams, ...handlers: RequestHandler[]): T; +>path : PathParams +>PathParams : PathParams +>handlers : RequestHandler[] +>RequestHandler : RequestHandler +>T : T + + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +>path : PathParams +>PathParams : PathParams +>handlers : RequestHandlerParams[] +>RequestHandlerParams : RequestHandlerParams +>T : T +} + +type PathParams = string | RegExp | (string | RegExp)[]; +>PathParams : PathParams +>RegExp : RegExp +>RegExp : RegExp + +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; +>RequestHandlerParams : RequestHandlerParams +>RequestHandler : RequestHandler +>ErrorRequestHandler : ErrorRequestHandler +>RequestHandler : RequestHandler +>ErrorRequestHandler : ErrorRequestHandler + +interface RequestHandler { +>RequestHandler : RequestHandler + + (req: Request, res: Response, next: NextFunction): any; +>req : Request +>Request : Request +>res : Response +>Response : Response +>next : NextFunction +>NextFunction : NextFunction +} + +interface ErrorRequestHandler { +>ErrorRequestHandler : ErrorRequestHandler + + (err: any, req: Request, res: Response, next: NextFunction): any; +>err : any +>req : Request +>Request : Request +>res : Response +>Response : Response +>next : NextFunction +>NextFunction : NextFunction +} + +interface Request { +>Request : Request + + method: string; +>method : string +} + +interface Response { +>Response : Response + + statusCode: number; +>statusCode : number +} + +interface NextFunction { +>NextFunction : NextFunction + + (err?: any): void; +>err : any +} + diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializer.js b/tests/baselines/reference/contextuallyTypedBindingInitializer.js index f2424ce55d7..6542e747edc 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializer.js +++ b/tests/baselines/reference/contextuallyTypedBindingInitializer.js @@ -37,7 +37,7 @@ function f2(_a) { var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v.toString(); } : _b; } function f3(_a) { - var _b = "show", _c = _a[_b], showRename = _c === void 0 ? function (v) { return v.toString(); } : _c; + var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v.toString(); } : _b; } function ff(_a) { var _b = _a.nested, nested = _b === void 0 ? { show: function (v) { return v.toString(); } } : _b; diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.js b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.js index 3f1ed156fdb..bdc7ed68b3f 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.js +++ b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.js @@ -35,7 +35,7 @@ function f2(_a) { var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v; } : _b; } function f3(_a) { - var _b = "show", _c = _a[_b], showRename = _c === void 0 ? function (v) { return v; } : _c; + var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v; } : _b; } function ff(_a) { var _b = _a.nested, nestedRename = _b === void 0 ? { show: function (v) { return v; } } : _b; diff --git a/tests/baselines/reference/contextuallyTypedIife.js b/tests/baselines/reference/contextuallyTypedIife.js index 0a84e45e30b..d2eaaf9c2d5 100644 --- a/tests/baselines/reference/contextuallyTypedIife.js +++ b/tests/baselines/reference/contextuallyTypedIife.js @@ -57,21 +57,21 @@ let eleven = (o => o.a(11))({ a: function(n) { return n; } }); (function () { var numbers = []; for (var _i = 0; _i < arguments.length; _i++) { - numbers[_i - 0] = arguments[_i]; + numbers[_i] = arguments[_i]; } return numbers.every(function (n) { return n > 0; }); })(5, 6, 7); (function () { var mixed = []; for (var _i = 0; _i < arguments.length; _i++) { - mixed[_i - 0] = arguments[_i]; + mixed[_i] = arguments[_i]; } return mixed.every(function (n) { return !!n; }); })(5, 'oops', 'oh no'); (function () { var noNumbers = []; for (var _i = 0; _i < arguments.length; _i++) { - noNumbers[_i - 0] = arguments[_i]; + noNumbers[_i] = arguments[_i]; } return noNumbers.some(function (n) { return n > 0; }); })(); diff --git a/tests/baselines/reference/contextuallyTypingRestParameters.js b/tests/baselines/reference/contextuallyTypingRestParameters.js index 17561f5d7fc..8a1f2ffbdfb 100644 --- a/tests/baselines/reference/contextuallyTypingRestParameters.js +++ b/tests/baselines/reference/contextuallyTypingRestParameters.js @@ -11,7 +11,7 @@ var x: (...y: string[]) => void = function (.../*3*/y) { var x = function () { var y = []; for (var _i = 0; _i < arguments.length; _i++) { - y[_i - 0] = arguments[_i]; + y[_i] = arguments[_i]; } var t = y; var x2 = t; // This should be error diff --git a/tests/baselines/reference/controlFlowArrayErrors.errors.txt b/tests/baselines/reference/controlFlowArrayErrors.errors.txt new file mode 100644 index 00000000000..2ef009dc0e1 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrayErrors.errors.txt @@ -0,0 +1,105 @@ +tests/cases/compiler/controlFlowArrayErrors.ts(5,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(6,13): error TS7005: Variable 'x' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(12,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(14,13): error TS7005: Variable 'x' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(20,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(23,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(30,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. +tests/cases/compiler/controlFlowArrayErrors.ts(35,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. +tests/cases/compiler/controlFlowArrayErrors.ts(49,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: (string | number)[]) => number) | ((...items: boolean[]) => number)' has no compatible call signatures. +tests/cases/compiler/controlFlowArrayErrors.ts(57,12): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. +tests/cases/compiler/controlFlowArrayErrors.ts(61,11): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(64,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. + + +==== tests/cases/compiler/controlFlowArrayErrors.ts (12 errors) ==== + + declare function cond(): boolean; + + function f1() { + let x = []; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + x.push(5); + let z = x; + } + + function f2() { + let x; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x = []; + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + x.push(5); + let z = x; + } + + function f3() { + let x = []; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x.push(5); + function g() { + x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + } + } + + function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error + ~~~~ +!!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. + } + + function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error + ~~~~ +!!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. + } + + function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error + ~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: (string | number)[]) => number) | ((...items: boolean[]) => number)' has no compatible call signatures. + } + + function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error + ~~~~~~~ +!!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. + } + + function f8() { + const x = []; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x.push(5); + function g() { + x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowArrayErrors.js b/tests/baselines/reference/controlFlowArrayErrors.js new file mode 100644 index 00000000000..59995eb3094 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrayErrors.js @@ -0,0 +1,125 @@ +//// [controlFlowArrayErrors.ts] + +declare function cond(): boolean; + +function f1() { + let x = []; // Implicit any[] error in some locations + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f2() { + let x; // Implicit any[] error in some locations + x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f3() { + let x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} + +function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} + +function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} + +function f8() { + const x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} + +//// [controlFlowArrayErrors.js] +function f1() { + var x = []; // Implicit any[] error in some locations + var y = x; // Implicit any[] error + x.push(5); + var z = x; +} +function f2() { + var x; // Implicit any[] error in some locations + x = []; + var y = x; // Implicit any[] error + x.push(5); + var z = x; +} +function f3() { + var x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} +function f4() { + var x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} +function f5() { + var x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} +function f6() { + var x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} +function f7() { + var x = []; // x has evolving array value + x.push(5); + var y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} +function f8() { + var x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js new file mode 100644 index 00000000000..3f119599495 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.js @@ -0,0 +1,343 @@ +//// [controlFlowArrays.ts] + +declare function cond(): boolean; + +function f1() { + let x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} + +function f2() { + let x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f3() { + let x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} + +function f4() { + let x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} + +function f5() { + let x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} + +function f6() { + let x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} + +function f7() { + let x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} + +function f8() { + let x = []; + x.push(5); + if (cond()) return x; // number[] + x.push("hello"); + if (cond()) return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} + +function f9() { + let x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} + +function f10() { + let x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} + +function f11() { + let x = []; + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; +} + +function f12() { + let x; + x = []; + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; +} + +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f14() { + const x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f15() { + let x = []; + while (cond()) { + while (cond()) {} + x.push("hello"); + } + return x; // string[] +} + +function f16() { + let x; + let y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] +} + +function f17() { + let x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} + +function f18() { + let x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] +} + +//// [controlFlowArrays.js] +function f1() { + var x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} +function f2() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} +function f3() { + var x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} +function f4() { + var x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} +function f5() { + var x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} +function f6() { + var x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} +function f7() { + var x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} +function f8() { + var x = []; + x.push(5); + if (cond()) + return x; // number[] + x.push("hello"); + if (cond()) + return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} +function f9() { + var x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} +function f10() { + var x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} +function f11() { + var x = []; + if (x.length === 0) { + x.push("hello"); + } + return x; +} +function f12() { + var x; + x = []; + if (x.length === 0) { + x.push("hello"); + } + return x; +} +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} +function f14() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} +function f15() { + var x = []; + while (cond()) { + while (cond()) { } + x.push("hello"); + } + return x; // string[] +} +function f16() { + var x; + var y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] +} +function f17() { + var x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} +function f18() { + var x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] +} diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols new file mode 100644 index 00000000000..184a813a05f --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -0,0 +1,470 @@ +=== tests/cases/compiler/controlFlowArrays.ts === + +declare function cond(): boolean; +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + +function f1() { +>f1 : Symbol(f1, Decl(controlFlowArrays.ts, 1, 33)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[0] = 5; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[1] = "hello"; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[2] = true; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) +} + +function f2() { +>f2 : Symbol(f2, Decl(controlFlowArrays.ts, 9, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +} + +function f3() { +>f3 : Symbol(f3, Decl(controlFlowArrays.ts, 17, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) + + x.push(5, "hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) +} + +function f4() { +>f4 : Symbol(f4, Decl(controlFlowArrays.ts, 24, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + else { + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +} + +function f5() { +>f5 : Symbol(f5, Decl(controlFlowArrays.ts, 35, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + else { + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +} + +function f6() { +>f6 : Symbol(f6, Decl(controlFlowArrays.ts, 48, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = 5; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + } + else { + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // number | string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) +} + +function f7() { +>f7 : Symbol(f7, Decl(controlFlowArrays.ts, 60, 1)) + + let x = null; +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + } + return x; // string[] | null +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) +} + +function f8() { +>f8 : Symbol(f8, Decl(controlFlowArrays.ts, 71, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + if (cond()) return x; // number[] +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + if (cond()) return x; // (string | number)[] +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +} + +function f9() { +>f9 : Symbol(f9, Decl(controlFlowArrays.ts, 81, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // number[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + } + else { + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + } +} + +function f10() { +>f10 : Symbol(f10, Decl(controlFlowArrays.ts, 93, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x; // boolean[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + } + else { + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x; // number[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + } + x.push(99); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +} + +function f11() { +>f11 : Symbol(f11, Decl(controlFlowArrays.ts, 111, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) + + if (x.length === 0) { // x.length ok on implicit any[] +>x.length : Symbol(Array.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +>length : Symbol(Array.length, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +} + +function f12() { +>f12 : Symbol(f12, Decl(controlFlowArrays.ts, 119, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) + + if (x.length === 0) { // x.length ok on implicit any[] +>x.length : Symbol(Array.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) +>length : Symbol(Array.length, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) +} + +function f13() { +>f13 : Symbol(f13, Decl(controlFlowArrays.ts, 128, 1)) + + var x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) +} + +function f14() { +>f14 : Symbol(f14, Decl(controlFlowArrays.ts, 136, 1)) + + const x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) +} + +function f15() { +>f15 : Symbol(f15, Decl(controlFlowArrays.ts, 144, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + while (cond()) {} +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) +} + +function f16() { +>f16 : Symbol(f16, Decl(controlFlowArrays.ts, 153, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) + + let y; +>y : Symbol(y, Decl(controlFlowArrays.ts, 157, 7)) + + (x = [], x).push(5); +>(x = [], x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + (x.push("hello"), x).push(true); +>(x.push("hello"), x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + ((x))[3] = { a: 1 }; +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>a : Symbol(a, Decl(controlFlowArrays.ts, 160, 16)) + + return x; // (string | number | boolean | { a: number })[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +} + +function f17() { +>f17 : Symbol(f17, Decl(controlFlowArrays.ts, 162, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) + + x.unshift(5); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x.unshift("hello"); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x.unshift(true); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) +} + +function f18() { +>f18 : Symbol(f18, Decl(controlFlowArrays.ts, 170, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.unshift("hello"); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x[2] = true; +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) +} diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types new file mode 100644 index 00000000000..2a27bbf10de --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.types @@ -0,0 +1,615 @@ +=== tests/cases/compiler/controlFlowArrays.ts === + +declare function cond(): boolean; +>cond : () => boolean + +function f1() { +>f1 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x[0] = 5; +>x[0] = 5 : 5 +>x[0] : any +>x : any[] +>0 : 0 +>5 : 5 + + x[1] = "hello"; +>x[1] = "hello" : "hello" +>x[1] : any +>x : any[] +>1 : 1 +>"hello" : "hello" + + x[2] = true; +>x[2] = true : true +>x[2] : any +>x : any[] +>2 : 2 +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f2() { +>f2 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f3() { +>f3 : () => (string | number)[] + + let x; +>x : any + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push(5, "hello"); +>x.push(5, "hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 +>"hello" : "hello" + + return x; // (string | number)[] +>x : (string | number)[] +} + +function f4() { +>f4 : () => (string | number)[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + } + else { + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // (string | number)[] +>x : (string | number)[] +} + +function f5() { +>f5 : () => (string | number)[] + + let x; +>x : any + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + } + else { + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // (string | number)[] +>x : (string | number)[] +} + +function f6() { +>f6 : () => number | string[] + + let x; +>x : any + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = 5; +>x = 5 : 5 +>x : any +>5 : 5 + } + else { + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // number | string[] +>x : number | string[] +} + +function f7() { +>f7 : () => string[] | null + + let x = null; +>x : any +>null : null + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + } + return x; // string[] | null +>x : string[] | null +} + +function f8() { +>f8 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + if (cond()) return x; // number[] +>cond() : boolean +>cond : () => boolean +>x : number[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + if (cond()) return x; // (string | number)[] +>cond() : boolean +>cond : () => boolean +>x : (string | number)[] + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f9() { +>f9 : () => string[] | number[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + return x; // number[] +>x : number[] + } + else { + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + return x; // string[] +>x : string[] + } +} + +function f10() { +>f10 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + x; // boolean[] +>x : boolean[] + } + else { + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x; // number[] +>x : number[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + x; // (string | number)[] +>x : (string | number)[] + } + x.push(99); +>x.push(99) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>99 : 99 + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f11() { +>f11 : () => string[] + + let x = []; +>x : any[] +>[] : never[] + + if (x.length === 0) { // x.length ok on implicit any[] +>x.length === 0 : boolean +>x.length : number +>x : any[] +>length : number +>0 : 0 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; +>x : string[] +} + +function f12() { +>f12 : () => string[] + + let x; +>x : any + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + if (x.length === 0) { // x.length ok on implicit any[] +>x.length === 0 : boolean +>x.length : number +>x : any[] +>length : number +>0 : 0 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; +>x : string[] +} + +function f13() { +>f13 : () => (string | number | boolean)[] + + var x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f14() { +>f14 : () => (string | number | boolean)[] + + const x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f15() { +>f15 : () => string[] + + let x = []; +>x : any[] +>[] : never[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + while (cond()) {} +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // string[] +>x : string[] +} + +function f16() { +>f16 : () => (string | number | boolean | { a: number; })[] + + let x; +>x : any + + let y; +>y : any + + (x = [], x).push(5); +>(x = [], x).push(5) : number +>(x = [], x).push : (...items: any[]) => number +>(x = [], x) : any[] +>x = [], x : any[] +>x = [] : never[] +>x : any +>[] : never[] +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + (x.push("hello"), x).push(true); +>(x.push("hello"), x).push(true) : number +>(x.push("hello"), x).push : (...items: any[]) => number +>(x.push("hello"), x) : any[] +>x.push("hello"), x : any[] +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" +>x : any[] +>push : (...items: any[]) => number +>true : true + + ((x))[3] = { a: 1 }; +>((x))[3] = { a: 1 } : { a: number; } +>((x))[3] : any +>((x)) : any[] +>(x) : any[] +>x : any[] +>3 : 3 +>{ a: 1 } : { a: number; } +>a : number +>1 : 1 + + return x; // (string | number | boolean | { a: number })[] +>x : (string | number | boolean | { a: number; })[] +} + +function f17() { +>f17 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.unshift(5); +>x.unshift(5) : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>5 : 5 + + x.unshift("hello"); +>x.unshift("hello") : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>"hello" : "hello" + + x.unshift(true); +>x.unshift(true) : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f18() { +>f18 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.unshift("hello"); +>x.unshift("hello") : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>"hello" : "hello" + + x[2] = true; +>x[2] = true : true +>x[2] : any +>x : any[] +>2 : 2 +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} diff --git a/tests/baselines/reference/controlFlowBinaryOrExpression.symbols b/tests/baselines/reference/controlFlowBinaryOrExpression.symbols index 217e11dc95d..5251973005f 100644 --- a/tests/baselines/reference/controlFlowBinaryOrExpression.symbols +++ b/tests/baselines/reference/controlFlowBinaryOrExpression.symbols @@ -64,25 +64,13 @@ if (isNodeList(sourceObj)) { >sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) sourceObj.length; ->sourceObj.length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27)) +>sourceObj.length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33)) >sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) ->length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27)) +>length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33)) } if (isHTMLCollection(sourceObj)) { >isHTMLCollection : Symbol(isHTMLCollection, Decl(controlFlowBinaryOrExpression.ts, 18, 67)) ->sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) - - sourceObj.length; ->sourceObj.length : Symbol(HTMLCollection.length, Decl(controlFlowBinaryOrExpression.ts, 14, 33)) ->sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) ->length : Symbol(HTMLCollection.length, Decl(controlFlowBinaryOrExpression.ts, 14, 33)) -} - -if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) { ->isNodeList : Symbol(isNodeList, Decl(controlFlowBinaryOrExpression.ts, 16, 1)) ->sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) ->isHTMLCollection : Symbol(isHTMLCollection, Decl(controlFlowBinaryOrExpression.ts, 18, 67)) >sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) sourceObj.length; @@ -91,3 +79,15 @@ if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) { >length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33)) } +if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) { +>isNodeList : Symbol(isNodeList, Decl(controlFlowBinaryOrExpression.ts, 16, 1)) +>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) +>isHTMLCollection : Symbol(isHTMLCollection, Decl(controlFlowBinaryOrExpression.ts, 18, 67)) +>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) + + sourceObj.length; +>sourceObj.length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27)) +>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3)) +>length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27)) +} + diff --git a/tests/baselines/reference/controlFlowBinaryOrExpression.types b/tests/baselines/reference/controlFlowBinaryOrExpression.types index 3634a322396..e843844ebf1 100644 --- a/tests/baselines/reference/controlFlowBinaryOrExpression.types +++ b/tests/baselines/reference/controlFlowBinaryOrExpression.types @@ -80,7 +80,7 @@ if (isNodeList(sourceObj)) { sourceObj.length; >sourceObj.length : number ->sourceObj : NodeList +>sourceObj : NodeList | HTMLCollection >length : number } @@ -91,7 +91,7 @@ if (isHTMLCollection(sourceObj)) { sourceObj.length; >sourceObj.length : number ->sourceObj : HTMLCollection +>sourceObj : NodeList | HTMLCollection >length : number } @@ -102,11 +102,11 @@ if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) { >sourceObj : NodeList | HTMLCollection | { a: string; } >isHTMLCollection(sourceObj) : boolean >isHTMLCollection : (sourceObj: any) => sourceObj is HTMLCollection ->sourceObj : HTMLCollection | { a: string; } +>sourceObj : { a: string; } sourceObj.length; >sourceObj.length : number ->sourceObj : NodeList | HTMLCollection +>sourceObj : NodeList >length : number } diff --git a/tests/baselines/reference/controlFlowCaching.errors.txt b/tests/baselines/reference/controlFlowCaching.errors.txt deleted file mode 100644 index 1086695313e..00000000000 --- a/tests/baselines/reference/controlFlowCaching.errors.txt +++ /dev/null @@ -1,128 +0,0 @@ -tests/cases/compiler/controlFlowCaching.ts(38,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(38,29): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(40,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(40,29): error TS2339: Property 'x' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(42,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(42,29): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(44,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(44,29): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(46,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(46,29): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(48,17): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(48,29): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(53,5): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(53,14): error TS2339: Property 'y' does not exist on type 'never'. -tests/cases/compiler/controlFlowCaching.ts(55,14): error TS2678: Type '"start"' is not comparable to type 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(58,14): error TS2678: Type '"end"' is not comparable to type 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(61,14): error TS2678: Type '"middle"' is not comparable to type 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(62,13): error TS2532: Object is possibly 'undefined'. -tests/cases/compiler/controlFlowCaching.ts(62,25): error TS2339: Property 'y' does not exist on type 'never'. - - -==== tests/cases/compiler/controlFlowCaching.ts (19 errors) ==== - - // Repro for #8401 - - function f(dim, offsets, arr, acommon, centerAnchorLimit, g, has, lin) { - var isRtl = this._isRtl(); // chart mirroring - // prepare variable - var o = this.opt, ta = this.chart.theme.axis, position = o.position, - leftBottom = position !== "rightOrTop", rotation = o.rotation % 360, - start, stop, titlePos, titleRotation = 0, titleOffset, axisVector, tickVector, anchorOffset, labelOffset, labelAlign, - labelGap = this.chart.theme.axis.tick.labelGap, - taFont = o.font || (ta.majorTick && ta.majorTick.font) || (ta.tick && ta.tick.font), - taTitleFont = o.titleFont || (ta.title && ta.title.font), - taFontColor = o.fontColor || (ta.majorTick && ta.majorTick.fontColor) || (ta.tick && ta.tick.fontColor) || "black", - taTitleFontColor = o.titleFontColor || (ta.title && ta.title.fontColor) || "black", - taTitleGap = (o.titleGap == 0) ? 0 : o.titleGap || (ta.title && ta.title.gap) || 15, - taTitleOrientation = o.titleOrientation || (ta.title && ta.title.orientation) || "axis", - taMajorTick = this.chart.theme.getTick("major", o), - taMinorTick = this.chart.theme.getTick("minor", o), - taMicroTick = this.chart.theme.getTick("micro", o), - - taStroke = "stroke" in o ? o.stroke : ta.stroke, - size = taFont ? g.normalizedLength(g.splitFontString(taFont).size) : 0, - cosr = Math.abs(Math.cos(rotation * Math.PI / 180)), - sinr = Math.abs(Math.sin(rotation * Math.PI / 180)), - tsize = taTitleFont ? g.normalizedLength(g.splitFontString(taTitleFont).size) : 0; - if (rotation < 0) { - rotation += 360; - } - var cachedLabelW = this._getMaxLabelSize(); - cachedLabelW = cachedLabelW && cachedLabelW.majLabelW; - titleOffset = size * cosr + (cachedLabelW || 0) * sinr + labelGap + Math.max(taMajorTick.length > 0 ? taMajorTick.length : 0, - taMinorTick.length > 0 ? taMinorTick.length : 0) + - tsize + taTitleGap; - axisVector = { x: isRtl ? -1 : 1, y: 0 }; // chart mirroring - switch (rotation) { - default: - if (rotation < (90 - centerAnchorLimit)) { - labelOffset.y = leftBottom ? size : 0; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - } else if (rotation < (90 + centerAnchorLimit)) { - labelOffset.x = -size * 0.4; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'x' does not exist on type 'never'. - } else if (rotation < 180) { - labelOffset.y = leftBottom ? 0 : -size; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - } else if (rotation < (270 - centerAnchorLimit)) { - labelOffset.y = leftBottom ? 0 : -size; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - } else if (rotation < (270 + centerAnchorLimit)) { - labelOffset.y = leftBottom ? size * 0.4 : 0; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - } else { - labelOffset.y = leftBottom ? size : 0; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - } - } - - titleRotation = (taTitleOrientation && taTitleOrientation == "away") ? 180 : 0; - titlePos.y = offsets.t - titleOffset + (titleRotation ? 0 : tsize); - ~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - switch (labelAlign) { - case "start": - ~~~~~~~ -!!! error TS2678: Type '"start"' is not comparable to type 'undefined'. - labelAlign = "end"; - break; - case "end": - ~~~~~ -!!! error TS2678: Type '"end"' is not comparable to type 'undefined'. - labelAlign = "start"; - break; - case "middle": - ~~~~~~~~ -!!! error TS2678: Type '"middle"' is not comparable to type 'undefined'. - labelOffset.y -= size; - ~~~~~~~~~~~ -!!! error TS2532: Object is possibly 'undefined'. - ~ -!!! error TS2339: Property 'y' does not exist on type 'never'. - break; - } - - let _ = rotation; - } - \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowLetVar.js b/tests/baselines/reference/controlFlowJavascript.js similarity index 63% rename from tests/baselines/reference/controlFlowLetVar.js rename to tests/baselines/reference/controlFlowJavascript.js index 24ad95259b1..66518a6567a 100644 --- a/tests/baselines/reference/controlFlowLetVar.js +++ b/tests/baselines/reference/controlFlowJavascript.js @@ -1,8 +1,8 @@ -//// [controlFlowLetVar.ts] +//// [controlFlowJavascript.js] -declare let cond: boolean; +let cond = true; -// CFA for 'let' with no type annotation and initializer +// CFA for 'let' and no initializer function f1() { let x; if (cond) { @@ -14,7 +14,7 @@ function f1() { const y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'undefined' initializer +// CFA for 'let' and 'undefined' initializer function f2() { let x = undefined; if (cond) { @@ -26,7 +26,7 @@ function f2() { const y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'null' initializer +// CFA for 'let' and 'null' initializer function f3() { let x = null; if (cond) { @@ -38,19 +38,7 @@ function f3() { const y = x; // string | number | null } -// No CFA for 'let' with with type annotation -function f4() { - let x: any; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - const y = x; // any -} - -// CFA for 'var' with no type annotation and initializer +// CFA for 'var' with no initializer function f5() { var x; if (cond) { @@ -62,7 +50,7 @@ function f5() { const y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'undefined' initializer +// CFA for 'var' with 'undefined' initializer function f6() { var x = undefined; if (cond) { @@ -74,7 +62,7 @@ function f6() { const y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'null' initializer +// CFA for 'var' with 'null' initializer function f7() { var x = null; if (cond) { @@ -86,18 +74,6 @@ function f7() { const y = x; // string | number | null } -// No CFA for 'var' with with type annotation -function f8() { - var x: any; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - const y = x; // any -} - // No CFA for captured outer variables function f9() { let x; @@ -126,10 +102,12 @@ function f10() { const f = () => { const z = x; // any }; -} +} -//// [controlFlowLetVar.js] -// CFA for 'let' with no type annotation and initializer + +//// [out.js] +var cond = true; +// CFA for 'let' and no initializer function f1() { var x; if (cond) { @@ -140,7 +118,7 @@ function f1() { } var y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'undefined' initializer +// CFA for 'let' and 'undefined' initializer function f2() { var x = undefined; if (cond) { @@ -151,7 +129,7 @@ function f2() { } var y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'null' initializer +// CFA for 'let' and 'null' initializer function f3() { var x = null; if (cond) { @@ -162,18 +140,7 @@ function f3() { } var y = x; // string | number | null } -// No CFA for 'let' with with type annotation -function f4() { - var x; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - var y = x; // any -} -// CFA for 'var' with no type annotation and initializer +// CFA for 'var' with no initializer function f5() { var x; if (cond) { @@ -184,7 +151,7 @@ function f5() { } var y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'undefined' initializer +// CFA for 'var' with 'undefined' initializer function f6() { var x = undefined; if (cond) { @@ -195,7 +162,7 @@ function f6() { } var y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'null' initializer +// CFA for 'var' with 'null' initializer function f7() { var x = null; if (cond) { @@ -206,17 +173,6 @@ function f7() { } var y = x; // string | number | null } -// No CFA for 'var' with with type annotation -function f8() { - var x; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - var y = x; // any -} // No CFA for captured outer variables function f9() { var x; diff --git a/tests/baselines/reference/controlFlowJavascript.symbols b/tests/baselines/reference/controlFlowJavascript.symbols new file mode 100644 index 00000000000..b3316de3b4e --- /dev/null +++ b/tests/baselines/reference/controlFlowJavascript.symbols @@ -0,0 +1,216 @@ +=== tests/cases/compiler/controlFlowJavascript.js === + +let cond = true; +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + +// CFA for 'let' and no initializer +function f1() { +>f1 : Symbol(f1, Decl(controlFlowJavascript.js, 1, 16)) + + let x; +>x : Symbol(x, Decl(controlFlowJavascript.js, 5, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 5, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 5, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 12, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 5, 7)) +} + +// CFA for 'let' and 'undefined' initializer +function f2() { +>f2 : Symbol(f2, Decl(controlFlowJavascript.js, 13, 1)) + + let x = undefined; +>x : Symbol(x, Decl(controlFlowJavascript.js, 17, 7)) +>undefined : Symbol(undefined) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 17, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 17, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 24, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 17, 7)) +} + +// CFA for 'let' and 'null' initializer +function f3() { +>f3 : Symbol(f3, Decl(controlFlowJavascript.js, 25, 1)) + + let x = null; +>x : Symbol(x, Decl(controlFlowJavascript.js, 29, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 29, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 29, 7)) + } + const y = x; // string | number | null +>y : Symbol(y, Decl(controlFlowJavascript.js, 36, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 29, 7)) +} + +// CFA for 'var' with no initializer +function f5() { +>f5 : Symbol(f5, Decl(controlFlowJavascript.js, 37, 1)) + + var x; +>x : Symbol(x, Decl(controlFlowJavascript.js, 41, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 41, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 41, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 48, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 41, 7)) +} + +// CFA for 'var' with 'undefined' initializer +function f6() { +>f6 : Symbol(f6, Decl(controlFlowJavascript.js, 49, 1)) + + var x = undefined; +>x : Symbol(x, Decl(controlFlowJavascript.js, 53, 7)) +>undefined : Symbol(undefined) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 53, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 53, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 60, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 53, 7)) +} + +// CFA for 'var' with 'null' initializer +function f7() { +>f7 : Symbol(f7, Decl(controlFlowJavascript.js, 61, 1)) + + var x = null; +>x : Symbol(x, Decl(controlFlowJavascript.js, 65, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 65, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 65, 7)) + } + const y = x; // string | number | null +>y : Symbol(y, Decl(controlFlowJavascript.js, 72, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 65, 7)) +} + +// No CFA for captured outer variables +function f9() { +>f9 : Symbol(f9, Decl(controlFlowJavascript.js, 73, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowJavascript.js, 77, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 77, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 77, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 84, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 77, 7)) + + function f() { +>f : Symbol(f, Decl(controlFlowJavascript.js, 84, 16)) + + const z = x; // any +>z : Symbol(z, Decl(controlFlowJavascript.js, 86, 13)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 77, 7)) + } +} + +// No CFA for captured outer variables +function f10() { +>f10 : Symbol(f10, Decl(controlFlowJavascript.js, 88, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowJavascript.js, 92, 7)) + + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = 1; +>x : Symbol(x, Decl(controlFlowJavascript.js, 92, 7)) + } + if (cond) { +>cond : Symbol(cond, Decl(controlFlowJavascript.js, 1, 3)) + + x = "hello"; +>x : Symbol(x, Decl(controlFlowJavascript.js, 92, 7)) + } + const y = x; // string | number | undefined +>y : Symbol(y, Decl(controlFlowJavascript.js, 99, 9)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 92, 7)) + + const f = () => { +>f : Symbol(f, Decl(controlFlowJavascript.js, 100, 9)) + + const z = x; // any +>z : Symbol(z, Decl(controlFlowJavascript.js, 101, 13)) +>x : Symbol(x, Decl(controlFlowJavascript.js, 92, 7)) + + }; +} + diff --git a/tests/baselines/reference/controlFlowLetVar.types b/tests/baselines/reference/controlFlowJavascript.types similarity index 59% rename from tests/baselines/reference/controlFlowLetVar.types rename to tests/baselines/reference/controlFlowJavascript.types index 09f0ea83488..0b88c62cb78 100644 --- a/tests/baselines/reference/controlFlowLetVar.types +++ b/tests/baselines/reference/controlFlowJavascript.types @@ -1,9 +1,10 @@ -=== tests/cases/compiler/controlFlowLetVar.ts === +=== tests/cases/compiler/controlFlowJavascript.js === -declare let cond: boolean; +let cond = true; >cond : boolean +>true : true -// CFA for 'let' with no type annotation and initializer +// CFA for 'let' and no initializer function f1() { >f1 : () => void @@ -27,11 +28,11 @@ function f1() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number } -// CFA for 'let' with no type annotation and 'undefined' initializer +// CFA for 'let' and 'undefined' initializer function f2() { >f2 : () => void @@ -56,11 +57,11 @@ function f2() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number } -// CFA for 'let' with no type annotation and 'null' initializer +// CFA for 'let' and 'null' initializer function f3() { >f3 : () => void @@ -85,39 +86,11 @@ function f3() { >"hello" : "hello" } const y = x; // string | number | null ->y : string | number | null ->x : string | number | null +>y : string | number +>x : string | number } -// No CFA for 'let' with with type annotation -function f4() { ->f4 : () => void - - let x: any; ->x : any - - if (cond) { ->cond : boolean - - x = 1; ->x = 1 : 1 ->x : any ->1 : 1 - } - if (cond) { ->cond : boolean - - x = "hello"; ->x = "hello" : "hello" ->x : any ->"hello" : "hello" - } - const y = x; // any ->y : any ->x : any -} - -// CFA for 'var' with no type annotation and initializer +// CFA for 'var' with no initializer function f5() { >f5 : () => void @@ -141,11 +114,11 @@ function f5() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number } -// CFA for 'var' with no type annotation and 'undefined' initializer +// CFA for 'var' with 'undefined' initializer function f6() { >f6 : () => void @@ -170,11 +143,11 @@ function f6() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number } -// CFA for 'var' with no type annotation and 'null' initializer +// CFA for 'var' with 'null' initializer function f7() { >f7 : () => void @@ -199,36 +172,8 @@ function f7() { >"hello" : "hello" } const y = x; // string | number | null ->y : string | number | null ->x : string | number | null -} - -// No CFA for 'var' with with type annotation -function f8() { ->f8 : () => void - - var x: any; ->x : any - - if (cond) { ->cond : boolean - - x = 1; ->x = 1 : 1 ->x : any ->1 : 1 - } - if (cond) { ->cond : boolean - - x = "hello"; ->x = "hello" : "hello" ->x : any ->"hello" : "hello" - } - const y = x; // any ->y : any ->x : any +>y : string | number +>x : string | number } // No CFA for captured outer variables @@ -255,8 +200,8 @@ function f9() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number function f() { >f : () => void @@ -291,8 +236,8 @@ function f10() { >"hello" : "hello" } const y = x; // string | number | undefined ->y : string | number | undefined ->x : string | number | undefined +>y : string | number +>x : string | number const f = () => { >f : () => void @@ -304,3 +249,4 @@ function f10() { }; } + diff --git a/tests/baselines/reference/controlFlowLetVar.symbols b/tests/baselines/reference/controlFlowLetVar.symbols deleted file mode 100644 index f58edd781b7..00000000000 --- a/tests/baselines/reference/controlFlowLetVar.symbols +++ /dev/null @@ -1,263 +0,0 @@ -=== tests/cases/compiler/controlFlowLetVar.ts === - -declare let cond: boolean; ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - -// CFA for 'let' with no type annotation and initializer -function f1() { ->f1 : Symbol(f1, Decl(controlFlowLetVar.ts, 1, 26)) - - let x; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 5, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 5, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 5, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 12, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 5, 7)) -} - -// CFA for 'let' with no type annotation and 'undefined' initializer -function f2() { ->f2 : Symbol(f2, Decl(controlFlowLetVar.ts, 13, 1)) - - let x = undefined; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 17, 7)) ->undefined : Symbol(undefined) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 17, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 17, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 24, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 17, 7)) -} - -// CFA for 'let' with no type annotation and 'null' initializer -function f3() { ->f3 : Symbol(f3, Decl(controlFlowLetVar.ts, 25, 1)) - - let x = null; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 29, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 29, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 29, 7)) - } - const y = x; // string | number | null ->y : Symbol(y, Decl(controlFlowLetVar.ts, 36, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 29, 7)) -} - -// No CFA for 'let' with with type annotation -function f4() { ->f4 : Symbol(f4, Decl(controlFlowLetVar.ts, 37, 1)) - - let x: any; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 41, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 41, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 41, 7)) - } - const y = x; // any ->y : Symbol(y, Decl(controlFlowLetVar.ts, 48, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 41, 7)) -} - -// CFA for 'var' with no type annotation and initializer -function f5() { ->f5 : Symbol(f5, Decl(controlFlowLetVar.ts, 49, 1)) - - var x; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 53, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 53, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 53, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 60, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 53, 7)) -} - -// CFA for 'var' with no type annotation and 'undefined' initializer -function f6() { ->f6 : Symbol(f6, Decl(controlFlowLetVar.ts, 61, 1)) - - var x = undefined; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 65, 7)) ->undefined : Symbol(undefined) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 65, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 65, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 72, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 65, 7)) -} - -// CFA for 'var' with no type annotation and 'null' initializer -function f7() { ->f7 : Symbol(f7, Decl(controlFlowLetVar.ts, 73, 1)) - - var x = null; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 77, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 77, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 77, 7)) - } - const y = x; // string | number | null ->y : Symbol(y, Decl(controlFlowLetVar.ts, 84, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 77, 7)) -} - -// No CFA for 'var' with with type annotation -function f8() { ->f8 : Symbol(f8, Decl(controlFlowLetVar.ts, 85, 1)) - - var x: any; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 89, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 89, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 89, 7)) - } - const y = x; // any ->y : Symbol(y, Decl(controlFlowLetVar.ts, 96, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 89, 7)) -} - -// No CFA for captured outer variables -function f9() { ->f9 : Symbol(f9, Decl(controlFlowLetVar.ts, 97, 1)) - - let x; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 101, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 101, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 101, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 108, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 101, 7)) - - function f() { ->f : Symbol(f, Decl(controlFlowLetVar.ts, 108, 16)) - - const z = x; // any ->z : Symbol(z, Decl(controlFlowLetVar.ts, 110, 13)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 101, 7)) - } -} - -// No CFA for captured outer variables -function f10() { ->f10 : Symbol(f10, Decl(controlFlowLetVar.ts, 112, 1)) - - let x; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 116, 7)) - - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = 1; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 116, 7)) - } - if (cond) { ->cond : Symbol(cond, Decl(controlFlowLetVar.ts, 1, 11)) - - x = "hello"; ->x : Symbol(x, Decl(controlFlowLetVar.ts, 116, 7)) - } - const y = x; // string | number | undefined ->y : Symbol(y, Decl(controlFlowLetVar.ts, 123, 9)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 116, 7)) - - const f = () => { ->f : Symbol(f, Decl(controlFlowLetVar.ts, 124, 9)) - - const z = x; // any ->z : Symbol(z, Decl(controlFlowLetVar.ts, 125, 13)) ->x : Symbol(x, Decl(controlFlowLetVar.ts, 116, 7)) - - }; -} diff --git a/tests/baselines/reference/controlFlowSelfReferentialLoop.errors.txt b/tests/baselines/reference/controlFlowSelfReferentialLoop.errors.txt new file mode 100644 index 00000000000..deef6403761 --- /dev/null +++ b/tests/baselines/reference/controlFlowSelfReferentialLoop.errors.txt @@ -0,0 +1,188 @@ +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,17): error TS7006: Parameter 'a' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,19): error TS7006: Parameter 'b' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,21): error TS7006: Parameter 'c' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,23): error TS7006: Parameter 'd' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,25): error TS7006: Parameter 'x' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,27): error TS7006: Parameter 's' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(6,29): error TS7006: Parameter 'ac' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,17): error TS7006: Parameter 'a' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,19): error TS7006: Parameter 'b' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,21): error TS7006: Parameter 'c' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,23): error TS7006: Parameter 'd' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,25): error TS7006: Parameter 'x' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,27): error TS7006: Parameter 's' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(10,29): error TS7006: Parameter 'ac' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,17): error TS7006: Parameter 'a' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,19): error TS7006: Parameter 'b' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,21): error TS7006: Parameter 'c' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,23): error TS7006: Parameter 'd' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,25): error TS7006: Parameter 'x' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,27): error TS7006: Parameter 's' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(14,29): error TS7006: Parameter 'ac' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,17): error TS7006: Parameter 'a' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,19): error TS7006: Parameter 'b' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,21): error TS7006: Parameter 'c' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,23): error TS7006: Parameter 'd' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,25): error TS7006: Parameter 'x' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,27): error TS7006: Parameter 's' implicitly has an 'any' type. +tests/cases/compiler/controlFlowSelfReferentialLoop.ts(18,29): error TS7006: Parameter 'ac' implicitly has an 'any' type. + + +==== tests/cases/compiler/controlFlowSelfReferentialLoop.ts (28 errors) ==== + + // Repro from #12319 + + function md5(string:string): void { + + function FF(a,b,c,d,x,s,ac) { + ~ +!!! error TS7006: Parameter 'a' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'b' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'c' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'd' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'x' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 's' implicitly has an 'any' type. + ~~ +!!! error TS7006: Parameter 'ac' implicitly has an 'any' type. + return 0; + }; + + function GG(a,b,c,d,x,s,ac) { + ~ +!!! error TS7006: Parameter 'a' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'b' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'c' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'd' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'x' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 's' implicitly has an 'any' type. + ~~ +!!! error TS7006: Parameter 'ac' implicitly has an 'any' type. + return 0; + }; + + function HH(a,b,c,d,x,s,ac) { + ~ +!!! error TS7006: Parameter 'a' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'b' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'c' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'd' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'x' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 's' implicitly has an 'any' type. + ~~ +!!! error TS7006: Parameter 'ac' implicitly has an 'any' type. + return 0; + }; + + function II(a,b,c,d,x,s,ac) { + ~ +!!! error TS7006: Parameter 'a' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'b' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'c' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'd' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 'x' implicitly has an 'any' type. + ~ +!!! error TS7006: Parameter 's' implicitly has an 'any' type. + ~~ +!!! error TS7006: Parameter 'ac' implicitly has an 'any' type. + return 0; + }; + + var x=Array(); + var k,AA,BB,CC,DD,a,b,c,d; + var S11=7, S12=12, S13=17, S14=22; + var S21=5, S22=9 , S23=14, S24=20; + var S31=4, S32=11, S33=16, S34=23; + var S41=6, S42=10, S43=15, S44=21; + + x = [1]; + + a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; + + for (k=0;k { return [10]; } function f1() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } function f2(x) { } diff --git a/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types b/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types index 6d9c17b4ab9..b1a85f3fc30 100644 --- a/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types +++ b/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types @@ -23,7 +23,7 @@ function foo(a: string): string | number { return a.length; >a.length : number ->a : string +>a : "hello" >length : number } diff --git a/tests/baselines/reference/declFileTypeofInAnonymousType.js b/tests/baselines/reference/declFileTypeofInAnonymousType.js index 68db3d120cd..656cd49ebfa 100644 --- a/tests/baselines/reference/declFileTypeofInAnonymousType.js +++ b/tests/baselines/reference/declFileTypeofInAnonymousType.js @@ -31,12 +31,12 @@ var m1; return c; }()); m1.c = c; + var e; (function (e) { e[e["weekday"] = 0] = "weekday"; e[e["weekend"] = 1] = "weekend"; e[e["holiday"] = 2] = "holiday"; - })(m1.e || (m1.e = {})); - var e = m1.e; + })(e = m1.e || (m1.e = {})); })(m1 || (m1 = {})); var a; var b = { diff --git a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js index a3cdee31222..941bb383f81 100644 --- a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js +++ b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js @@ -13,13 +13,13 @@ function foo2(...rest: any[]) { function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } function foo2() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } diff --git a/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt b/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt new file mode 100644 index 00000000000..ffbfd25fa94 --- /dev/null +++ b/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(3,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(3,13): error TS2304: Cannot find name 'TypeNotFound'. +tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(3,13): error TS4092: Parameter 'index' of index signature from exported interface has or is using private name 'TypeNotFound'. + + +==== tests/cases/compiler/declarationEmitIndexTypeNotFound.ts (3 errors) ==== + + export interface Test { + [index: TypeNotFound]: any; + ~~~~~ +!!! error TS1023: An index signature parameter type must be 'string' or 'number'. + ~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'TypeNotFound'. + ~~~~~~~~~~~~ +!!! error TS4092: Parameter 'index' of index signature from exported interface has or is using private name 'TypeNotFound'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitIndexTypeNotFound.js b/tests/baselines/reference/declarationEmitIndexTypeNotFound.js new file mode 100644 index 00000000000..22100e5cb72 --- /dev/null +++ b/tests/baselines/reference/declarationEmitIndexTypeNotFound.js @@ -0,0 +1,9 @@ +//// [declarationEmitIndexTypeNotFound.ts] + +export interface Test { + [index: TypeNotFound]: any; +} + + +//// [declarationEmitIndexTypeNotFound.js] +"use strict"; diff --git a/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.errors.txt b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.errors.txt new file mode 100644 index 00000000000..7dc3a70fdc7 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.errors.txt @@ -0,0 +1,9 @@ +tests/cases/compiler/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.ts(3,25): error TS2499: An interface can only extend an identifier/qualified-name with optional type arguments. + + +==== tests/cases/compiler/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.ts (1 errors) ==== + + class A { } + interface Class extends (typeof A) { } + ~~~~~~~~~~ +!!! error TS2499: An interface can only extend an identifier/qualified-name with optional type arguments. \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.js b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.js new file mode 100644 index 00000000000..ef2d2e479b0 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.js @@ -0,0 +1,18 @@ +//// [declarationEmitInterfaceWithNonEntityNameExpressionHeritage.ts] + +class A { } +interface Class extends (typeof A) { } + +//// [declarationEmitInterfaceWithNonEntityNameExpressionHeritage.js] +var A = (function () { + function A() { + } + return A; +}()); + + +//// [declarationEmitInterfaceWithNonEntityNameExpressionHeritage.d.ts] +declare class A { +} +interface Class { +} diff --git a/tests/baselines/reference/declarationEmitNameConflicts2.js b/tests/baselines/reference/declarationEmitNameConflicts2.js index 41dcec4690f..05529fbf5be 100644 --- a/tests/baselines/reference/declarationEmitNameConflicts2.js +++ b/tests/baselines/reference/declarationEmitNameConflicts2.js @@ -33,9 +33,9 @@ var X; var M; (function (M) { })(M = base.M || (base.M = {})); + var E; (function (E) { - })(base.E || (base.E = {})); - var E = base.E; + })(E = base.E || (base.E = {})); })(base = Y.base || (Y.base = {})); })(Y = X.Y || (X.Y = {})); })(X || (X = {})); diff --git a/tests/baselines/reference/declarationEmitNameConflicts3.js b/tests/baselines/reference/declarationEmitNameConflicts3.js index b0a87e64483..ffcfead83bf 100644 --- a/tests/baselines/reference/declarationEmitNameConflicts3.js +++ b/tests/baselines/reference/declarationEmitNameConflicts3.js @@ -68,10 +68,10 @@ var M; return E; }(C)); P.E = E; + var D; (function (D) { D[D["f"] = 0] = "f"; - })(P.D || (P.D = {})); - var D = P.D; + })(D = P.D || (P.D = {})); P.w = M.D.f; // error, should be typeof M.D.f P.x = M.C.f; // error, should be typeof M.C.f P.x = M.E.f; // error, should be typeof M.E.f diff --git a/tests/baselines/reference/declarationEmitPromise.js b/tests/baselines/reference/declarationEmitPromise.js index e6f3f922b46..9e820a789c9 100644 --- a/tests/baselines/reference/declarationEmitPromise.js +++ b/tests/baselines/reference/declarationEmitPromise.js @@ -29,7 +29,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class bluebird { diff --git a/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.errors.txt b/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.errors.txt new file mode 100644 index 00000000000..af0bcad47fa --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.ts(2,18): error TS2304: Cannot find name 'Unknown'. +tests/cases/compiler/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.ts(2,18): error TS4083: Type parameter 'T' of exported type alias has or is using private name 'Unknown'. + + +==== tests/cases/compiler/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.ts (2 errors) ==== + + type A = {} + ~~~~~~~ +!!! error TS2304: Cannot find name 'Unknown'. + ~~~~~~~ +!!! error TS4083: Type parameter 'T' of exported type alias has or is using private name 'Unknown'. \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.js b/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.js new file mode 100644 index 00000000000..eedcc6eccb7 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.js @@ -0,0 +1,5 @@ +//// [declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.ts] + +type A = {} + +//// [declarationEmitTypeAliasTypeParameterExtendingUnknownSymbol.js] diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.js index c41c4690391..6079de35964 100644 --- a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.js +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.js @@ -12,4 +12,4 @@ exports.y = function (x) { return 1; }; //// [declarationEmitTypeAliasWithTypeParameters1.d.ts] export declare type Bar = () => [X, Y]; export declare type Foo = Bar; -export declare const y: (x: () => [any, string]) => number; +export declare const y: (x: Bar) => number; diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.types b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.types index 3ff9f9bde1d..a8b0f146f8e 100644 --- a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.types +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters1.types @@ -8,15 +8,15 @@ export type Bar = () => [X, Y]; >Y : Y export type Foo = Bar; ->Foo : () => [any, Y] +>Foo : Bar >Y : Y >Bar : Bar >Y : Y export const y = (x: Foo) => 1 ->y : (x: () => [any, string]) => number ->(x: Foo) => 1 : (x: () => [any, string]) => number ->x : () => [any, string] ->Foo : () => [any, Y] +>y : (x: Bar) => number +>(x: Foo) => 1 : (x: Bar) => number +>x : Bar +>Foo : Bar >1 : 1 diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.js new file mode 100644 index 00000000000..d5bf31bd755 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.js @@ -0,0 +1,17 @@ +//// [declarationEmitTypeAliasWithTypeParameters2.ts] + +export type Bar = () => [X, Y, Z]; +export type Baz = Bar; +export type Baa = Baz; +export const y = (x: Baa) => 1 + +//// [declarationEmitTypeAliasWithTypeParameters2.js] +"use strict"; +exports.y = function (x) { return 1; }; + + +//// [declarationEmitTypeAliasWithTypeParameters2.d.ts] +export declare type Bar = () => [X, Y, Z]; +export declare type Baz = Bar; +export declare type Baa = Baz; +export declare const y: (x: Bar) => number; diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.symbols b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.symbols new file mode 100644 index 00000000000..cc13e9fd30b --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.symbols @@ -0,0 +1,30 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters2.ts === + +export type Bar = () => [X, Y, Z]; +>Bar : Symbol(Bar, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 0, 0)) +>X : Symbol(X, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 16)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 18)) +>Z : Symbol(Z, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 21)) +>X : Symbol(X, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 16)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 18)) +>Z : Symbol(Z, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 21)) + +export type Baz = Bar; +>Baz : Symbol(Baz, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 43)) +>M : Symbol(M, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 16)) +>N : Symbol(N, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 18)) +>Bar : Symbol(Bar, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 0, 0)) +>M : Symbol(M, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 16)) +>N : Symbol(N, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 18)) + +export type Baa = Baz; +>Baa : Symbol(Baa, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 42)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 3, 16)) +>Baz : Symbol(Baz, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 1, 43)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 3, 16)) + +export const y = (x: Baa) => 1 +>y : Symbol(y, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 4, 12)) +>x : Symbol(x, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 4, 18)) +>Baa : Symbol(Baa, Decl(declarationEmitTypeAliasWithTypeParameters2.ts, 2, 42)) + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.types b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.types new file mode 100644 index 00000000000..74becc49765 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters2.types @@ -0,0 +1,32 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters2.ts === + +export type Bar = () => [X, Y, Z]; +>Bar : Bar +>X : X +>Y : Y +>Z : Z +>X : X +>Y : Y +>Z : Z + +export type Baz = Bar; +>Baz : Bar +>M : M +>N : N +>Bar : Bar +>M : M +>N : N + +export type Baa = Baz; +>Baa : Bar +>Y : Y +>Baz : Bar +>Y : Y + +export const y = (x: Baa) => 1 +>y : (x: Bar) => number +>(x: Baa) => 1 : (x: Bar) => number +>x : Bar +>Baa : Bar +>1 : 1 + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.js new file mode 100644 index 00000000000..9e2a366a685 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.js @@ -0,0 +1,21 @@ +//// [declarationEmitTypeAliasWithTypeParameters3.ts] + +type Foo = { + foo(): Foo +}; +function bar() { + return {} as Foo; +} + + +//// [declarationEmitTypeAliasWithTypeParameters3.js] +function bar() { + return {}; +} + + +//// [declarationEmitTypeAliasWithTypeParameters3.d.ts] +declare type Foo = { + foo(): Foo; +}; +declare function bar(): Foo; diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.symbols b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.symbols new file mode 100644 index 00000000000..a18b1372cf1 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters3.ts === + +type Foo = { +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 1, 9)) + + foo(): Foo +>foo : Symbol(foo, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 1, 15)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 2, 8)) +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 0, 0)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 2, 8)) + +}; +function bar() { +>bar : Symbol(bar, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 3, 2)) + + return {} as Foo; +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters3.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.types b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.types new file mode 100644 index 00000000000..1b2ff140178 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters3.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters3.ts === + +type Foo = { +>Foo : Foo +>T : T + + foo(): Foo +>foo : () => Foo +>U : U +>Foo : Foo +>U : U + +}; +function bar() { +>bar : () => Foo + + return {} as Foo; +>{} as Foo : Foo +>{} : {} +>Foo : Foo +} + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.js new file mode 100644 index 00000000000..26908d915e0 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.js @@ -0,0 +1,24 @@ +//// [declarationEmitTypeAliasWithTypeParameters4.ts] + +type Foo = { + foo(): Foo +}; +type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} + + +//// [declarationEmitTypeAliasWithTypeParameters4.js] +function foo() { + return {}; +} + + +//// [declarationEmitTypeAliasWithTypeParameters4.d.ts] +declare type Foo = { + foo(): Foo; +}; +declare type SubFoo = Foo; +declare function foo(): Foo; diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.symbols b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.symbols new file mode 100644 index 00000000000..de73f544645 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.symbols @@ -0,0 +1,29 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters4.ts === + +type Foo = { +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 1, 9)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 1, 11)) + + foo(): Foo +>foo : Symbol(foo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 1, 18)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 2, 8)) +>J : Symbol(J, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 2, 10)) +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 0, 0)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 2, 8)) +>J : Symbol(J, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 2, 10)) + +}; +type SubFoo = Foo; +>SubFoo : Symbol(SubFoo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 3, 2)) +>R : Symbol(R, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 4, 12)) +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 0, 0)) +>R : Symbol(R, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 4, 12)) + +function foo() { +>foo : Symbol(foo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 4, 32)) + + return {} as SubFoo; +>SubFoo : Symbol(SubFoo, Decl(declarationEmitTypeAliasWithTypeParameters4.ts, 3, 2)) +} + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.types b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.types new file mode 100644 index 00000000000..c545ac6bb05 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters4.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters4.ts === + +type Foo = { +>Foo : Foo +>T : T +>Y : Y + + foo(): Foo +>foo : () => Foo +>U : U +>J : J +>Foo : Foo +>U : U +>J : J + +}; +type SubFoo = Foo; +>SubFoo : Foo +>R : R +>Foo : Foo +>R : R + +function foo() { +>foo : () => Foo + + return {} as SubFoo; +>{} as SubFoo : Foo +>{} : {} +>SubFoo : Foo +} + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.errors.txt b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.errors.txt new file mode 100644 index 00000000000..7f683dcc7b7 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters5.ts(5,25): error TS4081: Exported type alias 'SubFoo' has or is using private name 'Foo'. + + +==== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters5.ts (1 errors) ==== + + type Foo = { + foo(): Foo + }; + export type SubFoo = Foo; + ~~~ +!!! error TS4081: Exported type alias 'SubFoo' has or is using private name 'Foo'. + + function foo() { + return {} as SubFoo; + } + \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.js new file mode 100644 index 00000000000..2f4fff7d72c --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters5.js @@ -0,0 +1,17 @@ +//// [declarationEmitTypeAliasWithTypeParameters5.ts] + +type Foo = { + foo(): Foo +}; +export type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} + + +//// [declarationEmitTypeAliasWithTypeParameters5.js] +"use strict"; +function foo() { + return {}; +} diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.js b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.js new file mode 100644 index 00000000000..c8001446e3e --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.js @@ -0,0 +1,24 @@ +//// [declarationEmitTypeAliasWithTypeParameters6.ts] + +type Foo = { + foo(): Foo +}; +type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} + + +//// [declarationEmitTypeAliasWithTypeParameters6.js] +function foo() { + return {}; +} + + +//// [declarationEmitTypeAliasWithTypeParameters6.d.ts] +declare type Foo = { + foo(): Foo; +}; +declare type SubFoo = Foo; +declare function foo(): Foo; diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.symbols b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.symbols new file mode 100644 index 00000000000..ec29989f078 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters6.ts === + +type Foo = { +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 1, 9)) +>Y : Symbol(Y, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 1, 11)) + + foo(): Foo +>foo : Symbol(foo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 1, 18)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 2, 8)) +>J : Symbol(J, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 2, 10)) +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 0, 0)) +>U : Symbol(U, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 2, 8)) +>J : Symbol(J, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 2, 10)) + +}; +type SubFoo = Foo; +>SubFoo : Symbol(SubFoo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 3, 2)) +>R : Symbol(R, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 4, 12)) +>S : Symbol(S, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 4, 14)) +>Foo : Symbol(Foo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 0, 0)) +>S : Symbol(S, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 4, 14)) +>R : Symbol(R, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 4, 12)) + +function foo() { +>foo : Symbol(foo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 4, 30)) + + return {} as SubFoo; +>SubFoo : Symbol(SubFoo, Decl(declarationEmitTypeAliasWithTypeParameters6.ts, 3, 2)) +} + diff --git a/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.types b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.types new file mode 100644 index 00000000000..b02ccbc2be7 --- /dev/null +++ b/tests/baselines/reference/declarationEmitTypeAliasWithTypeParameters6.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters6.ts === + +type Foo = { +>Foo : Foo +>T : T +>Y : Y + + foo(): Foo +>foo : () => Foo +>U : U +>J : J +>Foo : Foo +>U : U +>J : J + +}; +type SubFoo = Foo; +>SubFoo : Foo +>R : R +>S : S +>Foo : Foo +>S : S +>R : R + +function foo() { +>foo : () => Foo + + return {} as SubFoo; +>{} as SubFoo : Foo +>{} : {} +>SubFoo : Foo +} + diff --git a/tests/baselines/reference/declarationFileOverwriteError.errors.txt b/tests/baselines/reference/declarationFileOverwriteError.errors.txt index 1974976dee1..211469778b1 100644 --- a/tests/baselines/reference/declarationFileOverwriteError.errors.txt +++ b/tests/baselines/reference/declarationFileOverwriteError.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.d.ts' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/a.d.ts' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.d.ts (0 errors) ==== declare class c { diff --git a/tests/baselines/reference/declarationFileOverwriteErrorWithOut.errors.txt b/tests/baselines/reference/declarationFileOverwriteErrorWithOut.errors.txt index 658465de9c2..ea4a93b3b12 100644 --- a/tests/baselines/reference/declarationFileOverwriteErrorWithOut.errors.txt +++ b/tests/baselines/reference/declarationFileOverwriteErrorWithOut.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/out.d.ts' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/out.d.ts' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/out.d.ts (0 errors) ==== declare class c { diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences1.js b/tests/baselines/reference/declarationFilesWithTypeReferences1.js new file mode 100644 index 00000000000..b4695f28f13 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences1.js @@ -0,0 +1,22 @@ +//// [tests/cases/compiler/declarationFilesWithTypeReferences1.ts] //// + +//// [index.d.ts] + +interface Error { + stack2: string; +} + +//// [app.ts] + +function foo(): Error { + return undefined; +} + +//// [app.js] +function foo() { + return undefined; +} + + +//// [app.d.ts] +declare function foo(): Error; diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences1.symbols b/tests/baselines/reference/declarationFilesWithTypeReferences1.symbols new file mode 100644 index 00000000000..3d3df3c1622 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences1.symbols @@ -0,0 +1,18 @@ +=== /node_modules/@types/node/index.d.ts === + +interface Error { +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(index.d.ts, 0, 0)) + + stack2: string; +>stack2 : Symbol(Error.stack2, Decl(index.d.ts, 1, 17)) +} + +=== /app.ts === + +function foo(): Error { +>foo : Symbol(foo, Decl(app.ts, 0, 0)) +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(index.d.ts, 0, 0)) + + return undefined; +>undefined : Symbol(undefined) +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences1.types b/tests/baselines/reference/declarationFilesWithTypeReferences1.types new file mode 100644 index 00000000000..7837b7b3a6c --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences1.types @@ -0,0 +1,18 @@ +=== /node_modules/@types/node/index.d.ts === + +interface Error { +>Error : Error + + stack2: string; +>stack2 : string +} + +=== /app.ts === + +function foo(): Error { +>foo : () => Error +>Error : Error + + return undefined; +>undefined : undefined +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences2.js b/tests/baselines/reference/declarationFilesWithTypeReferences2.js new file mode 100644 index 00000000000..b85dcc45107 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences2.js @@ -0,0 +1,23 @@ +//// [tests/cases/compiler/declarationFilesWithTypeReferences2.ts] //// + +//// [index.d.ts] + +interface Error2 { + stack2: string; +} + +//// [app.ts] + +function foo(): Error2 { + return undefined; +} + +//// [app.js] +function foo() { + return undefined; +} + + +//// [app.d.ts] +/// +declare function foo(): Error2; diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences2.symbols b/tests/baselines/reference/declarationFilesWithTypeReferences2.symbols new file mode 100644 index 00000000000..dc6d8a3a6de --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences2.symbols @@ -0,0 +1,18 @@ +=== /node_modules/@types/node/index.d.ts === + +interface Error2 { +>Error2 : Symbol(Error2, Decl(index.d.ts, 0, 0)) + + stack2: string; +>stack2 : Symbol(Error2.stack2, Decl(index.d.ts, 1, 18)) +} + +=== /app.ts === + +function foo(): Error2 { +>foo : Symbol(foo, Decl(app.ts, 0, 0)) +>Error2 : Symbol(Error2, Decl(index.d.ts, 0, 0)) + + return undefined; +>undefined : Symbol(undefined) +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences2.types b/tests/baselines/reference/declarationFilesWithTypeReferences2.types new file mode 100644 index 00000000000..c56f4ba6a67 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences2.types @@ -0,0 +1,18 @@ +=== /node_modules/@types/node/index.d.ts === + +interface Error2 { +>Error2 : Error2 + + stack2: string; +>stack2 : string +} + +=== /app.ts === + +function foo(): Error2 { +>foo : () => Error2 +>Error2 : Error2 + + return undefined; +>undefined : undefined +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences3.js b/tests/baselines/reference/declarationFilesWithTypeReferences3.js new file mode 100644 index 00000000000..3a18859c610 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences3.js @@ -0,0 +1,24 @@ +//// [tests/cases/compiler/declarationFilesWithTypeReferences3.ts] //// + +//// [index.d.ts] + +interface Error2 { + stack2: string; +} + +//// [app.ts] +/// +function foo(): Error2 { + return undefined; +} + +//// [app.js] +/// +function foo() { + return undefined; +} + + +//// [app.d.ts] +/// +declare function foo(): Error2; diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences3.symbols b/tests/baselines/reference/declarationFilesWithTypeReferences3.symbols new file mode 100644 index 00000000000..78335f988e9 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences3.symbols @@ -0,0 +1,18 @@ +=== /a/node_modules/@types/node/index.d.ts === + +interface Error2 { +>Error2 : Symbol(Error2, Decl(index.d.ts, 0, 0)) + + stack2: string; +>stack2 : Symbol(Error2.stack2, Decl(index.d.ts, 1, 18)) +} + +=== /a/app.ts === +/// +function foo(): Error2 { +>foo : Symbol(foo, Decl(app.ts, 0, 0)) +>Error2 : Symbol(Error2, Decl(index.d.ts, 0, 0)) + + return undefined; +>undefined : Symbol(undefined) +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences3.types b/tests/baselines/reference/declarationFilesWithTypeReferences3.types new file mode 100644 index 00000000000..9ac0105890a --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences3.types @@ -0,0 +1,18 @@ +=== /a/node_modules/@types/node/index.d.ts === + +interface Error2 { +>Error2 : Error2 + + stack2: string; +>stack2 : string +} + +=== /a/app.ts === +/// +function foo(): Error2 { +>foo : () => Error2 +>Error2 : Error2 + + return undefined; +>undefined : undefined +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences4.js b/tests/baselines/reference/declarationFilesWithTypeReferences4.js new file mode 100644 index 00000000000..b45860be9bb --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences4.js @@ -0,0 +1,23 @@ +//// [tests/cases/compiler/declarationFilesWithTypeReferences4.ts] //// + +//// [index.d.ts] + +interface Error { + stack2: string; +} + +//// [app.ts] +/// +function foo(): Error { + return undefined; +} + +//// [app.js] +/// +function foo() { + return undefined; +} + + +//// [app.d.ts] +declare function foo(): Error; diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences4.symbols b/tests/baselines/reference/declarationFilesWithTypeReferences4.symbols new file mode 100644 index 00000000000..216bd2a6a1c --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences4.symbols @@ -0,0 +1,18 @@ +=== /a/node_modules/@types/node/index.d.ts === + +interface Error { +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(index.d.ts, 0, 0)) + + stack2: string; +>stack2 : Symbol(Error.stack2, Decl(index.d.ts, 1, 17)) +} + +=== /a/app.ts === +/// +function foo(): Error { +>foo : Symbol(foo, Decl(app.ts, 0, 0)) +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(index.d.ts, 0, 0)) + + return undefined; +>undefined : Symbol(undefined) +} diff --git a/tests/baselines/reference/declarationFilesWithTypeReferences4.types b/tests/baselines/reference/declarationFilesWithTypeReferences4.types new file mode 100644 index 00000000000..0ae603716b1 --- /dev/null +++ b/tests/baselines/reference/declarationFilesWithTypeReferences4.types @@ -0,0 +1,18 @@ +=== /a/node_modules/@types/node/index.d.ts === + +interface Error { +>Error : Error + + stack2: string; +>stack2 : string +} + +=== /a/app.ts === +/// +function foo(): Error { +>foo : () => Error +>Error : Error + + return undefined; +>undefined : undefined +} diff --git a/tests/baselines/reference/declarationsAndAssignments.js b/tests/baselines/reference/declarationsAndAssignments.js index 018aa5522ca..3a2f9ef3b4e 100644 --- a/tests/baselines/reference/declarationsAndAssignments.js +++ b/tests/baselines/reference/declarationsAndAssignments.js @@ -300,8 +300,8 @@ function f18() { var a; var b; var aa; - (_a = { a: a, b: b }, a = _a.a, b = _a.b, _a); - (_b = { b: b, a: a }, a = _b.a, b = _b.b, _b); + (_a = { a: a, b: b }, a = _a.a, b = _a.b); + (_b = { b: b, a: a }, a = _b.a, b = _b.b); _c = [a, b], aa[0] = _c[0], b = _c[1]; _d = [b, a], a = _d[0], b = _d[1]; // Error _e = [2, "def"], _f = _e[0], a = _f === void 0 ? 1 : _f, _g = _e[1], b = _g === void 0 ? "abc" : _g; @@ -311,7 +311,7 @@ function f19() { var a, b; _a = [1, 2], a = _a[0], b = _a[1]; _b = [b, a], a = _b[0], b = _b[1]; - (_c = { b: b, a: a }, a = _c.a, b = _c.b, _c); + (_c = { b: b, a: a }, a = _c.a, b = _c.b); _d = [[2, 3]][0], _e = _d === void 0 ? [1, 2] : _d, a = _e[0], b = _e[1]; var x = (_f = [1, 2], a = _f[0], b = _f[1], _f); var _a, _b, _c, _d, _e, _f; diff --git a/tests/baselines/reference/declareModifierOnImport1.js b/tests/baselines/reference/declareModifierOnImport1.js index 510407b4deb..3dc3601d470 100644 --- a/tests/baselines/reference/declareModifierOnImport1.js +++ b/tests/baselines/reference/declareModifierOnImport1.js @@ -2,3 +2,4 @@ declare import a = b; //// [declareModifierOnImport1.js] +var a = b; diff --git a/tests/baselines/reference/decoratedClassExportsCommonJS1.js b/tests/baselines/reference/decoratedClassExportsCommonJS1.js index 9674d7853d5..7ef4369f975 100644 --- a/tests/baselines/reference/decoratedClassExportsCommonJS1.js +++ b/tests/baselines/reference/decoratedClassExportsCommonJS1.js @@ -14,15 +14,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +let Testing123 = Testing123_1 = class Testing123 { }; -let Testing123_1 = class Testing123 { -}; -let Testing123 = Testing123_1; Testing123.prop1 = Testing123_1.prop0; Testing123 = Testing123_1 = __decorate([ - Something({ v: () => Testing123_1 }), - __metadata("design:paramtypes", []) + Something({ v: () => Testing123_1 }) ], Testing123); exports.Testing123 = Testing123; +var Testing123_1; diff --git a/tests/baselines/reference/decoratedClassExportsCommonJS2.js b/tests/baselines/reference/decoratedClassExportsCommonJS2.js index 3ca6fa2d70e..994178cbb79 100644 --- a/tests/baselines/reference/decoratedClassExportsCommonJS2.js +++ b/tests/baselines/reference/decoratedClassExportsCommonJS2.js @@ -13,14 +13,10 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +let Testing123 = Testing123_1 = class Testing123 { }; -let Testing123_1 = class Testing123 { -}; -let Testing123 = Testing123_1; Testing123 = Testing123_1 = __decorate([ - Something({ v: () => Testing123_1 }), - __metadata("design:paramtypes", []) + Something({ v: () => Testing123_1 }) ], Testing123); exports.Testing123 = Testing123; +var Testing123_1; diff --git a/tests/baselines/reference/decoratedClassExportsSystem1.js b/tests/baselines/reference/decoratedClassExportsSystem1.js index 43a4421642e..2f33feb28fb 100644 --- a/tests/baselines/reference/decoratedClassExportsSystem1.js +++ b/tests/baselines/reference/decoratedClassExportsSystem1.js @@ -17,21 +17,16 @@ System.register([], function (exports_1, context_1) { else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; - var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); - }; var __moduleName = context_1 && context_1.id; - var Testing123_1, Testing123; + var Testing123, Testing123_1; return { setters: [], execute: function () { - Testing123_1 = class Testing123 { + Testing123 = Testing123_1 = class Testing123 { }; - Testing123 = Testing123_1; Testing123.prop1 = Testing123_1.prop0; Testing123 = Testing123_1 = __decorate([ - Something({ v: () => Testing123_1 }), - __metadata("design:paramtypes", []) + Something({ v: () => Testing123_1 }) ], Testing123); exports_1("Testing123", Testing123); } diff --git a/tests/baselines/reference/decoratedClassExportsSystem2.js b/tests/baselines/reference/decoratedClassExportsSystem2.js index cbb592539cf..2c9c62cadb2 100644 --- a/tests/baselines/reference/decoratedClassExportsSystem2.js +++ b/tests/baselines/reference/decoratedClassExportsSystem2.js @@ -14,20 +14,15 @@ System.register([], function (exports_1, context_1) { else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; - var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); - }; var __moduleName = context_1 && context_1.id; - var Testing123_1, Testing123; + var Testing123, Testing123_1; return { setters: [], execute: function () { - Testing123_1 = class Testing123 { + Testing123 = Testing123_1 = class Testing123 { }; - Testing123 = Testing123_1; Testing123 = Testing123_1 = __decorate([ - Something({ v: () => Testing123_1 }), - __metadata("design:paramtypes", []) + Something({ v: () => Testing123_1 }) ], Testing123); exports_1("Testing123", Testing123); } diff --git a/tests/baselines/reference/decoratorInJsFile.errors.txt b/tests/baselines/reference/decoratorInJsFile.errors.txt new file mode 100644 index 00000000000..93bd5143b74 --- /dev/null +++ b/tests/baselines/reference/decoratorInJsFile.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/a.js(4,12): error TS8010: 'types' can only be used in a .ts file. + + +==== tests/cases/compiler/a.js (1 errors) ==== + + @SomeDecorator + class SomeClass { + foo(x: number) { + ~~~~~~ +!!! error TS8010: 'types' can only be used in a .ts file. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorInJsFile1.errors.txt b/tests/baselines/reference/decoratorInJsFile1.errors.txt new file mode 100644 index 00000000000..f4422c0c2d9 --- /dev/null +++ b/tests/baselines/reference/decoratorInJsFile1.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/a.js(3,7): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning. +tests/cases/compiler/a.js(4,12): error TS8010: 'types' can only be used in a .ts file. + + +==== tests/cases/compiler/a.js (2 errors) ==== + + @SomeDecorator + class SomeClass { + ~~~~~~~~~ +!!! error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning. + foo(x: number) { + ~~~~~~ +!!! error TS8010: 'types' can only be used in a .ts file. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorMetadataOnInferredType.js b/tests/baselines/reference/decoratorMetadataOnInferredType.js index 0c63bcf49da..43cdaa79ab8 100644 --- a/tests/baselines/reference/decoratorMetadataOnInferredType.js +++ b/tests/baselines/reference/decoratorMetadataOnInferredType.js @@ -33,8 +33,8 @@ var B = (function () { } return B; }()); -exports.B = B; __decorate([ decorator, __metadata("design:type", Object) ], B.prototype, "x", void 0); +exports.B = B; diff --git a/tests/baselines/reference/decoratorMetadataPromise.js b/tests/baselines/reference/decoratorMetadataPromise.js index 52449f91755..23491449dfa 100644 --- a/tests/baselines/reference/decoratorMetadataPromise.js +++ b/tests/baselines/reference/decoratorMetadataPromise.js @@ -27,7 +27,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class A { diff --git a/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js new file mode 100644 index 00000000000..be249800d57 --- /dev/null +++ b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js @@ -0,0 +1,112 @@ +//// [tests/cases/compiler/decoratorMetadataRestParameterWithImportedType.ts] //// + +//// [aux.ts] + +export class SomeClass { + field: string; +} + +//// [aux1.ts] +export class SomeClass1 { + field: string; +} + +//// [aux2.ts] +export class SomeClass2 { + field: string; +} +//// [main.ts] +import { SomeClass } from './aux'; +import { SomeClass1 } from './aux1'; + +function annotation(): ClassDecorator { + return (target: any): void => { }; +} + +function annotation1(): MethodDecorator { + return (target: any): void => { }; +} + +@annotation() +export class ClassA { + array: SomeClass[]; + + constructor(...init: SomeClass[]) { + this.array = init; + } + + @annotation1() + foo(... args: SomeClass1[]) { + } +} + +//// [aux.js] +"use strict"; +var SomeClass = (function () { + function SomeClass() { + } + return SomeClass; +}()); +exports.SomeClass = SomeClass; +//// [aux1.js] +"use strict"; +var SomeClass1 = (function () { + function SomeClass1() { + } + return SomeClass1; +}()); +exports.SomeClass1 = SomeClass1; +//// [aux2.js] +"use strict"; +var SomeClass2 = (function () { + function SomeClass2() { + } + return SomeClass2; +}()); +exports.SomeClass2 = SomeClass2; +//// [main.js] +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var aux_1 = require("./aux"); +var aux1_1 = require("./aux1"); +function annotation() { + return function (target) { }; +} +function annotation1() { + return function (target) { }; +} +var ClassA = (function () { + function ClassA() { + var init = []; + for (var _i = 0; _i < arguments.length; _i++) { + init[_i] = arguments[_i]; + } + this.array = init; + } + ClassA.prototype.foo = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + }; + return ClassA; +}()); +__decorate([ + annotation1(), + __metadata("design:type", Function), + __metadata("design:paramtypes", [aux1_1.SomeClass1]), + __metadata("design:returntype", void 0) +], ClassA.prototype, "foo", null); +ClassA = __decorate([ + annotation(), + __metadata("design:paramtypes", [aux_1.SomeClass]) +], ClassA); +exports.ClassA = ClassA; diff --git a/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.symbols b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.symbols new file mode 100644 index 00000000000..9bd293cdfcb --- /dev/null +++ b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.symbols @@ -0,0 +1,77 @@ +=== tests/cases/compiler/aux.ts === + +export class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(aux.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass.field, Decl(aux.ts, 1, 24)) +} + +=== tests/cases/compiler/aux1.ts === +export class SomeClass1 { +>SomeClass1 : Symbol(SomeClass1, Decl(aux1.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass1.field, Decl(aux1.ts, 0, 25)) +} + +=== tests/cases/compiler/aux2.ts === +export class SomeClass2 { +>SomeClass2 : Symbol(SomeClass2, Decl(aux2.ts, 0, 0)) + + field: string; +>field : Symbol(SomeClass2.field, Decl(aux2.ts, 0, 25)) +} +=== tests/cases/compiler/main.ts === +import { SomeClass } from './aux'; +>SomeClass : Symbol(SomeClass, Decl(main.ts, 0, 8)) + +import { SomeClass1 } from './aux1'; +>SomeClass1 : Symbol(SomeClass1, Decl(main.ts, 1, 8)) + +function annotation(): ClassDecorator { +>annotation : Symbol(annotation, Decl(main.ts, 1, 36)) +>ClassDecorator : Symbol(ClassDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(main.ts, 4, 12)) +} + +function annotation1(): MethodDecorator { +>annotation1 : Symbol(annotation1, Decl(main.ts, 5, 1)) +>MethodDecorator : Symbol(MethodDecorator, Decl(lib.d.ts, --, --)) + + return (target: any): void => { }; +>target : Symbol(target, Decl(main.ts, 8, 12)) +} + +@annotation() +>annotation : Symbol(annotation, Decl(main.ts, 1, 36)) + +export class ClassA { +>ClassA : Symbol(ClassA, Decl(main.ts, 9, 1)) + + array: SomeClass[]; +>array : Symbol(ClassA.array, Decl(main.ts, 12, 21)) +>SomeClass : Symbol(SomeClass, Decl(main.ts, 0, 8)) + + constructor(...init: SomeClass[]) { +>init : Symbol(init, Decl(main.ts, 15, 16)) +>SomeClass : Symbol(SomeClass, Decl(main.ts, 0, 8)) + + this.array = init; +>this.array : Symbol(ClassA.array, Decl(main.ts, 12, 21)) +>this : Symbol(ClassA, Decl(main.ts, 9, 1)) +>array : Symbol(ClassA.array, Decl(main.ts, 12, 21)) +>init : Symbol(init, Decl(main.ts, 15, 16)) + } + + @annotation1() +>annotation1 : Symbol(annotation1, Decl(main.ts, 5, 1)) + + foo(... args: SomeClass1[]) { +>foo : Symbol(ClassA.foo, Decl(main.ts, 17, 5)) +>args : Symbol(args, Decl(main.ts, 20, 8)) +>SomeClass1 : Symbol(SomeClass1, Decl(main.ts, 1, 8)) + } +} diff --git a/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.types b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.types new file mode 100644 index 00000000000..6c27aa2c942 --- /dev/null +++ b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.types @@ -0,0 +1,82 @@ +=== tests/cases/compiler/aux.ts === + +export class SomeClass { +>SomeClass : SomeClass + + field: string; +>field : string +} + +=== tests/cases/compiler/aux1.ts === +export class SomeClass1 { +>SomeClass1 : SomeClass1 + + field: string; +>field : string +} + +=== tests/cases/compiler/aux2.ts === +export class SomeClass2 { +>SomeClass2 : SomeClass2 + + field: string; +>field : string +} +=== tests/cases/compiler/main.ts === +import { SomeClass } from './aux'; +>SomeClass : typeof SomeClass + +import { SomeClass1 } from './aux1'; +>SomeClass1 : typeof SomeClass1 + +function annotation(): ClassDecorator { +>annotation : () => ClassDecorator +>ClassDecorator : ClassDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} + +function annotation1(): MethodDecorator { +>annotation1 : () => MethodDecorator +>MethodDecorator : MethodDecorator + + return (target: any): void => { }; +>(target: any): void => { } : (target: any) => void +>target : any +} + +@annotation() +>annotation() : ClassDecorator +>annotation : () => ClassDecorator + +export class ClassA { +>ClassA : ClassA + + array: SomeClass[]; +>array : SomeClass[] +>SomeClass : SomeClass + + constructor(...init: SomeClass[]) { +>init : SomeClass[] +>SomeClass : SomeClass + + this.array = init; +>this.array = init : SomeClass[] +>this.array : SomeClass[] +>this : this +>array : SomeClass[] +>init : SomeClass[] + } + + @annotation1() +>annotation1() : MethodDecorator +>annotation1 : () => MethodDecorator + + foo(... args: SomeClass1[]) { +>foo : (...args: SomeClass1[]) => void +>args : SomeClass1[] +>SomeClass1 : SomeClass1 + } +} diff --git a/tests/baselines/reference/decoratorMetadataWithConstructorType.js b/tests/baselines/reference/decoratorMetadataWithConstructorType.js index 49b72e39a09..2c14c9b5bda 100644 --- a/tests/baselines/reference/decoratorMetadataWithConstructorType.js +++ b/tests/baselines/reference/decoratorMetadataWithConstructorType.js @@ -33,8 +33,8 @@ var B = (function () { } return B; }()); -exports.B = B; __decorate([ decorator, __metadata("design:type", A) ], B.prototype, "x", void 0); +exports.B = B; diff --git a/tests/baselines/reference/decoratorOnClass5.es6.js b/tests/baselines/reference/decoratorOnClass5.es6.js index e34740d6517..426a93668e7 100644 --- a/tests/baselines/reference/decoratorOnClass5.es6.js +++ b/tests/baselines/reference/decoratorOnClass5.es6.js @@ -16,12 +16,12 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -let C_1 = class C { +let C = C_1 = class C { static x() { return C_1.y; } }; -let C = C_1; C.y = 1; C = C_1 = __decorate([ dec ], C); let c = new C(); +var C_1; diff --git a/tests/baselines/reference/decoratorOnClass6.es6.js b/tests/baselines/reference/decoratorOnClass6.es6.js index fff39d85916..7da4a20bb93 100644 --- a/tests/baselines/reference/decoratorOnClass6.es6.js +++ b/tests/baselines/reference/decoratorOnClass6.es6.js @@ -16,13 +16,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -let C_1 = class C { +let C = C_1 = class C { static x() { return C_1.y; } }; -let C = C_1; C.y = 1; C = C_1 = __decorate([ dec ], C); export { C }; let c = new C(); +var C_1; diff --git a/tests/baselines/reference/decoratorOnClass7.es6.js b/tests/baselines/reference/decoratorOnClass7.es6.js index 7f111ea4abf..92ee02c899e 100644 --- a/tests/baselines/reference/decoratorOnClass7.es6.js +++ b/tests/baselines/reference/decoratorOnClass7.es6.js @@ -16,13 +16,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -let C_1 = class C { +let C = C_1 = class C { static x() { return C_1.y; } }; -let C = C_1; C.y = 1; C = C_1 = __decorate([ dec ], C); export default C; let c = new C(); +var C_1; diff --git a/tests/baselines/reference/decoratorOnClassAccessor7.errors.txt b/tests/baselines/reference/decoratorOnClassAccessor7.errors.txt new file mode 100644 index 00000000000..d776297fcf4 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassAccessor7.errors.txt @@ -0,0 +1,41 @@ +tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts(26,5): error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name. +tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts(31,5): error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name. + + +==== tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts (2 errors) ==== + declare function dec1(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + declare function dec2(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + + class A { + @dec1 get x() { return 0; } + set x(value: number) { } + } + + class B { + get x() { return 0; } + @dec2 set x(value: number) { } + } + + class C { + @dec1 set x(value: number) { } + get x() { return 0; } + } + + class D { + set x(value: number) { } + @dec2 get x() { return 0; } + } + + class E { + @dec1 get x() { return 0; } + @dec2 set x(value: number) { } + ~ +!!! error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name. + } + + class F { + @dec1 set x(value: number) { } + @dec2 get x() { return 0; } + ~ +!!! error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name. + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassAccessor7.js b/tests/baselines/reference/decoratorOnClassAccessor7.js new file mode 100644 index 00000000000..5ae0c29c14b --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassAccessor7.js @@ -0,0 +1,125 @@ +//// [decoratorOnClassAccessor7.ts] +declare function dec1(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; +declare function dec2(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + +class A { + @dec1 get x() { return 0; } + set x(value: number) { } +} + +class B { + get x() { return 0; } + @dec2 set x(value: number) { } +} + +class C { + @dec1 set x(value: number) { } + get x() { return 0; } +} + +class D { + set x(value: number) { } + @dec2 get x() { return 0; } +} + +class E { + @dec1 get x() { return 0; } + @dec2 set x(value: number) { } +} + +class F { + @dec1 set x(value: number) { } + @dec2 get x() { return 0; } +} + +//// [decoratorOnClassAccessor7.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var A = (function () { + function A() { + } + Object.defineProperty(A.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return A; +}()); +__decorate([ + dec1 +], A.prototype, "x", null); +var B = (function () { + function B() { + } + Object.defineProperty(B.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return B; +}()); +__decorate([ + dec2 +], B.prototype, "x", null); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return C; +}()); +__decorate([ + dec1 +], C.prototype, "x", null); +var D = (function () { + function D() { + } + Object.defineProperty(D.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return D; +}()); +__decorate([ + dec2 +], D.prototype, "x", null); +var E = (function () { + function E() { + } + Object.defineProperty(E.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return E; +}()); +__decorate([ + dec1 +], E.prototype, "x", null); +var F = (function () { + function F() { + } + Object.defineProperty(F.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return F; +}()); +__decorate([ + dec1 +], F.prototype, "x", null); diff --git a/tests/baselines/reference/decoratorOnClassAccessor8.js b/tests/baselines/reference/decoratorOnClassAccessor8.js new file mode 100644 index 00000000000..7347e630eab --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassAccessor8.js @@ -0,0 +1,135 @@ +//// [decoratorOnClassAccessor8.ts] +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + +class A { + @dec get x() { return 0; } + set x(value: number) { } +} + +class B { + get x() { return 0; } + @dec set x(value: number) { } +} + +class C { + @dec set x(value: number) { } + get x() { return 0; } +} + +class D { + set x(value: number) { } + @dec get x() { return 0; } +} + +class E { + @dec get x() { return 0; } +} + +class F { + @dec set x(value: number) { } +} + +//// [decoratorOnClassAccessor8.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var A = (function () { + function A() { + } + Object.defineProperty(A.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return A; +}()); +__decorate([ + dec, + __metadata("design:type", Object), + __metadata("design:paramtypes", [Number]) +], A.prototype, "x", null); +var B = (function () { + function B() { + } + Object.defineProperty(B.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return B; +}()); +__decorate([ + dec, + __metadata("design:type", Number), + __metadata("design:paramtypes", [Number]) +], B.prototype, "x", null); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return C; +}()); +__decorate([ + dec, + __metadata("design:type", Number), + __metadata("design:paramtypes", [Number]) +], C.prototype, "x", null); +var D = (function () { + function D() { + } + Object.defineProperty(D.prototype, "x", { + get: function () { return 0; }, + set: function (value) { }, + enumerable: true, + configurable: true + }); + return D; +}()); +__decorate([ + dec, + __metadata("design:type", Object), + __metadata("design:paramtypes", [Number]) +], D.prototype, "x", null); +var E = (function () { + function E() { + } + Object.defineProperty(E.prototype, "x", { + get: function () { return 0; }, + enumerable: true, + configurable: true + }); + return E; +}()); +__decorate([ + dec, + __metadata("design:type", Object), + __metadata("design:paramtypes", []) +], E.prototype, "x", null); +var F = (function () { + function F() { + } + Object.defineProperty(F.prototype, "x", { + set: function (value) { }, + enumerable: true, + configurable: true + }); + return F; +}()); +__decorate([ + dec, + __metadata("design:type", Number), + __metadata("design:paramtypes", [Number]) +], F.prototype, "x", null); diff --git a/tests/baselines/reference/decoratorOnClassAccessor8.symbols b/tests/baselines/reference/decoratorOnClassAccessor8.symbols new file mode 100644 index 00000000000..d1e22d586fc --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassAccessor8.symbols @@ -0,0 +1,76 @@ +=== tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor8.ts === +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>T : Symbol(T, Decl(decoratorOnClassAccessor8.ts, 0, 21)) +>target : Symbol(target, Decl(decoratorOnClassAccessor8.ts, 0, 24)) +>propertyKey : Symbol(propertyKey, Decl(decoratorOnClassAccessor8.ts, 0, 36)) +>descriptor : Symbol(descriptor, Decl(decoratorOnClassAccessor8.ts, 0, 57)) +>TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(decoratorOnClassAccessor8.ts, 0, 21)) +>TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(decoratorOnClassAccessor8.ts, 0, 21)) + +class A { +>A : Symbol(A, Decl(decoratorOnClassAccessor8.ts, 0, 126)) + + @dec get x() { return 0; } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(A.x, Decl(decoratorOnClassAccessor8.ts, 2, 9), Decl(decoratorOnClassAccessor8.ts, 3, 30)) + + set x(value: number) { } +>x : Symbol(A.x, Decl(decoratorOnClassAccessor8.ts, 2, 9), Decl(decoratorOnClassAccessor8.ts, 3, 30)) +>value : Symbol(value, Decl(decoratorOnClassAccessor8.ts, 4, 10)) +} + +class B { +>B : Symbol(B, Decl(decoratorOnClassAccessor8.ts, 5, 1)) + + get x() { return 0; } +>x : Symbol(B.x, Decl(decoratorOnClassAccessor8.ts, 7, 9), Decl(decoratorOnClassAccessor8.ts, 8, 25)) + + @dec set x(value: number) { } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(B.x, Decl(decoratorOnClassAccessor8.ts, 7, 9), Decl(decoratorOnClassAccessor8.ts, 8, 25)) +>value : Symbol(value, Decl(decoratorOnClassAccessor8.ts, 9, 15)) +} + +class C { +>C : Symbol(C, Decl(decoratorOnClassAccessor8.ts, 10, 1)) + + @dec set x(value: number) { } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(C.x, Decl(decoratorOnClassAccessor8.ts, 12, 9), Decl(decoratorOnClassAccessor8.ts, 13, 33)) +>value : Symbol(value, Decl(decoratorOnClassAccessor8.ts, 13, 15)) + + get x() { return 0; } +>x : Symbol(C.x, Decl(decoratorOnClassAccessor8.ts, 12, 9), Decl(decoratorOnClassAccessor8.ts, 13, 33)) +} + +class D { +>D : Symbol(D, Decl(decoratorOnClassAccessor8.ts, 15, 1)) + + set x(value: number) { } +>x : Symbol(D.x, Decl(decoratorOnClassAccessor8.ts, 17, 9), Decl(decoratorOnClassAccessor8.ts, 18, 28)) +>value : Symbol(value, Decl(decoratorOnClassAccessor8.ts, 18, 10)) + + @dec get x() { return 0; } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(D.x, Decl(decoratorOnClassAccessor8.ts, 17, 9), Decl(decoratorOnClassAccessor8.ts, 18, 28)) +} + +class E { +>E : Symbol(E, Decl(decoratorOnClassAccessor8.ts, 20, 1)) + + @dec get x() { return 0; } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(E.x, Decl(decoratorOnClassAccessor8.ts, 22, 9)) +} + +class F { +>F : Symbol(F, Decl(decoratorOnClassAccessor8.ts, 24, 1)) + + @dec set x(value: number) { } +>dec : Symbol(dec, Decl(decoratorOnClassAccessor8.ts, 0, 0)) +>x : Symbol(F.x, Decl(decoratorOnClassAccessor8.ts, 26, 9)) +>value : Symbol(value, Decl(decoratorOnClassAccessor8.ts, 27, 15)) +} diff --git a/tests/baselines/reference/decoratorOnClassAccessor8.types b/tests/baselines/reference/decoratorOnClassAccessor8.types new file mode 100644 index 00000000000..e8f46ee460d --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassAccessor8.types @@ -0,0 +1,81 @@ +=== tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor8.ts === +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>T : T +>target : any +>propertyKey : string +>descriptor : TypedPropertyDescriptor +>TypedPropertyDescriptor : TypedPropertyDescriptor +>T : T +>TypedPropertyDescriptor : TypedPropertyDescriptor +>T : T + +class A { +>A : A + + @dec get x() { return 0; } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>0 : 0 + + set x(value: number) { } +>x : number +>value : number +} + +class B { +>B : B + + get x() { return 0; } +>x : number +>0 : 0 + + @dec set x(value: number) { } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>value : number +} + +class C { +>C : C + + @dec set x(value: number) { } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>value : number + + get x() { return 0; } +>x : number +>0 : 0 +} + +class D { +>D : D + + set x(value: number) { } +>x : number +>value : number + + @dec get x() { return 0; } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>0 : 0 +} + +class E { +>E : E + + @dec get x() { return 0; } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>0 : 0 +} + +class F { +>F : F + + @dec set x(value: number) { } +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>x : number +>value : number +} diff --git a/tests/baselines/reference/decoratorOnClassConstructor4.js b/tests/baselines/reference/decoratorOnClassConstructor4.js new file mode 100644 index 00000000000..22414e89e43 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassConstructor4.js @@ -0,0 +1,58 @@ +//// [decoratorOnClassConstructor4.ts] +declare var dec: any; + +@dec +class A { +} + +@dec +class B { + constructor(x: number) {} +} + +@dec +class C extends A { +} + +//// [decoratorOnClassConstructor4.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var A = (function () { + function A() { + } + return A; +}()); +A = __decorate([ + dec +], A); +var B = (function () { + function B(x) { + } + return B; +}()); +B = __decorate([ + dec, + __metadata("design:paramtypes", [Number]) +], B); +var C = (function (_super) { + __extends(C, _super); + function C() { + return _super.apply(this, arguments) || this; + } + return C; +}(A)); +C = __decorate([ + dec +], C); diff --git a/tests/baselines/reference/decoratorOnClassConstructor4.symbols b/tests/baselines/reference/decoratorOnClassConstructor4.symbols new file mode 100644 index 00000000000..8a414abd7b1 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassConstructor4.symbols @@ -0,0 +1,28 @@ +=== tests/cases/conformance/decorators/class/constructor/decoratorOnClassConstructor4.ts === +declare var dec: any; +>dec : Symbol(dec, Decl(decoratorOnClassConstructor4.ts, 0, 11)) + +@dec +>dec : Symbol(dec, Decl(decoratorOnClassConstructor4.ts, 0, 11)) + +class A { +>A : Symbol(A, Decl(decoratorOnClassConstructor4.ts, 0, 21)) +} + +@dec +>dec : Symbol(dec, Decl(decoratorOnClassConstructor4.ts, 0, 11)) + +class B { +>B : Symbol(B, Decl(decoratorOnClassConstructor4.ts, 4, 1)) + + constructor(x: number) {} +>x : Symbol(x, Decl(decoratorOnClassConstructor4.ts, 8, 16)) +} + +@dec +>dec : Symbol(dec, Decl(decoratorOnClassConstructor4.ts, 0, 11)) + +class C extends A { +>C : Symbol(C, Decl(decoratorOnClassConstructor4.ts, 9, 1)) +>A : Symbol(A, Decl(decoratorOnClassConstructor4.ts, 0, 21)) +} diff --git a/tests/baselines/reference/decoratorOnClassConstructor4.types b/tests/baselines/reference/decoratorOnClassConstructor4.types new file mode 100644 index 00000000000..f4203bd5d7d --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassConstructor4.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/decorators/class/constructor/decoratorOnClassConstructor4.ts === +declare var dec: any; +>dec : any + +@dec +>dec : any + +class A { +>A : A +} + +@dec +>dec : any + +class B { +>B : B + + constructor(x: number) {} +>x : number +} + +@dec +>dec : any + +class C extends A { +>C : C +>A : A +} diff --git a/tests/baselines/reference/decoratorWithUnderscoreMethod.js b/tests/baselines/reference/decoratorWithUnderscoreMethod.js new file mode 100644 index 00000000000..bf79890263b --- /dev/null +++ b/tests/baselines/reference/decoratorWithUnderscoreMethod.js @@ -0,0 +1,37 @@ +//// [decoratorWithUnderscoreMethod.ts] + +declare var console : { log(arg: string): void }; +function dec(): Function { + return function (target: any, propKey: string, descr: PropertyDescriptor): void { + console.log(target[propKey]); + //logs undefined + //propKey has three underscores as prefix, but the method has only two underscores + }; +} + +class A { + @dec() + private __foo(bar: string): void { + // do something with bar + } +} + +//// [decoratorWithUnderscoreMethod.js] +function dec() { + return function (target, propKey, descr) { + console.log(target[propKey]); + //logs undefined + //propKey has three underscores as prefix, but the method has only two underscores + }; +} +var A = (function () { + function A() { + } + A.prototype.__foo = function (bar) { + // do something with bar + }; + return A; +}()); +__decorate([ + dec() +], A.prototype, "__foo"); diff --git a/tests/baselines/reference/decoratorWithUnderscoreMethod.symbols b/tests/baselines/reference/decoratorWithUnderscoreMethod.symbols new file mode 100644 index 00000000000..a512bde71f6 --- /dev/null +++ b/tests/baselines/reference/decoratorWithUnderscoreMethod.symbols @@ -0,0 +1,42 @@ +=== tests/cases/compiler/decoratorWithUnderscoreMethod.ts === + +declare var console : { log(arg: string): void }; +>console : Symbol(console, Decl(decoratorWithUnderscoreMethod.ts, 1, 11)) +>log : Symbol(log, Decl(decoratorWithUnderscoreMethod.ts, 1, 23)) +>arg : Symbol(arg, Decl(decoratorWithUnderscoreMethod.ts, 1, 28)) + +function dec(): Function { +>dec : Symbol(dec, Decl(decoratorWithUnderscoreMethod.ts, 1, 49)) +>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + + return function (target: any, propKey: string, descr: PropertyDescriptor): void { +>target : Symbol(target, Decl(decoratorWithUnderscoreMethod.ts, 3, 21)) +>propKey : Symbol(propKey, Decl(decoratorWithUnderscoreMethod.ts, 3, 33)) +>descr : Symbol(descr, Decl(decoratorWithUnderscoreMethod.ts, 3, 50)) +>PropertyDescriptor : Symbol(PropertyDescriptor, Decl(lib.d.ts, --, --)) + + console.log(target[propKey]); +>console.log : Symbol(log, Decl(decoratorWithUnderscoreMethod.ts, 1, 23)) +>console : Symbol(console, Decl(decoratorWithUnderscoreMethod.ts, 1, 11)) +>log : Symbol(log, Decl(decoratorWithUnderscoreMethod.ts, 1, 23)) +>target : Symbol(target, Decl(decoratorWithUnderscoreMethod.ts, 3, 21)) +>propKey : Symbol(propKey, Decl(decoratorWithUnderscoreMethod.ts, 3, 33)) + + //logs undefined + //propKey has three underscores as prefix, but the method has only two underscores + }; +} + +class A { +>A : Symbol(A, Decl(decoratorWithUnderscoreMethod.ts, 8, 1)) + + @dec() +>dec : Symbol(dec, Decl(decoratorWithUnderscoreMethod.ts, 1, 49)) + + private __foo(bar: string): void { +>__foo : Symbol(A.__foo, Decl(decoratorWithUnderscoreMethod.ts, 10, 9)) +>bar : Symbol(bar, Decl(decoratorWithUnderscoreMethod.ts, 12, 18)) + + // do something with bar + } +} diff --git a/tests/baselines/reference/decoratorWithUnderscoreMethod.types b/tests/baselines/reference/decoratorWithUnderscoreMethod.types new file mode 100644 index 00000000000..1ce08dc8a9e --- /dev/null +++ b/tests/baselines/reference/decoratorWithUnderscoreMethod.types @@ -0,0 +1,46 @@ +=== tests/cases/compiler/decoratorWithUnderscoreMethod.ts === + +declare var console : { log(arg: string): void }; +>console : { log(arg: string): void; } +>log : (arg: string) => void +>arg : string + +function dec(): Function { +>dec : () => Function +>Function : Function + + return function (target: any, propKey: string, descr: PropertyDescriptor): void { +>function (target: any, propKey: string, descr: PropertyDescriptor): void { console.log(target[propKey]); //logs undefined //propKey has three underscores as prefix, but the method has only two underscores } : (target: any, propKey: string, descr: PropertyDescriptor) => void +>target : any +>propKey : string +>descr : PropertyDescriptor +>PropertyDescriptor : PropertyDescriptor + + console.log(target[propKey]); +>console.log(target[propKey]) : void +>console.log : (arg: string) => void +>console : { log(arg: string): void; } +>log : (arg: string) => void +>target[propKey] : any +>target : any +>propKey : string + + //logs undefined + //propKey has three underscores as prefix, but the method has only two underscores + }; +} + +class A { +>A : A + + @dec() +>dec() : Function +>dec : () => Function + + private __foo(bar: string): void { +>__foo : (bar: string) => void +>bar : string + + // do something with bar + } +} diff --git a/tests/baselines/reference/decrementAndIncrementOperators.errors.txt b/tests/baselines/reference/decrementAndIncrementOperators.errors.txt index ec58db836a6..f8a0b5dcd82 100644 --- a/tests/baselines/reference/decrementAndIncrementOperators.errors.txt +++ b/tests/baselines/reference/decrementAndIncrementOperators.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/decrementAndIncrementOperators.ts(4,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(6,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(7,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(9,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(10,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(12,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(13,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(15,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(16,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(18,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(19,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(21,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/compiler/decrementAndIncrementOperators.ts(22,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/compiler/decrementAndIncrementOperators.ts(4,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(6,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(7,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(9,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(10,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(12,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(13,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(15,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(16,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(18,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(19,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(21,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/compiler/decrementAndIncrementOperators.ts(22,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ==== tests/cases/compiler/decrementAndIncrementOperators.ts (13 errors) ==== @@ -19,49 +19,49 @@ tests/cases/compiler/decrementAndIncrementOperators.ts(22,3): error TS2357: The // errors 1 ++; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (1)++; ~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (1)--; ~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ++(1); ~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. --(1); ~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (1 + 2)++; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (1 + 2)--; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ++(1 + 2); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. --(1 + 2); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (x + x)++; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. (x + x)--; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ++(x + x); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. --(x + x); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. //OK x++; diff --git a/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt b/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt index 2e1d594164d..e42b6ff67b4 100644 --- a/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt @@ -1,36 +1,36 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2539: Cannot assign to 'undefined' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,27): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,25): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -79,10 +79,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber2 = --A; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. var ResultIsNumber3 = --M; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber4 = --obj; ~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -95,10 +95,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber7 = A--; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. var ResultIsNumber8 = M--; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber9 = obj--; ~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -115,7 +115,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber13 = --undefined; ~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'undefined' because it is not a variable. var ResultIsNumber14 = null--; ~~~~ @@ -125,28 +125,28 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber16 = undefined--; ~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'undefined' because it is not a variable. // any type expressions var ResultIsNumber17 = --foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber18 = --A.foo(); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber19 = --(null + undefined); ~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber20 = --(null + null); ~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. var ResultIsNumber21 = --(undefined + undefined); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber22 = --obj1.x; @@ -158,23 +158,23 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp var ResultIsNumber24 = foo()--; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber25 = A.foo()--; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber26 = (null + undefined)--; ~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber27 = (null + null)--; ~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. var ResultIsNumber28 = (undefined + undefined)--; ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber29 = obj1.x--; diff --git a/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt b/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt index 29e06bc6a4e..aae28d5e417 100644 --- a/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(6,25): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(7,23): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(10,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(6,31): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(7,29): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(10,9): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,1): error TS2542: Index signature in type 'typeof ENUM1' only permits reading. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,7): error TS2304: Cannot find name 'A'. @@ -12,19 +12,19 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // expression var ResultIsNumber1 = --ENUM1["A"]; - ~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. var ResultIsNumber2 = ENUM1.A--; - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. // miss assignment operator --ENUM1["A"]; - ~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. ENUM1[A]--; ~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2542: Index signature in type 'typeof ENUM1' only permits reading. ~ !!! error TS2304: Cannot find name 'A'. \ No newline at end of file diff --git a/tests/baselines/reference/decrementOperatorWithEnumTypeInvalidOperations.errors.txt b/tests/baselines/reference/decrementOperatorWithEnumTypeInvalidOperations.errors.txt index 079bb2a6b64..0a79432c59c 100644 --- a/tests/baselines/reference/decrementOperatorWithEnumTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithEnumTypeInvalidOperations.errors.txt @@ -1,15 +1,15 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(7,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(8,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(10,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(11,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(14,25): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(7,25): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(8,25): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(10,23): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(11,23): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(14,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(14,43): error TS2339: Property 'B' does not exist on type 'typeof ENUM'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(15,23): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(15,23): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(15,29): error TS2339: Property 'A' does not exist on type 'typeof ENUM'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(18,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(19,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(21,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(22,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(18,3): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(19,3): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(21,1): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts(22,1): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. ==== tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumTypeInvalidOperations.ts (12 errors) ==== @@ -21,41 +21,41 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // enum type var var ResultIsNumber1 = --ENUM; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. var ResultIsNumber2 = --ENUM1; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. var ResultIsNumber3 = ENUM--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. var ResultIsNumber4 = ENUM1--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. // enum type expressions var ResultIsNumber5 = --(ENUM["A"] + ENUM.B); ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~ !!! error TS2339: Property 'B' does not exist on type 'typeof ENUM'. var ResultIsNumber6 = (ENUM.A + ENUM["B"])--; ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~ !!! error TS2339: Property 'A' does not exist on type 'typeof ENUM'. // miss assignment operator --ENUM; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. --ENUM1; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. ENUM--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. ENUM1--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt b/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt index 8df7e508099..8cf459cb790 100644 --- a/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt @@ -1,23 +1,23 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(35,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(35,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ==== tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts (20 errors) ==== @@ -48,7 +48,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // number type literal var ResultIsNumber3 = --1; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber4 = --{ x: 1, y: 2}; ~~~~~~~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -58,7 +58,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp var ResultIsNumber6 = 1--; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber7 = { x: 1, y: 2 }--; ~~~~~~~~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -69,41 +69,41 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // number type expressions var ResultIsNumber9 = --foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber10 = --A.foo(); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber11 = --(NUMBER + NUMBER); ~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber12 = foo()--; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber13 = A.foo()--; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber14 = (NUMBER + NUMBER)--; ~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. // miss assignment operator --1; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. --NUMBER1; ~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. --foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. 1--; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. NUMBER1--; ~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. foo()--; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. \ No newline at end of file +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/defaultExportInAwaitExpression01.js b/tests/baselines/reference/defaultExportInAwaitExpression01.js index a16e2f07f5f..9a122ae99c5 100644 --- a/tests/baselines/reference/defaultExportInAwaitExpression01.js +++ b/tests/baselines/reference/defaultExportInAwaitExpression01.js @@ -32,7 +32,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; (function (dependencies, factory) { diff --git a/tests/baselines/reference/defaultExportInAwaitExpression02.js b/tests/baselines/reference/defaultExportInAwaitExpression02.js index db05d62a2ad..8499164f675 100644 --- a/tests/baselines/reference/defaultExportInAwaitExpression02.js +++ b/tests/baselines/reference/defaultExportInAwaitExpression02.js @@ -24,7 +24,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const a_1 = require("./a"); diff --git a/tests/baselines/reference/defaultExportWithOverloads01.js b/tests/baselines/reference/defaultExportWithOverloads01.js index f88d60182db..770b685378d 100644 --- a/tests/baselines/reference/defaultExportWithOverloads01.js +++ b/tests/baselines/reference/defaultExportWithOverloads01.js @@ -10,7 +10,7 @@ export default function f(...args: any[]) { function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tests/baselines/reference/defaultExportsCannotMerge02.js b/tests/baselines/reference/defaultExportsCannotMerge02.js index ae5701b86bc..f327c62e571 100644 --- a/tests/baselines/reference/defaultExportsCannotMerge02.js +++ b/tests/baselines/reference/defaultExportsCannotMerge02.js @@ -33,7 +33,7 @@ var Decl = (function () { return Decl; }()); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports.Decl; +exports.default = Decl; //// [m2.js] "use strict"; var m1_1 = require("m1"); diff --git a/tests/baselines/reference/defaultExportsCannotMerge04.js b/tests/baselines/reference/defaultExportsCannotMerge04.js index ef8d6853d98..7c9bd88bc16 100644 --- a/tests/baselines/reference/defaultExportsCannotMerge04.js +++ b/tests/baselines/reference/defaultExportsCannotMerge04.js @@ -18,7 +18,7 @@ export interface Foo { function Foo() { } Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports.Foo; +exports.default = Foo; var Foo; (function (Foo) { -})(exports.Foo || (exports.Foo = {})); +})(Foo || (Foo = {})); diff --git a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js index 504d414a608..039e25919f8 100644 --- a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js +++ b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js @@ -42,7 +42,8 @@ var Base = (function () { var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - return _super.call(this, _this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return Derived; }(Base)); diff --git a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.errors.txt b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.errors.txt new file mode 100644 index 00000000000..a68affcf73d --- /dev/null +++ b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.errors.txt @@ -0,0 +1,26 @@ +tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts(2,22): error TS2448: Block-scoped variable 'e' used before its declaration. +tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts(3,22): error TS2448: Block-scoped variable 'i' used before its declaration. +tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts(7,27): error TS2372: Parameter 'e' cannot be referenced in its initializer. +tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts(9,27): error TS2373: Initializer of parameter 'h' cannot reference identifier 'i' declared after it. + + +==== tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts (4 errors) ==== + const [a, b = a] = [1]; // ok + const [c, d = c, e = e] = [1]; // error for e = e + ~ +!!! error TS2448: Block-scoped variable 'e' used before its declaration. + const [f, g = f, h = i, i = f] = [1]; // error for h = i + ~ +!!! error TS2448: Block-scoped variable 'i' used before its declaration. + + (function ([a, b = a]) { // ok + })([1]); + (function ([c, d = c, e = e]) { // error for e = e + ~ +!!! error TS2372: Parameter 'e' cannot be referenced in its initializer. + })([1]); + (function ([f, g = f, h = i, i = f]) { // error for h = i + ~ +!!! error TS2373: Initializer of parameter 'h' cannot reference identifier 'i' declared after it. + })([1]) + \ No newline at end of file diff --git a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.js b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.js new file mode 100644 index 00000000000..7073061dec6 --- /dev/null +++ b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment3.js @@ -0,0 +1,26 @@ +//// [destructuringArrayBindingPatternAndAssignment3.ts] +const [a, b = a] = [1]; // ok +const [c, d = c, e = e] = [1]; // error for e = e +const [f, g = f, h = i, i = f] = [1]; // error for h = i + +(function ([a, b = a]) { // ok +})([1]); +(function ([c, d = c, e = e]) { // error for e = e +})([1]); +(function ([f, g = f, h = i, i = f]) { // error for h = i +})([1]) + + +//// [destructuringArrayBindingPatternAndAssignment3.js] +var _a = [1], a = _a[0], _b = _a[1], b = _b === void 0 ? a : _b; // ok +var _c = [1], c = _c[0], _d = _c[1], d = _d === void 0 ? c : _d, _e = _c[2], e = _e === void 0 ? e : _e; // error for e = e +var _f = [1], f = _f[0], _g = _f[1], g = _g === void 0 ? f : _g, _h = _f[2], h = _h === void 0 ? i : _h, _j = _f[3], i = _j === void 0 ? f : _j; // error for h = i +(function (_a) { + var a = _a[0], _b = _a[1], b = _b === void 0 ? a : _b; +})([1]); +(function (_a) { + var c = _a[0], _b = _a[1], d = _b === void 0 ? c : _b, _c = _a[2], e = _c === void 0 ? e : _c; +})([1]); +(function (_a) { + var f = _a[0], _b = _a[1], g = _b === void 0 ? f : _b, _c = _a[2], h = _c === void 0 ? i : _c, _d = _a[3], i = _d === void 0 ? f : _d; +})([1]); diff --git a/tests/baselines/reference/destructuringAssignmentWithDefault.js b/tests/baselines/reference/destructuringAssignmentWithDefault.js index ce3837e1162..fe3ccdcee53 100644 --- a/tests/baselines/reference/destructuringAssignmentWithDefault.js +++ b/tests/baselines/reference/destructuringAssignmentWithDefault.js @@ -7,5 +7,5 @@ let x = 0; //// [destructuringAssignmentWithDefault.js] var a = {}; var x = 0; -(_a = a.x, x = _a === void 0 ? 1 : _a, a); +(_a = a.x, x = _a === void 0 ? 1 : _a); var _a; diff --git a/tests/baselines/reference/destructuringCatch.js b/tests/baselines/reference/destructuringCatch.js new file mode 100644 index 00000000000..4593b22f127 --- /dev/null +++ b/tests/baselines/reference/destructuringCatch.js @@ -0,0 +1,59 @@ +//// [destructuringCatch.ts] + +try { + throw [0, 1]; +} +catch ([a, b]) { + a + b; +} + +try { + throw { a: 0, b: 1 }; +} +catch ({a, b}) { + a + b; +} + +try { + throw [{ x: [0], z: 1 }]; +} +catch ([{x: [y], z}]) { + y + z; +} + +// Test of comment ranges. A fix to GH#11755 should update this. +try { +} +catch (/*Test comment ranges*/[/*a*/a]) { + +} + + +//// [destructuringCatch.js] +try { + throw [0, 1]; +} +catch (_a) { + var a = _a[0], b = _a[1]; + a + b; +} +try { + throw { a: 0, b: 1 }; +} +catch (_b) { + var a = _b.a, b = _b.b; + a + b; +} +try { + throw [{ x: [0], z: 1 }]; +} +catch (_c) { + var _d = _c[0], y = _d.x[0], z = _d.z; + y + z; +} +// Test of comment ranges. A fix to GH#11755 should update this. +try { +} +catch (_e) { + var /*a*/ a = _e[0]; +} diff --git a/tests/baselines/reference/destructuringCatch.symbols b/tests/baselines/reference/destructuringCatch.symbols new file mode 100644 index 00000000000..1d0a954b377 --- /dev/null +++ b/tests/baselines/reference/destructuringCatch.symbols @@ -0,0 +1,51 @@ +=== tests/cases/conformance/es6/destructuring/destructuringCatch.ts === + +try { + throw [0, 1]; +} +catch ([a, b]) { +>a : Symbol(a, Decl(destructuringCatch.ts, 4, 8)) +>b : Symbol(b, Decl(destructuringCatch.ts, 4, 10)) + + a + b; +>a : Symbol(a, Decl(destructuringCatch.ts, 4, 8)) +>b : Symbol(b, Decl(destructuringCatch.ts, 4, 10)) +} + +try { + throw { a: 0, b: 1 }; +>a : Symbol(a, Decl(destructuringCatch.ts, 9, 11)) +>b : Symbol(b, Decl(destructuringCatch.ts, 9, 17)) +} +catch ({a, b}) { +>a : Symbol(a, Decl(destructuringCatch.ts, 11, 8)) +>b : Symbol(b, Decl(destructuringCatch.ts, 11, 10)) + + a + b; +>a : Symbol(a, Decl(destructuringCatch.ts, 11, 8)) +>b : Symbol(b, Decl(destructuringCatch.ts, 11, 10)) +} + +try { + throw [{ x: [0], z: 1 }]; +>x : Symbol(x, Decl(destructuringCatch.ts, 16, 12)) +>z : Symbol(z, Decl(destructuringCatch.ts, 16, 20)) +} +catch ([{x: [y], z}]) { +>x : Symbol(x) +>y : Symbol(y, Decl(destructuringCatch.ts, 18, 13)) +>z : Symbol(z, Decl(destructuringCatch.ts, 18, 16)) + + y + z; +>y : Symbol(y, Decl(destructuringCatch.ts, 18, 13)) +>z : Symbol(z, Decl(destructuringCatch.ts, 18, 16)) +} + +// Test of comment ranges. A fix to GH#11755 should update this. +try { +} +catch (/*Test comment ranges*/[/*a*/a]) { +>a : Symbol(a, Decl(destructuringCatch.ts, 25, 31)) + +} + diff --git a/tests/baselines/reference/destructuringCatch.types b/tests/baselines/reference/destructuringCatch.types new file mode 100644 index 00000000000..3f057e64e4e --- /dev/null +++ b/tests/baselines/reference/destructuringCatch.types @@ -0,0 +1,65 @@ +=== tests/cases/conformance/es6/destructuring/destructuringCatch.ts === + +try { + throw [0, 1]; +>[0, 1] : number[] +>0 : 0 +>1 : 1 +} +catch ([a, b]) { +>a : any +>b : any + + a + b; +>a + b : any +>a : any +>b : any +} + +try { + throw { a: 0, b: 1 }; +>{ a: 0, b: 1 } : { a: number; b: number; } +>a : number +>0 : 0 +>b : number +>1 : 1 +} +catch ({a, b}) { +>a : any +>b : any + + a + b; +>a + b : any +>a : any +>b : any +} + +try { + throw [{ x: [0], z: 1 }]; +>[{ x: [0], z: 1 }] : { x: number[]; z: number; }[] +>{ x: [0], z: 1 } : { x: number[]; z: number; } +>x : number[] +>[0] : number[] +>0 : 0 +>z : number +>1 : 1 +} +catch ([{x: [y], z}]) { +>x : any +>y : any +>z : any + + y + z; +>y + z : any +>y : any +>z : any +} + +// Test of comment ranges. A fix to GH#11755 should update this. +try { +} +catch (/*Test comment ranges*/[/*a*/a]) { +>a : any + +} + diff --git a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt index bb4b79987e3..33344b9b5eb 100644 --- a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt +++ b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt @@ -5,16 +5,12 @@ tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAs tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(4,6): error TS2459: Type 'string | number | {}' has no property 'i1' and no string index signature. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(5,12): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(5,21): error TS2353: Object literal may only specify known properties, and 'f212' does not exist in type '{ f21: any; }'. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(6,7): error TS1180: Property destructuring pattern expected. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(7,5): error TS2353: Object literal may only specify known properties, and 'a' does not exist in type '{ d1: any; }'. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(7,11): error TS2353: Object literal may only specify known properties, and 'b' does not exist in type '{ d1: any; }'. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(7,24): error TS2353: Object literal may only specify known properties, and 'e' does not exist in type '{ d1: any; }'. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(9,7): error TS1005: ':' expected. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(9,15): error TS1005: ':' expected. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(10,12): error TS1005: ':' expected. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(6,7): error TS1005: ':' expected. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(6,15): error TS1005: ':' expected. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(7,12): error TS1005: ':' expected. -==== tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts (13 errors) ==== +==== tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts (9 errors) ==== // Error var {h?} = { h?: 1 }; ~ @@ -33,17 +29,6 @@ tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAs !!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value. ~~~~ !!! error TS2353: Object literal may only specify known properties, and 'f212' does not exist in type '{ f21: any; }'. - var { ...d1 } = { - ~~~ -!!! error TS1180: Property destructuring pattern expected. - a: 1, b: 1, d1: 9, e: 10 - ~ -!!! error TS2353: Object literal may only specify known properties, and 'a' does not exist in type '{ d1: any; }'. - ~ -!!! error TS2353: Object literal may only specify known properties, and 'b' does not exist in type '{ d1: any; }'. - ~ -!!! error TS2353: Object literal may only specify known properties, and 'e' does not exist in type '{ d1: any; }'. - } var {1} = { 1 }; ~ !!! error TS1005: ':' expected. @@ -51,4 +36,5 @@ tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAs !!! error TS1005: ':' expected. var {"prop"} = { "prop": 1 }; ~ -!!! error TS1005: ':' expected. \ No newline at end of file +!!! error TS1005: ':' expected. + \ No newline at end of file diff --git a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.js b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.js index 77288e6a542..0872a71c73b 100644 --- a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.js +++ b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.js @@ -4,11 +4,9 @@ var {h?} = { h?: 1 }; var {i}: string | number = { i: 2 }; var {i1}: string | number| {} = { i1: 2 }; var { f2: {f21} = { f212: "string" } }: any = undefined; -var { ...d1 } = { - a: 1, b: 1, d1: 9, e: 10 -} var {1} = { 1 }; -var {"prop"} = { "prop": 1 }; +var {"prop"} = { "prop": 1 }; + //// [destructuringObjectBindingPatternAndAssignment3.js] // Error @@ -16,8 +14,5 @@ var h = { h: 1 }.h; var i = { i: 2 }.i; var i1 = { i1: 2 }.i1; var _a = undefined.f2, f21 = (_a === void 0 ? { f212: "string" } : _a).f21; -var d1 = { - a: 1, b: 1, d1: 9, e: 10 -}.d1; var = { 1: }[1]; var = { "prop": 1 }["prop"]; diff --git a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.errors.txt b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.errors.txt new file mode 100644 index 00000000000..6a3f0f2b457 --- /dev/null +++ b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.errors.txt @@ -0,0 +1,18 @@ +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts(6,9): error TS2448: Block-scoped variable 'f' used before its declaration. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts(7,9): error TS2448: Block-scoped variable 'f' used before its declaration. + + +==== tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts (2 errors) ==== + const { + a = 1, + b = 2, + c = b, // ok + d = a, // ok + e = f, // error + ~ +!!! error TS2448: Block-scoped variable 'f' used before its declaration. + f = f // error + ~ +!!! error TS2448: Block-scoped variable 'f' used before its declaration. + } = { } as any; + \ No newline at end of file diff --git a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.js b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.js new file mode 100644 index 00000000000..c34cbb62c1c --- /dev/null +++ b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment4.js @@ -0,0 +1,21 @@ +//// [destructuringObjectBindingPatternAndAssignment4.ts] +const { + a = 1, + b = 2, + c = b, // ok + d = a, // ok + e = f, // error + f = f // error +} = { } as any; + + +//// [destructuringObjectBindingPatternAndAssignment4.js] +var _a = {}, _b = _a.a, a = _b === void 0 ? 1 : _b, _c = _a.b, b = _c === void 0 ? 2 : _c, _d = _a.c, c = _d === void 0 ? b : _d, // ok +_e = _a.d, // ok +d = _e === void 0 ? a : _e, // ok +_f = _a.e, // ok +e = _f === void 0 ? f : _f, // error +_g = _a.f // error +, // error +f = _g === void 0 ? f : _g // error +; diff --git a/tests/baselines/reference/destructuringParameterDeclaration4.js b/tests/baselines/reference/destructuringParameterDeclaration4.js index 44838d600d8..52007df17c9 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration4.js +++ b/tests/baselines/reference/destructuringParameterDeclaration4.js @@ -43,31 +43,31 @@ foo1(1, 2, "string", E1.a, E.b); // Error function a0() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } // Error, rest parameter must be array type function a1() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } function a2() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } } // Error, rest parameter must be array type function a3() { var b = []; for (var _i = 0; _i < arguments.length; _i++) { - b[_i - 0] = arguments[_i]; + b[_i] = arguments[_i]; } } // Error, can't be optional function a4() { var b = []; for (var _i = 0; _i < arguments.length; _i++) { - b[_i - 0] = arguments[_i]; + b[_i] = arguments[_i]; } } // Error, can't have initializer function a5(_a) { @@ -86,7 +86,7 @@ var C = (function () { function C() { var temp = []; for (var _i = 0; _i < arguments.length; _i++) { - temp[_i - 0] = arguments[_i]; + temp[_i] = arguments[_i]; } this.temp = temp; } // Error, rest parameter can't have properties @@ -96,7 +96,7 @@ var C = (function () { function foo1() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } } foo1(1, 2, "string", E1.a, E.b); // Error diff --git a/tests/baselines/reference/destructuringParameterDeclaration6.js b/tests/baselines/reference/destructuringParameterDeclaration6.js index ad86b2983b3..a8c7f65211f 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration6.js +++ b/tests/baselines/reference/destructuringParameterDeclaration6.js @@ -27,7 +27,7 @@ b2({ while: 1 }); "use strict"; // Error function a(_a) { - var = _a.while; + var = _a["while"]; } function a1(_a) { var public = _a.public; @@ -40,29 +40,29 @@ while (, ) function a5() { var = []; for (var _i = 0; _i < arguments.length; _i++) { - [_i - 0] = arguments[_i]; + [_i] = arguments[_i]; } } while () { } function a6() { var public = []; for (var _i = 0; _i < arguments.length; _i++) { - public[_i - 0] = arguments[_i]; + public[_i] = arguments[_i]; } } function a7() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } } -a({ while: 1 }); +a({ "while": 1 }); // No Error function b1(_a) { var x = _a.public; } function b2(_a) { - var y = _a.while; + var y = _a["while"]; } b1({ public: 1 }); -b2({ while: 1 }); +b2({ "while": 1 }); diff --git a/tests/baselines/reference/destructuringParameterProperties5.errors.txt b/tests/baselines/reference/destructuringParameterProperties5.errors.txt index 8eff6ad0feb..e0540240b61 100644 --- a/tests/baselines/reference/destructuringParameterProperties5.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties5.errors.txt @@ -1,15 +1,15 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,17): error TS1187: A parameter property may not be declared using a binding pattern. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,27): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x1' and no string index signature. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,31): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x2' and no string index signature. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,35): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x3' and no string index signature. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,27): error TS2459: Type 'ObjType1' has no property 'x1' and no string index signature. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,31): error TS2459: Type 'ObjType1' has no property 'x2' and no string index signature. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,35): error TS2459: Type 'ObjType1' has no property 'x3' and no string index signature. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,29): error TS2339: Property 'x1' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,40): error TS2339: Property 'x2' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,51): error TS2339: Property 'x3' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,62): error TS2339: Property 'y' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,72): error TS2339: Property 'z' does not exist on type 'C1'. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(11,19): error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[{ x: number; y: string; z: boolean; }, number, string]'. - Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. - Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(11,19): error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[ObjType1, number, string]'. + Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type 'ObjType1'. + Object literal may only specify known properties, and 'x1' does not exist in type 'ObjType1'. ==== tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts (10 errors) ==== @@ -21,11 +21,11 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1187: A parameter property may not be declared using a binding pattern. ~~ -!!! error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x1' and no string index signature. +!!! error TS2459: Type 'ObjType1' has no property 'x1' and no string index signature. ~~ -!!! error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x2' and no string index signature. +!!! error TS2459: Type 'ObjType1' has no property 'x2' and no string index signature. ~~ -!!! error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x3' and no string index signature. +!!! error TS2459: Type 'ObjType1' has no property 'x3' and no string index signature. var foo: any = x1 || x2 || x3 || y || z; var bar: any = this.x1 || this.x2 || this.x3 || this.y || this.z; ~~ @@ -43,7 +43,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(1 var a = new C1([{ x1: 10, x2: "", x3: true }, "", false]); ~~~~~~ -!!! error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[{ x: number; y: string; z: boolean; }, number, string]'. -!!! error TS2345: Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. -!!! error TS2345: Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. +!!! error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[ObjType1, number, string]'. +!!! error TS2345: Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type 'ObjType1'. +!!! error TS2345: Object literal may only specify known properties, and 'x1' does not exist in type 'ObjType1'. var [a_x1, a_x2, a_x3, a_y, a_z] = [a.x1, a.x2, a.x3, a.y, a.z]; \ No newline at end of file diff --git a/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction1.js b/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction1.js index 51ae4090ae1..495ac29f269 100644 --- a/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction1.js +++ b/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction1.js @@ -19,7 +19,7 @@ var TestFile = (function () { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } /// Test summary /// diff --git a/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction2.js b/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction2.js index 22dfe4bbc44..e6ced9a8a42 100644 --- a/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction2.js +++ b/tests/baselines/reference/detachedCommentAtStartOfLambdaFunction2.js @@ -23,7 +23,7 @@ var TestFile = (function () { /// var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } return message + _this.name; }; diff --git a/tests/baselines/reference/disallowLineTerminatorBeforeArrow.js b/tests/baselines/reference/disallowLineTerminatorBeforeArrow.js index 1044146ccd0..9f0d04d301c 100644 --- a/tests/baselines/reference/disallowLineTerminatorBeforeArrow.js +++ b/tests/baselines/reference/disallowLineTerminatorBeforeArrow.js @@ -92,13 +92,13 @@ var f4 = function (x, y) { var f5 = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; var f6 = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; var f7 = function (x, y, z) { @@ -138,9 +138,9 @@ var m; } return City; }()); + var Enum; (function (Enum) { Enum[Enum["claw"] = (function () { return 10; })()] = "claw"; - })(m.Enum || (m.Enum = {})); - var Enum = m.Enum; + })(Enum = m.Enum || (m.Enum = {})); m.v = function (x) { return new City(Enum.claw); }; })(m || (m = {})); diff --git a/tests/baselines/reference/doWhileUnreachableCode.js b/tests/baselines/reference/doWhileUnreachableCode.js new file mode 100644 index 00000000000..3434a93f52d --- /dev/null +++ b/tests/baselines/reference/doWhileUnreachableCode.js @@ -0,0 +1,26 @@ +//// [doWhileUnreachableCode.ts] +function test() { + let foo = 0; + testLoop: do { + foo++; + continue testLoop; + } while (function() { + var x = 1; + return false; + }()); + + return foo; +} + +//// [doWhileUnreachableCode.js] +function test() { + var foo = 0; + testLoop: do { + foo++; + continue testLoop; + } while (function () { + var x = 1; + return false; + }()); + return foo; +} diff --git a/tests/baselines/reference/doWhileUnreachableCode.symbols b/tests/baselines/reference/doWhileUnreachableCode.symbols new file mode 100644 index 00000000000..571976490c3 --- /dev/null +++ b/tests/baselines/reference/doWhileUnreachableCode.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/doWhileUnreachableCode.ts === +function test() { +>test : Symbol(test, Decl(doWhileUnreachableCode.ts, 0, 0)) + + let foo = 0; +>foo : Symbol(foo, Decl(doWhileUnreachableCode.ts, 1, 7)) + + testLoop: do { + foo++; +>foo : Symbol(foo, Decl(doWhileUnreachableCode.ts, 1, 7)) + + continue testLoop; + } while (function() { + var x = 1; +>x : Symbol(x, Decl(doWhileUnreachableCode.ts, 6, 11)) + + return false; + }()); + + return foo; +>foo : Symbol(foo, Decl(doWhileUnreachableCode.ts, 1, 7)) +} diff --git a/tests/baselines/reference/doWhileUnreachableCode.types b/tests/baselines/reference/doWhileUnreachableCode.types new file mode 100644 index 00000000000..0c176dda799 --- /dev/null +++ b/tests/baselines/reference/doWhileUnreachableCode.types @@ -0,0 +1,34 @@ +=== tests/cases/compiler/doWhileUnreachableCode.ts === +function test() { +>test : () => number + + let foo = 0; +>foo : number +>0 : 0 + + testLoop: do { +>testLoop : any + + foo++; +>foo++ : number +>foo : number + + continue testLoop; +>testLoop : any + + } while (function() { +>function() { var x = 1; return false; }() : boolean +>function() { var x = 1; return false; } : () => boolean + + var x = 1; +>x : number +>1 : 1 + + return false; +>false : false + + }()); + + return foo; +>foo : number +} diff --git a/tests/baselines/reference/dottedNamesInSystem.js b/tests/baselines/reference/dottedNamesInSystem.js index c4bb44f03cf..257d7e616af 100644 --- a/tests/baselines/reference/dottedNamesInSystem.js +++ b/tests/baselines/reference/dottedNamesInSystem.js @@ -14,8 +14,8 @@ System.register([], function (exports_1, context_1) { function bar() { return A.B.C.foo(); } - var A; exports_1("bar", bar); + var A; return { setters: [], execute: function () { @@ -28,7 +28,7 @@ System.register([], function (exports_1, context_1) { C.foo = foo; })(C = B.C || (B.C = {})); })(B = A.B || (A.B = {})); - })(A = A || (A = {})); + })(A || (A = {})); exports_1("A", A); } }; diff --git a/tests/baselines/reference/downlevelLetConst14.types b/tests/baselines/reference/downlevelLetConst14.types index 493c17b97cd..29c87e76cce 100644 --- a/tests/baselines/reference/downlevelLetConst14.types +++ b/tests/baselines/reference/downlevelLetConst14.types @@ -77,22 +77,22 @@ use(x); use(z0); >use(z0) : any >use : (a: any) => any ->z0 : undefined +>z0 : any use(z1); >use(z1) : any >use : (a: any) => any ->z1 : undefined +>z1 : any use(z2); >use(z2) : any >use : (a: any) => any ->z2 : undefined +>z2 : any use(z3); >use(z3) : any >use : (a: any) => any ->z3 : undefined +>z3 : any var z6; >z6 : any @@ -149,7 +149,7 @@ use(y); use(z6); >use(z6) : any >use : (a: any) => any ->z6 : undefined +>z6 : any var z = false; >z : boolean diff --git a/tests/baselines/reference/downlevelLetConst15.types b/tests/baselines/reference/downlevelLetConst15.types index 6d224b6310d..9e58c648821 100644 --- a/tests/baselines/reference/downlevelLetConst15.types +++ b/tests/baselines/reference/downlevelLetConst15.types @@ -83,22 +83,22 @@ use(x); use(z0); >use(z0) : any >use : (a: any) => any ->z0 : undefined +>z0 : any use(z1); >use(z1) : any >use : (a: any) => any ->z1 : undefined +>z1 : any use(z2); >use(z2) : any >use : (a: any) => any ->z2 : undefined +>z2 : any use(z3); >use(z3) : any >use : (a: any) => any ->z3 : undefined +>z3 : any var z6; >z6 : any @@ -155,7 +155,7 @@ use(y); use(z6); >use(z6) : any >use : (a: any) => any ->z6 : undefined +>z6 : any var z = false; >z : boolean diff --git a/tests/baselines/reference/duplicateLocalVariable1.errors.txt b/tests/baselines/reference/duplicateLocalVariable1.errors.txt index 87bcc71cdfc..b264574ea09 100644 --- a/tests/baselines/reference/duplicateLocalVariable1.errors.txt +++ b/tests/baselines/reference/duplicateLocalVariable1.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/duplicateLocalVariable1.ts(2,4): error TS1005: ';' expected tests/cases/compiler/duplicateLocalVariable1.ts(2,11): error TS1146: Declaration expected. tests/cases/compiler/duplicateLocalVariable1.ts(2,13): error TS2304: Cannot find name 'commonjs'. tests/cases/compiler/duplicateLocalVariable1.ts(187,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. -tests/cases/compiler/duplicateLocalVariable1.ts(187,29): error TS2365: Operator '<' cannot be applied to types 'string' and '14'. +tests/cases/compiler/duplicateLocalVariable1.ts(187,29): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. tests/cases/compiler/duplicateLocalVariable1.ts(187,37): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -203,7 +203,7 @@ tests/cases/compiler/duplicateLocalVariable1.ts(187,37): error TS2356: An arithm ~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. ~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types 'string' and '14'. +!!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. ~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. bytes.push(fb.readByte()); diff --git a/tests/baselines/reference/duplicateLocalVariable2.errors.txt b/tests/baselines/reference/duplicateLocalVariable2.errors.txt index 466e145d28d..5e89cc422cc 100644 --- a/tests/baselines/reference/duplicateLocalVariable2.errors.txt +++ b/tests/baselines/reference/duplicateLocalVariable2.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/duplicateLocalVariable2.ts(27,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. -tests/cases/compiler/duplicateLocalVariable2.ts(27,29): error TS2365: Operator '<' cannot be applied to types 'string' and '14'. +tests/cases/compiler/duplicateLocalVariable2.ts(27,29): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -34,7 +34,7 @@ tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithme ~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. ~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types 'string' and '14'. +!!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. ~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. bytes.push(fb.readByte()); diff --git a/tests/baselines/reference/emitDecoratorMetadata_restArgs.js b/tests/baselines/reference/emitDecoratorMetadata_restArgs.js index ec8240b2642..4bc1f023212 100644 --- a/tests/baselines/reference/emitDecoratorMetadata_restArgs.js +++ b/tests/baselines/reference/emitDecoratorMetadata_restArgs.js @@ -32,13 +32,13 @@ var A = (function () { function A() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } A.prototype.method = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } }; return A; @@ -57,13 +57,13 @@ var B = (function () { function B() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } B.prototype.method = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } }; return B; diff --git a/tests/baselines/reference/emitRestParametersFunction.js b/tests/baselines/reference/emitRestParametersFunction.js index 01116f2ac92..dff77ad4b55 100644 --- a/tests/baselines/reference/emitRestParametersFunction.js +++ b/tests/baselines/reference/emitRestParametersFunction.js @@ -6,7 +6,7 @@ function foo(x: number, y: string, ...rest) { } function bar() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } function foo(x, y) { diff --git a/tests/baselines/reference/emitRestParametersFunctionExpression.js b/tests/baselines/reference/emitRestParametersFunctionExpression.js index da87cc79f2d..55d4b505808 100644 --- a/tests/baselines/reference/emitRestParametersFunctionExpression.js +++ b/tests/baselines/reference/emitRestParametersFunctionExpression.js @@ -9,7 +9,7 @@ var funcExp3 = (function (...rest) { })() var funcExp = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; var funcExp1 = function (X) { @@ -21,12 +21,12 @@ var funcExp1 = function (X) { var funcExp2 = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; var funcExp3 = (function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } })(); diff --git a/tests/baselines/reference/emitRestParametersFunctionProperty.js b/tests/baselines/reference/emitRestParametersFunctionProperty.js index 4fd60a9269d..99d004daeb2 100644 --- a/tests/baselines/reference/emitRestParametersFunctionProperty.js +++ b/tests/baselines/reference/emitRestParametersFunctionProperty.js @@ -13,7 +13,7 @@ var obj2 = { func: function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } }; diff --git a/tests/baselines/reference/emitRestParametersMethod.js b/tests/baselines/reference/emitRestParametersMethod.js index 1dec771cde8..fed2138f36b 100644 --- a/tests/baselines/reference/emitRestParametersMethod.js +++ b/tests/baselines/reference/emitRestParametersMethod.js @@ -24,7 +24,7 @@ var C = (function () { C.prototype.bar = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; C.prototype.foo = function (x) { @@ -39,13 +39,13 @@ var D = (function () { function D() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } D.prototype.bar = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } }; D.prototype.foo = function (x) { diff --git a/tests/baselines/reference/emitSkipsThisWithRestParameter.js b/tests/baselines/reference/emitSkipsThisWithRestParameter.js index d1e99f9409d..5645a7e0636 100644 --- a/tests/baselines/reference/emitSkipsThisWithRestParameter.js +++ b/tests/baselines/reference/emitSkipsThisWithRestParameter.js @@ -11,7 +11,7 @@ function rebase(fn) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return fn.apply(this, [this].concat(args)); }; diff --git a/tests/baselines/reference/emptyAssignmentPatterns02_ES5.js b/tests/baselines/reference/emptyAssignmentPatterns02_ES5.js index 370e019104f..f5434d4a1c3 100644 --- a/tests/baselines/reference/emptyAssignmentPatterns02_ES5.js +++ b/tests/baselines/reference/emptyAssignmentPatterns02_ES5.js @@ -9,8 +9,8 @@ let x, y, z, a1, a2, a3; //// [emptyAssignmentPatterns02_ES5.js] var a; var x, y, z, a1, a2, a3; -(x = a.x, y = a.y, z = a.z, a); -(a1 = a[0], a2 = a[1], a3 = a[2], a); +(x = a.x, y = a.y, z = a.z); +(a1 = a[0], a2 = a[1], a3 = a[2]); //// [emptyAssignmentPatterns02_ES5.d.ts] diff --git a/tests/baselines/reference/emptyAssignmentPatterns04_ES5.js b/tests/baselines/reference/emptyAssignmentPatterns04_ES5.js index e6b3cc7e3f2..91559d18252 100644 --- a/tests/baselines/reference/emptyAssignmentPatterns04_ES5.js +++ b/tests/baselines/reference/emptyAssignmentPatterns04_ES5.js @@ -9,9 +9,8 @@ let x, y, z, a1, a2, a3; //// [emptyAssignmentPatterns04_ES5.js] var a; var x, y, z, a1, a2, a3; -(_a = a, x = _a.x, y = _a.y, z = _a.z, _a); -(_b = a, a1 = _b[0], a2 = _b[1], a3 = _b[2], _b); -var _a, _b; +(x = a.x, y = a.y, z = a.z); +(a1 = a[0], a2 = a[1], a3 = a[2]); //// [emptyAssignmentPatterns04_ES5.d.ts] diff --git a/tests/baselines/reference/enumAssignmentCompat3.js b/tests/baselines/reference/enumAssignmentCompat3.js index 62f05c18b5f..accaaa7a99e 100644 --- a/tests/baselines/reference/enumAssignmentCompat3.js +++ b/tests/baselines/reference/enumAssignmentCompat3.js @@ -92,78 +92,77 @@ merged2 = abc; // ok //// [enumAssignmentCompat3.js] var First; (function (First) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; E[E["c"] = 2] = "c"; - })(First.E || (First.E = {})); - var E = First.E; + })(E = First.E || (First.E = {})); })(First || (First = {})); var Abc; (function (Abc) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; E[E["c"] = 2] = "c"; - })(Abc.E || (Abc.E = {})); - var E = Abc.E; + })(E = Abc.E || (Abc.E = {})); + var Nope; (function (Nope) { Nope[Nope["a"] = 0] = "a"; Nope[Nope["b"] = 1] = "b"; Nope[Nope["c"] = 2] = "c"; - })(Abc.Nope || (Abc.Nope = {})); - var Nope = Abc.Nope; + })(Nope = Abc.Nope || (Abc.Nope = {})); })(Abc || (Abc = {})); var Abcd; (function (Abcd) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; E[E["c"] = 2] = "c"; E[E["d"] = 3] = "d"; - })(Abcd.E || (Abcd.E = {})); - var E = Abcd.E; + })(E = Abcd.E || (Abcd.E = {})); })(Abcd || (Abcd = {})); var Ab; (function (Ab) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; - })(Ab.E || (Ab.E = {})); - var E = Ab.E; + })(E = Ab.E || (Ab.E = {})); })(Ab || (Ab = {})); var Cd; (function (Cd) { + var E; (function (E) { E[E["c"] = 0] = "c"; E[E["d"] = 1] = "d"; - })(Cd.E || (Cd.E = {})); - var E = Cd.E; + })(E = Cd.E || (Cd.E = {})); })(Cd || (Cd = {})); var Decl; (function (Decl) { })(Decl || (Decl = {})); var Merged; (function (Merged) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; - })(Merged.E || (Merged.E = {})); - var E = Merged.E; + })(E = Merged.E || (Merged.E = {})); (function (E) { E[E["c"] = 3] = "c"; E[E["d"] = 4] = "d"; - })(Merged.E || (Merged.E = {})); - var E = Merged.E; + })(E = Merged.E || (Merged.E = {})); })(Merged || (Merged = {})); var Merged2; (function (Merged2) { + var E; (function (E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; E[E["c"] = 2] = "c"; - })(Merged2.E || (Merged2.E = {})); - var E = Merged2.E; + })(E = Merged2.E || (Merged2.E = {})); (function (E) { E.d = 5; })(E = Merged2.E || (Merged2.E = {})); diff --git a/tests/baselines/reference/enumAssignmentCompat4.js b/tests/baselines/reference/enumAssignmentCompat4.js index ad28324ce0f..35bc9319ce9 100644 --- a/tests/baselines/reference/enumAssignmentCompat4.js +++ b/tests/baselines/reference/enumAssignmentCompat4.js @@ -26,20 +26,20 @@ let broken = [ //// [enumAssignmentCompat4.js] var M; (function (M) { + var MyEnum; (function (MyEnum) { MyEnum[MyEnum["BAR"] = 0] = "BAR"; - })(M.MyEnum || (M.MyEnum = {})); - var MyEnum = M.MyEnum; + })(MyEnum = M.MyEnum || (M.MyEnum = {})); M.object2 = { foo: MyEnum.BAR }; })(M || (M = {})); var N; (function (N) { + var MyEnum; (function (MyEnum) { MyEnum[MyEnum["FOO"] = 0] = "FOO"; - })(N.MyEnum || (N.MyEnum = {})); - var MyEnum = N.MyEnum; + })(MyEnum = N.MyEnum || (N.MyEnum = {})); ; N.object1 = { foo: MyEnum.FOO diff --git a/tests/baselines/reference/enumFromExternalModule.js b/tests/baselines/reference/enumFromExternalModule.js index 77f0e643969..a6e9f6b6076 100644 --- a/tests/baselines/reference/enumFromExternalModule.js +++ b/tests/baselines/reference/enumFromExternalModule.js @@ -12,10 +12,10 @@ var x = f.Mode.Open; //// [enumFromExternalModule_0.js] "use strict"; +var Mode; (function (Mode) { Mode[Mode["Open"] = 0] = "Open"; -})(exports.Mode || (exports.Mode = {})); -var Mode = exports.Mode; +})(Mode = exports.Mode || (exports.Mode = {})); //// [enumFromExternalModule_1.js] "use strict"; /// diff --git a/tests/baselines/reference/enumLiteralAssignableToEnumInsideUnion.js b/tests/baselines/reference/enumLiteralAssignableToEnumInsideUnion.js index 8786745a504..077e5690dd8 100644 --- a/tests/baselines/reference/enumLiteralAssignableToEnumInsideUnion.js +++ b/tests/baselines/reference/enumLiteralAssignableToEnumInsideUnion.js @@ -32,35 +32,35 @@ const e5: Ka.Foo | boolean = Z.Foo.A; // ok //// [enumLiteralAssignableToEnumInsideUnion.js] var X; (function (X) { + var Foo; (function (Foo) { Foo[Foo["A"] = 0] = "A"; Foo[Foo["B"] = 1] = "B"; - })(X.Foo || (X.Foo = {})); - var Foo = X.Foo; + })(Foo = X.Foo || (X.Foo = {})); })(X || (X = {})); var Y; (function (Y) { + var Foo; (function (Foo) { Foo[Foo["A"] = 0] = "A"; Foo[Foo["B"] = 1] = "B"; - })(Y.Foo || (Y.Foo = {})); - var Foo = Y.Foo; + })(Foo = Y.Foo || (Y.Foo = {})); })(Y || (Y = {})); var Z; (function (Z) { + var Foo; (function (Foo) { Foo[Foo["A"] = 2] = "A"; Foo[Foo["B"] = 4] = "B"; - })(Z.Foo || (Z.Foo = {})); - var Foo = Z.Foo; + })(Foo = Z.Foo || (Z.Foo = {})); })(Z || (Z = {})); var Ka; (function (Ka) { + var Foo; (function (Foo) { Foo[Foo["A"] = 1024] = "A"; Foo[Foo["B"] = 2048] = "B"; - })(Ka.Foo || (Ka.Foo = {})); - var Foo = Ka.Foo; + })(Foo = Ka.Foo || (Ka.Foo = {})); })(Ka || (Ka = {})); var e0 = Y.Foo.A; // ok var e1 = Z.Foo.A; // not legal, Z is computed diff --git a/tests/baselines/reference/enumLiteralTypes1.types b/tests/baselines/reference/enumLiteralTypes1.types index 754574f547c..b2a466c777d 100644 --- a/tests/baselines/reference/enumLiteralTypes1.types +++ b/tests/baselines/reference/enumLiteralTypes1.types @@ -209,11 +209,11 @@ function f4(a: Choice.Yes, b: YesNo) { a++; >a++ : number ->a : Choice.Yes +>a : Choice b++; >b++ : number ->b : YesNo +>b : Choice } declare function g(x: Choice.Yes): string; diff --git a/tests/baselines/reference/enumLiteralTypes2.types b/tests/baselines/reference/enumLiteralTypes2.types index e27410a4dc7..6b881bee8c3 100644 --- a/tests/baselines/reference/enumLiteralTypes2.types +++ b/tests/baselines/reference/enumLiteralTypes2.types @@ -210,7 +210,7 @@ function f4(a: Choice.Yes, b: UnknownYesNo) { a++; >a++ : number ->a : Choice.Yes +>a : Choice b++; >b++ : number diff --git a/tests/baselines/reference/enumMerging.js b/tests/baselines/reference/enumMerging.js index d830b03cac9..c3fa7fffeb3 100644 --- a/tests/baselines/reference/enumMerging.js +++ b/tests/baselines/reference/enumMerging.js @@ -82,35 +82,33 @@ var M1; EImpl1[EImpl1["E"] = 2] = "E"; EImpl1[EImpl1["F"] = 3] = "F"; })(EImpl1 || (EImpl1 = {})); + var EConst1; (function (EConst1) { EConst1[EConst1["A"] = 3] = "A"; EConst1[EConst1["B"] = 2] = "B"; EConst1[EConst1["C"] = 1] = "C"; - })(M1.EConst1 || (M1.EConst1 = {})); - var EConst1 = M1.EConst1; + })(EConst1 = M1.EConst1 || (M1.EConst1 = {})); (function (EConst1) { EConst1[EConst1["D"] = 7] = "D"; EConst1[EConst1["E"] = 9] = "E"; EConst1[EConst1["F"] = 8] = "F"; - })(M1.EConst1 || (M1.EConst1 = {})); - var EConst1 = M1.EConst1; + })(EConst1 = M1.EConst1 || (M1.EConst1 = {})); var x = [EConst1.A, EConst1.B, EConst1.C, EConst1.D, EConst1.E, EConst1.F]; })(M1 || (M1 = {})); // Enum with only computed members across 2 declarations with the same root module var M2; (function (M2) { + var EComp2; (function (EComp2) { EComp2[EComp2["A"] = 'foo'.length] = "A"; EComp2[EComp2["B"] = 'foo'.length] = "B"; EComp2[EComp2["C"] = 'foo'.length] = "C"; - })(M2.EComp2 || (M2.EComp2 = {})); - var EComp2 = M2.EComp2; + })(EComp2 = M2.EComp2 || (M2.EComp2 = {})); (function (EComp2) { EComp2[EComp2["D"] = 'foo'.length] = "D"; EComp2[EComp2["E"] = 'foo'.length] = "E"; EComp2[EComp2["F"] = 'foo'.length] = "F"; - })(M2.EComp2 || (M2.EComp2 = {})); - var EComp2 = M2.EComp2; + })(EComp2 = M2.EComp2 || (M2.EComp2 = {})); var x = [EComp2.A, EComp2.B, EComp2.C, EComp2.D, EComp2.E, EComp2.F]; })(M2 || (M2 = {})); // Enum with initializer in only one of two declarations with constant members with the same root module @@ -130,41 +128,41 @@ var M3; // Enums with same name but different root module var M4; (function (M4) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; - })(M4.Color || (M4.Color = {})); - var Color = M4.Color; + })(Color = M4.Color || (M4.Color = {})); })(M4 || (M4 = {})); var M5; (function (M5) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; - })(M5.Color || (M5.Color = {})); - var Color = M5.Color; + })(Color = M5.Color || (M5.Color = {})); })(M5 || (M5 = {})); var M6; (function (M6) { var A; (function (A) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; - })(A.Color || (A.Color = {})); - var Color = A.Color; + })(Color = A.Color || (A.Color = {})); })(A = M6.A || (M6.A = {})); })(M6 || (M6 = {})); (function (M6) { var A; (function (A) { + var Color; (function (Color) { Color[Color["Yellow"] = 1] = "Yellow"; - })(A.Color || (A.Color = {})); - var Color = A.Color; + })(Color = A.Color || (A.Color = {})); })(A = M6.A || (M6.A = {})); var t = A.Color.Yellow; t = A.Color.Red; diff --git a/tests/baselines/reference/enumMergingErrors.js b/tests/baselines/reference/enumMergingErrors.js index c9b4aaef754..05482f48377 100644 --- a/tests/baselines/reference/enumMergingErrors.js +++ b/tests/baselines/reference/enumMergingErrors.js @@ -46,84 +46,84 @@ module M2 { // Enum with constant, computed, constant members split across 3 declarations with the same root module var M; (function (M) { + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; - })(M.E1 || (M.E1 = {})); - var E1 = M.E1; + })(E1 = M.E1 || (M.E1 = {})); + var E2; (function (E2) { E2[E2["C"] = 0] = "C"; - })(M.E2 || (M.E2 = {})); - var E2 = M.E2; + })(E2 = M.E2 || (M.E2 = {})); + var E3; (function (E3) { E3[E3["A"] = 0] = "A"; - })(M.E3 || (M.E3 = {})); - var E3 = M.E3; + })(E3 = M.E3 || (M.E3 = {})); })(M || (M = {})); (function (M) { + var E1; (function (E1) { E1[E1["B"] = 'foo'.length] = "B"; - })(M.E1 || (M.E1 = {})); - var E1 = M.E1; + })(E1 = M.E1 || (M.E1 = {})); + var E2; (function (E2) { E2[E2["B"] = 'foo'.length] = "B"; - })(M.E2 || (M.E2 = {})); - var E2 = M.E2; + })(E2 = M.E2 || (M.E2 = {})); + var E3; (function (E3) { E3[E3["C"] = 0] = "C"; - })(M.E3 || (M.E3 = {})); - var E3 = M.E3; + })(E3 = M.E3 || (M.E3 = {})); })(M || (M = {})); (function (M) { + var E1; (function (E1) { E1[E1["C"] = 0] = "C"; - })(M.E1 || (M.E1 = {})); - var E1 = M.E1; + })(E1 = M.E1 || (M.E1 = {})); + var E2; (function (E2) { E2[E2["A"] = 0] = "A"; - })(M.E2 || (M.E2 = {})); - var E2 = M.E2; + })(E2 = M.E2 || (M.E2 = {})); + var E3; (function (E3) { E3[E3["B"] = 'foo'.length] = "B"; - })(M.E3 || (M.E3 = {})); - var E3 = M.E3; + })(E3 = M.E3 || (M.E3 = {})); })(M || (M = {})); // Enum with no initializer in either declaration with constant members with the same root module var M1; (function (M1) { + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; - })(M1.E1 || (M1.E1 = {})); - var E1 = M1.E1; + })(E1 = M1.E1 || (M1.E1 = {})); })(M1 || (M1 = {})); (function (M1) { + var E1; (function (E1) { E1[E1["B"] = 0] = "B"; - })(M1.E1 || (M1.E1 = {})); - var E1 = M1.E1; + })(E1 = M1.E1 || (M1.E1 = {})); })(M1 || (M1 = {})); (function (M1) { + var E1; (function (E1) { E1[E1["C"] = 0] = "C"; - })(M1.E1 || (M1.E1 = {})); - var E1 = M1.E1; + })(E1 = M1.E1 || (M1.E1 = {})); })(M1 || (M1 = {})); // Enum with initializer in only one of three declarations with constant members with the same root module var M2; (function (M2) { + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; - })(M2.E1 || (M2.E1 = {})); - var E1 = M2.E1; + })(E1 = M2.E1 || (M2.E1 = {})); })(M2 || (M2 = {})); (function (M2) { + var E1; (function (E1) { E1[E1["B"] = 0] = "B"; - })(M2.E1 || (M2.E1 = {})); - var E1 = M2.E1; + })(E1 = M2.E1 || (M2.E1 = {})); })(M2 || (M2 = {})); (function (M2) { + var E1; (function (E1) { E1[E1["C"] = 0] = "C"; - })(M2.E1 || (M2.E1 = {})); - var E1 = M2.E1; + })(E1 = M2.E1 || (M2.E1 = {})); })(M2 || (M2 = {})); diff --git a/tests/baselines/reference/errorMessagesIntersectionTypes04.errors.txt b/tests/baselines/reference/errorMessagesIntersectionTypes04.errors.txt index 7582c68ecec..d2e81844da1 100644 --- a/tests/baselines/reference/errorMessagesIntersectionTypes04.errors.txt +++ b/tests/baselines/reference/errorMessagesIntersectionTypes04.errors.txt @@ -1,7 +1,8 @@ tests/cases/compiler/errorMessagesIntersectionTypes04.ts(17,5): error TS2322: Type 'A & B' is not assignable to type 'number'. tests/cases/compiler/errorMessagesIntersectionTypes04.ts(18,5): error TS2322: Type 'A & B' is not assignable to type 'boolean'. tests/cases/compiler/errorMessagesIntersectionTypes04.ts(19,5): error TS2322: Type 'A & B' is not assignable to type 'string'. -tests/cases/compiler/errorMessagesIntersectionTypes04.ts(21,5): error TS2322: Type 'number & boolean' is not assignable to type 'string'. +tests/cases/compiler/errorMessagesIntersectionTypes04.ts(21,5): error TS2322: Type '(number & true) | (number & false)' is not assignable to type 'string'. + Type 'number & true' is not assignable to type 'string'. ==== tests/cases/compiler/errorMessagesIntersectionTypes04.ts (4 errors) ==== @@ -33,5 +34,6 @@ tests/cases/compiler/errorMessagesIntersectionTypes04.ts(21,5): error TS2322: Ty str = num_and_bool; ~~~ -!!! error TS2322: Type 'number & boolean' is not assignable to type 'string'. +!!! error TS2322: Type '(number & true) | (number & false)' is not assignable to type 'string'. +!!! error TS2322: Type 'number & true' is not assignable to type 'string'. } \ No newline at end of file diff --git a/tests/baselines/reference/errorSuperCalls.errors.txt b/tests/baselines/reference/errorSuperCalls.errors.txt index 49bcb4b4d45..036367fd44b 100644 --- a/tests/baselines/reference/errorSuperCalls.errors.txt +++ b/tests/baselines/reference/errorSuperCalls.errors.txt @@ -7,6 +7,7 @@ tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(26,9): error T tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(30,16): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(34,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(38,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. +tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(46,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(46,14): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(58,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(62,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. @@ -14,7 +15,7 @@ tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(67,9): error T tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(71,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. -==== tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts (14 errors) ==== +==== tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts (15 errors) ==== //super call in class constructor with no base type class NoBase { constructor() { @@ -79,6 +80,8 @@ tests/cases/conformance/expressions/superCalls/errorSuperCalls.ts(71,9): error T //super call with type arguments constructor() { super(); + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. super(); diff --git a/tests/baselines/reference/es2017basicAsync.js b/tests/baselines/reference/es2017basicAsync.js new file mode 100644 index 00000000000..d0443c1899c --- /dev/null +++ b/tests/baselines/reference/es2017basicAsync.js @@ -0,0 +1,87 @@ +//// [es2017basicAsync.ts] + +async (): Promise => { + await 0; +} + +async function asyncFunc() { + await 0; +} + +const asyncArrowFunc = async (): Promise => { + await 0; +} + +async function asyncIIFE() { + await 0; + + await (async function(): Promise { + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { + await 1; + })(); + + await (async (): Promise => { + await 1; + })(); +} + +class AsyncClass { + asyncPropFunc = async function(): Promise { + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { + await 2; + } + + asyncPropArrowFunc = async (): Promise => { + await 2; + } + + async asyncMethod(): Promise { + await 2; + } +} + + +//// [es2017basicAsync.js] +async () => { + await 0; +}; +async function asyncFunc() { + await 0; +} +const asyncArrowFunc = async () => { + await 0; +}; +async function asyncIIFE() { + await 0; + await (async function () { + await 1; + })(); + await (async function asyncNamedFunc() { + await 1; + })(); + await (async () => { + await 1; + })(); +} +class AsyncClass { + constructor() { + this.asyncPropFunc = async function () { + await 2; + }; + this.asyncPropNamedFunc = async function namedFunc() { + await 2; + }; + this.asyncPropArrowFunc = async () => { + await 2; + }; + } + async asyncMethod() { + await 2; + } +} diff --git a/tests/baselines/reference/es2017basicAsync.symbols b/tests/baselines/reference/es2017basicAsync.symbols new file mode 100644 index 00000000000..d79faf1502a --- /dev/null +++ b/tests/baselines/reference/es2017basicAsync.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/es2017basicAsync.ts === + +async (): Promise => { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 0; +} + +async function asyncFunc() { +>asyncFunc : Symbol(asyncFunc, Decl(es2017basicAsync.ts, 3, 1)) + + await 0; +} + +const asyncArrowFunc = async (): Promise => { +>asyncArrowFunc : Symbol(asyncArrowFunc, Decl(es2017basicAsync.ts, 9, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 0; +} + +async function asyncIIFE() { +>asyncIIFE : Symbol(asyncIIFE, Decl(es2017basicAsync.ts, 11, 1)) + + await 0; + + await (async function(): Promise { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { +>asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es2017basicAsync.ts, 20, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); + + await (async (): Promise => { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); +} + +class AsyncClass { +>AsyncClass : Symbol(AsyncClass, Decl(es2017basicAsync.ts, 27, 1)) + + asyncPropFunc = async function(): Promise { +>asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es2017basicAsync.ts, 29, 18)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { +>asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es2017basicAsync.ts, 32, 5)) +>namedFunc : Symbol(namedFunc, Decl(es2017basicAsync.ts, 34, 24)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + asyncPropArrowFunc = async (): Promise => { +>asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es2017basicAsync.ts, 36, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + async asyncMethod(): Promise { +>asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es2017basicAsync.ts, 40, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } +} + diff --git a/tests/baselines/reference/es2017basicAsync.types b/tests/baselines/reference/es2017basicAsync.types new file mode 100644 index 00000000000..30d19cb4dfe --- /dev/null +++ b/tests/baselines/reference/es2017basicAsync.types @@ -0,0 +1,121 @@ +=== tests/cases/compiler/es2017basicAsync.ts === + +async (): Promise => { +>async (): Promise => { await 0;} : () => Promise +>Promise : Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +async function asyncFunc() { +>asyncFunc : () => Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +const asyncArrowFunc = async (): Promise => { +>asyncArrowFunc : () => Promise +>async (): Promise => { await 0;} : () => Promise +>Promise : Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +async function asyncIIFE() { +>asyncIIFE : () => Promise + + await 0; +>await 0 : 0 +>0 : 0 + + await (async function(): Promise { +>await (async function(): Promise { await 1; })() : void +>(async function(): Promise { await 1; })() : Promise +>(async function(): Promise { await 1; }) : () => Promise +>async function(): Promise { await 1; } : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); + + await (async function asyncNamedFunc(): Promise { +>await (async function asyncNamedFunc(): Promise { await 1; })() : void +>(async function asyncNamedFunc(): Promise { await 1; })() : Promise +>(async function asyncNamedFunc(): Promise { await 1; }) : () => Promise +>async function asyncNamedFunc(): Promise { await 1; } : () => Promise +>asyncNamedFunc : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); + + await (async (): Promise => { +>await (async (): Promise => { await 1; })() : void +>(async (): Promise => { await 1; })() : Promise +>(async (): Promise => { await 1; }) : () => Promise +>async (): Promise => { await 1; } : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); +} + +class AsyncClass { +>AsyncClass : AsyncClass + + asyncPropFunc = async function(): Promise { +>asyncPropFunc : () => Promise +>async function(): Promise { await 2; } : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + asyncPropNamedFunc = async function namedFunc(): Promise { +>asyncPropNamedFunc : () => Promise +>async function namedFunc(): Promise { await 2; } : () => Promise +>namedFunc : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + asyncPropArrowFunc = async (): Promise => { +>asyncPropArrowFunc : () => Promise +>async (): Promise => { await 2; } : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + async asyncMethod(): Promise { +>asyncMethod : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } +} + diff --git a/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.errors.txt b/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.errors.txt new file mode 100644 index 00000000000..137b76f660d --- /dev/null +++ b/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts(2,7): error TS8018: Octal literals are not allowed in enums members initializer. Use the syntax '-0o1'. +tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts(3,7): error TS8018: Octal literals are not allowed in enums members initializer. Use the syntax '0o2'. + + +==== tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts (2 errors) ==== + enum E { + x = -01, + ~~~ +!!! error TS8018: Octal literals are not allowed in enums members initializer. Use the syntax '-0o1'. + y = 02, + ~~ +!!! error TS8018: Octal literals are not allowed in enums members initializer. Use the syntax '0o2'. + } \ No newline at end of file diff --git a/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.js b/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.js new file mode 100644 index 00000000000..0098d841f2a --- /dev/null +++ b/tests/baselines/reference/es3-oldStyleOctalLiteralInEnums.js @@ -0,0 +1,12 @@ +//// [es3-oldStyleOctalLiteralInEnums.ts] +enum E { + x = -01, + y = 02, +} + +//// [es3-oldStyleOctalLiteralInEnums.js] +var E; +(function (E) { + E[E["x"] = -1] = "x"; + E[E["y"] = 2] = "y"; +})(E || (E = {})); diff --git a/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.errors.txt b/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.errors.txt new file mode 100644 index 00000000000..5fc9843989c --- /dev/null +++ b/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts(1,8): error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '0o10'. +tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts(2,8): error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '-0o20'. + + +==== tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts (2 errors) ==== + let x: 010; + ~~~ +!!! error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '0o10'. + let y: -020; + ~~~~ +!!! error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '-0o20'. + \ No newline at end of file diff --git a/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.js b/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.js new file mode 100644 index 00000000000..5ac915400cd --- /dev/null +++ b/tests/baselines/reference/es3-oldStyleOctalLiteralTypes.js @@ -0,0 +1,8 @@ +//// [es3-oldStyleOctalLiteralTypes.ts] +let x: 010; +let y: -020; + + +//// [es3-oldStyleOctalLiteralTypes.js] +var x; +var y; diff --git a/tests/baselines/reference/es3defaultAliasIsQuoted.js b/tests/baselines/reference/es3defaultAliasIsQuoted.js index 2ce6113b4fe..89fd0c47a7e 100644 --- a/tests/baselines/reference/es3defaultAliasIsQuoted.js +++ b/tests/baselines/reference/es3defaultAliasIsQuoted.js @@ -21,8 +21,8 @@ var Foo = (function () { } return Foo; }()); -exports.Foo = Foo; Foo.CONSTANT = "Foo"; +exports.Foo = Foo; function assert(value) { if (!value) throw new Error("Assertion failed!"); diff --git a/tests/baselines/reference/es5-asyncFunction.js b/tests/baselines/reference/es5-asyncFunction.js index 5123566dc8c..6f04c7ed7ef 100644 --- a/tests/baselines/reference/es5-asyncFunction.js +++ b/tests/baselines/reference/es5-asyncFunction.js @@ -14,7 +14,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/es5-asyncFunctionBinaryExpressions.js b/tests/baselines/reference/es5-asyncFunctionBinaryExpressions.js index a7aff630256..23a79cef343 100644 --- a/tests/baselines/reference/es5-asyncFunctionBinaryExpressions.js +++ b/tests/baselines/reference/es5-asyncFunctionBinaryExpressions.js @@ -169,8 +169,7 @@ function binaryLogicalAnd1() { switch (_b.label) { case 0: _a = x; - if (!_a) - return [3 /*break*/, 2]; + if (!_a) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a = (_b.sent()); diff --git a/tests/baselines/reference/es5-asyncFunctionConditionals.js b/tests/baselines/reference/es5-asyncFunctionConditionals.js index b42b0c07b0a..e9fc995fc2d 100644 --- a/tests/baselines/reference/es5-asyncFunctionConditionals.js +++ b/tests/baselines/reference/es5-asyncFunctionConditionals.js @@ -32,8 +32,7 @@ function conditional1() { return __generator(this, function (_b) { switch (_b.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a = _b.sent(); @@ -54,8 +53,7 @@ function conditional2() { return __generator(this, function (_b) { switch (_b.label) { case 0: - if (!x) - return [3 /*break*/, 1]; + if (!x) return [3 /*break*/, 1]; _a = y; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, z]; diff --git a/tests/baselines/reference/es5-asyncFunctionDoStatements.js b/tests/baselines/reference/es5-asyncFunctionDoStatements.js index 7151446dddf..32a7e9b0435 100644 --- a/tests/baselines/reference/es5-asyncFunctionDoStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionDoStatements.js @@ -97,8 +97,7 @@ function doStatement1() { _a.sent(); _a.label = 2; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -114,8 +113,7 @@ function doStatement2() { _a.label = 1; case 1: return [4 /*yield*/, y]; case 2: - if (_a.sent()) - return [3 /*break*/, 0]; + if (_a.sent()) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -141,8 +139,7 @@ function doStatement4() { _a.sent(); return [3 /*break*/, 2]; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -161,8 +158,7 @@ function doStatement5() { _a.sent(); _a.label = 2; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -176,8 +172,7 @@ function doStatement6() { case 0: return [3 /*break*/, 1]; case 1: return [4 /*yield*/, y]; case 2: - if (_a.sent()) - return [3 /*break*/, 0]; + if (_a.sent()) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -203,8 +198,7 @@ function doStatement8() { _a.sent(); return [3 /*break*/, 2]; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -223,8 +217,7 @@ function doStatement9() { _a.sent(); _a.label = 2; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -238,8 +231,7 @@ function doStatement10() { case 0: return [3 /*break*/, 1]; case 1: return [4 /*yield*/, y]; case 2: - if (_a.sent()) - return [3 /*break*/, 0]; + if (_a.sent()) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -265,8 +257,7 @@ function doStatement12() { _a.sent(); return [3 /*break*/, 3]; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -285,8 +276,7 @@ function doStatement13() { _a.sent(); _a.label = 2; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -300,8 +290,7 @@ function doStatement14() { case 0: return [3 /*break*/, 3]; case 1: return [4 /*yield*/, y]; case 2: - if (_a.sent()) - return [3 /*break*/, 0]; + if (_a.sent()) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -327,8 +316,7 @@ function doStatement16() { _a.sent(); return [3 /*break*/, 3]; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -347,8 +335,7 @@ function doStatement17() { _a.sent(); _a.label = 2; case 2: - if (y) - return [3 /*break*/, 0]; + if (y) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } @@ -362,8 +349,7 @@ function doStatement18() { case 0: return [3 /*break*/, 3]; case 1: return [4 /*yield*/, y]; case 2: - if (_a.sent()) - return [3 /*break*/, 0]; + if (_a.sent()) return [3 /*break*/, 0]; _a.label = 3; case 3: return [2 /*return*/]; } diff --git a/tests/baselines/reference/es5-asyncFunctionForInStatements.js b/tests/baselines/reference/es5-asyncFunctionForInStatements.js index 30946fca56d..ec6bfbb97e1 100644 --- a/tests/baselines/reference/es5-asyncFunctionForInStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionForInStatements.js @@ -62,8 +62,7 @@ function forInStatement1() { _i = 0; _c.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x = _a[_i]; z; _c.label = 3; @@ -87,8 +86,7 @@ function forInStatement2() { _i = 0; _c.label = 1; case 1: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x = _a[_i]; return [4 /*yield*/, z]; case 2: @@ -114,8 +112,7 @@ function forInStatement3() { _i = 0; _c.label = 1; case 1: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; return [4 /*yield*/, x]; case 2: (_c.sent()).a = _a[_i]; @@ -143,8 +140,7 @@ function forInStatement4() { _i = 0; _c.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x.a = _a[_i]; z; _c.label = 3; @@ -168,8 +164,7 @@ function forInStatement5() { _i = 0; _c.label = 1; case 1: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x.a = _a[_i]; return [4 /*yield*/, z]; case 2: @@ -208,8 +203,7 @@ function forInStatement7() { _i = 0; _c.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; b = _a[_i]; z; _c.label = 3; @@ -233,8 +227,7 @@ function forInStatement8() { _i = 0; _c.label = 1; case 1: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; c = _a[_i]; return [4 /*yield*/, z]; case 2: diff --git a/tests/baselines/reference/es5-asyncFunctionForOfStatements.js b/tests/baselines/reference/es5-asyncFunctionForOfStatements.js index e12f1e18d44..9cf1d0098b2 100644 --- a/tests/baselines/reference/es5-asyncFunctionForOfStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionForOfStatements.js @@ -102,8 +102,7 @@ function forOfStatement1() { _a = _b.sent(); _b.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x = _a[_i]; z; _b.label = 3; @@ -124,8 +123,7 @@ function forOfStatement2() { _i = 0, y_2 = y; _a.label = 1; case 1: - if (!(_i < y_2.length)) - return [3 /*break*/, 4]; + if (!(_i < y_2.length)) return [3 /*break*/, 4]; x = y_2[_i]; return [4 /*yield*/, z]; case 2: @@ -148,8 +146,7 @@ function forOfStatement3() { _i = 0, y_3 = y; _a.label = 1; case 1: - if (!(_i < y_3.length)) - return [3 /*break*/, 4]; + if (!(_i < y_3.length)) return [3 /*break*/, 4]; return [4 /*yield*/, x]; case 2: (_a.sent()).a = y_3[_i]; @@ -175,8 +172,7 @@ function forOfStatement4() { _a = _b.sent(); _b.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x.a = _a[_i]; z; _b.label = 3; @@ -197,8 +193,7 @@ function forOfStatement5() { _i = 0, y_4 = y; _a.label = 1; case 1: - if (!(_i < y_4.length)) - return [3 /*break*/, 4]; + if (!(_i < y_4.length)) return [3 /*break*/, 4]; x.a = y_4[_i]; return [4 /*yield*/, z]; case 2: @@ -236,8 +231,7 @@ function forOfStatement7() { _a = _b.sent(); _b.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; c = _a[_i]; z; _b.label = 3; @@ -258,8 +252,7 @@ function forOfStatement8() { _i = 0, y_6 = y; _a.label = 1; case 1: - if (!(_i < y_6.length)) - return [3 /*break*/, 4]; + if (!(_i < y_6.length)) return [3 /*break*/, 4]; d = y_6[_i]; return [4 /*yield*/, z]; case 2: @@ -285,8 +278,7 @@ function forOfStatement9() { _a = _b.sent(); _b.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x = _a[_i][0]; z; _b.label = 3; @@ -307,8 +299,7 @@ function forOfStatement10() { _i = 0, y_7 = y; _a.label = 1; case 1: - if (!(_i < y_7.length)) - return [3 /*break*/, 4]; + if (!(_i < y_7.length)) return [3 /*break*/, 4]; x = y_7[_i][0]; return [4 /*yield*/, z]; case 2: @@ -331,11 +322,9 @@ function forOfStatement11() { _i = 0, y_8 = y; _c.label = 1; case 1: - if (!(_i < y_8.length)) - return [3 /*break*/, 6]; + if (!(_i < y_8.length)) return [3 /*break*/, 6]; _b = y_8[_i][0]; - if (!(_b === void 0)) - return [3 /*break*/, 3]; + if (!(_b === void 0)) return [3 /*break*/, 3]; return [4 /*yield*/, a]; case 2: _a = _c.sent(); @@ -367,8 +356,7 @@ function forOfStatement12() { _a = _c.sent(); _c.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; _b = _a[_i][0], x = _b === void 0 ? a : _b; z; _c.label = 3; @@ -389,8 +377,7 @@ function forOfStatement13() { _i = 0, y_9 = y; _b.label = 1; case 1: - if (!(_i < y_9.length)) - return [3 /*break*/, 4]; + if (!(_i < y_9.length)) return [3 /*break*/, 4]; _a = y_9[_i][0], x = _a === void 0 ? a : _a; return [4 /*yield*/, z]; case 2: @@ -416,8 +403,7 @@ function forOfStatement14() { _a = _b.sent(); _b.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; x = _a[_i].x; z; _b.label = 3; @@ -438,8 +424,7 @@ function forOfStatement15() { _i = 0, y_10 = y; _a.label = 1; case 1: - if (!(_i < y_10.length)) - return [3 /*break*/, 4]; + if (!(_i < y_10.length)) return [3 /*break*/, 4]; x = y_10[_i].x; return [4 /*yield*/, z]; case 2: @@ -462,11 +447,9 @@ function forOfStatement16() { _i = 0, y_11 = y; _c.label = 1; case 1: - if (!(_i < y_11.length)) - return [3 /*break*/, 6]; + if (!(_i < y_11.length)) return [3 /*break*/, 6]; _b = y_11[_i].x; - if (!(_b === void 0)) - return [3 /*break*/, 3]; + if (!(_b === void 0)) return [3 /*break*/, 3]; return [4 /*yield*/, a]; case 2: _a = _c.sent(); @@ -498,8 +481,7 @@ function forOfStatement17() { _a = _c.sent(); _c.label = 2; case 2: - if (!(_i < _a.length)) - return [3 /*break*/, 4]; + if (!(_i < _a.length)) return [3 /*break*/, 4]; _b = _a[_i].x, x = _b === void 0 ? a : _b; z; _c.label = 3; @@ -520,8 +502,7 @@ function forOfStatement18() { _i = 0, y_12 = y; _b.label = 1; case 1: - if (!(_i < y_12.length)) - return [3 /*break*/, 4]; + if (!(_i < y_12.length)) return [3 /*break*/, 4]; _a = y_12[_i].x, x = _a === void 0 ? a : _a; return [4 /*yield*/, z]; case 2: diff --git a/tests/baselines/reference/es5-asyncFunctionForStatements.js b/tests/baselines/reference/es5-asyncFunctionForStatements.js index e02d20c7864..aad8a1f46ef 100644 --- a/tests/baselines/reference/es5-asyncFunctionForStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionForStatements.js @@ -49,8 +49,7 @@ function forStatement1() { _a.sent(); _a.label = 2; case 2: - if (!y) - return [3 /*break*/, 4]; + if (!y) return [3 /*break*/, 4]; a; _a.label = 3; case 3: @@ -70,8 +69,7 @@ function forStatement2() { _a.label = 1; case 1: return [4 /*yield*/, y]; case 2: - if (!_a.sent()) - return [3 /*break*/, 4]; + if (!_a.sent()) return [3 /*break*/, 4]; a; _a.label = 3; case 3: @@ -90,8 +88,7 @@ function forStatement3() { x; _a.label = 1; case 1: - if (!y) - return [3 /*break*/, 4]; + if (!y) return [3 /*break*/, 4]; a; _a.label = 2; case 2: return [4 /*yield*/, z]; @@ -111,8 +108,7 @@ function forStatement4() { x; _a.label = 1; case 1: - if (!y) - return [3 /*break*/, 4]; + if (!y) return [3 /*break*/, 4]; return [4 /*yield*/, a]; case 2: _a.sent(); diff --git a/tests/baselines/reference/es5-asyncFunctionIfStatements.js b/tests/baselines/reference/es5-asyncFunctionIfStatements.js index 7ac35c995e7..39fc2ade726 100644 --- a/tests/baselines/reference/es5-asyncFunctionIfStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionIfStatements.js @@ -36,8 +36,7 @@ function ifStatement2() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -55,8 +54,7 @@ function ifStatement3() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 1]; + if (!x) return [3 /*break*/, 1]; y; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, z]; diff --git a/tests/baselines/reference/es5-asyncFunctionNestedLoops.js b/tests/baselines/reference/es5-asyncFunctionNestedLoops.js index 28ccc288b7e..36408e241a0 100644 --- a/tests/baselines/reference/es5-asyncFunctionNestedLoops.js +++ b/tests/baselines/reference/es5-asyncFunctionNestedLoops.js @@ -19,8 +19,7 @@ function nestedLoops() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); diff --git a/tests/baselines/reference/es5-asyncFunctionNewExpressions.js b/tests/baselines/reference/es5-asyncFunctionNewExpressions.js index 486bf0fdd7f..0fb1140f129 100644 --- a/tests/baselines/reference/es5-asyncFunctionNewExpressions.js +++ b/tests/baselines/reference/es5-asyncFunctionNewExpressions.js @@ -119,7 +119,7 @@ function newExpression2() { _a = x.bind; return [4 /*yield*/, y]; case 1: - new (_a.apply(x, [_c.sent(), z]))(); + new (_a.apply(x, [void 0, _c.sent(), z]))(); return [2 /*return*/]; } }); @@ -132,7 +132,7 @@ function newExpression3() { switch (_c.label) { case 0: _a = x.bind; - _b = [y]; + _b = [void 0, y]; return [4 /*yield*/, z]; case 1: new (_a.apply(x, _b.concat([_c.sent()])))(); @@ -280,7 +280,7 @@ function newExpression13() { _b = (_a = x.a).bind; return [4 /*yield*/, y]; case 1: - new (_b.apply(_a, [_d.sent(), z]))(); + new (_b.apply(_a, [void 0, _d.sent(), z]))(); return [2 /*return*/]; } }); @@ -293,7 +293,7 @@ function newExpression14() { switch (_d.label) { case 0: _b = (_a = x.a).bind; - _c = [y]; + _c = [void 0, y]; return [4 /*yield*/, z]; case 1: new (_b.apply(_a, _c.concat([_d.sent()])))(); @@ -362,7 +362,7 @@ function newExpression19() { _b = (_a = x[a]).bind; return [4 /*yield*/, y]; case 1: - new (_b.apply(_a, [_d.sent(), z]))(); + new (_b.apply(_a, [void 0, _d.sent(), z]))(); return [2 /*return*/]; } }); @@ -375,7 +375,7 @@ function newExpression20() { switch (_d.label) { case 0: _b = (_a = x[a]).bind; - _c = [y]; + _c = [void 0, y]; return [4 /*yield*/, z]; case 1: new (_b.apply(_a, _c.concat([_d.sent()])))(); diff --git a/tests/baselines/reference/es5-asyncFunctionWhileStatements.js b/tests/baselines/reference/es5-asyncFunctionWhileStatements.js index c85aabb01e3..750673fb6c4 100644 --- a/tests/baselines/reference/es5-asyncFunctionWhileStatements.js +++ b/tests/baselines/reference/es5-asyncFunctionWhileStatements.js @@ -94,8 +94,7 @@ function whileStatement1() { switch (_a.label) { case 0: return [4 /*yield*/, x]; case 1: - if (!_a.sent()) - return [3 /*break*/, 2]; + if (!_a.sent()) return [3 /*break*/, 2]; y; return [3 /*break*/, 0]; case 2: return [2 /*return*/]; @@ -108,8 +107,7 @@ function whileStatement2() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -135,8 +133,7 @@ function whileStatement4() { switch (_a.label) { case 0: return [4 /*yield*/, x]; case 1: - if (!_a.sent()) - return [3 /*break*/, 2]; + if (!_a.sent()) return [3 /*break*/, 2]; return [3 /*break*/, 0]; case 2: return [2 /*return*/]; } @@ -148,8 +145,7 @@ function whileStatement5() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -164,8 +160,7 @@ function whileStatement6() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; if (1) return [3 /*break*/, 0]; return [4 /*yield*/, y]; @@ -193,8 +188,7 @@ function whileStatement8() { switch (_a.label) { case 0: return [4 /*yield*/, x]; case 1: - if (!_a.sent()) - return [3 /*break*/, 2]; + if (!_a.sent()) return [3 /*break*/, 2]; return [3 /*break*/, 0]; case 2: return [2 /*return*/]; } @@ -206,8 +200,7 @@ function whileStatement9() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -222,8 +215,7 @@ function whileStatement10() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; if (1) return [3 /*break*/, 0]; return [4 /*yield*/, y]; @@ -251,8 +243,7 @@ function whileStatement12() { switch (_a.label) { case 0: return [4 /*yield*/, x]; case 1: - if (!_a.sent()) - return [3 /*break*/, 2]; + if (!_a.sent()) return [3 /*break*/, 2]; return [3 /*break*/, 2]; case 2: return [2 /*return*/]; } @@ -264,8 +255,7 @@ function whileStatement13() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -280,8 +270,7 @@ function whileStatement14() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; if (1) return [3 /*break*/, 2]; return [4 /*yield*/, y]; @@ -309,8 +298,7 @@ function whileStatement16() { switch (_a.label) { case 0: return [4 /*yield*/, x]; case 1: - if (!_a.sent()) - return [3 /*break*/, 2]; + if (!_a.sent()) return [3 /*break*/, 2]; return [3 /*break*/, 2]; case 2: return [2 /*return*/]; } @@ -322,8 +310,7 @@ function whileStatement17() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; return [4 /*yield*/, y]; case 1: _a.sent(); @@ -338,8 +325,7 @@ function whileStatement18() { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!x) - return [3 /*break*/, 2]; + if (!x) return [3 /*break*/, 2]; if (1) return [3 /*break*/, 2]; return [4 /*yield*/, y]; diff --git a/tests/baselines/reference/es5-importHelpersAsyncFunctions.js b/tests/baselines/reference/es5-importHelpersAsyncFunctions.js index 0fd308cee3b..71c4af8d559 100644 --- a/tests/baselines/reference/es5-importHelpersAsyncFunctions.js +++ b/tests/baselines/reference/es5-importHelpersAsyncFunctions.js @@ -34,7 +34,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.errors.txt b/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.errors.txt new file mode 100644 index 00000000000..a504568ce20 --- /dev/null +++ b/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts(2,7): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o1'. +tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts(3,7): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o2'. + + +==== tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts (2 errors) ==== + enum E { + x = -01, + ~~~ +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o1'. + y = 02, + ~~ +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o2'. + } \ No newline at end of file diff --git a/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.js b/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.js new file mode 100644 index 00000000000..71f718054fe --- /dev/null +++ b/tests/baselines/reference/es5-oldStyleOctalLiteralInEnums.js @@ -0,0 +1,12 @@ +//// [es5-oldStyleOctalLiteralInEnums.ts] +enum E { + x = -01, + y = 02, +} + +//// [es5-oldStyleOctalLiteralInEnums.js] +var E; +(function (E) { + E[E["x"] = -1] = "x"; + E[E["y"] = 2] = "y"; +})(E || (E = {})); diff --git a/tests/baselines/reference/es5ExportEquals.js b/tests/baselines/reference/es5ExportEquals.js index 4697c61976b..3a1ae6fe242 100644 --- a/tests/baselines/reference/es5ExportEquals.js +++ b/tests/baselines/reference/es5ExportEquals.js @@ -8,7 +8,6 @@ export = f; //// [es5ExportEquals.js] "use strict"; function f() { } -exports.f = f; module.exports = f; diff --git a/tests/baselines/reference/es5ModuleInternalNamedImports.js b/tests/baselines/reference/es5ModuleInternalNamedImports.js index 2fcbd5a53d8..cc596980889 100644 --- a/tests/baselines/reference/es5ModuleInternalNamedImports.js +++ b/tests/baselines/reference/es5ModuleInternalNamedImports.js @@ -59,9 +59,9 @@ define(["require", "exports"], function (require, exports) { function M_F() { } M.M_F = M_F; // enum + var M_E; (function (M_E) { - })(M.M_E || (M.M_E = {})); - var M_E = M.M_E; + })(M_E = M.M_E || (M.M_E = {})); // alias M.M_A = M_M; })(M = exports.M || (exports.M = {})); diff --git a/tests/baselines/reference/es6ClassTest2.js b/tests/baselines/reference/es6ClassTest2.js index de5657b087e..533b332422d 100644 --- a/tests/baselines/reference/es6ClassTest2.js +++ b/tests/baselines/reference/es6ClassTest2.js @@ -236,7 +236,7 @@ var SplatMonster = (function () { function SplatMonster() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } SplatMonster.prototype.roar = function (name) { diff --git a/tests/baselines/reference/es6ClassTest5.js b/tests/baselines/reference/es6ClassTest5.js index b909fac58b5..7d4238fda65 100644 --- a/tests/baselines/reference/es6ClassTest5.js +++ b/tests/baselines/reference/es6ClassTest5.js @@ -23,7 +23,7 @@ var C1T5 = (function () { }()); var bigClass = (function () { function bigClass() { - this.break = 1; + this["break"] = 1; } return bigClass; }()); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js index d62cfbc2872..0a0e028b696 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js @@ -16,7 +16,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = a; //// [es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_1.js] "use strict"; -var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"), nameSpaceBinding = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1; +var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"); var x = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1.default; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js index c19f68463fa..5f2cb4e97e0 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js @@ -19,7 +19,6 @@ define(["require", "exports"], function (require, exports) { //// [client.js] define(["require", "exports", "server"], function (require, exports, server_1) { "use strict"; - var nameSpaceBinding = server_1; exports.x = server_1.default; }); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js index 20abd2e6132..60bdc654842 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js @@ -18,7 +18,7 @@ var a = (function () { exports.a = a; //// [client.js] "use strict"; -var server_1 = require("./server"), nameSpaceBinding = server_1; +var nameSpaceBinding = require("./server"); exports.x = new nameSpaceBinding.a(); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js index 5a2f1f35290..8752157eddd 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js @@ -23,7 +23,6 @@ define(["require", "exports"], function (require, exports) { //// [client.js] define(["require", "exports", "server"], function (require, exports, server_1) { "use strict"; - var nameSpaceBinding = server_1; exports.x = new server_1.default(); }); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js index 2639291d854..9d11e154755 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js @@ -13,7 +13,7 @@ var x: number = nameSpaceBinding.a; exports.a = 10; //// [es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_1.js] "use strict"; -var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"), nameSpaceBinding = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1; +var nameSpaceBinding = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"); var x = nameSpaceBinding.a; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js index f417a086df7..e16ebf99957 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js @@ -13,7 +13,7 @@ export var x: number = nameSpaceBinding.a; exports.a = 10; //// [client.js] "use strict"; -var server_1 = require("./server"), nameSpaceBinding = server_1; +var nameSpaceBinding = require("./server"); exports.x = nameSpaceBinding.a; diff --git a/tests/baselines/reference/es6ModuleConstEnumDeclaration2.js b/tests/baselines/reference/es6ModuleConstEnumDeclaration2.js index 539ec121b6b..3e4475f2ffa 100644 --- a/tests/baselines/reference/es6ModuleConstEnumDeclaration2.js +++ b/tests/baselines/reference/es6ModuleConstEnumDeclaration2.js @@ -63,12 +63,12 @@ var x = 0 /* a */; var y = 0 /* x */; export var m1; (function (m1) { + var e3; (function (e3) { e3[e3["a"] = 0] = "a"; e3[e3["b"] = 1] = "b"; e3[e3["c"] = 2] = "c"; - })(m1.e3 || (m1.e3 = {})); - var e3 = m1.e3; + })(e3 = m1.e3 || (m1.e3 = {})); var e4; (function (e4) { e4[e4["x"] = 0] = "x"; @@ -82,12 +82,12 @@ export var m1; })(m1 || (m1 = {})); var m2; (function (m2) { + var e5; (function (e5) { e5[e5["a"] = 0] = "a"; e5[e5["b"] = 1] = "b"; e5[e5["c"] = 2] = "c"; - })(m2.e5 || (m2.e5 = {})); - var e5 = m2.e5; + })(e5 = m2.e5 || (m2.e5 = {})); var e6; (function (e6) { e6[e6["x"] = 0] = "x"; diff --git a/tests/baselines/reference/es6ModuleEnumDeclaration.js b/tests/baselines/reference/es6ModuleEnumDeclaration.js index 30c382a4508..91ba2efe8d3 100644 --- a/tests/baselines/reference/es6ModuleEnumDeclaration.js +++ b/tests/baselines/reference/es6ModuleEnumDeclaration.js @@ -62,12 +62,12 @@ var x = e1.a; var y = e2.x; export var m1; (function (m1) { + var e3; (function (e3) { e3[e3["a"] = 0] = "a"; e3[e3["b"] = 1] = "b"; e3[e3["c"] = 2] = "c"; - })(m1.e3 || (m1.e3 = {})); - var e3 = m1.e3; + })(e3 = m1.e3 || (m1.e3 = {})); var e4; (function (e4) { e4[e4["x"] = 0] = "x"; @@ -81,12 +81,12 @@ export var m1; })(m1 || (m1 = {})); var m2; (function (m2) { + var e5; (function (e5) { e5[e5["a"] = 0] = "a"; e5[e5["b"] = 1] = "b"; e5[e5["c"] = 2] = "c"; - })(m2.e5 || (m2.e5 = {})); - var e5 = m2.e5; + })(e5 = m2.e5 || (m2.e5 = {})); var e6; (function (e6) { e6[e6["x"] = 0] = "x"; diff --git a/tests/baselines/reference/es6ModuleInternalNamedImports.js b/tests/baselines/reference/es6ModuleInternalNamedImports.js index 22d15b9fd61..fe2e0217795 100644 --- a/tests/baselines/reference/es6ModuleInternalNamedImports.js +++ b/tests/baselines/reference/es6ModuleInternalNamedImports.js @@ -50,9 +50,9 @@ export var M; function M_F() { } M.M_F = M_F; // enum + var M_E; (function (M_E) { - })(M.M_E || (M.M_E = {})); - var M_E = M.M_E; + })(M_E = M.M_E || (M.M_E = {})); // alias M.M_A = M_M; })(M || (M = {})); diff --git a/tests/baselines/reference/es6ModuleInternalNamedImports2.js b/tests/baselines/reference/es6ModuleInternalNamedImports2.js index 35eabc9a65e..93d8f40c1d2 100644 --- a/tests/baselines/reference/es6ModuleInternalNamedImports2.js +++ b/tests/baselines/reference/es6ModuleInternalNamedImports2.js @@ -52,9 +52,9 @@ export var M; function M_F() { } M.M_F = M_F; // enum + var M_E; (function (M_E) { - })(M.M_E || (M.M_E = {})); - var M_E = M.M_E; + })(M_E = M.M_E || (M.M_E = {})); // alias M.M_A = M_M; })(M || (M = {})); diff --git a/tests/baselines/reference/es6modulekindWithES5Target.js b/tests/baselines/reference/es6modulekindWithES5Target.js index 10d9cd2e36f..66967cbc89f 100644 --- a/tests/baselines/reference/es6modulekindWithES5Target.js +++ b/tests/baselines/reference/es6modulekindWithES5Target.js @@ -27,13 +27,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -export var C = (function () { +var C = (function () { function C() { this.p = 1; } C.prototype.method = function () { }; return C; }()); +export { C }; C.s = 0; export { C as C2 }; var D = (function () { diff --git a/tests/baselines/reference/es6modulekindWithES5Target11.js b/tests/baselines/reference/es6modulekindWithES5Target11.js index 1268c33697a..4ec0802a5f5 100644 --- a/tests/baselines/reference/es6modulekindWithES5Target11.js +++ b/tests/baselines/reference/es6modulekindWithES5Target11.js @@ -16,16 +16,17 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var C = (function () { +var C = C_1 = (function () { function C() { this.p = 1; } - C.x = function () { return C.y; }; + C.x = function () { return C_1.y; }; C.prototype.method = function () { }; return C; }()); C.y = 1; -C = __decorate([ +C = C_1 = __decorate([ foo ], C); export default C; +var C_1; diff --git a/tests/baselines/reference/es6modulekindWithES5Target12.js b/tests/baselines/reference/es6modulekindWithES5Target12.js index 316718e6f80..74646f73e55 100644 --- a/tests/baselines/reference/es6modulekindWithES5Target12.js +++ b/tests/baselines/reference/es6modulekindWithES5Target12.js @@ -38,11 +38,12 @@ export namespace F { } //// [es6modulekindWithES5Target12.js] -export var C = (function () { +var C = (function () { function C() { } return C; }()); +export { C }; (function (C) { C.x = 1; })(C || (C = {})); diff --git a/tests/baselines/reference/es6modulekindWithES5Target6.js b/tests/baselines/reference/es6modulekindWithES5Target6.js index d305c60e54e..cff2327dacb 100644 --- a/tests/baselines/reference/es6modulekindWithES5Target6.js +++ b/tests/baselines/reference/es6modulekindWithES5Target6.js @@ -17,7 +17,7 @@ export function f1(d) { export function f2() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } export default function f3(d) { diff --git a/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.js b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.js new file mode 100644 index 00000000000..218d760d6c5 --- /dev/null +++ b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.js @@ -0,0 +1,39 @@ +//// [exhaustiveSwitchWithWideningLiteralTypes.ts] + +// Repro from #12529 + +class A { + readonly kind = "A"; // (property) A.kind: "A" +} + +class B { + readonly kind = "B"; // (property) B.kind: "B" +} + +function f(value: A | B): number { + switch(value.kind) { + case "A": return 0; + case "B": return 1; + } +} + +//// [exhaustiveSwitchWithWideningLiteralTypes.js] +// Repro from #12529 +var A = (function () { + function A() { + this.kind = "A"; // (property) A.kind: "A" + } + return A; +}()); +var B = (function () { + function B() { + this.kind = "B"; // (property) B.kind: "B" + } + return B; +}()); +function f(value) { + switch (value.kind) { + case "A": return 0; + case "B": return 1; + } +} diff --git a/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.symbols b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.symbols new file mode 100644 index 00000000000..929a394dc7b --- /dev/null +++ b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/exhaustiveSwitchWithWideningLiteralTypes.ts === + +// Repro from #12529 + +class A { +>A : Symbol(A, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 0, 0)) + + readonly kind = "A"; // (property) A.kind: "A" +>kind : Symbol(A.kind, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 3, 9)) +} + +class B { +>B : Symbol(B, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 5, 1)) + + readonly kind = "B"; // (property) B.kind: "B" +>kind : Symbol(B.kind, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 7, 9)) +} + +function f(value: A | B): number { +>f : Symbol(f, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 9, 1)) +>value : Symbol(value, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 11, 11)) +>A : Symbol(A, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 0, 0)) +>B : Symbol(B, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 5, 1)) + + switch(value.kind) { +>value.kind : Symbol(kind, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 3, 9), Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 7, 9)) +>value : Symbol(value, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 11, 11)) +>kind : Symbol(kind, Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 3, 9), Decl(exhaustiveSwitchWithWideningLiteralTypes.ts, 7, 9)) + + case "A": return 0; + case "B": return 1; + } +} diff --git a/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.types b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.types new file mode 100644 index 00000000000..3955c80ff1e --- /dev/null +++ b/tests/baselines/reference/exhaustiveSwitchWithWideningLiteralTypes.types @@ -0,0 +1,40 @@ +=== tests/cases/compiler/exhaustiveSwitchWithWideningLiteralTypes.ts === + +// Repro from #12529 + +class A { +>A : A + + readonly kind = "A"; // (property) A.kind: "A" +>kind : "A" +>"A" : "A" +} + +class B { +>B : B + + readonly kind = "B"; // (property) B.kind: "B" +>kind : "B" +>"B" : "B" +} + +function f(value: A | B): number { +>f : (value: A | B) => number +>value : A | B +>A : A +>B : B + + switch(value.kind) { +>value.kind : "A" | "B" +>value : A | B +>kind : "A" | "B" + + case "A": return 0; +>"A" : "A" +>0 : 0 + + case "B": return 1; +>"B" : "B" +>1 : 1 + } +} diff --git a/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.js b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.js new file mode 100644 index 00000000000..8715fd9eaca --- /dev/null +++ b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.js @@ -0,0 +1,16 @@ +//// [explicitAnyAfterSpreadNoImplicitAnyError.ts] +({ a: [], ...(null as any) }); +let x: any; + + +//// [explicitAnyAfterSpreadNoImplicitAnyError.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +(__assign({ a: [] }, null)); +var x; diff --git a/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.symbols b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.symbols new file mode 100644 index 00000000000..c53845d99aa --- /dev/null +++ b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/explicitAnyAfterSpreadNoImplicitAnyError.ts === +({ a: [], ...(null as any) }); +>a : Symbol(a, Decl(explicitAnyAfterSpreadNoImplicitAnyError.ts, 0, 2)) + +let x: any; +>x : Symbol(x, Decl(explicitAnyAfterSpreadNoImplicitAnyError.ts, 1, 3)) + diff --git a/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.types b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.types new file mode 100644 index 00000000000..5e463e77bbb --- /dev/null +++ b/tests/baselines/reference/explicitAnyAfterSpreadNoImplicitAnyError.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/explicitAnyAfterSpreadNoImplicitAnyError.ts === +({ a: [], ...(null as any) }); +>({ a: [], ...(null as any) }) : any +>{ a: [], ...(null as any) } : any +>a : undefined[] +>[] : undefined[] +>(null as any) : any +>null as any : any +>null : null + +let x: any; +>x : any + diff --git a/tests/baselines/reference/exportAsNamespace.d.symbols b/tests/baselines/reference/exportAsNamespace.d.symbols new file mode 100644 index 00000000000..ca65cb2574e --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace.d.symbols @@ -0,0 +1,9 @@ +=== tests/cases/compiler/exportAsNamespace.d.ts === +// issue: https://github.com/Microsoft/TypeScript/issues/11545 + +export var X; +>X : Symbol(X, Decl(exportAsNamespace.d.ts, 2, 10)) + +export as namespace N +>N : Symbol(N, Decl(exportAsNamespace.d.ts, 2, 13)) + diff --git a/tests/baselines/reference/exportAsNamespace.d.types b/tests/baselines/reference/exportAsNamespace.d.types new file mode 100644 index 00000000000..706857bf8ed --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace.d.types @@ -0,0 +1,9 @@ +=== tests/cases/compiler/exportAsNamespace.d.ts === +// issue: https://github.com/Microsoft/TypeScript/issues/11545 + +export var X; +>X : any + +export as namespace N +>N : typeof N + diff --git a/tests/baselines/reference/exportAssignmentAndDeclaration.js b/tests/baselines/reference/exportAssignmentAndDeclaration.js index 9e87d733c6b..df1f2ef0d0a 100644 --- a/tests/baselines/reference/exportAssignmentAndDeclaration.js +++ b/tests/baselines/reference/exportAssignmentAndDeclaration.js @@ -13,12 +13,12 @@ export = C1; //// [foo_0.js] define(["require", "exports"], function (require, exports) { "use strict"; + var E1; (function (E1) { E1[E1["A"] = 0] = "A"; E1[E1["B"] = 1] = "B"; E1[E1["C"] = 2] = "C"; - })(exports.E1 || (exports.E1 = {})); - var E1 = exports.E1; + })(E1 = exports.E1 || (exports.E1 = {})); var C1 = (function () { function C1() { } diff --git a/tests/baselines/reference/exportAssignmentWithExports.js b/tests/baselines/reference/exportAssignmentWithExports.js index 626e7881548..8441b7b4320 100644 --- a/tests/baselines/reference/exportAssignmentWithExports.js +++ b/tests/baselines/reference/exportAssignmentWithExports.js @@ -10,7 +10,6 @@ var C = (function () { } return C; }()); -exports.C = C; var D = (function () { function D() { } diff --git a/tests/baselines/reference/exportCodeGen.js b/tests/baselines/reference/exportCodeGen.js index 41564c35d1a..d72c633731d 100644 --- a/tests/baselines/reference/exportCodeGen.js +++ b/tests/baselines/reference/exportCodeGen.js @@ -90,10 +90,10 @@ var D; // validate all exportable statements var E; (function (E) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; - })(E.Color || (E.Color = {})); - var Color = E.Color; + })(Color = E.Color || (E.Color = {})); function fn() { } E.fn = fn; var C = (function () { diff --git a/tests/baselines/reference/exportDefaultAsyncFunction.js b/tests/baselines/reference/exportDefaultAsyncFunction.js index 22f686b6ec8..9931d1f1eea 100644 --- a/tests/baselines/reference/exportDefaultAsyncFunction.js +++ b/tests/baselines/reference/exportDefaultAsyncFunction.js @@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; export default function foo() { diff --git a/tests/baselines/reference/exportDefaultAsyncFunction2.js b/tests/baselines/reference/exportDefaultAsyncFunction2.js index aed6eb6c879..7b79bed9408 100644 --- a/tests/baselines/reference/exportDefaultAsyncFunction2.js +++ b/tests/baselines/reference/exportDefaultAsyncFunction2.js @@ -40,7 +40,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; export default () => __awaiter(this, void 0, void 0, function* () { return 0; }); diff --git a/tests/baselines/reference/exportDefaultInJsFile01.errors.txt b/tests/baselines/reference/exportDefaultInJsFile01.errors.txt index 34035e1e14e..0565c8bd61e 100644 --- a/tests/baselines/reference/exportDefaultInJsFile01.errors.txt +++ b/tests/baselines/reference/exportDefaultInJsFile01.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/conformance/salsa/myFile01.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/conformance/salsa/myFile01.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/conformance/salsa/myFile01.js (0 errors) ==== export default "hello"; \ No newline at end of file diff --git a/tests/baselines/reference/exportDefaultInJsFile02.errors.txt b/tests/baselines/reference/exportDefaultInJsFile02.errors.txt index 5e17306e066..a74fbacfcfd 100644 --- a/tests/baselines/reference/exportDefaultInJsFile02.errors.txt +++ b/tests/baselines/reference/exportDefaultInJsFile02.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/conformance/salsa/myFile02.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/conformance/salsa/myFile02.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/conformance/salsa/myFile02.js (0 errors) ==== export default "hello"; \ No newline at end of file diff --git a/tests/baselines/reference/exportEqualsAmd.js b/tests/baselines/reference/exportEqualsAmd.js index 385012a6e0f..8b66b8896e3 100644 --- a/tests/baselines/reference/exportEqualsAmd.js +++ b/tests/baselines/reference/exportEqualsAmd.js @@ -4,6 +4,6 @@ export = { ["hi"]: "there" }; //// [exportEqualsAmd.js] define(["require", "exports"], function (require, exports) { "use strict"; - return _a = {}, _a["hi"] = "there", _a; var _a; + return _a = {}, _a["hi"] = "there", _a; }); diff --git a/tests/baselines/reference/exportEqualsCommonJs.js b/tests/baselines/reference/exportEqualsCommonJs.js index 01b7a43b310..03202239b17 100644 --- a/tests/baselines/reference/exportEqualsCommonJs.js +++ b/tests/baselines/reference/exportEqualsCommonJs.js @@ -3,5 +3,5 @@ export = { ["hi"]: "there" }; //// [exportEqualsCommonJs.js] "use strict"; -module.exports = (_a = {}, _a["hi"] = "there", _a); var _a; +module.exports = (_a = {}, _a["hi"] = "there", _a); diff --git a/tests/baselines/reference/exportEqualsUmd.js b/tests/baselines/reference/exportEqualsUmd.js index cd4c99f504d..500c8795dc7 100644 --- a/tests/baselines/reference/exportEqualsUmd.js +++ b/tests/baselines/reference/exportEqualsUmd.js @@ -11,6 +11,6 @@ export = { ["hi"]: "there" }; } })(["require", "exports"], function (require, exports) { "use strict"; - return _a = {}, _a["hi"] = "there", _a; var _a; + return _a = {}, _a["hi"] = "there", _a; }); diff --git a/tests/baselines/reference/exportStarForValues10.js b/tests/baselines/reference/exportStarForValues10.js index 3da80002780..f7dd6e94ce5 100644 --- a/tests/baselines/reference/exportStarForValues10.js +++ b/tests/baselines/reference/exportStarForValues10.js @@ -42,8 +42,7 @@ System.register(["file0"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default") - exports[n] = m[n]; + if (n !== "default") exports[n] = m[n]; } exports_1(exports); } diff --git a/tests/baselines/reference/exportsAndImports3-amd.js b/tests/baselines/reference/exportsAndImports3-amd.js index 0e315f1f18b..cbf30735182 100644 --- a/tests/baselines/reference/exportsAndImports3-amd.js +++ b/tests/baselines/reference/exportsAndImports3-amd.js @@ -49,12 +49,12 @@ define(["require", "exports"], function (require, exports) { }()); exports.C = C; exports.C1 = C; + var E; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; - })(exports.E || (exports.E = {})); - var E = exports.E; + })(E = exports.E || (exports.E = {})); exports.E1 = E; var M; (function (M) { diff --git a/tests/baselines/reference/exportsAndImports3-es6.js b/tests/baselines/reference/exportsAndImports3-es6.js index ea16836b1f2..85daa3f0f5c 100644 --- a/tests/baselines/reference/exportsAndImports3-es6.js +++ b/tests/baselines/reference/exportsAndImports3-es6.js @@ -45,12 +45,12 @@ class C { } exports.C = C; exports.C1 = C; +var E; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; -})(exports.E || (exports.E = {})); -var E = exports.E; +})(E = exports.E || (exports.E = {})); exports.E1 = E; var M; (function (M) { diff --git a/tests/baselines/reference/exportsAndImports3.js b/tests/baselines/reference/exportsAndImports3.js index 16115a192da..dbcd9486215 100644 --- a/tests/baselines/reference/exportsAndImports3.js +++ b/tests/baselines/reference/exportsAndImports3.js @@ -48,12 +48,12 @@ var C = (function () { }()); exports.C = C; exports.C1 = C; +var E; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; -})(exports.E || (exports.E = {})); -var E = exports.E; +})(E = exports.E || (exports.E = {})); exports.E1 = E; var M; (function (M) { diff --git a/tests/baselines/reference/extendPrivateConstructorClass.errors.txt b/tests/baselines/reference/extendPrivateConstructorClass.errors.txt new file mode 100644 index 00000000000..02e9c6a1c88 --- /dev/null +++ b/tests/baselines/reference/extendPrivateConstructorClass.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/extendPrivateConstructorClass.ts(7,17): error TS2675: Cannot extend a class 'abc.XYZ'. Class constructor is marked as private. + + +==== tests/cases/compiler/extendPrivateConstructorClass.ts (1 errors) ==== + declare namespace abc { + class XYZ { + private constructor(); + } + } + + class C extends abc.XYZ { + ~~~~~~~ +!!! error TS2675: Cannot extend a class 'abc.XYZ'. Class constructor is marked as private. + } + \ No newline at end of file diff --git a/tests/baselines/reference/extendPrivateConstructorClass.js b/tests/baselines/reference/extendPrivateConstructorClass.js new file mode 100644 index 00000000000..8893e9735ff --- /dev/null +++ b/tests/baselines/reference/extendPrivateConstructorClass.js @@ -0,0 +1,24 @@ +//// [extendPrivateConstructorClass.ts] +declare namespace abc { + class XYZ { + private constructor(); + } +} + +class C extends abc.XYZ { +} + + +//// [extendPrivateConstructorClass.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + return _super.apply(this, arguments) || this; + } + return C; +}(abc.XYZ)); diff --git a/tests/baselines/reference/externModule.js b/tests/baselines/reference/externModule.js index ff83d07ef98..f7edc1283df 100644 --- a/tests/baselines/reference/externModule.js +++ b/tests/baselines/reference/externModule.js @@ -43,11 +43,12 @@ n=XDate.UTC(1964,2,1); declare; module; { - export var XDate = (function () { + var XDate = (function () { function XDate() { } return XDate; }()); + export { XDate }; } var d = new XDate(); d.getDay(); diff --git a/tests/baselines/reference/externalModuleImmutableBindings.errors.txt b/tests/baselines/reference/externalModuleImmutableBindings.errors.txt index c8c61b2dc81..815b5847458 100644 --- a/tests/baselines/reference/externalModuleImmutableBindings.errors.txt +++ b/tests/baselines/reference/externalModuleImmutableBindings.errors.txt @@ -1,23 +1,23 @@ -tests/cases/compiler/f2.ts(7,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/f2.ts(7,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(8,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/compiler/f2.ts(9,7): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. -tests/cases/compiler/f2.ts(12,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(13,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(18,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/f2.ts(12,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(13,7): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(17,8): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(18,8): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/compiler/f2.ts(19,8): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. -tests/cases/compiler/f2.ts(22,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(23,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(27,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. -tests/cases/compiler/f2.ts(28,6): error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(29,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. -tests/cases/compiler/f2.ts(30,6): error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. +tests/cases/compiler/f2.ts(22,8): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(23,8): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(27,12): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(28,12): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(29,12): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(30,12): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/compiler/f2.ts(31,12): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. tests/cases/compiler/f2.ts(32,12): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. -tests/cases/compiler/f2.ts(36,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. -tests/cases/compiler/f2.ts(37,6): error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. -tests/cases/compiler/f2.ts(38,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. -tests/cases/compiler/f2.ts(39,6): error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. +tests/cases/compiler/f2.ts(36,13): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(37,13): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(38,13): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/compiler/f2.ts(39,13): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/compiler/f2.ts(40,13): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. tests/cases/compiler/f2.ts(41,13): error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. @@ -33,57 +33,57 @@ tests/cases/compiler/f2.ts(41,13): error TS2339: Property 'blah' does not exist var n = 'baz'; stuff.x = 0; - ~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. stuff['x'] = 1; - ~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. stuff.blah = 2; ~~~~ !!! error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. stuff[n] = 3; stuff.x++; - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. stuff['x']++; - ~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. stuff['blah']++; stuff[n]++; (stuff.x) = 0; - ~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. (stuff['x']) = 1; - ~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. (stuff.blah) = 2; ~~~~ !!! error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. (stuff[n]) = 3; (stuff.x)++; - ~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. (stuff['x'])++; - ~~~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. (stuff['blah'])++; (stuff[n])++; for (stuff.x in []) {} - ~~~~~~~ -!!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for (stuff.x of []) {} - ~~~~~~~ -!!! error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for (stuff['x'] in []) {} - ~~~~~~~~~~ -!!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for (stuff['x'] of []) {} - ~~~~~~~~~~ -!!! error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for (stuff.blah in []) {} ~~~~ !!! error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. @@ -94,17 +94,17 @@ tests/cases/compiler/f2.ts(41,13): error TS2339: Property 'blah' does not exist for (stuff[n] of []) {} for ((stuff.x) in []) {} - ~~~~~~~~~ -!!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for ((stuff.x) of []) {} - ~~~~~~~~~ -!!! error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for ((stuff['x']) in []) {} - ~~~~~~~~~~~~ -!!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for ((stuff['x']) of []) {} - ~~~~~~~~~~~~ -!!! error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. for ((stuff.blah) in []) {} ~~~~ !!! error TS2339: Property 'blah' does not exist on type 'typeof "tests/cases/compiler/f1"'. diff --git a/tests/baselines/reference/fatarrowfunctionsErrors.js b/tests/baselines/reference/fatarrowfunctionsErrors.js index 2ac20f1966a..0f318f1aa84 100644 --- a/tests/baselines/reference/fatarrowfunctionsErrors.js +++ b/tests/baselines/reference/fatarrowfunctionsErrors.js @@ -16,11 +16,11 @@ var x4= (...a: any[]) { }; foo(function () { var Far = []; for (var _i = 0; _i < arguments.length; _i++) { - Far[_i - 0] = arguments[_i]; + Far[_i] = arguments[_i]; } return 0; }); -foo((1), { return: 0 }); +foo((1), { "return": 0 }); foo(function (x) { return x; }); foo(function (x) { if (x === void 0) { x = 0; } @@ -36,6 +36,6 @@ var x3 = function (a) { }; var x4 = function () { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } }; diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js index e6e43f8bbf4..f7e49680f8a 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js @@ -159,7 +159,7 @@ foo( (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 8; }); @@ -203,7 +203,7 @@ foo( (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 28; }); @@ -226,7 +226,7 @@ false ? function (arg) { false ? function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 48; } : null; @@ -247,7 +247,7 @@ false ? (function (arg) { false ? (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 58; }) : null; @@ -268,7 +268,7 @@ false ? null : function (arg) { false ? null : function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 68; }; @@ -294,7 +294,7 @@ false ? null : function () { (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 96; }) instanceof Function; @@ -326,13 +326,13 @@ false ? null : function () { (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 0; }) + '' + (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 107; }); @@ -354,7 +354,7 @@ false ? null : function () { function foo() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } foo(function (a) { return 110; }, (function (a) { return 111; }), function (a) { @@ -371,7 +371,7 @@ foo(function (a) { return 110; }, (function (a) { return 111; }), function (a) { }, function () { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } return 119; }, function (a, b) { diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js index 4d27f8230eb..edbc897922c 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js @@ -12,21 +12,21 @@ (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 102; }); (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 103; }); (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 104; }); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js index 665c5244016..d5d4b099a06 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js @@ -6,7 +6,7 @@ (function () { var = []; for (var _i = 0; _i < arguments.length; _i++) { - [_i - 0] = arguments[_i]; + [_i] = arguments[_i]; } return 105; }); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js index dfd7e9f74dc..0fbf4b7486e 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js @@ -56,7 +56,7 @@ foo(function (a) { return 110; }, (function (a) { return 111; }), function (a) { }, function () { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } return 119; }, function (a, b) { diff --git a/tests/baselines/reference/flowInFinally1.js b/tests/baselines/reference/flowInFinally1.js new file mode 100644 index 00000000000..b6bf494e832 --- /dev/null +++ b/tests/baselines/reference/flowInFinally1.js @@ -0,0 +1,33 @@ +//// [flowInFinally1.ts] + +class A { + constructor() { } + method() { } +} + +let a: A | null = null; + +try { + a = new A(); +} finally { + if (a) { + a.method(); + } +} + +//// [flowInFinally1.js] +var A = (function () { + function A() { + } + A.prototype.method = function () { }; + return A; +}()); +var a = null; +try { + a = new A(); +} +finally { + if (a) { + a.method(); + } +} diff --git a/tests/baselines/reference/flowInFinally1.symbols b/tests/baselines/reference/flowInFinally1.symbols new file mode 100644 index 00000000000..2ecedaee025 --- /dev/null +++ b/tests/baselines/reference/flowInFinally1.symbols @@ -0,0 +1,29 @@ +=== tests/cases/compiler/flowInFinally1.ts === + +class A { +>A : Symbol(A, Decl(flowInFinally1.ts, 0, 0)) + + constructor() { } + method() { } +>method : Symbol(A.method, Decl(flowInFinally1.ts, 2, 19)) +} + +let a: A | null = null; +>a : Symbol(a, Decl(flowInFinally1.ts, 6, 3)) +>A : Symbol(A, Decl(flowInFinally1.ts, 0, 0)) + +try { + a = new A(); +>a : Symbol(a, Decl(flowInFinally1.ts, 6, 3)) +>A : Symbol(A, Decl(flowInFinally1.ts, 0, 0)) + +} finally { + if (a) { +>a : Symbol(a, Decl(flowInFinally1.ts, 6, 3)) + + a.method(); +>a.method : Symbol(A.method, Decl(flowInFinally1.ts, 2, 19)) +>a : Symbol(a, Decl(flowInFinally1.ts, 6, 3)) +>method : Symbol(A.method, Decl(flowInFinally1.ts, 2, 19)) + } +} diff --git a/tests/baselines/reference/flowInFinally1.types b/tests/baselines/reference/flowInFinally1.types new file mode 100644 index 00000000000..c9cbab6dbd1 --- /dev/null +++ b/tests/baselines/reference/flowInFinally1.types @@ -0,0 +1,34 @@ +=== tests/cases/compiler/flowInFinally1.ts === + +class A { +>A : A + + constructor() { } + method() { } +>method : () => void +} + +let a: A | null = null; +>a : A | null +>A : A +>null : null +>null : null + +try { + a = new A(); +>a = new A() : A +>a : A | null +>new A() : A +>A : typeof A + +} finally { + if (a) { +>a : A | null + + a.method(); +>a.method() : void +>a.method : () => void +>a : A +>method : () => void + } +} diff --git a/tests/baselines/reference/for-inStatements.errors.txt b/tests/baselines/reference/for-inStatements.errors.txt index f0e6c950ebb..c5ca29d2150 100644 --- a/tests/baselines/reference/for-inStatements.errors.txt +++ b/tests/baselines/reference/for-inStatements.errors.txt @@ -1,7 +1,9 @@ +tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(33,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. +tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(50,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -==== tests/cases/conformance/statements/for-inStatements/for-inStatements.ts (1 errors) ==== +==== tests/cases/conformance/statements/for-inStatements/for-inStatements.ts (3 errors) ==== var aString: string; for (aString in {}) { } @@ -35,6 +37,8 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): for (var x in this.biz()) { } for (var x in this.biz) { } for (var x in this) { } + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. return null; } @@ -52,6 +56,8 @@ tests/cases/conformance/statements/for-inStatements/for-inStatements.ts(79,15): for (var x in this.biz()) { } for (var x in this.biz) { } for (var x in this) { } + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. for (var x in super.biz) { } for (var x in super.biz()) { } diff --git a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt index 6886d992bb2..03361cfcfab 100644 --- a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt +++ b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(5,14): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(5,16): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(6,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(7,9): error TS2365: Operator '===' cannot be applied to types 'string' and 'number'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(9,16): error TS2339: Property 'unknownProperty' does not exist on type 'string'. @@ -12,7 +12,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors. for (let x in a) { let a1 = a[x + 1]; - ~~~~~~~~ + ~~~~~ !!! error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. let a2 = a[x - 1]; ~ diff --git a/tests/baselines/reference/for-inStatementsInvalid.errors.txt b/tests/baselines/reference/for-inStatementsInvalid.errors.txt index 00ab58ab94d..f98349973a3 100644 --- a/tests/baselines/reference/for-inStatementsInvalid.errors.txt +++ b/tests/baselines/reference/for-inStatementsInvalid.errors.txt @@ -9,13 +9,15 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(1 tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(20,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(22,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(29,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(31,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(38,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(46,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. +tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(48,18): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(51,23): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(62,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -==== tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts (15 errors) ==== +==== tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts (17 errors) ==== var aNumber: number; for (aNumber in {}) { } ~~~~~~~ @@ -69,6 +71,8 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 !!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. for (var x in this.biz) { } for (var x in this) { } + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. return null; } @@ -90,6 +94,8 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsInvalid.ts(6 !!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. for (var x in this.biz) { } for (var x in this) { } + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type 'string', but here has type 'keyof this'. for (var x in super.biz) { } for (var x in super.biz()) { } diff --git a/tests/baselines/reference/for-of2.errors.txt b/tests/baselines/reference/for-of2.errors.txt index f4f39f60f67..1975f8be0af 100644 --- a/tests/baselines/reference/for-of2.errors.txt +++ b/tests/baselines/reference/for-of2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/for-ofStatements/for-of2.ts(1,7): error TS1155: 'const' declarations must be initialized -tests/cases/conformance/es6/for-ofStatements/for-of2.ts(2,6): error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. +tests/cases/conformance/es6/for-ofStatements/for-of2.ts(2,6): error TS2540: Cannot assign to 'v' because it is a constant or a read-only property. ==== tests/cases/conformance/es6/for-ofStatements/for-of2.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/es6/for-ofStatements/for-of2.ts(2,6): error TS2485: The !!! error TS1155: 'const' declarations must be initialized for (v of []) { } ~ -!!! error TS2485: The left-hand side of a 'for...of' statement cannot be a constant or a read-only property. \ No newline at end of file +!!! error TS2540: Cannot assign to 'v' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/for-of3.errors.txt b/tests/baselines/reference/for-of3.errors.txt index 99ed3098a63..1d58db6f186 100644 --- a/tests/baselines/reference/for-of3.errors.txt +++ b/tests/baselines/reference/for-of3.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/for-ofStatements/for-of3.ts(2,6): error TS2487: Invalid left-hand side in 'for...of' statement. +tests/cases/conformance/es6/for-ofStatements/for-of3.ts(2,6): error TS2487: The left-hand side of a 'for...of' statement must be a variable or a property access. ==== tests/cases/conformance/es6/for-ofStatements/for-of3.ts (1 errors) ==== var v: any; for (v++ of []) { } ~~~ -!!! error TS2487: Invalid left-hand side in 'for...of' statement. \ No newline at end of file +!!! error TS2487: The left-hand side of a 'for...of' statement must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/forIn.errors.txt b/tests/baselines/reference/forIn.errors.txt index a7dd629698a..ccc1423f1aa 100644 --- a/tests/baselines/reference/forIn.errors.txt +++ b/tests/baselines/reference/forIn.errors.txt @@ -1,24 +1,17 @@ tests/cases/compiler/forIn.ts(2,10): error TS2404: The left-hand side of a 'for...in' statement cannot use a type annotation. -tests/cases/compiler/forIn.ts(2,22): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/compiler/forIn.ts(7,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -tests/cases/compiler/forIn.ts(18,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/compiler/forIn.ts(20,4): error TS2304: Cannot find name 'k'. -==== tests/cases/compiler/forIn.ts (5 errors) ==== +==== tests/cases/compiler/forIn.ts (2 errors) ==== var arr = null; for (var i:number in arr) { // error ~ !!! error TS2404: The left-hand side of a 'for...in' statement cannot use a type annotation. - ~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. var x1 = arr[i]; var y1 = arr[i]; } for (var j in arr) { // ok - ~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. var x2 = arr[j]; var y2 = arr[j]; } @@ -30,8 +23,6 @@ tests/cases/compiler/forIn.ts(20,4): error TS2304: Cannot find name 'k'. } for (var l in arr) { - ~~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. // error in the body k[l] = 1; ~ diff --git a/tests/baselines/reference/forInStatement3.types b/tests/baselines/reference/forInStatement3.types index d3767790ed2..09e6cf3ad96 100644 --- a/tests/baselines/reference/forInStatement3.types +++ b/tests/baselines/reference/forInStatement3.types @@ -8,7 +8,7 @@ function F() { >T : T for (var a in expr) { ->a : string +>a : keyof T >expr : T } } diff --git a/tests/baselines/reference/forOfStringConstituents.js b/tests/baselines/reference/forOfStringConstituents.js new file mode 100644 index 00000000000..0f0d86d8cc6 --- /dev/null +++ b/tests/baselines/reference/forOfStringConstituents.js @@ -0,0 +1,15 @@ +//// [forOfStringConstituents.ts] +interface A { x: 0; y: C[]; } +interface B { x: 1; y: CD[]; } +interface C { x: 2; } +interface D { x: 3; } +type AB = A | B; +type CD = C | D; +declare let x: AB, y: CD; +for (y of x.y); + +//// [forOfStringConstituents.js] +for (var _i = 0, _a = x.y; _i < _a.length; _i++) { + y = _a[_i]; + ; +} diff --git a/tests/baselines/reference/forOfStringConstituents.symbols b/tests/baselines/reference/forOfStringConstituents.symbols new file mode 100644 index 00000000000..226f8e35a55 --- /dev/null +++ b/tests/baselines/reference/forOfStringConstituents.symbols @@ -0,0 +1,43 @@ +=== tests/cases/compiler/forOfStringConstituents.ts === +interface A { x: 0; y: C[]; } +>A : Symbol(A, Decl(forOfStringConstituents.ts, 0, 0)) +>x : Symbol(A.x, Decl(forOfStringConstituents.ts, 0, 13)) +>y : Symbol(A.y, Decl(forOfStringConstituents.ts, 0, 19)) +>C : Symbol(C, Decl(forOfStringConstituents.ts, 1, 30)) + +interface B { x: 1; y: CD[]; } +>B : Symbol(B, Decl(forOfStringConstituents.ts, 0, 29)) +>x : Symbol(B.x, Decl(forOfStringConstituents.ts, 1, 13)) +>y : Symbol(B.y, Decl(forOfStringConstituents.ts, 1, 19)) +>CD : Symbol(CD, Decl(forOfStringConstituents.ts, 4, 16)) + +interface C { x: 2; } +>C : Symbol(C, Decl(forOfStringConstituents.ts, 1, 30)) +>x : Symbol(C.x, Decl(forOfStringConstituents.ts, 2, 13)) + +interface D { x: 3; } +>D : Symbol(D, Decl(forOfStringConstituents.ts, 2, 21)) +>x : Symbol(D.x, Decl(forOfStringConstituents.ts, 3, 13)) + +type AB = A | B; +>AB : Symbol(AB, Decl(forOfStringConstituents.ts, 3, 21)) +>A : Symbol(A, Decl(forOfStringConstituents.ts, 0, 0)) +>B : Symbol(B, Decl(forOfStringConstituents.ts, 0, 29)) + +type CD = C | D; +>CD : Symbol(CD, Decl(forOfStringConstituents.ts, 4, 16)) +>C : Symbol(C, Decl(forOfStringConstituents.ts, 1, 30)) +>D : Symbol(D, Decl(forOfStringConstituents.ts, 2, 21)) + +declare let x: AB, y: CD; +>x : Symbol(x, Decl(forOfStringConstituents.ts, 6, 11)) +>AB : Symbol(AB, Decl(forOfStringConstituents.ts, 3, 21)) +>y : Symbol(y, Decl(forOfStringConstituents.ts, 6, 18)) +>CD : Symbol(CD, Decl(forOfStringConstituents.ts, 4, 16)) + +for (y of x.y); +>y : Symbol(y, Decl(forOfStringConstituents.ts, 6, 18)) +>x.y : Symbol(y, Decl(forOfStringConstituents.ts, 0, 19), Decl(forOfStringConstituents.ts, 1, 19)) +>x : Symbol(x, Decl(forOfStringConstituents.ts, 6, 11)) +>y : Symbol(y, Decl(forOfStringConstituents.ts, 0, 19), Decl(forOfStringConstituents.ts, 1, 19)) + diff --git a/tests/baselines/reference/forOfStringConstituents.types b/tests/baselines/reference/forOfStringConstituents.types new file mode 100644 index 00000000000..2bd2a1abd4e --- /dev/null +++ b/tests/baselines/reference/forOfStringConstituents.types @@ -0,0 +1,43 @@ +=== tests/cases/compiler/forOfStringConstituents.ts === +interface A { x: 0; y: C[]; } +>A : A +>x : 0 +>y : C[] +>C : C + +interface B { x: 1; y: CD[]; } +>B : B +>x : 1 +>y : CD[] +>CD : CD + +interface C { x: 2; } +>C : C +>x : 2 + +interface D { x: 3; } +>D : D +>x : 3 + +type AB = A | B; +>AB : AB +>A : A +>B : B + +type CD = C | D; +>CD : CD +>C : C +>D : D + +declare let x: AB, y: CD; +>x : AB +>AB : AB +>y : CD +>CD : CD + +for (y of x.y); +>y : CD +>x.y : C[] | CD[] +>x : AB +>y : C[] | CD[] + diff --git a/tests/baselines/reference/functionCall10.js b/tests/baselines/reference/functionCall10.js index 9d5cb33a56a..51ed76990b3 100644 --- a/tests/baselines/reference/functionCall10.js +++ b/tests/baselines/reference/functionCall10.js @@ -10,7 +10,7 @@ foo(1, 'bar'); function foo() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } } ; diff --git a/tests/baselines/reference/functionOverloadsRecursiveGenericReturnType.js b/tests/baselines/reference/functionOverloadsRecursiveGenericReturnType.js index 1d38d65ad38..b616d18c974 100644 --- a/tests/baselines/reference/functionOverloadsRecursiveGenericReturnType.js +++ b/tests/baselines/reference/functionOverloadsRecursiveGenericReturnType.js @@ -28,7 +28,7 @@ var A = (function () { function Choice() { var v_args = []; for (var _i = 0; _i < arguments.length; _i++) { - v_args[_i - 0] = arguments[_i]; + v_args[_i] = arguments[_i]; } return new A(); } diff --git a/tests/baselines/reference/generatorTransformFinalLabel.js b/tests/baselines/reference/generatorTransformFinalLabel.js index 32272ae0748..58cffc80bee 100644 --- a/tests/baselines/reference/generatorTransformFinalLabel.js +++ b/tests/baselines/reference/generatorTransformFinalLabel.js @@ -14,8 +14,7 @@ function test(skip) { return __generator(this, function (_a) { switch (_a.label) { case 0: - if (!!skip) - return [3 /*break*/, 2]; + if (!!skip) return [3 /*break*/, 2]; return [4 /*yield*/, 1]; case 1: _a.sent(); diff --git a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js index 6d65ee5531b..401a2e94b68 100644 --- a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js +++ b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js @@ -37,11 +37,11 @@ var TypeScript2; ; ; ; + var PullSymbolVisibility; (function (PullSymbolVisibility) { PullSymbolVisibility[PullSymbolVisibility["Private"] = 0] = "Private"; PullSymbolVisibility[PullSymbolVisibility["Public"] = 1] = "Public"; - })(TypeScript2.PullSymbolVisibility || (TypeScript2.PullSymbolVisibility = {})); - var PullSymbolVisibility = TypeScript2.PullSymbolVisibility; + })(PullSymbolVisibility = TypeScript2.PullSymbolVisibility || (TypeScript2.PullSymbolVisibility = {})); var PullSymbol = (function () { function PullSymbol(name, declKind) { } diff --git a/tests/baselines/reference/genericRestArgs.js b/tests/baselines/reference/genericRestArgs.js index 75c88d7cbf2..1cfeb61e169 100644 --- a/tests/baselines/reference/genericRestArgs.js +++ b/tests/baselines/reference/genericRestArgs.js @@ -16,7 +16,7 @@ var a2Gc = makeArrayG(1, ""); // error function makeArrayG() { var items = []; for (var _i = 0; _i < arguments.length; _i++) { - items[_i - 0] = arguments[_i]; + items[_i] = arguments[_i]; } return items; } diff --git a/tests/baselines/reference/globalAugmentationModuleResolution.js b/tests/baselines/reference/globalAugmentationModuleResolution.js new file mode 100644 index 00000000000..e1a4ebce8c5 --- /dev/null +++ b/tests/baselines/reference/globalAugmentationModuleResolution.js @@ -0,0 +1,10 @@ +//// [a.ts] + +export { }; + +declare global { + var x: number; +} + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/globalAugmentationModuleResolution.symbols b/tests/baselines/reference/globalAugmentationModuleResolution.symbols new file mode 100644 index 00000000000..614860d654e --- /dev/null +++ b/tests/baselines/reference/globalAugmentationModuleResolution.symbols @@ -0,0 +1,10 @@ +=== tests/cases/conformance/externalModules/a.ts === + +export { }; + +declare global { +>global : Symbol(global, Decl(a.ts, 1, 11)) + + var x: number; +>x : Symbol(x, Decl(a.ts, 4, 5)) +} diff --git a/tests/baselines/reference/globalAugmentationModuleResolution.trace.json b/tests/baselines/reference/globalAugmentationModuleResolution.trace.json new file mode 100644 index 00000000000..0637a088a01 --- /dev/null +++ b/tests/baselines/reference/globalAugmentationModuleResolution.trace.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/tests/baselines/reference/globalAugmentationModuleResolution.types b/tests/baselines/reference/globalAugmentationModuleResolution.types new file mode 100644 index 00000000000..c057ea2943d --- /dev/null +++ b/tests/baselines/reference/globalAugmentationModuleResolution.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/externalModules/a.ts === + +export { }; + +declare global { +>global : any + + var x: number; +>x : number +} diff --git a/tests/baselines/reference/grammarAmbiguities1.errors.txt b/tests/baselines/reference/grammarAmbiguities1.errors.txt index 8809c4aa334..12df5f3c1e0 100644 --- a/tests/baselines/reference/grammarAmbiguities1.errors.txt +++ b/tests/baselines/reference/grammarAmbiguities1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/grammarAmbiguities1.ts(8,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/grammarAmbiguities1.ts(8,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. -tests/cases/compiler/grammarAmbiguities1.ts(8,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and '7'. +tests/cases/compiler/grammarAmbiguities1.ts(8,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. tests/cases/compiler/grammarAmbiguities1.ts(9,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/grammarAmbiguities1.ts(9,3): error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. @@ -20,7 +20,7 @@ tests/cases/compiler/grammarAmbiguities1.ts(9,10): error TS2365: Operator '>' ca ~~~~~ !!! error TS2365: Operator '<' cannot be applied to types '(x: any) => any' and 'typeof A'. ~~~~~ -!!! error TS2365: Operator '>' cannot be applied to types 'typeof B' and '7'. +!!! error TS2365: Operator '>' cannot be applied to types 'typeof B' and 'number'. f(g < A, B > +(7)); ~~~~~~~~~~~~~~~~~~ !!! error TS2346: Supplied parameters do not match any signature of call target. diff --git a/tests/baselines/reference/implicitAnyDeclareFunctionWithoutFormalType.js b/tests/baselines/reference/implicitAnyDeclareFunctionWithoutFormalType.js index c13479daff3..0b2ba6191ef 100644 --- a/tests/baselines/reference/implicitAnyDeclareFunctionWithoutFormalType.js +++ b/tests/baselines/reference/implicitAnyDeclareFunctionWithoutFormalType.js @@ -22,7 +22,7 @@ function func2(a, b, c) { } function func3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } ; // error at "args" diff --git a/tests/baselines/reference/implicitAnyInCatch.types b/tests/baselines/reference/implicitAnyInCatch.types index d2a1be4a910..93cce09928e 100644 --- a/tests/baselines/reference/implicitAnyInCatch.types +++ b/tests/baselines/reference/implicitAnyInCatch.types @@ -22,7 +22,7 @@ class C { >temp : () => void for (var x in this) { ->x : string +>x : keyof this >this : this } } diff --git a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt index 95739a450a8..4302211d9a0 100644 --- a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt +++ b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt @@ -1,17 +1,14 @@ tests/cases/compiler/implicitAnyWidenToAny.ts(4,5): error TS7005: Variable 'widenArray' implicitly has an 'any[]' type. -tests/cases/compiler/implicitAnyWidenToAny.ts(5,5): error TS7005: Variable 'emptyArray' implicitly has an 'any[]' type. -==== tests/cases/compiler/implicitAnyWidenToAny.ts (2 errors) ==== +==== tests/cases/compiler/implicitAnyWidenToAny.ts (1 errors) ==== // these should be errors var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" ~~~~~~~~~~ !!! error TS7005: Variable 'widenArray' implicitly has an 'any[]' type. - var emptyArray = []; // error at "emptyArray" - ~~~~~~~~~~ -!!! error TS7005: Variable 'emptyArray' implicitly has an 'any[]' type. + var emptyArray = []; // these should not be error class AnimalObj { diff --git a/tests/baselines/reference/implicitAnyWidenToAny.js b/tests/baselines/reference/implicitAnyWidenToAny.js index 0779a166744..0d1c42ad9d0 100644 --- a/tests/baselines/reference/implicitAnyWidenToAny.js +++ b/tests/baselines/reference/implicitAnyWidenToAny.js @@ -3,7 +3,7 @@ var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error class AnimalObj { @@ -32,7 +32,7 @@ var obj1 = anyReturnFunc(); var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error var AnimalObj = (function () { function AnimalObj() { diff --git a/tests/baselines/reference/implicitIndexSignatures.types b/tests/baselines/reference/implicitIndexSignatures.types index ac8da0c7b6c..0b68f136e2e 100644 --- a/tests/baselines/reference/implicitIndexSignatures.types +++ b/tests/baselines/reference/implicitIndexSignatures.types @@ -1,6 +1,6 @@ === tests/cases/compiler/implicitIndexSignatures.ts === type StringMap = { [x: string]: string }; ->StringMap : { [x: string]: string; } +>StringMap : StringMap >x : string const empty1 = {}; @@ -24,12 +24,12 @@ let names2: { a: string, b: string }; >b : string let map: StringMap; ->map : { [x: string]: string; } ->StringMap : { [x: string]: string; } +>map : StringMap +>StringMap : StringMap map = { x: "xxx", y: "yyy" }; >map = { x: "xxx", y: "yyy" } : { x: string; y: string; } ->map : { [x: string]: string; } +>map : StringMap >{ x: "xxx", y: "yyy" } : { x: string; y: string; } >x : string >"xxx" : "xxx" @@ -38,22 +38,22 @@ map = { x: "xxx", y: "yyy" }; map = empty1; >map = empty1 : {} ->map : { [x: string]: string; } +>map : StringMap >empty1 : {} map = empty2; >map = empty2 : {} ->map : { [x: string]: string; } +>map : StringMap >empty2 : {} map = names1; >map = names1 : { a: string; b: string; } ->map : { [x: string]: string; } +>map : StringMap >names1 : { a: string; b: string; } map = names2; >map = names2 : { a: string; b: string; } ->map : { [x: string]: string; } +>map : StringMap >names2 : { a: string; b: string; } declare function getStringIndexValue(map: { [x: string]: T }): T; diff --git a/tests/baselines/reference/importDeclWithDeclareModifier.js b/tests/baselines/reference/importDeclWithDeclareModifier.js index e5267678a49..7c3d3782934 100644 --- a/tests/baselines/reference/importDeclWithDeclareModifier.js +++ b/tests/baselines/reference/importDeclWithDeclareModifier.js @@ -9,4 +9,5 @@ var b: a; //// [importDeclWithDeclareModifier.js] "use strict"; +exports.a = x.c; var b; diff --git a/tests/baselines/reference/importHelpers.js b/tests/baselines/reference/importHelpers.js index ae4d3127010..762f0778945 100644 --- a/tests/baselines/reference/importHelpers.js +++ b/tests/baselines/reference/importHelpers.js @@ -64,8 +64,7 @@ tslib_1.__decorate([ tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ - dec, - tslib_1.__metadata("design:paramtypes", []) + dec ], C); //// [script.js] var __extends = (this && this.__extends) || function (d, b) { @@ -111,6 +110,5 @@ __decorate([ __metadata("design:returntype", void 0) ], C.prototype, "method", null); C = __decorate([ - dec, - __metadata("design:paramtypes", []) + dec ], C); diff --git a/tests/baselines/reference/importHelpersDeclarations.symbols b/tests/baselines/reference/importHelpersDeclarations.symbols new file mode 100644 index 00000000000..f578850cc4e --- /dev/null +++ b/tests/baselines/reference/importHelpersDeclarations.symbols @@ -0,0 +1,8 @@ +=== tests/cases/compiler/declaration.d.ts === +export declare class D { +>D : Symbol(D, Decl(declaration.d.ts, 0, 0)) +} +export declare class E extends D { +>E : Symbol(E, Decl(declaration.d.ts, 1, 1)) +>D : Symbol(D, Decl(declaration.d.ts, 0, 0)) +} diff --git a/tests/baselines/reference/importHelpersDeclarations.types b/tests/baselines/reference/importHelpersDeclarations.types new file mode 100644 index 00000000000..4b8c56d7869 --- /dev/null +++ b/tests/baselines/reference/importHelpersDeclarations.types @@ -0,0 +1,8 @@ +=== tests/cases/compiler/declaration.d.ts === +export declare class D { +>D : D +} +export declare class E extends D { +>E : E +>D : D +} diff --git a/tests/baselines/reference/importHelpersInIsolatedModules.js b/tests/baselines/reference/importHelpersInIsolatedModules.js index 28c00f97554..5c395ea0b9f 100644 --- a/tests/baselines/reference/importHelpersInIsolatedModules.js +++ b/tests/baselines/reference/importHelpersInIsolatedModules.js @@ -64,8 +64,7 @@ tslib_1.__decorate([ tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ - dec, - tslib_1.__metadata("design:paramtypes", []) + dec ], C); //// [script.js] "use strict"; @@ -96,6 +95,5 @@ tslib_1.__decorate([ tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ - dec, - tslib_1.__metadata("design:paramtypes", []) + dec ], C); diff --git a/tests/baselines/reference/importHelpersNoHelpers.errors.txt b/tests/baselines/reference/importHelpersNoHelpers.errors.txt index ebb25dbd7c9..a0c089a9ddc 100644 --- a/tests/baselines/reference/importHelpersNoHelpers.errors.txt +++ b/tests/baselines/reference/importHelpersNoHelpers.errors.txt @@ -1,25 +1,39 @@ -error TS2305: Module 'tslib' has no exported member '__decorate'. -error TS2305: Module 'tslib' has no exported member '__extends'. -error TS2305: Module 'tslib' has no exported member '__metadata'. -error TS2305: Module 'tslib' has no exported member '__param'. +tests/cases/compiler/external.ts(2,16): error TS2343: This syntax requires an imported helper named '__extends', but module 'tslib' has no exported member '__extends'. +tests/cases/compiler/external.ts(6,1): error TS2343: This syntax requires an imported helper named '__decorate', but module 'tslib' has no exported member '__decorate'. +tests/cases/compiler/external.ts(6,1): error TS2343: This syntax requires an imported helper named '__metadata', but module 'tslib' has no exported member '__metadata'. +tests/cases/compiler/external.ts(8,12): error TS2343: This syntax requires an imported helper named '__param', but module 'tslib' has no exported member '__param'. +tests/cases/compiler/external.ts(13,13): error TS2343: This syntax requires an imported helper named '__assign', but module 'tslib' has no exported member '__assign'. +tests/cases/compiler/external.ts(14,12): error TS2343: This syntax requires an imported helper named '__rest', but module 'tslib' has no exported member '__rest'. -!!! error TS2305: Module 'tslib' has no exported member '__decorate'. -!!! error TS2305: Module 'tslib' has no exported member '__extends'. -!!! error TS2305: Module 'tslib' has no exported member '__metadata'. -!!! error TS2305: Module 'tslib' has no exported member '__param'. -==== tests/cases/compiler/external.ts (0 errors) ==== +==== tests/cases/compiler/external.ts (6 errors) ==== export class A { } export class B extends A { } + ~~~~~~~~~ +!!! error TS2343: This syntax requires an imported helper named '__extends', but module 'tslib' has no exported member '__extends'. declare var dec: any; @dec + ~~~~ +!!! error TS2343: This syntax requires an imported helper named '__decorate', but module 'tslib' has no exported member '__decorate'. + ~~~~ +!!! error TS2343: This syntax requires an imported helper named '__metadata', but module 'tslib' has no exported member '__metadata'. class C { method(@dec x: number) { + ~~~~ +!!! error TS2343: This syntax requires an imported helper named '__param', but module 'tslib' has no exported member '__param'. } } + const o = { a: 1 }; + const y = { ...o }; + ~~~~ +!!! error TS2343: This syntax requires an imported helper named '__assign', but module 'tslib' has no exported member '__assign'. + const { ...x } = y; + ~ +!!! error TS2343: This syntax requires an imported helper named '__rest', but module 'tslib' has no exported member '__rest'. + ==== tests/cases/compiler/script.ts (0 errors) ==== class A { } class B extends A { } @@ -33,4 +47,5 @@ error TS2305: Module 'tslib' has no exported member '__param'. } ==== tests/cases/compiler/tslib.d.ts (0 errors) ==== - export {} \ No newline at end of file + export {} + \ No newline at end of file diff --git a/tests/baselines/reference/importHelpersNoHelpers.js b/tests/baselines/reference/importHelpersNoHelpers.js index e22d1f4353d..560e16d1cca 100644 --- a/tests/baselines/reference/importHelpersNoHelpers.js +++ b/tests/baselines/reference/importHelpersNoHelpers.js @@ -11,6 +11,10 @@ class C { method(@dec x: number) { } } + +const o = { a: 1 }; +const y = { ...o }; +const { ...x } = y; //// [script.ts] class A { } @@ -25,7 +29,8 @@ class C { } //// [tslib.d.ts] -export {} +export {} + //// [external.js] "use strict"; @@ -58,9 +63,11 @@ tslib_1.__decorate([ tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ - dec, - tslib_1.__metadata("design:paramtypes", []) + dec ], C); +var o = { a: 1 }; +var y = tslib_1.__assign({}, o); +var x = tslib_1.__rest(y, []); //// [script.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -105,6 +112,5 @@ __decorate([ __metadata("design:returntype", void 0) ], C.prototype, "method", null); C = __decorate([ - dec, - __metadata("design:paramtypes", []) + dec ], C); diff --git a/tests/baselines/reference/importHelpersNoModule.errors.txt b/tests/baselines/reference/importHelpersNoModule.errors.txt index d59fd0537ca..b6786ec3635 100644 --- a/tests/baselines/reference/importHelpersNoModule.errors.txt +++ b/tests/baselines/reference/importHelpersNoModule.errors.txt @@ -1,10 +1,11 @@ -error TS2307: Cannot find module 'tslib'. +tests/cases/compiler/external.ts(2,16): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. -!!! error TS2307: Cannot find module 'tslib'. -==== tests/cases/compiler/external.ts (0 errors) ==== +==== tests/cases/compiler/external.ts (1 errors) ==== export class A { } export class B extends A { } + ~~~~~~~~~ +!!! error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. declare var dec: any; diff --git a/tests/baselines/reference/importHelpersNoModule.js b/tests/baselines/reference/importHelpersNoModule.js index 41df9710f33..65a004eb66c 100644 --- a/tests/baselines/reference/importHelpersNoModule.js +++ b/tests/baselines/reference/importHelpersNoModule.js @@ -56,8 +56,7 @@ tslib_1.__decorate([ tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ - dec, - tslib_1.__metadata("design:paramtypes", []) + dec ], C); //// [script.js] var __extends = (this && this.__extends) || function (d, b) { @@ -103,6 +102,5 @@ __decorate([ __metadata("design:returntype", void 0) ], C.prototype, "method", null); C = __decorate([ - dec, - __metadata("design:paramtypes", []) + dec ], C); diff --git a/tests/baselines/reference/importImportOnlyModule.js b/tests/baselines/reference/importImportOnlyModule.js index 38ffc08d65e..013999321f9 100644 --- a/tests/baselines/reference/importImportOnlyModule.js +++ b/tests/baselines/reference/importImportOnlyModule.js @@ -24,8 +24,8 @@ define(["require", "exports"], function (require, exports) { } return C1; }()); - exports.C1 = C1; C1.s1 = true; + exports.C1 = C1; }); //// [foo_1.js] define(["require", "exports"], function (require, exports) { diff --git a/tests/baselines/reference/importWithTrailingSlash.trace.json b/tests/baselines/reference/importWithTrailingSlash.trace.json index 3c99d4eb6a0..56de914f395 100644 --- a/tests/baselines/reference/importWithTrailingSlash.trace.json +++ b/tests/baselines/reference/importWithTrailingSlash.trace.json @@ -3,26 +3,22 @@ "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location '/a'.", "File '/a.ts' exist - use it as a name resolution result.", - "Resolving real path for '/a.ts', result '/a.ts'", "======== Module name '.' was successfully resolved to '/a.ts'. ========", "======== Resolving module './' from '/a/test.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location '/a/'.", "File '/a/package.json' does not exist.", "File '/a/index.ts' exist - use it as a name resolution result.", - "Resolving real path for '/a/index.ts', result '/a/index.ts'", "======== Module name './' was successfully resolved to '/a/index.ts'. ========", "======== Resolving module '..' from '/a/b/test.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location '/a'.", "File '/a.ts' exist - use it as a name resolution result.", - "Resolving real path for '/a.ts', result '/a.ts'", "======== Module name '..' was successfully resolved to '/a.ts'. ========", "======== Resolving module '../' from '/a/b/test.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location '/a/'.", "File '/a/package.json' does not exist.", "File '/a/index.ts' exist - use it as a name resolution result.", - "Resolving real path for '/a/index.ts', result '/a/index.ts'", "======== Module name '../' was successfully resolved to '/a/index.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/importWithTrailingSlash_noResolve.trace.json b/tests/baselines/reference/importWithTrailingSlash_noResolve.trace.json index e010603106f..55b75c57dde 100644 --- a/tests/baselines/reference/importWithTrailingSlash_noResolve.trace.json +++ b/tests/baselines/reference/importWithTrailingSlash_noResolve.trace.json @@ -6,5 +6,9 @@ "File '/foo/index.ts' does not exist.", "File '/foo/index.tsx' does not exist.", "File '/foo/index.d.ts' does not exist.", + "Loading module as file / folder, candidate module location '/foo/'.", + "File '/foo/package.json' does not exist.", + "File '/foo/index.js' does not exist.", + "File '/foo/index.jsx' does not exist.", "======== Module name './foo/' was not resolved. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/importsImplicitlyReadonly.errors.txt b/tests/baselines/reference/importsImplicitlyReadonly.errors.txt index cc6e1918020..43596ffcea3 100644 --- a/tests/baselines/reference/importsImplicitlyReadonly.errors.txt +++ b/tests/baselines/reference/importsImplicitlyReadonly.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/externalModules/b.ts(6,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/externalModules/b.ts(7,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/externalModules/b.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/externalModules/b.ts(9,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/externalModules/b.ts(6,1): error TS2539: Cannot assign to 'x' because it is not a variable. +tests/cases/conformance/externalModules/b.ts(7,1): error TS2539: Cannot assign to 'y' because it is not a variable. +tests/cases/conformance/externalModules/b.ts(8,4): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. +tests/cases/conformance/externalModules/b.ts(9,4): error TS2540: Cannot assign to 'y' because it is a constant or a read-only property. ==== tests/cases/conformance/externalModules/b.ts (4 errors) ==== @@ -12,16 +12,16 @@ tests/cases/conformance/externalModules/b.ts(9,1): error TS2450: Left-hand side x = 1; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'x' because it is not a variable. y = 1; // Error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'y' because it is not a variable. a1.x = 1; // Error - ~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. a1.y = 1; // Error - ~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'y' because it is a constant or a read-only property. a2.x = 1; a2.y = 1; a3.x = 1; diff --git a/tests/baselines/reference/inOperatorWithGeneric.types b/tests/baselines/reference/inOperatorWithGeneric.types index facdb7b50e2..eba9bf1419b 100644 --- a/tests/baselines/reference/inOperatorWithGeneric.types +++ b/tests/baselines/reference/inOperatorWithGeneric.types @@ -9,7 +9,7 @@ class C { >T : T for (var p in x) { ->p : string +>p : keyof T >x : T } } diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt b/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt index 0985157e0da..5aeae5f160e 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt @@ -1,8 +1,6 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(12,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(13,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(14,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(16,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(17,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(19,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(20,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(30,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter @@ -19,7 +17,7 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInv tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(43,17): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter -==== tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts (19 errors) ==== +==== tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts (17 errors) ==== enum E { a } var x: any; @@ -42,11 +40,7 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInv !!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. var ra4 = a4 in x; var ra5 = null in x; - ~~~~ -!!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. var ra6 = undefined in x; - ~~~~~~~~~ -!!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. var ra7 = E.a in x; var ra8 = false in x; ~~~~~ diff --git a/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.errors.txt b/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.errors.txt new file mode 100644 index 00000000000..3f1de47c347 --- /dev/null +++ b/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/incompatibleAssignmentOfIdenticallyNamedTypes.ts(6,9): error TS90010: Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated. + + +==== tests/cases/compiler/incompatibleAssignmentOfIdenticallyNamedTypes.ts (1 errors) ==== + interface T { } + declare const a: T; + class Foo { + x: T; + fn() { + this.x = a; + ~~~~~~ +!!! error TS90010: Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated. + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.js b/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.js new file mode 100644 index 00000000000..677d177a4d0 --- /dev/null +++ b/tests/baselines/reference/incompatibleAssignmentOfIdenticallyNamedTypes.js @@ -0,0 +1,20 @@ +//// [incompatibleAssignmentOfIdenticallyNamedTypes.ts] +interface T { } +declare const a: T; +class Foo { + x: T; + fn() { + this.x = a; + } +} + + +//// [incompatibleAssignmentOfIdenticallyNamedTypes.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.fn = function () { + this.x = a; + }; + return Foo; +}()); diff --git a/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt index 4aae7f5b51e..0a303d12bf3 100644 --- a/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt @@ -1,36 +1,36 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2539: Cannot assign to 'undefined' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(48,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,27): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,25): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -74,10 +74,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber2 = ++A; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. var ResultIsNumber3 = ++M; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber4 = ++obj; ~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -90,10 +90,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber7 = A++; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'A' because it is not a variable. var ResultIsNumber8 = M++; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber9 = obj++; ~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -110,7 +110,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber13 = ++undefined; ~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'undefined' because it is not a variable. var ResultIsNumber14 = null++; ~~~~ @@ -120,28 +120,28 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. var ResultIsNumber16 = undefined++; ~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'undefined' because it is not a variable. // any type expressions var ResultIsNumber17 = ++foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber18 = ++A.foo(); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber19 = ++(null + undefined); ~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber20 = ++(null + null); ~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. var ResultIsNumber21 = ++(undefined + undefined); ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber22 = ++obj1.x; @@ -153,23 +153,23 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp var ResultIsNumber24 = foo()++; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber25 = A.foo()++; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber26 = (null + undefined)++; ~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber27 = (null + null)++; ~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. var ResultIsNumber28 = (undefined + undefined)++; ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber29 = obj1.x++; diff --git a/tests/baselines/reference/incrementOperatorWithEnumType.errors.txt b/tests/baselines/reference/incrementOperatorWithEnumType.errors.txt index fc8b682b59e..8fdbc343562 100644 --- a/tests/baselines/reference/incrementOperatorWithEnumType.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithEnumType.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(6,25): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(7,23): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(10,3): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(12,1): error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(6,31): error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(7,29): error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(10,9): error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts(12,7): error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. ==== tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumType.ts (4 errors) ==== @@ -11,17 +11,17 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // expression var ResultIsNumber1 = ++ENUM1["B"]; - ~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. var ResultIsNumber2 = ENUM1.B++; - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. // miss assignment operator ++ENUM1["B"]; - ~~~~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. + ~~~ +!!! error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. ENUM1.B++; - ~~~~~~~ -!!! error TS2449: The operand of an increment or decrement operator cannot be a constant or a read-only property. \ No newline at end of file + ~ +!!! error TS2540: Cannot assign to 'B' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt index 08a1b8ec460..ac021746157 100644 --- a/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(7,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(8,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(10,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(11,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(7,25): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(8,25): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(10,23): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(11,23): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(14,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(15,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(18,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(19,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(21,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(22,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(18,3): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(19,3): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(21,1): error TS2539: Cannot assign to 'ENUM' because it is not a variable. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(22,1): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. ==== tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts (10 errors) ==== @@ -19,17 +19,17 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // enum type var var ResultIsNumber1 = ++ENUM; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. var ResultIsNumber2 = ++ENUM1; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. var ResultIsNumber3 = ENUM++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. var ResultIsNumber4 = ENUM1++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. // enum type expressions var ResultIsNumber5 = ++(ENUM[1] + ENUM[2]); @@ -42,14 +42,14 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // miss assignment operator ++ENUM; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. ++ENUM1; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. ENUM++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'ENUM' because it is not a variable. ENUM1++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'ENUM1' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt index 71c3ad67c46..093a41aa355 100644 --- a/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt @@ -1,23 +1,23 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(35,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(35,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ==== tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts (20 errors) ==== @@ -48,7 +48,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // number type literal var ResultIsNumber3 = ++1; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber4 = ++{ x: 1, y: 2}; ~~~~~~~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -58,7 +58,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp var ResultIsNumber6 = 1++; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber7 = { x: 1, y: 2 }++; ~~~~~~~~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. @@ -69,41 +69,41 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // number type expressions var ResultIsNumber9 = ++foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber10 = ++A.foo(); ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber11 = ++(NUMBER + NUMBER); ~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber12 = foo()++; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber13 = A.foo()++; ~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber14 = (NUMBER + NUMBER)++; ~~~~~~~~~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. // miss assignment operator ++1; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ++NUMBER1; ~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. ++foo(); ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. 1++; ~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. NUMBER1++; ~~~~~~~ !!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. foo()++; ~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. \ No newline at end of file +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/indexTypeCheck.errors.txt b/tests/baselines/reference/indexTypeCheck.errors.txt index 06b844f8321..9d839e9eb30 100644 --- a/tests/baselines/reference/indexTypeCheck.errors.txt +++ b/tests/baselines/reference/indexTypeCheck.errors.txt @@ -5,7 +5,7 @@ tests/cases/compiler/indexTypeCheck.ts(22,2): error TS2413: Numeric index type ' tests/cases/compiler/indexTypeCheck.ts(27,2): error TS2413: Numeric index type 'number' is not assignable to string index type 'string'. tests/cases/compiler/indexTypeCheck.ts(32,3): error TS1096: An index signature must have exactly one parameter. tests/cases/compiler/indexTypeCheck.ts(36,3): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/indexTypeCheck.ts(51,1): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/indexTypeCheck.ts(51,8): error TS2538: Type 'Blue' cannot be used as an index type. ==== tests/cases/compiler/indexTypeCheck.ts (8 errors) ==== @@ -74,8 +74,8 @@ tests/cases/compiler/indexTypeCheck.ts(51,1): error TS2342: An index expression s[{}]; // ok yellow[blue]; // error - ~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~ +!!! error TS2538: Type 'Blue' cannot be used as an index type. var x:number[]; x[0]; diff --git a/tests/baselines/reference/indexWithUndefinedAndNull.errors.txt b/tests/baselines/reference/indexWithUndefinedAndNull.errors.txt new file mode 100644 index 00000000000..6d6fa9c39e8 --- /dev/null +++ b/tests/baselines/reference/indexWithUndefinedAndNull.errors.txt @@ -0,0 +1,28 @@ +tests/cases/compiler/indexWithUndefinedAndNull.ts(9,21): error TS2538: Type 'undefined' cannot be used as an index type. +tests/cases/compiler/indexWithUndefinedAndNull.ts(10,9): error TS2538: Type 'null' cannot be used as an index type. +tests/cases/compiler/indexWithUndefinedAndNull.ts(11,21): error TS2538: Type 'undefined' cannot be used as an index type. +tests/cases/compiler/indexWithUndefinedAndNull.ts(12,9): error TS2538: Type 'null' cannot be used as an index type. + + +==== tests/cases/compiler/indexWithUndefinedAndNull.ts (4 errors) ==== + interface N { + [n: number]: string; + } + interface S { + [s: string]: number; + } + let n: N; + let s: S; + let str: string = n[undefined]; + ~~~~~~~~~ +!!! error TS2538: Type 'undefined' cannot be used as an index type. + str = n[null]; + ~~~~ +!!! error TS2538: Type 'null' cannot be used as an index type. + let num: number = s[undefined]; + ~~~~~~~~~ +!!! error TS2538: Type 'undefined' cannot be used as an index type. + num = s[null]; + ~~~~ +!!! error TS2538: Type 'null' cannot be used as an index type. + \ No newline at end of file diff --git a/tests/baselines/reference/indexWithUndefinedAndNullStrictNullChecks.errors.txt b/tests/baselines/reference/indexWithUndefinedAndNullStrictNullChecks.errors.txt index a1fce75c54e..764ce212971 100644 --- a/tests/baselines/reference/indexWithUndefinedAndNullStrictNullChecks.errors.txt +++ b/tests/baselines/reference/indexWithUndefinedAndNullStrictNullChecks.errors.txt @@ -1,11 +1,11 @@ tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(9,19): error TS2454: Variable 'n' is used before being assigned. -tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(9,19): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(9,21): error TS2538: Type 'undefined' cannot be used as an index type. tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(10,7): error TS2454: Variable 'n' is used before being assigned. -tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(10,7): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(10,9): error TS2538: Type 'null' cannot be used as an index type. tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(11,19): error TS2454: Variable 's' is used before being assigned. -tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(11,19): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(11,21): error TS2538: Type 'undefined' cannot be used as an index type. tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(12,7): error TS2454: Variable 's' is used before being assigned. -tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(12,7): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(12,9): error TS2538: Type 'null' cannot be used as an index type. ==== tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts (8 errors) ==== @@ -20,21 +20,21 @@ tests/cases/compiler/indexWithUndefinedAndNullStrictNullChecks.ts(12,7): error T let str: string = n[undefined]; ~ !!! error TS2454: Variable 'n' is used before being assigned. - ~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~ +!!! error TS2538: Type 'undefined' cannot be used as an index type. str = n[null]; ~ !!! error TS2454: Variable 'n' is used before being assigned. - ~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~ +!!! error TS2538: Type 'null' cannot be used as an index type. let num: number = s[undefined]; ~ !!! error TS2454: Variable 's' is used before being assigned. - ~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~ +!!! error TS2538: Type 'undefined' cannot be used as an index type. num = s[null]; ~ !!! error TS2454: Variable 's' is used before being assigned. - ~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~ +!!! error TS2538: Type 'null' cannot be used as an index type. \ No newline at end of file diff --git a/tests/baselines/reference/inferenceLimit.js b/tests/baselines/reference/inferenceLimit.js index b9423ebd655..84f0989e987 100644 --- a/tests/baselines/reference/inferenceLimit.js +++ b/tests/baselines/reference/inferenceLimit.js @@ -49,7 +49,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class BrokenClass { diff --git a/tests/baselines/reference/inheritedConstructorWithRestParams.js b/tests/baselines/reference/inheritedConstructorWithRestParams.js index c9db1756676..6a30836d728 100644 --- a/tests/baselines/reference/inheritedConstructorWithRestParams.js +++ b/tests/baselines/reference/inheritedConstructorWithRestParams.js @@ -24,7 +24,7 @@ var Base = (function () { function Base() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } } return Base; diff --git a/tests/baselines/reference/initializePropertiesWithRenamedLet.js b/tests/baselines/reference/initializePropertiesWithRenamedLet.js index d53fed8c0f7..4abe488aa08 100644 --- a/tests/baselines/reference/initializePropertiesWithRenamedLet.js +++ b/tests/baselines/reference/initializePropertiesWithRenamedLet.js @@ -28,7 +28,6 @@ if (true) { var x_1 = { x: 0 }.x; var y_1 = { y: 0 }.y; var z_1; - (_a = { z: 0 }, z_1 = _a.z, _a); - (_b = { z: 0 }, z_1 = _b.z, _b); + (z_1 = { z: 0 }.z); + (z_1 = { z: 0 }.z); } -var _a, _b; diff --git a/tests/baselines/reference/initializePropertiesWithRenamedLet.types b/tests/baselines/reference/initializePropertiesWithRenamedLet.types index d6937da8983..65ea68059a7 100644 --- a/tests/baselines/reference/initializePropertiesWithRenamedLet.types +++ b/tests/baselines/reference/initializePropertiesWithRenamedLet.types @@ -10,15 +10,15 @@ if (true) { >x0 : any var obj1 = { x0: x0 }; ->obj1 : { x0: undefined; } ->{ x0: x0 } : { x0: undefined; } ->x0 : undefined ->x0 : undefined +>obj1 : { x0: any; } +>{ x0: x0 } : { x0: any; } +>x0 : any +>x0 : any var obj2 = { x0 }; ->obj2 : { x0: undefined; } ->{ x0 } : { x0: undefined; } ->x0 : undefined +>obj2 : { x0: any; } +>{ x0 } : { x0: any; } +>x0 : any } var x, y, z; diff --git a/tests/baselines/reference/innerModExport1.js b/tests/baselines/reference/innerModExport1.js index cbeced37046..285120c7462 100644 --- a/tests/baselines/reference/innerModExport1.js +++ b/tests/baselines/reference/innerModExport1.js @@ -27,10 +27,9 @@ var Outer; module; { var non_export_var = 0; - Outer.export_var = 1; + export var export_var = 1; function NonExportFunc() { return 0; } - function ExportFunc() { return 0; } - Outer.ExportFunc = ExportFunc; + export function ExportFunc() { return 0; } } Outer.outer_var_export = 0; function outerFuncExport() { return 0; } diff --git a/tests/baselines/reference/innerModExport2.js b/tests/baselines/reference/innerModExport2.js index a1526daf6f3..2024cd8284f 100644 --- a/tests/baselines/reference/innerModExport2.js +++ b/tests/baselines/reference/innerModExport2.js @@ -28,10 +28,9 @@ var Outer; module; { var non_export_var = 0; - Outer.export_var = 1; + export var export_var = 1; function NonExportFunc() { return 0; } - function ExportFunc() { return 0; } - Outer.ExportFunc = ExportFunc; + export function ExportFunc() { return 0; } } var export_var; Outer.outer_var_export = 0; diff --git a/tests/baselines/reference/instanceofWithStructurallyIdenticalTypes.errors.txt b/tests/baselines/reference/instanceofWithStructurallyIdenticalTypes.errors.txt new file mode 100644 index 00000000000..3f1e210d7b4 --- /dev/null +++ b/tests/baselines/reference/instanceofWithStructurallyIdenticalTypes.errors.txt @@ -0,0 +1,76 @@ +tests/cases/compiler/instanceofWithStructurallyIdenticalTypes.ts(32,18): error TS2339: Property 'item' does not exist on type 'never'. + + +==== tests/cases/compiler/instanceofWithStructurallyIdenticalTypes.ts (1 errors) ==== + // Repro from #7271 + + class C1 { item: string } + class C2 { item: string[] } + class C3 { item: string } + + function foo1(x: C1 | C2 | C3): string { + if (x instanceof C1) { + return x.item; + } + else if (x instanceof C2) { + return x.item[0]; + } + else if (x instanceof C3) { + return x.item; + } + return "error"; + } + + function isC1(c: C1 | C2 | C3): c is C1 { return c instanceof C1 } + function isC2(c: C1 | C2 | C3): c is C2 { return c instanceof C2 } + function isC3(c: C1 | C2 | C3): c is C3 { return c instanceof C3 } + + function foo2(x: C1 | C2 | C3): string { + if (isC1(x)) { + return x.item; + } + else if (isC2(x)) { + return x.item[0]; + } + else if (isC3(x)) { + return x.item; + ~~~~ +!!! error TS2339: Property 'item' does not exist on type 'never'. + } + return "error"; + } + + // More tests + + class A { a: string } + class A1 extends A { } + class A2 { a: string } + class B extends A { b: string } + + function goo(x: A) { + if (x instanceof A) { + x; // A + } + else { + x; // never + } + if (x instanceof A1) { + x; // A1 + } + else { + x; // A + } + if (x instanceof A2) { + x; // A2 + } + else { + x; // A + } + if (x instanceof B) { + x; // B + } + else { + x; // A + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/instantiatedModule.js b/tests/baselines/reference/instantiatedModule.js index d8ef427619a..8e7027d5fd7 100644 --- a/tests/baselines/reference/instantiatedModule.js +++ b/tests/baselines/reference/instantiatedModule.js @@ -101,11 +101,11 @@ var p2 = new m2.Point(); var p2 = new M2.Point(); var M3; (function (M3) { + var Color; (function (Color) { Color[Color["Blue"] = 0] = "Blue"; Color[Color["Red"] = 1] = "Red"; - })(M3.Color || (M3.Color = {})); - var Color = M3.Color; + })(Color = M3.Color || (M3.Color = {})); })(M3 || (M3 = {})); var m3; var m3 = M3; diff --git a/tests/baselines/reference/instantiatedTypeAliasDisplay.js b/tests/baselines/reference/instantiatedTypeAliasDisplay.js new file mode 100644 index 00000000000..9c2b91b613e --- /dev/null +++ b/tests/baselines/reference/instantiatedTypeAliasDisplay.js @@ -0,0 +1,36 @@ +//// [instantiatedTypeAliasDisplay.ts] + +// Repros from #12066 + +interface X
{ + a: A; +} +interface Y { + b: B; +} +type Z = X | Y; + +declare function f1(): Z; +declare function f2(a: A, b: B, c: C, d: D): Z; + +const x1 = f1(); // Z +const x2 = f2({}, {}, {}, {}); // Z<{}, string[]> + +//// [instantiatedTypeAliasDisplay.js] +// Repros from #12066 +var x1 = f1(); // Z +var x2 = f2({}, {}, {}, {}); // Z<{}, string[]> + + +//// [instantiatedTypeAliasDisplay.d.ts] +interface X { + a: A; +} +interface Y { + b: B; +} +declare type Z = X | Y; +declare function f1(): Z; +declare function f2(a: A, b: B, c: C, d: D): Z; +declare const x1: Z; +declare const x2: Z<{}, string[]>; diff --git a/tests/baselines/reference/instantiatedTypeAliasDisplay.symbols b/tests/baselines/reference/instantiatedTypeAliasDisplay.symbols new file mode 100644 index 00000000000..fa8140cfcd7 --- /dev/null +++ b/tests/baselines/reference/instantiatedTypeAliasDisplay.symbols @@ -0,0 +1,61 @@ +=== tests/cases/compiler/instantiatedTypeAliasDisplay.ts === + +// Repros from #12066 + +interface X { +>X : Symbol(X, Decl(instantiatedTypeAliasDisplay.ts, 0, 0)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 3, 12)) + + a: A; +>a : Symbol(X.a, Decl(instantiatedTypeAliasDisplay.ts, 3, 16)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 3, 12)) +} +interface Y { +>Y : Symbol(Y, Decl(instantiatedTypeAliasDisplay.ts, 5, 1)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 6, 12)) + + b: B; +>b : Symbol(Y.b, Decl(instantiatedTypeAliasDisplay.ts, 6, 16)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 6, 12)) +} +type Z = X | Y; +>Z : Symbol(Z, Decl(instantiatedTypeAliasDisplay.ts, 8, 1)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 9, 7)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 9, 9)) +>X : Symbol(X, Decl(instantiatedTypeAliasDisplay.ts, 0, 0)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 9, 7)) +>Y : Symbol(Y, Decl(instantiatedTypeAliasDisplay.ts, 5, 1)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 9, 9)) + +declare function f1(): Z; +>f1 : Symbol(f1, Decl(instantiatedTypeAliasDisplay.ts, 9, 27)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 11, 20)) +>Z : Symbol(Z, Decl(instantiatedTypeAliasDisplay.ts, 8, 1)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 11, 20)) + +declare function f2(a: A, b: B, c: C, d: D): Z; +>f2 : Symbol(f2, Decl(instantiatedTypeAliasDisplay.ts, 11, 39)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 12, 20)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 12, 22)) +>C : Symbol(C, Decl(instantiatedTypeAliasDisplay.ts, 12, 25)) +>D : Symbol(D, Decl(instantiatedTypeAliasDisplay.ts, 12, 28)) +>E : Symbol(E, Decl(instantiatedTypeAliasDisplay.ts, 12, 31)) +>a : Symbol(a, Decl(instantiatedTypeAliasDisplay.ts, 12, 35)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 12, 20)) +>b : Symbol(b, Decl(instantiatedTypeAliasDisplay.ts, 12, 40)) +>B : Symbol(B, Decl(instantiatedTypeAliasDisplay.ts, 12, 22)) +>c : Symbol(c, Decl(instantiatedTypeAliasDisplay.ts, 12, 46)) +>C : Symbol(C, Decl(instantiatedTypeAliasDisplay.ts, 12, 25)) +>d : Symbol(d, Decl(instantiatedTypeAliasDisplay.ts, 12, 52)) +>D : Symbol(D, Decl(instantiatedTypeAliasDisplay.ts, 12, 28)) +>Z : Symbol(Z, Decl(instantiatedTypeAliasDisplay.ts, 8, 1)) +>A : Symbol(A, Decl(instantiatedTypeAliasDisplay.ts, 12, 20)) + +const x1 = f1(); // Z +>x1 : Symbol(x1, Decl(instantiatedTypeAliasDisplay.ts, 14, 5)) +>f1 : Symbol(f1, Decl(instantiatedTypeAliasDisplay.ts, 9, 27)) + +const x2 = f2({}, {}, {}, {}); // Z<{}, string[]> +>x2 : Symbol(x2, Decl(instantiatedTypeAliasDisplay.ts, 15, 5)) +>f2 : Symbol(f2, Decl(instantiatedTypeAliasDisplay.ts, 11, 39)) + diff --git a/tests/baselines/reference/instantiatedTypeAliasDisplay.types b/tests/baselines/reference/instantiatedTypeAliasDisplay.types new file mode 100644 index 00000000000..89320e1dba6 --- /dev/null +++ b/tests/baselines/reference/instantiatedTypeAliasDisplay.types @@ -0,0 +1,67 @@ +=== tests/cases/compiler/instantiatedTypeAliasDisplay.ts === + +// Repros from #12066 + +interface X { +>X : X +>A : A + + a: A; +>a : A +>A : A +} +interface Y { +>Y : Y +>B : B + + b: B; +>b : B +>B : B +} +type Z = X | Y; +>Z : Z +>A : A +>B : B +>X : X +>A : A +>Y : Y +>B : B + +declare function f1(): Z; +>f1 : () => Z +>A : A +>Z : Z +>A : A + +declare function f2(a: A, b: B, c: C, d: D): Z; +>f2 : (a: A, b: B, c: C, d: D) => Z +>A : A +>B : B +>C : C +>D : D +>E : E +>a : A +>A : A +>b : B +>B : B +>c : C +>C : C +>d : D +>D : D +>Z : Z +>A : A + +const x1 = f1(); // Z +>x1 : Z +>f1() : Z +>f1 : () => Z + +const x2 = f2({}, {}, {}, {}); // Z<{}, string[]> +>x2 : Z<{}, string[]> +>f2({}, {}, {}, {}) : Z<{}, string[]> +>f2 : (a: A, b: B, c: C, d: D) => Z +>{} : {} +>{} : {} +>{} : {} +>{} : {} + diff --git a/tests/baselines/reference/interfaceAssignmentCompat.js b/tests/baselines/reference/interfaceAssignmentCompat.js index edaebbd38a2..98586da24e5 100644 --- a/tests/baselines/reference/interfaceAssignmentCompat.js +++ b/tests/baselines/reference/interfaceAssignmentCompat.js @@ -55,12 +55,12 @@ M.test(); //// [interfaceAssignmentCompat.js] var M; (function (M) { + var Color; (function (Color) { Color[Color["Green"] = 0] = "Green"; Color[Color["Blue"] = 1] = "Blue"; Color[Color["Brown"] = 2] = "Brown"; - })(M.Color || (M.Color = {})); - var Color = M.Color; + })(Color = M.Color || (M.Color = {})); function CompareEyes(a, b) { return a.color - b.color; } diff --git a/tests/baselines/reference/interfaceSpread.errors.txt b/tests/baselines/reference/interfaceSpread.errors.txt new file mode 100644 index 00000000000..c6acc633912 --- /dev/null +++ b/tests/baselines/reference/interfaceSpread.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/types/spread/interfaceSpread.ts(2,5): error TS2698: Interface declaration cannot contain a spread property. +tests/cases/conformance/types/spread/interfaceSpread.ts(7,10): error TS2339: Property 'jam' does not exist on type 'Congealed<{ jam: number; }, { peanutButter: number; }>'. +tests/cases/conformance/types/spread/interfaceSpread.ts(8,10): error TS2339: Property 'peanutButter' does not exist on type 'Congealed<{ jam: number; }, { peanutButter: number; }>'. + + +==== tests/cases/conformance/types/spread/interfaceSpread.ts (3 errors) ==== + interface Congealed { + ...T + ~~~~ +!!! error TS2698: Interface declaration cannot contain a spread property. + ...U + } + + let sandwich: Congealed<{jam: number }, { peanutButter: number }>; + sandwich.jam; + ~~~ +!!! error TS2339: Property 'jam' does not exist on type 'Congealed<{ jam: number; }, { peanutButter: number; }>'. + sandwich.peanutButter; + ~~~~~~~~~~~~ +!!! error TS2339: Property 'peanutButter' does not exist on type 'Congealed<{ jam: number; }, { peanutButter: number; }>'. + \ No newline at end of file diff --git a/tests/baselines/reference/interfaceSpread.js b/tests/baselines/reference/interfaceSpread.js new file mode 100644 index 00000000000..89f25314366 --- /dev/null +++ b/tests/baselines/reference/interfaceSpread.js @@ -0,0 +1,15 @@ +//// [interfaceSpread.ts] +interface Congealed { + ...T + ...U +} + +let sandwich: Congealed<{jam: number }, { peanutButter: number }>; +sandwich.jam; +sandwich.peanutButter; + + +//// [interfaceSpread.js] +var sandwich; +sandwich.jam; +sandwich.peanutButter; diff --git a/tests/baselines/reference/internalAliasEnum.js b/tests/baselines/reference/internalAliasEnum.js index 6400cf26ddc..40fac82eb4d 100644 --- a/tests/baselines/reference/internalAliasEnum.js +++ b/tests/baselines/reference/internalAliasEnum.js @@ -16,12 +16,12 @@ module c { //// [internalAliasEnum.js] var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a || (a = {})); var c; (function (c) { diff --git a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js index dd30dc814ae..c7b8bf2cacc 100644 --- a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js @@ -17,12 +17,12 @@ export module c { "use strict"; var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a = exports.a || (exports.a = {})); var c; (function (c) { diff --git a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js index 7f00d69a8d6..267fffc7b70 100644 --- a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js @@ -17,12 +17,12 @@ export module c { "use strict"; var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a = exports.a || (exports.a = {})); var c; (function (c) { diff --git a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExportAccessError.js b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExportAccessError.js index 8612e74f829..a44298b6864 100644 --- a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExportAccessError.js +++ b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExportAccessError.js @@ -18,12 +18,12 @@ var happyFriday = c.b.Friday; "use strict"; var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a = exports.a || (exports.a = {})); var c; (function (c) { diff --git a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js index c7396fded2a..8e11f60dcc7 100644 --- a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js @@ -16,12 +16,12 @@ define(["require", "exports"], function (require, exports) { "use strict"; var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a = exports.a || (exports.a = {})); exports.b = a.weekend; exports.bVal = exports.b.Sunday; diff --git a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js index 1cf1b0b8b16..8ec0dcea815 100644 --- a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js @@ -16,12 +16,12 @@ define(["require", "exports"], function (require, exports) { "use strict"; var a; (function (a) { + var weekend; (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; - })(a.weekend || (a.weekend = {})); - var weekend = a.weekend; + })(weekend = a.weekend || (a.weekend = {})); })(a = exports.a || (exports.a = {})); var b = a.weekend; exports.bVal = b.Sunday; diff --git a/tests/baselines/reference/intersectionAndUnionTypes.errors.txt b/tests/baselines/reference/intersectionAndUnionTypes.errors.txt index 5a04d4f25d3..62ddfd497a3 100644 --- a/tests/baselines/reference/intersectionAndUnionTypes.errors.txt +++ b/tests/baselines/reference/intersectionAndUnionTypes.errors.txt @@ -30,28 +30,29 @@ tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(29,1): e Type 'A & B' is not assignable to type 'C | D'. Type 'A & B' is not assignable to type 'D'. Property 'd' is missing in type 'A & B'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(31,1): error TS2322: Type 'A & B' is not assignable to type '(A | B) & (C | D)'. - Type 'A & B' is not assignable to type 'C | D'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(31,1): error TS2322: Type 'A & B' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'A & B' is not assignable to type 'B & D'. Type 'A & B' is not assignable to type 'D'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(32,1): error TS2322: Type 'A | B' is not assignable to type '(A | B) & (C | D)'. - Type 'A' is not assignable to type '(A | B) & (C | D)'. - Type 'A' is not assignable to type 'C | D'. - Type 'A' is not assignable to type 'D'. - Property 'd' is missing in type 'A'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(33,1): error TS2322: Type 'C & D' is not assignable to type '(A | B) & (C | D)'. - Type 'C & D' is not assignable to type 'A | B'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(32,1): error TS2322: Type 'A | B' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'A' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'A' is not assignable to type 'B & D'. + Type 'A' is not assignable to type 'B'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(33,1): error TS2322: Type 'C & D' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'C & D' is not assignable to type 'B & D'. Type 'C & D' is not assignable to type 'B'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(34,1): error TS2322: Type 'C | D' is not assignable to type '(A | B) & (C | D)'. - Type 'C' is not assignable to type '(A | B) & (C | D)'. - Type 'C' is not assignable to type 'A | B'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(34,1): error TS2322: Type 'C | D' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'C' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. + Type 'C' is not assignable to type 'B & D'. Type 'C' is not assignable to type 'B'. Property 'b' is missing in type 'C'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(35,1): error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'A & B'. - Type '(A | B) & (C | D)' is not assignable to type 'A'. - Property 'a' is missing in type '(A | B) & (C | D)'. -tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(37,1): error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'C & D'. - Type '(A | B) & (C | D)' is not assignable to type 'C'. - Property 'c' is missing in type '(A | B) & (C | D)'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(35,1): error TS2322: Type '(A & C) | (A & D) | (B & C) | (B & D)' is not assignable to type 'A & B'. + Type 'A & C' is not assignable to type 'A & B'. + Type 'A & C' is not assignable to type 'B'. + Property 'b' is missing in type 'A & C'. +tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(37,1): error TS2322: Type '(A & C) | (A & D) | (B & C) | (B & D)' is not assignable to type 'C & D'. + Type 'A & C' is not assignable to type 'C & D'. + Type 'A & C' is not assignable to type 'D'. + Property 'd' is missing in type 'A & C'. ==== tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts (14 errors) ==== @@ -127,38 +128,39 @@ tests/cases/conformance/types/intersection/intersectionAndUnionTypes.ts(37,1): e y = anb; ~ -!!! error TS2322: Type 'A & B' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'A & B' is not assignable to type 'C | D'. +!!! error TS2322: Type 'A & B' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'A & B' is not assignable to type 'B & D'. !!! error TS2322: Type 'A & B' is not assignable to type 'D'. y = aob; ~ -!!! error TS2322: Type 'A | B' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'A' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'A' is not assignable to type 'C | D'. -!!! error TS2322: Type 'A' is not assignable to type 'D'. -!!! error TS2322: Property 'd' is missing in type 'A'. +!!! error TS2322: Type 'A | B' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'A' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'A' is not assignable to type 'B & D'. +!!! error TS2322: Type 'A' is not assignable to type 'B'. y = cnd; ~ -!!! error TS2322: Type 'C & D' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'C & D' is not assignable to type 'A | B'. +!!! error TS2322: Type 'C & D' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'C & D' is not assignable to type 'B & D'. !!! error TS2322: Type 'C & D' is not assignable to type 'B'. y = cod; ~ -!!! error TS2322: Type 'C | D' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'C' is not assignable to type '(A | B) & (C | D)'. -!!! error TS2322: Type 'C' is not assignable to type 'A | B'. +!!! error TS2322: Type 'C | D' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'C' is not assignable to type '(A & C) | (A & D) | (B & C) | (B & D)'. +!!! error TS2322: Type 'C' is not assignable to type 'B & D'. !!! error TS2322: Type 'C' is not assignable to type 'B'. !!! error TS2322: Property 'b' is missing in type 'C'. anb = y; ~~~ -!!! error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'A & B'. -!!! error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'A'. -!!! error TS2322: Property 'a' is missing in type '(A | B) & (C | D)'. +!!! error TS2322: Type '(A & C) | (A & D) | (B & C) | (B & D)' is not assignable to type 'A & B'. +!!! error TS2322: Type 'A & C' is not assignable to type 'A & B'. +!!! error TS2322: Type 'A & C' is not assignable to type 'B'. +!!! error TS2322: Property 'b' is missing in type 'A & C'. aob = y; // Ok cnd = y; ~~~ -!!! error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'C & D'. -!!! error TS2322: Type '(A | B) & (C | D)' is not assignable to type 'C'. -!!! error TS2322: Property 'c' is missing in type '(A | B) & (C | D)'. +!!! error TS2322: Type '(A & C) | (A & D) | (B & C) | (B & D)' is not assignable to type 'C & D'. +!!! error TS2322: Type 'A & C' is not assignable to type 'C & D'. +!!! error TS2322: Type 'A & C' is not assignable to type 'D'. +!!! error TS2322: Property 'd' is missing in type 'A & C'. cod = y; // Ok \ No newline at end of file diff --git a/tests/baselines/reference/intersectionTypeNormalization.js b/tests/baselines/reference/intersectionTypeNormalization.js new file mode 100644 index 00000000000..f6eea23e98e --- /dev/null +++ b/tests/baselines/reference/intersectionTypeNormalization.js @@ -0,0 +1,129 @@ +//// [intersectionTypeNormalization.ts] +interface A { a: string } +interface B { b: string } +interface C { c: string } +interface D { d: string } + +// Identical ways of writing the same type +type X1 = (A | B) & (C | D); +type X2 = A & (C | D) | B & (C | D) +type X3 = A & C | A & D | B & C | B & D; + +var x: X1; +var x: X2; +var x: X3; + +interface X { x: string } +interface Y { y: string } + +// Identical ways of writing the same type +type Y1 = (A | X & Y) & (C | D); +type Y2 = A & (C | D) | X & Y & (C | D) +type Y3 = A & C | A & D | X & Y & C | X & Y & D; + +var y: Y1; +var y: Y2; +var y: Y3; + +interface M { m: string } +interface N { n: string } + +// Identical ways of writing the same type +type Z1 = (A | X & (M | N)) & (C | D); +type Z2 = A & (C | D) | X & (M | N) & (C | D) +type Z3 = A & C | A & D | X & (M | N) & C | X & (M | N) & D; +type Z4 = A & C | A & D | X & M & C | X & N & C | X & M & D | X & N & D; + +var z: Z1; +var z: Z2; +var z: Z3; +var z: Z4; + +// Repro from #9919 + +type ToString = { + toString(): string; +} + +type BoxedValue = { kind: 'int', num: number } + | { kind: 'string', str: string } + +type IntersectionFail = BoxedValue & ToString + +type IntersectionInline = { kind: 'int', num: number } & ToString + | { kind: 'string', str: string } & ToString + +function getValueAsString(value: IntersectionFail): string { + if (value.kind === 'int') { + return '' + value.num; + } + return value.str; +} + +// Repro from #12535 + +namespace enums { + export const enum A { + a1, + a2, + a3, + // ... elements omitted for the sake of clarity + a75, + a76, + a77, + } + export const enum B { + b1, + b2, + // ... elements omitted for the sake of clarity + b86, + b87, + } + export const enum C { + c1, + c2, + // ... elements omitted for the sake of clarity + c210, + c211, + } + export type Genre = A | B | C; +} + +type Foo = { + genreId: enums.Genre; +}; + +type Bar = { + genreId: enums.Genre; +}; + +type FooBar = Foo & Bar; + +function foo(so: any) { + const val = so as FooBar; + const isGenre = val.genreId; + return isGenre; +} + +//// [intersectionTypeNormalization.js] +var x; +var x; +var x; +var y; +var y; +var y; +var z; +var z; +var z; +var z; +function getValueAsString(value) { + if (value.kind === 'int') { + return '' + value.num; + } + return value.str; +} +function foo(so) { + var val = so; + var isGenre = val.genreId; + return isGenre; +} diff --git a/tests/baselines/reference/intersectionTypeNormalization.symbols b/tests/baselines/reference/intersectionTypeNormalization.symbols new file mode 100644 index 00000000000..fd81eac6d18 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeNormalization.symbols @@ -0,0 +1,352 @@ +=== tests/cases/compiler/intersectionTypeNormalization.ts === +interface A { a: string } +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>a : Symbol(A.a, Decl(intersectionTypeNormalization.ts, 0, 13)) + +interface B { b: string } +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 0, 25)) +>b : Symbol(B.b, Decl(intersectionTypeNormalization.ts, 1, 13)) + +interface C { c: string } +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>c : Symbol(C.c, Decl(intersectionTypeNormalization.ts, 2, 13)) + +interface D { d: string } +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>d : Symbol(D.d, Decl(intersectionTypeNormalization.ts, 3, 13)) + +// Identical ways of writing the same type +type X1 = (A | B) & (C | D); +>X1 : Symbol(X1, Decl(intersectionTypeNormalization.ts, 3, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 0, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type X2 = A & (C | D) | B & (C | D) +>X2 : Symbol(X2, Decl(intersectionTypeNormalization.ts, 6, 28)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 0, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type X3 = A & C | A & D | B & C | B & D; +>X3 : Symbol(X3, Decl(intersectionTypeNormalization.ts, 7, 35)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 0, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 0, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +var x: X1; +>x : Symbol(x, Decl(intersectionTypeNormalization.ts, 10, 3), Decl(intersectionTypeNormalization.ts, 11, 3), Decl(intersectionTypeNormalization.ts, 12, 3)) +>X1 : Symbol(X1, Decl(intersectionTypeNormalization.ts, 3, 25)) + +var x: X2; +>x : Symbol(x, Decl(intersectionTypeNormalization.ts, 10, 3), Decl(intersectionTypeNormalization.ts, 11, 3), Decl(intersectionTypeNormalization.ts, 12, 3)) +>X2 : Symbol(X2, Decl(intersectionTypeNormalization.ts, 6, 28)) + +var x: X3; +>x : Symbol(x, Decl(intersectionTypeNormalization.ts, 10, 3), Decl(intersectionTypeNormalization.ts, 11, 3), Decl(intersectionTypeNormalization.ts, 12, 3)) +>X3 : Symbol(X3, Decl(intersectionTypeNormalization.ts, 7, 35)) + +interface X { x: string } +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>x : Symbol(X.x, Decl(intersectionTypeNormalization.ts, 14, 13)) + +interface Y { y: string } +>Y : Symbol(Y, Decl(intersectionTypeNormalization.ts, 14, 25)) +>y : Symbol(Y.y, Decl(intersectionTypeNormalization.ts, 15, 13)) + +// Identical ways of writing the same type +type Y1 = (A | X & Y) & (C | D); +>Y1 : Symbol(Y1, Decl(intersectionTypeNormalization.ts, 15, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>Y : Symbol(Y, Decl(intersectionTypeNormalization.ts, 14, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type Y2 = A & (C | D) | X & Y & (C | D) +>Y2 : Symbol(Y2, Decl(intersectionTypeNormalization.ts, 18, 32)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>Y : Symbol(Y, Decl(intersectionTypeNormalization.ts, 14, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type Y3 = A & C | A & D | X & Y & C | X & Y & D; +>Y3 : Symbol(Y3, Decl(intersectionTypeNormalization.ts, 19, 39)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>Y : Symbol(Y, Decl(intersectionTypeNormalization.ts, 14, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>Y : Symbol(Y, Decl(intersectionTypeNormalization.ts, 14, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +var y: Y1; +>y : Symbol(y, Decl(intersectionTypeNormalization.ts, 22, 3), Decl(intersectionTypeNormalization.ts, 23, 3), Decl(intersectionTypeNormalization.ts, 24, 3)) +>Y1 : Symbol(Y1, Decl(intersectionTypeNormalization.ts, 15, 25)) + +var y: Y2; +>y : Symbol(y, Decl(intersectionTypeNormalization.ts, 22, 3), Decl(intersectionTypeNormalization.ts, 23, 3), Decl(intersectionTypeNormalization.ts, 24, 3)) +>Y2 : Symbol(Y2, Decl(intersectionTypeNormalization.ts, 18, 32)) + +var y: Y3; +>y : Symbol(y, Decl(intersectionTypeNormalization.ts, 22, 3), Decl(intersectionTypeNormalization.ts, 23, 3), Decl(intersectionTypeNormalization.ts, 24, 3)) +>Y3 : Symbol(Y3, Decl(intersectionTypeNormalization.ts, 19, 39)) + +interface M { m: string } +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>m : Symbol(M.m, Decl(intersectionTypeNormalization.ts, 26, 13)) + +interface N { n: string } +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>n : Symbol(N.n, Decl(intersectionTypeNormalization.ts, 27, 13)) + +// Identical ways of writing the same type +type Z1 = (A | X & (M | N)) & (C | D); +>Z1 : Symbol(Z1, Decl(intersectionTypeNormalization.ts, 27, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type Z2 = A & (C | D) | X & (M | N) & (C | D) +>Z2 : Symbol(Z2, Decl(intersectionTypeNormalization.ts, 30, 38)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type Z3 = A & C | A & D | X & (M | N) & C | X & (M | N) & D; +>Z3 : Symbol(Z3, Decl(intersectionTypeNormalization.ts, 31, 45)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +type Z4 = A & C | A & D | X & M & C | X & N & C | X & M & D | X & N & D; +>Z4 : Symbol(Z4, Decl(intersectionTypeNormalization.ts, 32, 60)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 0, 0)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 1, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>M : Symbol(M, Decl(intersectionTypeNormalization.ts, 24, 10)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) +>X : Symbol(X, Decl(intersectionTypeNormalization.ts, 12, 10)) +>N : Symbol(N, Decl(intersectionTypeNormalization.ts, 26, 25)) +>D : Symbol(D, Decl(intersectionTypeNormalization.ts, 2, 25)) + +var z: Z1; +>z : Symbol(z, Decl(intersectionTypeNormalization.ts, 35, 3), Decl(intersectionTypeNormalization.ts, 36, 3), Decl(intersectionTypeNormalization.ts, 37, 3), Decl(intersectionTypeNormalization.ts, 38, 3)) +>Z1 : Symbol(Z1, Decl(intersectionTypeNormalization.ts, 27, 25)) + +var z: Z2; +>z : Symbol(z, Decl(intersectionTypeNormalization.ts, 35, 3), Decl(intersectionTypeNormalization.ts, 36, 3), Decl(intersectionTypeNormalization.ts, 37, 3), Decl(intersectionTypeNormalization.ts, 38, 3)) +>Z2 : Symbol(Z2, Decl(intersectionTypeNormalization.ts, 30, 38)) + +var z: Z3; +>z : Symbol(z, Decl(intersectionTypeNormalization.ts, 35, 3), Decl(intersectionTypeNormalization.ts, 36, 3), Decl(intersectionTypeNormalization.ts, 37, 3), Decl(intersectionTypeNormalization.ts, 38, 3)) +>Z3 : Symbol(Z3, Decl(intersectionTypeNormalization.ts, 31, 45)) + +var z: Z4; +>z : Symbol(z, Decl(intersectionTypeNormalization.ts, 35, 3), Decl(intersectionTypeNormalization.ts, 36, 3), Decl(intersectionTypeNormalization.ts, 37, 3), Decl(intersectionTypeNormalization.ts, 38, 3)) +>Z4 : Symbol(Z4, Decl(intersectionTypeNormalization.ts, 32, 60)) + +// Repro from #9919 + +type ToString = { +>ToString : Symbol(ToString, Decl(intersectionTypeNormalization.ts, 38, 10)) + + toString(): string; +>toString : Symbol(toString, Decl(intersectionTypeNormalization.ts, 42, 17)) +} + +type BoxedValue = { kind: 'int', num: number } +>BoxedValue : Symbol(BoxedValue, Decl(intersectionTypeNormalization.ts, 44, 1)) +>kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 46, 19)) +>num : Symbol(num, Decl(intersectionTypeNormalization.ts, 46, 32)) + + | { kind: 'string', str: string } +>kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 47, 19)) +>str : Symbol(str, Decl(intersectionTypeNormalization.ts, 47, 35)) + +type IntersectionFail = BoxedValue & ToString +>IntersectionFail : Symbol(IntersectionFail, Decl(intersectionTypeNormalization.ts, 47, 49)) +>BoxedValue : Symbol(BoxedValue, Decl(intersectionTypeNormalization.ts, 44, 1)) +>ToString : Symbol(ToString, Decl(intersectionTypeNormalization.ts, 38, 10)) + +type IntersectionInline = { kind: 'int', num: number } & ToString +>IntersectionInline : Symbol(IntersectionInline, Decl(intersectionTypeNormalization.ts, 49, 45)) +>kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 51, 27)) +>num : Symbol(num, Decl(intersectionTypeNormalization.ts, 51, 40)) +>ToString : Symbol(ToString, Decl(intersectionTypeNormalization.ts, 38, 10)) + + | { kind: 'string', str: string } & ToString +>kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 52, 27)) +>str : Symbol(str, Decl(intersectionTypeNormalization.ts, 52, 43)) +>ToString : Symbol(ToString, Decl(intersectionTypeNormalization.ts, 38, 10)) + +function getValueAsString(value: IntersectionFail): string { +>getValueAsString : Symbol(getValueAsString, Decl(intersectionTypeNormalization.ts, 52, 68)) +>value : Symbol(value, Decl(intersectionTypeNormalization.ts, 54, 26)) +>IntersectionFail : Symbol(IntersectionFail, Decl(intersectionTypeNormalization.ts, 47, 49)) + + if (value.kind === 'int') { +>value.kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 46, 19), Decl(intersectionTypeNormalization.ts, 47, 19)) +>value : Symbol(value, Decl(intersectionTypeNormalization.ts, 54, 26)) +>kind : Symbol(kind, Decl(intersectionTypeNormalization.ts, 46, 19), Decl(intersectionTypeNormalization.ts, 47, 19)) + + return '' + value.num; +>value.num : Symbol(num, Decl(intersectionTypeNormalization.ts, 46, 32)) +>value : Symbol(value, Decl(intersectionTypeNormalization.ts, 54, 26)) +>num : Symbol(num, Decl(intersectionTypeNormalization.ts, 46, 32)) + } + return value.str; +>value.str : Symbol(str, Decl(intersectionTypeNormalization.ts, 47, 35)) +>value : Symbol(value, Decl(intersectionTypeNormalization.ts, 54, 26)) +>str : Symbol(str, Decl(intersectionTypeNormalization.ts, 47, 35)) +} + +// Repro from #12535 + +namespace enums { +>enums : Symbol(enums, Decl(intersectionTypeNormalization.ts, 59, 1)) + + export const enum A { +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 63, 17)) + + a1, +>a1 : Symbol(A.a1, Decl(intersectionTypeNormalization.ts, 64, 25)) + + a2, +>a2 : Symbol(A.a2, Decl(intersectionTypeNormalization.ts, 65, 11)) + + a3, +>a3 : Symbol(A.a3, Decl(intersectionTypeNormalization.ts, 66, 11)) + + // ... elements omitted for the sake of clarity + a75, +>a75 : Symbol(A.a75, Decl(intersectionTypeNormalization.ts, 67, 11)) + + a76, +>a76 : Symbol(A.a76, Decl(intersectionTypeNormalization.ts, 69, 12)) + + a77, +>a77 : Symbol(A.a77, Decl(intersectionTypeNormalization.ts, 70, 12)) + } + export const enum B { +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 72, 5)) + + b1, +>b1 : Symbol(B.b1, Decl(intersectionTypeNormalization.ts, 73, 25)) + + b2, +>b2 : Symbol(B.b2, Decl(intersectionTypeNormalization.ts, 74, 11)) + + // ... elements omitted for the sake of clarity + b86, +>b86 : Symbol(B.b86, Decl(intersectionTypeNormalization.ts, 75, 11)) + + b87, +>b87 : Symbol(B.b87, Decl(intersectionTypeNormalization.ts, 77, 12)) + } + export const enum C { +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 79, 5)) + + c1, +>c1 : Symbol(C.c1, Decl(intersectionTypeNormalization.ts, 80, 25)) + + c2, +>c2 : Symbol(C.c2, Decl(intersectionTypeNormalization.ts, 81, 11)) + + // ... elements omitted for the sake of clarity + c210, +>c210 : Symbol(C.c210, Decl(intersectionTypeNormalization.ts, 82, 11)) + + c211, +>c211 : Symbol(C.c211, Decl(intersectionTypeNormalization.ts, 84, 13)) + } + export type Genre = A | B | C; +>Genre : Symbol(Genre, Decl(intersectionTypeNormalization.ts, 86, 5)) +>A : Symbol(A, Decl(intersectionTypeNormalization.ts, 63, 17)) +>B : Symbol(B, Decl(intersectionTypeNormalization.ts, 72, 5)) +>C : Symbol(C, Decl(intersectionTypeNormalization.ts, 79, 5)) +} + +type Foo = { +>Foo : Symbol(Foo, Decl(intersectionTypeNormalization.ts, 88, 1)) + + genreId: enums.Genre; +>genreId : Symbol(genreId, Decl(intersectionTypeNormalization.ts, 90, 12)) +>enums : Symbol(enums, Decl(intersectionTypeNormalization.ts, 59, 1)) +>Genre : Symbol(enums.Genre, Decl(intersectionTypeNormalization.ts, 86, 5)) + +}; + +type Bar = { +>Bar : Symbol(Bar, Decl(intersectionTypeNormalization.ts, 92, 2)) + + genreId: enums.Genre; +>genreId : Symbol(genreId, Decl(intersectionTypeNormalization.ts, 94, 12)) +>enums : Symbol(enums, Decl(intersectionTypeNormalization.ts, 59, 1)) +>Genre : Symbol(enums.Genre, Decl(intersectionTypeNormalization.ts, 86, 5)) + +}; + +type FooBar = Foo & Bar; +>FooBar : Symbol(FooBar, Decl(intersectionTypeNormalization.ts, 96, 2)) +>Foo : Symbol(Foo, Decl(intersectionTypeNormalization.ts, 88, 1)) +>Bar : Symbol(Bar, Decl(intersectionTypeNormalization.ts, 92, 2)) + +function foo(so: any) { +>foo : Symbol(foo, Decl(intersectionTypeNormalization.ts, 98, 24)) +>so : Symbol(so, Decl(intersectionTypeNormalization.ts, 100, 13)) + + const val = so as FooBar; +>val : Symbol(val, Decl(intersectionTypeNormalization.ts, 101, 9)) +>so : Symbol(so, Decl(intersectionTypeNormalization.ts, 100, 13)) +>FooBar : Symbol(FooBar, Decl(intersectionTypeNormalization.ts, 96, 2)) + + const isGenre = val.genreId; +>isGenre : Symbol(isGenre, Decl(intersectionTypeNormalization.ts, 102, 9)) +>val.genreId : Symbol(genreId, Decl(intersectionTypeNormalization.ts, 90, 12), Decl(intersectionTypeNormalization.ts, 94, 12)) +>val : Symbol(val, Decl(intersectionTypeNormalization.ts, 101, 9)) +>genreId : Symbol(genreId, Decl(intersectionTypeNormalization.ts, 90, 12), Decl(intersectionTypeNormalization.ts, 94, 12)) + + return isGenre; +>isGenre : Symbol(isGenre, Decl(intersectionTypeNormalization.ts, 102, 9)) +} diff --git a/tests/baselines/reference/intersectionTypeNormalization.types b/tests/baselines/reference/intersectionTypeNormalization.types new file mode 100644 index 00000000000..3ffe7484afe --- /dev/null +++ b/tests/baselines/reference/intersectionTypeNormalization.types @@ -0,0 +1,357 @@ +=== tests/cases/compiler/intersectionTypeNormalization.ts === +interface A { a: string } +>A : A +>a : string + +interface B { b: string } +>B : B +>b : string + +interface C { c: string } +>C : C +>c : string + +interface D { d: string } +>D : D +>d : string + +// Identical ways of writing the same type +type X1 = (A | B) & (C | D); +>X1 : X1 +>A : A +>B : B +>C : C +>D : D + +type X2 = A & (C | D) | B & (C | D) +>X2 : X1 +>A : A +>C : C +>D : D +>B : B +>C : C +>D : D + +type X3 = A & C | A & D | B & C | B & D; +>X3 : X1 +>A : A +>C : C +>A : A +>D : D +>B : B +>C : C +>B : B +>D : D + +var x: X1; +>x : X1 +>X1 : X1 + +var x: X2; +>x : X1 +>X2 : X1 + +var x: X3; +>x : X1 +>X3 : X1 + +interface X { x: string } +>X : X +>x : string + +interface Y { y: string } +>Y : Y +>y : string + +// Identical ways of writing the same type +type Y1 = (A | X & Y) & (C | D); +>Y1 : Y1 +>A : A +>X : X +>Y : Y +>C : C +>D : D + +type Y2 = A & (C | D) | X & Y & (C | D) +>Y2 : Y1 +>A : A +>C : C +>D : D +>X : X +>Y : Y +>C : C +>D : D + +type Y3 = A & C | A & D | X & Y & C | X & Y & D; +>Y3 : Y1 +>A : A +>C : C +>A : A +>D : D +>X : X +>Y : Y +>C : C +>X : X +>Y : Y +>D : D + +var y: Y1; +>y : Y1 +>Y1 : Y1 + +var y: Y2; +>y : Y1 +>Y2 : Y1 + +var y: Y3; +>y : Y1 +>Y3 : Y1 + +interface M { m: string } +>M : M +>m : string + +interface N { n: string } +>N : N +>n : string + +// Identical ways of writing the same type +type Z1 = (A | X & (M | N)) & (C | D); +>Z1 : Z1 +>A : A +>X : X +>M : M +>N : N +>C : C +>D : D + +type Z2 = A & (C | D) | X & (M | N) & (C | D) +>Z2 : Z1 +>A : A +>C : C +>D : D +>X : X +>M : M +>N : N +>C : C +>D : D + +type Z3 = A & C | A & D | X & (M | N) & C | X & (M | N) & D; +>Z3 : Z1 +>A : A +>C : C +>A : A +>D : D +>X : X +>M : M +>N : N +>C : C +>X : X +>M : M +>N : N +>D : D + +type Z4 = A & C | A & D | X & M & C | X & N & C | X & M & D | X & N & D; +>Z4 : Z1 +>A : A +>C : C +>A : A +>D : D +>X : X +>M : M +>C : C +>X : X +>N : N +>C : C +>X : X +>M : M +>D : D +>X : X +>N : N +>D : D + +var z: Z1; +>z : Z1 +>Z1 : Z1 + +var z: Z2; +>z : Z1 +>Z2 : Z1 + +var z: Z3; +>z : Z1 +>Z3 : Z1 + +var z: Z4; +>z : Z1 +>Z4 : Z1 + +// Repro from #9919 + +type ToString = { +>ToString : ToString + + toString(): string; +>toString : () => string +} + +type BoxedValue = { kind: 'int', num: number } +>BoxedValue : BoxedValue +>kind : "int" +>num : number + + | { kind: 'string', str: string } +>kind : "string" +>str : string + +type IntersectionFail = BoxedValue & ToString +>IntersectionFail : IntersectionFail +>BoxedValue : BoxedValue +>ToString : ToString + +type IntersectionInline = { kind: 'int', num: number } & ToString +>IntersectionInline : IntersectionInline +>kind : "int" +>num : number +>ToString : ToString + + | { kind: 'string', str: string } & ToString +>kind : "string" +>str : string +>ToString : ToString + +function getValueAsString(value: IntersectionFail): string { +>getValueAsString : (value: IntersectionFail) => string +>value : IntersectionFail +>IntersectionFail : IntersectionFail + + if (value.kind === 'int') { +>value.kind === 'int' : boolean +>value.kind : "int" | "string" +>value : IntersectionFail +>kind : "int" | "string" +>'int' : "int" + + return '' + value.num; +>'' + value.num : string +>'' : "" +>value.num : number +>value : { kind: "int"; num: number; } & ToString +>num : number + } + return value.str; +>value.str : string +>value : { kind: "string"; str: string; } & ToString +>str : string +} + +// Repro from #12535 + +namespace enums { +>enums : typeof enums + + export const enum A { +>A : A + + a1, +>a1 : A.a1 + + a2, +>a2 : A.a2 + + a3, +>a3 : A.a3 + + // ... elements omitted for the sake of clarity + a75, +>a75 : A.a75 + + a76, +>a76 : A.a76 + + a77, +>a77 : A.a77 + } + export const enum B { +>B : B + + b1, +>b1 : B.b1 + + b2, +>b2 : B.b2 + + // ... elements omitted for the sake of clarity + b86, +>b86 : B.b86 + + b87, +>b87 : B.b87 + } + export const enum C { +>C : C + + c1, +>c1 : C.c1 + + c2, +>c2 : C.c2 + + // ... elements omitted for the sake of clarity + c210, +>c210 : C.c210 + + c211, +>c211 : C.c211 + } + export type Genre = A | B | C; +>Genre : Genre +>A : A +>B : B +>C : C +} + +type Foo = { +>Foo : Foo + + genreId: enums.Genre; +>genreId : enums.Genre +>enums : any +>Genre : enums.Genre + +}; + +type Bar = { +>Bar : Bar + + genreId: enums.Genre; +>genreId : enums.Genre +>enums : any +>Genre : enums.Genre + +}; + +type FooBar = Foo & Bar; +>FooBar : FooBar +>Foo : Foo +>Bar : Bar + +function foo(so: any) { +>foo : (so: any) => enums.Genre +>so : any + + const val = so as FooBar; +>val : FooBar +>so as FooBar : FooBar +>so : any +>FooBar : FooBar + + const isGenre = val.genreId; +>isGenre : enums.Genre +>val.genreId : enums.Genre +>val : FooBar +>genreId : enums.Genre + + return isGenre; +>isGenre : enums.Genre +} diff --git a/tests/baselines/reference/intersectionTypeReadonly.errors.txt b/tests/baselines/reference/intersectionTypeReadonly.errors.txt index d9e22fd2223..88ca9cb3b0c 100644 --- a/tests/baselines/reference/intersectionTypeReadonly.errors.txt +++ b/tests/baselines/reference/intersectionTypeReadonly.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(21,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(23,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(25,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(17,6): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(19,11): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(21,9): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(23,15): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(25,15): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. ==== tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts (5 errors) ==== @@ -23,22 +23,22 @@ tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(25,1): er } let base: Base; base.value = 12 // error, lhs can't be a readonly property - ~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let identical: Base & Identical; identical.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let mutable: Base & Mutable; mutable.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let differentType: Base & DifferentType; differentType.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let differentName: Base & DifferentName; differentName.value = 12; // error, property 'value' doesn't exist - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/intersectionTypeWithLeadingOperator.js b/tests/baselines/reference/intersectionTypeWithLeadingOperator.js new file mode 100644 index 00000000000..61b034f1e03 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeWithLeadingOperator.js @@ -0,0 +1,10 @@ +//// [intersectionTypeWithLeadingOperator.ts] +type A = & string; +type B = + & { foo: string } + & { bar: number }; + +type C = [& { foo: 1 } & { bar: 2 }, & { foo: 3 } & { bar: 4 }]; + + +//// [intersectionTypeWithLeadingOperator.js] diff --git a/tests/baselines/reference/intersectionTypeWithLeadingOperator.symbols b/tests/baselines/reference/intersectionTypeWithLeadingOperator.symbols new file mode 100644 index 00000000000..f6648183bb6 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeWithLeadingOperator.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/intersectionTypeWithLeadingOperator.ts === +type A = & string; +>A : Symbol(A, Decl(intersectionTypeWithLeadingOperator.ts, 0, 0)) + +type B = +>B : Symbol(B, Decl(intersectionTypeWithLeadingOperator.ts, 0, 18)) + + & { foo: string } +>foo : Symbol(foo, Decl(intersectionTypeWithLeadingOperator.ts, 2, 5)) + + & { bar: number }; +>bar : Symbol(bar, Decl(intersectionTypeWithLeadingOperator.ts, 3, 5)) + +type C = [& { foo: 1 } & { bar: 2 }, & { foo: 3 } & { bar: 4 }]; +>C : Symbol(C, Decl(intersectionTypeWithLeadingOperator.ts, 3, 20)) +>foo : Symbol(foo, Decl(intersectionTypeWithLeadingOperator.ts, 5, 13)) +>bar : Symbol(bar, Decl(intersectionTypeWithLeadingOperator.ts, 5, 26)) +>foo : Symbol(foo, Decl(intersectionTypeWithLeadingOperator.ts, 5, 40)) +>bar : Symbol(bar, Decl(intersectionTypeWithLeadingOperator.ts, 5, 53)) + diff --git a/tests/baselines/reference/intersectionTypeWithLeadingOperator.types b/tests/baselines/reference/intersectionTypeWithLeadingOperator.types new file mode 100644 index 00000000000..9961f051f7f --- /dev/null +++ b/tests/baselines/reference/intersectionTypeWithLeadingOperator.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/intersectionTypeWithLeadingOperator.ts === +type A = & string; +>A : string + +type B = +>B : B + + & { foo: string } +>foo : string + + & { bar: number }; +>bar : number + +type C = [& { foo: 1 } & { bar: 2 }, & { foo: 3 } & { bar: 4 }]; +>C : [{ foo: 1; } & { bar: 2; }, { foo: 3; } & { bar: 4; }] +>foo : 1 +>bar : 2 +>foo : 3 +>bar : 4 + diff --git a/tests/baselines/reference/invalidBooleanAssignments.errors.txt b/tests/baselines/reference/invalidBooleanAssignments.errors.txt index 7963197a003..06ec14b4dd6 100644 --- a/tests/baselines/reference/invalidBooleanAssignments.errors.txt +++ b/tests/baselines/reference/invalidBooleanAssignments.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(9, tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(12,5): error TS2322: Type 'true' is not assignable to type 'C'. tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(15,5): error TS2322: Type 'true' is not assignable to type 'I'. tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(17,5): error TS2322: Type 'true' is not assignable to type '() => string'. -tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(21,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(21,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(24,5): error TS2322: Type 'boolean' is not assignable to type 'T'. -tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(26,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(26,1): error TS2539: Cannot assign to 'i' because it is not a variable. ==== tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts (10 errors) ==== @@ -47,7 +47,7 @@ tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(26 module M { export var a = 1; } M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function i(a: T) { a = x; @@ -56,4 +56,4 @@ tests/cases/conformance/types/primitives/boolean/invalidBooleanAssignments.ts(26 } i = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'i' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt b/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt index bf5cf5c0f12..c69cc85ad9d 100644 --- a/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt +++ b/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(5,12): error TS2503: Cannot find namespace 'V'. tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(11,12): error TS2503: Cannot find namespace 'C'. -tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(23,12): error TS2693: 'I' only refers to a type, but is being used as a value here. +tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(23,12): error TS2702: 'I' only refers to a type, but is being used as a namespace here. ==== tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts (3 errors) ==== @@ -32,5 +32,5 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIde import i = I; ~ -!!! error TS2693: 'I' only refers to a type, but is being used as a value here. +!!! error TS2702: 'I' only refers to a type, but is being used as a namespace here. \ No newline at end of file diff --git a/tests/baselines/reference/invalidModuleWithVarStatements.js b/tests/baselines/reference/invalidModuleWithVarStatements.js index ce5fbd54ed1..caa6b24f00f 100644 --- a/tests/baselines/reference/invalidModuleWithVarStatements.js +++ b/tests/baselines/reference/invalidModuleWithVarStatements.js @@ -39,11 +39,11 @@ var Y2; })(Y2 || (Y2 = {})); var Y4; (function (Y4) { - static var x = 0; + var x = 0; })(Y4 || (Y4 = {})); var YY; (function (YY) { - static function fn(x) { } + function fn(x) { } })(YY || (YY = {})); var YY2; (function (YY2) { diff --git a/tests/baselines/reference/invalidNumberAssignments.errors.txt b/tests/baselines/reference/invalidNumberAssignments.errors.txt index 23f308830ff..102376f1c50 100644 --- a/tests/baselines/reference/invalidNumberAssignments.errors.txt +++ b/tests/baselines/reference/invalidNumberAssignments.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(9,5) tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(12,5): error TS2322: Type 'number' is not assignable to type 'I'. tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(14,5): error TS2322: Type '1' is not assignable to type '{ baz: string; }'. tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(15,5): error TS2322: Type '1' is not assignable to type '{ 0: number; }'. -tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(18,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(18,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(21,5): error TS2322: Type 'number' is not assignable to type 'T'. -tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(23,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(23,1): error TS2539: Cannot assign to 'i' because it is not a variable. ==== tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts (10 errors) ==== @@ -44,7 +44,7 @@ tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(23,1 module M { export var x = 1; } M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function i(a: T) { a = x; @@ -53,4 +53,4 @@ tests/cases/conformance/types/primitives/number/invalidNumberAssignments.ts(23,1 } i = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'i' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/invalidStringAssignments.errors.txt b/tests/baselines/reference/invalidStringAssignments.errors.txt index b37c56e8a40..728ce09e6b4 100644 --- a/tests/baselines/reference/invalidStringAssignments.errors.txt +++ b/tests/baselines/reference/invalidStringAssignments.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(9,5) tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(12,5): error TS2322: Type 'string' is not assignable to type 'I'. tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(14,5): error TS2322: Type '1' is not assignable to type '{ baz: string; }'. tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(15,5): error TS2322: Type '1' is not assignable to type '{ 0: number; }'. -tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(18,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(18,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(21,5): error TS2322: Type 'string' is not assignable to type 'T'. -tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(23,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(23,1): error TS2539: Cannot assign to 'i' because it is not a variable. tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(26,5): error TS2322: Type 'string' is not assignable to type 'E'. @@ -45,7 +45,7 @@ tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(26,5 module M { export var x = 1; } M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function i(a: T) { a = x; @@ -54,7 +54,7 @@ tests/cases/conformance/types/primitives/string/invalidStringAssignments.ts(26,5 } i = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'i' because it is not a variable. enum E { A } var j: E = x; diff --git a/tests/baselines/reference/invalidUndefinedAssignments.errors.txt b/tests/baselines/reference/invalidUndefinedAssignments.errors.txt index 05921e9433f..b0a30f2dff3 100644 --- a/tests/baselines/reference/invalidUndefinedAssignments.errors.txt +++ b/tests/baselines/reference/invalidUndefinedAssignments.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(4,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(5,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(9,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(4,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(5,3): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(9,1): error TS2539: Cannot assign to 'C' because it is not a variable. tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(14,1): error TS2693: 'I' only refers to a type, but is being used as a value here. -tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(17,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(21,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(17,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts(21,1): error TS2539: Cannot assign to 'i' because it is not a variable. ==== tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.ts (6 errors) ==== @@ -12,16 +12,16 @@ tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.t enum E { A } E = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'E' because it is not a variable. E.A = x; - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. class C { foo: string } var f: C; C = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. interface I { foo: string } var g: I; @@ -33,10 +33,10 @@ tests/cases/conformance/types/primitives/undefined/invalidUndefinedAssignments.t module M { export var x = 1; } M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function i(a: T) { } // BUG 767030 i = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'i' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/invalidUseOfTypeAsNamespace.errors.txt b/tests/baselines/reference/invalidUseOfTypeAsNamespace.errors.txt new file mode 100644 index 00000000000..0353d46d632 --- /dev/null +++ b/tests/baselines/reference/invalidUseOfTypeAsNamespace.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/invalidUseOfTypeAsNamespace.ts(4,16): error TS2702: 'OhNo' only refers to a type, but is being used as a namespace here. + + +==== tests/cases/compiler/invalidUseOfTypeAsNamespace.ts (1 errors) ==== + interface OhNo { + } + + declare let y: OhNo.hello; + ~~~~ +!!! error TS2702: 'OhNo' only refers to a type, but is being used as a namespace here. + \ No newline at end of file diff --git a/tests/baselines/reference/invalidUseOfTypeAsNamespace.js b/tests/baselines/reference/invalidUseOfTypeAsNamespace.js new file mode 100644 index 00000000000..3b598fdea9c --- /dev/null +++ b/tests/baselines/reference/invalidUseOfTypeAsNamespace.js @@ -0,0 +1,8 @@ +//// [invalidUseOfTypeAsNamespace.ts] +interface OhNo { +} + +declare let y: OhNo.hello; + + +//// [invalidUseOfTypeAsNamespace.js] diff --git a/tests/baselines/reference/invalidVoidAssignments.errors.txt b/tests/baselines/reference/invalidVoidAssignments.errors.txt index de19fc3a218..ae599fb52b0 100644 --- a/tests/baselines/reference/invalidVoidAssignments.errors.txt +++ b/tests/baselines/reference/invalidVoidAssignments.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(9,5): er tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(12,5): error TS2322: Type 'void' is not assignable to type 'I'. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(14,5): error TS2322: Type '1' is not assignable to type '{ baz: string; }'. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(15,5): error TS2322: Type '1' is not assignable to type '{ 0: number; }'. -tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(18,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(18,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(21,5): error TS2322: Type 'void' is not assignable to type 'T'. -tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(23,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(23,1): error TS2539: Cannot assign to 'i' because it is not a variable. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(26,1): error TS2322: Type 'typeof E' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(27,1): error TS2322: Type 'E' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(29,1): error TS2322: Type '{ f(): void; }' is not assignable to type 'void'. @@ -47,7 +47,7 @@ tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(29,1): e module M { export var x = 1; } M = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. function i(a: T) { a = x; @@ -56,7 +56,7 @@ tests/cases/conformance/types/primitives/void/invalidVoidAssignments.ts(29,1): e } i = x; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'i' because it is not a variable. enum E { A } x = E; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.js b/tests/baselines/reference/isomorphicMappedTypeInference.js new file mode 100644 index 00000000000..560c926877a --- /dev/null +++ b/tests/baselines/reference/isomorphicMappedTypeInference.js @@ -0,0 +1,330 @@ +//// [isomorphicMappedTypeInference.ts] + +type Box = { + value: T; +} + +type Boxified = { + [P in keyof T]: Box; +} + +function box(x: T): Box { + return { value: x }; +} + +function unbox(x: Box): T { + return x.value; +} + +function boxify(obj: T): Boxified { + let result = {} as Boxified; + for (let k in obj) { + result[k] = box(obj[k]); + } + return result; +} + +function unboxify(obj: Boxified): T { + let result = {} as T; + for (let k in obj) { + result[k] = unbox(obj[k]); + } + return result; +} + +function assignBoxified(obj: Boxified, values: T) { + for (let k in values) { + obj[k].value = values[k]; + } +} + +function f1() { + let v = { + a: 42, + b: "hello", + c: true + }; + let b = boxify(v); + let x: number = b.a.value; +} + +function f2() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + let v = unboxify(b); + let x: number = v.a; +} + +function f3() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + assignBoxified(b, { c: false }); +} + +function f4() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + b = boxify(unboxify(b)); + b = unboxify(boxify(b)); +} + +function makeRecord(obj: { [P in K]: T }) { + return obj; +} + +function f5(s: string) { + let b = makeRecord({ + a: box(42), + b: box("hello"), + c: box(true) + }); + let v = unboxify(b); + let x: string | number | boolean = v.a; +} + +function makeDictionary(obj: { [x: string]: T }) { + return obj; +} + +function f6(s: string) { + let b = makeDictionary({ + a: box(42), + b: box("hello"), + c: box(true) + }); + let v = unboxify(b); + let x: string | number | boolean = v[s]; +} + +declare function validate(obj: { [P in keyof T]?: T[P] }): T; +declare function clone(obj: { readonly [P in keyof T]: T[P] }): T; +declare function validateAndClone(obj: { readonly [P in keyof T]?: T[P] }): T; + +type Foo = { + a?: number; + readonly b: string; +} + +function f10(foo: Foo) { + let x = validate(foo); // { a: number, readonly b: string } + let y = clone(foo); // { a?: number, b: string } + let z = validateAndClone(foo); // { a: number, b: string } +} + +// Repro from #12606 + +type Func = (...args: any[]) => T; +type Spec = { + [P in keyof T]: Func | Spec ; +}; + +/** + * Given a spec object recursively mapping properties to functions, creates a function + * producing an object of the same structure, by mapping each property to the result + * of calling its associated function with the supplied arguments. + */ +declare function applySpec(obj: Spec): (...args: any[]) => T; + +// Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } +var g1 = applySpec({ + sum: (a: any) => 3, + nested: { + mul: (b: any) => "n" + } +}); + +// Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } +var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); + +// Repro from #12633 + +const foo = (object: T, partial: Partial) => object; +let o = {a: 5, b: 7}; +foo(o, {b: 9}); +o = foo(o, {b: 9}); + +//// [isomorphicMappedTypeInference.js] +function box(x) { + return { value: x }; +} +function unbox(x) { + return x.value; +} +function boxify(obj) { + var result = {}; + for (var k in obj) { + result[k] = box(obj[k]); + } + return result; +} +function unboxify(obj) { + var result = {}; + for (var k in obj) { + result[k] = unbox(obj[k]); + } + return result; +} +function assignBoxified(obj, values) { + for (var k in values) { + obj[k].value = values[k]; + } +} +function f1() { + var v = { + a: 42, + b: "hello", + c: true + }; + var b = boxify(v); + var x = b.a.value; +} +function f2() { + var b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + var v = unboxify(b); + var x = v.a; +} +function f3() { + var b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + assignBoxified(b, { c: false }); +} +function f4() { + var b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + b = boxify(unboxify(b)); + b = unboxify(boxify(b)); +} +function makeRecord(obj) { + return obj; +} +function f5(s) { + var b = makeRecord({ + a: box(42), + b: box("hello"), + c: box(true) + }); + var v = unboxify(b); + var x = v.a; +} +function makeDictionary(obj) { + return obj; +} +function f6(s) { + var b = makeDictionary({ + a: box(42), + b: box("hello"), + c: box(true) + }); + var v = unboxify(b); + var x = v[s]; +} +function f10(foo) { + var x = validate(foo); // { a: number, readonly b: string } + var y = clone(foo); // { a?: number, b: string } + var z = validateAndClone(foo); // { a: number, b: string } +} +// Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } +var g1 = applySpec({ + sum: function (a) { return 3; }, + nested: { + mul: function (b) { return "n"; } + } +}); +// Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } +var g2 = applySpec({ foo: { bar: { baz: function (x) { return true; } } } }); +// Repro from #12633 +var foo = function (object, partial) { return object; }; +var o = { a: 5, b: 7 }; +foo(o, { b: 9 }); +o = foo(o, { b: 9 }); + + +//// [isomorphicMappedTypeInference.d.ts] +declare type Box = { + value: T; +}; +declare type Boxified = { + [P in keyof T]: Box; +}; +declare function box(x: T): Box; +declare function unbox(x: Box): T; +declare function boxify(obj: T): Boxified; +declare function unboxify(obj: Boxified): T; +declare function assignBoxified(obj: Boxified, values: T): void; +declare function f1(): void; +declare function f2(): void; +declare function f3(): void; +declare function f4(): void; +declare function makeRecord(obj: { + [P in K]: T; +}): { + [P in K]: T; +}; +declare function f5(s: string): void; +declare function makeDictionary(obj: { + [x: string]: T; +}): { + [x: string]: T; +}; +declare function f6(s: string): void; +declare function validate(obj: { + [P in keyof T]?: T[P]; +}): T; +declare function clone(obj: { + readonly [P in keyof T]: T[P]; +}): T; +declare function validateAndClone(obj: { + readonly [P in keyof T]?: T[P]; +}): T; +declare type Foo = { + a?: number; + readonly b: string; +}; +declare function f10(foo: Foo): void; +declare type Func = (...args: any[]) => T; +declare type Spec = { + [P in keyof T]: Func | Spec; +}; +/** + * Given a spec object recursively mapping properties to functions, creates a function + * producing an object of the same structure, by mapping each property to the result + * of calling its associated function with the supplied arguments. + */ +declare function applySpec(obj: Spec): (...args: any[]) => T; +declare var g1: (...args: any[]) => { + sum: number; + nested: { + mul: string; + }; +}; +declare var g2: (...args: any[]) => { + foo: { + bar: { + baz: boolean; + }; + }; +}; +declare const foo: (object: T, partial: Partial) => T; +declare let o: { + a: number; + b: number; +}; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.symbols b/tests/baselines/reference/isomorphicMappedTypeInference.symbols new file mode 100644 index 00000000000..93ce825c35d --- /dev/null +++ b/tests/baselines/reference/isomorphicMappedTypeInference.symbols @@ -0,0 +1,489 @@ +=== tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts === + +type Box = { +>Box : Symbol(Box, Decl(isomorphicMappedTypeInference.ts, 0, 0)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 1, 9)) + + value: T; +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 1, 9)) +} + +type Boxified = { +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 3, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 5, 14)) + + [P in keyof T]: Box; +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 6, 5)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 5, 14)) +>Box : Symbol(Box, Decl(isomorphicMappedTypeInference.ts, 0, 0)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 5, 14)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 6, 5)) +} + +function box(x: T): Box { +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 9, 13)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 9, 16)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 9, 13)) +>Box : Symbol(Box, Decl(isomorphicMappedTypeInference.ts, 0, 0)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 9, 13)) + + return { value: x }; +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 10, 12)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 9, 16)) +} + +function unbox(x: Box): T { +>unbox : Symbol(unbox, Decl(isomorphicMappedTypeInference.ts, 11, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 13, 15)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 13, 18)) +>Box : Symbol(Box, Decl(isomorphicMappedTypeInference.ts, 0, 0)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 13, 15)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 13, 15)) + + return x.value; +>x.value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 13, 18)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +} + +function boxify(obj: T): Boxified { +>boxify : Symbol(boxify, Decl(isomorphicMappedTypeInference.ts, 15, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 17, 16)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 17, 19)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 17, 16)) +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 3, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 17, 16)) + + let result = {} as Boxified; +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 18, 7)) +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 3, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 17, 16)) + + for (let k in obj) { +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 19, 12)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 17, 19)) + + result[k] = box(obj[k]); +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 18, 7)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 19, 12)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 17, 19)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 19, 12)) + } + return result; +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 18, 7)) +} + +function unboxify(obj: Boxified): T { +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 25, 18)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 25, 21)) +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 3, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 25, 18)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 25, 18)) + + let result = {} as T; +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 26, 7)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 25, 18)) + + for (let k in obj) { +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 27, 12)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 25, 21)) + + result[k] = unbox(obj[k]); +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 26, 7)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 27, 12)) +>unbox : Symbol(unbox, Decl(isomorphicMappedTypeInference.ts, 11, 1)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 25, 21)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 27, 12)) + } + return result; +>result : Symbol(result, Decl(isomorphicMappedTypeInference.ts, 26, 7)) +} + +function assignBoxified(obj: Boxified, values: T) { +>assignBoxified : Symbol(assignBoxified, Decl(isomorphicMappedTypeInference.ts, 31, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 33, 24)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 33, 27)) +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 3, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 33, 24)) +>values : Symbol(values, Decl(isomorphicMappedTypeInference.ts, 33, 44)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 33, 24)) + + for (let k in values) { +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 34, 12)) +>values : Symbol(values, Decl(isomorphicMappedTypeInference.ts, 33, 44)) + + obj[k].value = values[k]; +>obj[k].value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 33, 27)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 34, 12)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +>values : Symbol(values, Decl(isomorphicMappedTypeInference.ts, 33, 44)) +>k : Symbol(k, Decl(isomorphicMappedTypeInference.ts, 34, 12)) + } +} + +function f1() { +>f1 : Symbol(f1, Decl(isomorphicMappedTypeInference.ts, 37, 1)) + + let v = { +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 40, 7)) + + a: 42, +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 40, 13)) + + b: "hello", +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 41, 14)) + + c: true +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 42, 19)) + + }; + let b = boxify(v); +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 45, 7)) +>boxify : Symbol(boxify, Decl(isomorphicMappedTypeInference.ts, 15, 1)) +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 40, 7)) + + let x: number = b.a.value; +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 46, 7)) +>b.a.value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +>b.a : Symbol(a) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 45, 7)) +>a : Symbol(a) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 1, 15)) +} + +function f2() { +>f2 : Symbol(f2, Decl(isomorphicMappedTypeInference.ts, 47, 1)) + + let b = { +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 50, 7)) + + a: box(42), +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 50, 13)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + b: box("hello"), +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 51, 19)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + c: box(true) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 52, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + }; + let v = unboxify(b); +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 55, 7)) +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 50, 7)) + + let x: number = v.a; +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 56, 7)) +>v.a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 50, 13)) +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 55, 7)) +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 50, 13)) +} + +function f3() { +>f3 : Symbol(f3, Decl(isomorphicMappedTypeInference.ts, 57, 1)) + + let b = { +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 60, 7)) + + a: box(42), +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 60, 13)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + b: box("hello"), +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 61, 19)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + c: box(true) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 62, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + }; + assignBoxified(b, { c: false }); +>assignBoxified : Symbol(assignBoxified, Decl(isomorphicMappedTypeInference.ts, 31, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 60, 7)) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 65, 23)) +} + +function f4() { +>f4 : Symbol(f4, Decl(isomorphicMappedTypeInference.ts, 66, 1)) + + let b = { +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 69, 7)) + + a: box(42), +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 69, 13)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + b: box("hello"), +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 70, 19)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + c: box(true) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 71, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + }; + b = boxify(unboxify(b)); +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 69, 7)) +>boxify : Symbol(boxify, Decl(isomorphicMappedTypeInference.ts, 15, 1)) +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 69, 7)) + + b = unboxify(boxify(b)); +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 69, 7)) +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>boxify : Symbol(boxify, Decl(isomorphicMappedTypeInference.ts, 15, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 69, 7)) +} + +function makeRecord(obj: { [P in K]: T }) { +>makeRecord : Symbol(makeRecord, Decl(isomorphicMappedTypeInference.ts, 76, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 78, 20)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 78, 22)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 78, 41)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 78, 49)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 78, 22)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 78, 20)) + + return obj; +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 78, 41)) +} + +function f5(s: string) { +>f5 : Symbol(f5, Decl(isomorphicMappedTypeInference.ts, 80, 1)) +>s : Symbol(s, Decl(isomorphicMappedTypeInference.ts, 82, 12)) + + let b = makeRecord({ +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 83, 7)) +>makeRecord : Symbol(makeRecord, Decl(isomorphicMappedTypeInference.ts, 76, 1)) + + a: box(42), +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 83, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + b: box("hello"), +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 84, 19)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + c: box(true) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 85, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + }); + let v = unboxify(b); +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 88, 7)) +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 83, 7)) + + let x: string | number | boolean = v.a; +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 89, 7)) +>v.a : Symbol(a) +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 88, 7)) +>a : Symbol(a) +} + +function makeDictionary(obj: { [x: string]: T }) { +>makeDictionary : Symbol(makeDictionary, Decl(isomorphicMappedTypeInference.ts, 90, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 92, 24)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 92, 27)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 92, 35)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 92, 24)) + + return obj; +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 92, 27)) +} + +function f6(s: string) { +>f6 : Symbol(f6, Decl(isomorphicMappedTypeInference.ts, 94, 1)) +>s : Symbol(s, Decl(isomorphicMappedTypeInference.ts, 96, 12)) + + let b = makeDictionary({ +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 97, 7)) +>makeDictionary : Symbol(makeDictionary, Decl(isomorphicMappedTypeInference.ts, 90, 1)) + + a: box(42), +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 97, 28)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + b: box("hello"), +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 98, 19)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + c: box(true) +>c : Symbol(c, Decl(isomorphicMappedTypeInference.ts, 99, 24)) +>box : Symbol(box, Decl(isomorphicMappedTypeInference.ts, 7, 1)) + + }); + let v = unboxify(b); +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 102, 7)) +>unboxify : Symbol(unboxify, Decl(isomorphicMappedTypeInference.ts, 23, 1)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 97, 7)) + + let x: string | number | boolean = v[s]; +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 103, 7)) +>v : Symbol(v, Decl(isomorphicMappedTypeInference.ts, 102, 7)) +>s : Symbol(s, Decl(isomorphicMappedTypeInference.ts, 96, 12)) +} + +declare function validate(obj: { [P in keyof T]?: T[P] }): T; +>validate : Symbol(validate, Decl(isomorphicMappedTypeInference.ts, 104, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 106, 26)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 106, 29)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 106, 37)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 106, 26)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 106, 26)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 106, 37)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 106, 26)) + +declare function clone(obj: { readonly [P in keyof T]: T[P] }): T; +>clone : Symbol(clone, Decl(isomorphicMappedTypeInference.ts, 106, 64)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 107, 23)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 107, 26)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 107, 43)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 107, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 107, 23)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 107, 43)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 107, 23)) + +declare function validateAndClone(obj: { readonly [P in keyof T]?: T[P] }): T; +>validateAndClone : Symbol(validateAndClone, Decl(isomorphicMappedTypeInference.ts, 107, 69)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 108, 34)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 108, 37)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 108, 54)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 108, 34)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 108, 34)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 108, 54)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 108, 34)) + +type Foo = { +>Foo : Symbol(Foo, Decl(isomorphicMappedTypeInference.ts, 108, 81)) + + a?: number; +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 110, 12)) + + readonly b: string; +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 111, 15)) +} + +function f10(foo: Foo) { +>f10 : Symbol(f10, Decl(isomorphicMappedTypeInference.ts, 113, 1)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 115, 13)) +>Foo : Symbol(Foo, Decl(isomorphicMappedTypeInference.ts, 108, 81)) + + let x = validate(foo); // { a: number, readonly b: string } +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 116, 7)) +>validate : Symbol(validate, Decl(isomorphicMappedTypeInference.ts, 104, 1)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 115, 13)) + + let y = clone(foo); // { a?: number, b: string } +>y : Symbol(y, Decl(isomorphicMappedTypeInference.ts, 117, 7)) +>clone : Symbol(clone, Decl(isomorphicMappedTypeInference.ts, 106, 64)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 115, 13)) + + let z = validateAndClone(foo); // { a: number, b: string } +>z : Symbol(z, Decl(isomorphicMappedTypeInference.ts, 118, 7)) +>validateAndClone : Symbol(validateAndClone, Decl(isomorphicMappedTypeInference.ts, 107, 69)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 115, 13)) +} + +// Repro from #12606 + +type Func = (...args: any[]) => T; +>Func : Symbol(Func, Decl(isomorphicMappedTypeInference.ts, 119, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 123, 10)) +>args : Symbol(args, Decl(isomorphicMappedTypeInference.ts, 123, 16)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 123, 10)) + +type Spec = { +>Spec : Symbol(Spec, Decl(isomorphicMappedTypeInference.ts, 123, 37)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 124, 10)) + + [P in keyof T]: Func | Spec ; +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 125, 5)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 124, 10)) +>Func : Symbol(Func, Decl(isomorphicMappedTypeInference.ts, 119, 1)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 124, 10)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 125, 5)) +>Spec : Symbol(Spec, Decl(isomorphicMappedTypeInference.ts, 123, 37)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 124, 10)) +>P : Symbol(P, Decl(isomorphicMappedTypeInference.ts, 125, 5)) + +}; + +/** + * Given a spec object recursively mapping properties to functions, creates a function + * producing an object of the same structure, by mapping each property to the result + * of calling its associated function with the supplied arguments. + */ +declare function applySpec(obj: Spec): (...args: any[]) => T; +>applySpec : Symbol(applySpec, Decl(isomorphicMappedTypeInference.ts, 126, 2)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 133, 27)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 133, 30)) +>Spec : Symbol(Spec, Decl(isomorphicMappedTypeInference.ts, 123, 37)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 133, 27)) +>args : Symbol(args, Decl(isomorphicMappedTypeInference.ts, 133, 46)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 133, 27)) + +// Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } +var g1 = applySpec({ +>g1 : Symbol(g1, Decl(isomorphicMappedTypeInference.ts, 136, 3)) +>applySpec : Symbol(applySpec, Decl(isomorphicMappedTypeInference.ts, 126, 2)) + + sum: (a: any) => 3, +>sum : Symbol(sum, Decl(isomorphicMappedTypeInference.ts, 136, 20)) +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 137, 10)) + + nested: { +>nested : Symbol(nested, Decl(isomorphicMappedTypeInference.ts, 137, 23)) + + mul: (b: any) => "n" +>mul : Symbol(mul, Decl(isomorphicMappedTypeInference.ts, 138, 13)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 139, 14)) + } +}); + +// Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } +var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); +>g2 : Symbol(g2, Decl(isomorphicMappedTypeInference.ts, 144, 3)) +>applySpec : Symbol(applySpec, Decl(isomorphicMappedTypeInference.ts, 126, 2)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 144, 20)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 144, 27)) +>baz : Symbol(baz, Decl(isomorphicMappedTypeInference.ts, 144, 34)) +>x : Symbol(x, Decl(isomorphicMappedTypeInference.ts, 144, 41)) + +// Repro from #12633 + +const foo = (object: T, partial: Partial) => object; +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 148, 5)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 148, 13)) +>object : Symbol(object, Decl(isomorphicMappedTypeInference.ts, 148, 16)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 148, 13)) +>partial : Symbol(partial, Decl(isomorphicMappedTypeInference.ts, 148, 26)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 148, 13)) +>object : Symbol(object, Decl(isomorphicMappedTypeInference.ts, 148, 16)) + +let o = {a: 5, b: 7}; +>o : Symbol(o, Decl(isomorphicMappedTypeInference.ts, 149, 3)) +>a : Symbol(a, Decl(isomorphicMappedTypeInference.ts, 149, 9)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 149, 14)) + +foo(o, {b: 9}); +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 148, 5)) +>o : Symbol(o, Decl(isomorphicMappedTypeInference.ts, 149, 3)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 150, 8)) + +o = foo(o, {b: 9}); +>o : Symbol(o, Decl(isomorphicMappedTypeInference.ts, 149, 3)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 148, 5)) +>o : Symbol(o, Decl(isomorphicMappedTypeInference.ts, 149, 3)) +>b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 151, 12)) + diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.types b/tests/baselines/reference/isomorphicMappedTypeInference.types new file mode 100644 index 00000000000..ca20e06e113 --- /dev/null +++ b/tests/baselines/reference/isomorphicMappedTypeInference.types @@ -0,0 +1,587 @@ +=== tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts === + +type Box = { +>Box : Box +>T : T + + value: T; +>value : T +>T : T +} + +type Boxified = { +>Boxified : Boxified +>T : T + + [P in keyof T]: Box; +>P : P +>T : T +>Box : Box +>T : T +>P : P +} + +function box(x: T): Box { +>box : (x: T) => Box +>T : T +>x : T +>T : T +>Box : Box +>T : T + + return { value: x }; +>{ value: x } : { value: T; } +>value : T +>x : T +} + +function unbox(x: Box): T { +>unbox : (x: Box) => T +>T : T +>x : Box +>Box : Box +>T : T +>T : T + + return x.value; +>x.value : T +>x : Box +>value : T +} + +function boxify(obj: T): Boxified { +>boxify : (obj: T) => Boxified +>T : T +>obj : T +>T : T +>Boxified : Boxified +>T : T + + let result = {} as Boxified; +>result : Boxified +>{} as Boxified : Boxified +>{} : {} +>Boxified : Boxified +>T : T + + for (let k in obj) { +>k : keyof T +>obj : T + + result[k] = box(obj[k]); +>result[k] = box(obj[k]) : Box +>result[k] : Box +>result : Boxified +>k : keyof T +>box(obj[k]) : Box +>box : (x: T) => Box +>obj[k] : T[keyof T] +>obj : T +>k : keyof T + } + return result; +>result : Boxified +} + +function unboxify(obj: Boxified): T { +>unboxify : (obj: Boxified) => T +>T : T +>obj : Boxified +>Boxified : Boxified +>T : T +>T : T + + let result = {} as T; +>result : T +>{} as T : T +>{} : {} +>T : T + + for (let k in obj) { +>k : keyof T +>obj : Boxified + + result[k] = unbox(obj[k]); +>result[k] = unbox(obj[k]) : T[keyof T] +>result[k] : T[keyof T] +>result : T +>k : keyof T +>unbox(obj[k]) : T[keyof T] +>unbox : (x: Box) => T +>obj[k] : Box +>obj : Boxified +>k : keyof T + } + return result; +>result : T +} + +function assignBoxified(obj: Boxified, values: T) { +>assignBoxified : (obj: Boxified, values: T) => void +>T : T +>obj : Boxified +>Boxified : Boxified +>T : T +>values : T +>T : T + + for (let k in values) { +>k : keyof T +>values : T + + obj[k].value = values[k]; +>obj[k].value = values[k] : T[keyof T] +>obj[k].value : T[keyof T] +>obj[k] : Box +>obj : Boxified +>k : keyof T +>value : T[keyof T] +>values[k] : T[keyof T] +>values : T +>k : keyof T + } +} + +function f1() { +>f1 : () => void + + let v = { +>v : { a: number; b: string; c: boolean; } +>{ a: 42, b: "hello", c: true } : { a: number; b: string; c: boolean; } + + a: 42, +>a : number +>42 : 42 + + b: "hello", +>b : string +>"hello" : "hello" + + c: true +>c : boolean +>true : true + + }; + let b = boxify(v); +>b : Boxified<{ a: number; b: string; c: boolean; }> +>boxify(v) : Boxified<{ a: number; b: string; c: boolean; }> +>boxify : (obj: T) => Boxified +>v : { a: number; b: string; c: boolean; } + + let x: number = b.a.value; +>x : number +>b.a.value : number +>b.a : Box +>b : Boxified<{ a: number; b: string; c: boolean; }> +>a : Box +>value : number +} + +function f2() { +>f2 : () => void + + let b = { +>b : { a: Box; b: Box; c: Box; } +>{ a: box(42), b: box("hello"), c: box(true) } : { a: Box; b: Box; c: Box; } + + a: box(42), +>a : Box +>box(42) : Box +>box : (x: T) => Box +>42 : 42 + + b: box("hello"), +>b : Box +>box("hello") : Box +>box : (x: T) => Box +>"hello" : "hello" + + c: box(true) +>c : Box +>box(true) : Box +>box : (x: T) => Box +>true : true + + }; + let v = unboxify(b); +>v : { a: number; b: string; c: boolean; } +>unboxify(b) : { a: number; b: string; c: boolean; } +>unboxify : (obj: Boxified) => T +>b : { a: Box; b: Box; c: Box; } + + let x: number = v.a; +>x : number +>v.a : number +>v : { a: number; b: string; c: boolean; } +>a : number +} + +function f3() { +>f3 : () => void + + let b = { +>b : { a: Box; b: Box; c: Box; } +>{ a: box(42), b: box("hello"), c: box(true) } : { a: Box; b: Box; c: Box; } + + a: box(42), +>a : Box +>box(42) : Box +>box : (x: T) => Box +>42 : 42 + + b: box("hello"), +>b : Box +>box("hello") : Box +>box : (x: T) => Box +>"hello" : "hello" + + c: box(true) +>c : Box +>box(true) : Box +>box : (x: T) => Box +>true : true + + }; + assignBoxified(b, { c: false }); +>assignBoxified(b, { c: false }) : void +>assignBoxified : (obj: Boxified, values: T) => void +>b : { a: Box; b: Box; c: Box; } +>{ c: false } : { c: false; } +>c : boolean +>false : false +} + +function f4() { +>f4 : () => void + + let b = { +>b : { a: Box; b: Box; c: Box; } +>{ a: box(42), b: box("hello"), c: box(true) } : { a: Box; b: Box; c: Box; } + + a: box(42), +>a : Box +>box(42) : Box +>box : (x: T) => Box +>42 : 42 + + b: box("hello"), +>b : Box +>box("hello") : Box +>box : (x: T) => Box +>"hello" : "hello" + + c: box(true) +>c : Box +>box(true) : Box +>box : (x: T) => Box +>true : true + + }; + b = boxify(unboxify(b)); +>b = boxify(unboxify(b)) : Boxified<{ a: number; b: string; c: boolean; }> +>b : { a: Box; b: Box; c: Box; } +>boxify(unboxify(b)) : Boxified<{ a: number; b: string; c: boolean; }> +>boxify : (obj: T) => Boxified +>unboxify(b) : { a: number; b: string; c: boolean; } +>unboxify : (obj: Boxified) => T +>b : { a: Box; b: Box; c: Box; } + + b = unboxify(boxify(b)); +>b = unboxify(boxify(b)) : { a: Box; b: Box; c: Box; } +>b : { a: Box; b: Box; c: Box; } +>unboxify(boxify(b)) : { a: Box; b: Box; c: Box; } +>unboxify : (obj: Boxified) => T +>boxify(b) : Boxified<{ a: Box; b: Box; c: Box; }> +>boxify : (obj: T) => Boxified +>b : { a: Box; b: Box; c: Box; } +} + +function makeRecord(obj: { [P in K]: T }) { +>makeRecord : (obj: { [P in K]: T; }) => { [P in K]: T; } +>T : T +>K : K +>obj : { [P in K]: T; } +>P : P +>K : K +>T : T + + return obj; +>obj : { [P in K]: T; } +} + +function f5(s: string) { +>f5 : (s: string) => void +>s : string + + let b = makeRecord({ +>b : { a: Box | Box | Box; b: Box | Box | Box; c: Box | Box | Box; } +>makeRecord({ a: box(42), b: box("hello"), c: box(true) }) : { a: Box | Box | Box; b: Box | Box | Box; c: Box | Box | Box; } +>makeRecord : (obj: { [P in K]: T; }) => { [P in K]: T; } +>{ a: box(42), b: box("hello"), c: box(true) } : { a: Box; b: Box; c: Box; } + + a: box(42), +>a : Box +>box(42) : Box +>box : (x: T) => Box +>42 : 42 + + b: box("hello"), +>b : Box +>box("hello") : Box +>box : (x: T) => Box +>"hello" : "hello" + + c: box(true) +>c : Box +>box(true) : Box +>box : (x: T) => Box +>true : true + + }); + let v = unboxify(b); +>v : { a: string | number | boolean; b: string | number | boolean; c: string | number | boolean; } +>unboxify(b) : { a: string | number | boolean; b: string | number | boolean; c: string | number | boolean; } +>unboxify : (obj: Boxified) => T +>b : { a: Box | Box | Box; b: Box | Box | Box; c: Box | Box | Box; } + + let x: string | number | boolean = v.a; +>x : string | number | boolean +>v.a : string | number | boolean +>v : { a: string | number | boolean; b: string | number | boolean; c: string | number | boolean; } +>a : string | number | boolean +} + +function makeDictionary(obj: { [x: string]: T }) { +>makeDictionary : (obj: { [x: string]: T; }) => { [x: string]: T; } +>T : T +>obj : { [x: string]: T; } +>x : string +>T : T + + return obj; +>obj : { [x: string]: T; } +} + +function f6(s: string) { +>f6 : (s: string) => void +>s : string + + let b = makeDictionary({ +>b : { [x: string]: Box | Box | Box; } +>makeDictionary({ a: box(42), b: box("hello"), c: box(true) }) : { [x: string]: Box | Box | Box; } +>makeDictionary : (obj: { [x: string]: T; }) => { [x: string]: T; } +>{ a: box(42), b: box("hello"), c: box(true) } : { a: Box; b: Box; c: Box; } + + a: box(42), +>a : Box +>box(42) : Box +>box : (x: T) => Box +>42 : 42 + + b: box("hello"), +>b : Box +>box("hello") : Box +>box : (x: T) => Box +>"hello" : "hello" + + c: box(true) +>c : Box +>box(true) : Box +>box : (x: T) => Box +>true : true + + }); + let v = unboxify(b); +>v : { [x: string]: string | number | boolean; } +>unboxify(b) : { [x: string]: string | number | boolean; } +>unboxify : (obj: Boxified) => T +>b : { [x: string]: Box | Box | Box; } + + let x: string | number | boolean = v[s]; +>x : string | number | boolean +>v[s] : string | number | boolean +>v : { [x: string]: string | number | boolean; } +>s : string +} + +declare function validate(obj: { [P in keyof T]?: T[P] }): T; +>validate : (obj: { [P in keyof T]?: T[P] | undefined; }) => T +>T : T +>obj : { [P in keyof T]?: T[P] | undefined; } +>P : P +>T : T +>T : T +>P : P +>T : T + +declare function clone(obj: { readonly [P in keyof T]: T[P] }): T; +>clone : (obj: { readonly [P in keyof T]: T[P]; }) => T +>T : T +>obj : { readonly [P in keyof T]: T[P]; } +>P : P +>T : T +>T : T +>P : P +>T : T + +declare function validateAndClone(obj: { readonly [P in keyof T]?: T[P] }): T; +>validateAndClone : (obj: { readonly [P in keyof T]?: T[P] | undefined; }) => T +>T : T +>obj : { readonly [P in keyof T]?: T[P] | undefined; } +>P : P +>T : T +>T : T +>P : P +>T : T + +type Foo = { +>Foo : Foo + + a?: number; +>a : number | undefined + + readonly b: string; +>b : string +} + +function f10(foo: Foo) { +>f10 : (foo: Foo) => void +>foo : Foo +>Foo : Foo + + let x = validate(foo); // { a: number, readonly b: string } +>x : { a: number; readonly b: string; } +>validate(foo) : { a: number; readonly b: string; } +>validate : (obj: { [P in keyof T]?: T[P] | undefined; }) => T +>foo : Foo + + let y = clone(foo); // { a?: number, b: string } +>y : { a?: number | undefined; b: string; } +>clone(foo) : { a?: number | undefined; b: string; } +>clone : (obj: { readonly [P in keyof T]: T[P]; }) => T +>foo : Foo + + let z = validateAndClone(foo); // { a: number, b: string } +>z : { a: number; b: string; } +>validateAndClone(foo) : { a: number; b: string; } +>validateAndClone : (obj: { readonly [P in keyof T]?: T[P] | undefined; }) => T +>foo : Foo +} + +// Repro from #12606 + +type Func = (...args: any[]) => T; +>Func : Func +>T : T +>args : any[] +>T : T + +type Spec = { +>Spec : Spec +>T : T + + [P in keyof T]: Func | Spec ; +>P : P +>T : T +>Func : Func +>T : T +>P : P +>Spec : Spec +>T : T +>P : P + +}; + +/** + * Given a spec object recursively mapping properties to functions, creates a function + * producing an object of the same structure, by mapping each property to the result + * of calling its associated function with the supplied arguments. + */ +declare function applySpec(obj: Spec): (...args: any[]) => T; +>applySpec : (obj: Spec) => (...args: any[]) => T +>T : T +>obj : Spec +>Spec : Spec +>T : T +>args : any[] +>T : T + +// Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } +var g1 = applySpec({ +>g1 : (...args: any[]) => { sum: number; nested: { mul: string; }; } +>applySpec({ sum: (a: any) => 3, nested: { mul: (b: any) => "n" }}) : (...args: any[]) => { sum: number; nested: { mul: string; }; } +>applySpec : (obj: Spec) => (...args: any[]) => T +>{ sum: (a: any) => 3, nested: { mul: (b: any) => "n" }} : { sum: (a: any) => number; nested: { mul: (b: any) => string; }; } + + sum: (a: any) => 3, +>sum : (a: any) => number +>(a: any) => 3 : (a: any) => number +>a : any +>3 : 3 + + nested: { +>nested : { mul: (b: any) => string; } +>{ mul: (b: any) => "n" } : { mul: (b: any) => string; } + + mul: (b: any) => "n" +>mul : (b: any) => string +>(b: any) => "n" : (b: any) => string +>b : any +>"n" : "n" + } +}); + +// Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } +var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); +>g2 : (...args: any[]) => { foo: { bar: { baz: boolean; }; }; } +>applySpec({ foo: { bar: { baz: (x: any) => true } } }) : (...args: any[]) => { foo: { bar: { baz: boolean; }; }; } +>applySpec : (obj: Spec) => (...args: any[]) => T +>{ foo: { bar: { baz: (x: any) => true } } } : { foo: { bar: { baz: (x: any) => boolean; }; }; } +>foo : { bar: { baz: (x: any) => boolean; }; } +>{ bar: { baz: (x: any) => true } } : { bar: { baz: (x: any) => boolean; }; } +>bar : { baz: (x: any) => boolean; } +>{ baz: (x: any) => true } : { baz: (x: any) => boolean; } +>baz : (x: any) => boolean +>(x: any) => true : (x: any) => boolean +>x : any +>true : true + +// Repro from #12633 + +const foo = (object: T, partial: Partial) => object; +>foo : (object: T, partial: Partial) => T +>(object: T, partial: Partial) => object : (object: T, partial: Partial) => T +>T : T +>object : T +>T : T +>partial : Partial +>Partial : Partial +>T : T +>object : T + +let o = {a: 5, b: 7}; +>o : { a: number; b: number; } +>{a: 5, b: 7} : { a: number; b: number; } +>a : number +>5 : 5 +>b : number +>7 : 7 + +foo(o, {b: 9}); +>foo(o, {b: 9}) : { a: number; b: number; } +>foo : (object: T, partial: Partial) => T +>o : { a: number; b: number; } +>{b: 9} : { b: number; } +>b : number +>9 : 9 + +o = foo(o, {b: 9}); +>o = foo(o, {b: 9}) : { a: number; b: number; } +>o : { a: number; b: number; } +>foo(o, {b: 9}) : { a: number; b: number; } +>foo : (object: T, partial: Partial) => T +>o : { a: number; b: number; } +>{b: 9} : { b: number; } +>b : number +>9 : 9 + diff --git a/tests/baselines/reference/jsFileCompilationAbstractModifier.errors.txt b/tests/baselines/reference/jsFileCompilationAbstractModifier.errors.txt new file mode 100644 index 00000000000..c7d2ad270be --- /dev/null +++ b/tests/baselines/reference/jsFileCompilationAbstractModifier.errors.txt @@ -0,0 +1,16 @@ +error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig +tests/cases/compiler/a.js(1,1): error TS8009: 'abstract' can only be used in a .ts file. +tests/cases/compiler/a.js(2,5): error TS8009: 'abstract' can only be used in a .ts file. + + +!!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig +==== tests/cases/compiler/a.js (2 errors) ==== + abstract class c { + ~~~~~~~~ +!!! error TS8009: 'abstract' can only be used in a .ts file. + abstract x; + ~~~~~~~~ +!!! error TS8009: 'abstract' can only be used in a .ts file. + } \ No newline at end of file diff --git a/tests/baselines/reference/jsFileCompilationAmbientVarDeclarationSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationAmbientVarDeclarationSyntax.errors.txt index 19bfd5d1c02..039834ff702 100644 --- a/tests/baselines/reference/jsFileCompilationAmbientVarDeclarationSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationAmbientVarDeclarationSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,1): error TS8009: 'declare' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== declare var v; ~~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationConstModifier.symbols b/tests/baselines/reference/jsFileCompilationConstModifier.symbols new file mode 100644 index 00000000000..137dafd3473 --- /dev/null +++ b/tests/baselines/reference/jsFileCompilationConstModifier.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/a.js === +const c = 10; +>c : Symbol(c, Decl(a.js, 0, 5)) + diff --git a/tests/baselines/reference/jsFileCompilationConstModifier.types b/tests/baselines/reference/jsFileCompilationConstModifier.types new file mode 100644 index 00000000000..8e74679f2a5 --- /dev/null +++ b/tests/baselines/reference/jsFileCompilationConstModifier.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/a.js === +const c = 10; +>c : 10 +>10 : 10 + diff --git a/tests/baselines/reference/jsFileCompilationEmitBlockedCorrectly.errors.txt b/tests/baselines/reference/jsFileCompilationEmitBlockedCorrectly.errors.txt index 0aa9d5733d5..75bcf88b10a 100644 --- a/tests/baselines/reference/jsFileCompilationEmitBlockedCorrectly.errors.txt +++ b/tests/baselines/reference/jsFileCompilationEmitBlockedCorrectly.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig error TS5056: Cannot write file 'tests/cases/compiler/a.js' because it would be overwritten by multiple input files. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5056: Cannot write file 'tests/cases/compiler/a.js' because it would be overwritten by multiple input files. ==== tests/cases/compiler/a.ts (0 errors) ==== class c { diff --git a/tests/baselines/reference/jsFileCompilationEnumSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationEnumSyntax.errors.txt index 538dfb38972..c6da8931d5e 100644 --- a/tests/baselines/reference/jsFileCompilationEnumSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationEnumSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,6): error TS8015: 'enum declarations' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== enum E { } ~ diff --git a/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithNoOut.errors.txt b/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithNoOut.errors.txt index 641731936f8..54e91c5d196 100644 --- a/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithNoOut.errors.txt +++ b/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithNoOut.errors.txt @@ -1,9 +1,11 @@ error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. error TS5055: Cannot write file 'tests/cases/compiler/c.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. !!! error TS5055: Cannot write file 'tests/cases/compiler/c.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/jsFileCompilationExportAssignmentSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationExportAssignmentSyntax.errors.txt index f537941c55c..babbeea8004 100644 --- a/tests/baselines/reference/jsFileCompilationExportAssignmentSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationExportAssignmentSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,1): error TS8003: 'export=' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== export = b; ~~~~~~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationHeritageClauseSyntaxOfClass.errors.txt b/tests/baselines/reference/jsFileCompilationHeritageClauseSyntaxOfClass.errors.txt index 33b8a45f1aa..3b30663308f 100644 --- a/tests/baselines/reference/jsFileCompilationHeritageClauseSyntaxOfClass.errors.txt +++ b/tests/baselines/reference/jsFileCompilationHeritageClauseSyntaxOfClass.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,9): error TS8005: 'implements clauses' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== class C implements D { } ~~~~~~~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationImportEqualsSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationImportEqualsSyntax.errors.txt index b4161367037..a064f53e92f 100644 --- a/tests/baselines/reference/jsFileCompilationImportEqualsSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationImportEqualsSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,1): error TS8002: 'import ... =' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== import a = b; ~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationInterfaceSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationInterfaceSyntax.errors.txt index 17fb8fcb187..9e53438c732 100644 --- a/tests/baselines/reference/jsFileCompilationInterfaceSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationInterfaceSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,11): error TS8006: 'interface declarations' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== interface I { } ~ diff --git a/tests/baselines/reference/jsFileCompilationModuleSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationModuleSyntax.errors.txt index 662028c53ed..6952c0055c0 100644 --- a/tests/baselines/reference/jsFileCompilationModuleSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationModuleSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,8): error TS8007: 'module declarations' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== module M { } ~ diff --git a/tests/baselines/reference/jsFileCompilationNoErrorWithoutDeclarationsWithJsFileReferenceWithNoOut.errors.txt b/tests/baselines/reference/jsFileCompilationNoErrorWithoutDeclarationsWithJsFileReferenceWithNoOut.errors.txt index f2f4142b993..888310414f2 100644 --- a/tests/baselines/reference/jsFileCompilationNoErrorWithoutDeclarationsWithJsFileReferenceWithNoOut.errors.txt +++ b/tests/baselines/reference/jsFileCompilationNoErrorWithoutDeclarationsWithJsFileReferenceWithNoOut.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/c.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/c.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/jsFileCompilationOptionalParameter.errors.txt b/tests/baselines/reference/jsFileCompilationOptionalParameter.errors.txt index 295f827dd2d..15bfe2281d9 100644 --- a/tests/baselines/reference/jsFileCompilationOptionalParameter.errors.txt +++ b/tests/baselines/reference/jsFileCompilationOptionalParameter.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,13): error TS8009: '?' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== function F(p?) { } ~ diff --git a/tests/baselines/reference/jsFileCompilationPublicMethodSyntaxOfClass.errors.txt b/tests/baselines/reference/jsFileCompilationPublicMethodSyntaxOfClass.errors.txt index d67c9baea70..af95c136205 100644 --- a/tests/baselines/reference/jsFileCompilationPublicMethodSyntaxOfClass.errors.txt +++ b/tests/baselines/reference/jsFileCompilationPublicMethodSyntaxOfClass.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(2,5): error TS8009: 'public' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== class C { public foo() { diff --git a/tests/baselines/reference/jsFileCompilationPublicParameterModifier.errors.txt b/tests/baselines/reference/jsFileCompilationPublicParameterModifier.errors.txt index bc4913f6217..9314e1da807 100644 --- a/tests/baselines/reference/jsFileCompilationPublicParameterModifier.errors.txt +++ b/tests/baselines/reference/jsFileCompilationPublicParameterModifier.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,23): error TS8012: 'parameter modifiers' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== class C { constructor(public x) { }} ~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationReturnTypeSyntaxOfFunction.errors.txt b/tests/baselines/reference/jsFileCompilationReturnTypeSyntaxOfFunction.errors.txt index 6dad5a29485..acae950d081 100644 --- a/tests/baselines/reference/jsFileCompilationReturnTypeSyntaxOfFunction.errors.txt +++ b/tests/baselines/reference/jsFileCompilationReturnTypeSyntaxOfFunction.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,15): error TS8010: 'types' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== function F(): number { } ~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationSyntaxError.errors.txt b/tests/baselines/reference/jsFileCompilationSyntaxError.errors.txt index d98a1e7e7bb..eb4c114d3d0 100644 --- a/tests/baselines/reference/jsFileCompilationSyntaxError.errors.txt +++ b/tests/baselines/reference/jsFileCompilationSyntaxError.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (0 errors) ==== /** * @type {number} diff --git a/tests/baselines/reference/jsFileCompilationTypeAliasSyntax.errors.txt b/tests/baselines/reference/jsFileCompilationTypeAliasSyntax.errors.txt index 2b5112e1ce2..74978eddf8c 100644 --- a/tests/baselines/reference/jsFileCompilationTypeAliasSyntax.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeAliasSyntax.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,6): error TS8008: 'type aliases' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== type a = b; ~ diff --git a/tests/baselines/reference/jsFileCompilationTypeArgumentSyntaxOfCall.errors.txt b/tests/baselines/reference/jsFileCompilationTypeArgumentSyntaxOfCall.errors.txt index 8ac59196ed9..f53ec55d2b1 100644 --- a/tests/baselines/reference/jsFileCompilationTypeArgumentSyntaxOfCall.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeArgumentSyntaxOfCall.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,5): error TS8011: 'type arguments' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== Foo(); ~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt b/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt index 662eea4d405..be1e6d32436 100644 --- a/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt @@ -1,9 +1,11 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,10): error TS17008: JSX element 'string' has no corresponding closing tag. tests/cases/compiler/a.js(1,27): error TS1005: 'undefined; ~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationTypeOfParameter.errors.txt b/tests/baselines/reference/jsFileCompilationTypeOfParameter.errors.txt index 680b32a64f1..811c0793ffe 100644 --- a/tests/baselines/reference/jsFileCompilationTypeOfParameter.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeOfParameter.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,15): error TS8010: 'types' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== function F(a: number) { } ~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfClass.errors.txt b/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfClass.errors.txt index 161c832ffd5..0fe902aa661 100644 --- a/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfClass.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfClass.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,9): error TS8004: 'type parameter declarations' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== class C { } ~ diff --git a/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfFunction.errors.txt b/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfFunction.errors.txt index d7626f68564..bfc4c7be26a 100644 --- a/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfFunction.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeParameterSyntaxOfFunction.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,12): error TS8004: 'type parameter declarations' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== function F() { } ~ diff --git a/tests/baselines/reference/jsFileCompilationTypeSyntaxOfVar.errors.txt b/tests/baselines/reference/jsFileCompilationTypeSyntaxOfVar.errors.txt index 2c6ac3771be..65333751780 100644 --- a/tests/baselines/reference/jsFileCompilationTypeSyntaxOfVar.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeSyntaxOfVar.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig tests/cases/compiler/a.js(1,8): error TS8010: 'types' can only be used in a .ts file. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.js (1 errors) ==== var v: () => number; ~~~~~~~~~~~~ diff --git a/tests/baselines/reference/jsFileCompilationWithDeclarationEmitPathSameAsInput.errors.txt b/tests/baselines/reference/jsFileCompilationWithDeclarationEmitPathSameAsInput.errors.txt index 9e9c2adb0ef..4170e818fd7 100644 --- a/tests/baselines/reference/jsFileCompilationWithDeclarationEmitPathSameAsInput.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithDeclarationEmitPathSameAsInput.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.d.ts' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/a.d.ts' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/jsFileCompilationWithJsEmitPathSameAsInput.errors.txt b/tests/baselines/reference/jsFileCompilationWithJsEmitPathSameAsInput.errors.txt index 4cc2cc2ab45..8004efd02ef 100644 --- a/tests/baselines/reference/jsFileCompilationWithJsEmitPathSameAsInput.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithJsEmitPathSameAsInput.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig error TS5056: Cannot write file 'tests/cases/compiler/a.js' because it would be overwritten by multiple input files. !!! error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5056: Cannot write file 'tests/cases/compiler/a.js' because it would be overwritten by multiple input files. ==== tests/cases/compiler/a.ts (0 errors) ==== class c { diff --git a/tests/baselines/reference/jsFileCompilationWithMapFileAsJs.errors.txt b/tests/baselines/reference/jsFileCompilationWithMapFileAsJs.errors.txt index 06186b9f0b2..069c562f29b 100644 --- a/tests/baselines/reference/jsFileCompilationWithMapFileAsJs.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithMapFileAsJs.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig error TS6054: File 'tests/cases/compiler/b.js.map' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'. !!! error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS6054: File 'tests/cases/compiler/b.js.map' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'. ==== tests/cases/compiler/a.ts (0 errors) ==== diff --git a/tests/baselines/reference/jsFileCompilationWithMapFileAsJsWithInlineSourceMap.errors.txt b/tests/baselines/reference/jsFileCompilationWithMapFileAsJsWithInlineSourceMap.errors.txt index 06186b9f0b2..069c562f29b 100644 --- a/tests/baselines/reference/jsFileCompilationWithMapFileAsJsWithInlineSourceMap.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithMapFileAsJsWithInlineSourceMap.errors.txt @@ -1,8 +1,10 @@ error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig error TS6054: File 'tests/cases/compiler/b.js.map' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'. !!! error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS6054: File 'tests/cases/compiler/b.js.map' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'. ==== tests/cases/compiler/a.ts (0 errors) ==== diff --git a/tests/baselines/reference/jsFileCompilationWithOutDeclarationFileNameSameAsInputJsFile.errors.txt b/tests/baselines/reference/jsFileCompilationWithOutDeclarationFileNameSameAsInputJsFile.errors.txt index 10c7b8c90dd..0a4f0cdf1a4 100644 --- a/tests/baselines/reference/jsFileCompilationWithOutDeclarationFileNameSameAsInputJsFile.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithOutDeclarationFileNameSameAsInputJsFile.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/b.d.ts' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/b.d.ts' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/jsFileCompilationWithOutFileNameSameAsInputJsFile.errors.txt b/tests/baselines/reference/jsFileCompilationWithOutFileNameSameAsInputJsFile.errors.txt index 0f6852b21a0..3f72a8113ef 100644 --- a/tests/baselines/reference/jsFileCompilationWithOutFileNameSameAsInputJsFile.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithOutFileNameSameAsInputJsFile.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/jsFileCompilationWithoutOut.errors.txt b/tests/baselines/reference/jsFileCompilationWithoutOut.errors.txt index 0f6852b21a0..3f72a8113ef 100644 --- a/tests/baselines/reference/jsFileCompilationWithoutOut.errors.txt +++ b/tests/baselines/reference/jsFileCompilationWithoutOut.errors.txt @@ -1,7 +1,9 @@ error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5055: Cannot write file 'tests/cases/compiler/b.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== tests/cases/compiler/a.ts (0 errors) ==== class c { } diff --git a/tests/baselines/reference/json.stringify.types b/tests/baselines/reference/json.stringify.types index 8ff84885d9c..b063b06d8d0 100644 --- a/tests/baselines/reference/json.stringify.types +++ b/tests/baselines/reference/json.stringify.types @@ -1,7 +1,7 @@ === tests/cases/compiler/json.stringify.ts === var value = null; ->value : any +>value : null >null : null JSON.stringify(value, undefined, 2); diff --git a/tests/baselines/reference/jsxEmitWithAttributes.js b/tests/baselines/reference/jsxEmitWithAttributes.js new file mode 100644 index 00000000000..1acead2801d --- /dev/null +++ b/tests/baselines/reference/jsxEmitWithAttributes.js @@ -0,0 +1,81 @@ +//// [tests/cases/compiler/jsxEmitWithAttributes.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//// [test.js] +"use strict"; +const Element_1 = require("./Element"); +let c; +class A { + view() { + return [ + Element_1.Element.createElement("meta", { content: "helloworld" }), + Element_1.Element.createElement("meta", { content: c.a.b }) + ]; + } +} diff --git a/tests/baselines/reference/jsxEmitWithAttributes.symbols b/tests/baselines/reference/jsxEmitWithAttributes.symbols new file mode 100644 index 00000000000..16cd35d1ca3 --- /dev/null +++ b/tests/baselines/reference/jsxEmitWithAttributes.symbols @@ -0,0 +1,119 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) + + interface Element { +>Element : Symbol(Element, Decl(Element.ts, 1, 23)) + + name: string; +>name : Symbol(Element.name, Decl(Element.ts, 2, 23)) + + isIntrinsic: boolean; +>isIntrinsic : Symbol(Element.isIntrinsic, Decl(Element.ts, 3, 21)) + + isCustomElement: boolean; +>isCustomElement : Symbol(Element.isCustomElement, Decl(Element.ts, 4, 29)) + + toString(renderId?: number): string; +>toString : Symbol(Element.toString, Decl(Element.ts, 5, 33)) +>renderId : Symbol(renderId, Decl(Element.ts, 6, 17)) + + bindDOM(renderId?: number): number; +>bindDOM : Symbol(Element.bindDOM, Decl(Element.ts, 6, 44)) +>renderId : Symbol(renderId, Decl(Element.ts, 7, 16)) + + resetComponent(): void; +>resetComponent : Symbol(Element.resetComponent, Decl(Element.ts, 7, 43)) + + instantiateComponents(renderId?: number): number; +>instantiateComponents : Symbol(Element.instantiateComponents, Decl(Element.ts, 8, 31)) +>renderId : Symbol(renderId, Decl(Element.ts, 9, 30)) + + props: any; +>props : Symbol(Element.props, Decl(Element.ts, 9, 57)) + } +} +export namespace Element { +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) + + export function isElement(el: any): el is JSX.Element { +>isElement : Symbol(isElement, Decl(Element.ts, 13, 26)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) +>Element : Symbol(JSX.Element, Decl(Element.ts, 1, 23)) + + return el.markAsChildOfRootElement !== undefined; +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>undefined : Symbol(undefined) + } + + export function createElement(args: any[]) { +>createElement : Symbol(createElement, Decl(Element.ts, 16, 5)) +>args : Symbol(args, Decl(Element.ts, 18, 34)) + + return { + } + } +} + +export let createElement = Element.createElement; +>createElement : Symbol(createElement, Decl(Element.ts, 25, 10)) +>Element.createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) +>createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) + +function toCamelCase(text: string): string { +>toCamelCase : Symbol(toCamelCase, Decl(Element.ts, 25, 49)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : Symbol(Element, Decl(test.tsx, 0, 8)) + +let c: { +>c : Symbol(c, Decl(test.tsx, 2, 3)) + + a?: { +>a : Symbol(a, Decl(test.tsx, 2, 8)) + + b: string +>b : Symbol(b, Decl(test.tsx, 3, 6)) + } +}; + +class A { +>A : Symbol(A, Decl(test.tsx, 6, 2)) + + view() { +>view : Symbol(A.view, Decl(test.tsx, 8, 9)) + + return [ + , +>meta : Symbol(unknown) +>content : Symbol(unknown) +>meta : Symbol(unknown) + + +>meta : Symbol(unknown) +>content : Symbol(unknown) +>c.a!.b : Symbol(b, Decl(test.tsx, 3, 6)) +>c.a : Symbol(a, Decl(test.tsx, 2, 8)) +>c : Symbol(c, Decl(test.tsx, 2, 3)) +>a : Symbol(a, Decl(test.tsx, 2, 8)) +>b : Symbol(b, Decl(test.tsx, 3, 6)) +>meta : Symbol(unknown) + + ]; + } +} diff --git a/tests/baselines/reference/jsxEmitWithAttributes.types b/tests/baselines/reference/jsxEmitWithAttributes.types new file mode 100644 index 00000000000..663ba4b5bfc --- /dev/null +++ b/tests/baselines/reference/jsxEmitWithAttributes.types @@ -0,0 +1,134 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : any + + interface Element { +>Element : Element + + name: string; +>name : string + + isIntrinsic: boolean; +>isIntrinsic : boolean + + isCustomElement: boolean; +>isCustomElement : boolean + + toString(renderId?: number): string; +>toString : (renderId?: number) => string +>renderId : number + + bindDOM(renderId?: number): number; +>bindDOM : (renderId?: number) => number +>renderId : number + + resetComponent(): void; +>resetComponent : () => void + + instantiateComponents(renderId?: number): number; +>instantiateComponents : (renderId?: number) => number +>renderId : number + + props: any; +>props : any + } +} +export namespace Element { +>Element : typeof Element + + export function isElement(el: any): el is JSX.Element { +>isElement : (el: any) => el is JSX.Element +>el : any +>el : any +>JSX : any +>Element : JSX.Element + + return el.markAsChildOfRootElement !== undefined; +>el.markAsChildOfRootElement !== undefined : boolean +>el.markAsChildOfRootElement : any +>el : any +>markAsChildOfRootElement : any +>undefined : undefined + } + + export function createElement(args: any[]) { +>createElement : (args: any[]) => {} +>args : any[] + + return { +>{ } : {} + } + } +} + +export let createElement = Element.createElement; +>createElement : (args: any[]) => {} +>Element.createElement : (args: any[]) => {} +>Element : typeof Element +>createElement : (args: any[]) => {} + +function toCamelCase(text: string): string { +>toCamelCase : (text: string) => string +>text : string + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase() + text.substring(1) : string +>text[0].toLowerCase() : string +>text[0].toLowerCase : () => string +>text[0] : string +>text : string +>0 : 0 +>toLowerCase : () => string +>text.substring(1) : string +>text.substring : (start: number, end?: number) => string +>text : string +>substring : (start: number, end?: number) => string +>1 : 1 +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : typeof Element + +let c: { +>c : { a?: { b: string; }; } + + a?: { +>a : { b: string; } + + b: string +>b : string + } +}; + +class A { +>A : A + + view() { +>view : () => any[] + + return [ +>[ , ] : any[] + + , +> : any +>meta : any +>content : any +>meta : any + + +> : any +>meta : any +>content : any +>c.a!.b : string +>c.a! : { b: string; } +>c.a : { b: string; } +>c : { a?: { b: string; }; } +>a : { b: string; } +>b : string +>meta : any + + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryAndReactNamespace.errors.txt b/tests/baselines/reference/jsxFactoryAndReactNamespace.errors.txt new file mode 100644 index 00000000000..c4859fd534c --- /dev/null +++ b/tests/baselines/reference/jsxFactoryAndReactNamespace.errors.txt @@ -0,0 +1,53 @@ +error TS5053: Option 'reactNamespace' cannot be specified with option 'jsxFactory'. + + +!!! error TS5053: Option 'reactNamespace' cannot be specified with option 'jsxFactory'. +==== tests/cases/compiler/Element.ts (0 errors) ==== + + declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } + } + export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } + } + + export let createElement = Element.createElement; + + function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); + } + +==== tests/cases/compiler/test.tsx (0 errors) ==== + import { Element} from './Element'; + + let c: { + a?: { + b: string + } + }; + + class A { + view() { + return [ + , + + ]; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryAndReactNamespace.js b/tests/baselines/reference/jsxFactoryAndReactNamespace.js new file mode 100644 index 00000000000..0a6402ca70c --- /dev/null +++ b/tests/baselines/reference/jsxFactoryAndReactNamespace.js @@ -0,0 +1,81 @@ +//// [tests/cases/compiler/jsxFactoryAndReactNamespace.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//// [test.js] +"use strict"; +const Element_1 = require("./Element"); +let c; +class A { + view() { + return [ + Element_1.Element.createElement("meta", { content: "helloworld" }), + Element_1.Element.createElement("meta", { content: c.a.b }) + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryIdentifier.js b/tests/baselines/reference/jsxFactoryIdentifier.js new file mode 100644 index 00000000000..82c8f6410e6 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifier.js @@ -0,0 +1,83 @@ +//// [tests/cases/compiler/jsxFactoryIdentifier.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; +let createElement = Element.createElement; +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//# sourceMappingURL=Element.js.map//// [test.js] +"use strict"; +const Element_1 = require("./Element"); +let createElement = Element_1.Element.createElement; +let c; +class A { + view() { + return [ + createElement("meta", { content: "helloworld" }), + createElement("meta", { content: c.a.b }) + ]; + } +} +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifier.js.map b/tests/baselines/reference/jsxFactoryIdentifier.js.map new file mode 100644 index 00000000000..cad196b8ba5 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifier.js.map @@ -0,0 +1,3 @@ +//// [Element.js.map] +{"version":3,"file":"Element.js","sourceRoot":"","sources":["Element.ts"],"names":[],"mappings":";AAaA,IAAiB,OAAO,CAUvB;AAVD,WAAiB,OAAO;IACpB,mBAA0B,EAAO;QAC7B,MAAM,CAAC,EAAE,CAAC,wBAAwB,KAAK,SAAS,CAAC;IACrD,CAAC;IAFe,iBAAS,YAExB,CAAA;IAED,uBAA8B,IAAW;QAErC,MAAM,CAAC,EACN,CAAA;IACL,CAAC;IAJe,qBAAa,gBAI5B,CAAA;AACL,CAAC,EAVgB,OAAO,GAAP,eAAO,KAAP,eAAO,QAUvB;AAEU,QAAA,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;AAEjD,qBAAqB,IAAY;IAC7B,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AACrD,CAAC"}//// [test.js.map] +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.tsx"],"names":[],"mappings":";AAAA,uCAAmC;AACnC,IAAI,aAAa,GAAG,iBAAO,CAAC,aAAa,CAAC;AAC1C,IAAI,CAIH,CAAC;AAEF;IACC,IAAI;QACH,MAAM,CAAC;YACN,wBAAM,OAAO,EAAC,YAAY,GAAQ;YAClC,wBAAM,OAAO,EAAE,CAAC,CAAC,CAAE,CAAC,CAAC,GAAS;SAC9B,CAAC;IACH,CAAC;CACD"} \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifier.sourcemap.txt b/tests/baselines/reference/jsxFactoryIdentifier.sourcemap.txt new file mode 100644 index 00000000000..a4ddc8c050b --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifier.sourcemap.txt @@ -0,0 +1,520 @@ +=================================================================== +JsFile: Element.js +mapUrl: Element.js.map +sourceRoot: +sources: Element.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/Element.js +sourceFile:Element.ts +------------------------------------------------------------------- +>>>"use strict"; +>>>var Element; +1 > +2 >^^^^ +3 > ^^^^^^^ +4 > ^ +5 > ^^^^^^^^^^-> +1 > + >declare namespace JSX { + > interface Element { + > name: string; + > isIntrinsic: boolean; + > isCustomElement: boolean; + > toString(renderId?: number): string; + > bindDOM(renderId?: number): number; + > resetComponent(): void; + > instantiateComponents(renderId?: number): number; + > props: any; + > } + >} + > +2 >export namespace +3 > Element +4 > { + > export function isElement(el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } + > + > export function createElement(args: any[]) { + > + > return { + > } + > } + > } +1 >Emitted(2, 1) Source(14, 1) + SourceIndex(0) +2 >Emitted(2, 5) Source(14, 18) + SourceIndex(0) +3 >Emitted(2, 12) Source(14, 25) + SourceIndex(0) +4 >Emitted(2, 13) Source(24, 2) + SourceIndex(0) +--- +>>>(function (Element) { +1-> +2 >^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^^^^^^^^^^-> +1-> +2 >export namespace +3 > Element +1->Emitted(3, 1) Source(14, 1) + SourceIndex(0) +2 >Emitted(3, 12) Source(14, 18) + SourceIndex(0) +3 >Emitted(3, 19) Source(14, 25) + SourceIndex(0) +--- +>>> function isElement(el) { +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^ +3 > ^^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1-> { + > +2 > export function isElement( +3 > el: any +1->Emitted(4, 5) Source(15, 5) + SourceIndex(0) +2 >Emitted(4, 24) Source(15, 31) + SourceIndex(0) +3 >Emitted(4, 26) Source(15, 38) + SourceIndex(0) +--- +>>> return el.markAsChildOfRootElement !== undefined; +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^ +5 > ^ +6 > ^^^^^^^^^^^^^^^^^^^^^^^^ +7 > ^^^^^ +8 > ^^^^^^^^^ +9 > ^ +1->): el is JSX.Element { + > +2 > return +3 > +4 > el +5 > . +6 > markAsChildOfRootElement +7 > !== +8 > undefined +9 > ; +1->Emitted(5, 9) Source(16, 9) + SourceIndex(0) +2 >Emitted(5, 15) Source(16, 15) + SourceIndex(0) +3 >Emitted(5, 16) Source(16, 16) + SourceIndex(0) +4 >Emitted(5, 18) Source(16, 18) + SourceIndex(0) +5 >Emitted(5, 19) Source(16, 19) + SourceIndex(0) +6 >Emitted(5, 43) Source(16, 43) + SourceIndex(0) +7 >Emitted(5, 48) Source(16, 48) + SourceIndex(0) +8 >Emitted(5, 57) Source(16, 57) + SourceIndex(0) +9 >Emitted(5, 58) Source(16, 58) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 > } +1 >Emitted(6, 5) Source(17, 5) + SourceIndex(0) +2 >Emitted(6, 6) Source(17, 6) + SourceIndex(0) +--- +>>> Element.isElement = isElement; +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^^^^^^ +4 > ^ +5 > ^-> +1-> +2 > isElement +3 > (el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } +4 > +1->Emitted(7, 5) Source(15, 21) + SourceIndex(0) +2 >Emitted(7, 22) Source(15, 30) + SourceIndex(0) +3 >Emitted(7, 34) Source(17, 6) + SourceIndex(0) +4 >Emitted(7, 35) Source(17, 6) + SourceIndex(0) +--- +>>> function createElement(args) { +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^ +1-> + > + > +2 > export function createElement( +3 > args: any[] +1->Emitted(8, 5) Source(19, 5) + SourceIndex(0) +2 >Emitted(8, 28) Source(19, 35) + SourceIndex(0) +3 >Emitted(8, 32) Source(19, 46) + SourceIndex(0) +--- +>>> return {}; +1 >^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^ +5 > ^ +1 >) { + > + > +2 > return +3 > +4 > { + > } +5 > +1 >Emitted(9, 9) Source(21, 9) + SourceIndex(0) +2 >Emitted(9, 15) Source(21, 15) + SourceIndex(0) +3 >Emitted(9, 16) Source(21, 16) + SourceIndex(0) +4 >Emitted(9, 18) Source(22, 10) + SourceIndex(0) +5 >Emitted(9, 19) Source(22, 10) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 > } +1 >Emitted(10, 5) Source(23, 5) + SourceIndex(0) +2 >Emitted(10, 6) Source(23, 6) + SourceIndex(0) +--- +>>> Element.createElement = createElement; +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^^^^^^^^^^ +4 > ^ +5 > ^^^^^^^^^^^^^^^-> +1-> +2 > createElement +3 > (args: any[]) { + > + > return { + > } + > } +4 > +1->Emitted(11, 5) Source(19, 21) + SourceIndex(0) +2 >Emitted(11, 26) Source(19, 34) + SourceIndex(0) +3 >Emitted(11, 42) Source(23, 6) + SourceIndex(0) +4 >Emitted(11, 43) Source(23, 6) + SourceIndex(0) +--- +>>>})(Element = exports.Element || (exports.Element = {})); +1-> +2 >^ +3 > ^^ +4 > ^^^^^^^ +5 > ^^^ +6 > ^^^^^^^^^^^^^^^ +7 > ^^^^^ +8 > ^^^^^^^^^^^^^^^ +9 > ^^^^^^^^ +1-> + > +2 >} +3 > +4 > Element +5 > +6 > Element +7 > +8 > Element +9 > { + > export function isElement(el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } + > + > export function createElement(args: any[]) { + > + > return { + > } + > } + > } +1->Emitted(12, 1) Source(24, 1) + SourceIndex(0) +2 >Emitted(12, 2) Source(24, 2) + SourceIndex(0) +3 >Emitted(12, 4) Source(14, 18) + SourceIndex(0) +4 >Emitted(12, 11) Source(14, 25) + SourceIndex(0) +5 >Emitted(12, 14) Source(14, 18) + SourceIndex(0) +6 >Emitted(12, 29) Source(14, 25) + SourceIndex(0) +7 >Emitted(12, 34) Source(14, 18) + SourceIndex(0) +8 >Emitted(12, 49) Source(14, 25) + SourceIndex(0) +9 >Emitted(12, 57) Source(24, 2) + SourceIndex(0) +--- +>>>exports.createElement = Element.createElement; +1 > +2 >^^^^^^^^ +3 > ^^^^^^^^^^^^^ +4 > ^^^ +5 > ^^^^^^^ +6 > ^ +7 > ^^^^^^^^^^^^^ +8 > ^ +1 > + > + >export let +2 > +3 > createElement +4 > = +5 > Element +6 > . +7 > createElement +8 > ; +1 >Emitted(13, 1) Source(26, 12) + SourceIndex(0) +2 >Emitted(13, 9) Source(26, 12) + SourceIndex(0) +3 >Emitted(13, 22) Source(26, 25) + SourceIndex(0) +4 >Emitted(13, 25) Source(26, 28) + SourceIndex(0) +5 >Emitted(13, 32) Source(26, 35) + SourceIndex(0) +6 >Emitted(13, 33) Source(26, 36) + SourceIndex(0) +7 >Emitted(13, 46) Source(26, 49) + SourceIndex(0) +8 >Emitted(13, 47) Source(26, 50) + SourceIndex(0) +--- +>>>function toCamelCase(text) { +1 > +2 >^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > + > +2 >function toCamelCase( +3 > text: string +1 >Emitted(14, 1) Source(28, 1) + SourceIndex(0) +2 >Emitted(14, 22) Source(28, 22) + SourceIndex(0) +3 >Emitted(14, 26) Source(28, 34) + SourceIndex(0) +--- +>>> return text[0].toLowerCase() + text.substring(1); +1->^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^ +5 > ^ +6 > ^ +7 > ^ +8 > ^ +9 > ^^^^^^^^^^^ +10> ^^ +11> ^^^ +12> ^^^^ +13> ^ +14> ^^^^^^^^^ +15> ^ +16> ^ +17> ^ +18> ^ +1->): string { + > +2 > return +3 > +4 > text +5 > [ +6 > 0 +7 > ] +8 > . +9 > toLowerCase +10> () +11> + +12> text +13> . +14> substring +15> ( +16> 1 +17> ) +18> ; +1->Emitted(15, 5) Source(29, 5) + SourceIndex(0) +2 >Emitted(15, 11) Source(29, 11) + SourceIndex(0) +3 >Emitted(15, 12) Source(29, 12) + SourceIndex(0) +4 >Emitted(15, 16) Source(29, 16) + SourceIndex(0) +5 >Emitted(15, 17) Source(29, 17) + SourceIndex(0) +6 >Emitted(15, 18) Source(29, 18) + SourceIndex(0) +7 >Emitted(15, 19) Source(29, 19) + SourceIndex(0) +8 >Emitted(15, 20) Source(29, 20) + SourceIndex(0) +9 >Emitted(15, 31) Source(29, 31) + SourceIndex(0) +10>Emitted(15, 33) Source(29, 33) + SourceIndex(0) +11>Emitted(15, 36) Source(29, 36) + SourceIndex(0) +12>Emitted(15, 40) Source(29, 40) + SourceIndex(0) +13>Emitted(15, 41) Source(29, 41) + SourceIndex(0) +14>Emitted(15, 50) Source(29, 50) + SourceIndex(0) +15>Emitted(15, 51) Source(29, 51) + SourceIndex(0) +16>Emitted(15, 52) Source(29, 52) + SourceIndex(0) +17>Emitted(15, 53) Source(29, 53) + SourceIndex(0) +18>Emitted(15, 54) Source(29, 54) + SourceIndex(0) +--- +>>>} +1 > +2 >^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 >} +1 >Emitted(16, 1) Source(30, 1) + SourceIndex(0) +2 >Emitted(16, 2) Source(30, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=Element.js.map=================================================================== +JsFile: test.js +mapUrl: test.js.map +sourceRoot: +sources: test.tsx +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/test.js +sourceFile:test.tsx +------------------------------------------------------------------- +>>>"use strict"; +>>>const Element_1 = require("./Element"); +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^^^^^^^^-> +1 > +2 >import { Element} from './Element'; +1 >Emitted(2, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(2, 40) Source(1, 36) + SourceIndex(0) +--- +>>>let createElement = Element_1.Element.createElement; +1-> +2 >^^^^ +3 > ^^^^^^^^^^^^^ +4 > ^^^ +5 > ^^^^^^^^^^^^^^^^^ +6 > ^ +7 > ^^^^^^^^^^^^^ +8 > ^ +1-> + > +2 >let +3 > createElement +4 > = +5 > Element +6 > . +7 > createElement +8 > ; +1->Emitted(3, 1) Source(2, 1) + SourceIndex(0) +2 >Emitted(3, 5) Source(2, 5) + SourceIndex(0) +3 >Emitted(3, 18) Source(2, 18) + SourceIndex(0) +4 >Emitted(3, 21) Source(2, 21) + SourceIndex(0) +5 >Emitted(3, 38) Source(2, 28) + SourceIndex(0) +6 >Emitted(3, 39) Source(2, 29) + SourceIndex(0) +7 >Emitted(3, 52) Source(2, 42) + SourceIndex(0) +8 >Emitted(3, 53) Source(2, 43) + SourceIndex(0) +--- +>>>let c; +1 > +2 >^^^^ +3 > ^ +4 > ^ +5 > ^^^^-> +1 > + > +2 >let +3 > c: { + > a?: { + > b: string + > } + > } +4 > ; +1 >Emitted(4, 1) Source(3, 1) + SourceIndex(0) +2 >Emitted(4, 5) Source(3, 5) + SourceIndex(0) +3 >Emitted(4, 6) Source(7, 2) + SourceIndex(0) +4 >Emitted(4, 7) Source(7, 3) + SourceIndex(0) +--- +>>>class A { +1-> +2 >^^^^^^^^^^^^^-> +1-> + > + > +1->Emitted(5, 1) Source(9, 1) + SourceIndex(0) +--- +>>> view() { +1->^^^^ +2 > ^^^^ +3 > ^^^^^^^^^-> +1->class A { + > +2 > view +1->Emitted(6, 5) Source(10, 2) + SourceIndex(0) +2 >Emitted(6, 9) Source(10, 6) + SourceIndex(0) +--- +>>> return [ +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1->() { + > +2 > return +3 > +1->Emitted(7, 9) Source(11, 3) + SourceIndex(0) +2 >Emitted(7, 15) Source(11, 9) + SourceIndex(0) +3 >Emitted(7, 16) Source(11, 10) + SourceIndex(0) +--- +>>> createElement("meta", { content: "helloworld" }), +1->^^^^^^^^^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^ +5 > ^^^^^^^^^^^^ +6 > ^^^ +1->[ + > +2 > content +4 > = +5 > "helloworld" +6 > > +1->Emitted(8, 13) Source(12, 4) + SourceIndex(0) +2 >Emitted(8, 37) Source(12, 10) + SourceIndex(0) +3 >Emitted(8, 44) Source(12, 17) + SourceIndex(0) +4 >Emitted(8, 46) Source(12, 18) + SourceIndex(0) +5 >Emitted(8, 58) Source(12, 30) + SourceIndex(0) +6 >Emitted(8, 61) Source(12, 38) + SourceIndex(0) +--- +>>> createElement("meta", { content: c.a.b }) +1 >^^^^^^^^^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^ +5 > ^ +6 > ^ +7 > ^ +8 > ^ +9 > ^ +10> ^^^ +1 >, + > +2 > content +4 > ={ +5 > c +6 > . +7 > a! +8 > . +9 > b +10> }> +1 >Emitted(9, 13) Source(13, 4) + SourceIndex(0) +2 >Emitted(9, 37) Source(13, 10) + SourceIndex(0) +3 >Emitted(9, 44) Source(13, 17) + SourceIndex(0) +4 >Emitted(9, 46) Source(13, 19) + SourceIndex(0) +5 >Emitted(9, 47) Source(13, 20) + SourceIndex(0) +6 >Emitted(9, 48) Source(13, 21) + SourceIndex(0) +7 >Emitted(9, 49) Source(13, 23) + SourceIndex(0) +8 >Emitted(9, 50) Source(13, 24) + SourceIndex(0) +9 >Emitted(9, 51) Source(13, 25) + SourceIndex(0) +10>Emitted(9, 54) Source(13, 34) + SourceIndex(0) +--- +>>> ]; +1 >^^^^^^^^^ +2 > ^ +1 > + > ] +2 > ; +1 >Emitted(10, 10) Source(14, 4) + SourceIndex(0) +2 >Emitted(10, 11) Source(14, 5) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +1 > + > +2 > } +1 >Emitted(11, 5) Source(15, 2) + SourceIndex(0) +2 >Emitted(11, 6) Source(15, 3) + SourceIndex(0) +--- +>>>} +1 >^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >} +1 >Emitted(12, 2) Source(16, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifier.symbols b/tests/baselines/reference/jsxFactoryIdentifier.symbols new file mode 100644 index 00000000000..0d0f1e80490 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifier.symbols @@ -0,0 +1,125 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) + + interface Element { +>Element : Symbol(Element, Decl(Element.ts, 1, 23)) + + name: string; +>name : Symbol(Element.name, Decl(Element.ts, 2, 23)) + + isIntrinsic: boolean; +>isIntrinsic : Symbol(Element.isIntrinsic, Decl(Element.ts, 3, 21)) + + isCustomElement: boolean; +>isCustomElement : Symbol(Element.isCustomElement, Decl(Element.ts, 4, 29)) + + toString(renderId?: number): string; +>toString : Symbol(Element.toString, Decl(Element.ts, 5, 33)) +>renderId : Symbol(renderId, Decl(Element.ts, 6, 17)) + + bindDOM(renderId?: number): number; +>bindDOM : Symbol(Element.bindDOM, Decl(Element.ts, 6, 44)) +>renderId : Symbol(renderId, Decl(Element.ts, 7, 16)) + + resetComponent(): void; +>resetComponent : Symbol(Element.resetComponent, Decl(Element.ts, 7, 43)) + + instantiateComponents(renderId?: number): number; +>instantiateComponents : Symbol(Element.instantiateComponents, Decl(Element.ts, 8, 31)) +>renderId : Symbol(renderId, Decl(Element.ts, 9, 30)) + + props: any; +>props : Symbol(Element.props, Decl(Element.ts, 9, 57)) + } +} +export namespace Element { +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) + + export function isElement(el: any): el is JSX.Element { +>isElement : Symbol(isElement, Decl(Element.ts, 13, 26)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) +>Element : Symbol(JSX.Element, Decl(Element.ts, 1, 23)) + + return el.markAsChildOfRootElement !== undefined; +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>undefined : Symbol(undefined) + } + + export function createElement(args: any[]) { +>createElement : Symbol(createElement, Decl(Element.ts, 16, 5)) +>args : Symbol(args, Decl(Element.ts, 18, 34)) + + return { + } + } +} + +export let createElement = Element.createElement; +>createElement : Symbol(createElement, Decl(Element.ts, 25, 10)) +>Element.createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) +>createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) + +function toCamelCase(text: string): string { +>toCamelCase : Symbol(toCamelCase, Decl(Element.ts, 25, 49)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : Symbol(Element, Decl(test.tsx, 0, 8)) + +let createElement = Element.createElement; +>createElement : Symbol(createElement, Decl(test.tsx, 1, 3)) +>Element.createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) +>Element : Symbol(Element, Decl(test.tsx, 0, 8)) +>createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) + +let c: { +>c : Symbol(c, Decl(test.tsx, 2, 3)) + + a?: { +>a : Symbol(a, Decl(test.tsx, 2, 8)) + + b: string +>b : Symbol(b, Decl(test.tsx, 3, 6)) + } +}; + +class A { +>A : Symbol(A, Decl(test.tsx, 6, 2)) + + view() { +>view : Symbol(A.view, Decl(test.tsx, 8, 9)) + + return [ + , +>meta : Symbol(unknown) +>content : Symbol(unknown) +>meta : Symbol(unknown) + + +>meta : Symbol(unknown) +>content : Symbol(unknown) +>c.a!.b : Symbol(b, Decl(test.tsx, 3, 6)) +>c.a : Symbol(a, Decl(test.tsx, 2, 8)) +>c : Symbol(c, Decl(test.tsx, 2, 3)) +>a : Symbol(a, Decl(test.tsx, 2, 8)) +>b : Symbol(b, Decl(test.tsx, 3, 6)) +>meta : Symbol(unknown) + + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryIdentifier.types b/tests/baselines/reference/jsxFactoryIdentifier.types new file mode 100644 index 00000000000..c946c90559d --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifier.types @@ -0,0 +1,140 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : any + + interface Element { +>Element : Element + + name: string; +>name : string + + isIntrinsic: boolean; +>isIntrinsic : boolean + + isCustomElement: boolean; +>isCustomElement : boolean + + toString(renderId?: number): string; +>toString : (renderId?: number) => string +>renderId : number + + bindDOM(renderId?: number): number; +>bindDOM : (renderId?: number) => number +>renderId : number + + resetComponent(): void; +>resetComponent : () => void + + instantiateComponents(renderId?: number): number; +>instantiateComponents : (renderId?: number) => number +>renderId : number + + props: any; +>props : any + } +} +export namespace Element { +>Element : typeof Element + + export function isElement(el: any): el is JSX.Element { +>isElement : (el: any) => el is JSX.Element +>el : any +>el : any +>JSX : any +>Element : JSX.Element + + return el.markAsChildOfRootElement !== undefined; +>el.markAsChildOfRootElement !== undefined : boolean +>el.markAsChildOfRootElement : any +>el : any +>markAsChildOfRootElement : any +>undefined : undefined + } + + export function createElement(args: any[]) { +>createElement : (args: any[]) => {} +>args : any[] + + return { +>{ } : {} + } + } +} + +export let createElement = Element.createElement; +>createElement : (args: any[]) => {} +>Element.createElement : (args: any[]) => {} +>Element : typeof Element +>createElement : (args: any[]) => {} + +function toCamelCase(text: string): string { +>toCamelCase : (text: string) => string +>text : string + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase() + text.substring(1) : string +>text[0].toLowerCase() : string +>text[0].toLowerCase : () => string +>text[0] : string +>text : string +>0 : 0 +>toLowerCase : () => string +>text.substring(1) : string +>text.substring : (start: number, end?: number) => string +>text : string +>substring : (start: number, end?: number) => string +>1 : 1 +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : typeof Element + +let createElement = Element.createElement; +>createElement : (args: any[]) => {} +>Element.createElement : (args: any[]) => {} +>Element : typeof Element +>createElement : (args: any[]) => {} + +let c: { +>c : { a?: { b: string; }; } + + a?: { +>a : { b: string; } + + b: string +>b : string + } +}; + +class A { +>A : A + + view() { +>view : () => any[] + + return [ +>[ , ] : any[] + + , +> : any +>meta : any +>content : any +>meta : any + + +> : any +>meta : any +>content : any +>c.a!.b : string +>c.a! : { b: string; } +>c.a : { b: string; } +>c : { a?: { b: string; }; } +>a : { b: string; } +>b : string +>meta : any + + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js new file mode 100644 index 00000000000..ffec40ff7b6 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js @@ -0,0 +1,24 @@ +//// [test.tsx] + +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render(createElement) { + return
; + } +} + + +//// [test.js] +"use strict"; +class AppComponent { + render(createElement) { + return createElement("div", null); + } +} +exports.AppComponent = AppComponent; +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js.map b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js.map new file mode 100644 index 00000000000..c108b93a913 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.js.map @@ -0,0 +1,2 @@ +//// [test.js.map] +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.tsx"],"names":[],"mappings":";AAOA;IACI,MAAM,CAAC,aAAa;QAChB,MAAM,CAAC,0BAAO,CAAC;IACnB,CAAC;CACJ;AAJD,oCAIC"} \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierAsParameter.sourcemap.txt b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.sourcemap.txt new file mode 100644 index 00000000000..c7867fc54e0 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.sourcemap.txt @@ -0,0 +1,87 @@ +=================================================================== +JsFile: test.js +mapUrl: test.js.map +sourceRoot: +sources: test.tsx +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/test.js +sourceFile:test.tsx +------------------------------------------------------------------- +>>>"use strict"; +>>>class AppComponent { +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >declare module JSX { + > interface IntrinsicElements { + > [s: string]: any; + > } + >} + > + > +1 >Emitted(2, 1) Source(8, 1) + SourceIndex(0) +--- +>>> render(createElement) { +1->^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^ +5 > ^^^^^^^^^^^^^^^^^^^-> +1->export class AppComponent { + > +2 > render +3 > ( +4 > createElement +1->Emitted(3, 5) Source(9, 5) + SourceIndex(0) +2 >Emitted(3, 11) Source(9, 11) + SourceIndex(0) +3 >Emitted(3, 12) Source(9, 12) + SourceIndex(0) +4 >Emitted(3, 25) Source(9, 25) + SourceIndex(0) +--- +>>> return createElement("div", null); +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^ +5 > ^ +1->) { + > +2 > return +3 > +4 >
+5 > ; +1->Emitted(4, 9) Source(10, 9) + SourceIndex(0) +2 >Emitted(4, 15) Source(10, 15) + SourceIndex(0) +3 >Emitted(4, 16) Source(10, 16) + SourceIndex(0) +4 >Emitted(4, 42) Source(10, 23) + SourceIndex(0) +5 >Emitted(4, 43) Source(10, 24) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +1 > + > +2 > } +1 >Emitted(5, 5) Source(11, 5) + SourceIndex(0) +2 >Emitted(5, 6) Source(11, 6) + SourceIndex(0) +--- +>>>} +1 >^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >} +1 >Emitted(6, 2) Source(12, 2) + SourceIndex(0) +--- +>>>exports.AppComponent = AppComponent; +1-> +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1-> +2 >export class AppComponent { + > render(createElement) { + > return
; + > } + >} +1->Emitted(7, 1) Source(8, 1) + SourceIndex(0) +2 >Emitted(7, 37) Source(12, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierAsParameter.symbols b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.symbols new file mode 100644 index 00000000000..865292092a5 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.symbols @@ -0,0 +1,25 @@ +=== tests/cases/compiler/test.tsx === + +declare module JSX { +>JSX : Symbol(JSX, Decl(test.tsx, 0, 0)) + + interface IntrinsicElements { +>IntrinsicElements : Symbol(IntrinsicElements, Decl(test.tsx, 1, 20)) + + [s: string]: any; +>s : Symbol(s, Decl(test.tsx, 3, 9)) + } +} + +export class AppComponent { +>AppComponent : Symbol(AppComponent, Decl(test.tsx, 5, 1)) + + render(createElement) { +>render : Symbol(AppComponent.render, Decl(test.tsx, 7, 27)) +>createElement : Symbol(createElement, Decl(test.tsx, 8, 11)) + + return
; +>div : Symbol(unknown) + } +} + diff --git a/tests/baselines/reference/jsxFactoryIdentifierAsParameter.types b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.types new file mode 100644 index 00000000000..d55737d98ae --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierAsParameter.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/test.tsx === + +declare module JSX { +>JSX : any + + interface IntrinsicElements { +>IntrinsicElements : IntrinsicElements + + [s: string]: any; +>s : string + } +} + +export class AppComponent { +>AppComponent : AppComponent + + render(createElement) { +>render : (createElement: any) => any +>createElement : any + + return
; +>
: any +>div : any + } +} + diff --git a/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.errors.txt b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.errors.txt new file mode 100644 index 00000000000..99e039a045f --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/test.tsx(10,17): error TS2304: Cannot find name 'createElement'. + + +==== tests/cases/compiler/test.tsx (1 errors) ==== + + declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } + } + + export class AppComponent { + render() { + return
; + ~~~ +!!! error TS2304: Cannot find name 'createElement'. + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js new file mode 100644 index 00000000000..23f6f44e0c7 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js @@ -0,0 +1,24 @@ +//// [test.tsx] + +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render() { + return
; + } +} + + +//// [test.js] +"use strict"; +class AppComponent { + render() { + return createElement("div", null); + } +} +exports.AppComponent = AppComponent; +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js.map b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js.map new file mode 100644 index 00000000000..715014ff53f --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.js.map @@ -0,0 +1,2 @@ +//// [test.js.map] +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.tsx"],"names":[],"mappings":";AAOA;IACI,MAAM;QACF,MAAM,CAAC,0BAAO,CAAC;IACnB,CAAC;CACJ;AAJD,oCAIC"} \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.sourcemap.txt b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.sourcemap.txt new file mode 100644 index 00000000000..f1ebaf49870 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryIdentifierWithAbsentParameter.sourcemap.txt @@ -0,0 +1,81 @@ +=================================================================== +JsFile: test.js +mapUrl: test.js.map +sourceRoot: +sources: test.tsx +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/test.js +sourceFile:test.tsx +------------------------------------------------------------------- +>>>"use strict"; +>>>class AppComponent { +1 > +2 >^^^^^^^^^^^^^^^-> +1 > + >declare module JSX { + > interface IntrinsicElements { + > [s: string]: any; + > } + >} + > + > +1 >Emitted(2, 1) Source(8, 1) + SourceIndex(0) +--- +>>> render() { +1->^^^^ +2 > ^^^^^^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1->export class AppComponent { + > +2 > render +1->Emitted(3, 5) Source(9, 5) + SourceIndex(0) +2 >Emitted(3, 11) Source(9, 11) + SourceIndex(0) +--- +>>> return createElement("div", null); +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^ +5 > ^ +1->() { + > +2 > return +3 > +4 >
+5 > ; +1->Emitted(4, 9) Source(10, 9) + SourceIndex(0) +2 >Emitted(4, 15) Source(10, 15) + SourceIndex(0) +3 >Emitted(4, 16) Source(10, 16) + SourceIndex(0) +4 >Emitted(4, 42) Source(10, 23) + SourceIndex(0) +5 >Emitted(4, 43) Source(10, 24) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +1 > + > +2 > } +1 >Emitted(5, 5) Source(11, 5) + SourceIndex(0) +2 >Emitted(5, 6) Source(11, 6) + SourceIndex(0) +--- +>>>} +1 >^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >} +1 >Emitted(6, 2) Source(12, 2) + SourceIndex(0) +--- +>>>exports.AppComponent = AppComponent; +1-> +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1-> +2 >export class AppComponent { + > render() { + > return
; + > } + >} +1->Emitted(7, 1) Source(8, 1) + SourceIndex(0) +2 >Emitted(7, 37) Source(12, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.errors.txt b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.errors.txt new file mode 100644 index 00000000000..e14f5f988f8 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.errors.txt @@ -0,0 +1,59 @@ +error TS5067: Invalid value for 'jsxFactory'. 'Element.createElement=' is not a valid identifier or qualified-name. +tests/cases/compiler/test.tsx(12,5): error TS2304: Cannot find name 'React'. +tests/cases/compiler/test.tsx(13,5): error TS2304: Cannot find name 'React'. + + +!!! error TS5067: Invalid value for 'jsxFactory'. 'Element.createElement=' is not a valid identifier or qualified-name. +==== tests/cases/compiler/Element.ts (0 errors) ==== + + declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } + } + export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } + } + + export let createElement = Element.createElement; + + function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); + } + +==== tests/cases/compiler/test.tsx (2 errors) ==== + import { Element} from './Element'; + + let c: { + a?: { + b: string + } + }; + + class A { + view() { + return [ + , + ~~~~ +!!! error TS2304: Cannot find name 'React'. + + ~~~~ +!!! error TS2304: Cannot find name 'React'. + ]; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.js b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.js new file mode 100644 index 00000000000..90bb675442a --- /dev/null +++ b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName.js @@ -0,0 +1,80 @@ +//// [tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//// [test.js] +"use strict"; +let c; +class A { + view() { + return [ + React.createElement("meta", { content: "helloworld" }), + React.createElement("meta", { content: c.a.b }) + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.errors.txt b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.errors.txt new file mode 100644 index 00000000000..1c33f3a7a51 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.errors.txt @@ -0,0 +1,59 @@ +error TS5067: Invalid value for 'jsxFactory'. 'id1 id2' is not a valid identifier or qualified-name. +tests/cases/compiler/test.tsx(12,5): error TS2304: Cannot find name 'React'. +tests/cases/compiler/test.tsx(13,5): error TS2304: Cannot find name 'React'. + + +!!! error TS5067: Invalid value for 'jsxFactory'. 'id1 id2' is not a valid identifier or qualified-name. +==== tests/cases/compiler/Element.ts (0 errors) ==== + + declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } + } + export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } + } + + export let createElement = Element.createElement; + + function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); + } + +==== tests/cases/compiler/test.tsx (2 errors) ==== + import { Element} from './Element'; + + let c: { + a?: { + b: string + } + }; + + class A { + view() { + return [ + , + ~~~~ +!!! error TS2304: Cannot find name 'React'. + + ~~~~ +!!! error TS2304: Cannot find name 'React'. + ]; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.js b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.js new file mode 100644 index 00000000000..0bc0c6e57c5 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryNotIdentifierOrQualifiedName2.js @@ -0,0 +1,80 @@ +//// [tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName2.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//// [test.js] +"use strict"; +let c; +class A { + view() { + return [ + React.createElement("meta", { content: "helloworld" }), + React.createElement("meta", { content: c.a.b }) + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryQualifiedName.js b/tests/baselines/reference/jsxFactoryQualifiedName.js new file mode 100644 index 00000000000..80a77d35302 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedName.js @@ -0,0 +1,82 @@ +//// [tests/cases/compiler/jsxFactoryQualifiedName.ts] //// + +//// [Element.ts] + +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +//// [test.tsx] +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} + +//// [Element.js] +"use strict"; +var Element; +(function (Element) { + function isElement(el) { + return el.markAsChildOfRootElement !== undefined; + } + Element.isElement = isElement; + function createElement(args) { + return {}; + } + Element.createElement = createElement; +})(Element = exports.Element || (exports.Element = {})); +exports.createElement = Element.createElement; +function toCamelCase(text) { + return text[0].toLowerCase() + text.substring(1); +} +//# sourceMappingURL=Element.js.map//// [test.js] +"use strict"; +const Element_1 = require("./Element"); +let c; +class A { + view() { + return [ + Element_1.Element.createElement("meta", { content: "helloworld" }), + Element_1.Element.createElement("meta", { content: c.a.b }) + ]; + } +} +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedName.js.map b/tests/baselines/reference/jsxFactoryQualifiedName.js.map new file mode 100644 index 00000000000..f8cef24a0f0 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedName.js.map @@ -0,0 +1,3 @@ +//// [Element.js.map] +{"version":3,"file":"Element.js","sourceRoot":"","sources":["Element.ts"],"names":[],"mappings":";AAaA,IAAiB,OAAO,CAUvB;AAVD,WAAiB,OAAO;IACpB,mBAA0B,EAAO;QAC7B,MAAM,CAAC,EAAE,CAAC,wBAAwB,KAAK,SAAS,CAAC;IACrD,CAAC;IAFe,iBAAS,YAExB,CAAA;IAED,uBAA8B,IAAW;QAErC,MAAM,CAAC,EACN,CAAA;IACL,CAAC;IAJe,qBAAa,gBAI5B,CAAA;AACL,CAAC,EAVgB,OAAO,GAAP,eAAO,KAAP,eAAO,QAUvB;AAEU,QAAA,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;AAEjD,qBAAqB,IAAY;IAC7B,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AACrD,CAAC"}//// [test.js.map] +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.tsx"],"names":[],"mappings":";AAAA,uCAAmC;AAEnC,IAAI,CAIH,CAAC;AAEF;IACC,IAAI;QACH,MAAM,CAAC;YACN,0CAAM,OAAO,EAAC,YAAY,GAAQ;YAClC,0CAAM,OAAO,EAAE,CAAC,CAAC,CAAE,CAAC,CAAC,GAAS;SAC9B,CAAC;IACH,CAAC;CACD"} \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedName.sourcemap.txt b/tests/baselines/reference/jsxFactoryQualifiedName.sourcemap.txt new file mode 100644 index 00000000000..98517620c73 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedName.sourcemap.txt @@ -0,0 +1,493 @@ +=================================================================== +JsFile: Element.js +mapUrl: Element.js.map +sourceRoot: +sources: Element.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/Element.js +sourceFile:Element.ts +------------------------------------------------------------------- +>>>"use strict"; +>>>var Element; +1 > +2 >^^^^ +3 > ^^^^^^^ +4 > ^ +5 > ^^^^^^^^^^-> +1 > + >declare namespace JSX { + > interface Element { + > name: string; + > isIntrinsic: boolean; + > isCustomElement: boolean; + > toString(renderId?: number): string; + > bindDOM(renderId?: number): number; + > resetComponent(): void; + > instantiateComponents(renderId?: number): number; + > props: any; + > } + >} + > +2 >export namespace +3 > Element +4 > { + > export function isElement(el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } + > + > export function createElement(args: any[]) { + > + > return { + > } + > } + > } +1 >Emitted(2, 1) Source(14, 1) + SourceIndex(0) +2 >Emitted(2, 5) Source(14, 18) + SourceIndex(0) +3 >Emitted(2, 12) Source(14, 25) + SourceIndex(0) +4 >Emitted(2, 13) Source(24, 2) + SourceIndex(0) +--- +>>>(function (Element) { +1-> +2 >^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^^^^^^^^^^-> +1-> +2 >export namespace +3 > Element +1->Emitted(3, 1) Source(14, 1) + SourceIndex(0) +2 >Emitted(3, 12) Source(14, 18) + SourceIndex(0) +3 >Emitted(3, 19) Source(14, 25) + SourceIndex(0) +--- +>>> function isElement(el) { +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^ +3 > ^^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1-> { + > +2 > export function isElement( +3 > el: any +1->Emitted(4, 5) Source(15, 5) + SourceIndex(0) +2 >Emitted(4, 24) Source(15, 31) + SourceIndex(0) +3 >Emitted(4, 26) Source(15, 38) + SourceIndex(0) +--- +>>> return el.markAsChildOfRootElement !== undefined; +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^ +5 > ^ +6 > ^^^^^^^^^^^^^^^^^^^^^^^^ +7 > ^^^^^ +8 > ^^^^^^^^^ +9 > ^ +1->): el is JSX.Element { + > +2 > return +3 > +4 > el +5 > . +6 > markAsChildOfRootElement +7 > !== +8 > undefined +9 > ; +1->Emitted(5, 9) Source(16, 9) + SourceIndex(0) +2 >Emitted(5, 15) Source(16, 15) + SourceIndex(0) +3 >Emitted(5, 16) Source(16, 16) + SourceIndex(0) +4 >Emitted(5, 18) Source(16, 18) + SourceIndex(0) +5 >Emitted(5, 19) Source(16, 19) + SourceIndex(0) +6 >Emitted(5, 43) Source(16, 43) + SourceIndex(0) +7 >Emitted(5, 48) Source(16, 48) + SourceIndex(0) +8 >Emitted(5, 57) Source(16, 57) + SourceIndex(0) +9 >Emitted(5, 58) Source(16, 58) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 > } +1 >Emitted(6, 5) Source(17, 5) + SourceIndex(0) +2 >Emitted(6, 6) Source(17, 6) + SourceIndex(0) +--- +>>> Element.isElement = isElement; +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^^^^^^ +4 > ^ +5 > ^-> +1-> +2 > isElement +3 > (el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } +4 > +1->Emitted(7, 5) Source(15, 21) + SourceIndex(0) +2 >Emitted(7, 22) Source(15, 30) + SourceIndex(0) +3 >Emitted(7, 34) Source(17, 6) + SourceIndex(0) +4 >Emitted(7, 35) Source(17, 6) + SourceIndex(0) +--- +>>> function createElement(args) { +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^ +1-> + > + > +2 > export function createElement( +3 > args: any[] +1->Emitted(8, 5) Source(19, 5) + SourceIndex(0) +2 >Emitted(8, 28) Source(19, 35) + SourceIndex(0) +3 >Emitted(8, 32) Source(19, 46) + SourceIndex(0) +--- +>>> return {}; +1 >^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^ +5 > ^ +1 >) { + > + > +2 > return +3 > +4 > { + > } +5 > +1 >Emitted(9, 9) Source(21, 9) + SourceIndex(0) +2 >Emitted(9, 15) Source(21, 15) + SourceIndex(0) +3 >Emitted(9, 16) Source(21, 16) + SourceIndex(0) +4 >Emitted(9, 18) Source(22, 10) + SourceIndex(0) +5 >Emitted(9, 19) Source(22, 10) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 > } +1 >Emitted(10, 5) Source(23, 5) + SourceIndex(0) +2 >Emitted(10, 6) Source(23, 6) + SourceIndex(0) +--- +>>> Element.createElement = createElement; +1->^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^^^^^^^^^^ +4 > ^ +5 > ^^^^^^^^^^^^^^^-> +1-> +2 > createElement +3 > (args: any[]) { + > + > return { + > } + > } +4 > +1->Emitted(11, 5) Source(19, 21) + SourceIndex(0) +2 >Emitted(11, 26) Source(19, 34) + SourceIndex(0) +3 >Emitted(11, 42) Source(23, 6) + SourceIndex(0) +4 >Emitted(11, 43) Source(23, 6) + SourceIndex(0) +--- +>>>})(Element = exports.Element || (exports.Element = {})); +1-> +2 >^ +3 > ^^ +4 > ^^^^^^^ +5 > ^^^ +6 > ^^^^^^^^^^^^^^^ +7 > ^^^^^ +8 > ^^^^^^^^^^^^^^^ +9 > ^^^^^^^^ +1-> + > +2 >} +3 > +4 > Element +5 > +6 > Element +7 > +8 > Element +9 > { + > export function isElement(el: any): el is JSX.Element { + > return el.markAsChildOfRootElement !== undefined; + > } + > + > export function createElement(args: any[]) { + > + > return { + > } + > } + > } +1->Emitted(12, 1) Source(24, 1) + SourceIndex(0) +2 >Emitted(12, 2) Source(24, 2) + SourceIndex(0) +3 >Emitted(12, 4) Source(14, 18) + SourceIndex(0) +4 >Emitted(12, 11) Source(14, 25) + SourceIndex(0) +5 >Emitted(12, 14) Source(14, 18) + SourceIndex(0) +6 >Emitted(12, 29) Source(14, 25) + SourceIndex(0) +7 >Emitted(12, 34) Source(14, 18) + SourceIndex(0) +8 >Emitted(12, 49) Source(14, 25) + SourceIndex(0) +9 >Emitted(12, 57) Source(24, 2) + SourceIndex(0) +--- +>>>exports.createElement = Element.createElement; +1 > +2 >^^^^^^^^ +3 > ^^^^^^^^^^^^^ +4 > ^^^ +5 > ^^^^^^^ +6 > ^ +7 > ^^^^^^^^^^^^^ +8 > ^ +1 > + > + >export let +2 > +3 > createElement +4 > = +5 > Element +6 > . +7 > createElement +8 > ; +1 >Emitted(13, 1) Source(26, 12) + SourceIndex(0) +2 >Emitted(13, 9) Source(26, 12) + SourceIndex(0) +3 >Emitted(13, 22) Source(26, 25) + SourceIndex(0) +4 >Emitted(13, 25) Source(26, 28) + SourceIndex(0) +5 >Emitted(13, 32) Source(26, 35) + SourceIndex(0) +6 >Emitted(13, 33) Source(26, 36) + SourceIndex(0) +7 >Emitted(13, 46) Source(26, 49) + SourceIndex(0) +8 >Emitted(13, 47) Source(26, 50) + SourceIndex(0) +--- +>>>function toCamelCase(text) { +1 > +2 >^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > + > +2 >function toCamelCase( +3 > text: string +1 >Emitted(14, 1) Source(28, 1) + SourceIndex(0) +2 >Emitted(14, 22) Source(28, 22) + SourceIndex(0) +3 >Emitted(14, 26) Source(28, 34) + SourceIndex(0) +--- +>>> return text[0].toLowerCase() + text.substring(1); +1->^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^ +5 > ^ +6 > ^ +7 > ^ +8 > ^ +9 > ^^^^^^^^^^^ +10> ^^ +11> ^^^ +12> ^^^^ +13> ^ +14> ^^^^^^^^^ +15> ^ +16> ^ +17> ^ +18> ^ +1->): string { + > +2 > return +3 > +4 > text +5 > [ +6 > 0 +7 > ] +8 > . +9 > toLowerCase +10> () +11> + +12> text +13> . +14> substring +15> ( +16> 1 +17> ) +18> ; +1->Emitted(15, 5) Source(29, 5) + SourceIndex(0) +2 >Emitted(15, 11) Source(29, 11) + SourceIndex(0) +3 >Emitted(15, 12) Source(29, 12) + SourceIndex(0) +4 >Emitted(15, 16) Source(29, 16) + SourceIndex(0) +5 >Emitted(15, 17) Source(29, 17) + SourceIndex(0) +6 >Emitted(15, 18) Source(29, 18) + SourceIndex(0) +7 >Emitted(15, 19) Source(29, 19) + SourceIndex(0) +8 >Emitted(15, 20) Source(29, 20) + SourceIndex(0) +9 >Emitted(15, 31) Source(29, 31) + SourceIndex(0) +10>Emitted(15, 33) Source(29, 33) + SourceIndex(0) +11>Emitted(15, 36) Source(29, 36) + SourceIndex(0) +12>Emitted(15, 40) Source(29, 40) + SourceIndex(0) +13>Emitted(15, 41) Source(29, 41) + SourceIndex(0) +14>Emitted(15, 50) Source(29, 50) + SourceIndex(0) +15>Emitted(15, 51) Source(29, 51) + SourceIndex(0) +16>Emitted(15, 52) Source(29, 52) + SourceIndex(0) +17>Emitted(15, 53) Source(29, 53) + SourceIndex(0) +18>Emitted(15, 54) Source(29, 54) + SourceIndex(0) +--- +>>>} +1 > +2 >^ +3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + > +2 >} +1 >Emitted(16, 1) Source(30, 1) + SourceIndex(0) +2 >Emitted(16, 2) Source(30, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=Element.js.map=================================================================== +JsFile: test.js +mapUrl: test.js.map +sourceRoot: +sources: test.tsx +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/test.js +sourceFile:test.tsx +------------------------------------------------------------------- +>>>"use strict"; +>>>const Element_1 = require("./Element"); +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1 > +2 >import { Element} from './Element'; +1 >Emitted(2, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(2, 40) Source(1, 36) + SourceIndex(0) +--- +>>>let c; +1 > +2 >^^^^ +3 > ^ +4 > ^ +5 > ^^^^-> +1 > + > + > +2 >let +3 > c: { + > a?: { + > b: string + > } + > } +4 > ; +1 >Emitted(3, 1) Source(3, 1) + SourceIndex(0) +2 >Emitted(3, 5) Source(3, 5) + SourceIndex(0) +3 >Emitted(3, 6) Source(7, 2) + SourceIndex(0) +4 >Emitted(3, 7) Source(7, 3) + SourceIndex(0) +--- +>>>class A { +1-> +2 >^^^^^^^^^^^^^-> +1-> + > + > +1->Emitted(4, 1) Source(9, 1) + SourceIndex(0) +--- +>>> view() { +1->^^^^ +2 > ^^^^ +3 > ^^^^^^^^^-> +1->class A { + > +2 > view +1->Emitted(5, 5) Source(10, 2) + SourceIndex(0) +2 >Emitted(5, 9) Source(10, 6) + SourceIndex(0) +--- +>>> return [ +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1->() { + > +2 > return +3 > +1->Emitted(6, 9) Source(11, 3) + SourceIndex(0) +2 >Emitted(6, 15) Source(11, 9) + SourceIndex(0) +3 >Emitted(6, 16) Source(11, 10) + SourceIndex(0) +--- +>>> Element_1.Element.createElement("meta", { content: "helloworld" }), +1->^^^^^^^^^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^ +5 > ^^^^^^^^^^^^ +6 > ^^^ +1->[ + > +2 > content +4 > = +5 > "helloworld" +6 > > +1->Emitted(7, 13) Source(12, 4) + SourceIndex(0) +2 >Emitted(7, 55) Source(12, 10) + SourceIndex(0) +3 >Emitted(7, 62) Source(12, 17) + SourceIndex(0) +4 >Emitted(7, 64) Source(12, 18) + SourceIndex(0) +5 >Emitted(7, 76) Source(12, 30) + SourceIndex(0) +6 >Emitted(7, 79) Source(12, 38) + SourceIndex(0) +--- +>>> Element_1.Element.createElement("meta", { content: c.a.b }) +1 >^^^^^^^^^^^^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +3 > ^^^^^^^ +4 > ^^ +5 > ^ +6 > ^ +7 > ^ +8 > ^ +9 > ^ +10> ^^^ +1 >, + > +2 > content +4 > ={ +5 > c +6 > . +7 > a! +8 > . +9 > b +10> }> +1 >Emitted(8, 13) Source(13, 4) + SourceIndex(0) +2 >Emitted(8, 55) Source(13, 10) + SourceIndex(0) +3 >Emitted(8, 62) Source(13, 17) + SourceIndex(0) +4 >Emitted(8, 64) Source(13, 19) + SourceIndex(0) +5 >Emitted(8, 65) Source(13, 20) + SourceIndex(0) +6 >Emitted(8, 66) Source(13, 21) + SourceIndex(0) +7 >Emitted(8, 67) Source(13, 23) + SourceIndex(0) +8 >Emitted(8, 68) Source(13, 24) + SourceIndex(0) +9 >Emitted(8, 69) Source(13, 25) + SourceIndex(0) +10>Emitted(8, 72) Source(13, 34) + SourceIndex(0) +--- +>>> ]; +1 >^^^^^^^^^ +2 > ^ +1 > + > ] +2 > ; +1 >Emitted(9, 10) Source(14, 4) + SourceIndex(0) +2 >Emitted(9, 11) Source(14, 5) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +1 > + > +2 > } +1 >Emitted(10, 5) Source(15, 2) + SourceIndex(0) +2 >Emitted(10, 6) Source(15, 3) + SourceIndex(0) +--- +>>>} +1 >^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >} +1 >Emitted(11, 2) Source(16, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedName.symbols b/tests/baselines/reference/jsxFactoryQualifiedName.symbols new file mode 100644 index 00000000000..16cd35d1ca3 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedName.symbols @@ -0,0 +1,119 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) + + interface Element { +>Element : Symbol(Element, Decl(Element.ts, 1, 23)) + + name: string; +>name : Symbol(Element.name, Decl(Element.ts, 2, 23)) + + isIntrinsic: boolean; +>isIntrinsic : Symbol(Element.isIntrinsic, Decl(Element.ts, 3, 21)) + + isCustomElement: boolean; +>isCustomElement : Symbol(Element.isCustomElement, Decl(Element.ts, 4, 29)) + + toString(renderId?: number): string; +>toString : Symbol(Element.toString, Decl(Element.ts, 5, 33)) +>renderId : Symbol(renderId, Decl(Element.ts, 6, 17)) + + bindDOM(renderId?: number): number; +>bindDOM : Symbol(Element.bindDOM, Decl(Element.ts, 6, 44)) +>renderId : Symbol(renderId, Decl(Element.ts, 7, 16)) + + resetComponent(): void; +>resetComponent : Symbol(Element.resetComponent, Decl(Element.ts, 7, 43)) + + instantiateComponents(renderId?: number): number; +>instantiateComponents : Symbol(Element.instantiateComponents, Decl(Element.ts, 8, 31)) +>renderId : Symbol(renderId, Decl(Element.ts, 9, 30)) + + props: any; +>props : Symbol(Element.props, Decl(Element.ts, 9, 57)) + } +} +export namespace Element { +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) + + export function isElement(el: any): el is JSX.Element { +>isElement : Symbol(isElement, Decl(Element.ts, 13, 26)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>JSX : Symbol(JSX, Decl(Element.ts, 0, 0)) +>Element : Symbol(JSX.Element, Decl(Element.ts, 1, 23)) + + return el.markAsChildOfRootElement !== undefined; +>el : Symbol(el, Decl(Element.ts, 14, 30)) +>undefined : Symbol(undefined) + } + + export function createElement(args: any[]) { +>createElement : Symbol(createElement, Decl(Element.ts, 16, 5)) +>args : Symbol(args, Decl(Element.ts, 18, 34)) + + return { + } + } +} + +export let createElement = Element.createElement; +>createElement : Symbol(createElement, Decl(Element.ts, 25, 10)) +>Element.createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) +>Element : Symbol(Element, Decl(Element.ts, 12, 1)) +>createElement : Symbol(Element.createElement, Decl(Element.ts, 16, 5)) + +function toCamelCase(text: string): string { +>toCamelCase : Symbol(toCamelCase, Decl(Element.ts, 25, 49)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>text.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +>text : Symbol(text, Decl(Element.ts, 27, 21)) +>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : Symbol(Element, Decl(test.tsx, 0, 8)) + +let c: { +>c : Symbol(c, Decl(test.tsx, 2, 3)) + + a?: { +>a : Symbol(a, Decl(test.tsx, 2, 8)) + + b: string +>b : Symbol(b, Decl(test.tsx, 3, 6)) + } +}; + +class A { +>A : Symbol(A, Decl(test.tsx, 6, 2)) + + view() { +>view : Symbol(A.view, Decl(test.tsx, 8, 9)) + + return [ + , +>meta : Symbol(unknown) +>content : Symbol(unknown) +>meta : Symbol(unknown) + + +>meta : Symbol(unknown) +>content : Symbol(unknown) +>c.a!.b : Symbol(b, Decl(test.tsx, 3, 6)) +>c.a : Symbol(a, Decl(test.tsx, 2, 8)) +>c : Symbol(c, Decl(test.tsx, 2, 3)) +>a : Symbol(a, Decl(test.tsx, 2, 8)) +>b : Symbol(b, Decl(test.tsx, 3, 6)) +>meta : Symbol(unknown) + + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryQualifiedName.types b/tests/baselines/reference/jsxFactoryQualifiedName.types new file mode 100644 index 00000000000..663ba4b5bfc --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedName.types @@ -0,0 +1,134 @@ +=== tests/cases/compiler/Element.ts === + +declare namespace JSX { +>JSX : any + + interface Element { +>Element : Element + + name: string; +>name : string + + isIntrinsic: boolean; +>isIntrinsic : boolean + + isCustomElement: boolean; +>isCustomElement : boolean + + toString(renderId?: number): string; +>toString : (renderId?: number) => string +>renderId : number + + bindDOM(renderId?: number): number; +>bindDOM : (renderId?: number) => number +>renderId : number + + resetComponent(): void; +>resetComponent : () => void + + instantiateComponents(renderId?: number): number; +>instantiateComponents : (renderId?: number) => number +>renderId : number + + props: any; +>props : any + } +} +export namespace Element { +>Element : typeof Element + + export function isElement(el: any): el is JSX.Element { +>isElement : (el: any) => el is JSX.Element +>el : any +>el : any +>JSX : any +>Element : JSX.Element + + return el.markAsChildOfRootElement !== undefined; +>el.markAsChildOfRootElement !== undefined : boolean +>el.markAsChildOfRootElement : any +>el : any +>markAsChildOfRootElement : any +>undefined : undefined + } + + export function createElement(args: any[]) { +>createElement : (args: any[]) => {} +>args : any[] + + return { +>{ } : {} + } + } +} + +export let createElement = Element.createElement; +>createElement : (args: any[]) => {} +>Element.createElement : (args: any[]) => {} +>Element : typeof Element +>createElement : (args: any[]) => {} + +function toCamelCase(text: string): string { +>toCamelCase : (text: string) => string +>text : string + + return text[0].toLowerCase() + text.substring(1); +>text[0].toLowerCase() + text.substring(1) : string +>text[0].toLowerCase() : string +>text[0].toLowerCase : () => string +>text[0] : string +>text : string +>0 : 0 +>toLowerCase : () => string +>text.substring(1) : string +>text.substring : (start: number, end?: number) => string +>text : string +>substring : (start: number, end?: number) => string +>1 : 1 +} + +=== tests/cases/compiler/test.tsx === +import { Element} from './Element'; +>Element : typeof Element + +let c: { +>c : { a?: { b: string; }; } + + a?: { +>a : { b: string; } + + b: string +>b : string + } +}; + +class A { +>A : A + + view() { +>view : () => any[] + + return [ +>[ , ] : any[] + + , +> : any +>meta : any +>content : any +>meta : any + + +> : any +>meta : any +>content : any +>c.a!.b : string +>c.a! : { b: string; } +>c.a : { b: string; } +>c : { a?: { b: string; }; } +>a : { b: string; } +>b : string +>meta : any + + ]; + } +} diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.errors.txt b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.errors.txt new file mode 100644 index 00000000000..97a05d840f0 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/test.tsx(10,17): error TS2304: Cannot find name 'MyElement'. + + +==== tests/cases/compiler/test.tsx (1 errors) ==== + + declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } + } + + export class AppComponent { + render(createElement) { + return
; + ~~~ +!!! error TS2304: Cannot find name 'MyElement'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js new file mode 100644 index 00000000000..6714b68a093 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js @@ -0,0 +1,23 @@ +//// [test.tsx] + +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render(createElement) { + return
; + } +} + +//// [test.js] +"use strict"; +class AppComponent { + render(createElement) { + return MyElement.createElement("div", null); + } +} +exports.AppComponent = AppComponent; +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js.map b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js.map new file mode 100644 index 00000000000..ac54c9638cd --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.js.map @@ -0,0 +1,2 @@ +//// [test.js.map] +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.tsx"],"names":[],"mappings":";AAOA;IACI,MAAM,CAAC,aAAa;QAChB,MAAM,CAAC,oCAAO,CAAC;IACnB,CAAC;CACJ;AAJD,oCAIC"} \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.sourcemap.txt b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.sourcemap.txt new file mode 100644 index 00000000000..2616efcf63b --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameResolutionError.sourcemap.txt @@ -0,0 +1,87 @@ +=================================================================== +JsFile: test.js +mapUrl: test.js.map +sourceRoot: +sources: test.tsx +=================================================================== +------------------------------------------------------------------- +emittedFile:tests/cases/compiler/test.js +sourceFile:test.tsx +------------------------------------------------------------------- +>>>"use strict"; +>>>class AppComponent { +1 > +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >declare module JSX { + > interface IntrinsicElements { + > [s: string]: any; + > } + >} + > + > +1 >Emitted(2, 1) Source(8, 1) + SourceIndex(0) +--- +>>> render(createElement) { +1->^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^ +5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1->export class AppComponent { + > +2 > render +3 > ( +4 > createElement +1->Emitted(3, 5) Source(9, 5) + SourceIndex(0) +2 >Emitted(3, 11) Source(9, 11) + SourceIndex(0) +3 >Emitted(3, 12) Source(9, 12) + SourceIndex(0) +4 >Emitted(3, 25) Source(9, 25) + SourceIndex(0) +--- +>>> return MyElement.createElement("div", null); +1->^^^^^^^^ +2 > ^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +5 > ^ +1->) { + > +2 > return +3 > +4 >
+5 > ; +1->Emitted(4, 9) Source(10, 9) + SourceIndex(0) +2 >Emitted(4, 15) Source(10, 15) + SourceIndex(0) +3 >Emitted(4, 16) Source(10, 16) + SourceIndex(0) +4 >Emitted(4, 52) Source(10, 23) + SourceIndex(0) +5 >Emitted(4, 53) Source(10, 24) + SourceIndex(0) +--- +>>> } +1 >^^^^ +2 > ^ +1 > + > +2 > } +1 >Emitted(5, 5) Source(11, 5) + SourceIndex(0) +2 >Emitted(5, 6) Source(11, 6) + SourceIndex(0) +--- +>>>} +1 >^ +2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > + >} +1 >Emitted(6, 2) Source(12, 2) + SourceIndex(0) +--- +>>>exports.AppComponent = AppComponent; +1-> +2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +1-> +2 >export class AppComponent { + > render(createElement) { + > return
; + > } + >} +1->Emitted(7, 1) Source(8, 1) + SourceIndex(0) +2 >Emitted(7, 37) Source(12, 2) + SourceIndex(0) +--- +>>>//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.js b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.js new file mode 100644 index 00000000000..ecf7d13d89d --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.js @@ -0,0 +1,27 @@ +//// [index.tsx] + +import "./jsx"; + +var skate: any; +const React = { createElement: skate.h }; + +class Component { + renderCallback() { + return
test
; + } +}; + +//// [index.js] +"use strict"; +require("./jsx"); +var skate; +var React = { createElement: skate.h }; +var Component = (function () { + function Component() { + } + Component.prototype.renderCallback = function () { + return skate.h("div", null, "test"); + }; + return Component; +}()); +; diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.symbols b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.symbols new file mode 100644 index 00000000000..35879c81ca6 --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/index.tsx === + +import "./jsx"; + +var skate: any; +>skate : Symbol(skate, Decl(index.tsx, 3, 3)) + +const React = { createElement: skate.h }; +>React : Symbol(React, Decl(index.tsx, 4, 5)) +>createElement : Symbol(createElement, Decl(index.tsx, 4, 15)) +>skate : Symbol(skate, Decl(index.tsx, 3, 3)) + +class Component { +>Component : Symbol(Component, Decl(index.tsx, 4, 41)) + + renderCallback() { +>renderCallback : Symbol(Component.renderCallback, Decl(index.tsx, 6, 17)) + + return
test
; +>div : Symbol(unknown) +>div : Symbol(unknown) + } +}; diff --git a/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.types b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.types new file mode 100644 index 00000000000..21fd4bae84b --- /dev/null +++ b/tests/baselines/reference/jsxFactoryQualifiedNameWithEs5.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/index.tsx === + +import "./jsx"; + +var skate: any; +>skate : any + +const React = { createElement: skate.h }; +>React : { createElement: any; } +>{ createElement: skate.h } : { createElement: any; } +>createElement : any +>skate.h : any +>skate : any +>h : any + +class Component { +>Component : Component + + renderCallback() { +>renderCallback : () => any + + return
test
; +>
test
: any +>div : any +>div : any + } +}; diff --git a/tests/baselines/reference/jsxViaImport.2.js b/tests/baselines/reference/jsxViaImport.2.js new file mode 100644 index 00000000000..19432238e0b --- /dev/null +++ b/tests/baselines/reference/jsxViaImport.2.js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/jsxViaImport.2.tsx] //// + +//// [component.d.ts] + +declare module JSX { + interface ElementAttributesProperty { props; } +} +declare module React { + class Component { } +} +declare module "BaseComponent" { + export default class extends React.Component { + } +} + +//// [consumer.tsx] +/// +import BaseComponent from 'BaseComponent'; +class TestComponent extends React.Component { + render() { + return ; + } +} + + +//// [consumer.jsx] +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/// +var BaseComponent_1 = require("BaseComponent"); +var TestComponent = (function (_super) { + __extends(TestComponent, _super); + function TestComponent() { + return _super.apply(this, arguments) || this; + } + TestComponent.prototype.render = function () { + return ; + }; + return TestComponent; +}(React.Component)); diff --git a/tests/baselines/reference/jsxViaImport.2.symbols b/tests/baselines/reference/jsxViaImport.2.symbols new file mode 100644 index 00000000000..5fb24088d2e --- /dev/null +++ b/tests/baselines/reference/jsxViaImport.2.symbols @@ -0,0 +1,44 @@ +=== tests/cases/compiler/consumer.tsx === +/// +import BaseComponent from 'BaseComponent'; +>BaseComponent : Symbol(BaseComponent, Decl(consumer.tsx, 1, 6)) + +class TestComponent extends React.Component { +>TestComponent : Symbol(TestComponent, Decl(consumer.tsx, 1, 42)) +>React.Component : Symbol(React.Component, Decl(component.d.ts, 4, 22)) +>React : Symbol(React, Decl(component.d.ts, 3, 1)) +>Component : Symbol(React.Component, Decl(component.d.ts, 4, 22)) + + render() { +>render : Symbol(TestComponent.render, Decl(consumer.tsx, 2, 54)) + + return ; +>BaseComponent : Symbol(BaseComponent, Decl(consumer.tsx, 1, 6)) + } +} + +=== tests/cases/compiler/component.d.ts === + +declare module JSX { +>JSX : Symbol(JSX, Decl(component.d.ts, 0, 0)) + + interface ElementAttributesProperty { props; } +>ElementAttributesProperty : Symbol(ElementAttributesProperty, Decl(component.d.ts, 1, 20)) +>props : Symbol(ElementAttributesProperty.props, Decl(component.d.ts, 2, 39)) +} +declare module React { +>React : Symbol(React, Decl(component.d.ts, 3, 1)) + + class Component { } +>Component : Symbol(Component, Decl(component.d.ts, 4, 22)) +>T : Symbol(T, Decl(component.d.ts, 5, 18)) +>U : Symbol(U, Decl(component.d.ts, 5, 20)) +} +declare module "BaseComponent" { + export default class extends React.Component { +>React.Component : Symbol(React.Component, Decl(component.d.ts, 4, 22)) +>React : Symbol(React, Decl(component.d.ts, 3, 1)) +>Component : Symbol(React.Component, Decl(component.d.ts, 4, 22)) + } +} + diff --git a/tests/baselines/reference/jsxViaImport.2.types b/tests/baselines/reference/jsxViaImport.2.types new file mode 100644 index 00000000000..c1e418c6b32 --- /dev/null +++ b/tests/baselines/reference/jsxViaImport.2.types @@ -0,0 +1,45 @@ +=== tests/cases/compiler/consumer.tsx === +/// +import BaseComponent from 'BaseComponent'; +>BaseComponent : typeof BaseComponent + +class TestComponent extends React.Component { +>TestComponent : TestComponent +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + + render() { +>render : () => any + + return ; +> : any +>BaseComponent : typeof BaseComponent + } +} + +=== tests/cases/compiler/component.d.ts === + +declare module JSX { +>JSX : any + + interface ElementAttributesProperty { props; } +>ElementAttributesProperty : ElementAttributesProperty +>props : any +} +declare module React { +>React : typeof React + + class Component { } +>Component : Component +>T : T +>U : U +} +declare module "BaseComponent" { + export default class extends React.Component { +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + } +} + diff --git a/tests/baselines/reference/keyofAndForIn.js b/tests/baselines/reference/keyofAndForIn.js new file mode 100644 index 00000000000..0debf28b75e --- /dev/null +++ b/tests/baselines/reference/keyofAndForIn.js @@ -0,0 +1,81 @@ +//// [keyofAndForIn.ts] + +// Repro from #12513 + +function f1(obj: { [P in K]: T }, k: K) { + const b = k in obj; + let k1: K; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} + +function f2(obj: { [P in keyof T]: T[P] }, k: keyof T) { + const b = k in obj; + let k1: keyof T; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} + +function f3(obj: { [P in K]: T[P] }, k: K) { + const b = k in obj; + let k1: K; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} + +//// [keyofAndForIn.js] +// Repro from #12513 +function f1(obj, k) { + var b = k in obj; + var k1; + for (k1 in obj) { + var x1 = obj[k1]; + } + for (var k2 in obj) { + var x2 = obj[k2]; + } +} +function f2(obj, k) { + var b = k in obj; + var k1; + for (k1 in obj) { + var x1 = obj[k1]; + } + for (var k2 in obj) { + var x2 = obj[k2]; + } +} +function f3(obj, k) { + var b = k in obj; + var k1; + for (k1 in obj) { + var x1 = obj[k1]; + } + for (var k2 in obj) { + var x2 = obj[k2]; + } +} + + +//// [keyofAndForIn.d.ts] +declare function f1(obj: { + [P in K]: T; +}, k: K): void; +declare function f2(obj: { + [P in keyof T]: T[P]; +}, k: keyof T): void; +declare function f3(obj: { + [P in K]: T[P]; +}, k: K): void; diff --git a/tests/baselines/reference/keyofAndForIn.symbols b/tests/baselines/reference/keyofAndForIn.symbols new file mode 100644 index 00000000000..36b5d3e2d72 --- /dev/null +++ b/tests/baselines/reference/keyofAndForIn.symbols @@ -0,0 +1,125 @@ +=== tests/cases/conformance/types/keyof/keyofAndForIn.ts === + +// Repro from #12513 + +function f1(obj: { [P in K]: T }, k: K) { +>f1 : Symbol(f1, Decl(keyofAndForIn.ts, 0, 0)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 3, 12)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 3, 29)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) +>P : Symbol(P, Decl(keyofAndForIn.ts, 3, 41)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 3, 12)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 3, 29)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 3, 54)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 3, 12)) + + const b = k in obj; +>b : Symbol(b, Decl(keyofAndForIn.ts, 4, 9)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 3, 54)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) + + let k1: K; +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 5, 7)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 3, 12)) + + for (k1 in obj) { +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 5, 7)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) + + let x1 = obj[k1]; +>x1 : Symbol(x1, Decl(keyofAndForIn.ts, 7, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 5, 7)) + } + for (let k2 in obj) { +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 9, 12)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) + + let x2 = obj[k2]; +>x2 : Symbol(x2, Decl(keyofAndForIn.ts, 10, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 3, 33)) +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 9, 12)) + } +} + +function f2(obj: { [P in keyof T]: T[P] }, k: keyof T) { +>f2 : Symbol(f2, Decl(keyofAndForIn.ts, 12, 1)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 14, 12)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) +>P : Symbol(P, Decl(keyofAndForIn.ts, 14, 23)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 14, 12)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 14, 12)) +>P : Symbol(P, Decl(keyofAndForIn.ts, 14, 23)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 14, 45)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 14, 12)) + + const b = k in obj; +>b : Symbol(b, Decl(keyofAndForIn.ts, 15, 9)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 14, 45)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) + + let k1: keyof T; +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 16, 7)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 14, 12)) + + for (k1 in obj) { +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 16, 7)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) + + let x1 = obj[k1]; +>x1 : Symbol(x1, Decl(keyofAndForIn.ts, 18, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 16, 7)) + } + for (let k2 in obj) { +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 20, 12)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) + + let x2 = obj[k2]; +>x2 : Symbol(x2, Decl(keyofAndForIn.ts, 21, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 14, 15)) +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 20, 12)) + } +} + +function f3(obj: { [P in K]: T[P] }, k: K) { +>f3 : Symbol(f3, Decl(keyofAndForIn.ts, 23, 1)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 25, 12)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 25, 14)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 25, 12)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) +>P : Symbol(P, Decl(keyofAndForIn.ts, 25, 42)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 25, 14)) +>T : Symbol(T, Decl(keyofAndForIn.ts, 25, 12)) +>P : Symbol(P, Decl(keyofAndForIn.ts, 25, 42)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 25, 58)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 25, 14)) + + const b = k in obj; +>b : Symbol(b, Decl(keyofAndForIn.ts, 26, 9)) +>k : Symbol(k, Decl(keyofAndForIn.ts, 25, 58)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) + + let k1: K; +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 27, 7)) +>K : Symbol(K, Decl(keyofAndForIn.ts, 25, 14)) + + for (k1 in obj) { +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 27, 7)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) + + let x1 = obj[k1]; +>x1 : Symbol(x1, Decl(keyofAndForIn.ts, 29, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) +>k1 : Symbol(k1, Decl(keyofAndForIn.ts, 27, 7)) + } + for (let k2 in obj) { +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 31, 12)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) + + let x2 = obj[k2]; +>x2 : Symbol(x2, Decl(keyofAndForIn.ts, 32, 11)) +>obj : Symbol(obj, Decl(keyofAndForIn.ts, 25, 34)) +>k2 : Symbol(k2, Decl(keyofAndForIn.ts, 31, 12)) + } +} diff --git a/tests/baselines/reference/keyofAndForIn.types b/tests/baselines/reference/keyofAndForIn.types new file mode 100644 index 00000000000..5e992e5d261 --- /dev/null +++ b/tests/baselines/reference/keyofAndForIn.types @@ -0,0 +1,134 @@ +=== tests/cases/conformance/types/keyof/keyofAndForIn.ts === + +// Repro from #12513 + +function f1(obj: { [P in K]: T }, k: K) { +>f1 : (obj: { [P in K]: T; }, k: K) => void +>K : K +>T : T +>obj : { [P in K]: T; } +>P : P +>K : K +>T : T +>k : K +>K : K + + const b = k in obj; +>b : boolean +>k in obj : boolean +>k : K +>obj : { [P in K]: T; } + + let k1: K; +>k1 : K +>K : K + + for (k1 in obj) { +>k1 : K +>obj : { [P in K]: T; } + + let x1 = obj[k1]; +>x1 : T +>obj[k1] : T +>obj : { [P in K]: T; } +>k1 : K + } + for (let k2 in obj) { +>k2 : K +>obj : { [P in K]: T; } + + let x2 = obj[k2]; +>x2 : T +>obj[k2] : T +>obj : { [P in K]: T; } +>k2 : K + } +} + +function f2(obj: { [P in keyof T]: T[P] }, k: keyof T) { +>f2 : (obj: { [P in keyof T]: T[P]; }, k: keyof T) => void +>T : T +>obj : { [P in keyof T]: T[P]; } +>P : P +>T : T +>T : T +>P : P +>k : keyof T +>T : T + + const b = k in obj; +>b : boolean +>k in obj : boolean +>k : keyof T +>obj : { [P in keyof T]: T[P]; } + + let k1: keyof T; +>k1 : keyof T +>T : T + + for (k1 in obj) { +>k1 : keyof T +>obj : { [P in keyof T]: T[P]; } + + let x1 = obj[k1]; +>x1 : T[keyof T] +>obj[k1] : T[keyof T] +>obj : { [P in keyof T]: T[P]; } +>k1 : keyof T + } + for (let k2 in obj) { +>k2 : keyof T +>obj : { [P in keyof T]: T[P]; } + + let x2 = obj[k2]; +>x2 : T[keyof T] +>obj[k2] : T[keyof T] +>obj : { [P in keyof T]: T[P]; } +>k2 : keyof T + } +} + +function f3(obj: { [P in K]: T[P] }, k: K) { +>f3 : (obj: { [P in K]: T[P]; }, k: K) => void +>T : T +>K : K +>T : T +>obj : { [P in K]: T[P]; } +>P : P +>K : K +>T : T +>P : P +>k : K +>K : K + + const b = k in obj; +>b : boolean +>k in obj : boolean +>k : K +>obj : { [P in K]: T[P]; } + + let k1: K; +>k1 : K +>K : K + + for (k1 in obj) { +>k1 : K +>obj : { [P in K]: T[P]; } + + let x1 = obj[k1]; +>x1 : T[K] +>obj[k1] : T[K] +>obj : { [P in K]: T[P]; } +>k1 : K + } + for (let k2 in obj) { +>k2 : K +>obj : { [P in K]: T[P]; } + + let x2 = obj[k2]; +>x2 : T[K] +>obj[k2] : T[K] +>obj : { [P in K]: T[P]; } +>k2 : K + } +} diff --git a/tests/baselines/reference/keyofAndIndexedAccess.js b/tests/baselines/reference/keyofAndIndexedAccess.js new file mode 100644 index 00000000000..4b93897fdc4 --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccess.js @@ -0,0 +1,922 @@ +//// [keyofAndIndexedAccess.ts] + +class Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +class TaggedShape extends Shape { + tag: string; +} + +class Item { + name: string; + price: number; +} + +class Options { + visible: "yes" | "no"; +} + +type Dictionary = { [x: string]: T }; +type NumericallyIndexed = { [x: number]: T }; + +const enum E { A, B, C } + +type K00 = keyof any; // string +type K01 = keyof string; // "toString" | "charAt" | ... +type K02 = keyof number; // "toString" | "toFixed" | "toExponential" | ... +type K03 = keyof boolean; // "valueOf" +type K04 = keyof void; // never +type K05 = keyof undefined; // never +type K06 = keyof null; // never +type K07 = keyof never; // never + +type K10 = keyof Shape; // "name" | "width" | "height" | "visible" +type K11 = keyof Shape[]; // "length" | "toString" | ... +type K12 = keyof Dictionary; // string +type K13 = keyof {}; // never +type K14 = keyof Object; // "constructor" | "toString" | ... +type K15 = keyof E; // "toString" | "toFixed" | "toExponential" | ... +type K16 = keyof [string, number]; // "0" | "1" | "length" | "toString" | ... +type K17 = keyof (Shape | Item); // "name" +type K18 = keyof (Shape & Item); // "name" | "width" | "height" | "visible" | "price" +type K19 = keyof NumericallyIndexed // never + +type KeyOf = keyof T; + +type K20 = KeyOf; // "name" | "width" | "height" | "visible" +type K21 = KeyOf>; // string + +type NAME = "name"; +type WIDTH_OR_HEIGHT = "width" | "height"; + +type Q10 = Shape["name"]; // string +type Q11 = Shape["width" | "height"]; // number +type Q12 = Shape["name" | "visible"]; // string | boolean + +type Q20 = Shape[NAME]; // string +type Q21 = Shape[WIDTH_OR_HEIGHT]; // number + +type Q30 = [string, number][0]; // string +type Q31 = [string, number][1]; // number +type Q32 = [string, number][2]; // string | number +type Q33 = [string, number][E.A]; // string +type Q34 = [string, number][E.B]; // number +type Q35 = [string, number][E.C]; // string | number +type Q36 = [string, number]["0"]; // string +type Q37 = [string, number]["1"]; // string + +type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" +type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" + +type Q50 = Dictionary["howdy"]; // Shape +type Q51 = Dictionary[123]; // Shape +type Q52 = Dictionary[E.B]; // Shape + +declare let cond: boolean; + +function getProperty(obj: T, key: K) { + return obj[key]; +} + +function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; +} + +function f10(shape: Shape) { + let name = getProperty(shape, "name"); // string + let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number + let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean + setProperty(shape, "name", "rectangle"); + setProperty(shape, cond ? "width" : "height", 10); + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe +} + +function f11(a: Shape[]) { + let len = getProperty(a, "length"); // number + setProperty(a, "length", len); +} + +function f12(t: [Shape, boolean]) { + let len = getProperty(t, "length"); + let s2 = getProperty(t, "0"); // Shape + let b2 = getProperty(t, "1"); // boolean +} + +function f13(foo: any, bar: any) { + let x = getProperty(foo, "x"); // any + let y = getProperty(foo, "100"); // any + let z = getProperty(foo, bar); // any +} + +class Component { + props: PropType; + getProperty(key: K) { + return this.props[key]; + } + setProperty(key: K, value: PropType[K]) { + this.props[key] = value; + } +} + +function f20(component: Component) { + let name = component.getProperty("name"); // string + let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number + let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean + component.setProperty("name", "rectangle"); + component.setProperty(cond ? "width" : "height", 10) + component.setProperty(cond ? "name" : "visible", true); // Technically not safe +} + +function pluck(array: T[], key: K) { + return array.map(x => x[key]); +} + +function f30(shapes: Shape[]) { + let names = pluck(shapes, "name"); // string[] + let widths = pluck(shapes, "width"); // number[] + let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] +} + +function f31(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} + +function f32(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} + +function f33(shape: S, key: K) { + let name = getProperty(shape, "name"); + let prop = getProperty(shape, key); + return prop; +} + +function f34(ts: TaggedShape) { + let tag1 = f33(ts, "tag"); + let tag2 = getProperty(ts, "tag"); +} + +class C { + public x: string; + protected y: string; + private z: string; +} + +// Indexed access expressions have always permitted access to private and protected members. +// For consistency we also permit such access in indexed access types. +function f40(c: C) { + type X = C["x"]; + type Y = C["y"]; + type Z = C["z"]; + let x: X = c["x"]; + let y: Y = c["y"]; + let z: Z = c["z"]; +} + +function f50(k: keyof T, s: string) { + const x1 = s as keyof T; + const x2 = k as string; +} + +function f51(k: K, s: string) { + const x1 = s as keyof T; + const x2 = k as string; +} + +function f52(obj: { [x: string]: boolean }, k: keyof T, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; +} + +function f53(obj: { [x: string]: boolean }, k: K, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; +} + +function f54(obj: T, key: keyof T) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; +} + +function f55(obj: T, key: K) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; +} + +function f60(source: T, target: T) { + for (let k in source) { + target[k] = source[k]; + } +} + +function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { + func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); +} + +function f71(func: (x: T, y: U) => Partial) { + let x = func({ a: 1, b: "hello" }, { c: true }); + x.a; // number | undefined + x.b; // string | undefined + x.c; // boolean | undefined +} + +function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} + +function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} + +function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { + let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +} + +function f80(obj: T) { + let a1 = obj.a; // { x: any } + let a2 = obj['a']; // { x: any } + let a3 = obj['a'] as T['a']; // T["a"] + let x1 = obj.a.x; // any + let x2 = obj['a']['x']; // any + let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] +} + +function f81(obj: T) { + return obj['a']['x'] as T['a']['x']; +} + +function f82() { + let x1 = f81({ a: { x: "hello" } }); // string + let x2 = f81({ a: { x: 42 } }); // number +} + +function f83(obj: T, key: K) { + return obj[key]['x'] as T[K]['x']; +} + +function f84() { + let x1 = f83({ foo: { x: "hello" } }, "foo"); // string + let x2 = f83({ bar: { x: 42 } }, "bar"); // number +} + +class C1 { + x: number; + get(key: K) { + return this[key]; + } + set(key: K, value: this[K]) { + this[key] = value; + } + foo() { + let x1 = this.x; // number + let x2 = this["x"]; // number + let x3 = this.get("x"); // this["x"] + let x4 = getProperty(this, "x"); // this["x"] + this.x = 42; + this["x"] = 42; + this.set("x", 42); + setProperty(this, "x", 42); + } +} + +// Repros from #12011 + +class Base { + get(prop: K) { + return this[prop]; + } + set(prop: K, value: this[K]) { + this[prop] = value; + } +} + +class Person extends Base { + parts: number; + constructor(parts: number) { + super(); + this.set("parts", parts); + } + getParts() { + return this.get("parts") + } +} + +class OtherPerson { + parts: number; + constructor(parts: number) { + setProperty(this, "parts", parts); + } + getParts() { + return getProperty(this, "parts") + } +} + +// Modified repro from #12544 + +function path(obj: T, key1: K1): T[K1]; +function path(obj: T, key1: K1, key2: K2): T[K1][K2]; +function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; +function path(obj: any, ...keys: (string | number)[]): any; +function path(obj: any, ...keys: (string | number)[]): any { + let result = obj; + for (let k of keys) { + result = result[k]; + } + return result; +} + +type Thing = { + a: { x: number, y: string }, + b: boolean +}; + + +function f1(thing: Thing) { + let x1 = path(thing, 'a'); // { x: number, y: string } + let x2 = path(thing, 'a', 'y'); // string + let x3 = path(thing, 'b'); // boolean + let x4 = path(thing, ...['a', 'x']); // any +} + +// Repro from comment in #12114 + +const assignTo2 = (object: T, key1: K1, key2: K2) => + (value: T[K1][K2]) => object[key1][key2] = value; + +// Modified repro from #12573 + +declare function one(handler: (t: T) => void): T +var empty = one(() => {}) // inferred as {}, expected + +type Handlers = { [K in keyof T]: (t: T[K]) => void } +declare function on(handlerHash: Handlers): T +var hashOfEmpty1 = on({ test: () => {} }); // {} +var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } + +// Repro from #12624 + +interface Options1 { + data?: Data + computed?: Computed; +} + +declare class Component1 { + constructor(options: Options1); + get(key: K): (Data & Computed)[K]; +} + +let c1 = new Component1({ + data: { + hello: "" + } +}); + +c1.get("hello"); + +// Repro from #12625 + +interface Options2 { + data?: Data + computed?: Computed; +} + +declare class Component2 { + constructor(options: Options2); + get(key: K): (Data & Computed)[K]; +} + +// Repro from #12641 + +interface R { + p: number; +} + +function f(p: K) { + let a: any; + a[p].add; // any +} + +// Repro from #12651 + +type MethodDescriptor = { + name: string; + args: any[]; + returnValue: any; +} + +declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; + +type SomeMethodDescriptor = { + name: "someMethod"; + args: [string, number]; + returnValue: string[]; +} + +let result = dispatchMethod("someMethod", ["hello", 35]); + +//// [keyofAndIndexedAccess.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Shape = (function () { + function Shape() { + } + return Shape; +}()); +var TaggedShape = (function (_super) { + __extends(TaggedShape, _super); + function TaggedShape() { + return _super.apply(this, arguments) || this; + } + return TaggedShape; +}(Shape)); +var Item = (function () { + function Item() { + } + return Item; +}()); +var Options = (function () { + function Options() { + } + return Options; +}()); +function getProperty(obj, key) { + return obj[key]; +} +function setProperty(obj, key, value) { + obj[key] = value; +} +function f10(shape) { + var name = getProperty(shape, "name"); // string + var widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number + var nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean + setProperty(shape, "name", "rectangle"); + setProperty(shape, cond ? "width" : "height", 10); + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe +} +function f11(a) { + var len = getProperty(a, "length"); // number + setProperty(a, "length", len); +} +function f12(t) { + var len = getProperty(t, "length"); + var s2 = getProperty(t, "0"); // Shape + var b2 = getProperty(t, "1"); // boolean +} +function f13(foo, bar) { + var x = getProperty(foo, "x"); // any + var y = getProperty(foo, "100"); // any + var z = getProperty(foo, bar); // any +} +var Component = (function () { + function Component() { + } + Component.prototype.getProperty = function (key) { + return this.props[key]; + }; + Component.prototype.setProperty = function (key, value) { + this.props[key] = value; + }; + return Component; +}()); +function f20(component) { + var name = component.getProperty("name"); // string + var widthOrHeight = component.getProperty(cond ? "width" : "height"); // number + var nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean + component.setProperty("name", "rectangle"); + component.setProperty(cond ? "width" : "height", 10); + component.setProperty(cond ? "name" : "visible", true); // Technically not safe +} +function pluck(array, key) { + return array.map(function (x) { return x[key]; }); +} +function f30(shapes) { + var names = pluck(shapes, "name"); // string[] + var widths = pluck(shapes, "width"); // number[] + var nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] +} +function f31(key) { + var shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} +function f32(key) { + var shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} +function f33(shape, key) { + var name = getProperty(shape, "name"); + var prop = getProperty(shape, key); + return prop; +} +function f34(ts) { + var tag1 = f33(ts, "tag"); + var tag2 = getProperty(ts, "tag"); +} +var C = (function () { + function C() { + } + return C; +}()); +// Indexed access expressions have always permitted access to private and protected members. +// For consistency we also permit such access in indexed access types. +function f40(c) { + var x = c["x"]; + var y = c["y"]; + var z = c["z"]; +} +function f50(k, s) { + var x1 = s; + var x2 = k; +} +function f51(k, s) { + var x1 = s; + var x2 = k; +} +function f52(obj, k, s, n) { + var x1 = obj[s]; + var x2 = obj[n]; + var x3 = obj[k]; +} +function f53(obj, k, s, n) { + var x1 = obj[s]; + var x2 = obj[n]; + var x3 = obj[k]; +} +function f54(obj, key) { + for (var s in obj[key]) { + } + var b = "foo" in obj[key]; +} +function f55(obj, key) { + for (var s in obj[key]) { + } + var b = "foo" in obj[key]; +} +function f60(source, target) { + for (var k in source) { + target[k] = source[k]; + } +} +function f70(func) { + func('a', 'a'); + func('a', 'b'); + func('a', 'c'); +} +function f71(func) { + var x = func({ a: 1, b: "hello" }, { c: true }); + x.a; // number | undefined + x.b; // string | undefined + x.c; // boolean | undefined +} +function f72(func) { + var a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + var b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + var c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} +function f73(func) { + var a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + var b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + var c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} +function f74(func) { + var a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number + var b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +} +function f80(obj) { + var a1 = obj.a; // { x: any } + var a2 = obj['a']; // { x: any } + var a3 = obj['a']; // T["a"] + var x1 = obj.a.x; // any + var x2 = obj['a']['x']; // any + var x3 = obj['a']['x']; // T["a"]["x"] +} +function f81(obj) { + return obj['a']['x']; +} +function f82() { + var x1 = f81({ a: { x: "hello" } }); // string + var x2 = f81({ a: { x: 42 } }); // number +} +function f83(obj, key) { + return obj[key]['x']; +} +function f84() { + var x1 = f83({ foo: { x: "hello" } }, "foo"); // string + var x2 = f83({ bar: { x: 42 } }, "bar"); // number +} +var C1 = (function () { + function C1() { + } + C1.prototype.get = function (key) { + return this[key]; + }; + C1.prototype.set = function (key, value) { + this[key] = value; + }; + C1.prototype.foo = function () { + var x1 = this.x; // number + var x2 = this["x"]; // number + var x3 = this.get("x"); // this["x"] + var x4 = getProperty(this, "x"); // this["x"] + this.x = 42; + this["x"] = 42; + this.set("x", 42); + setProperty(this, "x", 42); + }; + return C1; +}()); +// Repros from #12011 +var Base = (function () { + function Base() { + } + Base.prototype.get = function (prop) { + return this[prop]; + }; + Base.prototype.set = function (prop, value) { + this[prop] = value; + }; + return Base; +}()); +var Person = (function (_super) { + __extends(Person, _super); + function Person(parts) { + var _this = _super.call(this) || this; + _this.set("parts", parts); + return _this; + } + Person.prototype.getParts = function () { + return this.get("parts"); + }; + return Person; +}(Base)); +var OtherPerson = (function () { + function OtherPerson(parts) { + setProperty(this, "parts", parts); + } + OtherPerson.prototype.getParts = function () { + return getProperty(this, "parts"); + }; + return OtherPerson; +}()); +function path(obj) { + var keys = []; + for (var _i = 1; _i < arguments.length; _i++) { + keys[_i - 1] = arguments[_i]; + } + var result = obj; + for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { + var k = keys_1[_a]; + result = result[k]; + } + return result; +} +function f1(thing) { + var x1 = path(thing, 'a'); // { x: number, y: string } + var x2 = path(thing, 'a', 'y'); // string + var x3 = path(thing, 'b'); // boolean + var x4 = path.apply(void 0, [thing].concat(['a', 'x'])); // any +} +// Repro from comment in #12114 +var assignTo2 = function (object, key1, key2) { + return function (value) { return object[key1][key2] = value; }; +}; +var empty = one(function () { }); // inferred as {}, expected +var hashOfEmpty1 = on({ test: function () { } }); // {} +var hashOfEmpty2 = on({ test: function (x) { } }); // { test: boolean } +var c1 = new Component1({ + data: { + hello: "" + } +}); +c1.get("hello"); +function f(p) { + var a; + a[p].add; // any +} +var result = dispatchMethod("someMethod", ["hello", 35]); + + +//// [keyofAndIndexedAccess.d.ts] +declare class Shape { + name: string; + width: number; + height: number; + visible: boolean; +} +declare class TaggedShape extends Shape { + tag: string; +} +declare class Item { + name: string; + price: number; +} +declare class Options { + visible: "yes" | "no"; +} +declare type Dictionary = { + [x: string]: T; +}; +declare type NumericallyIndexed = { + [x: number]: T; +}; +declare const enum E { + A = 0, + B = 1, + C = 2, +} +declare type K00 = keyof any; +declare type K01 = keyof string; +declare type K02 = keyof number; +declare type K03 = keyof boolean; +declare type K04 = keyof void; +declare type K05 = keyof undefined; +declare type K06 = keyof null; +declare type K07 = keyof never; +declare type K10 = keyof Shape; +declare type K11 = keyof Shape[]; +declare type K12 = keyof Dictionary; +declare type K13 = keyof {}; +declare type K14 = keyof Object; +declare type K15 = keyof E; +declare type K16 = keyof [string, number]; +declare type K17 = keyof (Shape | Item); +declare type K18 = keyof (Shape & Item); +declare type K19 = keyof NumericallyIndexed; +declare type KeyOf = keyof T; +declare type K20 = KeyOf; +declare type K21 = KeyOf>; +declare type NAME = "name"; +declare type WIDTH_OR_HEIGHT = "width" | "height"; +declare type Q10 = Shape["name"]; +declare type Q11 = Shape["width" | "height"]; +declare type Q12 = Shape["name" | "visible"]; +declare type Q20 = Shape[NAME]; +declare type Q21 = Shape[WIDTH_OR_HEIGHT]; +declare type Q30 = [string, number][0]; +declare type Q31 = [string, number][1]; +declare type Q32 = [string, number][2]; +declare type Q33 = [string, number][E.A]; +declare type Q34 = [string, number][E.B]; +declare type Q35 = [string, number][E.C]; +declare type Q36 = [string, number]["0"]; +declare type Q37 = [string, number]["1"]; +declare type Q40 = (Shape | Options)["visible"]; +declare type Q41 = (Shape & Options)["visible"]; +declare type Q50 = Dictionary["howdy"]; +declare type Q51 = Dictionary[123]; +declare type Q52 = Dictionary[E.B]; +declare let cond: boolean; +declare function getProperty(obj: T, key: K): T[K]; +declare function setProperty(obj: T, key: K, value: T[K]): void; +declare function f10(shape: Shape): void; +declare function f11(a: Shape[]): void; +declare function f12(t: [Shape, boolean]): void; +declare function f13(foo: any, bar: any): void; +declare class Component { + props: PropType; + getProperty(key: K): PropType[K]; + setProperty(key: K, value: PropType[K]): void; +} +declare function f20(component: Component): void; +declare function pluck(array: T[], key: K): T[K][]; +declare function f30(shapes: Shape[]): void; +declare function f31(key: K): Shape[K]; +declare function f32(key: K): Shape[K]; +declare function f33(shape: S, key: K): S[K]; +declare function f34(ts: TaggedShape): void; +declare class C { + x: string; + protected y: string; + private z; +} +declare function f40(c: C): void; +declare function f50(k: keyof T, s: string): void; +declare function f51(k: K, s: string): void; +declare function f52(obj: { + [x: string]: boolean; +}, k: keyof T, s: string, n: number): void; +declare function f53(obj: { + [x: string]: boolean; +}, k: K, s: string, n: number): void; +declare function f54(obj: T, key: keyof T): void; +declare function f55(obj: T, key: K): void; +declare function f60(source: T, target: T): void; +declare function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void): void; +declare function f71(func: (x: T, y: U) => Partial): void; +declare function f72(func: (x: T, y: U, k: K) => (T & U)[K]): void; +declare function f73(func: (x: T, y: U, k: K) => (T & U)[K]): void; +declare function f74(func: (x: T, y: U, k: K) => (T | U)[K]): void; +declare function f80(obj: T): void; +declare function f81(obj: T): T["a"]["x"]; +declare function f82(): void; +declare function f83(obj: T, key: K): T[K]["x"]; +declare function f84(): void; +declare class C1 { + x: number; + get(key: K): this[K]; + set(key: K, value: this[K]): void; + foo(): void; +} +declare class Base { + get(prop: K): this[K]; + set(prop: K, value: this[K]): void; +} +declare class Person extends Base { + parts: number; + constructor(parts: number); + getParts(): this["parts"]; +} +declare class OtherPerson { + parts: number; + constructor(parts: number); + getParts(): this["parts"]; +} +declare function path(obj: T, key1: K1): T[K1]; +declare function path(obj: T, key1: K1, key2: K2): T[K1][K2]; +declare function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; +declare function path(obj: any, ...keys: (string | number)[]): any; +declare type Thing = { + a: { + x: number; + y: string; + }; + b: boolean; +}; +declare function f1(thing: Thing): void; +declare const assignTo2: (object: T, key1: K1, key2: K2) => (value: T[K1][K2]) => T[K1][K2]; +declare function one(handler: (t: T) => void): T; +declare var empty: {}; +declare type Handlers = { + [K in keyof T]: (t: T[K]) => void; +}; +declare function on(handlerHash: Handlers): T; +declare var hashOfEmpty1: {}; +declare var hashOfEmpty2: { + test: boolean; +}; +interface Options1 { + data?: Data; + computed?: Computed; +} +declare class Component1 { + constructor(options: Options1); + get(key: K): (Data & Computed)[K]; +} +declare let c1: Component1<{ + hello: string; +}, {}>; +interface Options2 { + data?: Data; + computed?: Computed; +} +declare class Component2 { + constructor(options: Options2); + get(key: K): (Data & Computed)[K]; +} +interface R { + p: number; +} +declare function f(p: K): void; +declare type MethodDescriptor = { + name: string; + args: any[]; + returnValue: any; +}; +declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; +declare type SomeMethodDescriptor = { + name: "someMethod"; + args: [string, number]; + returnValue: string[]; +}; +declare let result: string[]; diff --git a/tests/baselines/reference/keyofAndIndexedAccess.symbols b/tests/baselines/reference/keyofAndIndexedAccess.symbols new file mode 100644 index 00000000000..1c69d4959d8 --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccess.symbols @@ -0,0 +1,1578 @@ +=== tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts === + +class Shape { +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + name: string; +>name : Symbol(Shape.name, Decl(keyofAndIndexedAccess.ts, 1, 13)) + + width: number; +>width : Symbol(Shape.width, Decl(keyofAndIndexedAccess.ts, 2, 17)) + + height: number; +>height : Symbol(Shape.height, Decl(keyofAndIndexedAccess.ts, 3, 18)) + + visible: boolean; +>visible : Symbol(Shape.visible, Decl(keyofAndIndexedAccess.ts, 4, 19)) +} + +class TaggedShape extends Shape { +>TaggedShape : Symbol(TaggedShape, Decl(keyofAndIndexedAccess.ts, 6, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + tag: string; +>tag : Symbol(TaggedShape.tag, Decl(keyofAndIndexedAccess.ts, 8, 33)) +} + +class Item { +>Item : Symbol(Item, Decl(keyofAndIndexedAccess.ts, 10, 1)) + + name: string; +>name : Symbol(Item.name, Decl(keyofAndIndexedAccess.ts, 12, 12)) + + price: number; +>price : Symbol(Item.price, Decl(keyofAndIndexedAccess.ts, 13, 17)) +} + +class Options { +>Options : Symbol(Options, Decl(keyofAndIndexedAccess.ts, 15, 1)) + + visible: "yes" | "no"; +>visible : Symbol(Options.visible, Decl(keyofAndIndexedAccess.ts, 17, 15)) +} + +type Dictionary = { [x: string]: T }; +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 21, 16)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 21, 24)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 21, 16)) + +type NumericallyIndexed = { [x: number]: T }; +>NumericallyIndexed : Symbol(NumericallyIndexed, Decl(keyofAndIndexedAccess.ts, 21, 40)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 22, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 22, 32)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 22, 24)) + +const enum E { A, B, C } +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) +>A : Symbol(E.A, Decl(keyofAndIndexedAccess.ts, 24, 14)) +>B : Symbol(E.B, Decl(keyofAndIndexedAccess.ts, 24, 17)) +>C : Symbol(E.C, Decl(keyofAndIndexedAccess.ts, 24, 20)) + +type K00 = keyof any; // string +>K00 : Symbol(K00, Decl(keyofAndIndexedAccess.ts, 24, 24)) + +type K01 = keyof string; // "toString" | "charAt" | ... +>K01 : Symbol(K01, Decl(keyofAndIndexedAccess.ts, 26, 21)) + +type K02 = keyof number; // "toString" | "toFixed" | "toExponential" | ... +>K02 : Symbol(K02, Decl(keyofAndIndexedAccess.ts, 27, 24)) + +type K03 = keyof boolean; // "valueOf" +>K03 : Symbol(K03, Decl(keyofAndIndexedAccess.ts, 28, 24)) + +type K04 = keyof void; // never +>K04 : Symbol(K04, Decl(keyofAndIndexedAccess.ts, 29, 25)) + +type K05 = keyof undefined; // never +>K05 : Symbol(K05, Decl(keyofAndIndexedAccess.ts, 30, 22)) + +type K06 = keyof null; // never +>K06 : Symbol(K06, Decl(keyofAndIndexedAccess.ts, 31, 27)) + +type K07 = keyof never; // never +>K07 : Symbol(K07, Decl(keyofAndIndexedAccess.ts, 32, 22)) + +type K10 = keyof Shape; // "name" | "width" | "height" | "visible" +>K10 : Symbol(K10, Decl(keyofAndIndexedAccess.ts, 33, 23)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type K11 = keyof Shape[]; // "length" | "toString" | ... +>K11 : Symbol(K11, Decl(keyofAndIndexedAccess.ts, 35, 23)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type K12 = keyof Dictionary; // string +>K12 : Symbol(K12, Decl(keyofAndIndexedAccess.ts, 36, 25)) +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type K13 = keyof {}; // never +>K13 : Symbol(K13, Decl(keyofAndIndexedAccess.ts, 37, 35)) + +type K14 = keyof Object; // "constructor" | "toString" | ... +>K14 : Symbol(K14, Decl(keyofAndIndexedAccess.ts, 38, 20)) +>Object : Symbol(Object, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + +type K15 = keyof E; // "toString" | "toFixed" | "toExponential" | ... +>K15 : Symbol(K15, Decl(keyofAndIndexedAccess.ts, 39, 24)) +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) + +type K16 = keyof [string, number]; // "0" | "1" | "length" | "toString" | ... +>K16 : Symbol(K16, Decl(keyofAndIndexedAccess.ts, 40, 19)) + +type K17 = keyof (Shape | Item); // "name" +>K17 : Symbol(K17, Decl(keyofAndIndexedAccess.ts, 41, 34)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>Item : Symbol(Item, Decl(keyofAndIndexedAccess.ts, 10, 1)) + +type K18 = keyof (Shape & Item); // "name" | "width" | "height" | "visible" | "price" +>K18 : Symbol(K18, Decl(keyofAndIndexedAccess.ts, 42, 32)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>Item : Symbol(Item, Decl(keyofAndIndexedAccess.ts, 10, 1)) + +type K19 = keyof NumericallyIndexed // never +>K19 : Symbol(K19, Decl(keyofAndIndexedAccess.ts, 43, 32)) +>NumericallyIndexed : Symbol(NumericallyIndexed, Decl(keyofAndIndexedAccess.ts, 21, 40)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type KeyOf = keyof T; +>KeyOf : Symbol(KeyOf, Decl(keyofAndIndexedAccess.ts, 44, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 46, 11)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 46, 11)) + +type K20 = KeyOf; // "name" | "width" | "height" | "visible" +>K20 : Symbol(K20, Decl(keyofAndIndexedAccess.ts, 46, 24)) +>KeyOf : Symbol(KeyOf, Decl(keyofAndIndexedAccess.ts, 44, 42)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type K21 = KeyOf>; // string +>K21 : Symbol(K21, Decl(keyofAndIndexedAccess.ts, 48, 24)) +>KeyOf : Symbol(KeyOf, Decl(keyofAndIndexedAccess.ts, 44, 42)) +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type NAME = "name"; +>NAME : Symbol(NAME, Decl(keyofAndIndexedAccess.ts, 49, 36)) + +type WIDTH_OR_HEIGHT = "width" | "height"; +>WIDTH_OR_HEIGHT : Symbol(WIDTH_OR_HEIGHT, Decl(keyofAndIndexedAccess.ts, 51, 19)) + +type Q10 = Shape["name"]; // string +>Q10 : Symbol(Q10, Decl(keyofAndIndexedAccess.ts, 52, 42)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type Q11 = Shape["width" | "height"]; // number +>Q11 : Symbol(Q11, Decl(keyofAndIndexedAccess.ts, 54, 25)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type Q12 = Shape["name" | "visible"]; // string | boolean +>Q12 : Symbol(Q12, Decl(keyofAndIndexedAccess.ts, 55, 37)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type Q20 = Shape[NAME]; // string +>Q20 : Symbol(Q20, Decl(keyofAndIndexedAccess.ts, 56, 37)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>NAME : Symbol(NAME, Decl(keyofAndIndexedAccess.ts, 49, 36)) + +type Q21 = Shape[WIDTH_OR_HEIGHT]; // number +>Q21 : Symbol(Q21, Decl(keyofAndIndexedAccess.ts, 58, 23)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>WIDTH_OR_HEIGHT : Symbol(WIDTH_OR_HEIGHT, Decl(keyofAndIndexedAccess.ts, 51, 19)) + +type Q30 = [string, number][0]; // string +>Q30 : Symbol(Q30, Decl(keyofAndIndexedAccess.ts, 59, 34)) + +type Q31 = [string, number][1]; // number +>Q31 : Symbol(Q31, Decl(keyofAndIndexedAccess.ts, 61, 31)) + +type Q32 = [string, number][2]; // string | number +>Q32 : Symbol(Q32, Decl(keyofAndIndexedAccess.ts, 62, 31)) + +type Q33 = [string, number][E.A]; // string +>Q33 : Symbol(Q33, Decl(keyofAndIndexedAccess.ts, 63, 31)) +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) +>A : Symbol(E.A, Decl(keyofAndIndexedAccess.ts, 24, 14)) + +type Q34 = [string, number][E.B]; // number +>Q34 : Symbol(Q34, Decl(keyofAndIndexedAccess.ts, 64, 33)) +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) +>B : Symbol(E.B, Decl(keyofAndIndexedAccess.ts, 24, 17)) + +type Q35 = [string, number][E.C]; // string | number +>Q35 : Symbol(Q35, Decl(keyofAndIndexedAccess.ts, 65, 33)) +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) +>C : Symbol(E.C, Decl(keyofAndIndexedAccess.ts, 24, 20)) + +type Q36 = [string, number]["0"]; // string +>Q36 : Symbol(Q36, Decl(keyofAndIndexedAccess.ts, 66, 33)) + +type Q37 = [string, number]["1"]; // string +>Q37 : Symbol(Q37, Decl(keyofAndIndexedAccess.ts, 67, 33)) + +type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" +>Q40 : Symbol(Q40, Decl(keyofAndIndexedAccess.ts, 68, 33)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>Options : Symbol(Options, Decl(keyofAndIndexedAccess.ts, 15, 1)) + +type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" +>Q41 : Symbol(Q41, Decl(keyofAndIndexedAccess.ts, 70, 40)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>Options : Symbol(Options, Decl(keyofAndIndexedAccess.ts, 15, 1)) + +type Q50 = Dictionary["howdy"]; // Shape +>Q50 : Symbol(Q50, Decl(keyofAndIndexedAccess.ts, 71, 40)) +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type Q51 = Dictionary[123]; // Shape +>Q51 : Symbol(Q51, Decl(keyofAndIndexedAccess.ts, 73, 38)) +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + +type Q52 = Dictionary[E.B]; // Shape +>Q52 : Symbol(Q52, Decl(keyofAndIndexedAccess.ts, 74, 34)) +>Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 22, 48)) +>B : Symbol(E.B, Decl(keyofAndIndexedAccess.ts, 24, 17)) + +declare let cond: boolean; +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + +function getProperty(obj: T, key: K) { +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 79, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 79, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 79, 21)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 79, 43)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 79, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 79, 50)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 79, 23)) + + return obj[key]; +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 79, 43)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 79, 50)) +} + +function setProperty(obj: T, key: K, value: T[K]) { +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 83, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 83, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 83, 21)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 83, 43)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 83, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 83, 50)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 83, 23)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 83, 58)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 83, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 83, 23)) + + obj[key] = value; +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 83, 43)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 83, 50)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 83, 58)) +} + +function f10(shape: Shape) { +>f10 : Symbol(f10, Decl(keyofAndIndexedAccess.ts, 85, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + let name = getProperty(shape, "name"); // string +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 88, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) + + let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number +>widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 89, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean +>nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 90, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + setProperty(shape, "name", "rectangle"); +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) + + setProperty(shape, cond ? "width" : "height", 10); +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 87, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) +} + +function f11(a: Shape[]) { +>f11 : Symbol(f11, Decl(keyofAndIndexedAccess.ts, 94, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 96, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + let len = getProperty(a, "length"); // number +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 97, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 96, 13)) + + setProperty(a, "length", len); +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 96, 13)) +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 97, 7)) +} + +function f12(t: [Shape, boolean]) { +>f12 : Symbol(f12, Decl(keyofAndIndexedAccess.ts, 99, 1)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 101, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + let len = getProperty(t, "length"); +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 102, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 101, 13)) + + let s2 = getProperty(t, "0"); // Shape +>s2 : Symbol(s2, Decl(keyofAndIndexedAccess.ts, 103, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 101, 13)) + + let b2 = getProperty(t, "1"); // boolean +>b2 : Symbol(b2, Decl(keyofAndIndexedAccess.ts, 104, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 101, 13)) +} + +function f13(foo: any, bar: any) { +>f13 : Symbol(f13, Decl(keyofAndIndexedAccess.ts, 105, 1)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 107, 13)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 107, 22)) + + let x = getProperty(foo, "x"); // any +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 108, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 107, 13)) + + let y = getProperty(foo, "100"); // any +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 109, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 107, 13)) + + let z = getProperty(foo, bar); // any +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 110, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 107, 13)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 107, 22)) +} + +class Component { +>Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 111, 1)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 113, 16)) + + props: PropType; +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 113, 27)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 113, 16)) + + getProperty(key: K) { +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 115, 16)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 113, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 115, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 115, 16)) + + return this.props[key]; +>this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 113, 27)) +>this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 111, 1)) +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 113, 27)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 115, 42)) + } + setProperty(key: K, value: PropType[K]) { +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 118, 16)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 113, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 118, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 118, 16)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 118, 49)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 113, 16)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 118, 16)) + + this.props[key] = value; +>this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 113, 27)) +>this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 111, 1)) +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 113, 27)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 118, 42)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 118, 49)) + } +} + +function f20(component: Component) { +>f20 : Symbol(f20, Decl(keyofAndIndexedAccess.ts, 121, 1)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 111, 1)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + let name = component.getProperty("name"); // string +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 124, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) + + let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number +>widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 125, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean +>nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 126, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 114, 20)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + component.setProperty("name", "rectangle"); +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) + + component.setProperty(cond ? "width" : "height", 10) +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) + + component.setProperty(cond ? "name" : "visible", true); // Technically not safe +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 123, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 117, 5)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) +} + +function pluck(array: T[], key: K) { +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 130, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 132, 15)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 132, 17)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 132, 15)) +>array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 132, 37)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 132, 15)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 132, 48)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 132, 17)) + + return array.map(x => x[key]); +>array.map : Symbol(Array.map, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 132, 37)) +>map : Symbol(Array.map, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 133, 21)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 133, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 132, 48)) +} + +function f30(shapes: Shape[]) { +>f30 : Symbol(f30, Decl(keyofAndIndexedAccess.ts, 134, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 136, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) + + let names = pluck(shapes, "name"); // string[] +>names : Symbol(names, Decl(keyofAndIndexedAccess.ts, 137, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 130, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 136, 13)) + + let widths = pluck(shapes, "width"); // number[] +>widths : Symbol(widths, Decl(keyofAndIndexedAccess.ts, 138, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 130, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 136, 13)) + + let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] +>nameOrVisibles : Symbol(nameOrVisibles, Decl(keyofAndIndexedAccess.ts, 139, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 130, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 136, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 77, 11)) +} + +function f31(key: K) { +>f31 : Symbol(f31, Decl(keyofAndIndexedAccess.ts, 140, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 142, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 142, 36)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 142, 13)) + + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 143, 9)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 143, 26)) +>width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 143, 39)) +>height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 143, 49)) +>visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 143, 61)) + + return shape[key]; // Shape[K] +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 143, 9)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 142, 36)) +} + +function f32(key: K) { +>f32 : Symbol(f32, Decl(keyofAndIndexedAccess.ts, 145, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 147, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 147, 43)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 147, 13)) + + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 148, 9)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 148, 26)) +>width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 148, 39)) +>height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 148, 49)) +>visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 148, 61)) + + return shape[key]; // Shape[K] +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 148, 9)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 147, 43)) +} + +function f33(shape: S, key: K) { +>f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 150, 1)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 152, 13)) +>Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 152, 29)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 152, 13)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 152, 49)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 152, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 152, 58)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 152, 29)) + + let name = getProperty(shape, "name"); +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 153, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 152, 49)) + + let prop = getProperty(shape, key); +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 154, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 152, 49)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 152, 58)) + + return prop; +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 154, 7)) +} + +function f34(ts: TaggedShape) { +>f34 : Symbol(f34, Decl(keyofAndIndexedAccess.ts, 156, 1)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 158, 13)) +>TaggedShape : Symbol(TaggedShape, Decl(keyofAndIndexedAccess.ts, 6, 1)) + + let tag1 = f33(ts, "tag"); +>tag1 : Symbol(tag1, Decl(keyofAndIndexedAccess.ts, 159, 7)) +>f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 150, 1)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 158, 13)) + + let tag2 = getProperty(ts, "tag"); +>tag2 : Symbol(tag2, Decl(keyofAndIndexedAccess.ts, 160, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 158, 13)) +} + +class C { +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 161, 1)) + + public x: string; +>x : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 163, 9)) + + protected y: string; +>y : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 164, 21)) + + private z: string; +>z : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 165, 24)) +} + +// Indexed access expressions have always permitted access to private and protected members. +// For consistency we also permit such access in indexed access types. +function f40(c: C) { +>f40 : Symbol(f40, Decl(keyofAndIndexedAccess.ts, 167, 1)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 171, 13)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 161, 1)) + + type X = C["x"]; +>X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 171, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 161, 1)) + + type Y = C["y"]; +>Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 172, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 161, 1)) + + type Z = C["z"]; +>Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 173, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 161, 1)) + + let x: X = c["x"]; +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 175, 7)) +>X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 171, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 171, 13)) +>"x" : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 163, 9)) + + let y: Y = c["y"]; +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 176, 7)) +>Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 172, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 171, 13)) +>"y" : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 164, 21)) + + let z: Z = c["z"]; +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 177, 7)) +>Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 173, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 171, 13)) +>"z" : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 165, 24)) +} + +function f50(k: keyof T, s: string) { +>f50 : Symbol(f50, Decl(keyofAndIndexedAccess.ts, 178, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 180, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 180, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 180, 13)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 180, 27)) + + const x1 = s as keyof T; +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 181, 9)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 180, 27)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 180, 13)) + + const x2 = k as string; +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 182, 9)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 180, 16)) +} + +function f51(k: K, s: string) { +>f51 : Symbol(f51, Decl(keyofAndIndexedAccess.ts, 183, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 185, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 185, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 185, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 185, 35)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 185, 15)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 185, 40)) + + const x1 = s as keyof T; +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 186, 9)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 185, 40)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 185, 13)) + + const x2 = k as string; +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 187, 9)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 185, 35)) +} + +function f52(obj: { [x: string]: boolean }, k: keyof T, s: string, n: number) { +>f52 : Symbol(f52, Decl(keyofAndIndexedAccess.ts, 188, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 190, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 190, 16)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 190, 24)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 190, 46)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 190, 13)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 190, 58)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 190, 69)) + + const x1 = obj[s]; +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 191, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 190, 16)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 190, 58)) + + const x2 = obj[n]; +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 192, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 190, 16)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 190, 69)) + + const x3 = obj[k]; +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 193, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 190, 16)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 190, 46)) +} + +function f53(obj: { [x: string]: boolean }, k: K, s: string, n: number) { +>f53 : Symbol(f53, Decl(keyofAndIndexedAccess.ts, 194, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 196, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 196, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 196, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 196, 35)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 196, 43)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 196, 65)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 196, 15)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 196, 71)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 196, 82)) + + const x1 = obj[s]; +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 197, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 196, 35)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 196, 71)) + + const x2 = obj[n]; +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 198, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 196, 35)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 196, 82)) + + const x3 = obj[k]; +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 199, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 196, 35)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 196, 65)) +} + +function f54(obj: T, key: keyof T) { +>f54 : Symbol(f54, Decl(keyofAndIndexedAccess.ts, 200, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 202, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 202, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 202, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 202, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 202, 13)) + + for (let s in obj[key]) { +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 203, 12)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 202, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 202, 23)) + } + const b = "foo" in obj[key]; +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 205, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 202, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 202, 23)) +} + +function f55(obj: T, key: K) { +>f55 : Symbol(f55, Decl(keyofAndIndexedAccess.ts, 206, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 208, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 208, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 208, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 208, 35)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 208, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 208, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 208, 15)) + + for (let s in obj[key]) { +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 209, 12)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 208, 35)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 208, 42)) + } + const b = "foo" in obj[key]; +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 211, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 208, 35)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 208, 42)) +} + +function f60(source: T, target: T) { +>f60 : Symbol(f60, Decl(keyofAndIndexedAccess.ts, 212, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 214, 13)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 214, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 214, 13)) +>target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 214, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 214, 13)) + + for (let k in source) { +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 215, 12)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 214, 16)) + + target[k] = source[k]; +>target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 214, 26)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 215, 12)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 214, 16)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 215, 12)) + } +} + +function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { +>f70 : Symbol(f70, Decl(keyofAndIndexedAccess.ts, 218, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 220, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 220, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 220, 22)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 220, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 220, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 220, 22)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 220, 44)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 220, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 220, 22)) + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 220, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 221, 10)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 221, 18)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 221, 30)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 221, 38)) + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 220, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 222, 10)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 222, 18)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 222, 30)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 222, 38)) + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 220, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 223, 10)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 223, 18)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 223, 30)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 223, 38)) +} + +function f71(func: (x: T, y: U) => Partial) { +>f71 : Symbol(f71, Decl(keyofAndIndexedAccess.ts, 224, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 226, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 226, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 226, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 226, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 226, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 226, 31)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 226, 22)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 226, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 226, 22)) + + let x = func({ a: 1, b: "hello" }, { c: true }); +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 227, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 226, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 227, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 227, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 227, 40)) + + x.a; // number | undefined +>x.a : Symbol(a) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 227, 7)) +>a : Symbol(a) + + x.b; // string | undefined +>x.b : Symbol(b) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 227, 7)) +>b : Symbol(b) + + x.c; // boolean | undefined +>x.c : Symbol(c) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 227, 7)) +>c : Symbol(c) +} + +function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { +>f72 : Symbol(f72, Decl(keyofAndIndexedAccess.ts, 231, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 233, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 233, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 233, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 233, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 233, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 233, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 233, 55)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 233, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 233, 60)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 233, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 233, 66)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 233, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 233, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 233, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 233, 25)) + + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 234, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 233, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 234, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 234, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 234, 40)) + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 235, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 233, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 235, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 235, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 235, 40)) + + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 236, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 233, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 236, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 236, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 236, 40)) +} + +function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { +>f73 : Symbol(f73, Decl(keyofAndIndexedAccess.ts, 237, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 239, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 239, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 239, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 239, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 239, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 239, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 239, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 239, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 239, 56)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 239, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 239, 62)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 239, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 239, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 239, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 239, 25)) + + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 240, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 239, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 240, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 240, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 240, 40)) + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 241, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 239, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 241, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 241, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 241, 40)) + + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 242, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 239, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 242, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 242, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 242, 40)) +} + +function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { +>f74 : Symbol(f74, Decl(keyofAndIndexedAccess.ts, 243, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 245, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 245, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 245, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 245, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 245, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 245, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 245, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 245, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 245, 56)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 245, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 245, 62)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 245, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 245, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 245, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 245, 25)) + + let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 246, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 245, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 246, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 246, 24)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 246, 40)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 246, 46)) + + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 247, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 245, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 247, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 247, 24)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 247, 40)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 247, 46)) +} + +function f80(obj: T) { +>f80 : Symbol(f80, Decl(keyofAndIndexedAccess.ts, 248, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 250, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 250, 29)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 250, 13)) + + let a1 = obj.a; // { x: any } +>a1 : Symbol(a1, Decl(keyofAndIndexedAccess.ts, 251, 7)) +>obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) + + let a2 = obj['a']; // { x: any } +>a2 : Symbol(a2, Decl(keyofAndIndexedAccess.ts, 252, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) + + let a3 = obj['a'] as T['a']; // T["a"] +>a3 : Symbol(a3, Decl(keyofAndIndexedAccess.ts, 253, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 250, 13)) + + let x1 = obj.a.x; // any +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 254, 7)) +>obj.a.x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 250, 29)) +>obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 250, 29)) + + let x2 = obj['a']['x']; // any +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 255, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 250, 29)) + + let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 256, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 250, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 250, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 250, 29)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 250, 13)) +} + +function f81(obj: T) { +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 257, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 259, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 259, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 259, 29)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 259, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 259, 13)) + + return obj['a']['x'] as T['a']['x']; +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 259, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 259, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 259, 29)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 259, 13)) +} + +function f82() { +>f82 : Symbol(f82, Decl(keyofAndIndexedAccess.ts, 261, 1)) + + let x1 = f81({ a: { x: "hello" } }); // string +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 264, 7)) +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 257, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 264, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 264, 23)) + + let x2 = f81({ a: { x: 42 } }); // number +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 265, 7)) +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 257, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 265, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 265, 23)) +} + +function f83(obj: T, key: K) { +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 266, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 268, 13)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 268, 26)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 268, 39)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 268, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 268, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 268, 71)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 268, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 268, 78)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 268, 51)) + + return obj[key]['x'] as T[K]['x']; +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 268, 71)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 268, 78)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 268, 39)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 268, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 268, 51)) +} + +function f84() { +>f84 : Symbol(f84, Decl(keyofAndIndexedAccess.ts, 270, 1)) + + let x1 = f83({ foo: { x: "hello" } }, "foo"); // string +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 273, 7)) +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 266, 1)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 273, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 273, 25)) + + let x2 = f83({ bar: { x: 42 } }, "bar"); // number +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 274, 7)) +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 266, 1)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 274, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 274, 25)) +} + +class C1 { +>C1 : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) + + x: number; +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) + + get(key: K) { +>get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 278, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 279, 8)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 279, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 279, 8)) + + return this[key]; +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 279, 30)) + } + set(key: K, value: this[K]) { +>set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 281, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 282, 8)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 282, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 282, 8)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 282, 37)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 282, 8)) + + this[key] = value; +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 282, 30)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 282, 37)) + } + foo() { +>foo : Symbol(C1.foo, Decl(keyofAndIndexedAccess.ts, 284, 5)) + + let x1 = this.x; // number +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 286, 11)) +>this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) + + let x2 = this["x"]; // number +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 287, 11)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) + + let x3 = this.get("x"); // this["x"] +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 288, 11)) +>this.get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 278, 14)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 278, 14)) + + let x4 = getProperty(this, "x"); // this["x"] +>x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 289, 11)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) + + this.x = 42; +>this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) + + this["x"] = 42; +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 277, 10)) + + this.set("x", 42); +>this.set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 281, 5)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) +>set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 281, 5)) + + setProperty(this, "x", 42); +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 275, 1)) + } +} + +// Repros from #12011 + +class Base { +>Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 295, 1)) + + get(prop: K) { +>get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 299, 12)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 300, 8)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 300, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 300, 8)) + + return this[prop]; +>this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 295, 1)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 300, 30)) + } + set(prop: K, value: this[K]) { +>set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 302, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 303, 8)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 303, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 303, 8)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 303, 38)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 303, 8)) + + this[prop] = value; +>this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 295, 1)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 303, 30)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 303, 38)) + } +} + +class Person extends Base { +>Person : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 306, 1)) +>Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 295, 1)) + + parts: number; +>parts : Symbol(Person.parts, Decl(keyofAndIndexedAccess.ts, 308, 27)) + + constructor(parts: number) { +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 310, 16)) + + super(); +>super : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 295, 1)) + + this.set("parts", parts); +>this.set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 302, 5)) +>this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 306, 1)) +>set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 302, 5)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 310, 16)) + } + getParts() { +>getParts : Symbol(Person.getParts, Decl(keyofAndIndexedAccess.ts, 313, 5)) + + return this.get("parts") +>this.get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 299, 12)) +>this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 306, 1)) +>get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 299, 12)) + } +} + +class OtherPerson { +>OtherPerson : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 317, 1)) + + parts: number; +>parts : Symbol(OtherPerson.parts, Decl(keyofAndIndexedAccess.ts, 319, 19)) + + constructor(parts: number) { +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 321, 16)) + + setProperty(this, "parts", parts); +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 81, 1)) +>this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 317, 1)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 321, 16)) + } + getParts() { +>getParts : Symbol(OtherPerson.getParts, Decl(keyofAndIndexedAccess.ts, 323, 5)) + + return getProperty(this, "parts") +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 77, 26)) +>this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 317, 1)) + } +} + +// Modified repro from #12544 + +function path(obj: T, key1: K1): T[K1]; +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 331, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 331, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 331, 14)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 331, 37)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 331, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 331, 44)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 331, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 331, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 331, 16)) + +function path(obj: T, key1: K1, key2: K2): T[K1][K2]; +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 332, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 332, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 332, 14)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 332, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 332, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 332, 16)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 332, 61)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 332, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 332, 68)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 332, 16)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 332, 78)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 332, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 332, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 332, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 332, 36)) + +function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 333, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 333, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 333, 16)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 333, 60)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 333, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 333, 36)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 333, 89)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 333, 96)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 333, 16)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 333, 106)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 333, 36)) +>key3 : Symbol(key3, Decl(keyofAndIndexedAccess.ts, 333, 116)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 333, 60)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 333, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 333, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 333, 36)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 333, 60)) + +function path(obj: any, ...keys: (string | number)[]): any; +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 334, 14)) +>keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 334, 23)) + +function path(obj: any, ...keys: (string | number)[]): any { +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 335, 14)) +>keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 335, 23)) + + let result = obj; +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 336, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 335, 14)) + + for (let k of keys) { +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 337, 12)) +>keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 335, 23)) + + result = result[k]; +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 336, 7)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 336, 7)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 337, 12)) + } + return result; +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 336, 7)) +} + +type Thing = { +>Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 341, 1)) + + a: { x: number, y: string }, +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 343, 14)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 344, 8)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 344, 19)) + + b: boolean +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 344, 32)) + +}; + + +function f1(thing: Thing) { +>f1 : Symbol(f1, Decl(keyofAndIndexedAccess.ts, 346, 2)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 349, 12)) +>Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 341, 1)) + + let x1 = path(thing, 'a'); // { x: number, y: string } +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 350, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 349, 12)) + + let x2 = path(thing, 'a', 'y'); // string +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 351, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 349, 12)) + + let x3 = path(thing, 'b'); // boolean +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 352, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 349, 12)) + + let x4 = path(thing, ...['a', 'x']); // any +>x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 353, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 327, 1), Decl(keyofAndIndexedAccess.ts, 331, 62), Decl(keyofAndIndexedAccess.ts, 332, 100), Decl(keyofAndIndexedAccess.ts, 333, 142), Decl(keyofAndIndexedAccess.ts, 334, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 349, 12)) +} + +// Repro from comment in #12114 + +const assignTo2 = (object: T, key1: K1, key2: K2) => +>assignTo2 : Symbol(assignTo2, Decl(keyofAndIndexedAccess.ts, 358, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 358, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 358, 21)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 358, 19)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 358, 41)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 358, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 358, 21)) +>object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 358, 66)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 358, 19)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 358, 76)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 358, 21)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 358, 86)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 358, 41)) + + (value: T[K1][K2]) => object[key1][key2] = value; +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 359, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 358, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 358, 21)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 358, 41)) +>object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 358, 66)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 358, 76)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 358, 86)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 359, 5)) + +// Modified repro from #12573 + +declare function one(handler: (t: T) => void): T +>one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 359, 53)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 21)) +>handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 363, 24)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 363, 34)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 21)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 21)) + +var empty = one(() => {}) // inferred as {}, expected +>empty : Symbol(empty, Decl(keyofAndIndexedAccess.ts, 364, 3)) +>one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 359, 53)) + +type Handlers = { [K in keyof T]: (t: T[K]) => void } +>Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 364, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 366, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 366, 22)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 366, 14)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 366, 38)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 366, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 366, 22)) + +declare function on(handlerHash: Handlers): T +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 366, 56)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 367, 20)) +>handlerHash : Symbol(handlerHash, Decl(keyofAndIndexedAccess.ts, 367, 23)) +>Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 364, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 367, 20)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 367, 20)) + +var hashOfEmpty1 = on({ test: () => {} }); // {} +>hashOfEmpty1 : Symbol(hashOfEmpty1, Decl(keyofAndIndexedAccess.ts, 368, 3)) +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 366, 56)) +>test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 368, 23)) + +var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } +>hashOfEmpty2 : Symbol(hashOfEmpty2, Decl(keyofAndIndexedAccess.ts, 369, 3)) +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 366, 56)) +>test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 369, 23)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 369, 31)) + +// Repro from #12624 + +interface Options1 { +>Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 369, 52)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 373, 19)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 373, 24)) + + data?: Data +>data : Symbol(Options1.data, Decl(keyofAndIndexedAccess.ts, 373, 36)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 373, 19)) + + computed?: Computed; +>computed : Symbol(Options1.computed, Decl(keyofAndIndexedAccess.ts, 374, 15)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 373, 24)) +} + +declare class Component1 { +>Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 376, 1)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 378, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 378, 30)) + + constructor(options: Options1); +>options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 379, 16)) +>Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 369, 52)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 378, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 378, 30)) + + get(key: K): (Data & Computed)[K]; +>get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 379, 51)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 380, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 378, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 378, 30)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 380, 43)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 380, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 378, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 378, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 380, 8)) +} + +let c1 = new Component1({ +>c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 383, 3)) +>Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 376, 1)) + + data: { +>data : Symbol(data, Decl(keyofAndIndexedAccess.ts, 383, 25)) + + hello: "" +>hello : Symbol(hello, Decl(keyofAndIndexedAccess.ts, 384, 11)) + } +}); + +c1.get("hello"); +>c1.get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 379, 51)) +>c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 383, 3)) +>get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 379, 51)) + +// Repro from #12625 + +interface Options2 { +>Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 389, 16)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 393, 19)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 393, 24)) + + data?: Data +>data : Symbol(Options2.data, Decl(keyofAndIndexedAccess.ts, 393, 36)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 393, 19)) + + computed?: Computed; +>computed : Symbol(Options2.computed, Decl(keyofAndIndexedAccess.ts, 394, 15)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 393, 24)) +} + +declare class Component2 { +>Component2 : Symbol(Component2, Decl(keyofAndIndexedAccess.ts, 396, 1)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 398, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 398, 30)) + + constructor(options: Options2); +>options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 399, 16)) +>Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 389, 16)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 398, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 398, 30)) + + get(key: K): (Data & Computed)[K]; +>get : Symbol(Component2.get, Decl(keyofAndIndexedAccess.ts, 399, 51)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 400, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 398, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 398, 30)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 400, 47)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 400, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 398, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 398, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 400, 8)) +} + +// Repro from #12641 + +interface R { +>R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 401, 1)) + + p: number; +>p : Symbol(R.p, Decl(keyofAndIndexedAccess.ts, 405, 13)) +} + +function f(p: K) { +>f : Symbol(f, Decl(keyofAndIndexedAccess.ts, 407, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 409, 11)) +>R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 401, 1)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 409, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 409, 11)) + + let a: any; +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 410, 7)) + + a[p].add; // any +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 410, 7)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 409, 30)) +} + +// Repro from #12651 + +type MethodDescriptor = { +>MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 412, 1)) + + name: string; +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 416, 25)) + + args: any[]; +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 417, 14)) + + returnValue: any; +>returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 418, 13)) +} + +declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; +>dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 420, 1)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 422, 32)) +>MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 412, 1)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 422, 60)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 422, 32)) +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 422, 76)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 422, 32)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 422, 32)) + +type SomeMethodDescriptor = { +>SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 422, 112)) + + name: "someMethod"; +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 424, 29)) + + args: [string, number]; +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 425, 20)) + + returnValue: string[]; +>returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 426, 24)) +} + +let result = dispatchMethod("someMethod", ["hello", 35]); +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 430, 3)) +>dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 420, 1)) +>SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 422, 112)) + diff --git a/tests/baselines/reference/keyofAndIndexedAccess.types b/tests/baselines/reference/keyofAndIndexedAccess.types new file mode 100644 index 00000000000..f94249806f6 --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccess.types @@ -0,0 +1,1877 @@ +=== tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts === + +class Shape { +>Shape : Shape + + name: string; +>name : string + + width: number; +>width : number + + height: number; +>height : number + + visible: boolean; +>visible : boolean +} + +class TaggedShape extends Shape { +>TaggedShape : TaggedShape +>Shape : Shape + + tag: string; +>tag : string +} + +class Item { +>Item : Item + + name: string; +>name : string + + price: number; +>price : number +} + +class Options { +>Options : Options + + visible: "yes" | "no"; +>visible : "yes" | "no" +} + +type Dictionary = { [x: string]: T }; +>Dictionary : Dictionary +>T : T +>x : string +>T : T + +type NumericallyIndexed = { [x: number]: T }; +>NumericallyIndexed : NumericallyIndexed +>T : T +>x : number +>T : T + +const enum E { A, B, C } +>E : E +>A : E.A +>B : E.B +>C : E.C + +type K00 = keyof any; // string +>K00 : string + +type K01 = keyof string; // "toString" | "charAt" | ... +>K01 : "length" | "toString" | "concat" | "slice" | "indexOf" | "lastIndexOf" | "charAt" | "charCodeAt" | "localeCompare" | "match" | "replace" | "search" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "substr" | "valueOf" + +type K02 = keyof number; // "toString" | "toFixed" | "toExponential" | ... +>K02 : "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision" + +type K03 = keyof boolean; // "valueOf" +>K03 : "valueOf" + +type K04 = keyof void; // never +>K04 : never + +type K05 = keyof undefined; // never +>K05 : never + +type K06 = keyof null; // never +>K06 : never +>null : null + +type K07 = keyof never; // never +>K07 : never + +type K10 = keyof Shape; // "name" | "width" | "height" | "visible" +>K10 : "name" | "width" | "height" | "visible" +>Shape : Shape + +type K11 = keyof Shape[]; // "length" | "toString" | ... +>K11 : "length" | "toString" | "toLocaleString" | "push" | "pop" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | "every" | "some" | "forEach" | "map" | "filter" | "reduce" | "reduceRight" +>Shape : Shape + +type K12 = keyof Dictionary; // string +>K12 : string +>Dictionary : Dictionary +>Shape : Shape + +type K13 = keyof {}; // never +>K13 : never + +type K14 = keyof Object; // "constructor" | "toString" | ... +>K14 : "toString" | "toLocaleString" | "valueOf" | "constructor" | "hasOwnProperty" | "isPrototypeOf" | "propertyIsEnumerable" +>Object : Object + +type K15 = keyof E; // "toString" | "toFixed" | "toExponential" | ... +>K15 : "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision" +>E : E + +type K16 = keyof [string, number]; // "0" | "1" | "length" | "toString" | ... +>K16 : "0" | "1" | "length" | "toString" | "toLocaleString" | "push" | "pop" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | "every" | "some" | "forEach" | "map" | "filter" | "reduce" | "reduceRight" + +type K17 = keyof (Shape | Item); // "name" +>K17 : "name" +>Shape : Shape +>Item : Item + +type K18 = keyof (Shape & Item); // "name" | "width" | "height" | "visible" | "price" +>K18 : "name" | "width" | "height" | "visible" | "price" +>Shape : Shape +>Item : Item + +type K19 = keyof NumericallyIndexed // never +>K19 : never +>NumericallyIndexed : NumericallyIndexed +>Shape : Shape + +type KeyOf = keyof T; +>KeyOf : keyof T +>T : T +>T : T + +type K20 = KeyOf; // "name" | "width" | "height" | "visible" +>K20 : "name" | "width" | "height" | "visible" +>KeyOf : keyof T +>Shape : Shape + +type K21 = KeyOf>; // string +>K21 : string +>KeyOf : keyof T +>Dictionary : Dictionary +>Shape : Shape + +type NAME = "name"; +>NAME : "name" + +type WIDTH_OR_HEIGHT = "width" | "height"; +>WIDTH_OR_HEIGHT : "width" | "height" + +type Q10 = Shape["name"]; // string +>Q10 : string +>Shape : Shape + +type Q11 = Shape["width" | "height"]; // number +>Q11 : number +>Shape : Shape + +type Q12 = Shape["name" | "visible"]; // string | boolean +>Q12 : string | boolean +>Shape : Shape + +type Q20 = Shape[NAME]; // string +>Q20 : string +>Shape : Shape +>NAME : "name" + +type Q21 = Shape[WIDTH_OR_HEIGHT]; // number +>Q21 : number +>Shape : Shape +>WIDTH_OR_HEIGHT : "width" | "height" + +type Q30 = [string, number][0]; // string +>Q30 : string + +type Q31 = [string, number][1]; // number +>Q31 : number + +type Q32 = [string, number][2]; // string | number +>Q32 : string | number + +type Q33 = [string, number][E.A]; // string +>Q33 : string +>E : any +>A : E.A + +type Q34 = [string, number][E.B]; // number +>Q34 : number +>E : any +>B : E.B + +type Q35 = [string, number][E.C]; // string | number +>Q35 : string | number +>E : any +>C : E.C + +type Q36 = [string, number]["0"]; // string +>Q36 : string + +type Q37 = [string, number]["1"]; // string +>Q37 : number + +type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" +>Q40 : boolean | "yes" | "no" +>Shape : Shape +>Options : Options + +type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" +>Q41 : (true & "yes") | (true & "no") | (false & "yes") | (false & "no") +>Shape : Shape +>Options : Options + +type Q50 = Dictionary["howdy"]; // Shape +>Q50 : Shape +>Dictionary : Dictionary +>Shape : Shape + +type Q51 = Dictionary[123]; // Shape +>Q51 : Shape +>Dictionary : Dictionary +>Shape : Shape + +type Q52 = Dictionary[E.B]; // Shape +>Q52 : Shape +>Dictionary : Dictionary +>Shape : Shape +>E : any +>B : E.B + +declare let cond: boolean; +>cond : boolean + +function getProperty(obj: T, key: K) { +>getProperty : (obj: T, key: K) => T[K] +>T : T +>K : K +>T : T +>obj : T +>T : T +>key : K +>K : K + + return obj[key]; +>obj[key] : T[K] +>obj : T +>key : K +} + +function setProperty(obj: T, key: K, value: T[K]) { +>setProperty : (obj: T, key: K, value: T[K]) => void +>T : T +>K : K +>T : T +>obj : T +>T : T +>key : K +>K : K +>value : T[K] +>T : T +>K : K + + obj[key] = value; +>obj[key] = value : T[K] +>obj[key] : T[K] +>obj : T +>key : K +>value : T[K] +} + +function f10(shape: Shape) { +>f10 : (shape: Shape) => void +>shape : Shape +>Shape : Shape + + let name = getProperty(shape, "name"); // string +>name : string +>getProperty(shape, "name") : string +>getProperty : (obj: T, key: K) => T[K] +>shape : Shape +>"name" : "name" + + let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number +>widthOrHeight : number +>getProperty(shape, cond ? "width" : "height") : number +>getProperty : (obj: T, key: K) => T[K] +>shape : Shape +>cond ? "width" : "height" : "width" | "height" +>cond : boolean +>"width" : "width" +>"height" : "height" + + let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean +>nameOrVisible : string | boolean +>getProperty(shape, cond ? "name" : "visible") : string | boolean +>getProperty : (obj: T, key: K) => T[K] +>shape : Shape +>cond ? "name" : "visible" : "name" | "visible" +>cond : boolean +>"name" : "name" +>"visible" : "visible" + + setProperty(shape, "name", "rectangle"); +>setProperty(shape, "name", "rectangle") : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>shape : Shape +>"name" : "name" +>"rectangle" : "rectangle" + + setProperty(shape, cond ? "width" : "height", 10); +>setProperty(shape, cond ? "width" : "height", 10) : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>shape : Shape +>cond ? "width" : "height" : "width" | "height" +>cond : boolean +>"width" : "width" +>"height" : "height" +>10 : 10 + + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe +>setProperty(shape, cond ? "name" : "visible", true) : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>shape : Shape +>cond ? "name" : "visible" : "name" | "visible" +>cond : boolean +>"name" : "name" +>"visible" : "visible" +>true : true +} + +function f11(a: Shape[]) { +>f11 : (a: Shape[]) => void +>a : Shape[] +>Shape : Shape + + let len = getProperty(a, "length"); // number +>len : number +>getProperty(a, "length") : number +>getProperty : (obj: T, key: K) => T[K] +>a : Shape[] +>"length" : "length" + + setProperty(a, "length", len); +>setProperty(a, "length", len) : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>a : Shape[] +>"length" : "length" +>len : number +} + +function f12(t: [Shape, boolean]) { +>f12 : (t: [Shape, boolean]) => void +>t : [Shape, boolean] +>Shape : Shape + + let len = getProperty(t, "length"); +>len : number +>getProperty(t, "length") : number +>getProperty : (obj: T, key: K) => T[K] +>t : [Shape, boolean] +>"length" : "length" + + let s2 = getProperty(t, "0"); // Shape +>s2 : Shape +>getProperty(t, "0") : Shape +>getProperty : (obj: T, key: K) => T[K] +>t : [Shape, boolean] +>"0" : "0" + + let b2 = getProperty(t, "1"); // boolean +>b2 : boolean +>getProperty(t, "1") : boolean +>getProperty : (obj: T, key: K) => T[K] +>t : [Shape, boolean] +>"1" : "1" +} + +function f13(foo: any, bar: any) { +>f13 : (foo: any, bar: any) => void +>foo : any +>bar : any + + let x = getProperty(foo, "x"); // any +>x : any +>getProperty(foo, "x") : any +>getProperty : (obj: T, key: K) => T[K] +>foo : any +>"x" : "x" + + let y = getProperty(foo, "100"); // any +>y : any +>getProperty(foo, "100") : any +>getProperty : (obj: T, key: K) => T[K] +>foo : any +>"100" : "100" + + let z = getProperty(foo, bar); // any +>z : any +>getProperty(foo, bar) : any +>getProperty : (obj: T, key: K) => T[K] +>foo : any +>bar : any +} + +class Component { +>Component : Component +>PropType : PropType + + props: PropType; +>props : PropType +>PropType : PropType + + getProperty(key: K) { +>getProperty : (key: K) => PropType[K] +>K : K +>PropType : PropType +>key : K +>K : K + + return this.props[key]; +>this.props[key] : PropType[K] +>this.props : PropType +>this : this +>props : PropType +>key : K + } + setProperty(key: K, value: PropType[K]) { +>setProperty : (key: K, value: PropType[K]) => void +>K : K +>PropType : PropType +>key : K +>K : K +>value : PropType[K] +>PropType : PropType +>K : K + + this.props[key] = value; +>this.props[key] = value : PropType[K] +>this.props[key] : PropType[K] +>this.props : PropType +>this : this +>props : PropType +>key : K +>value : PropType[K] + } +} + +function f20(component: Component) { +>f20 : (component: Component) => void +>component : Component +>Component : Component +>Shape : Shape + + let name = component.getProperty("name"); // string +>name : string +>component.getProperty("name") : string +>component.getProperty : (key: K) => Shape[K] +>component : Component +>getProperty : (key: K) => Shape[K] +>"name" : "name" + + let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number +>widthOrHeight : number +>component.getProperty(cond ? "width" : "height") : number +>component.getProperty : (key: K) => Shape[K] +>component : Component +>getProperty : (key: K) => Shape[K] +>cond ? "width" : "height" : "width" | "height" +>cond : boolean +>"width" : "width" +>"height" : "height" + + let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean +>nameOrVisible : string | boolean +>component.getProperty(cond ? "name" : "visible") : string | boolean +>component.getProperty : (key: K) => Shape[K] +>component : Component +>getProperty : (key: K) => Shape[K] +>cond ? "name" : "visible" : "name" | "visible" +>cond : boolean +>"name" : "name" +>"visible" : "visible" + + component.setProperty("name", "rectangle"); +>component.setProperty("name", "rectangle") : void +>component.setProperty : (key: K, value: Shape[K]) => void +>component : Component +>setProperty : (key: K, value: Shape[K]) => void +>"name" : "name" +>"rectangle" : "rectangle" + + component.setProperty(cond ? "width" : "height", 10) +>component.setProperty(cond ? "width" : "height", 10) : void +>component.setProperty : (key: K, value: Shape[K]) => void +>component : Component +>setProperty : (key: K, value: Shape[K]) => void +>cond ? "width" : "height" : "width" | "height" +>cond : boolean +>"width" : "width" +>"height" : "height" +>10 : 10 + + component.setProperty(cond ? "name" : "visible", true); // Technically not safe +>component.setProperty(cond ? "name" : "visible", true) : void +>component.setProperty : (key: K, value: Shape[K]) => void +>component : Component +>setProperty : (key: K, value: Shape[K]) => void +>cond ? "name" : "visible" : "name" | "visible" +>cond : boolean +>"name" : "name" +>"visible" : "visible" +>true : true +} + +function pluck(array: T[], key: K) { +>pluck : (array: T[], key: K) => T[K][] +>T : T +>K : K +>T : T +>array : T[] +>T : T +>key : K +>K : K + + return array.map(x => x[key]); +>array.map(x => x[key]) : T[K][] +>array.map : { (this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; (this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; (this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; } +>array : T[] +>map : { (this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; (this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; (this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; } +>x => x[key] : (x: T) => T[K] +>x : T +>x[key] : T[K] +>x : T +>key : K +} + +function f30(shapes: Shape[]) { +>f30 : (shapes: Shape[]) => void +>shapes : Shape[] +>Shape : Shape + + let names = pluck(shapes, "name"); // string[] +>names : string[] +>pluck(shapes, "name") : string[] +>pluck : (array: T[], key: K) => T[K][] +>shapes : Shape[] +>"name" : "name" + + let widths = pluck(shapes, "width"); // number[] +>widths : number[] +>pluck(shapes, "width") : number[] +>pluck : (array: T[], key: K) => T[K][] +>shapes : Shape[] +>"width" : "width" + + let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] +>nameOrVisibles : (string | boolean)[] +>pluck(shapes, cond ? "name" : "visible") : (string | boolean)[] +>pluck : (array: T[], key: K) => T[K][] +>shapes : Shape[] +>cond ? "name" : "visible" : "name" | "visible" +>cond : boolean +>"name" : "name" +>"visible" : "visible" +} + +function f31(key: K) { +>f31 : (key: K) => Shape[K] +>K : K +>Shape : Shape +>key : K +>K : K + + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; +>shape : Shape +>Shape : Shape +>{ name: "foo", width: 5, height: 10, visible: true } : { name: string; width: number; height: number; visible: true; } +>name : string +>"foo" : "foo" +>width : number +>5 : 5 +>height : number +>10 : 10 +>visible : boolean +>true : true + + return shape[key]; // Shape[K] +>shape[key] : Shape[K] +>shape : Shape +>key : K +} + +function f32(key: K) { +>f32 : (key: K) => Shape[K] +>K : K +>key : K +>K : K + + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; +>shape : Shape +>Shape : Shape +>{ name: "foo", width: 5, height: 10, visible: true } : { name: string; width: number; height: number; visible: true; } +>name : string +>"foo" : "foo" +>width : number +>5 : 5 +>height : number +>10 : 10 +>visible : boolean +>true : true + + return shape[key]; // Shape[K] +>shape[key] : Shape[K] +>shape : Shape +>key : K +} + +function f33(shape: S, key: K) { +>f33 : (shape: S, key: K) => S[K] +>S : S +>Shape : Shape +>K : K +>S : S +>shape : S +>S : S +>key : K +>K : K + + let name = getProperty(shape, "name"); +>name : S["name"] +>getProperty(shape, "name") : S["name"] +>getProperty : (obj: T, key: K) => T[K] +>shape : S +>"name" : "name" + + let prop = getProperty(shape, key); +>prop : S[K] +>getProperty(shape, key) : S[K] +>getProperty : (obj: T, key: K) => T[K] +>shape : S +>key : K + + return prop; +>prop : S[K] +} + +function f34(ts: TaggedShape) { +>f34 : (ts: TaggedShape) => void +>ts : TaggedShape +>TaggedShape : TaggedShape + + let tag1 = f33(ts, "tag"); +>tag1 : string +>f33(ts, "tag") : string +>f33 : (shape: S, key: K) => S[K] +>ts : TaggedShape +>"tag" : "tag" + + let tag2 = getProperty(ts, "tag"); +>tag2 : string +>getProperty(ts, "tag") : string +>getProperty : (obj: T, key: K) => T[K] +>ts : TaggedShape +>"tag" : "tag" +} + +class C { +>C : C + + public x: string; +>x : string + + protected y: string; +>y : string + + private z: string; +>z : string +} + +// Indexed access expressions have always permitted access to private and protected members. +// For consistency we also permit such access in indexed access types. +function f40(c: C) { +>f40 : (c: C) => void +>c : C +>C : C + + type X = C["x"]; +>X : string +>C : C + + type Y = C["y"]; +>Y : string +>C : C + + type Z = C["z"]; +>Z : string +>C : C + + let x: X = c["x"]; +>x : string +>X : string +>c["x"] : string +>c : C +>"x" : "x" + + let y: Y = c["y"]; +>y : string +>Y : string +>c["y"] : string +>c : C +>"y" : "y" + + let z: Z = c["z"]; +>z : string +>Z : string +>c["z"] : string +>c : C +>"z" : "z" +} + +function f50(k: keyof T, s: string) { +>f50 : (k: keyof T, s: string) => void +>T : T +>k : keyof T +>T : T +>s : string + + const x1 = s as keyof T; +>x1 : keyof T +>s as keyof T : keyof T +>s : string +>T : T + + const x2 = k as string; +>x2 : string +>k as string : string +>k : keyof T +} + +function f51(k: K, s: string) { +>f51 : (k: K, s: string) => void +>T : T +>K : K +>T : T +>k : K +>K : K +>s : string + + const x1 = s as keyof T; +>x1 : keyof T +>s as keyof T : keyof T +>s : string +>T : T + + const x2 = k as string; +>x2 : string +>k as string : string +>k : K +} + +function f52(obj: { [x: string]: boolean }, k: keyof T, s: string, n: number) { +>f52 : (obj: { [x: string]: boolean; }, k: keyof T, s: string, n: number) => void +>T : T +>obj : { [x: string]: boolean; } +>x : string +>k : keyof T +>T : T +>s : string +>n : number + + const x1 = obj[s]; +>x1 : boolean +>obj[s] : boolean +>obj : { [x: string]: boolean; } +>s : string + + const x2 = obj[n]; +>x2 : boolean +>obj[n] : boolean +>obj : { [x: string]: boolean; } +>n : number + + const x3 = obj[k]; +>x3 : { [x: string]: boolean; }[keyof T] +>obj[k] : { [x: string]: boolean; }[keyof T] +>obj : { [x: string]: boolean; } +>k : keyof T +} + +function f53(obj: { [x: string]: boolean }, k: K, s: string, n: number) { +>f53 : (obj: { [x: string]: boolean; }, k: K, s: string, n: number) => void +>T : T +>K : K +>T : T +>obj : { [x: string]: boolean; } +>x : string +>k : K +>K : K +>s : string +>n : number + + const x1 = obj[s]; +>x1 : boolean +>obj[s] : boolean +>obj : { [x: string]: boolean; } +>s : string + + const x2 = obj[n]; +>x2 : boolean +>obj[n] : boolean +>obj : { [x: string]: boolean; } +>n : number + + const x3 = obj[k]; +>x3 : { [x: string]: boolean; }[K] +>obj[k] : { [x: string]: boolean; }[K] +>obj : { [x: string]: boolean; } +>k : K +} + +function f54(obj: T, key: keyof T) { +>f54 : (obj: T, key: keyof T) => void +>T : T +>obj : T +>T : T +>key : keyof T +>T : T + + for (let s in obj[key]) { +>s : keyof T[keyof T] +>obj[key] : T[keyof T] +>obj : T +>key : keyof T + } + const b = "foo" in obj[key]; +>b : boolean +>"foo" in obj[key] : boolean +>"foo" : "foo" +>obj[key] : T[keyof T] +>obj : T +>key : keyof T +} + +function f55(obj: T, key: K) { +>f55 : (obj: T, key: K) => void +>T : T +>K : K +>T : T +>obj : T +>T : T +>key : K +>K : K + + for (let s in obj[key]) { +>s : keyof T[K] +>obj[key] : T[K] +>obj : T +>key : K + } + const b = "foo" in obj[key]; +>b : boolean +>"foo" in obj[key] : boolean +>"foo" : "foo" +>obj[key] : T[K] +>obj : T +>key : K +} + +function f60(source: T, target: T) { +>f60 : (source: T, target: T) => void +>T : T +>source : T +>T : T +>target : T +>T : T + + for (let k in source) { +>k : keyof T +>source : T + + target[k] = source[k]; +>target[k] = source[k] : T[keyof T] +>target[k] : T[keyof T] +>target : T +>k : keyof T +>source[k] : T[keyof T] +>source : T +>k : keyof T + } +} + +function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { +>f70 : (func: (k1: keyof (T | U), k2: keyof (T & U)) => void) => void +>func : (k1: keyof (T | U), k2: keyof (T & U)) => void +>T : T +>U : U +>k1 : keyof (T | U) +>T : T +>U : U +>k2 : keyof (T & U) +>T : T +>U : U + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); +>func<{ a: any, b: any }, { a: any, c: any }>('a', 'a') : void +>func : (k1: keyof (T | U), k2: keyof (T & U)) => void +>a : any +>b : any +>a : any +>c : any +>'a' : "a" +>'a' : "a" + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); +>func<{ a: any, b: any }, { a: any, c: any }>('a', 'b') : void +>func : (k1: keyof (T | U), k2: keyof (T & U)) => void +>a : any +>b : any +>a : any +>c : any +>'a' : "a" +>'b' : "b" + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); +>func<{ a: any, b: any }, { a: any, c: any }>('a', 'c') : void +>func : (k1: keyof (T | U), k2: keyof (T & U)) => void +>a : any +>b : any +>a : any +>c : any +>'a' : "a" +>'c' : "c" +} + +function f71(func: (x: T, y: U) => Partial) { +>f71 : (func: (x: T, y: U) => Partial) => void +>func : (x: T, y: U) => Partial +>T : T +>U : U +>x : T +>T : T +>y : U +>U : U +>Partial : Partial +>T : T +>U : U + + let x = func({ a: 1, b: "hello" }, { c: true }); +>x : Partial<{ a: number; b: string; } & { c: boolean; }> +>func({ a: 1, b: "hello" }, { c: true }) : Partial<{ a: number; b: string; } & { c: boolean; }> +>func : (x: T, y: U) => Partial +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true + + x.a; // number | undefined +>x.a : number | undefined +>x : Partial<{ a: number; b: string; } & { c: boolean; }> +>a : number | undefined + + x.b; // string | undefined +>x.b : string | undefined +>x : Partial<{ a: number; b: string; } & { c: boolean; }> +>b : string | undefined + + x.c; // boolean | undefined +>x.c : boolean | undefined +>x : Partial<{ a: number; b: string; } & { c: boolean; }> +>c : boolean | undefined +} + +function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { +>f72 : (func: (x: T, y: U, k: K) => (T & U)[K]) => void +>func : (x: T, y: U, k: K) => (T & U)[K] +>T : T +>U : U +>K : K +>T : T +>U : U +>x : T +>T : T +>y : U +>U : U +>k : K +>K : K +>T : T +>U : U +>K : K + + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number +>a : number +>func({ a: 1, b: "hello" }, { c: true }, 'a') : number +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'a' : "a" + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : string +>func({ a: 1, b: "hello" }, { c: true }, 'b') : string +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'b' : "b" + + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : boolean +>func({ a: 1, b: "hello" }, { c: true }, 'c') : boolean +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'c' : "c" +} + +function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { +>f73 : (func: (x: T, y: U, k: K) => (T & U)[K]) => void +>func : (x: T, y: U, k: K) => (T & U)[K] +>T : T +>U : U +>K : K +>T : T +>U : U +>x : T +>T : T +>y : U +>U : U +>k : K +>K : K +>T : T +>U : U +>K : K + + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number +>a : number +>func({ a: 1, b: "hello" }, { c: true }, 'a') : number +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'a' : "a" + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : string +>func({ a: 1, b: "hello" }, { c: true }, 'b') : string +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'b' : "b" + + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : boolean +>func({ a: 1, b: "hello" }, { c: true }, 'c') : boolean +>func : (x: T, y: U, k: K) => (T & U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ c: true } : { c: true; } +>c : boolean +>true : true +>'c' : "c" +} + +function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { +>f74 : (func: (x: T, y: U, k: K) => (T | U)[K]) => void +>func : (x: T, y: U, k: K) => (T | U)[K] +>T : T +>U : U +>K : K +>T : T +>U : U +>x : T +>T : T +>y : U +>U : U +>k : K +>K : K +>T : T +>U : U +>K : K + + let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number +>a : number +>func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a') : number +>func : (x: T, y: U, k: K) => (T | U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ a: 2, b: true } : { a: number; b: true; } +>a : number +>2 : 2 +>b : boolean +>true : true +>'a' : "a" + + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +>b : string | boolean +>func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b') : string | boolean +>func : (x: T, y: U, k: K) => (T | U)[K] +>{ a: 1, b: "hello" } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>"hello" : "hello" +>{ a: 2, b: true } : { a: number; b: true; } +>a : number +>2 : 2 +>b : boolean +>true : true +>'b' : "b" +} + +function f80(obj: T) { +>f80 : (obj: T) => void +>T : T +>a : { x: any; } +>x : any +>obj : T +>T : T + + let a1 = obj.a; // { x: any } +>a1 : { x: any; } +>obj.a : { x: any; } +>obj : T +>a : { x: any; } + + let a2 = obj['a']; // { x: any } +>a2 : { x: any; } +>obj['a'] : { x: any; } +>obj : T +>'a' : "a" + + let a3 = obj['a'] as T['a']; // T["a"] +>a3 : T["a"] +>obj['a'] as T['a'] : T["a"] +>obj['a'] : { x: any; } +>obj : T +>'a' : "a" +>T : T + + let x1 = obj.a.x; // any +>x1 : any +>obj.a.x : any +>obj.a : { x: any; } +>obj : T +>a : { x: any; } +>x : any + + let x2 = obj['a']['x']; // any +>x2 : any +>obj['a']['x'] : any +>obj['a'] : { x: any; } +>obj : T +>'a' : "a" +>'x' : "x" + + let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] +>x3 : T["a"]["x"] +>obj['a']['x'] as T['a']['x'] : T["a"]["x"] +>obj['a']['x'] : any +>obj['a'] : { x: any; } +>obj : T +>'a' : "a" +>'x' : "x" +>T : T +} + +function f81(obj: T) { +>f81 : (obj: T) => T["a"]["x"] +>T : T +>a : { x: any; } +>x : any +>obj : T +>T : T + + return obj['a']['x'] as T['a']['x']; +>obj['a']['x'] as T['a']['x'] : T["a"]["x"] +>obj['a']['x'] : any +>obj['a'] : { x: any; } +>obj : T +>'a' : "a" +>'x' : "x" +>T : T +} + +function f82() { +>f82 : () => void + + let x1 = f81({ a: { x: "hello" } }); // string +>x1 : string +>f81({ a: { x: "hello" } }) : string +>f81 : (obj: T) => T["a"]["x"] +>{ a: { x: "hello" } } : { a: { x: string; }; } +>a : { x: string; } +>{ x: "hello" } : { x: string; } +>x : string +>"hello" : "hello" + + let x2 = f81({ a: { x: 42 } }); // number +>x2 : number +>f81({ a: { x: 42 } }) : number +>f81 : (obj: T) => T["a"]["x"] +>{ a: { x: 42 } } : { a: { x: number; }; } +>a : { x: number; } +>{ x: 42 } : { x: number; } +>x : number +>42 : 42 +} + +function f83(obj: T, key: K) { +>f83 : (obj: T, key: K) => T[K]["x"] +>T : T +>x : string +>x : any +>K : K +>T : T +>obj : T +>T : T +>key : K +>K : K + + return obj[key]['x'] as T[K]['x']; +>obj[key]['x'] as T[K]['x'] : T[K]["x"] +>obj[key]['x'] : any +>obj[key] : T[K] +>obj : T +>key : K +>'x' : "x" +>T : T +>K : K +} + +function f84() { +>f84 : () => void + + let x1 = f83({ foo: { x: "hello" } }, "foo"); // string +>x1 : string +>f83({ foo: { x: "hello" } }, "foo") : string +>f83 : (obj: T, key: K) => T[K]["x"] +>{ foo: { x: "hello" } } : { foo: { x: string; }; } +>foo : { x: string; } +>{ x: "hello" } : { x: string; } +>x : string +>"hello" : "hello" +>"foo" : "foo" + + let x2 = f83({ bar: { x: 42 } }, "bar"); // number +>x2 : number +>f83({ bar: { x: 42 } }, "bar") : number +>f83 : (obj: T, key: K) => T[K]["x"] +>{ bar: { x: 42 } } : { bar: { x: number; }; } +>bar : { x: number; } +>{ x: 42 } : { x: number; } +>x : number +>42 : 42 +>"bar" : "bar" +} + +class C1 { +>C1 : C1 + + x: number; +>x : number + + get(key: K) { +>get : (key: K) => this[K] +>K : K +>key : K +>K : K + + return this[key]; +>this[key] : this[K] +>this : this +>key : K + } + set(key: K, value: this[K]) { +>set : (key: K, value: this[K]) => void +>K : K +>key : K +>K : K +>value : this[K] +>K : K + + this[key] = value; +>this[key] = value : this[K] +>this[key] : this[K] +>this : this +>key : K +>value : this[K] + } + foo() { +>foo : () => void + + let x1 = this.x; // number +>x1 : number +>this.x : number +>this : this +>x : number + + let x2 = this["x"]; // number +>x2 : number +>this["x"] : number +>this : this +>"x" : "x" + + let x3 = this.get("x"); // this["x"] +>x3 : this["x"] +>this.get("x") : this["x"] +>this.get : (key: K) => this[K] +>this : this +>get : (key: K) => this[K] +>"x" : "x" + + let x4 = getProperty(this, "x"); // this["x"] +>x4 : this["x"] +>getProperty(this, "x") : this["x"] +>getProperty : (obj: T, key: K) => T[K] +>this : this +>"x" : "x" + + this.x = 42; +>this.x = 42 : 42 +>this.x : number +>this : this +>x : number +>42 : 42 + + this["x"] = 42; +>this["x"] = 42 : 42 +>this["x"] : number +>this : this +>"x" : "x" +>42 : 42 + + this.set("x", 42); +>this.set("x", 42) : void +>this.set : (key: K, value: this[K]) => void +>this : this +>set : (key: K, value: this[K]) => void +>"x" : "x" +>42 : 42 + + setProperty(this, "x", 42); +>setProperty(this, "x", 42) : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>this : this +>"x" : "x" +>42 : 42 + } +} + +// Repros from #12011 + +class Base { +>Base : Base + + get(prop: K) { +>get : (prop: K) => this[K] +>K : K +>prop : K +>K : K + + return this[prop]; +>this[prop] : this[K] +>this : this +>prop : K + } + set(prop: K, value: this[K]) { +>set : (prop: K, value: this[K]) => void +>K : K +>prop : K +>K : K +>value : this[K] +>K : K + + this[prop] = value; +>this[prop] = value : this[K] +>this[prop] : this[K] +>this : this +>prop : K +>value : this[K] + } +} + +class Person extends Base { +>Person : Person +>Base : Base + + parts: number; +>parts : number + + constructor(parts: number) { +>parts : number + + super(); +>super() : void +>super : typeof Base + + this.set("parts", parts); +>this.set("parts", parts) : void +>this.set : (prop: K, value: this[K]) => void +>this : this +>set : (prop: K, value: this[K]) => void +>"parts" : "parts" +>parts : number + } + getParts() { +>getParts : () => this["parts"] + + return this.get("parts") +>this.get("parts") : this["parts"] +>this.get : (prop: K) => this[K] +>this : this +>get : (prop: K) => this[K] +>"parts" : "parts" + } +} + +class OtherPerson { +>OtherPerson : OtherPerson + + parts: number; +>parts : number + + constructor(parts: number) { +>parts : number + + setProperty(this, "parts", parts); +>setProperty(this, "parts", parts) : void +>setProperty : (obj: T, key: K, value: T[K]) => void +>this : this +>"parts" : "parts" +>parts : number + } + getParts() { +>getParts : () => this["parts"] + + return getProperty(this, "parts") +>getProperty(this, "parts") : this["parts"] +>getProperty : (obj: T, key: K) => T[K] +>this : this +>"parts" : "parts" + } +} + +// Modified repro from #12544 + +function path(obj: T, key1: K1): T[K1]; +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>T : T +>K1 : K1 +>T : T +>obj : T +>T : T +>key1 : K1 +>K1 : K1 +>T : T +>K1 : K1 + +function path(obj: T, key1: K1, key2: K2): T[K1][K2]; +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>T : T +>K1 : K1 +>T : T +>K2 : K2 +>T : T +>K1 : K1 +>obj : T +>T : T +>key1 : K1 +>K1 : K1 +>key2 : K2 +>K2 : K2 +>T : T +>K1 : K1 +>K2 : K2 + +function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>T : T +>K1 : K1 +>T : T +>K2 : K2 +>T : T +>K1 : K1 +>K3 : K3 +>T : T +>K1 : K1 +>K2 : K2 +>obj : T +>T : T +>key1 : K1 +>K1 : K1 +>key2 : K2 +>K2 : K2 +>key3 : K3 +>K3 : K3 +>T : T +>K1 : K1 +>K2 : K2 +>K3 : K3 + +function path(obj: any, ...keys: (string | number)[]): any; +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>obj : any +>keys : (string | number)[] + +function path(obj: any, ...keys: (string | number)[]): any { +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>obj : any +>keys : (string | number)[] + + let result = obj; +>result : any +>obj : any + + for (let k of keys) { +>k : string | number +>keys : (string | number)[] + + result = result[k]; +>result = result[k] : any +>result : any +>result[k] : any +>result : any +>k : string | number + } + return result; +>result : any +} + +type Thing = { +>Thing : Thing + + a: { x: number, y: string }, +>a : { x: number; y: string; } +>x : number +>y : string + + b: boolean +>b : boolean + +}; + + +function f1(thing: Thing) { +>f1 : (thing: Thing) => void +>thing : Thing +>Thing : Thing + + let x1 = path(thing, 'a'); // { x: number, y: string } +>x1 : { x: number; y: string; } +>path(thing, 'a') : { x: number; y: string; } +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>thing : Thing +>'a' : "a" + + let x2 = path(thing, 'a', 'y'); // string +>x2 : string +>path(thing, 'a', 'y') : string +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>thing : Thing +>'a' : "a" +>'y' : "y" + + let x3 = path(thing, 'b'); // boolean +>x3 : boolean +>path(thing, 'b') : boolean +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>thing : Thing +>'b' : "b" + + let x4 = path(thing, ...['a', 'x']); // any +>x4 : any +>path(thing, ...['a', 'x']) : any +>path : { (obj: T, key1: K1): T[K1]; (obj: T, key1: K1, key2: K2): T[K1][K2]; (obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; (obj: any, ...keys: (string | number)[]): any; } +>thing : Thing +>...['a', 'x'] : string +>['a', 'x'] : string[] +>'a' : "a" +>'x' : "x" +} + +// Repro from comment in #12114 + +const assignTo2 = (object: T, key1: K1, key2: K2) => +>assignTo2 : (object: T, key1: K1, key2: K2) => (value: T[K1][K2]) => T[K1][K2] +>(object: T, key1: K1, key2: K2) => (value: T[K1][K2]) => object[key1][key2] = value : (object: T, key1: K1, key2: K2) => (value: T[K1][K2]) => T[K1][K2] +>T : T +>K1 : K1 +>T : T +>K2 : K2 +>T : T +>K1 : K1 +>object : T +>T : T +>key1 : K1 +>K1 : K1 +>key2 : K2 +>K2 : K2 + + (value: T[K1][K2]) => object[key1][key2] = value; +>(value: T[K1][K2]) => object[key1][key2] = value : (value: T[K1][K2]) => T[K1][K2] +>value : T[K1][K2] +>T : T +>K1 : K1 +>K2 : K2 +>object[key1][key2] = value : T[K1][K2] +>object[key1][key2] : T[K1][K2] +>object[key1] : T[K1] +>object : T +>key1 : K1 +>key2 : K2 +>value : T[K1][K2] + +// Modified repro from #12573 + +declare function one(handler: (t: T) => void): T +>one : (handler: (t: T) => void) => T +>T : T +>handler : (t: T) => void +>t : T +>T : T +>T : T + +var empty = one(() => {}) // inferred as {}, expected +>empty : {} +>one(() => {}) : {} +>one : (handler: (t: T) => void) => T +>() => {} : () => void + +type Handlers = { [K in keyof T]: (t: T[K]) => void } +>Handlers : Handlers +>T : T +>K : K +>T : T +>t : T[K] +>T : T +>K : K + +declare function on(handlerHash: Handlers): T +>on : (handlerHash: Handlers) => T +>T : T +>handlerHash : Handlers +>Handlers : Handlers +>T : T +>T : T + +var hashOfEmpty1 = on({ test: () => {} }); // {} +>hashOfEmpty1 : {} +>on({ test: () => {} }) : {} +>on : (handlerHash: Handlers) => T +>{ test: () => {} } : { test: () => void; } +>test : () => void +>() => {} : () => void + +var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } +>hashOfEmpty2 : { test: boolean; } +>on({ test: (x: boolean) => {} }) : { test: boolean; } +>on : (handlerHash: Handlers) => T +>{ test: (x: boolean) => {} } : { test: (x: boolean) => void; } +>test : (x: boolean) => void +>(x: boolean) => {} : (x: boolean) => void +>x : boolean + +// Repro from #12624 + +interface Options1 { +>Options1 : Options1 +>Data : Data +>Computed : Computed + + data?: Data +>data : Data | undefined +>Data : Data + + computed?: Computed; +>computed : Computed | undefined +>Computed : Computed +} + +declare class Component1 { +>Component1 : Component1 +>Data : Data +>Computed : Computed + + constructor(options: Options1); +>options : Options1 +>Options1 : Options1 +>Data : Data +>Computed : Computed + + get(key: K): (Data & Computed)[K]; +>get : (key: K) => (Data & Computed)[K] +>K : K +>Data : Data +>Computed : Computed +>key : K +>K : K +>Data : Data +>Computed : Computed +>K : K +} + +let c1 = new Component1({ +>c1 : Component1<{ hello: string; }, {}> +>new Component1({ data: { hello: "" }}) : Component1<{ hello: string; }, {}> +>Component1 : typeof Component1 +>{ data: { hello: "" }} : { data: { hello: string; }; } + + data: { +>data : { hello: string; } +>{ hello: "" } : { hello: string; } + + hello: "" +>hello : string +>"" : "" + } +}); + +c1.get("hello"); +>c1.get("hello") : string +>c1.get : (key: K) => ({ hello: string; } & {})[K] +>c1 : Component1<{ hello: string; }, {}> +>get : (key: K) => ({ hello: string; } & {})[K] +>"hello" : "hello" + +// Repro from #12625 + +interface Options2 { +>Options2 : Options2 +>Data : Data +>Computed : Computed + + data?: Data +>data : Data | undefined +>Data : Data + + computed?: Computed; +>computed : Computed | undefined +>Computed : Computed +} + +declare class Component2 { +>Component2 : Component2 +>Data : Data +>Computed : Computed + + constructor(options: Options2); +>options : Options2 +>Options2 : Options2 +>Data : Data +>Computed : Computed + + get(key: K): (Data & Computed)[K]; +>get : (key: K) => (Data & Computed)[K] +>K : K +>Data : Data +>Computed : Computed +>key : K +>K : K +>Data : Data +>Computed : Computed +>K : K +} + +// Repro from #12641 + +interface R { +>R : R + + p: number; +>p : number +} + +function f(p: K) { +>f : (p: K) => void +>K : K +>R : R +>p : K +>K : K + + let a: any; +>a : any + + a[p].add; // any +>a[p].add : any +>a[p] : any +>a : any +>p : K +>add : any +} + +// Repro from #12651 + +type MethodDescriptor = { +>MethodDescriptor : MethodDescriptor + + name: string; +>name : string + + args: any[]; +>args : any[] + + returnValue: any; +>returnValue : any +} + +declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; +>dispatchMethod : (name: M["name"], args: M["args"]) => M["returnValue"] +>M : M +>MethodDescriptor : MethodDescriptor +>name : M["name"] +>M : M +>args : M["args"] +>M : M +>M : M + +type SomeMethodDescriptor = { +>SomeMethodDescriptor : SomeMethodDescriptor + + name: "someMethod"; +>name : "someMethod" + + args: [string, number]; +>args : [string, number] + + returnValue: string[]; +>returnValue : string[] +} + +let result = dispatchMethod("someMethod", ["hello", 35]); +>result : string[] +>dispatchMethod("someMethod", ["hello", 35]) : string[] +>dispatchMethod : (name: M["name"], args: M["args"]) => M["returnValue"] +>SomeMethodDescriptor : SomeMethodDescriptor +>"someMethod" : "someMethod" +>["hello", 35] : [string, number] +>"hello" : "hello" +>35 : 35 + diff --git a/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt b/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt new file mode 100644 index 00000000000..1e88e2abc43 --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt @@ -0,0 +1,162 @@ +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(10,18): error TS2304: Cannot find name 'K0'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(20,18): error TS2339: Property 'foo' does not exist on type 'Shape'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(21,18): error TS2339: Property 'foo' does not exist on type 'Shape'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(22,18): error TS2538: Type 'any' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(23,18): error TS2537: Type 'Shape' has no matching index signature for type 'string'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(24,18): error TS2537: Type 'Shape' has no matching index signature for type 'number'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(25,18): error TS2538: Type 'boolean' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(26,18): error TS2538: Type 'void' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(27,18): error TS2538: Type 'undefined' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(28,18): error TS2538: Type '{ x: string; }' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(29,18): error TS2537: Type 'Shape' has no matching index signature for type 'string'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(30,18): error TS2538: Type 'string & number' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(31,18): error TS2537: Type 'Shape' has no matching index signature for type 'string'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(35,21): error TS2537: Type 'string[]' has no matching index signature for type 'string'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(36,21): error TS2538: Type 'boolean' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(41,31): error TS2538: Type 'boolean' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(46,16): error TS2538: Type 'boolean' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(63,33): error TS2345: Argument of type '"size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(64,33): error TS2345: Argument of type '"name" | "size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. + Type '"size"' is not assignable to type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(66,24): error TS2345: Argument of type '"size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(67,24): error TS2345: Argument of type '"name" | "size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. + Type '"size"' is not assignable to type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(72,5): error TS2536: Type 'keyof (T & U)' cannot be used to index type 'T | U'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(76,5): error TS2322: Type 'T | U' is not assignable to type 'T & U'. + Type 'T' is not assignable to type 'T & U'. + Type 'T' is not assignable to type 'U'. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(77,5): error TS2322: Type 'keyof (T & U)' is not assignable to type 'keyof (T | U)'. + + +==== tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts (24 errors) ==== + class Shape { + name: string; + width: number; + height: number; + visible: boolean; + } + + type Dictionary = { [x: string]: T }; + + type T00 = keyof K0; // Error + ~~ +!!! error TS2304: Cannot find name 'K0'. + + type T01 = keyof Object; + type T02 = keyof keyof Object; + type T03 = keyof keyof keyof Object; + type T04 = keyof keyof keyof keyof Object; + type T05 = keyof keyof keyof keyof keyof Object; + type T06 = keyof keyof keyof keyof keyof keyof Object; + + type T10 = Shape["name"]; + type T11 = Shape["foo"]; // Error + ~~~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Shape'. + type T12 = Shape["name" | "foo"]; // Error + ~~~~~~~~~~~~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Shape'. + type T13 = Shape[any]; // Error + ~~~ +!!! error TS2538: Type 'any' cannot be used as an index type. + type T14 = Shape[string]; // Error + ~~~~~~ +!!! error TS2537: Type 'Shape' has no matching index signature for type 'string'. + type T15 = Shape[number]; // Error + ~~~~~~ +!!! error TS2537: Type 'Shape' has no matching index signature for type 'number'. + type T16 = Shape[boolean]; // Error + ~~~~~~~ +!!! error TS2538: Type 'boolean' cannot be used as an index type. + type T17 = Shape[void]; // Error + ~~~~ +!!! error TS2538: Type 'void' cannot be used as an index type. + type T18 = Shape[undefined]; // Error + ~~~~~~~~~ +!!! error TS2538: Type 'undefined' cannot be used as an index type. + type T19 = Shape[{ x: string }]; // Error + ~~~~~~~~~~~~~ +!!! error TS2538: Type '{ x: string; }' cannot be used as an index type. + type T20 = Shape[string | number]; // Error + ~~~~~~~~~~~~~~~ +!!! error TS2537: Type 'Shape' has no matching index signature for type 'string'. + type T21 = Shape[string & number]; // Error + ~~~~~~~~~~~~~~~ +!!! error TS2538: Type 'string & number' cannot be used as an index type. + type T22 = Shape[string | boolean]; // Error + ~~~~~~~~~~~~~~~~ +!!! error TS2537: Type 'Shape' has no matching index signature for type 'string'. + + type T30 = string[]["length"]; + type T31 = string[][number]; + type T32 = string[][string]; // Error + ~~~~~~ +!!! error TS2537: Type 'string[]' has no matching index signature for type 'string'. + type T33 = string[][boolean]; // Error + ~~~~~~~ +!!! error TS2538: Type 'boolean' cannot be used as an index type. + + type T40 = Dictionary[any]; + type T41 = Dictionary[number]; + type T42 = Dictionary[string]; + type T43 = Dictionary[boolean]; // Error + ~~~~~~~ +!!! error TS2538: Type 'boolean' cannot be used as an index type. + + type T50 = any[any]; + type T51 = any[number]; + type T52 = any[string]; + type T53 = any[boolean]; // Error + ~~~~~~~ +!!! error TS2538: Type 'boolean' cannot be used as an index type. + + type T60 = {}["toString"]; + type T61 = []["toString"]; + + declare let cond: boolean; + + function getProperty(obj: T, key: K) { + return obj[key]; + } + + function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; + } + + function f10(shape: Shape) { + let x1 = getProperty(shape, "name"); + let x2 = getProperty(shape, "size"); // Error + ~~~~~~ +!!! error TS2345: Argument of type '"size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. + let x3 = getProperty(shape, cond ? "name" : "size"); // Error + ~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '"name" | "size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. +!!! error TS2345: Type '"size"' is not assignable to type '"name" | "width" | "height" | "visible"'. + setProperty(shape, "name", "rectangle"); + setProperty(shape, "size", 10); // Error + ~~~~~~ +!!! error TS2345: Argument of type '"size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. + setProperty(shape, cond ? "name" : "size", 10); // Error + ~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '"name" | "size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. +!!! error TS2345: Type '"size"' is not assignable to type '"name" | "width" | "height" | "visible"'. + } + + function f20(k1: keyof (T | U), k2: keyof (T & U), o1: T | U, o2: T & U) { + o1[k1]; + o1[k2]; // Error + ~~~~~~ +!!! error TS2536: Type 'keyof (T & U)' cannot be used to index type 'T | U'. + o2[k1]; + o2[k2]; + o1 = o2; + o2 = o1; // Error + ~~ +!!! error TS2322: Type 'T | U' is not assignable to type 'T & U'. +!!! error TS2322: Type 'T' is not assignable to type 'T & U'. +!!! error TS2322: Type 'T' is not assignable to type 'U'. + k1 = k2; // Error + ~~ +!!! error TS2322: Type 'keyof (T & U)' is not assignable to type 'keyof (T | U)'. + k2 = k1; + } \ No newline at end of file diff --git a/tests/baselines/reference/keyofAndIndexedAccessErrors.js b/tests/baselines/reference/keyofAndIndexedAccessErrors.js new file mode 100644 index 00000000000..556aca12971 --- /dev/null +++ b/tests/baselines/reference/keyofAndIndexedAccessErrors.js @@ -0,0 +1,111 @@ +//// [keyofAndIndexedAccessErrors.ts] +class Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +type Dictionary = { [x: string]: T }; + +type T00 = keyof K0; // Error + +type T01 = keyof Object; +type T02 = keyof keyof Object; +type T03 = keyof keyof keyof Object; +type T04 = keyof keyof keyof keyof Object; +type T05 = keyof keyof keyof keyof keyof Object; +type T06 = keyof keyof keyof keyof keyof keyof Object; + +type T10 = Shape["name"]; +type T11 = Shape["foo"]; // Error +type T12 = Shape["name" | "foo"]; // Error +type T13 = Shape[any]; // Error +type T14 = Shape[string]; // Error +type T15 = Shape[number]; // Error +type T16 = Shape[boolean]; // Error +type T17 = Shape[void]; // Error +type T18 = Shape[undefined]; // Error +type T19 = Shape[{ x: string }]; // Error +type T20 = Shape[string | number]; // Error +type T21 = Shape[string & number]; // Error +type T22 = Shape[string | boolean]; // Error + +type T30 = string[]["length"]; +type T31 = string[][number]; +type T32 = string[][string]; // Error +type T33 = string[][boolean]; // Error + +type T40 = Dictionary[any]; +type T41 = Dictionary[number]; +type T42 = Dictionary[string]; +type T43 = Dictionary[boolean]; // Error + +type T50 = any[any]; +type T51 = any[number]; +type T52 = any[string]; +type T53 = any[boolean]; // Error + +type T60 = {}["toString"]; +type T61 = []["toString"]; + +declare let cond: boolean; + +function getProperty(obj: T, key: K) { + return obj[key]; +} + +function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; +} + +function f10(shape: Shape) { + let x1 = getProperty(shape, "name"); + let x2 = getProperty(shape, "size"); // Error + let x3 = getProperty(shape, cond ? "name" : "size"); // Error + setProperty(shape, "name", "rectangle"); + setProperty(shape, "size", 10); // Error + setProperty(shape, cond ? "name" : "size", 10); // Error +} + +function f20(k1: keyof (T | U), k2: keyof (T & U), o1: T | U, o2: T & U) { + o1[k1]; + o1[k2]; // Error + o2[k1]; + o2[k2]; + o1 = o2; + o2 = o1; // Error + k1 = k2; // Error + k2 = k1; +} + +//// [keyofAndIndexedAccessErrors.js] +var Shape = (function () { + function Shape() { + } + return Shape; +}()); +function getProperty(obj, key) { + return obj[key]; +} +function setProperty(obj, key, value) { + obj[key] = value; +} +function f10(shape) { + var x1 = getProperty(shape, "name"); + var x2 = getProperty(shape, "size"); // Error + var x3 = getProperty(shape, cond ? "name" : "size"); // Error + setProperty(shape, "name", "rectangle"); + setProperty(shape, "size", 10); // Error + setProperty(shape, cond ? "name" : "size", 10); // Error +} +function f20(k1, k2, o1, o2) { + o1[k1]; + o1[k2]; // Error + o2[k1]; + o2[k2]; + o1 = o2; + o2 = o1; // Error + k1 = k2; // Error + k2 = k1; +} diff --git a/tests/baselines/reference/keyofIsLiteralContexualType.errors.txt b/tests/baselines/reference/keyofIsLiteralContexualType.errors.txt new file mode 100644 index 00000000000..c19a13209c9 --- /dev/null +++ b/tests/baselines/reference/keyofIsLiteralContexualType.errors.txt @@ -0,0 +1,28 @@ +tests/cases/compiler/keyofIsLiteralContexualType.ts(5,9): error TS2322: Type '("a" | "b" | "c")[]' is not assignable to type 'keyof T[]'. + Type '"a" | "b" | "c"' is not assignable to type 'keyof T'. + Type '"c"' is not assignable to type 'keyof T'. + Type '"c"' is not assignable to type '"a" | "b"'. +tests/cases/compiler/keyofIsLiteralContexualType.ts(13,11): error TS2339: Property 'b' does not exist on type 'Pick<{ a: number; b: number; c: number; }, "a" | "c">'. + + +==== tests/cases/compiler/keyofIsLiteralContexualType.ts (2 errors) ==== + // keyof T is a literal contextual type + + function foo() { + let a: (keyof T)[] = ["a", "b"]; + let b: (keyof T)[] = ["a", "b", "c"]; + ~ +!!! error TS2322: Type '("a" | "b" | "c")[]' is not assignable to type 'keyof T[]'. +!!! error TS2322: Type '"a" | "b" | "c"' is not assignable to type 'keyof T'. +!!! error TS2322: Type '"c"' is not assignable to type 'keyof T'. +!!! error TS2322: Type '"c"' is not assignable to type '"a" | "b"'. + } + + // Repro from #12455 + + declare function pick(obj: T, propNames: K[]): Pick; + + let x = pick({ a: 10, b: 20, c: 30 }, ["a", "c"]); + let b = x.b; // Error + ~ +!!! error TS2339: Property 'b' does not exist on type 'Pick<{ a: number; b: number; c: number; }, "a" | "c">'. \ No newline at end of file diff --git a/tests/baselines/reference/keyofIsLiteralContexualType.js b/tests/baselines/reference/keyofIsLiteralContexualType.js new file mode 100644 index 00000000000..5325b976174 --- /dev/null +++ b/tests/baselines/reference/keyofIsLiteralContexualType.js @@ -0,0 +1,23 @@ +//// [keyofIsLiteralContexualType.ts] +// keyof T is a literal contextual type + +function foo() { + let a: (keyof T)[] = ["a", "b"]; + let b: (keyof T)[] = ["a", "b", "c"]; +} + +// Repro from #12455 + +declare function pick(obj: T, propNames: K[]): Pick; + +let x = pick({ a: 10, b: 20, c: 30 }, ["a", "c"]); +let b = x.b; // Error + +//// [keyofIsLiteralContexualType.js] +// keyof T is a literal contextual type +function foo() { + var a = ["a", "b"]; + var b = ["a", "b", "c"]; +} +var x = pick({ a: 10, b: 20, c: 30 }, ["a", "c"]); +var b = x.b; // Error diff --git a/tests/baselines/reference/keywordField.js b/tests/baselines/reference/keywordField.js index 581d5afa14a..a146cffade8 100644 --- a/tests/baselines/reference/keywordField.js +++ b/tests/baselines/reference/keywordField.js @@ -12,7 +12,7 @@ var q = a["if"]; //// [keywordField.js] var obj = {}; -obj.if = 1; -var a = { if: "test" }; -var n = a.if; +obj["if"] = 1; +var a = { "if": "test" }; +var n = a["if"]; var q = a["if"]; diff --git a/tests/baselines/reference/keywordInJsxIdentifier.js b/tests/baselines/reference/keywordInJsxIdentifier.js index 6009e1980e6..d9c3b51e9a3 100644 --- a/tests/baselines/reference/keywordInJsxIdentifier.js +++ b/tests/baselines/reference/keywordInJsxIdentifier.js @@ -9,6 +9,6 @@ declare var React: any; //// [keywordInJsxIdentifier.js] React.createElement("foo", { "class-id": true }); -React.createElement("foo", { class: true }); +React.createElement("foo", { "class": true }); React.createElement("foo", { "class-id": "1" }); -React.createElement("foo", { class: "1" }); +React.createElement("foo", { "class": "1" }); diff --git a/tests/baselines/reference/library-reference-1.trace.json b/tests/baselines/reference/library-reference-1.trace.json index 71557236240..d13ac9da455 100644 --- a/tests/baselines/reference/library-reference-1.trace.json +++ b/tests/baselines/reference/library-reference-1.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path 'types'", "File 'types/jquery/package.json' does not exist.", "File 'types/jquery/index.d.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'jquery' was successfully resolved to 'types/jquery/index.d.ts', primary: true. ========", + "Resolving real path for 'types/jquery/index.d.ts', result '/src/types/jquery/index.d.ts'", + "======== Type reference directive 'jquery' was successfully resolved to '/src/types/jquery/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/src/__inferred type names__.ts', root directory 'types'. ========", "Resolving with primary search path 'types'", "File 'types/jquery/package.json' does not exist.", "File 'types/jquery/index.d.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'jquery' was successfully resolved to 'types/jquery/index.d.ts', primary: true. ========" + "Resolving real path for 'types/jquery/index.d.ts', result '/src/types/jquery/index.d.ts'", + "======== Type reference directive 'jquery' was successfully resolved to '/src/types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-10.trace.json b/tests/baselines/reference/library-reference-10.trace.json index f4df00fa52d..760f0c5ec82 100644 --- a/tests/baselines/reference/library-reference-10.trace.json +++ b/tests/baselines/reference/library-reference-10.trace.json @@ -4,11 +4,13 @@ "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'jquery' was successfully resolved to 'types/jquery/jquery.d.ts', primary: true. ========", + "Resolving real path for 'types/jquery/jquery.d.ts', result '/foo/types/jquery/jquery.d.ts'", + "======== Type reference directive 'jquery' was successfully resolved to '/foo/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/foo/__inferred type names__.ts', root directory './types'. ========", "Resolving with primary search path './types'", "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'jquery' was successfully resolved to 'types/jquery/jquery.d.ts', primary: true. ========" + "Resolving real path for 'types/jquery/jquery.d.ts', result '/foo/types/jquery/jquery.d.ts'", + "======== Type reference directive 'jquery' was successfully resolved to '/foo/types/jquery/jquery.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-11.trace.json b/tests/baselines/reference/library-reference-11.trace.json index e0af1e39c5a..78ac53013f7 100644 --- a/tests/baselines/reference/library-reference-11.trace.json +++ b/tests/baselines/reference/library-reference-11.trace.json @@ -2,20 +2,16 @@ "======== Resolving type reference directive 'jquery', containing file '/a/b/consumer.ts', root directory not set. ========", "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'", - "File '/a/b/node_modules/jquery.ts' does not exist.", "File '/a/b/node_modules/jquery.d.ts' does not exist.", "File '/a/b/node_modules/jquery/package.json' does not exist.", - "File '/a/b/node_modules/jquery/index.ts' does not exist.", "File '/a/b/node_modules/jquery/index.d.ts' does not exist.", - "File '/a/b/node_modules/@types/jquery.ts' does not exist.", "File '/a/b/node_modules/@types/jquery.d.ts' does not exist.", "File '/a/b/node_modules/@types/jquery/package.json' does not exist.", - "File '/a/b/node_modules/@types/jquery/index.ts' does not exist.", "File '/a/b/node_modules/@types/jquery/index.d.ts' does not exist.", - "File '/a/node_modules/jquery.ts' does not exist.", "File '/a/node_modules/jquery.d.ts' does not exist.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", "File '/a/node_modules/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/node_modules/jquery/jquery.d.ts', result '/a/node_modules/jquery/jquery.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/a/node_modules/jquery/jquery.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-12.trace.json b/tests/baselines/reference/library-reference-12.trace.json index 2cdf1f5f20a..6e09c7a3f04 100644 --- a/tests/baselines/reference/library-reference-12.trace.json +++ b/tests/baselines/reference/library-reference-12.trace.json @@ -2,20 +2,16 @@ "======== Resolving type reference directive 'jquery', containing file '/a/b/consumer.ts', root directory not set. ========", "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'", - "File '/a/b/node_modules/jquery.ts' does not exist.", "File '/a/b/node_modules/jquery.d.ts' does not exist.", "File '/a/b/node_modules/jquery/package.json' does not exist.", - "File '/a/b/node_modules/jquery/index.ts' does not exist.", "File '/a/b/node_modules/jquery/index.d.ts' does not exist.", - "File '/a/b/node_modules/@types/jquery.ts' does not exist.", "File '/a/b/node_modules/@types/jquery.d.ts' does not exist.", "File '/a/b/node_modules/@types/jquery/package.json' does not exist.", - "File '/a/b/node_modules/@types/jquery/index.ts' does not exist.", "File '/a/b/node_modules/@types/jquery/index.d.ts' does not exist.", - "File '/a/node_modules/jquery.ts' does not exist.", "File '/a/node_modules/jquery.d.ts' does not exist.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "'package.json' has 'types' field 'dist/jquery.d.ts' that references '/a/node_modules/jquery/dist/jquery.d.ts'.", "File '/a/node_modules/jquery/dist/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/node_modules/jquery/dist/jquery.d.ts', result '/a/node_modules/jquery/dist/jquery.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/a/node_modules/jquery/dist/jquery.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-13.trace.json b/tests/baselines/reference/library-reference-13.trace.json index a23f0ef0ca5..338cefbc47e 100644 --- a/tests/baselines/reference/library-reference-13.trace.json +++ b/tests/baselines/reference/library-reference-13.trace.json @@ -1,7 +1,8 @@ [ - "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/a/types'. ========", + "======== Resolving type reference directive 'jquery', containing file '/a/__inferred type names__.ts', root directory '/a/types'. ========", "Resolving with primary search path '/a/types'", "File '/a/types/jquery/package.json' does not exist.", "File '/a/types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/types/jquery/index.d.ts', result '/a/types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/a/types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-14.trace.json b/tests/baselines/reference/library-reference-14.trace.json index fb3a2bb7da4..338cefbc47e 100644 --- a/tests/baselines/reference/library-reference-14.trace.json +++ b/tests/baselines/reference/library-reference-14.trace.json @@ -3,5 +3,6 @@ "Resolving with primary search path '/a/types'", "File '/a/types/jquery/package.json' does not exist.", "File '/a/types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/a/types/jquery/index.d.ts', result '/a/types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/a/types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-15.trace.json b/tests/baselines/reference/library-reference-15.trace.json index e23517976b0..6d8b5cf1408 100644 --- a/tests/baselines/reference/library-reference-15.trace.json +++ b/tests/baselines/reference/library-reference-15.trace.json @@ -3,5 +3,6 @@ "Resolving with primary search path 'types'", "File 'types/jquery/package.json' does not exist.", "File 'types/jquery/index.d.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'jquery' was successfully resolved to 'types/jquery/index.d.ts', primary: true. ========" + "Resolving real path for 'types/jquery/index.d.ts', result '/a/types/jquery/index.d.ts'", + "======== Type reference directive 'jquery' was successfully resolved to '/a/types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-2.trace.json b/tests/baselines/reference/library-reference-2.trace.json index 64cdd809183..8837f2c9cb1 100644 --- a/tests/baselines/reference/library-reference-2.trace.json +++ b/tests/baselines/reference/library-reference-2.trace.json @@ -4,11 +4,13 @@ "Found 'package.json' at '/types/jquery/package.json'.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "File '/types/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/jquery/jquery.d.ts', result '/types/jquery/jquery.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file 'test/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "Found 'package.json' at '/types/jquery/package.json'.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "File '/types/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/jquery/jquery.d.ts', result '/types/jquery/jquery.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/types/jquery/jquery.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-3.trace.json b/tests/baselines/reference/library-reference-3.trace.json index 419fe6d055d..d672eb50de8 100644 --- a/tests/baselines/reference/library-reference-3.trace.json +++ b/tests/baselines/reference/library-reference-3.trace.json @@ -2,10 +2,9 @@ "======== Resolving type reference directive 'jquery', containing file '/src/consumer.ts', root directory not set. ========", "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/jquery.ts' does not exist.", "File '/src/node_modules/jquery.d.ts' does not exist.", "File '/src/node_modules/jquery/package.json' does not exist.", - "File '/src/node_modules/jquery/index.ts' does not exist.", "File '/src/node_modules/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/src/node_modules/jquery/index.d.ts', result '/src/node_modules/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/src/node_modules/jquery/index.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-4.trace.json b/tests/baselines/reference/library-reference-4.trace.json index 5df7320d322..b47ba1065f5 100644 --- a/tests/baselines/reference/library-reference-4.trace.json +++ b/tests/baselines/reference/library-reference-4.trace.json @@ -4,63 +4,51 @@ "File '/src/foo/package.json' does not exist.", "File '/src/foo/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/foo.ts' does not exist.", "File '/src/node_modules/foo.d.ts' does not exist.", "File '/src/node_modules/foo/package.json' does not exist.", - "File '/src/node_modules/foo/index.ts' does not exist.", "File '/src/node_modules/foo/index.d.ts' does not exist.", - "File '/src/node_modules/@types/foo.ts' does not exist.", "File '/src/node_modules/@types/foo.d.ts' does not exist.", "File '/src/node_modules/@types/foo/package.json' does not exist.", - "File '/src/node_modules/@types/foo/index.ts' does not exist.", "File '/src/node_modules/@types/foo/index.d.ts' does not exist.", - "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.d.ts' does not exist.", "File '/node_modules/foo/package.json' does not exist.", - "File '/node_modules/foo/index.ts' does not exist.", "File '/node_modules/foo/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/foo/index.d.ts', result '/node_modules/foo/index.d.ts'", "======== Type reference directive 'foo' was successfully resolved to '/node_modules/foo/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'bar', containing file '/src/root.ts', root directory '/src'. ========", "Resolving with primary search path '/src'", "File '/src/bar/package.json' does not exist.", "File '/src/bar/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/bar.ts' does not exist.", "File '/src/node_modules/bar.d.ts' does not exist.", "File '/src/node_modules/bar/package.json' does not exist.", - "File '/src/node_modules/bar/index.ts' does not exist.", "File '/src/node_modules/bar/index.d.ts' does not exist.", - "File '/src/node_modules/@types/bar.ts' does not exist.", "File '/src/node_modules/@types/bar.d.ts' does not exist.", "File '/src/node_modules/@types/bar/package.json' does not exist.", - "File '/src/node_modules/@types/bar/index.ts' does not exist.", "File '/src/node_modules/@types/bar/index.d.ts' does not exist.", - "File '/node_modules/bar.ts' does not exist.", "File '/node_modules/bar.d.ts' does not exist.", "File '/node_modules/bar/package.json' does not exist.", - "File '/node_modules/bar/index.ts' does not exist.", "File '/node_modules/bar/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/bar/index.d.ts', result '/node_modules/bar/index.d.ts'", "======== Type reference directive 'bar' was successfully resolved to '/node_modules/bar/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'alpha', containing file '/node_modules/foo/index.d.ts', root directory '/src'. ========", "Resolving with primary search path '/src'", "File '/src/alpha/package.json' does not exist.", "File '/src/alpha/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/node_modules/foo'", - "File '/node_modules/foo/node_modules/alpha.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha.d.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha/package.json' does not exist.", - "File '/node_modules/foo/node_modules/alpha/index.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/foo/node_modules/alpha/index.d.ts', result '/node_modules/foo/node_modules/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/foo/node_modules/alpha/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'alpha', containing file '/node_modules/bar/index.d.ts', root directory '/src'. ========", "Resolving with primary search path '/src'", "File '/src/alpha/package.json' does not exist.", "File '/src/alpha/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/node_modules/bar'", - "File '/node_modules/bar/node_modules/alpha.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha.d.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha/package.json' does not exist.", - "File '/node_modules/bar/node_modules/alpha/index.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/bar/node_modules/alpha/index.d.ts', result '/node_modules/bar/node_modules/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/bar/node_modules/alpha/index.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-5.trace.json b/tests/baselines/reference/library-reference-5.trace.json index 9b8705f0323..8f548e04d10 100644 --- a/tests/baselines/reference/library-reference-5.trace.json +++ b/tests/baselines/reference/library-reference-5.trace.json @@ -4,63 +4,51 @@ "File 'types/foo/package.json' does not exist.", "File 'types/foo/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/foo.ts' does not exist.", "File '/src/node_modules/foo.d.ts' does not exist.", "File '/src/node_modules/foo/package.json' does not exist.", - "File '/src/node_modules/foo/index.ts' does not exist.", "File '/src/node_modules/foo/index.d.ts' does not exist.", - "File '/src/node_modules/@types/foo.ts' does not exist.", "File '/src/node_modules/@types/foo.d.ts' does not exist.", "File '/src/node_modules/@types/foo/package.json' does not exist.", - "File '/src/node_modules/@types/foo/index.ts' does not exist.", "File '/src/node_modules/@types/foo/index.d.ts' does not exist.", - "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.d.ts' does not exist.", "File '/node_modules/foo/package.json' does not exist.", - "File '/node_modules/foo/index.ts' does not exist.", "File '/node_modules/foo/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/foo/index.d.ts', result '/node_modules/foo/index.d.ts'", "======== Type reference directive 'foo' was successfully resolved to '/node_modules/foo/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'bar', containing file '/src/root.ts', root directory 'types'. ========", "Resolving with primary search path 'types'", "File 'types/bar/package.json' does not exist.", "File 'types/bar/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/bar.ts' does not exist.", "File '/src/node_modules/bar.d.ts' does not exist.", "File '/src/node_modules/bar/package.json' does not exist.", - "File '/src/node_modules/bar/index.ts' does not exist.", "File '/src/node_modules/bar/index.d.ts' does not exist.", - "File '/src/node_modules/@types/bar.ts' does not exist.", "File '/src/node_modules/@types/bar.d.ts' does not exist.", "File '/src/node_modules/@types/bar/package.json' does not exist.", - "File '/src/node_modules/@types/bar/index.ts' does not exist.", "File '/src/node_modules/@types/bar/index.d.ts' does not exist.", - "File '/node_modules/bar.ts' does not exist.", "File '/node_modules/bar.d.ts' does not exist.", "File '/node_modules/bar/package.json' does not exist.", - "File '/node_modules/bar/index.ts' does not exist.", "File '/node_modules/bar/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/bar/index.d.ts', result '/node_modules/bar/index.d.ts'", "======== Type reference directive 'bar' was successfully resolved to '/node_modules/bar/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'alpha', containing file '/node_modules/foo/index.d.ts', root directory 'types'. ========", "Resolving with primary search path 'types'", "File 'types/alpha/package.json' does not exist.", "File 'types/alpha/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/node_modules/foo'", - "File '/node_modules/foo/node_modules/alpha.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha.d.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha/package.json' does not exist.", - "File '/node_modules/foo/node_modules/alpha/index.ts' does not exist.", "File '/node_modules/foo/node_modules/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/foo/node_modules/alpha/index.d.ts', result '/node_modules/foo/node_modules/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/foo/node_modules/alpha/index.d.ts', primary: false. ========", "======== Resolving type reference directive 'alpha', containing file '/node_modules/bar/index.d.ts', root directory 'types'. ========", "Resolving with primary search path 'types'", "File 'types/alpha/package.json' does not exist.", "File 'types/alpha/index.d.ts' does not exist.", "Looking up in 'node_modules' folder, initial location '/node_modules/bar'", - "File '/node_modules/bar/node_modules/alpha.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha.d.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha/package.json' does not exist.", - "File '/node_modules/bar/node_modules/alpha/index.ts' does not exist.", "File '/node_modules/bar/node_modules/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/bar/node_modules/alpha/index.d.ts', result '/node_modules/bar/node_modules/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/bar/node_modules/alpha/index.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-6.trace.json b/tests/baselines/reference/library-reference-6.trace.json index fd83c1431b4..6ca81a6c418 100644 --- a/tests/baselines/reference/library-reference-6.trace.json +++ b/tests/baselines/reference/library-reference-6.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/alpha/package.json' does not exist.", "File '/node_modules/@types/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/alpha/index.d.ts', result '/node_modules/@types/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/@types/alpha/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'alpha', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/alpha/package.json' does not exist.", "File '/node_modules/@types/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/alpha/index.d.ts', result '/node_modules/@types/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/node_modules/@types/alpha/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-7.trace.json b/tests/baselines/reference/library-reference-7.trace.json index 419fe6d055d..d672eb50de8 100644 --- a/tests/baselines/reference/library-reference-7.trace.json +++ b/tests/baselines/reference/library-reference-7.trace.json @@ -2,10 +2,9 @@ "======== Resolving type reference directive 'jquery', containing file '/src/consumer.ts', root directory not set. ========", "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/src'", - "File '/src/node_modules/jquery.ts' does not exist.", "File '/src/node_modules/jquery.d.ts' does not exist.", "File '/src/node_modules/jquery/package.json' does not exist.", - "File '/src/node_modules/jquery/index.ts' does not exist.", "File '/src/node_modules/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/src/node_modules/jquery/index.d.ts', result '/src/node_modules/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/src/node_modules/jquery/index.d.ts', primary: false. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/library-reference-8.trace.json b/tests/baselines/reference/library-reference-8.trace.json index d34f206e581..905c3c2bb36 100644 --- a/tests/baselines/reference/library-reference-8.trace.json +++ b/tests/baselines/reference/library-reference-8.trace.json @@ -3,30 +3,36 @@ "Resolving with primary search path '/test/types'", "File '/test/types/alpha/package.json' does not exist.", "File '/test/types/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/alpha/index.d.ts', result '/test/types/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/test/types/alpha/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'beta', containing file '/test/foo.ts', root directory '/test/types'. ========", "Resolving with primary search path '/test/types'", "File '/test/types/beta/package.json' does not exist.", "File '/test/types/beta/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/beta/index.d.ts', result '/test/types/beta/index.d.ts'", "======== Type reference directive 'beta' was successfully resolved to '/test/types/beta/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'beta', containing file '/test/types/alpha/index.d.ts', root directory '/test/types'. ========", "Resolving with primary search path '/test/types'", "File '/test/types/beta/package.json' does not exist.", "File '/test/types/beta/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/beta/index.d.ts', result '/test/types/beta/index.d.ts'", "======== Type reference directive 'beta' was successfully resolved to '/test/types/beta/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'alpha', containing file '/test/types/beta/index.d.ts', root directory '/test/types'. ========", "Resolving with primary search path '/test/types'", "File '/test/types/alpha/package.json' does not exist.", "File '/test/types/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/alpha/index.d.ts', result '/test/types/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/test/types/alpha/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'alpha', containing file '/test/__inferred type names__.ts', root directory '/test/types'. ========", "Resolving with primary search path '/test/types'", "File '/test/types/alpha/package.json' does not exist.", "File '/test/types/alpha/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/alpha/index.d.ts', result '/test/types/alpha/index.d.ts'", "======== Type reference directive 'alpha' was successfully resolved to '/test/types/alpha/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'beta', containing file '/test/__inferred type names__.ts', root directory '/test/types'. ========", "Resolving with primary search path '/test/types'", "File '/test/types/beta/package.json' does not exist.", "File '/test/types/beta/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/test/types/beta/index.d.ts', result '/test/types/beta/index.d.ts'", "======== Type reference directive 'beta' was successfully resolved to '/test/types/beta/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/literalTypes1.types b/tests/baselines/reference/literalTypes1.types index faff485d45a..1baaad3ff88 100644 --- a/tests/baselines/reference/literalTypes1.types +++ b/tests/baselines/reference/literalTypes1.types @@ -129,7 +129,7 @@ function f4(x: 0 | 1 | true | string) { >"def" : "def" x; ->x : string +>x : "abc" | "def" break; case null: @@ -163,7 +163,7 @@ function f5(x: string | number | boolean) { >"abc" : "abc" x; ->x : string +>x : "abc" break; case 0: @@ -173,7 +173,7 @@ function f5(x: string | number | boolean) { >1 : 1 x; ->x : number +>x : 0 | 1 break; case true: @@ -190,7 +190,7 @@ function f5(x: string | number | boolean) { >123 : 123 x; ->x : string | number +>x : "hello" | 123 break; default: diff --git a/tests/baselines/reference/literalTypes3.js b/tests/baselines/reference/literalTypes3.js new file mode 100644 index 00000000000..1989bb1d5a1 --- /dev/null +++ b/tests/baselines/reference/literalTypes3.js @@ -0,0 +1,125 @@ +//// [literalTypes3.ts] + +function f1(s: string) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} + +function f2(s: string) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} + +function f3(s: string) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} + +function f4(x: number) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} + +function f5(x: number, y: 1 | 2) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} + +function f6(x: number, y: 1 | 2) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} + +//// [literalTypes3.js] +function f1(s) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} +function f2(s) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} +function f3(s) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} +function f4(x) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} +function f5(x, y) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} +function f6(x, y) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} +function f7(x, y) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} +function f8(x) { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} diff --git a/tests/baselines/reference/literalTypes3.symbols b/tests/baselines/reference/literalTypes3.symbols new file mode 100644 index 00000000000..6cc7ab007e6 --- /dev/null +++ b/tests/baselines/reference/literalTypes3.symbols @@ -0,0 +1,137 @@ +=== tests/cases/conformance/types/literal/literalTypes3.ts === + +function f1(s: string) { +>f1 : Symbol(f1, Decl(literalTypes3.ts, 0, 0)) +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + if (s === "foo") { +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + s; // "foo" +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + } + if (s === "foo" || s === "bar") { +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + s; // "foo" | "bar" +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + } +} + +function f2(s: string) { +>f2 : Symbol(f2, Decl(literalTypes3.ts, 8, 1)) +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + switch (s) { +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + case "foo": + case "bar": + s; // "foo" | "bar" +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + case "baz": + s; // "foo" | "bar" | "baz" +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + break; + default: + s; // string +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + } +} + +function f3(s: string) { +>f3 : Symbol(f3, Decl(literalTypes3.ts, 21, 1)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) + + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>undefined : Symbol(undefined) +} + +function f4(x: number) { +>f4 : Symbol(f4, Decl(literalTypes3.ts, 25, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + + if (x === 1 || x === 2) { +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + + return x; // 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + } + throw new Error(); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f5(x: number, y: 1 | 2) { +>f5 : Symbol(f5, Decl(literalTypes3.ts, 32, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 34, 22)) + + if (x === 0 || x === y) { +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 34, 22)) + + x; // 0 | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) + } +} + +function f6(x: number, y: 1 | 2) { +>f6 : Symbol(f6, Decl(literalTypes3.ts, 38, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 40, 22)) + + if (y === x || 0 === x) { +>y : Symbol(y, Decl(literalTypes3.ts, 40, 22)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) + + x; // 0 | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { +>f7 : Symbol(f7, Decl(literalTypes3.ts, 44, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 46, 38)) + + if (x === y) { +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 46, 38)) + + x; // "foo" | "bar" | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) + } +} + +function f8(x: number | "foo" | "bar") { +>f8 : Symbol(f8, Decl(literalTypes3.ts, 50, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + switch (x) { +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + case 1: + case 2: + x; // 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + break; + case "foo": + x; // "foo" +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + break; + default: + x; // number | "bar" +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + } +} diff --git a/tests/baselines/reference/literalTypes3.types b/tests/baselines/reference/literalTypes3.types new file mode 100644 index 00000000000..6161bc4b72a --- /dev/null +++ b/tests/baselines/reference/literalTypes3.types @@ -0,0 +1,177 @@ +=== tests/cases/conformance/types/literal/literalTypes3.ts === + +function f1(s: string) { +>f1 : (s: string) => void +>s : string + + if (s === "foo") { +>s === "foo" : boolean +>s : string +>"foo" : "foo" + + s; // "foo" +>s : "foo" + } + if (s === "foo" || s === "bar") { +>s === "foo" || s === "bar" : boolean +>s === "foo" : boolean +>s : string +>"foo" : "foo" +>s === "bar" : boolean +>s : string +>"bar" : "bar" + + s; // "foo" | "bar" +>s : "foo" | "bar" + } +} + +function f2(s: string) { +>f2 : (s: string) => void +>s : string + + switch (s) { +>s : string + + case "foo": +>"foo" : "foo" + + case "bar": +>"bar" : "bar" + + s; // "foo" | "bar" +>s : "foo" | "bar" + + case "baz": +>"baz" : "baz" + + s; // "foo" | "bar" | "baz" +>s : "foo" | "bar" | "baz" + + break; + default: + s; // string +>s : string + } +} + +function f3(s: string) { +>f3 : (s: string) => "foo" | "bar" | undefined +>s : string + + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +>s === "foo" || s === "bar" ? s : undefined : "foo" | "bar" | undefined +>s === "foo" || s === "bar" : boolean +>s === "foo" : boolean +>s : string +>"foo" : "foo" +>s === "bar" : boolean +>s : string +>"bar" : "bar" +>s : "foo" | "bar" +>undefined : undefined +} + +function f4(x: number) { +>f4 : (x: number) => 1 | 2 +>x : number + + if (x === 1 || x === 2) { +>x === 1 || x === 2 : boolean +>x === 1 : boolean +>x : number +>1 : 1 +>x === 2 : boolean +>x : number +>2 : 2 + + return x; // 1 | 2 +>x : 1 | 2 + } + throw new Error(); +>new Error() : Error +>Error : ErrorConstructor +} + +function f5(x: number, y: 1 | 2) { +>f5 : (x: number, y: 1 | 2) => void +>x : number +>y : 1 | 2 + + if (x === 0 || x === y) { +>x === 0 || x === y : boolean +>x === 0 : boolean +>x : number +>0 : 0 +>x === y : boolean +>x : number +>y : 1 | 2 + + x; // 0 | 1 | 2 +>x : 1 | 2 | 0 + } +} + +function f6(x: number, y: 1 | 2) { +>f6 : (x: number, y: 1 | 2) => void +>x : number +>y : 1 | 2 + + if (y === x || 0 === x) { +>y === x || 0 === x : boolean +>y === x : boolean +>y : 1 | 2 +>x : number +>0 === x : boolean +>0 : 0 +>x : number + + x; // 0 | 1 | 2 +>x : 1 | 2 | 0 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { +>f7 : (x: number | "foo" | "bar", y: string | 1 | 2) => void +>x : number | "foo" | "bar" +>y : string | 1 | 2 + + if (x === y) { +>x === y : boolean +>x : number | "foo" | "bar" +>y : string | 1 | 2 + + x; // "foo" | "bar" | 1 | 2 +>x : "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { +>f8 : (x: number | "foo" | "bar") => void +>x : number | "foo" | "bar" + + switch (x) { +>x : number | "foo" | "bar" + + case 1: +>1 : 1 + + case 2: +>2 : 2 + + x; // 1 | 2 +>x : 1 | 2 + + break; + case "foo": +>"foo" : "foo" + + x; // "foo" +>x : "foo" + + break; + default: + x; // number | "bar" +>x : number | "bar" + } +} diff --git a/tests/baselines/reference/literalTypesWidenInParameterPosition.errors.txt b/tests/baselines/reference/literalTypesWidenInParameterPosition.errors.txt new file mode 100644 index 00000000000..69d7196b978 --- /dev/null +++ b/tests/baselines/reference/literalTypesWidenInParameterPosition.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/types/literal/literalTypesWidenInParameterPosition.ts(4,9): error TS2322: Type '5' is not assignable to type '1'. + + +==== tests/cases/conformance/types/literal/literalTypesWidenInParameterPosition.ts (1 errors) ==== + class D { + readonly noWiden = 1 + constructor(readonly widen = 2) { + this.noWiden = 5; // error + ~~~~~~~~~~~~ +!!! error TS2322: Type '5' is not assignable to type '1'. + this.widen = 6; // ok + } + } + new D(7); // ok + \ No newline at end of file diff --git a/tests/baselines/reference/literalTypesWidenInParameterPosition.js b/tests/baselines/reference/literalTypesWidenInParameterPosition.js new file mode 100644 index 00000000000..2c1d165b6ec --- /dev/null +++ b/tests/baselines/reference/literalTypesWidenInParameterPosition.js @@ -0,0 +1,23 @@ +//// [literalTypesWidenInParameterPosition.ts] +class D { + readonly noWiden = 1 + constructor(readonly widen = 2) { + this.noWiden = 5; // error + this.widen = 6; // ok + } +} +new D(7); // ok + + +//// [literalTypesWidenInParameterPosition.js] +var D = (function () { + function D(widen) { + if (widen === void 0) { widen = 2; } + this.widen = widen; + this.noWiden = 1; + this.noWiden = 5; // error + this.widen = 6; // ok + } + return D; +}()); +new D(7); // ok diff --git a/tests/baselines/reference/literals.errors.txt b/tests/baselines/reference/literals.errors.txt index d43e89bb4db..6fa1d7d3abd 100644 --- a/tests/baselines/reference/literals.errors.txt +++ b/tests/baselines/reference/literals.errors.txt @@ -2,8 +2,8 @@ tests/cases/conformance/expressions/literals/literals.ts(9,10): error TS2362: Th tests/cases/conformance/expressions/literals/literals.ts(9,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/literals/literals.ts(10,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/expressions/literals/literals.ts(10,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/literals/literals.ts(20,9): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. -tests/cases/conformance/expressions/literals/literals.ts(25,10): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +tests/cases/conformance/expressions/literals/literals.ts(20,9): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o1'. +tests/cases/conformance/expressions/literals/literals.ts(25,9): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o3'. ==== tests/cases/conformance/expressions/literals/literals.ts (6 errors) ==== @@ -36,14 +36,14 @@ tests/cases/conformance/expressions/literals/literals.ts(25,10): error TS1085: O var n = 1e4; var n = 001; // Error in ES5 ~~~ -!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o1'. var n = 0x1; var n = -1; var n = -1.0; var n = -1e-4; var n = -003; // Error in ES5 - ~~~ -!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. + ~~~~ +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o3'. var n = -0x1; var s: string; diff --git a/tests/baselines/reference/localImportNameVsGlobalName.js b/tests/baselines/reference/localImportNameVsGlobalName.js index 45ecdc4745e..916bdcc2960 100644 --- a/tests/baselines/reference/localImportNameVsGlobalName.js +++ b/tests/baselines/reference/localImportNameVsGlobalName.js @@ -16,13 +16,13 @@ module App { //// [localImportNameVsGlobalName.js] var Keyboard; (function (Keyboard) { + var Key; (function (Key) { Key[Key["UP"] = 0] = "UP"; Key[Key["DOWN"] = 1] = "DOWN"; Key[Key["LEFT"] = 2] = "LEFT"; Key[Key["RIGHT"] = 3] = "RIGHT"; - })(Keyboard.Key || (Keyboard.Key = {})); - var Key = Keyboard.Key; + })(Key = Keyboard.Key || (Keyboard.Key = {})); })(Keyboard || (Keyboard = {})); var App; (function (App) { diff --git a/tests/baselines/reference/localRequireFunction.js b/tests/baselines/reference/localRequireFunction.js new file mode 100644 index 00000000000..1ae20821a07 --- /dev/null +++ b/tests/baselines/reference/localRequireFunction.js @@ -0,0 +1,15 @@ +//// [app.js] + +function require(a) { + return a; +} + +const fs = require("fs"); +const text = fs.readFileSync("/a/b/c"); + +//// [app.js] +function require(a) { + return a; +} +var fs = require("fs"); +var text = fs.readFileSync("/a/b/c"); diff --git a/tests/baselines/reference/localRequireFunction.symbols b/tests/baselines/reference/localRequireFunction.symbols new file mode 100644 index 00000000000..b977328f0ef --- /dev/null +++ b/tests/baselines/reference/localRequireFunction.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/app.js === + +function require(a) { +>require : Symbol(require, Decl(app.js, 0, 0)) +>a : Symbol(a, Decl(app.js, 1, 17)) + + return a; +>a : Symbol(a, Decl(app.js, 1, 17)) +} + +const fs = require("fs"); +>fs : Symbol(fs, Decl(app.js, 5, 5)) +>require : Symbol(require, Decl(app.js, 0, 0)) + +const text = fs.readFileSync("/a/b/c"); +>text : Symbol(text, Decl(app.js, 6, 5)) +>fs : Symbol(fs, Decl(app.js, 5, 5)) + diff --git a/tests/baselines/reference/localRequireFunction.types b/tests/baselines/reference/localRequireFunction.types new file mode 100644 index 00000000000..4b5c7578cd9 --- /dev/null +++ b/tests/baselines/reference/localRequireFunction.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/app.js === + +function require(a) { +>require : (a: any) => any +>a : any + + return a; +>a : any +} + +const fs = require("fs"); +>fs : any +>require("fs") : any +>require : (a: any) => any +>"fs" : "fs" + +const text = fs.readFileSync("/a/b/c"); +>text : any +>fs.readFileSync("/a/b/c") : any +>fs.readFileSync : any +>fs : any +>readFileSync : any +>"/a/b/c" : "/a/b/c" + diff --git a/tests/baselines/reference/mappedTypeErrors.errors.txt b/tests/baselines/reference/mappedTypeErrors.errors.txt new file mode 100644 index 00000000000..94644a96af9 --- /dev/null +++ b/tests/baselines/reference/mappedTypeErrors.errors.txt @@ -0,0 +1,272 @@ +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(20,20): error TS2313: Type parameter 'P' has a circular constraint. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(21,20): error TS2322: Type 'number' is not assignable to type 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(22,20): error TS2322: Type 'Date' is not assignable to type 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(23,19): error TS2344: Type 'Date' does not satisfy the constraint 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(26,24): error TS2344: Type '"foo"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(27,24): error TS2344: Type '"name" | "foo"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + Type '"foo"' is not assignable to type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(29,24): error TS2344: Type '"x" | "y"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + Type '"x"' is not assignable to type '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(31,24): error TS2344: Type 'undefined' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(34,24): error TS2344: Type 'T' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + Type 'T' is not assignable to type '"visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(38,24): error TS2344: Type 'T' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + Type 'string | number' is not assignable to type '"name" | "width" | "height" | "visible"'. + Type 'string' is not assignable to type '"name" | "width" | "height" | "visible"'. + Type 'T' is not assignable to type '"visible"'. + Type 'string | number' is not assignable to type '"visible"'. + Type 'string' is not assignable to type '"visible"'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(60,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ [P in keyof T]?: T[P] | undefined; }'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(61,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ readonly [P in keyof T]: T[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(62,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ readonly [P in keyof T]?: T[P] | undefined; }'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(67,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ [P in keyof T]: T[P][]; }'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(76,45): error TS2345: Argument of type '{ x: number; }' is not assignable to parameter of type 'Readonly<{ x: number; y: number; }>'. + Property 'y' is missing in type '{ x: number; }'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(78,59): error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'Readonly<{ x: number; y: number; }>'. + Object literal may only specify known properties, and 'z' does not exist in type 'Readonly<{ x: number; y: number; }>'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(84,58): error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'Partial<{ x: number; y: number; }>'. + Object literal may only specify known properties, and 'z' does not exist in type 'Partial<{ x: number; y: number; }>'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(106,15): error TS2345: Argument of type '{ a: undefined; }' is not assignable to parameter of type 'Pick'. + Types of property 'a' are incompatible. + Type 'undefined' is not assignable to type 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(107,17): error TS2345: Argument of type '{ c: boolean; }' is not assignable to parameter of type 'Pick'. + Object literal may only specify known properties, and 'c' does not exist in type 'Pick'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(124,12): error TS2345: Argument of type '{ a: undefined; }' is not assignable to parameter of type 'Pick'. + Types of property 'a' are incompatible. + Type 'undefined' is not assignable to type 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(125,14): error TS2345: Argument of type '{ c: boolean; }' is not assignable to parameter of type 'Pick'. + Object literal may only specify known properties, and 'c' does not exist in type 'Pick'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(129,5): error TS2322: Type '{ a: string; }' is not assignable to type 'T2'. + Types of property 'a' are incompatible. + Type 'string' is not assignable to type 'number | undefined'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(130,5): error TS2322: Type '{ a: string; }' is not assignable to type 'Partial'. + Types of property 'a' are incompatible. + Type 'string' is not assignable to type 'number | undefined'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(131,5): error TS2322: Type '{ a: string; }' is not assignable to type '{ [x: string]: any; a?: number | undefined; }'. + Types of property 'a' are incompatible. + Type 'string' is not assignable to type 'number | undefined'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(137,16): error TS2322: Type '{}' is not assignable to type 'string'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(137,21): error TS2536: Type 'P' cannot be used to index type 'T'. + + +==== tests/cases/conformance/types/mapped/mappedTypeErrors.ts (26 errors) ==== + + interface Shape { + name: string; + width: number; + height: number; + visible: boolean; + } + + interface Named { + name: string; + } + + interface Point { + x: number; + y: number; + } + + // Constraint checking + + type T00 = { [P in P]: string }; // Error + ~ +!!! error TS2313: Type parameter 'P' has a circular constraint. + type T01 = { [P in number]: string }; // Error + ~~~~~~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. + type T02 = { [P in Date]: number }; // Error + ~~~~ +!!! error TS2322: Type 'Date' is not assignable to type 'string'. + type T03 = Record; // Error + ~~~~ +!!! error TS2344: Type 'Date' does not satisfy the constraint 'string'. + + type T10 = Pick; + type T11 = Pick; // Error + ~~~~~ +!!! error TS2344: Type '"foo"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + type T12 = Pick; // Error + ~~~~~~~~~~~~~~ +!!! error TS2344: Type '"name" | "foo"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type '"foo"' is not assignable to type '"name" | "width" | "height" | "visible"'. + type T13 = Pick; + type T14 = Pick; // Error + ~~~~~~~~~~~ +!!! error TS2344: Type '"x" | "y"' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type '"x"' is not assignable to type '"name" | "width" | "height" | "visible"'. + type T15 = Pick; + type T16 = Pick; // Error + ~~~~~~~~~ +!!! error TS2344: Type 'undefined' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. + + function f1(x: T) { + let y: Pick; // Error + ~ +!!! error TS2344: Type 'T' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type 'T' is not assignable to type '"visible"'. + } + + function f2(x: T) { + let y: Pick; // Error + ~ +!!! error TS2344: Type 'T' does not satisfy the constraint '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type 'string | number' is not assignable to type '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type 'string' is not assignable to type '"name" | "width" | "height" | "visible"'. +!!! error TS2344: Type 'T' is not assignable to type '"visible"'. +!!! error TS2344: Type 'string | number' is not assignable to type '"visible"'. +!!! error TS2344: Type 'string' is not assignable to type '"visible"'. + } + + function f3(x: T) { + let y: Pick; + } + + function f4(x: T) { + let y: Pick; + } + + // Type identity checking + + function f10() { + type K = keyof T; + var x: { [P in keyof T]: T[P] }; + var x: { [Q in keyof T]: T[Q] }; + var x: { [R in K]: T[R] }; + } + + function f11() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]?: T[P] }; // Error + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ [P in keyof T]?: T[P] | undefined; }'. + var x: { readonly [P in keyof T]: T[P] }; // Error + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ readonly [P in keyof T]: T[P]; }'. + var x: { readonly [P in keyof T]?: T[P] }; // Error + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ readonly [P in keyof T]?: T[P] | undefined; }'. + } + + function f12() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]: T[P][] }; // Error + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x' must be of type '{ [P in keyof T]: T[P]; }', but here has type '{ [P in keyof T]: T[P][]; }'. + } + + // Check that inferences to mapped types are secondary + + declare function objAndReadonly(primary: T, secondary: Readonly): T; + declare function objAndPartial(primary: T, secondary: Partial): T; + + function f20() { + let x1 = objAndReadonly({ x: 0, y: 0 }, { x: 1 }); // Error + ~~~~~~~~ +!!! error TS2345: Argument of type '{ x: number; }' is not assignable to parameter of type 'Readonly<{ x: number; y: number; }>'. +!!! error TS2345: Property 'y' is missing in type '{ x: number; }'. + let x2 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error + ~~~~ +!!! error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'Readonly<{ x: number; y: number; }>'. +!!! error TS2345: Object literal may only specify known properties, and 'z' does not exist in type 'Readonly<{ x: number; y: number; }>'. + } + + function f21() { + let x1 = objAndPartial({ x: 0, y: 0 }, { x: 1 }); + let x2 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error + ~~~~ +!!! error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'Partial<{ x: number; y: number; }>'. +!!! error TS2345: Object literal may only specify known properties, and 'z' does not exist in type 'Partial<{ x: number; y: number; }>'. + } + + // Verify use of Pick for setState functions (#12793) + + interface Foo { + a: string; + b?: number; + } + + function setState(obj: T, props: Pick) { + for (let k in props) { + obj[k] = props[k]; + } + } + + let foo: Foo = { a: "hello", b: 42 }; + setState(foo, { a: "test", b: 43 }) + setState(foo, { a: "hi" }); + setState(foo, { b: undefined }); + setState(foo, { }); + setState(foo, foo); + setState(foo, { a: undefined }); // Error + ~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '{ a: undefined; }' is not assignable to parameter of type 'Pick'. +!!! error TS2345: Types of property 'a' are incompatible. +!!! error TS2345: Type 'undefined' is not assignable to type 'string'. + setState(foo, { c: true }); // Error + ~~~~~~~ +!!! error TS2345: Argument of type '{ c: boolean; }' is not assignable to parameter of type 'Pick'. +!!! error TS2345: Object literal may only specify known properties, and 'c' does not exist in type 'Pick'. + + class C { + state: T; + setState(props: Pick) { + for (let k in props) { + this.state[k] = props[k]; + } + } + } + + let c = new C(); + c.setState({ a: "test", b: 43 }); + c.setState({ a: "hi" }); + c.setState({ b: undefined }); + c.setState({ }); + c.setState(foo); + c.setState({ a: undefined }); // Error + ~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '{ a: undefined; }' is not assignable to parameter of type 'Pick'. +!!! error TS2345: Types of property 'a' are incompatible. +!!! error TS2345: Type 'undefined' is not assignable to type 'string'. + c.setState({ c: true }); // Error + ~~~~~~~ +!!! error TS2345: Argument of type '{ c: boolean; }' is not assignable to parameter of type 'Pick'. +!!! error TS2345: Object literal may only specify known properties, and 'c' does not exist in type 'Pick'. + + type T2 = { a?: number, [key: string]: any }; + + let x1: T2 = { a: 'no' }; // Error + ~~ +!!! error TS2322: Type '{ a: string; }' is not assignable to type 'T2'. +!!! error TS2322: Types of property 'a' are incompatible. +!!! error TS2322: Type 'string' is not assignable to type 'number | undefined'. + let x2: Partial = { a: 'no' }; // Error + ~~ +!!! error TS2322: Type '{ a: string; }' is not assignable to type 'Partial'. +!!! error TS2322: Types of property 'a' are incompatible. +!!! error TS2322: Type 'string' is not assignable to type 'number | undefined'. + let x3: { [P in keyof T2]: T2[P]} = { a: 'no' }; // Error + ~~ +!!! error TS2322: Type '{ a: string; }' is not assignable to type '{ [x: string]: any; a?: number | undefined; }'. +!!! error TS2322: Types of property 'a' are incompatible. +!!! error TS2322: Type 'string' is not assignable to type 'number | undefined'. + + // Repro from #13044 + + type Foo2 = { + pf: {[P in F]?: T[P]}, + pt: {[P in T]?: T[P]}, // note: should be in keyof T + ~ +!!! error TS2322: Type '{}' is not assignable to type 'string'. + ~~~~ +!!! error TS2536: Type 'P' cannot be used to index type 'T'. + }; + type O = {x: number, y: boolean}; + let o: O = {x: 5, y: false}; + let f: Foo2 = { + pf: {x: 7}, + pt: {x: 7, y: false}, + }; + \ No newline at end of file diff --git a/tests/baselines/reference/mappedTypeErrors.js b/tests/baselines/reference/mappedTypeErrors.js new file mode 100644 index 00000000000..f194b6193fc --- /dev/null +++ b/tests/baselines/reference/mappedTypeErrors.js @@ -0,0 +1,303 @@ +//// [mappedTypeErrors.ts] + +interface Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +interface Named { + name: string; +} + +interface Point { + x: number; + y: number; +} + +// Constraint checking + +type T00 = { [P in P]: string }; // Error +type T01 = { [P in number]: string }; // Error +type T02 = { [P in Date]: number }; // Error +type T03 = Record; // Error + +type T10 = Pick; +type T11 = Pick; // Error +type T12 = Pick; // Error +type T13 = Pick; +type T14 = Pick; // Error +type T15 = Pick; +type T16 = Pick; // Error + +function f1(x: T) { + let y: Pick; // Error +} + +function f2(x: T) { + let y: Pick; // Error +} + +function f3(x: T) { + let y: Pick; +} + +function f4(x: T) { + let y: Pick; +} + +// Type identity checking + +function f10() { + type K = keyof T; + var x: { [P in keyof T]: T[P] }; + var x: { [Q in keyof T]: T[Q] }; + var x: { [R in K]: T[R] }; +} + +function f11() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]?: T[P] }; // Error + var x: { readonly [P in keyof T]: T[P] }; // Error + var x: { readonly [P in keyof T]?: T[P] }; // Error +} + +function f12() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]: T[P][] }; // Error +} + +// Check that inferences to mapped types are secondary + +declare function objAndReadonly(primary: T, secondary: Readonly): T; +declare function objAndPartial(primary: T, secondary: Partial): T; + +function f20() { + let x1 = objAndReadonly({ x: 0, y: 0 }, { x: 1 }); // Error + let x2 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} + +function f21() { + let x1 = objAndPartial({ x: 0, y: 0 }, { x: 1 }); + let x2 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} + +// Verify use of Pick for setState functions (#12793) + +interface Foo { + a: string; + b?: number; +} + +function setState(obj: T, props: Pick) { + for (let k in props) { + obj[k] = props[k]; + } +} + +let foo: Foo = { a: "hello", b: 42 }; +setState(foo, { a: "test", b: 43 }) +setState(foo, { a: "hi" }); +setState(foo, { b: undefined }); +setState(foo, { }); +setState(foo, foo); +setState(foo, { a: undefined }); // Error +setState(foo, { c: true }); // Error + +class C { + state: T; + setState(props: Pick) { + for (let k in props) { + this.state[k] = props[k]; + } + } +} + +let c = new C(); +c.setState({ a: "test", b: 43 }); +c.setState({ a: "hi" }); +c.setState({ b: undefined }); +c.setState({ }); +c.setState(foo); +c.setState({ a: undefined }); // Error +c.setState({ c: true }); // Error + +type T2 = { a?: number, [key: string]: any }; + +let x1: T2 = { a: 'no' }; // Error +let x2: Partial = { a: 'no' }; // Error +let x3: { [P in keyof T2]: T2[P]} = { a: 'no' }; // Error + +// Repro from #13044 + +type Foo2 = { + pf: {[P in F]?: T[P]}, + pt: {[P in T]?: T[P]}, // note: should be in keyof T +}; +type O = {x: number, y: boolean}; +let o: O = {x: 5, y: false}; +let f: Foo2 = { + pf: {x: 7}, + pt: {x: 7, y: false}, +}; + + +//// [mappedTypeErrors.js] +function f1(x) { + var y; // Error +} +function f2(x) { + var y; // Error +} +function f3(x) { + var y; +} +function f4(x) { + var y; +} +// Type identity checking +function f10() { + var x; + var x; + var x; +} +function f11() { + var x; + var x; // Error + var x; // Error + var x; // Error +} +function f12() { + var x; + var x; // Error +} +function f20() { + var x1 = objAndReadonly({ x: 0, y: 0 }, { x: 1 }); // Error + var x2 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1 }); + var x3 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} +function f21() { + var x1 = objAndPartial({ x: 0, y: 0 }, { x: 1 }); + var x2 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1 }); + var x3 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} +function setState(obj, props) { + for (var k in props) { + obj[k] = props[k]; + } +} +var foo = { a: "hello", b: 42 }; +setState(foo, { a: "test", b: 43 }); +setState(foo, { a: "hi" }); +setState(foo, { b: undefined }); +setState(foo, {}); +setState(foo, foo); +setState(foo, { a: undefined }); // Error +setState(foo, { c: true }); // Error +var C = (function () { + function C() { + } + C.prototype.setState = function (props) { + for (var k in props) { + this.state[k] = props[k]; + } + }; + return C; +}()); +var c = new C(); +c.setState({ a: "test", b: 43 }); +c.setState({ a: "hi" }); +c.setState({ b: undefined }); +c.setState({}); +c.setState(foo); +c.setState({ a: undefined }); // Error +c.setState({ c: true }); // Error +var x1 = { a: 'no' }; // Error +var x2 = { a: 'no' }; // Error +var x3 = { a: 'no' }; // Error +var o = { x: 5, y: false }; +var f = { + pf: { x: 7 }, + pt: { x: 7, y: false } +}; + + +//// [mappedTypeErrors.d.ts] +interface Shape { + name: string; + width: number; + height: number; + visible: boolean; +} +interface Named { + name: string; +} +interface Point { + x: number; + y: number; +} +declare type T00 = { + [P in P]: string; +}; +declare type T01 = { + [P in number]: string; +}; +declare type T02 = { + [P in Date]: number; +}; +declare type T03 = Record; +declare type T10 = Pick; +declare type T11 = Pick; +declare type T12 = Pick; +declare type T13 = Pick; +declare type T14 = Pick; +declare type T15 = Pick; +declare type T16 = Pick; +declare function f1(x: T): void; +declare function f2(x: T): void; +declare function f3(x: T): void; +declare function f4(x: T): void; +declare function f10(): void; +declare function f11(): void; +declare function f12(): void; +declare function objAndReadonly(primary: T, secondary: Readonly): T; +declare function objAndPartial(primary: T, secondary: Partial): T; +declare function f20(): void; +declare function f21(): void; +interface Foo { + a: string; + b?: number; +} +declare function setState(obj: T, props: Pick): void; +declare let foo: Foo; +declare class C { + state: T; + setState(props: Pick): void; +} +declare let c: C; +declare type T2 = { + a?: number; + [key: string]: any; +}; +declare let x1: T2; +declare let x2: Partial; +declare let x3: { + [P in keyof T2]: T2[P]; +}; +declare type Foo2 = { + pf: { + [P in F]?: T[P]; + }; + pt: { + [P in T]?: T[P]; + }; +}; +declare type O = { + x: number; + y: boolean; +}; +declare let o: O; +declare let f: Foo2; diff --git a/tests/baselines/reference/mappedTypeInferenceCircularity.js b/tests/baselines/reference/mappedTypeInferenceCircularity.js new file mode 100644 index 00000000000..d5918d342f6 --- /dev/null +++ b/tests/baselines/reference/mappedTypeInferenceCircularity.js @@ -0,0 +1,12 @@ +//// [mappedTypeInferenceCircularity.ts] +// Repro from #12511 + +type HTML = { [K in 'div']: Block }; +type Block

= (func: HTML) => {}; + +declare var h: HTML; +h.div(h); + +//// [mappedTypeInferenceCircularity.js] +// Repro from #12511 +h.div(h); diff --git a/tests/baselines/reference/mappedTypeInferenceCircularity.symbols b/tests/baselines/reference/mappedTypeInferenceCircularity.symbols new file mode 100644 index 00000000000..33dceb5cd76 --- /dev/null +++ b/tests/baselines/reference/mappedTypeInferenceCircularity.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/mappedTypeInferenceCircularity.ts === +// Repro from #12511 + +type HTML = { [K in 'div']: Block }; +>HTML : Symbol(HTML, Decl(mappedTypeInferenceCircularity.ts, 0, 0)) +>K : Symbol(K, Decl(mappedTypeInferenceCircularity.ts, 2, 15)) +>Block : Symbol(Block, Decl(mappedTypeInferenceCircularity.ts, 2, 42)) +>HTML : Symbol(HTML, Decl(mappedTypeInferenceCircularity.ts, 0, 0)) + +type Block

= (func: HTML) => {}; +>Block : Symbol(Block, Decl(mappedTypeInferenceCircularity.ts, 2, 42)) +>P : Symbol(P, Decl(mappedTypeInferenceCircularity.ts, 3, 11)) +>T : Symbol(T, Decl(mappedTypeInferenceCircularity.ts, 3, 17)) +>func : Symbol(func, Decl(mappedTypeInferenceCircularity.ts, 3, 20)) +>HTML : Symbol(HTML, Decl(mappedTypeInferenceCircularity.ts, 0, 0)) + +declare var h: HTML; +>h : Symbol(h, Decl(mappedTypeInferenceCircularity.ts, 5, 11)) +>HTML : Symbol(HTML, Decl(mappedTypeInferenceCircularity.ts, 0, 0)) + +h.div(h); +>h.div : Symbol(div) +>h : Symbol(h, Decl(mappedTypeInferenceCircularity.ts, 5, 11)) +>div : Symbol(div) +>h : Symbol(h, Decl(mappedTypeInferenceCircularity.ts, 5, 11)) + diff --git a/tests/baselines/reference/mappedTypeInferenceCircularity.types b/tests/baselines/reference/mappedTypeInferenceCircularity.types new file mode 100644 index 00000000000..451da474756 --- /dev/null +++ b/tests/baselines/reference/mappedTypeInferenceCircularity.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/mappedTypeInferenceCircularity.ts === +// Repro from #12511 + +type HTML = { [K in 'div']: Block }; +>HTML : HTML +>K : K +>Block : Block

+>HTML : HTML + +type Block

= (func: HTML) => {}; +>Block : Block

+>P : P +>T : T +>func : HTML +>HTML : HTML + +declare var h: HTML; +>h : HTML +>HTML : HTML + +h.div(h); +>h.div(h) : {} +>h.div : Block +>h : HTML +>div : Block +>h : HTML + diff --git a/tests/baselines/reference/mappedTypeModifiers.js b/tests/baselines/reference/mappedTypeModifiers.js new file mode 100644 index 00000000000..a247d18f2d4 --- /dev/null +++ b/tests/baselines/reference/mappedTypeModifiers.js @@ -0,0 +1,172 @@ +//// [mappedTypeModifiers.ts] + +type T = { a: number, b: string }; +type TP = { a?: number, b?: string }; +type TR = { readonly a: number, readonly b: string }; +type TPR = { readonly a?: number, readonly b?: string }; + +var v00: "a" | "b"; +var v00: keyof T; +var v00: keyof TP; +var v00: keyof TR; +var v00: keyof TPR; + +var v01: T; +var v01: { [P in keyof T]: T[P] }; +var v01: Pick; +var v01: Pick, keyof T>; + +var v02: TP; +var v02: { [P in keyof T]?: T[P] }; +var v02: Partial; +var v02: { [P in keyof TP]: TP[P] } +var v02: Pick; + +var v03: TR; +var v03: { readonly [P in keyof T]: T[P] }; +var v03: Readonly; +var v03: { [P in keyof TR]: TR[P] } +var v03: Pick; + +var v04: TPR; +var v04: { readonly [P in keyof T]?: T[P] }; +var v04: Partial; +var v04: Readonly; +var v04: Partial>; +var v04: Readonly>; +var v04: { [P in keyof TPR]: TPR[P] } +var v04: Pick; + +type Boxified = { [P in keyof T]: { x: T[P] } }; + +type B = { a: { x: number }, b: { x: string } }; +type BP = { a?: { x: number }, b?: { x: string } }; +type BR = { readonly a: { x: number }, readonly b: { x: string } }; +type BPR = { readonly a?: { x: number }, readonly b?: { x: string } }; + +var b00: "a" | "b"; +var b00: keyof B; +var b00: keyof BP; +var b00: keyof BR; +var b00: keyof BPR; + +var b01: B; +var b01: { [P in keyof B]: B[P] }; +var b01: Pick; +var b01: Pick, keyof B>; + +var b02: BP; +var b02: { [P in keyof B]?: B[P] }; +var b02: Partial; +var b02: { [P in keyof BP]: BP[P] } +var b02: Pick; + +var b03: BR; +var b03: { readonly [P in keyof B]: B[P] }; +var b03: Readonly; +var b03: { [P in keyof BR]: BR[P] } +var b03: Pick; + +var b04: BPR; +var b04: { readonly [P in keyof B]?: B[P] }; +var b04: Partial
; +var b04: Readonly; +var b04: Partial>; +var b04: Readonly>; +var b04: { [P in keyof BPR]: BPR[P] } +var b04: Pick; + +type Foo = { prop: number, [x: string]: number }; + +function f1(x: Partial) { + x.prop; // ok + (x["other"] || 0).toFixed(); +} + +function f2(x: Readonly) { + x.prop; // ok + x["other"].toFixed(); +} + +function f3(x: Boxified) { + x.prop; // ok + x["other"].x.toFixed(); +} + +function f4(x: { [P in keyof Foo]: Foo[P] }) { + x.prop; // ok + x["other"].toFixed(); +} + + +//// [mappedTypeModifiers.js] +var v00; +var v00; +var v00; +var v00; +var v00; +var v01; +var v01; +var v01; +var v01; +var v02; +var v02; +var v02; +var v02; +var v02; +var v03; +var v03; +var v03; +var v03; +var v03; +var v04; +var v04; +var v04; +var v04; +var v04; +var v04; +var v04; +var v04; +var b00; +var b00; +var b00; +var b00; +var b00; +var b01; +var b01; +var b01; +var b01; +var b02; +var b02; +var b02; +var b02; +var b02; +var b03; +var b03; +var b03; +var b03; +var b03; +var b04; +var b04; +var b04; +var b04; +var b04; +var b04; +var b04; +var b04; +function f1(x) { + x.prop; // ok + (x["other"] || 0).toFixed(); +} +function f2(x) { + x.prop; // ok + x["other"].toFixed(); +} +function f3(x) { + x.prop; // ok + x["other"].x.toFixed(); +} +function f4(x) { + x.prop; // ok + x["other"].toFixed(); +} diff --git a/tests/baselines/reference/mappedTypeModifiers.symbols b/tests/baselines/reference/mappedTypeModifiers.symbols new file mode 100644 index 00000000000..b2b8faed4cf --- /dev/null +++ b/tests/baselines/reference/mappedTypeModifiers.symbols @@ -0,0 +1,432 @@ +=== tests/cases/conformance/types/mapped/mappedTypeModifiers.ts === + +type T = { a: number, b: string }; +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 1, 10)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 1, 21)) + +type TP = { a?: number, b?: string }; +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 2, 11)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 2, 23)) + +type TR = { readonly a: number, readonly b: string }; +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 3, 11)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 3, 31)) + +type TPR = { readonly a?: number, readonly b?: string }; +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 4, 12)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 4, 33)) + +var v00: "a" | "b"; +>v00 : Symbol(v00, Decl(mappedTypeModifiers.ts, 6, 3), Decl(mappedTypeModifiers.ts, 7, 3), Decl(mappedTypeModifiers.ts, 8, 3), Decl(mappedTypeModifiers.ts, 9, 3), Decl(mappedTypeModifiers.ts, 10, 3)) + +var v00: keyof T; +>v00 : Symbol(v00, Decl(mappedTypeModifiers.ts, 6, 3), Decl(mappedTypeModifiers.ts, 7, 3), Decl(mappedTypeModifiers.ts, 8, 3), Decl(mappedTypeModifiers.ts, 9, 3), Decl(mappedTypeModifiers.ts, 10, 3)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v00: keyof TP; +>v00 : Symbol(v00, Decl(mappedTypeModifiers.ts, 6, 3), Decl(mappedTypeModifiers.ts, 7, 3), Decl(mappedTypeModifiers.ts, 8, 3), Decl(mappedTypeModifiers.ts, 9, 3), Decl(mappedTypeModifiers.ts, 10, 3)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) + +var v00: keyof TR; +>v00 : Symbol(v00, Decl(mappedTypeModifiers.ts, 6, 3), Decl(mappedTypeModifiers.ts, 7, 3), Decl(mappedTypeModifiers.ts, 8, 3), Decl(mappedTypeModifiers.ts, 9, 3), Decl(mappedTypeModifiers.ts, 10, 3)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) + +var v00: keyof TPR; +>v00 : Symbol(v00, Decl(mappedTypeModifiers.ts, 6, 3), Decl(mappedTypeModifiers.ts, 7, 3), Decl(mappedTypeModifiers.ts, 8, 3), Decl(mappedTypeModifiers.ts, 9, 3), Decl(mappedTypeModifiers.ts, 10, 3)) +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) + +var v01: T; +>v01 : Symbol(v01, Decl(mappedTypeModifiers.ts, 12, 3), Decl(mappedTypeModifiers.ts, 13, 3), Decl(mappedTypeModifiers.ts, 14, 3), Decl(mappedTypeModifiers.ts, 15, 3)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v01: { [P in keyof T]: T[P] }; +>v01 : Symbol(v01, Decl(mappedTypeModifiers.ts, 12, 3), Decl(mappedTypeModifiers.ts, 13, 3), Decl(mappedTypeModifiers.ts, 14, 3), Decl(mappedTypeModifiers.ts, 15, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 13, 12)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 13, 12)) + +var v01: Pick; +>v01 : Symbol(v01, Decl(mappedTypeModifiers.ts, 12, 3), Decl(mappedTypeModifiers.ts, 13, 3), Decl(mappedTypeModifiers.ts, 14, 3), Decl(mappedTypeModifiers.ts, 15, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v01: Pick, keyof T>; +>v01 : Symbol(v01, Decl(mappedTypeModifiers.ts, 12, 3), Decl(mappedTypeModifiers.ts, 13, 3), Decl(mappedTypeModifiers.ts, 14, 3), Decl(mappedTypeModifiers.ts, 15, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v02: TP; +>v02 : Symbol(v02, Decl(mappedTypeModifiers.ts, 17, 3), Decl(mappedTypeModifiers.ts, 18, 3), Decl(mappedTypeModifiers.ts, 19, 3), Decl(mappedTypeModifiers.ts, 20, 3), Decl(mappedTypeModifiers.ts, 21, 3)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) + +var v02: { [P in keyof T]?: T[P] }; +>v02 : Symbol(v02, Decl(mappedTypeModifiers.ts, 17, 3), Decl(mappedTypeModifiers.ts, 18, 3), Decl(mappedTypeModifiers.ts, 19, 3), Decl(mappedTypeModifiers.ts, 20, 3), Decl(mappedTypeModifiers.ts, 21, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 18, 12)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 18, 12)) + +var v02: Partial; +>v02 : Symbol(v02, Decl(mappedTypeModifiers.ts, 17, 3), Decl(mappedTypeModifiers.ts, 18, 3), Decl(mappedTypeModifiers.ts, 19, 3), Decl(mappedTypeModifiers.ts, 20, 3), Decl(mappedTypeModifiers.ts, 21, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v02: { [P in keyof TP]: TP[P] } +>v02 : Symbol(v02, Decl(mappedTypeModifiers.ts, 17, 3), Decl(mappedTypeModifiers.ts, 18, 3), Decl(mappedTypeModifiers.ts, 19, 3), Decl(mappedTypeModifiers.ts, 20, 3), Decl(mappedTypeModifiers.ts, 21, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 20, 12)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 20, 12)) + +var v02: Pick; +>v02 : Symbol(v02, Decl(mappedTypeModifiers.ts, 17, 3), Decl(mappedTypeModifiers.ts, 18, 3), Decl(mappedTypeModifiers.ts, 19, 3), Decl(mappedTypeModifiers.ts, 20, 3), Decl(mappedTypeModifiers.ts, 21, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) + +var v03: TR; +>v03 : Symbol(v03, Decl(mappedTypeModifiers.ts, 23, 3), Decl(mappedTypeModifiers.ts, 24, 3), Decl(mappedTypeModifiers.ts, 25, 3), Decl(mappedTypeModifiers.ts, 26, 3), Decl(mappedTypeModifiers.ts, 27, 3)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) + +var v03: { readonly [P in keyof T]: T[P] }; +>v03 : Symbol(v03, Decl(mappedTypeModifiers.ts, 23, 3), Decl(mappedTypeModifiers.ts, 24, 3), Decl(mappedTypeModifiers.ts, 25, 3), Decl(mappedTypeModifiers.ts, 26, 3), Decl(mappedTypeModifiers.ts, 27, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 24, 21)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 24, 21)) + +var v03: Readonly; +>v03 : Symbol(v03, Decl(mappedTypeModifiers.ts, 23, 3), Decl(mappedTypeModifiers.ts, 24, 3), Decl(mappedTypeModifiers.ts, 25, 3), Decl(mappedTypeModifiers.ts, 26, 3), Decl(mappedTypeModifiers.ts, 27, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v03: { [P in keyof TR]: TR[P] } +>v03 : Symbol(v03, Decl(mappedTypeModifiers.ts, 23, 3), Decl(mappedTypeModifiers.ts, 24, 3), Decl(mappedTypeModifiers.ts, 25, 3), Decl(mappedTypeModifiers.ts, 26, 3), Decl(mappedTypeModifiers.ts, 27, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 26, 12)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 26, 12)) + +var v03: Pick; +>v03 : Symbol(v03, Decl(mappedTypeModifiers.ts, 23, 3), Decl(mappedTypeModifiers.ts, 24, 3), Decl(mappedTypeModifiers.ts, 25, 3), Decl(mappedTypeModifiers.ts, 26, 3), Decl(mappedTypeModifiers.ts, 27, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) + +var v04: TPR; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) + +var v04: { readonly [P in keyof T]?: T[P] }; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 30, 21)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 30, 21)) + +var v04: Partial; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>TR : Symbol(TR, Decl(mappedTypeModifiers.ts, 2, 37)) + +var v04: Readonly; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>TP : Symbol(TP, Decl(mappedTypeModifiers.ts, 1, 34)) + +var v04: Partial>; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v04: Readonly>; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +var v04: { [P in keyof TPR]: TPR[P] } +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 35, 12)) +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 35, 12)) + +var v04: Pick; +>v04 : Symbol(v04, Decl(mappedTypeModifiers.ts, 29, 3), Decl(mappedTypeModifiers.ts, 30, 3), Decl(mappedTypeModifiers.ts, 31, 3), Decl(mappedTypeModifiers.ts, 32, 3), Decl(mappedTypeModifiers.ts, 33, 3), Decl(mappedTypeModifiers.ts, 34, 3), Decl(mappedTypeModifiers.ts, 35, 3), Decl(mappedTypeModifiers.ts, 36, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>TPR : Symbol(TPR, Decl(mappedTypeModifiers.ts, 3, 53)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 0, 0)) + +type Boxified = { [P in keyof T]: { x: T[P] } }; +>Boxified : Symbol(Boxified, Decl(mappedTypeModifiers.ts, 36, 28)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 38, 14)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 38, 22)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 38, 14)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 38, 38)) +>T : Symbol(T, Decl(mappedTypeModifiers.ts, 38, 14)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 38, 22)) + +type B = { a: { x: number }, b: { x: string } }; +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 40, 10)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 40, 15)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 40, 28)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 40, 33)) + +type BP = { a?: { x: number }, b?: { x: string } }; +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 41, 11)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 41, 17)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 41, 30)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 41, 36)) + +type BR = { readonly a: { x: number }, readonly b: { x: string } }; +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 42, 11)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 42, 25)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 42, 38)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 42, 52)) + +type BPR = { readonly a?: { x: number }, readonly b?: { x: string } }; +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) +>a : Symbol(a, Decl(mappedTypeModifiers.ts, 43, 12)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 43, 27)) +>b : Symbol(b, Decl(mappedTypeModifiers.ts, 43, 40)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 43, 55)) + +var b00: "a" | "b"; +>b00 : Symbol(b00, Decl(mappedTypeModifiers.ts, 45, 3), Decl(mappedTypeModifiers.ts, 46, 3), Decl(mappedTypeModifiers.ts, 47, 3), Decl(mappedTypeModifiers.ts, 48, 3), Decl(mappedTypeModifiers.ts, 49, 3)) + +var b00: keyof B; +>b00 : Symbol(b00, Decl(mappedTypeModifiers.ts, 45, 3), Decl(mappedTypeModifiers.ts, 46, 3), Decl(mappedTypeModifiers.ts, 47, 3), Decl(mappedTypeModifiers.ts, 48, 3), Decl(mappedTypeModifiers.ts, 49, 3)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b00: keyof BP; +>b00 : Symbol(b00, Decl(mappedTypeModifiers.ts, 45, 3), Decl(mappedTypeModifiers.ts, 46, 3), Decl(mappedTypeModifiers.ts, 47, 3), Decl(mappedTypeModifiers.ts, 48, 3), Decl(mappedTypeModifiers.ts, 49, 3)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) + +var b00: keyof BR; +>b00 : Symbol(b00, Decl(mappedTypeModifiers.ts, 45, 3), Decl(mappedTypeModifiers.ts, 46, 3), Decl(mappedTypeModifiers.ts, 47, 3), Decl(mappedTypeModifiers.ts, 48, 3), Decl(mappedTypeModifiers.ts, 49, 3)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) + +var b00: keyof BPR; +>b00 : Symbol(b00, Decl(mappedTypeModifiers.ts, 45, 3), Decl(mappedTypeModifiers.ts, 46, 3), Decl(mappedTypeModifiers.ts, 47, 3), Decl(mappedTypeModifiers.ts, 48, 3), Decl(mappedTypeModifiers.ts, 49, 3)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) + +var b01: B; +>b01 : Symbol(b01, Decl(mappedTypeModifiers.ts, 51, 3), Decl(mappedTypeModifiers.ts, 52, 3), Decl(mappedTypeModifiers.ts, 53, 3), Decl(mappedTypeModifiers.ts, 54, 3)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b01: { [P in keyof B]: B[P] }; +>b01 : Symbol(b01, Decl(mappedTypeModifiers.ts, 51, 3), Decl(mappedTypeModifiers.ts, 52, 3), Decl(mappedTypeModifiers.ts, 53, 3), Decl(mappedTypeModifiers.ts, 54, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 52, 12)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 52, 12)) + +var b01: Pick; +>b01 : Symbol(b01, Decl(mappedTypeModifiers.ts, 51, 3), Decl(mappedTypeModifiers.ts, 52, 3), Decl(mappedTypeModifiers.ts, 53, 3), Decl(mappedTypeModifiers.ts, 54, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b01: Pick, keyof B>; +>b01 : Symbol(b01, Decl(mappedTypeModifiers.ts, 51, 3), Decl(mappedTypeModifiers.ts, 52, 3), Decl(mappedTypeModifiers.ts, 53, 3), Decl(mappedTypeModifiers.ts, 54, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b02: BP; +>b02 : Symbol(b02, Decl(mappedTypeModifiers.ts, 56, 3), Decl(mappedTypeModifiers.ts, 57, 3), Decl(mappedTypeModifiers.ts, 58, 3), Decl(mappedTypeModifiers.ts, 59, 3), Decl(mappedTypeModifiers.ts, 60, 3)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) + +var b02: { [P in keyof B]?: B[P] }; +>b02 : Symbol(b02, Decl(mappedTypeModifiers.ts, 56, 3), Decl(mappedTypeModifiers.ts, 57, 3), Decl(mappedTypeModifiers.ts, 58, 3), Decl(mappedTypeModifiers.ts, 59, 3), Decl(mappedTypeModifiers.ts, 60, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 57, 12)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 57, 12)) + +var b02: Partial; +>b02 : Symbol(b02, Decl(mappedTypeModifiers.ts, 56, 3), Decl(mappedTypeModifiers.ts, 57, 3), Decl(mappedTypeModifiers.ts, 58, 3), Decl(mappedTypeModifiers.ts, 59, 3), Decl(mappedTypeModifiers.ts, 60, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b02: { [P in keyof BP]: BP[P] } +>b02 : Symbol(b02, Decl(mappedTypeModifiers.ts, 56, 3), Decl(mappedTypeModifiers.ts, 57, 3), Decl(mappedTypeModifiers.ts, 58, 3), Decl(mappedTypeModifiers.ts, 59, 3), Decl(mappedTypeModifiers.ts, 60, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 59, 12)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 59, 12)) + +var b02: Pick; +>b02 : Symbol(b02, Decl(mappedTypeModifiers.ts, 56, 3), Decl(mappedTypeModifiers.ts, 57, 3), Decl(mappedTypeModifiers.ts, 58, 3), Decl(mappedTypeModifiers.ts, 59, 3), Decl(mappedTypeModifiers.ts, 60, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) + +var b03: BR; +>b03 : Symbol(b03, Decl(mappedTypeModifiers.ts, 62, 3), Decl(mappedTypeModifiers.ts, 63, 3), Decl(mappedTypeModifiers.ts, 64, 3), Decl(mappedTypeModifiers.ts, 65, 3), Decl(mappedTypeModifiers.ts, 66, 3)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) + +var b03: { readonly [P in keyof B]: B[P] }; +>b03 : Symbol(b03, Decl(mappedTypeModifiers.ts, 62, 3), Decl(mappedTypeModifiers.ts, 63, 3), Decl(mappedTypeModifiers.ts, 64, 3), Decl(mappedTypeModifiers.ts, 65, 3), Decl(mappedTypeModifiers.ts, 66, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 63, 21)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 63, 21)) + +var b03: Readonly; +>b03 : Symbol(b03, Decl(mappedTypeModifiers.ts, 62, 3), Decl(mappedTypeModifiers.ts, 63, 3), Decl(mappedTypeModifiers.ts, 64, 3), Decl(mappedTypeModifiers.ts, 65, 3), Decl(mappedTypeModifiers.ts, 66, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b03: { [P in keyof BR]: BR[P] } +>b03 : Symbol(b03, Decl(mappedTypeModifiers.ts, 62, 3), Decl(mappedTypeModifiers.ts, 63, 3), Decl(mappedTypeModifiers.ts, 64, 3), Decl(mappedTypeModifiers.ts, 65, 3), Decl(mappedTypeModifiers.ts, 66, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 65, 12)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 65, 12)) + +var b03: Pick; +>b03 : Symbol(b03, Decl(mappedTypeModifiers.ts, 62, 3), Decl(mappedTypeModifiers.ts, 63, 3), Decl(mappedTypeModifiers.ts, 64, 3), Decl(mappedTypeModifiers.ts, 65, 3), Decl(mappedTypeModifiers.ts, 66, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) + +var b04: BPR; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) + +var b04: { readonly [P in keyof B]?: B[P] }; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 69, 21)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 69, 21)) + +var b04: Partial
; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>BR : Symbol(BR, Decl(mappedTypeModifiers.ts, 41, 51)) + +var b04: Readonly; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>BP : Symbol(BP, Decl(mappedTypeModifiers.ts, 40, 48)) + +var b04: Partial>; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b04: Readonly>; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>B : Symbol(B, Decl(mappedTypeModifiers.ts, 38, 51)) + +var b04: { [P in keyof BPR]: BPR[P] } +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 74, 12)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 74, 12)) + +var b04: Pick; +>b04 : Symbol(b04, Decl(mappedTypeModifiers.ts, 68, 3), Decl(mappedTypeModifiers.ts, 69, 3), Decl(mappedTypeModifiers.ts, 70, 3), Decl(mappedTypeModifiers.ts, 71, 3), Decl(mappedTypeModifiers.ts, 72, 3), Decl(mappedTypeModifiers.ts, 73, 3), Decl(mappedTypeModifiers.ts, 74, 3), Decl(mappedTypeModifiers.ts, 75, 3)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) +>BPR : Symbol(BPR, Decl(mappedTypeModifiers.ts, 42, 67)) + +type Foo = { prop: number, [x: string]: number }; +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) +>prop : Symbol(prop, Decl(mappedTypeModifiers.ts, 77, 12)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 77, 28)) + +function f1(x: Partial) { +>f1 : Symbol(f1, Decl(mappedTypeModifiers.ts, 77, 49)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 79, 12)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) + + x.prop; // ok +>x.prop : Symbol(prop) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 79, 12)) +>prop : Symbol(prop) + + (x["other"] || 0).toFixed(); +>(x["other"] || 0).toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 79, 12)) +>toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +} + +function f2(x: Readonly) { +>f2 : Symbol(f2, Decl(mappedTypeModifiers.ts, 82, 1)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 84, 12)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) + + x.prop; // ok +>x.prop : Symbol(prop) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 84, 12)) +>prop : Symbol(prop) + + x["other"].toFixed(); +>x["other"].toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 84, 12)) +>toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +} + +function f3(x: Boxified) { +>f3 : Symbol(f3, Decl(mappedTypeModifiers.ts, 87, 1)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 89, 12)) +>Boxified : Symbol(Boxified, Decl(mappedTypeModifiers.ts, 36, 28)) +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) + + x.prop; // ok +>x.prop : Symbol(prop) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 89, 12)) +>prop : Symbol(prop) + + x["other"].x.toFixed(); +>x["other"].x.toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +>x["other"].x : Symbol(x, Decl(mappedTypeModifiers.ts, 38, 38)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 89, 12)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 38, 38)) +>toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +} + +function f4(x: { [P in keyof Foo]: Foo[P] }) { +>f4 : Symbol(f4, Decl(mappedTypeModifiers.ts, 92, 1)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 94, 12)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 94, 18)) +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) +>Foo : Symbol(Foo, Decl(mappedTypeModifiers.ts, 75, 30)) +>P : Symbol(P, Decl(mappedTypeModifiers.ts, 94, 18)) + + x.prop; // ok +>x.prop : Symbol(prop) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 94, 12)) +>prop : Symbol(prop) + + x["other"].toFixed(); +>x["other"].toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(mappedTypeModifiers.ts, 94, 12)) +>toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/mappedTypeModifiers.types b/tests/baselines/reference/mappedTypeModifiers.types new file mode 100644 index 00000000000..7771de023f1 --- /dev/null +++ b/tests/baselines/reference/mappedTypeModifiers.types @@ -0,0 +1,447 @@ +=== tests/cases/conformance/types/mapped/mappedTypeModifiers.ts === + +type T = { a: number, b: string }; +>T : T +>a : number +>b : string + +type TP = { a?: number, b?: string }; +>TP : TP +>a : number | undefined +>b : string | undefined + +type TR = { readonly a: number, readonly b: string }; +>TR : TR +>a : number +>b : string + +type TPR = { readonly a?: number, readonly b?: string }; +>TPR : TPR +>a : number | undefined +>b : string | undefined + +var v00: "a" | "b"; +>v00 : "a" | "b" + +var v00: keyof T; +>v00 : "a" | "b" +>T : T + +var v00: keyof TP; +>v00 : "a" | "b" +>TP : TP + +var v00: keyof TR; +>v00 : "a" | "b" +>TR : TR + +var v00: keyof TPR; +>v00 : "a" | "b" +>TPR : TPR + +var v01: T; +>v01 : T +>T : T + +var v01: { [P in keyof T]: T[P] }; +>v01 : T +>P : P +>T : T +>T : T +>P : P + +var v01: Pick; +>v01 : T +>Pick : Pick +>T : T +>T : T + +var v01: Pick, keyof T>; +>v01 : T +>Pick : Pick +>Pick : Pick +>T : T +>T : T +>T : T + +var v02: TP; +>v02 : TP +>TP : TP + +var v02: { [P in keyof T]?: T[P] }; +>v02 : TP +>P : P +>T : T +>T : T +>P : P + +var v02: Partial; +>v02 : TP +>Partial : Partial +>T : T + +var v02: { [P in keyof TP]: TP[P] } +>v02 : TP +>P : P +>TP : TP +>TP : TP +>P : P + +var v02: Pick; +>v02 : TP +>Pick : Pick +>TP : TP +>TP : TP + +var v03: TR; +>v03 : TR +>TR : TR + +var v03: { readonly [P in keyof T]: T[P] }; +>v03 : TR +>P : P +>T : T +>T : T +>P : P + +var v03: Readonly; +>v03 : TR +>Readonly : Readonly +>T : T + +var v03: { [P in keyof TR]: TR[P] } +>v03 : TR +>P : P +>TR : TR +>TR : TR +>P : P + +var v03: Pick; +>v03 : TR +>Pick : Pick +>TR : TR +>TR : TR + +var v04: TPR; +>v04 : TPR +>TPR : TPR + +var v04: { readonly [P in keyof T]?: T[P] }; +>v04 : TPR +>P : P +>T : T +>T : T +>P : P + +var v04: Partial; +>v04 : TPR +>Partial : Partial +>TR : TR + +var v04: Readonly; +>v04 : TPR +>Readonly : Readonly +>TP : TP + +var v04: Partial>; +>v04 : TPR +>Partial : Partial +>Readonly : Readonly +>T : T + +var v04: Readonly>; +>v04 : TPR +>Readonly : Readonly +>Partial : Partial +>T : T + +var v04: { [P in keyof TPR]: TPR[P] } +>v04 : TPR +>P : P +>TPR : TPR +>TPR : TPR +>P : P + +var v04: Pick; +>v04 : TPR +>Pick : Pick +>TPR : TPR +>T : T + +type Boxified = { [P in keyof T]: { x: T[P] } }; +>Boxified : Boxified +>T : T +>P : P +>T : T +>x : T[P] +>T : T +>P : P + +type B = { a: { x: number }, b: { x: string } }; +>B : B +>a : { x: number; } +>x : number +>b : { x: string; } +>x : string + +type BP = { a?: { x: number }, b?: { x: string } }; +>BP : BP +>a : { x: number; } | undefined +>x : number +>b : { x: string; } | undefined +>x : string + +type BR = { readonly a: { x: number }, readonly b: { x: string } }; +>BR : BR +>a : { x: number; } +>x : number +>b : { x: string; } +>x : string + +type BPR = { readonly a?: { x: number }, readonly b?: { x: string } }; +>BPR : BPR +>a : { x: number; } | undefined +>x : number +>b : { x: string; } | undefined +>x : string + +var b00: "a" | "b"; +>b00 : "a" | "b" + +var b00: keyof B; +>b00 : "a" | "b" +>B : B + +var b00: keyof BP; +>b00 : "a" | "b" +>BP : BP + +var b00: keyof BR; +>b00 : "a" | "b" +>BR : BR + +var b00: keyof BPR; +>b00 : "a" | "b" +>BPR : BPR + +var b01: B; +>b01 : B +>B : B + +var b01: { [P in keyof B]: B[P] }; +>b01 : B +>P : P +>B : B +>B : B +>P : P + +var b01: Pick; +>b01 : B +>Pick : Pick +>B : B +>B : B + +var b01: Pick, keyof B>; +>b01 : B +>Pick : Pick +>Pick : Pick +>B : B +>B : B +>B : B + +var b02: BP; +>b02 : BP +>BP : BP + +var b02: { [P in keyof B]?: B[P] }; +>b02 : BP +>P : P +>B : B +>B : B +>P : P + +var b02: Partial; +>b02 : BP +>Partial : Partial +>B : B + +var b02: { [P in keyof BP]: BP[P] } +>b02 : BP +>P : P +>BP : BP +>BP : BP +>P : P + +var b02: Pick; +>b02 : BP +>Pick : Pick +>BP : BP +>BP : BP + +var b03: BR; +>b03 : BR +>BR : BR + +var b03: { readonly [P in keyof B]: B[P] }; +>b03 : BR +>P : P +>B : B +>B : B +>P : P + +var b03: Readonly; +>b03 : BR +>Readonly : Readonly +>B : B + +var b03: { [P in keyof BR]: BR[P] } +>b03 : BR +>P : P +>BR : BR +>BR : BR +>P : P + +var b03: Pick; +>b03 : BR +>Pick : Pick +>BR : BR +>BR : BR + +var b04: BPR; +>b04 : BPR +>BPR : BPR + +var b04: { readonly [P in keyof B]?: B[P] }; +>b04 : BPR +>P : P +>B : B +>B : B +>P : P + +var b04: Partial
; +>b04 : BPR +>Partial : Partial +>BR : BR + +var b04: Readonly; +>b04 : BPR +>Readonly : Readonly +>BP : BP + +var b04: Partial>; +>b04 : BPR +>Partial : Partial +>Readonly : Readonly +>B : B + +var b04: Readonly>; +>b04 : BPR +>Readonly : Readonly +>Partial : Partial +>B : B + +var b04: { [P in keyof BPR]: BPR[P] } +>b04 : BPR +>P : P +>BPR : BPR +>BPR : BPR +>P : P + +var b04: Pick; +>b04 : BPR +>Pick : Pick +>BPR : BPR +>BPR : BPR + +type Foo = { prop: number, [x: string]: number }; +>Foo : Foo +>prop : number +>x : string + +function f1(x: Partial) { +>f1 : (x: Partial) => void +>x : Partial +>Partial : Partial +>Foo : Foo + + x.prop; // ok +>x.prop : number | undefined +>x : Partial +>prop : number | undefined + + (x["other"] || 0).toFixed(); +>(x["other"] || 0).toFixed() : string +>(x["other"] || 0).toFixed : (fractionDigits?: number | undefined) => string +>(x["other"] || 0) : number +>x["other"] || 0 : number +>x["other"] : number | undefined +>x : Partial +>"other" : "other" +>0 : 0 +>toFixed : (fractionDigits?: number | undefined) => string +} + +function f2(x: Readonly) { +>f2 : (x: Readonly) => void +>x : Readonly +>Readonly : Readonly +>Foo : Foo + + x.prop; // ok +>x.prop : number +>x : Readonly +>prop : number + + x["other"].toFixed(); +>x["other"].toFixed() : string +>x["other"].toFixed : (fractionDigits?: number | undefined) => string +>x["other"] : number +>x : Readonly +>"other" : "other" +>toFixed : (fractionDigits?: number | undefined) => string +} + +function f3(x: Boxified) { +>f3 : (x: Boxified) => void +>x : Boxified +>Boxified : Boxified +>Foo : Foo + + x.prop; // ok +>x.prop : { x: number; } +>x : Boxified +>prop : { x: number; } + + x["other"].x.toFixed(); +>x["other"].x.toFixed() : string +>x["other"].x.toFixed : (fractionDigits?: number | undefined) => string +>x["other"].x : number +>x["other"] : { x: number; } +>x : Boxified +>"other" : "other" +>x : number +>toFixed : (fractionDigits?: number | undefined) => string +} + +function f4(x: { [P in keyof Foo]: Foo[P] }) { +>f4 : (x: { [x: string]: number; prop: number; }) => void +>x : { [x: string]: number; prop: number; } +>P : P +>Foo : Foo +>Foo : Foo +>P : P + + x.prop; // ok +>x.prop : number +>x : { [x: string]: number; prop: number; } +>prop : number + + x["other"].toFixed(); +>x["other"].toFixed() : string +>x["other"].toFixed : (fractionDigits?: number | undefined) => string +>x["other"] : number +>x : { [x: string]: number; prop: number; } +>"other" : "other" +>toFixed : (fractionDigits?: number | undefined) => string +} + diff --git a/tests/baselines/reference/mappedTypeRelationships.errors.txt b/tests/baselines/reference/mappedTypeRelationships.errors.txt new file mode 100644 index 00000000000..e8e0371ed9a --- /dev/null +++ b/tests/baselines/reference/mappedTypeRelationships.errors.txt @@ -0,0 +1,183 @@ +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(12,5): error TS2322: Type 'T[keyof T]' is not assignable to type 'U[keyof T]'. + Type 'T' is not assignable to type 'U'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(17,5): error TS2322: Type 'T[K]' is not assignable to type 'U[K]'. + Type 'T' is not assignable to type 'U'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(21,5): error TS2536: Type 'keyof U' cannot be used to index type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(22,12): error TS2536: Type 'keyof U' cannot be used to index type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(26,5): error TS2536: Type 'K' cannot be used to index type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(27,12): error TS2536: Type 'K' cannot be used to index type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(31,5): error TS2322: Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'. + Type 'undefined' is not assignable to type 'T[keyof T]'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(36,5): error TS2322: Type 'T[K] | undefined' is not assignable to type 'T[K]'. + Type 'undefined' is not assignable to type 'T[K]'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(41,5): error TS2322: Type 'U[keyof T] | undefined' is not assignable to type 'T[keyof T]'. + Type 'undefined' is not assignable to type 'T[keyof T]'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(42,5): error TS2322: Type 'T[keyof T]' is not assignable to type 'U[keyof T] | undefined'. + Type 'T[keyof T]' is not assignable to type 'U[keyof T]'. + Type 'T' is not assignable to type 'U'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(46,5): error TS2322: Type 'U[K] | undefined' is not assignable to type 'T[K]'. + Type 'undefined' is not assignable to type 'T[K]'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(47,5): error TS2322: Type 'T[K]' is not assignable to type 'U[K] | undefined'. + Type 'T[K]' is not assignable to type 'U[K]'. + Type 'T' is not assignable to type 'U'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(52,5): error TS2542: Index signature in type 'Readonly' only permits reading. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(57,5): error TS2542: Index signature in type 'Readonly' only permits reading. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(62,5): error TS2542: Index signature in type 'Readonly' only permits reading. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(67,5): error TS2542: Index signature in type 'Readonly' only permits reading. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(71,5): error TS2322: Type 'Partial' is not assignable to type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(76,5): error TS2322: Type 'Partial' is not assignable to type 'T'. + + +==== tests/cases/conformance/types/mapped/mappedTypeRelationships.ts (18 errors) ==== + + function f1(x: T, k: keyof T) { + return x[k]; + } + + function f2(x: T, k: K) { + return x[k]; + } + + function f3(x: T, y: U, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[keyof T]' is not assignable to type 'U[keyof T]'. +!!! error TS2322: Type 'T' is not assignable to type 'U'. + } + + function f4(x: T, y: U, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[K]' is not assignable to type 'U[K]'. +!!! error TS2322: Type 'T' is not assignable to type 'U'. + } + + function f5(x: T, y: U, k: keyof U) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2536: Type 'keyof U' cannot be used to index type 'T'. + y[k] = x[k]; // Error + ~~~~ +!!! error TS2536: Type 'keyof U' cannot be used to index type 'T'. + } + + function f6(x: T, y: U, k: K) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2536: Type 'K' cannot be used to index type 'T'. + y[k] = x[k]; // Error + ~~~~ +!!! error TS2536: Type 'K' cannot be used to index type 'T'. + } + + function f10(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'. +!!! error TS2322: Type 'undefined' is not assignable to type 'T[keyof T]'. + y[k] = x[k]; + } + + function f11(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[K] | undefined' is not assignable to type 'T[K]'. +!!! error TS2322: Type 'undefined' is not assignable to type 'T[K]'. + y[k] = x[k]; + } + + function f12(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2322: Type 'U[keyof T] | undefined' is not assignable to type 'T[keyof T]'. +!!! error TS2322: Type 'undefined' is not assignable to type 'T[keyof T]'. + y[k] = x[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[keyof T]' is not assignable to type 'U[keyof T] | undefined'. +!!! error TS2322: Type 'T[keyof T]' is not assignable to type 'U[keyof T]'. +!!! error TS2322: Type 'T' is not assignable to type 'U'. + } + + function f13(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + ~~~~ +!!! error TS2322: Type 'U[K] | undefined' is not assignable to type 'T[K]'. +!!! error TS2322: Type 'undefined' is not assignable to type 'T[K]'. + y[k] = x[k]; // Error + ~~~~ +!!! error TS2322: Type 'T[K]' is not assignable to type 'U[K] | undefined'. +!!! error TS2322: Type 'T[K]' is not assignable to type 'U[K]'. +!!! error TS2322: Type 'T' is not assignable to type 'U'. + } + + function f20(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2542: Index signature in type 'Readonly' only permits reading. + } + + function f21(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2542: Index signature in type 'Readonly' only permits reading. + } + + function f22(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2542: Index signature in type 'Readonly' only permits reading. + } + + function f23(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error + ~~~~ +!!! error TS2542: Index signature in type 'Readonly' only permits reading. + } + + function f30(x: T, y: Partial) { + x = y; // Error + ~ +!!! error TS2322: Type 'Partial' is not assignable to type 'T'. + y = x; + } + + function f31(x: T, y: Partial) { + x = y; // Error + ~ +!!! error TS2322: Type 'Partial' is not assignable to type 'T'. + y = x; + } + + function f40(x: T, y: Readonly) { + x = y; + y = x; + } + + function f41(x: T, y: Readonly) { + x = y; + y = x; + } + + type Item = { + name: string; + } + + type ItemMap = { + [x: string]: Item; + } + + function f50(obj: T, key: keyof T) { + let item: Item = obj[key]; + return obj[key].name; + } + + function f51(obj: T, key: K) { + let item: Item = obj[key]; + return obj[key].name; + } \ No newline at end of file diff --git a/tests/baselines/reference/mappedTypeRelationships.js b/tests/baselines/reference/mappedTypeRelationships.js new file mode 100644 index 00000000000..a81ff973da8 --- /dev/null +++ b/tests/baselines/reference/mappedTypeRelationships.js @@ -0,0 +1,216 @@ +//// [mappedTypeRelationships.ts] + +function f1(x: T, k: keyof T) { + return x[k]; +} + +function f2(x: T, k: K) { + return x[k]; +} + +function f3(x: T, y: U, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f4(x: T, y: U, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f5(x: T, y: U, k: keyof U) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f6(x: T, y: U, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f10(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + y[k] = x[k]; +} + +function f11(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; +} + +function f12(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f13(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f20(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f21(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f22(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f23(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f30(x: T, y: Partial) { + x = y; // Error + y = x; +} + +function f31(x: T, y: Partial) { + x = y; // Error + y = x; +} + +function f40(x: T, y: Readonly) { + x = y; + y = x; +} + +function f41(x: T, y: Readonly) { + x = y; + y = x; +} + +type Item = { + name: string; +} + +type ItemMap = { + [x: string]: Item; +} + +function f50(obj: T, key: keyof T) { + let item: Item = obj[key]; + return obj[key].name; +} + +function f51(obj: T, key: K) { + let item: Item = obj[key]; + return obj[key].name; +} + +//// [mappedTypeRelationships.js] +function f1(x, k) { + return x[k]; +} +function f2(x, k) { + return x[k]; +} +function f3(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f4(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f5(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} +function f6(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} +function f10(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; +} +function f11(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; +} +function f12(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} +function f13(x, y, k) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} +function f20(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f21(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f22(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f23(x, y, k) { + x[k] = y[k]; + y[k] = x[k]; // Error +} +function f30(x, y) { + x = y; // Error + y = x; +} +function f31(x, y) { + x = y; // Error + y = x; +} +function f40(x, y) { + x = y; + y = x; +} +function f41(x, y) { + x = y; + y = x; +} +function f50(obj, key) { + var item = obj[key]; + return obj[key].name; +} +function f51(obj, key) { + var item = obj[key]; + return obj[key].name; +} + + +//// [mappedTypeRelationships.d.ts] +declare function f1(x: T, k: keyof T): T[keyof T]; +declare function f2(x: T, k: K): T[K]; +declare function f3(x: T, y: U, k: keyof T): void; +declare function f4(x: T, y: U, k: K): void; +declare function f5(x: T, y: U, k: keyof U): void; +declare function f6(x: T, y: U, k: K): void; +declare function f10(x: T, y: Partial, k: keyof T): void; +declare function f11(x: T, y: Partial, k: K): void; +declare function f12(x: T, y: Partial, k: keyof T): void; +declare function f13(x: T, y: Partial, k: K): void; +declare function f20(x: T, y: Readonly, k: keyof T): void; +declare function f21(x: T, y: Readonly, k: K): void; +declare function f22(x: T, y: Readonly, k: keyof T): void; +declare function f23(x: T, y: Readonly, k: K): void; +declare function f30(x: T, y: Partial): void; +declare function f31(x: T, y: Partial): void; +declare function f40(x: T, y: Readonly): void; +declare function f41(x: T, y: Readonly): void; +declare type Item = { + name: string; +}; +declare type ItemMap = { + [x: string]: Item; +}; +declare function f50(obj: T, key: keyof T): string; +declare function f51(obj: T, key: K): string; diff --git a/tests/baselines/reference/mappedTypes1.js b/tests/baselines/reference/mappedTypes1.js new file mode 100644 index 00000000000..1998ad5ab6b --- /dev/null +++ b/tests/baselines/reference/mappedTypes1.js @@ -0,0 +1,147 @@ +//// [mappedTypes1.ts] + +type Item = { a: string, b: number, c: boolean }; + +type T00 = { [P in "x" | "y"]: number }; +type T01 = { [P in "x" | "y"]: P }; +type T02 = { [P in "a" | "b"]: Item[P]; } +type T03 = { [P in keyof Item]: Date }; + +type T10 = { [P in keyof Item]: Item[P] }; +type T11 = { [P in keyof Item]?: Item[P] }; +type T12 = { readonly [P in keyof Item]: Item[P] }; +type T13 = { readonly [P in keyof Item]?: Item[P] }; + +type T20 = { [P in keyof Item]: Item[P] | null }; +type T21 = { [P in keyof Item]: Array }; + +type T30 = { [P in keyof any]: void }; +type T31 = { [P in keyof string]: void }; +type T32 = { [P in keyof number]: void }; +type T33 = { [P in keyof boolean]: void }; +type T34 = { [P in keyof undefined]: void }; +type T35 = { [P in keyof null]: void }; +type T36 = { [P in keyof void]: void }; +type T37 = { [P in keyof symbol]: void }; +type T38 = { [P in keyof never]: void }; + +type T40 = { [P in string]: void }; +type T43 = { [P in "a" | "b"]: void }; +type T44 = { [P in "a" | "b" | "0" | "1"]: void }; +type T47 = { [P in string | "a" | "b" | "0" | "1"]: void }; + +declare function f1(): { [P in keyof T1]: void }; +declare function f2(): { [P in keyof T1]: void }; +declare function f3(): { [P in keyof T1]: void }; +declare function f4(): { [P in keyof T1]: void }; + +let x1 = f1(); +let x2 = f2(); +let x3 = f3(); +let x4 = f4(); + +//// [mappedTypes1.js] +var x1 = f1(); +var x2 = f2(); +var x3 = f3(); +var x4 = f4(); + + +//// [mappedTypes1.d.ts] +declare type Item = { + a: string; + b: number; + c: boolean; +}; +declare type T00 = { + [P in "x" | "y"]: number; +}; +declare type T01 = { + [P in "x" | "y"]: P; +}; +declare type T02 = { + [P in "a" | "b"]: Item[P]; +}; +declare type T03 = { + [P in keyof Item]: Date; +}; +declare type T10 = { + [P in keyof Item]: Item[P]; +}; +declare type T11 = { + [P in keyof Item]?: Item[P]; +}; +declare type T12 = { + readonly [P in keyof Item]: Item[P]; +}; +declare type T13 = { + readonly [P in keyof Item]?: Item[P]; +}; +declare type T20 = { + [P in keyof Item]: Item[P] | null; +}; +declare type T21 = { + [P in keyof Item]: Array; +}; +declare type T30 = { + [P in keyof any]: void; +}; +declare type T31 = { + [P in keyof string]: void; +}; +declare type T32 = { + [P in keyof number]: void; +}; +declare type T33 = { + [P in keyof boolean]: void; +}; +declare type T34 = { + [P in keyof undefined]: void; +}; +declare type T35 = { + [P in keyof null]: void; +}; +declare type T36 = { + [P in keyof void]: void; +}; +declare type T37 = { + [P in keyof symbol]: void; +}; +declare type T38 = { + [P in keyof never]: void; +}; +declare type T40 = { + [P in string]: void; +}; +declare type T43 = { + [P in "a" | "b"]: void; +}; +declare type T44 = { + [P in "a" | "b" | "0" | "1"]: void; +}; +declare type T47 = { + [P in string | "a" | "b" | "0" | "1"]: void; +}; +declare function f1(): { + [P in keyof T1]: void; +}; +declare function f2(): { + [P in keyof T1]: void; +}; +declare function f3(): { + [P in keyof T1]: void; +}; +declare function f4(): { + [P in keyof T1]: void; +}; +declare let x1: {}; +declare let x2: string; +declare let x3: number; +declare let x4: { + toString: void; + valueOf: void; + toFixed: void; + toExponential: void; + toPrecision: void; + toLocaleString: void; +}; diff --git a/tests/baselines/reference/mappedTypes1.symbols b/tests/baselines/reference/mappedTypes1.symbols new file mode 100644 index 00000000000..e8c09b25989 --- /dev/null +++ b/tests/baselines/reference/mappedTypes1.symbols @@ -0,0 +1,165 @@ +=== tests/cases/conformance/types/mapped/mappedTypes1.ts === + +type Item = { a: string, b: number, c: boolean }; +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>a : Symbol(a, Decl(mappedTypes1.ts, 1, 13)) +>b : Symbol(b, Decl(mappedTypes1.ts, 1, 24)) +>c : Symbol(c, Decl(mappedTypes1.ts, 1, 35)) + +type T00 = { [P in "x" | "y"]: number }; +>T00 : Symbol(T00, Decl(mappedTypes1.ts, 1, 49)) +>P : Symbol(P, Decl(mappedTypes1.ts, 3, 14)) + +type T01 = { [P in "x" | "y"]: P }; +>T01 : Symbol(T01, Decl(mappedTypes1.ts, 3, 40)) +>P : Symbol(P, Decl(mappedTypes1.ts, 4, 14)) +>P : Symbol(P, Decl(mappedTypes1.ts, 4, 14)) + +type T02 = { [P in "a" | "b"]: Item[P]; } +>T02 : Symbol(T02, Decl(mappedTypes1.ts, 4, 35)) +>P : Symbol(P, Decl(mappedTypes1.ts, 5, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 5, 14)) + +type T03 = { [P in keyof Item]: Date }; +>T03 : Symbol(T03, Decl(mappedTypes1.ts, 5, 41)) +>P : Symbol(P, Decl(mappedTypes1.ts, 6, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + +type T10 = { [P in keyof Item]: Item[P] }; +>T10 : Symbol(T10, Decl(mappedTypes1.ts, 6, 39)) +>P : Symbol(P, Decl(mappedTypes1.ts, 8, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 8, 14)) + +type T11 = { [P in keyof Item]?: Item[P] }; +>T11 : Symbol(T11, Decl(mappedTypes1.ts, 8, 42)) +>P : Symbol(P, Decl(mappedTypes1.ts, 9, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 9, 14)) + +type T12 = { readonly [P in keyof Item]: Item[P] }; +>T12 : Symbol(T12, Decl(mappedTypes1.ts, 9, 43)) +>P : Symbol(P, Decl(mappedTypes1.ts, 10, 23)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 10, 23)) + +type T13 = { readonly [P in keyof Item]?: Item[P] }; +>T13 : Symbol(T13, Decl(mappedTypes1.ts, 10, 51)) +>P : Symbol(P, Decl(mappedTypes1.ts, 11, 23)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 11, 23)) + +type T20 = { [P in keyof Item]: Item[P] | null }; +>T20 : Symbol(T20, Decl(mappedTypes1.ts, 11, 52)) +>P : Symbol(P, Decl(mappedTypes1.ts, 13, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 13, 14)) + +type T21 = { [P in keyof Item]: Array }; +>T21 : Symbol(T21, Decl(mappedTypes1.ts, 13, 49)) +>P : Symbol(P, Decl(mappedTypes1.ts, 14, 14)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>Item : Symbol(Item, Decl(mappedTypes1.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes1.ts, 14, 14)) + +type T30 = { [P in keyof any]: void }; +>T30 : Symbol(T30, Decl(mappedTypes1.ts, 14, 49)) +>P : Symbol(P, Decl(mappedTypes1.ts, 16, 14)) + +type T31 = { [P in keyof string]: void }; +>T31 : Symbol(T31, Decl(mappedTypes1.ts, 16, 38)) +>P : Symbol(P, Decl(mappedTypes1.ts, 17, 14)) + +type T32 = { [P in keyof number]: void }; +>T32 : Symbol(T32, Decl(mappedTypes1.ts, 17, 41)) +>P : Symbol(P, Decl(mappedTypes1.ts, 18, 14)) + +type T33 = { [P in keyof boolean]: void }; +>T33 : Symbol(T33, Decl(mappedTypes1.ts, 18, 41)) +>P : Symbol(P, Decl(mappedTypes1.ts, 19, 14)) + +type T34 = { [P in keyof undefined]: void }; +>T34 : Symbol(T34, Decl(mappedTypes1.ts, 19, 42)) +>P : Symbol(P, Decl(mappedTypes1.ts, 20, 14)) + +type T35 = { [P in keyof null]: void }; +>T35 : Symbol(T35, Decl(mappedTypes1.ts, 20, 44)) +>P : Symbol(P, Decl(mappedTypes1.ts, 21, 14)) + +type T36 = { [P in keyof void]: void }; +>T36 : Symbol(T36, Decl(mappedTypes1.ts, 21, 39)) +>P : Symbol(P, Decl(mappedTypes1.ts, 22, 14)) + +type T37 = { [P in keyof symbol]: void }; +>T37 : Symbol(T37, Decl(mappedTypes1.ts, 22, 39)) +>P : Symbol(P, Decl(mappedTypes1.ts, 23, 14)) + +type T38 = { [P in keyof never]: void }; +>T38 : Symbol(T38, Decl(mappedTypes1.ts, 23, 41)) +>P : Symbol(P, Decl(mappedTypes1.ts, 24, 14)) + +type T40 = { [P in string]: void }; +>T40 : Symbol(T40, Decl(mappedTypes1.ts, 24, 40)) +>P : Symbol(P, Decl(mappedTypes1.ts, 26, 14)) + +type T43 = { [P in "a" | "b"]: void }; +>T43 : Symbol(T43, Decl(mappedTypes1.ts, 26, 35)) +>P : Symbol(P, Decl(mappedTypes1.ts, 27, 14)) + +type T44 = { [P in "a" | "b" | "0" | "1"]: void }; +>T44 : Symbol(T44, Decl(mappedTypes1.ts, 27, 38)) +>P : Symbol(P, Decl(mappedTypes1.ts, 28, 14)) + +type T47 = { [P in string | "a" | "b" | "0" | "1"]: void }; +>T47 : Symbol(T47, Decl(mappedTypes1.ts, 28, 50)) +>P : Symbol(P, Decl(mappedTypes1.ts, 29, 14)) + +declare function f1(): { [P in keyof T1]: void }; +>f1 : Symbol(f1, Decl(mappedTypes1.ts, 29, 59)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 31, 20)) +>P : Symbol(P, Decl(mappedTypes1.ts, 31, 30)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 31, 20)) + +declare function f2(): { [P in keyof T1]: void }; +>f2 : Symbol(f2, Decl(mappedTypes1.ts, 31, 53)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 32, 20)) +>P : Symbol(P, Decl(mappedTypes1.ts, 32, 45)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 32, 20)) + +declare function f3(): { [P in keyof T1]: void }; +>f3 : Symbol(f3, Decl(mappedTypes1.ts, 32, 68)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 33, 20)) +>P : Symbol(P, Decl(mappedTypes1.ts, 33, 45)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 33, 20)) + +declare function f4(): { [P in keyof T1]: void }; +>f4 : Symbol(f4, Decl(mappedTypes1.ts, 33, 68)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 34, 20)) +>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>P : Symbol(P, Decl(mappedTypes1.ts, 34, 45)) +>T1 : Symbol(T1, Decl(mappedTypes1.ts, 34, 20)) + +let x1 = f1(); +>x1 : Symbol(x1, Decl(mappedTypes1.ts, 36, 3)) +>f1 : Symbol(f1, Decl(mappedTypes1.ts, 29, 59)) + +let x2 = f2(); +>x2 : Symbol(x2, Decl(mappedTypes1.ts, 37, 3)) +>f2 : Symbol(f2, Decl(mappedTypes1.ts, 31, 53)) + +let x3 = f3(); +>x3 : Symbol(x3, Decl(mappedTypes1.ts, 38, 3)) +>f3 : Symbol(f3, Decl(mappedTypes1.ts, 32, 68)) + +let x4 = f4(); +>x4 : Symbol(x4, Decl(mappedTypes1.ts, 39, 3)) +>f4 : Symbol(f4, Decl(mappedTypes1.ts, 33, 68)) + diff --git a/tests/baselines/reference/mappedTypes1.types b/tests/baselines/reference/mappedTypes1.types new file mode 100644 index 00000000000..35d13143bab --- /dev/null +++ b/tests/baselines/reference/mappedTypes1.types @@ -0,0 +1,171 @@ +=== tests/cases/conformance/types/mapped/mappedTypes1.ts === + +type Item = { a: string, b: number, c: boolean }; +>Item : Item +>a : string +>b : number +>c : boolean + +type T00 = { [P in "x" | "y"]: number }; +>T00 : T00 +>P : P + +type T01 = { [P in "x" | "y"]: P }; +>T01 : T01 +>P : P +>P : P + +type T02 = { [P in "a" | "b"]: Item[P]; } +>T02 : T02 +>P : P +>Item : Item +>P : P + +type T03 = { [P in keyof Item]: Date }; +>T03 : T03 +>P : P +>Item : Item +>Date : Date + +type T10 = { [P in keyof Item]: Item[P] }; +>T10 : T10 +>P : P +>Item : Item +>Item : Item +>P : P + +type T11 = { [P in keyof Item]?: Item[P] }; +>T11 : T11 +>P : P +>Item : Item +>Item : Item +>P : P + +type T12 = { readonly [P in keyof Item]: Item[P] }; +>T12 : T12 +>P : P +>Item : Item +>Item : Item +>P : P + +type T13 = { readonly [P in keyof Item]?: Item[P] }; +>T13 : T13 +>P : P +>Item : Item +>Item : Item +>P : P + +type T20 = { [P in keyof Item]: Item[P] | null }; +>T20 : T20 +>P : P +>Item : Item +>Item : Item +>P : P +>null : null + +type T21 = { [P in keyof Item]: Array }; +>T21 : T21 +>P : P +>Item : Item +>Array : T[] +>Item : Item +>P : P + +type T30 = { [P in keyof any]: void }; +>T30 : T30 +>P : P + +type T31 = { [P in keyof string]: void }; +>T31 : T31 +>P : P + +type T32 = { [P in keyof number]: void }; +>T32 : T32 +>P : P + +type T33 = { [P in keyof boolean]: void }; +>T33 : T33 +>P : P + +type T34 = { [P in keyof undefined]: void }; +>T34 : T34 +>P : P + +type T35 = { [P in keyof null]: void }; +>T35 : T35 +>P : P +>null : null + +type T36 = { [P in keyof void]: void }; +>T36 : T36 +>P : P + +type T37 = { [P in keyof symbol]: void }; +>T37 : T37 +>P : P + +type T38 = { [P in keyof never]: void }; +>T38 : T38 +>P : P + +type T40 = { [P in string]: void }; +>T40 : T40 +>P : P + +type T43 = { [P in "a" | "b"]: void }; +>T43 : T43 +>P : P + +type T44 = { [P in "a" | "b" | "0" | "1"]: void }; +>T44 : T44 +>P : P + +type T47 = { [P in string | "a" | "b" | "0" | "1"]: void }; +>T47 : T47 +>P : P + +declare function f1(): { [P in keyof T1]: void }; +>f1 : () => { [P in keyof T1]: void; } +>T1 : T1 +>P : P +>T1 : T1 + +declare function f2(): { [P in keyof T1]: void }; +>f2 : () => { [P in keyof T1]: void; } +>T1 : T1 +>P : P +>T1 : T1 + +declare function f3(): { [P in keyof T1]: void }; +>f3 : () => { [P in keyof T1]: void; } +>T1 : T1 +>P : P +>T1 : T1 + +declare function f4(): { [P in keyof T1]: void }; +>f4 : () => { [P in keyof T1]: void; } +>T1 : T1 +>Number : Number +>P : P +>T1 : T1 + +let x1 = f1(); +>x1 : {} +>f1() : {} +>f1 : () => { [P in keyof T1]: void; } + +let x2 = f2(); +>x2 : string +>f2() : string +>f2 : () => { [P in keyof T1]: void; } + +let x3 = f3(); +>x3 : number +>f3() : number +>f3 : () => { [P in keyof T1]: void; } + +let x4 = f4(); +>x4 : { toString: void; valueOf: void; toFixed: void; toExponential: void; toPrecision: void; toLocaleString: void; } +>f4() : { toString: void; valueOf: void; toFixed: void; toExponential: void; toPrecision: void; toLocaleString: void; } +>f4 : () => { [P in keyof T1]: void; } + diff --git a/tests/baselines/reference/mappedTypes2.js b/tests/baselines/reference/mappedTypes2.js new file mode 100644 index 00000000000..84d052b6287 --- /dev/null +++ b/tests/baselines/reference/mappedTypes2.js @@ -0,0 +1,186 @@ +//// [mappedTypes2.ts] + +function verifyLibTypes() { + var x1: Partial; + var x1: { [P in keyof T]?: T[P] }; + var x2: Readonly; + var x2: { readonly [P in keyof T]: T[P] }; + var x3: Pick; + var x3: { [P in K]: T[P] }; + var x4: Record; + var x4: { [P in K]: U }; +} + +type Proxy = { + get(): T; + set(value: T): void; +} + +type Proxify = { + [P in keyof T]: Proxy; +} + +type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; + +declare function assign(obj: T, props: Partial): void; +declare function freeze(obj: T): Readonly; +declare function pick(obj: T, ...keys: K[]): Pick; +declare function mapObject(obj: Record, f: (x: T) => U): Record; +declare function proxify(obj: T): Proxify; + +interface Point { + x: number; + y: number; +} + +interface Shape { + name: string; + width: number; + height: number; + location: Point; +} + +interface PartialShape { + name?: string; + width?: number; + height?: number; + location?: Point; +} + +interface ReadonlyShape { + readonly name: string; + readonly width: number; + readonly height: number; + readonly location: Point; +} + +function f0(s1: Shape, s2: Shape) { + assign(s1, { name: "circle" }); + assign(s2, { width: 10, height: 20 }); +} + +function f1(shape: Shape) { + var frozen: ReadonlyShape; + var frozen: Readonly; + var frozen = freeze(shape); +} + +function f2(shape: Shape) { + var partial: PartialShape; + var partial: Partial; + var partial: Partial = {}; +} + +function f3(shape: Shape) { + const x = pick(shape, "name", "location"); // { name: string, location: Point } +} + +function f4() { + const rec = { foo: "hello", bar: "world", baz: "bye" }; + const lengths = mapObject(rec, s => s.length); // { foo: number, bar: number, baz: number } +} + +function f5(shape: Shape) { + const p = proxify(shape); + let name = p.name.get(); + p.width.set(42); +} + +function f6(shape: DeepReadonly) { + let name = shape.name; // string + let location = shape.location; // DeepReadonly + let x = location.x; // number +} + +//// [mappedTypes2.js] +function verifyLibTypes() { + var x1; + var x1; + var x2; + var x2; + var x3; + var x3; + var x4; + var x4; +} +function f0(s1, s2) { + assign(s1, { name: "circle" }); + assign(s2, { width: 10, height: 20 }); +} +function f1(shape) { + var frozen; + var frozen; + var frozen = freeze(shape); +} +function f2(shape) { + var partial; + var partial; + var partial = {}; +} +function f3(shape) { + var x = pick(shape, "name", "location"); // { name: string, location: Point } +} +function f4() { + var rec = { foo: "hello", bar: "world", baz: "bye" }; + var lengths = mapObject(rec, function (s) { return s.length; }); // { foo: number, bar: number, baz: number } +} +function f5(shape) { + var p = proxify(shape); + var name = p.name.get(); + p.width.set(42); +} +function f6(shape) { + var name = shape.name; // string + var location = shape.location; // DeepReadonly + var x = location.x; // number +} + + +//// [mappedTypes2.d.ts] +declare function verifyLibTypes(): void; +declare type Proxy = { + get(): T; + set(value: T): void; +}; +declare type Proxify = { + [P in keyof T]: Proxy; +}; +declare type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; +declare function assign(obj: T, props: Partial): void; +declare function freeze(obj: T): Readonly; +declare function pick(obj: T, ...keys: K[]): Pick; +declare function mapObject(obj: Record, f: (x: T) => U): Record; +declare function proxify(obj: T): Proxify; +interface Point { + x: number; + y: number; +} +interface Shape { + name: string; + width: number; + height: number; + location: Point; +} +interface PartialShape { + name?: string; + width?: number; + height?: number; + location?: Point; +} +interface ReadonlyShape { + readonly name: string; + readonly width: number; + readonly height: number; + readonly location: Point; +} +declare function f0(s1: Shape, s2: Shape): void; +declare function f1(shape: Shape): void; +declare function f2(shape: Shape): void; +declare function f3(shape: Shape): void; +declare function f4(): void; +declare function f5(shape: Shape): void; +declare function f6(shape: DeepReadonly): void; diff --git a/tests/baselines/reference/mappedTypes2.symbols b/tests/baselines/reference/mappedTypes2.symbols new file mode 100644 index 00000000000..079a56243c5 --- /dev/null +++ b/tests/baselines/reference/mappedTypes2.symbols @@ -0,0 +1,353 @@ +=== tests/cases/conformance/types/mapped/mappedTypes2.ts === + +function verifyLibTypes() { +>verifyLibTypes : Symbol(verifyLibTypes, Decl(mappedTypes2.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>K : Symbol(K, Decl(mappedTypes2.ts, 1, 26)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>U : Symbol(U, Decl(mappedTypes2.ts, 1, 45)) + + var x1: Partial; +>x1 : Symbol(x1, Decl(mappedTypes2.ts, 2, 7), Decl(mappedTypes2.ts, 3, 7)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) + + var x1: { [P in keyof T]?: T[P] }; +>x1 : Symbol(x1, Decl(mappedTypes2.ts, 2, 7), Decl(mappedTypes2.ts, 3, 7)) +>P : Symbol(P, Decl(mappedTypes2.ts, 3, 15)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>P : Symbol(P, Decl(mappedTypes2.ts, 3, 15)) + + var x2: Readonly; +>x2 : Symbol(x2, Decl(mappedTypes2.ts, 4, 7), Decl(mappedTypes2.ts, 5, 7)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) + + var x2: { readonly [P in keyof T]: T[P] }; +>x2 : Symbol(x2, Decl(mappedTypes2.ts, 4, 7), Decl(mappedTypes2.ts, 5, 7)) +>P : Symbol(P, Decl(mappedTypes2.ts, 5, 24)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>P : Symbol(P, Decl(mappedTypes2.ts, 5, 24)) + + var x3: Pick; +>x3 : Symbol(x3, Decl(mappedTypes2.ts, 6, 7), Decl(mappedTypes2.ts, 7, 7)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>K : Symbol(K, Decl(mappedTypes2.ts, 1, 26)) + + var x3: { [P in K]: T[P] }; +>x3 : Symbol(x3, Decl(mappedTypes2.ts, 6, 7), Decl(mappedTypes2.ts, 7, 7)) +>P : Symbol(P, Decl(mappedTypes2.ts, 7, 15)) +>K : Symbol(K, Decl(mappedTypes2.ts, 1, 26)) +>T : Symbol(T, Decl(mappedTypes2.ts, 1, 24)) +>P : Symbol(P, Decl(mappedTypes2.ts, 7, 15)) + + var x4: Record; +>x4 : Symbol(x4, Decl(mappedTypes2.ts, 8, 7), Decl(mappedTypes2.ts, 9, 7)) +>Record : Symbol(Record, Decl(lib.d.ts, --, --)) +>K : Symbol(K, Decl(mappedTypes2.ts, 1, 26)) +>U : Symbol(U, Decl(mappedTypes2.ts, 1, 45)) + + var x4: { [P in K]: U }; +>x4 : Symbol(x4, Decl(mappedTypes2.ts, 8, 7), Decl(mappedTypes2.ts, 9, 7)) +>P : Symbol(P, Decl(mappedTypes2.ts, 9, 15)) +>K : Symbol(K, Decl(mappedTypes2.ts, 1, 26)) +>U : Symbol(U, Decl(mappedTypes2.ts, 1, 45)) +} + +type Proxy = { +>Proxy : Symbol(Proxy, Decl(mappedTypes2.ts, 10, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 12, 11)) + + get(): T; +>get : Symbol(get, Decl(mappedTypes2.ts, 12, 17)) +>T : Symbol(T, Decl(mappedTypes2.ts, 12, 11)) + + set(value: T): void; +>set : Symbol(set, Decl(mappedTypes2.ts, 13, 13)) +>value : Symbol(value, Decl(mappedTypes2.ts, 14, 8)) +>T : Symbol(T, Decl(mappedTypes2.ts, 12, 11)) +} + +type Proxify = { +>Proxify : Symbol(Proxify, Decl(mappedTypes2.ts, 15, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 17, 13)) + + [P in keyof T]: Proxy; +>P : Symbol(P, Decl(mappedTypes2.ts, 18, 5)) +>T : Symbol(T, Decl(mappedTypes2.ts, 17, 13)) +>Proxy : Symbol(Proxy, Decl(mappedTypes2.ts, 10, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 17, 13)) +>P : Symbol(P, Decl(mappedTypes2.ts, 18, 5)) +} + +type DeepReadonly = { +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes2.ts, 19, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 21, 18)) + + readonly [P in keyof T]: DeepReadonly; +>P : Symbol(P, Decl(mappedTypes2.ts, 22, 14)) +>T : Symbol(T, Decl(mappedTypes2.ts, 21, 18)) +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes2.ts, 19, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 21, 18)) +>P : Symbol(P, Decl(mappedTypes2.ts, 22, 14)) + +}; + +declare function assign(obj: T, props: Partial): void; +>assign : Symbol(assign, Decl(mappedTypes2.ts, 23, 2)) +>T : Symbol(T, Decl(mappedTypes2.ts, 25, 24)) +>obj : Symbol(obj, Decl(mappedTypes2.ts, 25, 27)) +>T : Symbol(T, Decl(mappedTypes2.ts, 25, 24)) +>props : Symbol(props, Decl(mappedTypes2.ts, 25, 34)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 25, 24)) + +declare function freeze(obj: T): Readonly; +>freeze : Symbol(freeze, Decl(mappedTypes2.ts, 25, 60)) +>T : Symbol(T, Decl(mappedTypes2.ts, 26, 24)) +>obj : Symbol(obj, Decl(mappedTypes2.ts, 26, 27)) +>T : Symbol(T, Decl(mappedTypes2.ts, 26, 24)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 26, 24)) + +declare function pick(obj: T, ...keys: K[]): Pick; +>pick : Symbol(pick, Decl(mappedTypes2.ts, 26, 48)) +>T : Symbol(T, Decl(mappedTypes2.ts, 27, 22)) +>K : Symbol(K, Decl(mappedTypes2.ts, 27, 24)) +>T : Symbol(T, Decl(mappedTypes2.ts, 27, 22)) +>obj : Symbol(obj, Decl(mappedTypes2.ts, 27, 44)) +>T : Symbol(T, Decl(mappedTypes2.ts, 27, 22)) +>keys : Symbol(keys, Decl(mappedTypes2.ts, 27, 51)) +>K : Symbol(K, Decl(mappedTypes2.ts, 27, 24)) +>Pick : Symbol(Pick, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypes2.ts, 27, 22)) +>K : Symbol(K, Decl(mappedTypes2.ts, 27, 24)) + +declare function mapObject(obj: Record, f: (x: T) => U): Record; +>mapObject : Symbol(mapObject, Decl(mappedTypes2.ts, 27, 78)) +>K : Symbol(K, Decl(mappedTypes2.ts, 28, 27)) +>T : Symbol(T, Decl(mappedTypes2.ts, 28, 44)) +>U : Symbol(U, Decl(mappedTypes2.ts, 28, 47)) +>obj : Symbol(obj, Decl(mappedTypes2.ts, 28, 51)) +>Record : Symbol(Record, Decl(lib.d.ts, --, --)) +>K : Symbol(K, Decl(mappedTypes2.ts, 28, 27)) +>T : Symbol(T, Decl(mappedTypes2.ts, 28, 44)) +>f : Symbol(f, Decl(mappedTypes2.ts, 28, 69)) +>x : Symbol(x, Decl(mappedTypes2.ts, 28, 74)) +>T : Symbol(T, Decl(mappedTypes2.ts, 28, 44)) +>U : Symbol(U, Decl(mappedTypes2.ts, 28, 47)) +>Record : Symbol(Record, Decl(lib.d.ts, --, --)) +>K : Symbol(K, Decl(mappedTypes2.ts, 28, 27)) +>U : Symbol(U, Decl(mappedTypes2.ts, 28, 47)) + +declare function proxify(obj: T): Proxify; +>proxify : Symbol(proxify, Decl(mappedTypes2.ts, 28, 100)) +>T : Symbol(T, Decl(mappedTypes2.ts, 29, 25)) +>obj : Symbol(obj, Decl(mappedTypes2.ts, 29, 28)) +>T : Symbol(T, Decl(mappedTypes2.ts, 29, 25)) +>Proxify : Symbol(Proxify, Decl(mappedTypes2.ts, 15, 1)) +>T : Symbol(T, Decl(mappedTypes2.ts, 29, 25)) + +interface Point { +>Point : Symbol(Point, Decl(mappedTypes2.ts, 29, 48)) + + x: number; +>x : Symbol(Point.x, Decl(mappedTypes2.ts, 31, 17)) + + y: number; +>y : Symbol(Point.y, Decl(mappedTypes2.ts, 32, 14)) +} + +interface Shape { +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + name: string; +>name : Symbol(Shape.name, Decl(mappedTypes2.ts, 36, 17)) + + width: number; +>width : Symbol(Shape.width, Decl(mappedTypes2.ts, 37, 17)) + + height: number; +>height : Symbol(Shape.height, Decl(mappedTypes2.ts, 38, 18)) + + location: Point; +>location : Symbol(Shape.location, Decl(mappedTypes2.ts, 39, 19)) +>Point : Symbol(Point, Decl(mappedTypes2.ts, 29, 48)) +} + +interface PartialShape { +>PartialShape : Symbol(PartialShape, Decl(mappedTypes2.ts, 41, 1)) + + name?: string; +>name : Symbol(PartialShape.name, Decl(mappedTypes2.ts, 43, 24)) + + width?: number; +>width : Symbol(PartialShape.width, Decl(mappedTypes2.ts, 44, 18)) + + height?: number; +>height : Symbol(PartialShape.height, Decl(mappedTypes2.ts, 45, 19)) + + location?: Point; +>location : Symbol(PartialShape.location, Decl(mappedTypes2.ts, 46, 20)) +>Point : Symbol(Point, Decl(mappedTypes2.ts, 29, 48)) +} + +interface ReadonlyShape { +>ReadonlyShape : Symbol(ReadonlyShape, Decl(mappedTypes2.ts, 48, 1)) + + readonly name: string; +>name : Symbol(ReadonlyShape.name, Decl(mappedTypes2.ts, 50, 25)) + + readonly width: number; +>width : Symbol(ReadonlyShape.width, Decl(mappedTypes2.ts, 51, 26)) + + readonly height: number; +>height : Symbol(ReadonlyShape.height, Decl(mappedTypes2.ts, 52, 27)) + + readonly location: Point; +>location : Symbol(ReadonlyShape.location, Decl(mappedTypes2.ts, 53, 28)) +>Point : Symbol(Point, Decl(mappedTypes2.ts, 29, 48)) +} + +function f0(s1: Shape, s2: Shape) { +>f0 : Symbol(f0, Decl(mappedTypes2.ts, 55, 1)) +>s1 : Symbol(s1, Decl(mappedTypes2.ts, 57, 12)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) +>s2 : Symbol(s2, Decl(mappedTypes2.ts, 57, 22)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + assign(s1, { name: "circle" }); +>assign : Symbol(assign, Decl(mappedTypes2.ts, 23, 2)) +>s1 : Symbol(s1, Decl(mappedTypes2.ts, 57, 12)) +>name : Symbol(name, Decl(mappedTypes2.ts, 58, 16)) + + assign(s2, { width: 10, height: 20 }); +>assign : Symbol(assign, Decl(mappedTypes2.ts, 23, 2)) +>s2 : Symbol(s2, Decl(mappedTypes2.ts, 57, 22)) +>width : Symbol(width, Decl(mappedTypes2.ts, 59, 16)) +>height : Symbol(height, Decl(mappedTypes2.ts, 59, 27)) +} + +function f1(shape: Shape) { +>f1 : Symbol(f1, Decl(mappedTypes2.ts, 60, 1)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 62, 12)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + var frozen: ReadonlyShape; +>frozen : Symbol(frozen, Decl(mappedTypes2.ts, 63, 7), Decl(mappedTypes2.ts, 64, 7), Decl(mappedTypes2.ts, 65, 7)) +>ReadonlyShape : Symbol(ReadonlyShape, Decl(mappedTypes2.ts, 48, 1)) + + var frozen: Readonly; +>frozen : Symbol(frozen, Decl(mappedTypes2.ts, 63, 7), Decl(mappedTypes2.ts, 64, 7), Decl(mappedTypes2.ts, 65, 7)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + var frozen = freeze(shape); +>frozen : Symbol(frozen, Decl(mappedTypes2.ts, 63, 7), Decl(mappedTypes2.ts, 64, 7), Decl(mappedTypes2.ts, 65, 7)) +>freeze : Symbol(freeze, Decl(mappedTypes2.ts, 25, 60)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 62, 12)) +} + +function f2(shape: Shape) { +>f2 : Symbol(f2, Decl(mappedTypes2.ts, 66, 1)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 68, 12)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + var partial: PartialShape; +>partial : Symbol(partial, Decl(mappedTypes2.ts, 69, 7), Decl(mappedTypes2.ts, 70, 7), Decl(mappedTypes2.ts, 71, 7)) +>PartialShape : Symbol(PartialShape, Decl(mappedTypes2.ts, 41, 1)) + + var partial: Partial; +>partial : Symbol(partial, Decl(mappedTypes2.ts, 69, 7), Decl(mappedTypes2.ts, 70, 7), Decl(mappedTypes2.ts, 71, 7)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + var partial: Partial = {}; +>partial : Symbol(partial, Decl(mappedTypes2.ts, 69, 7), Decl(mappedTypes2.ts, 70, 7), Decl(mappedTypes2.ts, 71, 7)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) +} + +function f3(shape: Shape) { +>f3 : Symbol(f3, Decl(mappedTypes2.ts, 72, 1)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 74, 12)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + const x = pick(shape, "name", "location"); // { name: string, location: Point } +>x : Symbol(x, Decl(mappedTypes2.ts, 75, 9)) +>pick : Symbol(pick, Decl(mappedTypes2.ts, 26, 48)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 74, 12)) +} + +function f4() { +>f4 : Symbol(f4, Decl(mappedTypes2.ts, 76, 1)) + + const rec = { foo: "hello", bar: "world", baz: "bye" }; +>rec : Symbol(rec, Decl(mappedTypes2.ts, 79, 9)) +>foo : Symbol(foo, Decl(mappedTypes2.ts, 79, 17)) +>bar : Symbol(bar, Decl(mappedTypes2.ts, 79, 31)) +>baz : Symbol(baz, Decl(mappedTypes2.ts, 79, 45)) + + const lengths = mapObject(rec, s => s.length); // { foo: number, bar: number, baz: number } +>lengths : Symbol(lengths, Decl(mappedTypes2.ts, 80, 9)) +>mapObject : Symbol(mapObject, Decl(mappedTypes2.ts, 27, 78)) +>rec : Symbol(rec, Decl(mappedTypes2.ts, 79, 9)) +>s : Symbol(s, Decl(mappedTypes2.ts, 80, 34)) +>s.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>s : Symbol(s, Decl(mappedTypes2.ts, 80, 34)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) +} + +function f5(shape: Shape) { +>f5 : Symbol(f5, Decl(mappedTypes2.ts, 81, 1)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 83, 12)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + const p = proxify(shape); +>p : Symbol(p, Decl(mappedTypes2.ts, 84, 9)) +>proxify : Symbol(proxify, Decl(mappedTypes2.ts, 28, 100)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 83, 12)) + + let name = p.name.get(); +>name : Symbol(name, Decl(mappedTypes2.ts, 85, 7)) +>p.name.get : Symbol(get, Decl(mappedTypes2.ts, 12, 17)) +>p.name : Symbol(name) +>p : Symbol(p, Decl(mappedTypes2.ts, 84, 9)) +>name : Symbol(name) +>get : Symbol(get, Decl(mappedTypes2.ts, 12, 17)) + + p.width.set(42); +>p.width.set : Symbol(set, Decl(mappedTypes2.ts, 13, 13)) +>p.width : Symbol(width) +>p : Symbol(p, Decl(mappedTypes2.ts, 84, 9)) +>width : Symbol(width) +>set : Symbol(set, Decl(mappedTypes2.ts, 13, 13)) +} + +function f6(shape: DeepReadonly) { +>f6 : Symbol(f6, Decl(mappedTypes2.ts, 87, 1)) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 89, 12)) +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes2.ts, 19, 1)) +>Shape : Symbol(Shape, Decl(mappedTypes2.ts, 34, 1)) + + let name = shape.name; // string +>name : Symbol(name, Decl(mappedTypes2.ts, 90, 7)) +>shape.name : Symbol(name) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 89, 12)) +>name : Symbol(name) + + let location = shape.location; // DeepReadonly +>location : Symbol(location, Decl(mappedTypes2.ts, 91, 7)) +>shape.location : Symbol(location) +>shape : Symbol(shape, Decl(mappedTypes2.ts, 89, 12)) +>location : Symbol(location) + + let x = location.x; // number +>x : Symbol(x, Decl(mappedTypes2.ts, 92, 7)) +>location.x : Symbol(x) +>location : Symbol(location, Decl(mappedTypes2.ts, 91, 7)) +>x : Symbol(x) +} diff --git a/tests/baselines/reference/mappedTypes2.types b/tests/baselines/reference/mappedTypes2.types new file mode 100644 index 00000000000..f082069f569 --- /dev/null +++ b/tests/baselines/reference/mappedTypes2.types @@ -0,0 +1,375 @@ +=== tests/cases/conformance/types/mapped/mappedTypes2.ts === + +function verifyLibTypes() { +>verifyLibTypes : () => void +>T : T +>K : K +>T : T +>U : U + + var x1: Partial; +>x1 : Partial +>Partial : Partial +>T : T + + var x1: { [P in keyof T]?: T[P] }; +>x1 : Partial +>P : P +>T : T +>T : T +>P : P + + var x2: Readonly; +>x2 : Readonly +>Readonly : Readonly +>T : T + + var x2: { readonly [P in keyof T]: T[P] }; +>x2 : Readonly +>P : P +>T : T +>T : T +>P : P + + var x3: Pick; +>x3 : Pick +>Pick : Pick +>T : T +>K : K + + var x3: { [P in K]: T[P] }; +>x3 : Pick +>P : P +>K : K +>T : T +>P : P + + var x4: Record; +>x4 : Record +>Record : Record +>K : K +>U : U + + var x4: { [P in K]: U }; +>x4 : Record +>P : P +>K : K +>U : U +} + +type Proxy = { +>Proxy : Proxy +>T : T + + get(): T; +>get : () => T +>T : T + + set(value: T): void; +>set : (value: T) => void +>value : T +>T : T +} + +type Proxify = { +>Proxify : Proxify +>T : T + + [P in keyof T]: Proxy; +>P : P +>T : T +>Proxy : Proxy +>T : T +>P : P +} + +type DeepReadonly = { +>DeepReadonly : DeepReadonly +>T : T + + readonly [P in keyof T]: DeepReadonly; +>P : P +>T : T +>DeepReadonly : DeepReadonly +>T : T +>P : P + +}; + +declare function assign(obj: T, props: Partial): void; +>assign : (obj: T, props: Partial) => void +>T : T +>obj : T +>T : T +>props : Partial +>Partial : Partial +>T : T + +declare function freeze(obj: T): Readonly; +>freeze : (obj: T) => Readonly +>T : T +>obj : T +>T : T +>Readonly : Readonly +>T : T + +declare function pick(obj: T, ...keys: K[]): Pick; +>pick : (obj: T, ...keys: K[]) => Pick +>T : T +>K : K +>T : T +>obj : T +>T : T +>keys : K[] +>K : K +>Pick : Pick +>T : T +>K : K + +declare function mapObject(obj: Record, f: (x: T) => U): Record; +>mapObject : (obj: Record, f: (x: T) => U) => Record +>K : K +>T : T +>U : U +>obj : Record +>Record : Record +>K : K +>T : T +>f : (x: T) => U +>x : T +>T : T +>U : U +>Record : Record +>K : K +>U : U + +declare function proxify(obj: T): Proxify; +>proxify : (obj: T) => Proxify +>T : T +>obj : T +>T : T +>Proxify : Proxify +>T : T + +interface Point { +>Point : Point + + x: number; +>x : number + + y: number; +>y : number +} + +interface Shape { +>Shape : Shape + + name: string; +>name : string + + width: number; +>width : number + + height: number; +>height : number + + location: Point; +>location : Point +>Point : Point +} + +interface PartialShape { +>PartialShape : PartialShape + + name?: string; +>name : string | undefined + + width?: number; +>width : number | undefined + + height?: number; +>height : number | undefined + + location?: Point; +>location : Point | undefined +>Point : Point +} + +interface ReadonlyShape { +>ReadonlyShape : ReadonlyShape + + readonly name: string; +>name : string + + readonly width: number; +>width : number + + readonly height: number; +>height : number + + readonly location: Point; +>location : Point +>Point : Point +} + +function f0(s1: Shape, s2: Shape) { +>f0 : (s1: Shape, s2: Shape) => void +>s1 : Shape +>Shape : Shape +>s2 : Shape +>Shape : Shape + + assign(s1, { name: "circle" }); +>assign(s1, { name: "circle" }) : void +>assign : (obj: T, props: Partial) => void +>s1 : Shape +>{ name: "circle" } : { name: string; } +>name : string +>"circle" : "circle" + + assign(s2, { width: 10, height: 20 }); +>assign(s2, { width: 10, height: 20 }) : void +>assign : (obj: T, props: Partial) => void +>s2 : Shape +>{ width: 10, height: 20 } : { width: number; height: number; } +>width : number +>10 : 10 +>height : number +>20 : 20 +} + +function f1(shape: Shape) { +>f1 : (shape: Shape) => void +>shape : Shape +>Shape : Shape + + var frozen: ReadonlyShape; +>frozen : ReadonlyShape +>ReadonlyShape : ReadonlyShape + + var frozen: Readonly; +>frozen : ReadonlyShape +>Readonly : Readonly +>Shape : Shape + + var frozen = freeze(shape); +>frozen : ReadonlyShape +>freeze(shape) : Readonly +>freeze : (obj: T) => Readonly +>shape : Shape +} + +function f2(shape: Shape) { +>f2 : (shape: Shape) => void +>shape : Shape +>Shape : Shape + + var partial: PartialShape; +>partial : PartialShape +>PartialShape : PartialShape + + var partial: Partial; +>partial : PartialShape +>Partial : Partial +>Shape : Shape + + var partial: Partial = {}; +>partial : PartialShape +>Partial : Partial +>Shape : Shape +>{} : {} +} + +function f3(shape: Shape) { +>f3 : (shape: Shape) => void +>shape : Shape +>Shape : Shape + + const x = pick(shape, "name", "location"); // { name: string, location: Point } +>x : Pick +>pick(shape, "name", "location") : Pick +>pick : (obj: T, ...keys: K[]) => Pick +>shape : Shape +>"name" : "name" +>"location" : "location" +} + +function f4() { +>f4 : () => void + + const rec = { foo: "hello", bar: "world", baz: "bye" }; +>rec : { foo: string; bar: string; baz: string; } +>{ foo: "hello", bar: "world", baz: "bye" } : { foo: string; bar: string; baz: string; } +>foo : string +>"hello" : "hello" +>bar : string +>"world" : "world" +>baz : string +>"bye" : "bye" + + const lengths = mapObject(rec, s => s.length); // { foo: number, bar: number, baz: number } +>lengths : Record<"foo" | "bar" | "baz", number> +>mapObject(rec, s => s.length) : Record<"foo" | "bar" | "baz", number> +>mapObject : (obj: Record, f: (x: T) => U) => Record +>rec : { foo: string; bar: string; baz: string; } +>s => s.length : (s: string) => number +>s : string +>s.length : number +>s : string +>length : number +} + +function f5(shape: Shape) { +>f5 : (shape: Shape) => void +>shape : Shape +>Shape : Shape + + const p = proxify(shape); +>p : Proxify +>proxify(shape) : Proxify +>proxify : (obj: T) => Proxify +>shape : Shape + + let name = p.name.get(); +>name : string +>p.name.get() : string +>p.name.get : () => string +>p.name : Proxy +>p : Proxify +>name : Proxy +>get : () => string + + p.width.set(42); +>p.width.set(42) : void +>p.width.set : (value: number) => void +>p.width : Proxy +>p : Proxify +>width : Proxy +>set : (value: number) => void +>42 : 42 +} + +function f6(shape: DeepReadonly) { +>f6 : (shape: DeepReadonly) => void +>shape : DeepReadonly +>DeepReadonly : DeepReadonly +>Shape : Shape + + let name = shape.name; // string +>name : string +>shape.name : string +>shape : DeepReadonly +>name : string + + let location = shape.location; // DeepReadonly +>location : DeepReadonly +>shape.location : DeepReadonly +>shape : DeepReadonly +>location : DeepReadonly + + let x = location.x; // number +>x : number +>location.x : number +>location : DeepReadonly +>x : number +} diff --git a/tests/baselines/reference/mappedTypes3.js b/tests/baselines/reference/mappedTypes3.js new file mode 100644 index 00000000000..712822e8728 --- /dev/null +++ b/tests/baselines/reference/mappedTypes3.js @@ -0,0 +1,84 @@ +//// [mappedTypes3.ts] + +class Box

{ + value: P; +} + +type Boxified = { + [K in keyof T]: Box; +} + +declare function boxify(obj: T): Boxified; +declare function unboxify(obj: Boxified): T; + +interface Bacon { + isPerfect: boolean; + weight: number; +} + +interface BoxifiedBacon { + isPerfect: Box; + weight: Box; +} + +function f1(b: Bacon) { + let bb = boxify(b); + let isPerfect = bb.isPerfect.value; + let weight = bb.weight.value; +} + +function f2(bb: Boxified) { + let b = unboxify(bb); // Infer Bacon for T + let bool = b.isPerfect; + let weight = b.weight; +} + +function f3(bb: BoxifiedBacon) { + let b = unboxify(bb); // Explicit type parameter required + let bool = b.isPerfect; + let weight = bb.weight; +} + +//// [mappedTypes3.js] +var Box = (function () { + function Box() { + } + return Box; +}()); +function f1(b) { + var bb = boxify(b); + var isPerfect = bb.isPerfect.value; + var weight = bb.weight.value; +} +function f2(bb) { + var b = unboxify(bb); // Infer Bacon for T + var bool = b.isPerfect; + var weight = b.weight; +} +function f3(bb) { + var b = unboxify(bb); // Explicit type parameter required + var bool = b.isPerfect; + var weight = bb.weight; +} + + +//// [mappedTypes3.d.ts] +declare class Box

{ + value: P; +} +declare type Boxified = { + [K in keyof T]: Box; +}; +declare function boxify(obj: T): Boxified; +declare function unboxify(obj: Boxified): T; +interface Bacon { + isPerfect: boolean; + weight: number; +} +interface BoxifiedBacon { + isPerfect: Box; + weight: Box; +} +declare function f1(b: Bacon): void; +declare function f2(bb: Boxified): void; +declare function f3(bb: BoxifiedBacon): void; diff --git a/tests/baselines/reference/mappedTypes3.symbols b/tests/baselines/reference/mappedTypes3.symbols new file mode 100644 index 00000000000..3d909c8e532 --- /dev/null +++ b/tests/baselines/reference/mappedTypes3.symbols @@ -0,0 +1,135 @@ +=== tests/cases/conformance/types/mapped/mappedTypes3.ts === + +class Box

{ +>Box : Symbol(Box, Decl(mappedTypes3.ts, 0, 0)) +>P : Symbol(P, Decl(mappedTypes3.ts, 1, 10)) + + value: P; +>value : Symbol(Box.value, Decl(mappedTypes3.ts, 1, 14)) +>P : Symbol(P, Decl(mappedTypes3.ts, 1, 10)) +} + +type Boxified = { +>Boxified : Symbol(Boxified, Decl(mappedTypes3.ts, 3, 1)) +>T : Symbol(T, Decl(mappedTypes3.ts, 5, 14)) + + [K in keyof T]: Box; +>K : Symbol(K, Decl(mappedTypes3.ts, 6, 5)) +>T : Symbol(T, Decl(mappedTypes3.ts, 5, 14)) +>Box : Symbol(Box, Decl(mappedTypes3.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypes3.ts, 5, 14)) +>K : Symbol(K, Decl(mappedTypes3.ts, 6, 5)) +} + +declare function boxify(obj: T): Boxified; +>boxify : Symbol(boxify, Decl(mappedTypes3.ts, 7, 1)) +>T : Symbol(T, Decl(mappedTypes3.ts, 9, 24)) +>obj : Symbol(obj, Decl(mappedTypes3.ts, 9, 27)) +>T : Symbol(T, Decl(mappedTypes3.ts, 9, 24)) +>Boxified : Symbol(Boxified, Decl(mappedTypes3.ts, 3, 1)) +>T : Symbol(T, Decl(mappedTypes3.ts, 9, 24)) + +declare function unboxify(obj: Boxified): T; +>unboxify : Symbol(unboxify, Decl(mappedTypes3.ts, 9, 48)) +>T : Symbol(T, Decl(mappedTypes3.ts, 10, 26)) +>obj : Symbol(obj, Decl(mappedTypes3.ts, 10, 29)) +>Boxified : Symbol(Boxified, Decl(mappedTypes3.ts, 3, 1)) +>T : Symbol(T, Decl(mappedTypes3.ts, 10, 26)) +>T : Symbol(T, Decl(mappedTypes3.ts, 10, 26)) + +interface Bacon { +>Bacon : Symbol(Bacon, Decl(mappedTypes3.ts, 10, 50)) + + isPerfect: boolean; +>isPerfect : Symbol(Bacon.isPerfect, Decl(mappedTypes3.ts, 12, 17)) + + weight: number; +>weight : Symbol(Bacon.weight, Decl(mappedTypes3.ts, 13, 23)) +} + +interface BoxifiedBacon { +>BoxifiedBacon : Symbol(BoxifiedBacon, Decl(mappedTypes3.ts, 15, 1)) + + isPerfect: Box; +>isPerfect : Symbol(BoxifiedBacon.isPerfect, Decl(mappedTypes3.ts, 17, 25)) +>Box : Symbol(Box, Decl(mappedTypes3.ts, 0, 0)) + + weight: Box; +>weight : Symbol(BoxifiedBacon.weight, Decl(mappedTypes3.ts, 18, 28)) +>Box : Symbol(Box, Decl(mappedTypes3.ts, 0, 0)) +} + +function f1(b: Bacon) { +>f1 : Symbol(f1, Decl(mappedTypes3.ts, 20, 1)) +>b : Symbol(b, Decl(mappedTypes3.ts, 22, 12)) +>Bacon : Symbol(Bacon, Decl(mappedTypes3.ts, 10, 50)) + + let bb = boxify(b); +>bb : Symbol(bb, Decl(mappedTypes3.ts, 23, 7)) +>boxify : Symbol(boxify, Decl(mappedTypes3.ts, 7, 1)) +>b : Symbol(b, Decl(mappedTypes3.ts, 22, 12)) + + let isPerfect = bb.isPerfect.value; +>isPerfect : Symbol(isPerfect, Decl(mappedTypes3.ts, 24, 7)) +>bb.isPerfect.value : Symbol(Box.value, Decl(mappedTypes3.ts, 1, 14)) +>bb.isPerfect : Symbol(isPerfect) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 23, 7)) +>isPerfect : Symbol(isPerfect) +>value : Symbol(Box.value, Decl(mappedTypes3.ts, 1, 14)) + + let weight = bb.weight.value; +>weight : Symbol(weight, Decl(mappedTypes3.ts, 25, 7)) +>bb.weight.value : Symbol(Box.value, Decl(mappedTypes3.ts, 1, 14)) +>bb.weight : Symbol(weight) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 23, 7)) +>weight : Symbol(weight) +>value : Symbol(Box.value, Decl(mappedTypes3.ts, 1, 14)) +} + +function f2(bb: Boxified) { +>f2 : Symbol(f2, Decl(mappedTypes3.ts, 26, 1)) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 28, 12)) +>Boxified : Symbol(Boxified, Decl(mappedTypes3.ts, 3, 1)) +>Bacon : Symbol(Bacon, Decl(mappedTypes3.ts, 10, 50)) + + let b = unboxify(bb); // Infer Bacon for T +>b : Symbol(b, Decl(mappedTypes3.ts, 29, 7)) +>unboxify : Symbol(unboxify, Decl(mappedTypes3.ts, 9, 48)) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 28, 12)) + + let bool = b.isPerfect; +>bool : Symbol(bool, Decl(mappedTypes3.ts, 30, 7)) +>b.isPerfect : Symbol(Bacon.isPerfect, Decl(mappedTypes3.ts, 12, 17)) +>b : Symbol(b, Decl(mappedTypes3.ts, 29, 7)) +>isPerfect : Symbol(Bacon.isPerfect, Decl(mappedTypes3.ts, 12, 17)) + + let weight = b.weight; +>weight : Symbol(weight, Decl(mappedTypes3.ts, 31, 7)) +>b.weight : Symbol(Bacon.weight, Decl(mappedTypes3.ts, 13, 23)) +>b : Symbol(b, Decl(mappedTypes3.ts, 29, 7)) +>weight : Symbol(Bacon.weight, Decl(mappedTypes3.ts, 13, 23)) +} + +function f3(bb: BoxifiedBacon) { +>f3 : Symbol(f3, Decl(mappedTypes3.ts, 32, 1)) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 34, 12)) +>BoxifiedBacon : Symbol(BoxifiedBacon, Decl(mappedTypes3.ts, 15, 1)) + + let b = unboxify(bb); // Explicit type parameter required +>b : Symbol(b, Decl(mappedTypes3.ts, 35, 7)) +>unboxify : Symbol(unboxify, Decl(mappedTypes3.ts, 9, 48)) +>Bacon : Symbol(Bacon, Decl(mappedTypes3.ts, 10, 50)) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 34, 12)) + + let bool = b.isPerfect; +>bool : Symbol(bool, Decl(mappedTypes3.ts, 36, 7)) +>b.isPerfect : Symbol(Bacon.isPerfect, Decl(mappedTypes3.ts, 12, 17)) +>b : Symbol(b, Decl(mappedTypes3.ts, 35, 7)) +>isPerfect : Symbol(Bacon.isPerfect, Decl(mappedTypes3.ts, 12, 17)) + + let weight = bb.weight; +>weight : Symbol(weight, Decl(mappedTypes3.ts, 37, 7)) +>bb.weight : Symbol(BoxifiedBacon.weight, Decl(mappedTypes3.ts, 18, 28)) +>bb : Symbol(bb, Decl(mappedTypes3.ts, 34, 12)) +>weight : Symbol(BoxifiedBacon.weight, Decl(mappedTypes3.ts, 18, 28)) +} diff --git a/tests/baselines/reference/mappedTypes3.types b/tests/baselines/reference/mappedTypes3.types new file mode 100644 index 00000000000..36471938d75 --- /dev/null +++ b/tests/baselines/reference/mappedTypes3.types @@ -0,0 +1,138 @@ +=== tests/cases/conformance/types/mapped/mappedTypes3.ts === + +class Box

{ +>Box : Box

+>P : P + + value: P; +>value : P +>P : P +} + +type Boxified = { +>Boxified : Boxified +>T : T + + [K in keyof T]: Box; +>K : K +>T : T +>Box : Box

+>T : T +>K : K +} + +declare function boxify(obj: T): Boxified; +>boxify : (obj: T) => Boxified +>T : T +>obj : T +>T : T +>Boxified : Boxified +>T : T + +declare function unboxify(obj: Boxified): T; +>unboxify : (obj: Boxified) => T +>T : T +>obj : Boxified +>Boxified : Boxified +>T : T +>T : T + +interface Bacon { +>Bacon : Bacon + + isPerfect: boolean; +>isPerfect : boolean + + weight: number; +>weight : number +} + +interface BoxifiedBacon { +>BoxifiedBacon : BoxifiedBacon + + isPerfect: Box; +>isPerfect : Box +>Box : Box

+ + weight: Box; +>weight : Box +>Box : Box

+} + +function f1(b: Bacon) { +>f1 : (b: Bacon) => void +>b : Bacon +>Bacon : Bacon + + let bb = boxify(b); +>bb : Boxified +>boxify(b) : Boxified +>boxify : (obj: T) => Boxified +>b : Bacon + + let isPerfect = bb.isPerfect.value; +>isPerfect : boolean +>bb.isPerfect.value : boolean +>bb.isPerfect : Box +>bb : Boxified +>isPerfect : Box +>value : boolean + + let weight = bb.weight.value; +>weight : number +>bb.weight.value : number +>bb.weight : Box +>bb : Boxified +>weight : Box +>value : number +} + +function f2(bb: Boxified) { +>f2 : (bb: Boxified) => void +>bb : Boxified +>Boxified : Boxified +>Bacon : Bacon + + let b = unboxify(bb); // Infer Bacon for T +>b : Bacon +>unboxify(bb) : Bacon +>unboxify : (obj: Boxified) => T +>bb : Boxified + + let bool = b.isPerfect; +>bool : boolean +>b.isPerfect : boolean +>b : Bacon +>isPerfect : boolean + + let weight = b.weight; +>weight : number +>b.weight : number +>b : Bacon +>weight : number +} + +function f3(bb: BoxifiedBacon) { +>f3 : (bb: BoxifiedBacon) => void +>bb : BoxifiedBacon +>BoxifiedBacon : BoxifiedBacon + + let b = unboxify(bb); // Explicit type parameter required +>b : Bacon +>unboxify(bb) : Bacon +>unboxify : (obj: Boxified) => T +>Bacon : Bacon +>bb : BoxifiedBacon + + let bool = b.isPerfect; +>bool : boolean +>b.isPerfect : boolean +>b : Bacon +>isPerfect : boolean + + let weight = bb.weight; +>weight : Box +>bb.weight : Box +>bb : BoxifiedBacon +>weight : Box +} diff --git a/tests/baselines/reference/mappedTypes4.js b/tests/baselines/reference/mappedTypes4.js new file mode 100644 index 00000000000..bb003b1a1ec --- /dev/null +++ b/tests/baselines/reference/mappedTypes4.js @@ -0,0 +1,129 @@ +//// [mappedTypes4.ts] + +type Box = { +}; + +type Boxified = { + [P in keyof T]: Box; +}; + +function boxify(obj: T): Boxified { + if (typeof obj === "object") { + let result = {} as Boxified; + for (let k in obj) { + result[k] = { value: obj[k] }; + } + return result; + } + return obj; +} + +type A = { a: string }; +type B = { b: string }; +type C = { c: string }; + +function f1(x: A | B | C | undefined) { + return boxify(x); +} + +type T00 = Partial; +type T01 = Readonly; +type T02 = Boxified +type T03 = Readonly; +type T04 = Boxified; +type T05 = Partial<"hello" | "world" | 42>; + +type BoxifiedWithSentinel = { + [P in keyof T]: Box | U; +} + +type T10 = BoxifiedWithSentinel; +type T11 = BoxifiedWithSentinel; +type T12 = BoxifiedWithSentinel; + +type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; + +type Foo = { + x: number; + y: { a: string, b: number }; + z: boolean; +}; + +type DeepReadonlyFoo = { + readonly x: number; + readonly y: { readonly a: string, readonly b: number }; + readonly z: boolean; +}; + +var x1: DeepReadonly; +var x1: DeepReadonlyFoo; + +//// [mappedTypes4.js] +function boxify(obj) { + if (typeof obj === "object") { + var result = {}; + for (var k in obj) { + result[k] = { value: obj[k] }; + } + return result; + } + return obj; +} +function f1(x) { + return boxify(x); +} +var x1; +var x1; + + +//// [mappedTypes4.d.ts] +declare type Box = {}; +declare type Boxified = { + [P in keyof T]: Box; +}; +declare function boxify(obj: T): Boxified; +declare type A = { + a: string; +}; +declare type B = { + b: string; +}; +declare type C = { + c: string; +}; +declare function f1(x: A | B | C | undefined): Boxified | Boxified | Boxified | undefined; +declare type T00 = Partial; +declare type T01 = Readonly; +declare type T02 = Boxified; +declare type T03 = Readonly; +declare type T04 = Boxified; +declare type T05 = Partial<"hello" | "world" | 42>; +declare type BoxifiedWithSentinel = { + [P in keyof T]: Box | U; +}; +declare type T10 = BoxifiedWithSentinel; +declare type T11 = BoxifiedWithSentinel; +declare type T12 = BoxifiedWithSentinel; +declare type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; +declare type Foo = { + x: number; + y: { + a: string; + b: number; + }; + z: boolean; +}; +declare type DeepReadonlyFoo = { + readonly x: number; + readonly y: { + readonly a: string; + readonly b: number; + }; + readonly z: boolean; +}; +declare var x1: DeepReadonly; +declare var x1: DeepReadonlyFoo; diff --git a/tests/baselines/reference/mappedTypes4.symbols b/tests/baselines/reference/mappedTypes4.symbols new file mode 100644 index 00000000000..b57adfe9954 --- /dev/null +++ b/tests/baselines/reference/mappedTypes4.symbols @@ -0,0 +1,198 @@ +=== tests/cases/conformance/types/mapped/mappedTypes4.ts === + +type Box = { +>Box : Symbol(Box, Decl(mappedTypes4.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypes4.ts, 1, 9)) + +}; + +type Boxified = { +>Boxified : Symbol(Boxified, Decl(mappedTypes4.ts, 2, 2)) +>T : Symbol(T, Decl(mappedTypes4.ts, 4, 14)) + + [P in keyof T]: Box; +>P : Symbol(P, Decl(mappedTypes4.ts, 5, 5)) +>T : Symbol(T, Decl(mappedTypes4.ts, 4, 14)) +>Box : Symbol(Box, Decl(mappedTypes4.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypes4.ts, 4, 14)) +>P : Symbol(P, Decl(mappedTypes4.ts, 5, 5)) + +}; + +function boxify(obj: T): Boxified { +>boxify : Symbol(boxify, Decl(mappedTypes4.ts, 6, 2)) +>T : Symbol(T, Decl(mappedTypes4.ts, 8, 16)) +>obj : Symbol(obj, Decl(mappedTypes4.ts, 8, 19)) +>T : Symbol(T, Decl(mappedTypes4.ts, 8, 16)) +>Boxified : Symbol(Boxified, Decl(mappedTypes4.ts, 2, 2)) +>T : Symbol(T, Decl(mappedTypes4.ts, 8, 16)) + + if (typeof obj === "object") { +>obj : Symbol(obj, Decl(mappedTypes4.ts, 8, 19)) + + let result = {} as Boxified; +>result : Symbol(result, Decl(mappedTypes4.ts, 10, 11)) +>Boxified : Symbol(Boxified, Decl(mappedTypes4.ts, 2, 2)) +>T : Symbol(T, Decl(mappedTypes4.ts, 8, 16)) + + for (let k in obj) { +>k : Symbol(k, Decl(mappedTypes4.ts, 11, 16)) +>obj : Symbol(obj, Decl(mappedTypes4.ts, 8, 19)) + + result[k] = { value: obj[k] }; +>result : Symbol(result, Decl(mappedTypes4.ts, 10, 11)) +>k : Symbol(k, Decl(mappedTypes4.ts, 11, 16)) +>value : Symbol(value, Decl(mappedTypes4.ts, 12, 25)) +>obj : Symbol(obj, Decl(mappedTypes4.ts, 8, 19)) +>k : Symbol(k, Decl(mappedTypes4.ts, 11, 16)) + } + return result; +>result : Symbol(result, Decl(mappedTypes4.ts, 10, 11)) + } + return obj; +>obj : Symbol(obj, Decl(mappedTypes4.ts, 8, 19)) +} + +type A = { a: string }; +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>a : Symbol(a, Decl(mappedTypes4.ts, 19, 10)) + +type B = { b: string }; +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>b : Symbol(b, Decl(mappedTypes4.ts, 20, 10)) + +type C = { c: string }; +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) +>c : Symbol(c, Decl(mappedTypes4.ts, 21, 10)) + +function f1(x: A | B | C | undefined) { +>f1 : Symbol(f1, Decl(mappedTypes4.ts, 21, 23)) +>x : Symbol(x, Decl(mappedTypes4.ts, 23, 12)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + + return boxify(x); +>boxify : Symbol(boxify, Decl(mappedTypes4.ts, 6, 2)) +>x : Symbol(x, Decl(mappedTypes4.ts, 23, 12)) +} + +type T00 = Partial; +>T00 : Symbol(T00, Decl(mappedTypes4.ts, 25, 1)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + +type T01 = Readonly; +>T01 : Symbol(T01, Decl(mappedTypes4.ts, 27, 30)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + +type T02 = Boxified +>T02 : Symbol(T02, Decl(mappedTypes4.ts, 28, 50)) +>Boxified : Symbol(Boxified, Decl(mappedTypes4.ts, 2, 2)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + +type T03 = Readonly; +>T03 : Symbol(T03, Decl(mappedTypes4.ts, 29, 41)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) + +type T04 = Boxified; +>T04 : Symbol(T04, Decl(mappedTypes4.ts, 30, 73)) +>Boxified : Symbol(Boxified, Decl(mappedTypes4.ts, 2, 2)) + +type T05 = Partial<"hello" | "world" | 42>; +>T05 : Symbol(T05, Decl(mappedTypes4.ts, 31, 73)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) + +type BoxifiedWithSentinel = { +>BoxifiedWithSentinel : Symbol(BoxifiedWithSentinel, Decl(mappedTypes4.ts, 32, 43)) +>T : Symbol(T, Decl(mappedTypes4.ts, 34, 26)) +>U : Symbol(U, Decl(mappedTypes4.ts, 34, 28)) + + [P in keyof T]: Box | U; +>P : Symbol(P, Decl(mappedTypes4.ts, 35, 5)) +>T : Symbol(T, Decl(mappedTypes4.ts, 34, 26)) +>Box : Symbol(Box, Decl(mappedTypes4.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypes4.ts, 34, 26)) +>P : Symbol(P, Decl(mappedTypes4.ts, 35, 5)) +>U : Symbol(U, Decl(mappedTypes4.ts, 34, 28)) +} + +type T10 = BoxifiedWithSentinel; +>T10 : Symbol(T10, Decl(mappedTypes4.ts, 36, 1)) +>BoxifiedWithSentinel : Symbol(BoxifiedWithSentinel, Decl(mappedTypes4.ts, 32, 43)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + +type T11 = BoxifiedWithSentinel; +>T11 : Symbol(T11, Decl(mappedTypes4.ts, 38, 49)) +>BoxifiedWithSentinel : Symbol(BoxifiedWithSentinel, Decl(mappedTypes4.ts, 32, 43)) +>A : Symbol(A, Decl(mappedTypes4.ts, 17, 1)) +>B : Symbol(B, Decl(mappedTypes4.ts, 19, 23)) +>C : Symbol(C, Decl(mappedTypes4.ts, 20, 23)) + +type T12 = BoxifiedWithSentinel; +>T12 : Symbol(T12, Decl(mappedTypes4.ts, 39, 54)) +>BoxifiedWithSentinel : Symbol(BoxifiedWithSentinel, Decl(mappedTypes4.ts, 32, 43)) + +type DeepReadonly = { +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes4.ts, 40, 51)) +>T : Symbol(T, Decl(mappedTypes4.ts, 42, 18)) + + readonly [P in keyof T]: DeepReadonly; +>P : Symbol(P, Decl(mappedTypes4.ts, 43, 14)) +>T : Symbol(T, Decl(mappedTypes4.ts, 42, 18)) +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes4.ts, 40, 51)) +>T : Symbol(T, Decl(mappedTypes4.ts, 42, 18)) +>P : Symbol(P, Decl(mappedTypes4.ts, 43, 14)) + +}; + +type Foo = { +>Foo : Symbol(Foo, Decl(mappedTypes4.ts, 44, 2)) + + x: number; +>x : Symbol(x, Decl(mappedTypes4.ts, 46, 12)) + + y: { a: string, b: number }; +>y : Symbol(y, Decl(mappedTypes4.ts, 47, 14)) +>a : Symbol(a, Decl(mappedTypes4.ts, 48, 8)) +>b : Symbol(b, Decl(mappedTypes4.ts, 48, 19)) + + z: boolean; +>z : Symbol(z, Decl(mappedTypes4.ts, 48, 32)) + +}; + +type DeepReadonlyFoo = { +>DeepReadonlyFoo : Symbol(DeepReadonlyFoo, Decl(mappedTypes4.ts, 50, 2)) + + readonly x: number; +>x : Symbol(x, Decl(mappedTypes4.ts, 52, 24)) + + readonly y: { readonly a: string, readonly b: number }; +>y : Symbol(y, Decl(mappedTypes4.ts, 53, 23)) +>a : Symbol(a, Decl(mappedTypes4.ts, 54, 17)) +>b : Symbol(b, Decl(mappedTypes4.ts, 54, 37)) + + readonly z: boolean; +>z : Symbol(z, Decl(mappedTypes4.ts, 54, 59)) + +}; + +var x1: DeepReadonly; +>x1 : Symbol(x1, Decl(mappedTypes4.ts, 58, 3), Decl(mappedTypes4.ts, 59, 3)) +>DeepReadonly : Symbol(DeepReadonly, Decl(mappedTypes4.ts, 40, 51)) +>Foo : Symbol(Foo, Decl(mappedTypes4.ts, 44, 2)) + +var x1: DeepReadonlyFoo; +>x1 : Symbol(x1, Decl(mappedTypes4.ts, 58, 3), Decl(mappedTypes4.ts, 59, 3)) +>DeepReadonlyFoo : Symbol(DeepReadonlyFoo, Decl(mappedTypes4.ts, 50, 2)) + diff --git a/tests/baselines/reference/mappedTypes4.types b/tests/baselines/reference/mappedTypes4.types new file mode 100644 index 00000000000..cc492d82120 --- /dev/null +++ b/tests/baselines/reference/mappedTypes4.types @@ -0,0 +1,213 @@ +=== tests/cases/conformance/types/mapped/mappedTypes4.ts === + +type Box = { +>Box : Box +>T : T + +}; + +type Boxified = { +>Boxified : Boxified +>T : T + + [P in keyof T]: Box; +>P : P +>T : T +>Box : Box +>T : T +>P : P + +}; + +function boxify(obj: T): Boxified { +>boxify : (obj: T) => Boxified +>T : T +>obj : T +>T : T +>Boxified : Boxified +>T : T + + if (typeof obj === "object") { +>typeof obj === "object" : boolean +>typeof obj : string +>obj : T +>"object" : "object" + + let result = {} as Boxified; +>result : Boxified +>{} as Boxified : Boxified +>{} : {} +>Boxified : Boxified +>T : T + + for (let k in obj) { +>k : keyof T +>obj : T + + result[k] = { value: obj[k] }; +>result[k] = { value: obj[k] } : { value: T[keyof T]; } +>result[k] : Box +>result : Boxified +>k : keyof T +>{ value: obj[k] } : { value: T[keyof T]; } +>value : T[keyof T] +>obj[k] : T[keyof T] +>obj : T +>k : keyof T + } + return result; +>result : Boxified + } + return obj; +>obj : any +>obj : never +} + +type A = { a: string }; +>A : A +>a : string + +type B = { b: string }; +>B : B +>b : string + +type C = { c: string }; +>C : C +>c : string + +function f1(x: A | B | C | undefined) { +>f1 : (x: A | B | C | undefined) => Boxified | Boxified | Boxified | undefined +>x : A | B | C | undefined +>A : A +>B : B +>C : C + + return boxify(x); +>boxify(x) : Boxified | Boxified | Boxified | undefined +>boxify : (obj: T) => Boxified +>x : A | B | C | undefined +} + +type T00 = Partial; +>T00 : Partial | Partial | Partial +>Partial : Partial +>A : A +>B : B +>C : C + +type T01 = Readonly; +>T01 : Readonly | Readonly | Readonly | null | undefined +>Readonly : Readonly +>A : A +>B : B +>C : C +>null : null + +type T02 = Boxified +>T02 : string | Boxified | Boxified | Boxified +>Boxified : Boxified +>A : A +>B : B +>C : C + +type T03 = Readonly; +>T03 : string | number | boolean | void | null | undefined +>Readonly : Readonly +>null : null + +type T04 = Boxified; +>T04 : string | number | boolean | void | null | undefined +>Boxified : Boxified +>null : null + +type T05 = Partial<"hello" | "world" | 42>; +>T05 : "hello" | "world" | 42 +>Partial : Partial + +type BoxifiedWithSentinel = { +>BoxifiedWithSentinel : BoxifiedWithSentinel +>T : T +>U : U + + [P in keyof T]: Box | U; +>P : P +>T : T +>Box : Box +>T : T +>P : P +>U : U +} + +type T10 = BoxifiedWithSentinel; +>T10 : BoxifiedWithSentinel | BoxifiedWithSentinel | BoxifiedWithSentinel +>BoxifiedWithSentinel : BoxifiedWithSentinel +>A : A +>B : B +>C : C +>null : null + +type T11 = BoxifiedWithSentinel; +>T11 : BoxifiedWithSentinel | BoxifiedWithSentinel | BoxifiedWithSentinel +>BoxifiedWithSentinel : BoxifiedWithSentinel +>A : A +>B : B +>C : C + +type T12 = BoxifiedWithSentinel; +>T12 : string +>BoxifiedWithSentinel : BoxifiedWithSentinel + +type DeepReadonly = { +>DeepReadonly : DeepReadonly +>T : T + + readonly [P in keyof T]: DeepReadonly; +>P : P +>T : T +>DeepReadonly : DeepReadonly +>T : T +>P : P + +}; + +type Foo = { +>Foo : Foo + + x: number; +>x : number + + y: { a: string, b: number }; +>y : { a: string; b: number; } +>a : string +>b : number + + z: boolean; +>z : boolean + +}; + +type DeepReadonlyFoo = { +>DeepReadonlyFoo : DeepReadonlyFoo + + readonly x: number; +>x : number + + readonly y: { readonly a: string, readonly b: number }; +>y : { readonly a: string; readonly b: number; } +>a : string +>b : number + + readonly z: boolean; +>z : boolean + +}; + +var x1: DeepReadonly; +>x1 : DeepReadonly +>DeepReadonly : DeepReadonly +>Foo : Foo + +var x1: DeepReadonlyFoo; +>x1 : DeepReadonly +>DeepReadonlyFoo : DeepReadonlyFoo + diff --git a/tests/baselines/reference/mappedTypesAndObjects.js b/tests/baselines/reference/mappedTypesAndObjects.js new file mode 100644 index 00000000000..53b39209693 --- /dev/null +++ b/tests/baselines/reference/mappedTypesAndObjects.js @@ -0,0 +1,72 @@ +//// [mappedTypesAndObjects.ts] + +function f1(x: Partial, y: Readonly) { + let obj: {}; + obj = x; + obj = y; +} + +function f2(x: Partial, y: Readonly) { + let obj: { [x: string]: any }; + obj = x; + obj = y; +} + +// Repro from #12900 + +interface Base { + foo: { [key: string]: any }; + bar: any; + baz: any; +} + +interface E1 extends Base { + foo: T; +} + +interface Something { name: string, value: string }; +interface E2 extends Base { + foo: Partial; // or other mapped type +} + +interface E3 extends Base { + foo: Partial; // or other mapped type +} + +//// [mappedTypesAndObjects.js] +function f1(x, y) { + var obj; + obj = x; + obj = y; +} +function f2(x, y) { + var obj; + obj = x; + obj = y; +} +; + + +//// [mappedTypesAndObjects.d.ts] +declare function f1(x: Partial, y: Readonly): void; +declare function f2(x: Partial, y: Readonly): void; +interface Base { + foo: { + [key: string]: any; + }; + bar: any; + baz: any; +} +interface E1 extends Base { + foo: T; +} +interface Something { + name: string; + value: string; +} +interface E2 extends Base { + foo: Partial; +} +interface E3 extends Base { + foo: Partial; +} diff --git a/tests/baselines/reference/mappedTypesAndObjects.symbols b/tests/baselines/reference/mappedTypesAndObjects.symbols new file mode 100644 index 00000000000..1690f1b6b04 --- /dev/null +++ b/tests/baselines/reference/mappedTypesAndObjects.symbols @@ -0,0 +1,98 @@ +=== tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts === + +function f1(x: Partial, y: Readonly) { +>f1 : Symbol(f1, Decl(mappedTypesAndObjects.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 1, 12)) +>x : Symbol(x, Decl(mappedTypesAndObjects.ts, 1, 15)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 1, 12)) +>y : Symbol(y, Decl(mappedTypesAndObjects.ts, 1, 29)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 1, 12)) + + let obj: {}; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 2, 7)) + + obj = x; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 2, 7)) +>x : Symbol(x, Decl(mappedTypesAndObjects.ts, 1, 15)) + + obj = y; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 2, 7)) +>y : Symbol(y, Decl(mappedTypesAndObjects.ts, 1, 29)) +} + +function f2(x: Partial, y: Readonly) { +>f2 : Symbol(f2, Decl(mappedTypesAndObjects.ts, 5, 1)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 7, 12)) +>x : Symbol(x, Decl(mappedTypesAndObjects.ts, 7, 15)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 7, 12)) +>y : Symbol(y, Decl(mappedTypesAndObjects.ts, 7, 29)) +>Readonly : Symbol(Readonly, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 7, 12)) + + let obj: { [x: string]: any }; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 8, 7)) +>x : Symbol(x, Decl(mappedTypesAndObjects.ts, 8, 16)) + + obj = x; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 8, 7)) +>x : Symbol(x, Decl(mappedTypesAndObjects.ts, 7, 15)) + + obj = y; +>obj : Symbol(obj, Decl(mappedTypesAndObjects.ts, 8, 7)) +>y : Symbol(y, Decl(mappedTypesAndObjects.ts, 7, 29)) +} + +// Repro from #12900 + +interface Base { +>Base : Symbol(Base, Decl(mappedTypesAndObjects.ts, 11, 1)) + + foo: { [key: string]: any }; +>foo : Symbol(Base.foo, Decl(mappedTypesAndObjects.ts, 15, 16)) +>key : Symbol(key, Decl(mappedTypesAndObjects.ts, 16, 11)) + + bar: any; +>bar : Symbol(Base.bar, Decl(mappedTypesAndObjects.ts, 16, 31)) + + baz: any; +>baz : Symbol(Base.baz, Decl(mappedTypesAndObjects.ts, 17, 12)) +} + +interface E1 extends Base { +>E1 : Symbol(E1, Decl(mappedTypesAndObjects.ts, 19, 1)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 21, 13)) +>Base : Symbol(Base, Decl(mappedTypesAndObjects.ts, 11, 1)) + + foo: T; +>foo : Symbol(E1.foo, Decl(mappedTypesAndObjects.ts, 21, 30)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 21, 13)) +} + +interface Something { name: string, value: string }; +>Something : Symbol(Something, Decl(mappedTypesAndObjects.ts, 23, 1)) +>name : Symbol(Something.name, Decl(mappedTypesAndObjects.ts, 25, 21)) +>value : Symbol(Something.value, Decl(mappedTypesAndObjects.ts, 25, 35)) + +interface E2 extends Base { +>E2 : Symbol(E2, Decl(mappedTypesAndObjects.ts, 25, 52)) +>Base : Symbol(Base, Decl(mappedTypesAndObjects.ts, 11, 1)) + + foo: Partial; // or other mapped type +>foo : Symbol(E2.foo, Decl(mappedTypesAndObjects.ts, 26, 27)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>Something : Symbol(Something, Decl(mappedTypesAndObjects.ts, 23, 1)) +} + +interface E3 extends Base { +>E3 : Symbol(E3, Decl(mappedTypesAndObjects.ts, 28, 1)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 30, 13)) +>Base : Symbol(Base, Decl(mappedTypesAndObjects.ts, 11, 1)) + + foo: Partial; // or other mapped type +>foo : Symbol(E3.foo, Decl(mappedTypesAndObjects.ts, 30, 30)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypesAndObjects.ts, 30, 13)) +} diff --git a/tests/baselines/reference/mappedTypesAndObjects.types b/tests/baselines/reference/mappedTypesAndObjects.types new file mode 100644 index 00000000000..e6f8e53f558 --- /dev/null +++ b/tests/baselines/reference/mappedTypesAndObjects.types @@ -0,0 +1,102 @@ +=== tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts === + +function f1(x: Partial, y: Readonly) { +>f1 : (x: Partial, y: Readonly) => void +>T : T +>x : Partial +>Partial : Partial +>T : T +>y : Readonly +>Readonly : Readonly +>T : T + + let obj: {}; +>obj : {} + + obj = x; +>obj = x : Partial +>obj : {} +>x : Partial + + obj = y; +>obj = y : Readonly +>obj : {} +>y : Readonly +} + +function f2(x: Partial, y: Readonly) { +>f2 : (x: Partial, y: Readonly) => void +>T : T +>x : Partial +>Partial : Partial +>T : T +>y : Readonly +>Readonly : Readonly +>T : T + + let obj: { [x: string]: any }; +>obj : { [x: string]: any; } +>x : string + + obj = x; +>obj = x : Partial +>obj : { [x: string]: any; } +>x : Partial + + obj = y; +>obj = y : Readonly +>obj : { [x: string]: any; } +>y : Readonly +} + +// Repro from #12900 + +interface Base { +>Base : Base + + foo: { [key: string]: any }; +>foo : { [key: string]: any; } +>key : string + + bar: any; +>bar : any + + baz: any; +>baz : any +} + +interface E1 extends Base { +>E1 : E1 +>T : T +>Base : Base + + foo: T; +>foo : T +>T : T +} + +interface Something { name: string, value: string }; +>Something : Something +>name : string +>value : string + +interface E2 extends Base { +>E2 : E2 +>Base : Base + + foo: Partial; // or other mapped type +>foo : Partial +>Partial : Partial +>Something : Something +} + +interface E3 extends Base { +>E3 : E3 +>T : T +>Base : Base + + foo: Partial; // or other mapped type +>foo : Partial +>Partial : Partial +>T : T +} diff --git a/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json index e53b2a0934f..f6df1476088 100644 --- a/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json +++ b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json @@ -5,24 +5,18 @@ "File '/node_modules/shortid.ts' does not exist.", "File '/node_modules/shortid.tsx' does not exist.", "File '/node_modules/shortid.d.ts' does not exist.", - "File '/node_modules/shortid.js' does not exist.", - "File '/node_modules/shortid.jsx' does not exist.", "File '/node_modules/shortid/package.json' does not exist.", "File '/node_modules/shortid/index.ts' does not exist.", "File '/node_modules/shortid/index.tsx' does not exist.", "File '/node_modules/shortid/index.d.ts' does not exist.", - "File '/node_modules/shortid/index.js' exist - use it as a name resolution result.", - "File '/node_modules/@types/shortid.ts' does not exist.", - "File '/node_modules/@types/shortid.tsx' does not exist.", "File '/node_modules/@types/shortid.d.ts' does not exist.", - "File '/node_modules/@types/shortid.js' does not exist.", - "File '/node_modules/@types/shortid.jsx' does not exist.", "File '/node_modules/@types/shortid/package.json' does not exist.", - "File '/node_modules/@types/shortid/index.ts' does not exist.", - "File '/node_modules/@types/shortid/index.tsx' does not exist.", "File '/node_modules/@types/shortid/index.d.ts' does not exist.", - "File '/node_modules/@types/shortid/index.js' does not exist.", - "File '/node_modules/@types/shortid/index.jsx' does not exist.", + "Loading module 'shortid' from 'node_modules' folder.", + "File '/node_modules/shortid.js' does not exist.", + "File '/node_modules/shortid.jsx' does not exist.", + "File '/node_modules/shortid/package.json' does not exist.", + "File '/node_modules/shortid/index.js' exist - use it as a name resolution result.", "Resolving real path for '/node_modules/shortid/index.js', result '/node_modules/shortid/index.js'", "======== Module name 'shortid' was successfully resolved to '/node_modules/shortid/index.js'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/mergeWithImportedType.js b/tests/baselines/reference/mergeWithImportedType.js index 89fc353d395..e8dc5a3c2f3 100644 --- a/tests/baselines/reference/mergeWithImportedType.js +++ b/tests/baselines/reference/mergeWithImportedType.js @@ -10,9 +10,9 @@ export type E = E; //// [f1.js] "use strict"; +var E; (function (E) { E[E["X"] = 0] = "X"; -})(exports.E || (exports.E = {})); -var E = exports.E; +})(E = exports.E || (exports.E = {})); //// [f2.js] "use strict"; diff --git a/tests/baselines/reference/mergedDeclarations3.js b/tests/baselines/reference/mergedDeclarations3.js index ddf94b46e81..d3b4e8fc9d5 100644 --- a/tests/baselines/reference/mergedDeclarations3.js +++ b/tests/baselines/reference/mergedDeclarations3.js @@ -42,11 +42,11 @@ M.foo.z // error //// [mergedDeclarations3.js] var M; (function (M) { + var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; - })(M.Color || (M.Color = {})); - var Color = M.Color; + })(Color = M.Color || (M.Color = {})); })(M || (M = {})); (function (M) { var Color; diff --git a/tests/baselines/reference/mergedModuleDeclarationCodeGen5.js b/tests/baselines/reference/mergedModuleDeclarationCodeGen5.js index 11a4773d63a..8891dbf61e2 100644 --- a/tests/baselines/reference/mergedModuleDeclarationCodeGen5.js +++ b/tests/baselines/reference/mergedModuleDeclarationCodeGen5.js @@ -45,9 +45,9 @@ var M; return fudge; }()); plop_1.fudge = fudge; + var plop; (function (plop) { - })(plop_1.plop || (plop_1.plop = {})); - var plop = plop_1.plop; + })(plop = plop_1.plop || (plop_1.plop = {})); // Emit these references as follows var v1 = gunk; // gunk var v2 = buz; // buz diff --git a/tests/baselines/reference/metadataOfClassFromModule.js b/tests/baselines/reference/metadataOfClassFromModule.js new file mode 100644 index 00000000000..8ef120600df --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromModule.js @@ -0,0 +1,44 @@ +//// [metadataOfClassFromModule.ts] +module MyModule { + + export function inject(target: any, key: string): void { } + + export class Leg { } + + export class Person { + @inject leftLeg: Leg; + } + +} + +//// [metadataOfClassFromModule.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var MyModule; +(function (MyModule) { + function inject(target, key) { } + MyModule.inject = inject; + var Leg = (function () { + function Leg() { + } + return Leg; + }()); + MyModule.Leg = Leg; + var Person = (function () { + function Person() { + } + return Person; + }()); + __decorate([ + inject, + __metadata("design:type", Leg) + ], Person.prototype, "leftLeg", void 0); + MyModule.Person = Person; +})(MyModule || (MyModule = {})); diff --git a/tests/baselines/reference/metadataOfClassFromModule.symbols b/tests/baselines/reference/metadataOfClassFromModule.symbols new file mode 100644 index 00000000000..f430677f0fa --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromModule.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/metadataOfClassFromModule.ts === +module MyModule { +>MyModule : Symbol(MyModule, Decl(metadataOfClassFromModule.ts, 0, 0)) + + export function inject(target: any, key: string): void { } +>inject : Symbol(inject, Decl(metadataOfClassFromModule.ts, 0, 17)) +>target : Symbol(target, Decl(metadataOfClassFromModule.ts, 2, 27)) +>key : Symbol(key, Decl(metadataOfClassFromModule.ts, 2, 39)) + + export class Leg { } +>Leg : Symbol(Leg, Decl(metadataOfClassFromModule.ts, 2, 62)) + + export class Person { +>Person : Symbol(Person, Decl(metadataOfClassFromModule.ts, 4, 24)) + + @inject leftLeg: Leg; +>inject : Symbol(inject, Decl(metadataOfClassFromModule.ts, 0, 17)) +>leftLeg : Symbol(Person.leftLeg, Decl(metadataOfClassFromModule.ts, 6, 25)) +>Leg : Symbol(Leg, Decl(metadataOfClassFromModule.ts, 2, 62)) + } + +} diff --git a/tests/baselines/reference/metadataOfClassFromModule.types b/tests/baselines/reference/metadataOfClassFromModule.types new file mode 100644 index 00000000000..eeb24bf82aa --- /dev/null +++ b/tests/baselines/reference/metadataOfClassFromModule.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/metadataOfClassFromModule.ts === +module MyModule { +>MyModule : typeof MyModule + + export function inject(target: any, key: string): void { } +>inject : (target: any, key: string) => void +>target : any +>key : string + + export class Leg { } +>Leg : Leg + + export class Person { +>Person : Person + + @inject leftLeg: Leg; +>inject : (target: any, key: string) => void +>leftLeg : Leg +>Leg : Leg + } + +} diff --git a/tests/baselines/reference/metadataOfUnionWithNull.js b/tests/baselines/reference/metadataOfUnionWithNull.js new file mode 100644 index 00000000000..cc594ae326d --- /dev/null +++ b/tests/baselines/reference/metadataOfUnionWithNull.js @@ -0,0 +1,113 @@ +//// [metadataOfUnionWithNull.ts] +function PropDeco(target: Object, propKey: string | symbol) { } + +class A { +} + +class B { + @PropDeco + x: "foo" | null; + + @PropDeco + y: true | never; + + @PropDeco + z: "foo" | undefined; + + @PropDeco + a: null; + + @PropDeco + b: never; + + @PropDeco + c: undefined; + + @PropDeco + d: undefined | null; + + @PropDeco + e: symbol | null; + + @PropDeco + f: symbol | A; + + @PropDeco + g: A | null; + + @PropDeco + h: null | B; + + @PropDeco + j: null | symbol; +} + +//// [metadataOfUnionWithNull.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +function PropDeco(target, propKey) { } +var A = (function () { + function A() { + } + return A; +}()); +var B = (function () { + function B() { + } + return B; +}()); +__decorate([ + PropDeco, + __metadata("design:type", String) +], B.prototype, "x"); +__decorate([ + PropDeco, + __metadata("design:type", Boolean) +], B.prototype, "y"); +__decorate([ + PropDeco, + __metadata("design:type", String) +], B.prototype, "z"); +__decorate([ + PropDeco, + __metadata("design:type", void 0) +], B.prototype, "a"); +__decorate([ + PropDeco, + __metadata("design:type", void 0) +], B.prototype, "b"); +__decorate([ + PropDeco, + __metadata("design:type", void 0) +], B.prototype, "c"); +__decorate([ + PropDeco, + __metadata("design:type", void 0) +], B.prototype, "d"); +__decorate([ + PropDeco, + __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) +], B.prototype, "e"); +__decorate([ + PropDeco, + __metadata("design:type", Object) +], B.prototype, "f"); +__decorate([ + PropDeco, + __metadata("design:type", A) +], B.prototype, "g"); +__decorate([ + PropDeco, + __metadata("design:type", B) +], B.prototype, "h"); +__decorate([ + PropDeco, + __metadata("design:type", typeof Symbol === "function" ? Symbol : Object) +], B.prototype, "j"); diff --git a/tests/baselines/reference/metadataOfUnionWithNull.symbols b/tests/baselines/reference/metadataOfUnionWithNull.symbols new file mode 100644 index 00000000000..13316bc7cf1 --- /dev/null +++ b/tests/baselines/reference/metadataOfUnionWithNull.symbols @@ -0,0 +1,89 @@ +=== tests/cases/compiler/metadataOfUnionWithNull.ts === +function PropDeco(target: Object, propKey: string | symbol) { } +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) +>target : Symbol(target, Decl(metadataOfUnionWithNull.ts, 0, 18)) +>Object : Symbol(Object, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>propKey : Symbol(propKey, Decl(metadataOfUnionWithNull.ts, 0, 33)) + +class A { +>A : Symbol(A, Decl(metadataOfUnionWithNull.ts, 0, 63)) +} + +class B { +>B : Symbol(B, Decl(metadataOfUnionWithNull.ts, 3, 1)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + x: "foo" | null; +>x : Symbol(B.x, Decl(metadataOfUnionWithNull.ts, 5, 9)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + y: true | never; +>y : Symbol(B.y, Decl(metadataOfUnionWithNull.ts, 7, 20)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + z: "foo" | undefined; +>z : Symbol(B.z, Decl(metadataOfUnionWithNull.ts, 10, 20)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + a: null; +>a : Symbol(B.a, Decl(metadataOfUnionWithNull.ts, 13, 25)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + b: never; +>b : Symbol(B.b, Decl(metadataOfUnionWithNull.ts, 16, 12)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + c: undefined; +>c : Symbol(B.c, Decl(metadataOfUnionWithNull.ts, 19, 13)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + d: undefined | null; +>d : Symbol(B.d, Decl(metadataOfUnionWithNull.ts, 22, 17)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + e: symbol | null; +>e : Symbol(B.e, Decl(metadataOfUnionWithNull.ts, 25, 24)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + f: symbol | A; +>f : Symbol(B.f, Decl(metadataOfUnionWithNull.ts, 28, 21)) +>A : Symbol(A, Decl(metadataOfUnionWithNull.ts, 0, 63)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + g: A | null; +>g : Symbol(B.g, Decl(metadataOfUnionWithNull.ts, 31, 18)) +>A : Symbol(A, Decl(metadataOfUnionWithNull.ts, 0, 63)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + h: null | B; +>h : Symbol(B.h, Decl(metadataOfUnionWithNull.ts, 34, 16)) +>B : Symbol(B, Decl(metadataOfUnionWithNull.ts, 3, 1)) + + @PropDeco +>PropDeco : Symbol(PropDeco, Decl(metadataOfUnionWithNull.ts, 0, 0)) + + j: null | symbol; +>j : Symbol(B.j, Decl(metadataOfUnionWithNull.ts, 37, 16)) +} diff --git a/tests/baselines/reference/metadataOfUnionWithNull.types b/tests/baselines/reference/metadataOfUnionWithNull.types new file mode 100644 index 00000000000..04a5b162d4c --- /dev/null +++ b/tests/baselines/reference/metadataOfUnionWithNull.types @@ -0,0 +1,97 @@ +=== tests/cases/compiler/metadataOfUnionWithNull.ts === +function PropDeco(target: Object, propKey: string | symbol) { } +>PropDeco : (target: Object, propKey: string | symbol) => void +>target : Object +>Object : Object +>propKey : string | symbol + +class A { +>A : A +} + +class B { +>B : B + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + x: "foo" | null; +>x : "foo" +>null : null + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + y: true | never; +>y : true +>true : true + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + z: "foo" | undefined; +>z : "foo" + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + a: null; +>a : null +>null : null + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + b: never; +>b : never + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + c: undefined; +>c : undefined + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + d: undefined | null; +>d : null +>null : null + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + e: symbol | null; +>e : symbol +>null : null + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + f: symbol | A; +>f : symbol | A +>A : A + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + g: A | null; +>g : A +>A : A +>null : null + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + h: null | B; +>h : B +>null : null +>B : B + + @PropDeco +>PropDeco : (target: Object, propKey: string | symbol) => void + + j: null | symbol; +>j : symbol +>null : null +} diff --git a/tests/baselines/reference/missingAndExcessProperties.js b/tests/baselines/reference/missingAndExcessProperties.js index b9fcadd9519..daefe18eed7 100644 --- a/tests/baselines/reference/missingAndExcessProperties.js +++ b/tests/baselines/reference/missingAndExcessProperties.js @@ -45,10 +45,10 @@ function f1() { // Missing properties function f2() { var x, y; - (_a = {}, x = _a.x, y = _a.y, _a); - (_b = {}, _c = _b.x, x = _c === void 0 ? 1 : _c, y = _b.y, _b); - (_d = {}, x = _d.x, _e = _d.y, y = _e === void 0 ? 1 : _e, _d); - (_f = {}, _g = _f.x, x = _g === void 0 ? 1 : _g, _h = _f.y, y = _h === void 0 ? 1 : _h, _f); + (_a = {}, x = _a.x, y = _a.y); + (_b = {}, _c = _b.x, x = _c === void 0 ? 1 : _c, y = _b.y); + (_d = {}, x = _d.x, _e = _d.y, y = _e === void 0 ? 1 : _e); + (_f = {}, _g = _f.x, x = _g === void 0 ? 1 : _g, _h = _f.y, y = _h === void 0 ? 1 : _h); var _a, _b, _c, _d, _e, _f, _g, _h; } // Excess properties @@ -62,8 +62,8 @@ function f3() { function f4() { var x, y; ({ x: 0, y: 0 }); - (_a = { x: 0, y: 0 }, x = _a.x, _a); - (_b = { x: 0, y: 0 }, y = _b.y, _b); - (_c = { x: 0, y: 0 }, x = _c.x, y = _c.y, _c); - var _a, _b, _c; + (x = { x: 0, y: 0 }.x); + (y = { x: 0, y: 0 }.y); + (_a = { x: 0, y: 0 }, x = _a.x, y = _a.y); + var _a; } diff --git a/tests/baselines/reference/missingPropertiesOfClassExpression.errors.txt b/tests/baselines/reference/missingPropertiesOfClassExpression.errors.txt index 23e67d7cf0b..b7331a68271 100644 --- a/tests/baselines/reference/missingPropertiesOfClassExpression.errors.txt +++ b/tests/baselines/reference/missingPropertiesOfClassExpression.errors.txt @@ -1,11 +1,8 @@ -tests/cases/compiler/missingPropertiesOfClassExpression.ts(1,22): error TS2690: A class must be declared after its base class. tests/cases/compiler/missingPropertiesOfClassExpression.ts(1,52): error TS2339: Property 'y' does not exist on type '(Anonymous class)'. -==== tests/cases/compiler/missingPropertiesOfClassExpression.ts (2 errors) ==== +==== tests/cases/compiler/missingPropertiesOfClassExpression.ts (1 errors) ==== class George extends class { reset() { return this.y; } } { - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2690: A class must be declared after its base class. ~ !!! error TS2339: Property 'y' does not exist on type '(Anonymous class)'. constructor() { diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.symbols b/tests/baselines/reference/modularizeLibrary_Dom.iterable.symbols index a487763582b..478997ca630 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.symbols +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.symbols @@ -2,9 +2,9 @@ for (const element of document.getElementsByTagName("a")) { >element : Symbol(element, Decl(modularizeLibrary_Dom.iterable.ts, 1, 10)) ->document.getElementsByTagName : Symbol(Document.getElementsByTagName, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) +>document.getElementsByTagName : Symbol(Document.getElementsByTagName, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) >document : Symbol(document, Decl(lib.dom.d.ts, --, --)) ->getElementsByTagName : Symbol(Document.getElementsByTagName, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) +>getElementsByTagName : Symbol(Document.getElementsByTagName, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) element.href; >element.href : Symbol(HTMLAnchorElement.href, Decl(lib.dom.d.ts, --, --)) diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types index dbce5e17ae2..054923fb5ee 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types @@ -3,9 +3,9 @@ for (const element of document.getElementsByTagName("a")) { >element : HTMLAnchorElement >document.getElementsByTagName("a") : NodeListOf ->document.getElementsByTagName : { (tagname: "a"): NodeListOf; (tagname: "abbr"): NodeListOf; (tagname: "acronym"): NodeListOf; (tagname: "address"): NodeListOf; (tagname: "applet"): NodeListOf; (tagname: "area"): NodeListOf; (tagname: "article"): NodeListOf; (tagname: "aside"): NodeListOf; (tagname: "audio"): NodeListOf; (tagname: "b"): NodeListOf; (tagname: "base"): NodeListOf; (tagname: "basefont"): NodeListOf; (tagname: "bdo"): NodeListOf; (tagname: "big"): NodeListOf; (tagname: "blockquote"): NodeListOf; (tagname: "body"): NodeListOf; (tagname: "br"): NodeListOf; (tagname: "button"): NodeListOf; (tagname: "canvas"): NodeListOf; (tagname: "caption"): NodeListOf; (tagname: "center"): NodeListOf; (tagname: "circle"): NodeListOf; (tagname: "cite"): NodeListOf; (tagname: "clippath"): NodeListOf; (tagname: "code"): NodeListOf; (tagname: "col"): NodeListOf; (tagname: "colgroup"): NodeListOf; (tagname: "datalist"): NodeListOf; (tagname: "dd"): NodeListOf; (tagname: "defs"): NodeListOf; (tagname: "del"): NodeListOf; (tagname: "desc"): NodeListOf; (tagname: "dfn"): NodeListOf; (tagname: "dir"): NodeListOf; (tagname: "div"): NodeListOf; (tagname: "dl"): NodeListOf; (tagname: "dt"): NodeListOf; (tagname: "ellipse"): NodeListOf; (tagname: "em"): NodeListOf; (tagname: "embed"): NodeListOf; (tagname: "feblend"): NodeListOf; (tagname: "fecolormatrix"): NodeListOf; (tagname: "fecomponenttransfer"): NodeListOf; (tagname: "fecomposite"): NodeListOf; (tagname: "feconvolvematrix"): NodeListOf; (tagname: "fediffuselighting"): NodeListOf; (tagname: "fedisplacementmap"): NodeListOf; (tagname: "fedistantlight"): NodeListOf; (tagname: "feflood"): NodeListOf; (tagname: "fefunca"): NodeListOf; (tagname: "fefuncb"): NodeListOf; (tagname: "fefuncg"): NodeListOf; (tagname: "fefuncr"): NodeListOf; (tagname: "fegaussianblur"): NodeListOf; (tagname: "feimage"): NodeListOf; (tagname: "femerge"): NodeListOf; (tagname: "femergenode"): NodeListOf; (tagname: "femorphology"): NodeListOf; (tagname: "feoffset"): NodeListOf; (tagname: "fepointlight"): NodeListOf; (tagname: "fespecularlighting"): NodeListOf; (tagname: "fespotlight"): NodeListOf; (tagname: "fetile"): NodeListOf; (tagname: "feturbulence"): NodeListOf; (tagname: "fieldset"): NodeListOf; (tagname: "figcaption"): NodeListOf; (tagname: "figure"): NodeListOf; (tagname: "filter"): NodeListOf; (tagname: "font"): NodeListOf; (tagname: "footer"): NodeListOf; (tagname: "foreignobject"): NodeListOf; (tagname: "form"): NodeListOf; (tagname: "frame"): NodeListOf; (tagname: "frameset"): NodeListOf; (tagname: "g"): NodeListOf; (tagname: "h1"): NodeListOf; (tagname: "h2"): NodeListOf; (tagname: "h3"): NodeListOf; (tagname: "h4"): NodeListOf; (tagname: "h5"): NodeListOf; (tagname: "h6"): NodeListOf; (tagname: "head"): NodeListOf; (tagname: "header"): NodeListOf; (tagname: "hgroup"): NodeListOf; (tagname: "hr"): NodeListOf; (tagname: "html"): NodeListOf; (tagname: "i"): NodeListOf; (tagname: "iframe"): NodeListOf; (tagname: "image"): NodeListOf; (tagname: "img"): NodeListOf; (tagname: "input"): NodeListOf; (tagname: "ins"): NodeListOf; (tagname: "isindex"): NodeListOf; (tagname: "kbd"): NodeListOf; (tagname: "keygen"): NodeListOf; (tagname: "label"): NodeListOf; (tagname: "legend"): NodeListOf; (tagname: "li"): NodeListOf; (tagname: "line"): NodeListOf; (tagname: "lineargradient"): NodeListOf; (tagname: "link"): NodeListOf; (tagname: "listing"): NodeListOf; (tagname: "map"): NodeListOf; (tagname: "mark"): NodeListOf; (tagname: "marker"): NodeListOf; (tagname: "marquee"): NodeListOf; (tagname: "mask"): NodeListOf; (tagname: "menu"): NodeListOf; (tagname: "meta"): NodeListOf; (tagname: "metadata"): NodeListOf; (tagname: "meter"): NodeListOf; (tagname: "nav"): NodeListOf; (tagname: "nextid"): NodeListOf; (tagname: "nobr"): NodeListOf; (tagname: "noframes"): NodeListOf; (tagname: "noscript"): NodeListOf; (tagname: "object"): NodeListOf; (tagname: "ol"): NodeListOf; (tagname: "optgroup"): NodeListOf; (tagname: "option"): NodeListOf; (tagname: "p"): NodeListOf; (tagname: "param"): NodeListOf; (tagname: "path"): NodeListOf; (tagname: "pattern"): NodeListOf; (tagname: "picture"): NodeListOf; (tagname: "plaintext"): NodeListOf; (tagname: "polygon"): NodeListOf; (tagname: "polyline"): NodeListOf; (tagname: "pre"): NodeListOf; (tagname: "progress"): NodeListOf; (tagname: "q"): NodeListOf; (tagname: "radialgradient"): NodeListOf; (tagname: "rect"): NodeListOf; (tagname: "rt"): NodeListOf; (tagname: "ruby"): NodeListOf; (tagname: "s"): NodeListOf; (tagname: "samp"): NodeListOf; (tagname: "script"): NodeListOf; (tagname: "section"): NodeListOf; (tagname: "select"): NodeListOf; (tagname: "small"): NodeListOf; (tagname: "source"): NodeListOf; (tagname: "span"): NodeListOf; (tagname: "stop"): NodeListOf; (tagname: "strike"): NodeListOf; (tagname: "strong"): NodeListOf; (tagname: "style"): NodeListOf; (tagname: "sub"): NodeListOf; (tagname: "sup"): NodeListOf; (tagname: "svg"): NodeListOf; (tagname: "switch"): NodeListOf; (tagname: "symbol"): NodeListOf; (tagname: "table"): NodeListOf; (tagname: "tbody"): NodeListOf; (tagname: "td"): NodeListOf; (tagname: "template"): NodeListOf; (tagname: "text"): NodeListOf; (tagname: "textpath"): NodeListOf; (tagname: "textarea"): NodeListOf; (tagname: "tfoot"): NodeListOf; (tagname: "th"): NodeListOf; (tagname: "thead"): NodeListOf; (tagname: "title"): NodeListOf; (tagname: "tr"): NodeListOf; (tagname: "track"): NodeListOf; (tagname: "tspan"): NodeListOf; (tagname: "tt"): NodeListOf; (tagname: "u"): NodeListOf; (tagname: "ul"): NodeListOf; (tagname: "use"): NodeListOf; (tagname: "var"): NodeListOf; (tagname: "video"): NodeListOf; (tagname: "view"): NodeListOf; (tagname: "wbr"): NodeListOf; (tagname: "x-ms-webview"): NodeListOf; (tagname: "xmp"): NodeListOf; (tagname: string): NodeListOf; } +>document.getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >document : Document ->getElementsByTagName : { (tagname: "a"): NodeListOf; (tagname: "abbr"): NodeListOf; (tagname: "acronym"): NodeListOf; (tagname: "address"): NodeListOf; (tagname: "applet"): NodeListOf; (tagname: "area"): NodeListOf; (tagname: "article"): NodeListOf; (tagname: "aside"): NodeListOf; (tagname: "audio"): NodeListOf; (tagname: "b"): NodeListOf; (tagname: "base"): NodeListOf; (tagname: "basefont"): NodeListOf; (tagname: "bdo"): NodeListOf; (tagname: "big"): NodeListOf; (tagname: "blockquote"): NodeListOf; (tagname: "body"): NodeListOf; (tagname: "br"): NodeListOf; (tagname: "button"): NodeListOf; (tagname: "canvas"): NodeListOf; (tagname: "caption"): NodeListOf; (tagname: "center"): NodeListOf; (tagname: "circle"): NodeListOf; (tagname: "cite"): NodeListOf; (tagname: "clippath"): NodeListOf; (tagname: "code"): NodeListOf; (tagname: "col"): NodeListOf; (tagname: "colgroup"): NodeListOf; (tagname: "datalist"): NodeListOf; (tagname: "dd"): NodeListOf; (tagname: "defs"): NodeListOf; (tagname: "del"): NodeListOf; (tagname: "desc"): NodeListOf; (tagname: "dfn"): NodeListOf; (tagname: "dir"): NodeListOf; (tagname: "div"): NodeListOf; (tagname: "dl"): NodeListOf; (tagname: "dt"): NodeListOf; (tagname: "ellipse"): NodeListOf; (tagname: "em"): NodeListOf; (tagname: "embed"): NodeListOf; (tagname: "feblend"): NodeListOf; (tagname: "fecolormatrix"): NodeListOf; (tagname: "fecomponenttransfer"): NodeListOf; (tagname: "fecomposite"): NodeListOf; (tagname: "feconvolvematrix"): NodeListOf; (tagname: "fediffuselighting"): NodeListOf; (tagname: "fedisplacementmap"): NodeListOf; (tagname: "fedistantlight"): NodeListOf; (tagname: "feflood"): NodeListOf; (tagname: "fefunca"): NodeListOf; (tagname: "fefuncb"): NodeListOf; (tagname: "fefuncg"): NodeListOf; (tagname: "fefuncr"): NodeListOf; (tagname: "fegaussianblur"): NodeListOf; (tagname: "feimage"): NodeListOf; (tagname: "femerge"): NodeListOf; (tagname: "femergenode"): NodeListOf; (tagname: "femorphology"): NodeListOf; (tagname: "feoffset"): NodeListOf; (tagname: "fepointlight"): NodeListOf; (tagname: "fespecularlighting"): NodeListOf; (tagname: "fespotlight"): NodeListOf; (tagname: "fetile"): NodeListOf; (tagname: "feturbulence"): NodeListOf; (tagname: "fieldset"): NodeListOf; (tagname: "figcaption"): NodeListOf; (tagname: "figure"): NodeListOf; (tagname: "filter"): NodeListOf; (tagname: "font"): NodeListOf; (tagname: "footer"): NodeListOf; (tagname: "foreignobject"): NodeListOf; (tagname: "form"): NodeListOf; (tagname: "frame"): NodeListOf; (tagname: "frameset"): NodeListOf; (tagname: "g"): NodeListOf; (tagname: "h1"): NodeListOf; (tagname: "h2"): NodeListOf; (tagname: "h3"): NodeListOf; (tagname: "h4"): NodeListOf; (tagname: "h5"): NodeListOf; (tagname: "h6"): NodeListOf; (tagname: "head"): NodeListOf; (tagname: "header"): NodeListOf; (tagname: "hgroup"): NodeListOf; (tagname: "hr"): NodeListOf; (tagname: "html"): NodeListOf; (tagname: "i"): NodeListOf; (tagname: "iframe"): NodeListOf; (tagname: "image"): NodeListOf; (tagname: "img"): NodeListOf; (tagname: "input"): NodeListOf; (tagname: "ins"): NodeListOf; (tagname: "isindex"): NodeListOf; (tagname: "kbd"): NodeListOf; (tagname: "keygen"): NodeListOf; (tagname: "label"): NodeListOf; (tagname: "legend"): NodeListOf; (tagname: "li"): NodeListOf; (tagname: "line"): NodeListOf; (tagname: "lineargradient"): NodeListOf; (tagname: "link"): NodeListOf; (tagname: "listing"): NodeListOf; (tagname: "map"): NodeListOf; (tagname: "mark"): NodeListOf; (tagname: "marker"): NodeListOf; (tagname: "marquee"): NodeListOf; (tagname: "mask"): NodeListOf; (tagname: "menu"): NodeListOf; (tagname: "meta"): NodeListOf; (tagname: "metadata"): NodeListOf; (tagname: "meter"): NodeListOf; (tagname: "nav"): NodeListOf; (tagname: "nextid"): NodeListOf; (tagname: "nobr"): NodeListOf; (tagname: "noframes"): NodeListOf; (tagname: "noscript"): NodeListOf; (tagname: "object"): NodeListOf; (tagname: "ol"): NodeListOf; (tagname: "optgroup"): NodeListOf; (tagname: "option"): NodeListOf; (tagname: "p"): NodeListOf; (tagname: "param"): NodeListOf; (tagname: "path"): NodeListOf; (tagname: "pattern"): NodeListOf; (tagname: "picture"): NodeListOf; (tagname: "plaintext"): NodeListOf; (tagname: "polygon"): NodeListOf; (tagname: "polyline"): NodeListOf; (tagname: "pre"): NodeListOf; (tagname: "progress"): NodeListOf; (tagname: "q"): NodeListOf; (tagname: "radialgradient"): NodeListOf; (tagname: "rect"): NodeListOf; (tagname: "rt"): NodeListOf; (tagname: "ruby"): NodeListOf; (tagname: "s"): NodeListOf; (tagname: "samp"): NodeListOf; (tagname: "script"): NodeListOf; (tagname: "section"): NodeListOf; (tagname: "select"): NodeListOf; (tagname: "small"): NodeListOf; (tagname: "source"): NodeListOf; (tagname: "span"): NodeListOf; (tagname: "stop"): NodeListOf; (tagname: "strike"): NodeListOf; (tagname: "strong"): NodeListOf; (tagname: "style"): NodeListOf; (tagname: "sub"): NodeListOf; (tagname: "sup"): NodeListOf; (tagname: "svg"): NodeListOf; (tagname: "switch"): NodeListOf; (tagname: "symbol"): NodeListOf; (tagname: "table"): NodeListOf; (tagname: "tbody"): NodeListOf; (tagname: "td"): NodeListOf; (tagname: "template"): NodeListOf; (tagname: "text"): NodeListOf; (tagname: "textpath"): NodeListOf; (tagname: "textarea"): NodeListOf; (tagname: "tfoot"): NodeListOf; (tagname: "th"): NodeListOf; (tagname: "thead"): NodeListOf; (tagname: "title"): NodeListOf; (tagname: "tr"): NodeListOf; (tagname: "track"): NodeListOf; (tagname: "tspan"): NodeListOf; (tagname: "tt"): NodeListOf; (tagname: "u"): NodeListOf; (tagname: "ul"): NodeListOf; (tagname: "use"): NodeListOf; (tagname: "var"): NodeListOf; (tagname: "video"): NodeListOf; (tagname: "view"): NodeListOf; (tagname: "wbr"): NodeListOf; (tagname: "x-ms-webview"): NodeListOf; (tagname: "xmp"): NodeListOf; (tagname: string): NodeListOf; } +>getElementsByTagName : { (tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf; } >"a" : "a" element.href; diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js index 180b53028ff..b83efdce890 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js @@ -87,7 +87,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // Using Es6 array diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js index cf69f260223..32d7135916b 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js @@ -87,7 +87,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // Using Es6 array diff --git a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js index 350113ec6a0..d0de3c93da0 100644 --- a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js +++ b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js @@ -87,7 +87,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // Using Es6 array diff --git a/tests/baselines/reference/moduleCodeGenTest5.js b/tests/baselines/reference/moduleCodeGenTest5.js index fa09b432ab7..6a7113c0368 100644 --- a/tests/baselines/reference/moduleCodeGenTest5.js +++ b/tests/baselines/reference/moduleCodeGenTest5.js @@ -43,10 +43,10 @@ var C2 = (function () { C2.prototype.p2 = function () { }; return C2; }()); +var E1; (function (E1) { E1[E1["A"] = 0] = "A"; -})(exports.E1 || (exports.E1 = {})); -var E1 = exports.E1; +})(E1 = exports.E1 || (exports.E1 = {})); var u = E1.A; var E2; (function (E2) { diff --git a/tests/baselines/reference/moduleDuplicateIdentifiers.js b/tests/baselines/reference/moduleDuplicateIdentifiers.js index 097192ac73c..64b82f82500 100644 --- a/tests/baselines/reference/moduleDuplicateIdentifiers.js +++ b/tests/baselines/reference/moduleDuplicateIdentifiers.js @@ -67,12 +67,12 @@ var Kettle = (function () { exports.Kettle = Kettle; exports.Pot = 2; exports.Pot = 42; // Shouldn't error +var Utensils; (function (Utensils) { Utensils[Utensils["Spoon"] = 0] = "Spoon"; Utensils[Utensils["Fork"] = 1] = "Fork"; Utensils[Utensils["Knife"] = 2] = "Knife"; -})(exports.Utensils || (exports.Utensils = {})); -var Utensils = exports.Utensils; +})(Utensils = exports.Utensils || (exports.Utensils = {})); (function (Utensils) { Utensils[Utensils["Spork"] = 3] = "Spork"; -})(exports.Utensils || (exports.Utensils = {})); +})(Utensils = exports.Utensils || (exports.Utensils = {})); diff --git a/tests/baselines/reference/moduleElementsInWrongContext3.js b/tests/baselines/reference/moduleElementsInWrongContext3.js index 76220eab251..851ad654494 100644 --- a/tests/baselines/reference/moduleElementsInWrongContext3.js +++ b/tests/baselines/reference/moduleElementsInWrongContext3.js @@ -47,9 +47,8 @@ var P; } return C; }()); - P.C = C; - function bee() { } - P.bee = bee; + export default C; + export function bee() { } import I2 = require("foo"); import * as Foo from "ambient"; import bar from "ambient"; diff --git a/tests/baselines/reference/moduleResolutionNoTs.js b/tests/baselines/reference/moduleResolutionNoTs.js index 9ff33d688ea..a17f108d872 100644 --- a/tests/baselines/reference/moduleResolutionNoTs.js +++ b/tests/baselines/reference/moduleResolutionNoTs.js @@ -25,7 +25,7 @@ import z2 from "./z"; "use strict"; exports.__esModule = true; exports["default"] = 0; -//// [y.js] +//// [y.jsx] "use strict"; exports.__esModule = true; exports["default"] = 0; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions.trace.json index 5060006ac56..6860c61bb17 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions.trace.json @@ -3,7 +3,6 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/src/a'.", "File '/src/a.ts' exist - use it as a name resolution result.", - "Resolving real path for '/src/a.ts', result '/src/a.ts'", "======== Module name './a' was successfully resolved to '/src/a.ts'. ========", "======== Resolving module './a.js' from '/src/d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -13,7 +12,6 @@ "File '/src/a.js.d.ts' does not exist.", "File name '/src/a.js' has a '.js' extension - stripping it", "File '/src/a.ts' exist - use it as a name resolution result.", - "Resolving real path for '/src/a.ts', result '/src/a.ts'", "======== Module name './a.js' was successfully resolved to '/src/a.ts'. ========", "======== Resolving module './jquery.js' from '/src/jquery_user_1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -25,6 +23,5 @@ "File '/src/jquery.ts' does not exist.", "File '/src/jquery.tsx' does not exist.", "File '/src/jquery.d.ts' exist - use it as a name resolution result.", - "Resolving real path for '/src/jquery.d.ts', result '/src/jquery.d.ts'", "======== Module name './jquery.js' was successfully resolved to '/src/jquery.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.errors.txt b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.errors.txt new file mode 100644 index 00000000000..aa415a95b1b --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.errors.txt @@ -0,0 +1,23 @@ +/a.ts(1,17): error TS6142: Module './tsx' was resolved to '/tsx.tsx', but '--jsx' is not set. +/a.ts(2,17): error TS6142: Module './jsx' was resolved to '/jsx.jsx', but '--jsx' is not set. +/a.ts(3,16): error TS6143: Module './js' was resolved to '/js.js', but '--allowJs' is not set. + + +==== /a.ts (3 errors) ==== + import tsx from "./tsx"; + ~~~~~~~ +!!! error TS6142: Module './tsx' was resolved to '/tsx.tsx', but '--jsx' is not set. + import jsx from "./jsx"; + ~~~~~~~ +!!! error TS6142: Module './jsx' was resolved to '/jsx.jsx', but '--jsx' is not set. + import js from "./js"; + ~~~~~~ +!!! error TS6143: Module './js' was resolved to '/js.js', but '--allowJs' is not set. + +==== /tsx.tsx (0 errors) ==== + + +==== /jsx.jsx (0 errors) ==== + +==== /js.js (0 errors) ==== + \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.js b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.js new file mode 100644 index 00000000000..2e5297bdf65 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_notSupported.ts] //// + +//// [tsx.tsx] + + +//// [jsx.jsx] + +//// [js.js] + +//// [a.ts] +import tsx from "./tsx"; +import jsx from "./jsx"; +import js from "./js"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.trace.json new file mode 100644 index 00000000000..f2b0214602c --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported.trace.json @@ -0,0 +1,35 @@ +[ + "======== Resolving module './tsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/tsx'.", + "File '/tsx.ts' does not exist.", + "File '/tsx.tsx' exist - use it as a name resolution result.", + "======== Module name './tsx' was successfully resolved to '/tsx.tsx'. ========", + "======== Resolving module './jsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.ts' does not exist.", + "File '/jsx.tsx' does not exist.", + "File '/jsx.d.ts' does not exist.", + "File '/jsx/package.json' does not exist.", + "File '/jsx/index.ts' does not exist.", + "File '/jsx/index.tsx' does not exist.", + "File '/jsx/index.d.ts' does not exist.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.js' does not exist.", + "File '/jsx.jsx' exist - use it as a name resolution result.", + "======== Module name './jsx' was successfully resolved to '/jsx.jsx'. ========", + "======== Resolving module './js' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/js'.", + "File '/js.ts' does not exist.", + "File '/js.tsx' does not exist.", + "File '/js.d.ts' does not exist.", + "File '/js/package.json' does not exist.", + "File '/js/index.ts' does not exist.", + "File '/js/index.tsx' does not exist.", + "File '/js/index.d.ts' does not exist.", + "Loading module as file / folder, candidate module location '/js'.", + "File '/js.js' exist - use it as a name resolution result.", + "======== Module name './js' was successfully resolved to '/js.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.errors.txt b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.errors.txt new file mode 100644 index 00000000000..bb8a0664ed6 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.errors.txt @@ -0,0 +1,12 @@ +/a.ts(1,17): error TS6142: Module './jsx' was resolved to '/jsx.jsx', but '--jsx' is not set. + + +==== /a.ts (1 errors) ==== + import jsx from "./jsx"; + ~~~~~~~ +!!! error TS6142: Module './jsx' was resolved to '/jsx.jsx', but '--jsx' is not set. + +==== /jsx.jsx (0 errors) ==== + // Test the error message if we have `--allowJs` but not `--jsx`. + + \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.js b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.js new file mode 100644 index 00000000000..c340f65f251 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_notSupported2.ts] //// + +//// [jsx.jsx] +// Test the error message if we have `--allowJs` but not `--jsx`. + + +//// [a.ts] +import jsx from "./jsx"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.trace.json new file mode 100644 index 00000000000..89bd061301e --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported2.trace.json @@ -0,0 +1,16 @@ +[ + "======== Resolving module './jsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.ts' does not exist.", + "File '/jsx.tsx' does not exist.", + "File '/jsx.d.ts' does not exist.", + "File '/jsx/package.json' does not exist.", + "File '/jsx/index.ts' does not exist.", + "File '/jsx/index.tsx' does not exist.", + "File '/jsx/index.d.ts' does not exist.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.js' does not exist.", + "File '/jsx.jsx' exist - use it as a name resolution result.", + "======== Module name './jsx' was successfully resolved to '/jsx.jsx'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.errors.txt b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.errors.txt new file mode 100644 index 00000000000..45e058bae54 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.errors.txt @@ -0,0 +1,12 @@ +/a.ts(1,17): error TS6143: Module './jsx' was resolved to '/jsx.jsx', but '--allowJs' is not set. + + +==== /a.ts (1 errors) ==== + import jsx from "./jsx"; + ~~~~~~~ +!!! error TS6143: Module './jsx' was resolved to '/jsx.jsx', but '--allowJs' is not set. + +==== /jsx.jsx (0 errors) ==== + // Test the error message if we have `--jsx` but not `--allowJw`. + + \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.js b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.js new file mode 100644 index 00000000000..f362701bbda --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_notSupported3.ts] //// + +//// [jsx.jsx] +// Test the error message if we have `--jsx` but not `--allowJw`. + + +//// [a.ts] +import jsx from "./jsx"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.trace.json new file mode 100644 index 00000000000..89bd061301e --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_notSupported3.trace.json @@ -0,0 +1,16 @@ +[ + "======== Resolving module './jsx' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.ts' does not exist.", + "File '/jsx.tsx' does not exist.", + "File '/jsx.d.ts' does not exist.", + "File '/jsx/package.json' does not exist.", + "File '/jsx/index.ts' does not exist.", + "File '/jsx/index.tsx' does not exist.", + "File '/jsx/index.d.ts' does not exist.", + "Loading module as file / folder, candidate module location '/jsx'.", + "File '/jsx.js' does not exist.", + "File '/jsx.jsx' exist - use it as a name resolution result.", + "======== Module name './jsx' was successfully resolved to '/jsx.jsx'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.js b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.js new file mode 100644 index 00000000000..177321c7d08 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.js @@ -0,0 +1,18 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_preferTs.ts] //// + +//// [b.js] + + +//// [index.ts] +export default 0; + +//// [a.ts] +import b from "./b"; + + +//// [index.js] +"use strict"; +exports.__esModule = true; +exports["default"] = 0; +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.symbols b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.symbols new file mode 100644 index 00000000000..af9dc4154d4 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.symbols @@ -0,0 +1,8 @@ +=== /a.ts === +import b from "./b"; +>b : Symbol(b, Decl(a.ts, 0, 6)) + +=== /b/index.ts === +export default 0; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.trace.json new file mode 100644 index 00000000000..f6612b84cc3 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.trace.json @@ -0,0 +1,11 @@ +[ + "======== Resolving module './b' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/b'.", + "File '/b.ts' does not exist.", + "File '/b.tsx' does not exist.", + "File '/b.d.ts' does not exist.", + "File '/b/package.json' does not exist.", + "File '/b/index.ts' exist - use it as a name resolution result.", + "======== Module name './b' was successfully resolved to '/b/index.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.types b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.types new file mode 100644 index 00000000000..0e418c5dc14 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_preferTs.types @@ -0,0 +1,8 @@ +=== /a.ts === +import b from "./b"; +>b : 0 + +=== /b/index.ts === +export default 0; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.js b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.js new file mode 100644 index 00000000000..b5d4ae20a4d --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_unexpected.ts] //// + +//// [normalize.css] +// This tests that a package.json "main" with an unexpected extension is ignored. + +This file is not read. + +//// [package.json] +{ "main": "normalize.css" } + +//// [a.ts] +import "normalize.css"; + + +//// [a.js] +"use strict"; +require("normalize.css"); diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.symbols b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.symbols new file mode 100644 index 00000000000..a73d58fd7d8 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.symbols @@ -0,0 +1,4 @@ +=== /a.ts === +import "normalize.css"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json new file mode 100644 index 00000000000..84532e8db7b --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json @@ -0,0 +1,29 @@ +[ + "======== Resolving module 'normalize.css' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'normalize.css' from 'node_modules' folder.", + "File '/node_modules/normalize.css.ts' does not exist.", + "File '/node_modules/normalize.css.tsx' does not exist.", + "File '/node_modules/normalize.css.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/normalize.css/package.json'.", + "'package.json' does not have a 'types' or 'main' field.", + "File '/node_modules/normalize.css/index.ts' does not exist.", + "File '/node_modules/normalize.css/index.tsx' does not exist.", + "File '/node_modules/normalize.css/index.d.ts' does not exist.", + "File '/node_modules/@types/normalize.css.d.ts' does not exist.", + "File '/node_modules/@types/normalize.css/package.json' does not exist.", + "File '/node_modules/@types/normalize.css/index.d.ts' does not exist.", + "Loading module 'normalize.css' from 'node_modules' folder.", + "File '/node_modules/normalize.css.js' does not exist.", + "File '/node_modules/normalize.css.jsx' does not exist.", + "Found 'package.json' at '/node_modules/normalize.css/package.json'.", + "No types specified in 'package.json', so returning 'main' value of 'normalize.css'", + "File '/node_modules/normalize.css/normalize.css' exist - use it as a name resolution result.", + "File '/node_modules/normalize.css/normalize.css' has an unsupported extension, so skipping it.", + "File '/node_modules/normalize.css/normalize.css.ts' does not exist.", + "File '/node_modules/normalize.css/normalize.css.tsx' does not exist.", + "File '/node_modules/normalize.css/normalize.css.d.ts' does not exist.", + "File '/node_modules/normalize.css/index.js' does not exist.", + "File '/node_modules/normalize.css/index.jsx' does not exist.", + "======== Module name 'normalize.css' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.types b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.types new file mode 100644 index 00000000000..a73d58fd7d8 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.types @@ -0,0 +1,4 @@ +=== /a.ts === +import "normalize.css"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.js b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.js new file mode 100644 index 00000000000..dc9df79e4df --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_unexpected2.ts] //// + +//// [foo.js] +// This tests that a package.json "types" with an unexpected extension is ignored. + +This file is not read. + +//// [package.json] +{ "types": "foo.js" } + +//// [a.ts] +import "foo"; + + +//// [a.js] +"use strict"; +require("foo"); diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.symbols b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.symbols new file mode 100644 index 00000000000..11c9c72cc69 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.symbols @@ -0,0 +1,4 @@ +=== /a.ts === +import "foo"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json new file mode 100644 index 00000000000..27c9d2243e5 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json @@ -0,0 +1,29 @@ +[ + "======== Resolving module 'foo' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/node_modules/foo.ts' does not exist.", + "File '/node_modules/foo.tsx' does not exist.", + "File '/node_modules/foo.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/foo/package.json'.", + "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", + "File '/node_modules/foo/foo.js' exist - use it as a name resolution result.", + "File '/node_modules/foo/foo.js' has an unsupported extension, so skipping it.", + "File '/node_modules/foo/foo.js.ts' does not exist.", + "File '/node_modules/foo/foo.js.tsx' does not exist.", + "File '/node_modules/foo/foo.js.d.ts' does not exist.", + "File '/node_modules/foo/index.ts' does not exist.", + "File '/node_modules/foo/index.tsx' does not exist.", + "File '/node_modules/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/node_modules/foo.js' does not exist.", + "File '/node_modules/foo.jsx' does not exist.", + "Found 'package.json' at '/node_modules/foo/package.json'.", + "'package.json' does not have a 'types' or 'main' field.", + "File '/node_modules/foo/index.js' does not exist.", + "File '/node_modules/foo/index.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.types b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.types new file mode 100644 index 00000000000..11c9c72cc69 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.types @@ -0,0 +1,4 @@ +=== /a.ts === +import "foo"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.js b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.js new file mode 100644 index 00000000000..51d476338c0 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.js @@ -0,0 +1,18 @@ +//// [tests/cases/compiler/moduleResolutionWithExtensions_withAmbientPresent.ts] //// + +//// [index.js] +// Allowjs is false, but this should *not* warn about the unused 'index.js' + + +//// [declarations.d.ts] +declare module "js" { + export const x = 0; +} + +//// [a.ts] +/// +import { x } from "js"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.symbols b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.symbols new file mode 100644 index 00000000000..1259c83ccde --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.symbols @@ -0,0 +1,11 @@ +=== /a.ts === +/// +import { x } from "js"; +>x : Symbol(x, Decl(a.ts, 1, 8)) + +=== /declarations.d.ts === +declare module "js" { + export const x = 0; +>x : Symbol(x, Decl(declarations.d.ts, 1, 16)) +} + diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.trace.json new file mode 100644 index 00000000000..8d4217a92bd --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.trace.json @@ -0,0 +1,22 @@ +[ + "======== Resolving module 'js' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'js' from 'node_modules' folder.", + "File '/node_modules/js.ts' does not exist.", + "File '/node_modules/js.tsx' does not exist.", + "File '/node_modules/js.d.ts' does not exist.", + "File '/node_modules/js/package.json' does not exist.", + "File '/node_modules/js/index.ts' does not exist.", + "File '/node_modules/js/index.tsx' does not exist.", + "File '/node_modules/js/index.d.ts' does not exist.", + "File '/node_modules/@types/js.d.ts' does not exist.", + "File '/node_modules/@types/js/package.json' does not exist.", + "File '/node_modules/@types/js/index.d.ts' does not exist.", + "Loading module 'js' from 'node_modules' folder.", + "File '/node_modules/js.js' does not exist.", + "File '/node_modules/js.jsx' does not exist.", + "File '/node_modules/js/package.json' does not exist.", + "File '/node_modules/js/index.js' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/js/index.js', result '/node_modules/js/index.js'", + "======== Module name 'js' was successfully resolved to '/node_modules/js/index.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.types b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.types new file mode 100644 index 00000000000..1e5af4e7579 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithExtensions_withAmbientPresent.types @@ -0,0 +1,12 @@ +=== /a.ts === +/// +import { x } from "js"; +>x : 0 + +=== /declarations.d.ts === +declare module "js" { + export const x = 0; +>x : 0 +>0 : 0 +} + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks.errors.txt b/tests/baselines/reference/moduleResolutionWithSymlinks.errors.txt deleted file mode 100644 index b51933902a4..00000000000 --- a/tests/baselines/reference/moduleResolutionWithSymlinks.errors.txt +++ /dev/null @@ -1,21 +0,0 @@ -/src/library-b/index.ts(1,23): error TS2307: Cannot find module 'library-a'. - - -==== /src/app.ts (0 errors) ==== - import { MyClass } from "./library-a"; - import { MyClass2 } from "./library-b"; - - let x: MyClass; - let y: MyClass2; - x = y; - y = x; -==== /src/library-a/index.ts (0 errors) ==== - - export class MyClass{} - -==== /src/library-b/index.ts (1 errors) ==== - import {MyClass} from "library-a"; - ~~~~~~~~~~~ -!!! error TS2307: Cannot find module 'library-a'. - export { MyClass as MyClass2 } - \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks.js b/tests/baselines/reference/moduleResolutionWithSymlinks.js index 4123430045e..fbf97fa3ba0 100644 --- a/tests/baselines/reference/moduleResolutionWithSymlinks.js +++ b/tests/baselines/reference/moduleResolutionWithSymlinks.js @@ -1,8 +1,10 @@ //// [tests/cases/compiler/moduleResolutionWithSymlinks.ts] //// //// [index.ts] +// When symlinked files are in node_modules, they are resolved with realpath; +// so a linked file does not create a duplicate SourceFile of the real one. -export class MyClass{} +export class MyClass { private x: number; } //// [index.ts] import {MyClass} from "library-a"; @@ -15,9 +17,31 @@ import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; -y = x; +y = x; + +/* +# To reproduce in a real project: + +mkdir src; cd src +mkdir library-a +echo 'export class MyClass { private x: number; }' > library-a/index.ts + +mkdir library-b; cd library-b +echo 'import {MyClass} from "library-a"; export { MyClass as MyClass2 }' > index.ts +mkdir node_modules; cd node_modules + +ln -s ../../library-a library-a # Linux +# Windows: open command prompt as administrator and run: mklink /D library-a ..\..\library-a + +cd ../.. # back to src +echo 'import { MyClass } from "./library-a"; import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; y = x;' > app.ts +tsc app.ts # Should write to library-a/index.js, library-b/index.js, and app.js +*/ -//// [index.js] + +//// [/src/library-a/index.js] +// When symlinked files are in node_modules, they are resolved with realpath; +// so a linked file does not create a duplicate SourceFile of the real one. "use strict"; var MyClass = (function () { function MyClass() { @@ -25,13 +49,31 @@ var MyClass = (function () { return MyClass; }()); exports.MyClass = MyClass; -//// [index.js] +//// [/src/library-b/index.js] "use strict"; var library_a_1 = require("library-a"); exports.MyClass2 = library_a_1.MyClass; -//// [app.js] +//// [/src/app.js] "use strict"; var x; var y; x = y; y = x; +/* +# To reproduce in a real project: + +mkdir src; cd src +mkdir library-a +echo 'export class MyClass { private x: number; }' > library-a/index.ts + +mkdir library-b; cd library-b +echo 'import {MyClass} from "library-a"; export { MyClass as MyClass2 }' > index.ts +mkdir node_modules; cd node_modules + +ln -s ../../library-a library-a # Linux +# Windows: open command prompt as administrator and run: mklink /D library-a ..\..\library-a + +cd ../.. # back to src +echo 'import { MyClass } from "./library-a"; import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; y = x;' > app.ts +tsc app.ts # Should write to library-a/index.js, library-b/index.js, and app.js +*/ diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks.symbols b/tests/baselines/reference/moduleResolutionWithSymlinks.symbols new file mode 100644 index 00000000000..ede12be3555 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks.symbols @@ -0,0 +1,58 @@ +=== /src/app.ts === +import { MyClass } from "./library-a"; +>MyClass : Symbol(MyClass, Decl(app.ts, 0, 8)) + +import { MyClass2 } from "./library-b"; +>MyClass2 : Symbol(MyClass2, Decl(app.ts, 1, 8)) + +let x: MyClass; +>x : Symbol(x, Decl(app.ts, 3, 3)) +>MyClass : Symbol(MyClass, Decl(app.ts, 0, 8)) + +let y: MyClass2; +>y : Symbol(y, Decl(app.ts, 4, 3)) +>MyClass2 : Symbol(MyClass2, Decl(app.ts, 1, 8)) + +x = y; +>x : Symbol(x, Decl(app.ts, 3, 3)) +>y : Symbol(y, Decl(app.ts, 4, 3)) + +y = x; +>y : Symbol(y, Decl(app.ts, 4, 3)) +>x : Symbol(x, Decl(app.ts, 3, 3)) + +/* +# To reproduce in a real project: + +mkdir src; cd src +mkdir library-a +echo 'export class MyClass { private x: number; }' > library-a/index.ts + +mkdir library-b; cd library-b +echo 'import {MyClass} from "library-a"; export { MyClass as MyClass2 }' > index.ts +mkdir node_modules; cd node_modules + +ln -s ../../library-a library-a # Linux +# Windows: open command prompt as administrator and run: mklink /D library-a ..\..\library-a + +cd ../.. # back to src +echo 'import { MyClass } from "./library-a"; import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; y = x;' > app.ts +tsc app.ts # Should write to library-a/index.js, library-b/index.js, and app.js +*/ + +=== /src/library-a/index.ts === +// When symlinked files are in node_modules, they are resolved with realpath; +// so a linked file does not create a duplicate SourceFile of the real one. + +export class MyClass { private x: number; } +>MyClass : Symbol(MyClass, Decl(index.ts, 0, 0)) +>x : Symbol(MyClass.x, Decl(index.ts, 3, 22)) + +=== /src/library-b/index.ts === +import {MyClass} from "library-a"; +>MyClass : Symbol(MyClass, Decl(index.ts, 0, 8)) + +export { MyClass as MyClass2 } +>MyClass : Symbol(MyClass2, Decl(index.ts, 1, 8)) +>MyClass2 : Symbol(MyClass2, Decl(index.ts, 1, 8)) + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks.trace.json b/tests/baselines/reference/moduleResolutionWithSymlinks.trace.json index f3bfae4b173..bd23ccdb366 100644 --- a/tests/baselines/reference/moduleResolutionWithSymlinks.trace.json +++ b/tests/baselines/reference/moduleResolutionWithSymlinks.trace.json @@ -7,7 +7,6 @@ "File '/src/library-a.d.ts' does not exist.", "File '/src/library-a/package.json' does not exist.", "File '/src/library-a/index.ts' exist - use it as a name resolution result.", - "Resolving real path for '/src/library-a/index.ts', result '/src/library-a/index.ts'", "======== Module name './library-a' was successfully resolved to '/src/library-a/index.ts'. ========", "======== Resolving module './library-b' from '/src/app.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -17,7 +16,6 @@ "File '/src/library-b.d.ts' does not exist.", "File '/src/library-b/package.json' does not exist.", "File '/src/library-b/index.ts' exist - use it as a name resolution result.", - "Resolving real path for '/src/library-b/index.ts', result '/src/library-b/index.ts'", "======== Module name './library-b' was successfully resolved to '/src/library-b/index.ts'. ========", "======== Resolving module 'library-a' from '/src/library-b/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -26,43 +24,7 @@ "File '/src/library-b/node_modules/library-a.tsx' does not exist.", "File '/src/library-b/node_modules/library-a.d.ts' does not exist.", "File '/src/library-b/node_modules/library-a/package.json' does not exist.", - "File '/src/library-b/node_modules/library-a/index.ts' does not exist.", - "File '/src/library-b/node_modules/library-a/index.tsx' does not exist.", - "File '/src/library-b/node_modules/library-a/index.d.ts' does not exist.", - "File '/src/library-b/node_modules/@types/library-a.ts' does not exist.", - "File '/src/library-b/node_modules/@types/library-a.tsx' does not exist.", - "File '/src/library-b/node_modules/@types/library-a.d.ts' does not exist.", - "File '/src/library-b/node_modules/@types/library-a/package.json' does not exist.", - "File '/src/library-b/node_modules/@types/library-a/index.ts' does not exist.", - "File '/src/library-b/node_modules/@types/library-a/index.tsx' does not exist.", - "File '/src/library-b/node_modules/@types/library-a/index.d.ts' does not exist.", - "File '/src/node_modules/library-a.ts' does not exist.", - "File '/src/node_modules/library-a.tsx' does not exist.", - "File '/src/node_modules/library-a.d.ts' does not exist.", - "File '/src/node_modules/library-a/package.json' does not exist.", - "File '/src/node_modules/library-a/index.ts' does not exist.", - "File '/src/node_modules/library-a/index.tsx' does not exist.", - "File '/src/node_modules/library-a/index.d.ts' does not exist.", - "File '/src/node_modules/@types/library-a.ts' does not exist.", - "File '/src/node_modules/@types/library-a.tsx' does not exist.", - "File '/src/node_modules/@types/library-a.d.ts' does not exist.", - "File '/src/node_modules/@types/library-a/package.json' does not exist.", - "File '/src/node_modules/@types/library-a/index.ts' does not exist.", - "File '/src/node_modules/@types/library-a/index.tsx' does not exist.", - "File '/src/node_modules/@types/library-a/index.d.ts' does not exist.", - "File '/node_modules/library-a.ts' does not exist.", - "File '/node_modules/library-a.tsx' does not exist.", - "File '/node_modules/library-a.d.ts' does not exist.", - "File '/node_modules/library-a/package.json' does not exist.", - "File '/node_modules/library-a/index.ts' does not exist.", - "File '/node_modules/library-a/index.tsx' does not exist.", - "File '/node_modules/library-a/index.d.ts' does not exist.", - "File '/node_modules/@types/library-a.ts' does not exist.", - "File '/node_modules/@types/library-a.tsx' does not exist.", - "File '/node_modules/@types/library-a.d.ts' does not exist.", - "File '/node_modules/@types/library-a/package.json' does not exist.", - "File '/node_modules/@types/library-a/index.ts' does not exist.", - "File '/node_modules/@types/library-a/index.tsx' does not exist.", - "File '/node_modules/@types/library-a/index.d.ts' does not exist.", - "======== Module name 'library-a' was not resolved. ========" + "File '/src/library-b/node_modules/library-a/index.ts' exist - use it as a name resolution result.", + "Resolving real path for '/src/library-b/node_modules/library-a/index.ts', result '/src/library-a/index.ts'", + "======== Module name 'library-a' was successfully resolved to '/src/library-a/index.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks.types b/tests/baselines/reference/moduleResolutionWithSymlinks.types new file mode 100644 index 00000000000..04781dcac0f --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks.types @@ -0,0 +1,60 @@ +=== /src/app.ts === +import { MyClass } from "./library-a"; +>MyClass : typeof MyClass + +import { MyClass2 } from "./library-b"; +>MyClass2 : typeof MyClass + +let x: MyClass; +>x : MyClass +>MyClass : MyClass + +let y: MyClass2; +>y : MyClass +>MyClass2 : MyClass + +x = y; +>x = y : MyClass +>x : MyClass +>y : MyClass + +y = x; +>y = x : MyClass +>y : MyClass +>x : MyClass + +/* +# To reproduce in a real project: + +mkdir src; cd src +mkdir library-a +echo 'export class MyClass { private x: number; }' > library-a/index.ts + +mkdir library-b; cd library-b +echo 'import {MyClass} from "library-a"; export { MyClass as MyClass2 }' > index.ts +mkdir node_modules; cd node_modules + +ln -s ../../library-a library-a # Linux +# Windows: open command prompt as administrator and run: mklink /D library-a ..\..\library-a + +cd ../.. # back to src +echo 'import { MyClass } from "./library-a"; import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; y = x;' > app.ts +tsc app.ts # Should write to library-a/index.js, library-b/index.js, and app.js +*/ + +=== /src/library-a/index.ts === +// When symlinked files are in node_modules, they are resolved with realpath; +// so a linked file does not create a duplicate SourceFile of the real one. + +export class MyClass { private x: number; } +>MyClass : MyClass +>x : number + +=== /src/library-b/index.ts === +import {MyClass} from "library-a"; +>MyClass : typeof MyClass + +export { MyClass as MyClass2 } +>MyClass : typeof MyClass +>MyClass2 : typeof MyClass + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.js b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.js new file mode 100644 index 00000000000..a927a496a96 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.js @@ -0,0 +1,32 @@ +//// [tests/cases/compiler/moduleResolutionWithSymlinks_notInNodeModules.ts] //// + +//// [abc.ts] +// When symlinked files are not in node_modules, realpath is not used. +// A symlink file acts like the real thing. So, 2 symlinks act like 2 different files. +// See GH#10364. + +export const x = 0; + +//// [app.ts] +import { x } from "./shared/abc"; +import { x as x2 } from "./shared2/abc"; +x + x2; + + +//// [/src/bin/shared/abc.js] +// When symlinked files are not in node_modules, realpath is not used. +// A symlink file acts like the real thing. So, 2 symlinks act like 2 different files. +// See GH#10364. +"use strict"; +exports.x = 0; +//// [/src/bin/shared2/abc.js] +// When symlinked files are not in node_modules, realpath is not used. +// A symlink file acts like the real thing. So, 2 symlinks act like 2 different files. +// See GH#10364. +"use strict"; +exports.x = 0; +//// [/src/bin/app.js] +"use strict"; +var abc_1 = require("./shared/abc"); +var abc_2 = require("./shared2/abc"); +abc_1.x + abc_2.x; diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.symbols b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.symbols new file mode 100644 index 00000000000..b496e1b76ac --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.symbols @@ -0,0 +1,12 @@ +=== /src/app.ts === +import { x } from "./shared/abc"; +>x : Symbol(x, Decl(app.ts, 0, 8)) + +import { x as x2 } from "./shared2/abc"; +>x : Symbol(x2, Decl(app.ts, 1, 8)) +>x2 : Symbol(x2, Decl(app.ts, 1, 8)) + +x + x2; +>x : Symbol(x, Decl(app.ts, 0, 8)) +>x2 : Symbol(x2, Decl(app.ts, 1, 8)) + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.trace.json b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.trace.json new file mode 100644 index 00000000000..c2f0c04d07f --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.trace.json @@ -0,0 +1,12 @@ +[ + "======== Resolving module './shared/abc' from '/src/app.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/src/shared/abc'.", + "File '/src/shared/abc.ts' exist - use it as a name resolution result.", + "======== Module name './shared/abc' was successfully resolved to '/src/shared/abc.ts'. ========", + "======== Resolving module './shared2/abc' from '/src/app.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/src/shared2/abc'.", + "File '/src/shared2/abc.ts' exist - use it as a name resolution result.", + "======== Module name './shared2/abc' was successfully resolved to '/src/shared2/abc.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.types b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.types new file mode 100644 index 00000000000..0d7fe290334 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_notInNodeModules.types @@ -0,0 +1,13 @@ +=== /src/app.ts === +import { x } from "./shared/abc"; +>x : 0 + +import { x as x2 } from "./shared2/abc"; +>x : 0 +>x2 : 0 + +x + x2; +>x + x2 : number +>x : 0 +>x2 : 0 + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.js b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.js new file mode 100644 index 00000000000..d04dfe0d8a8 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.js @@ -0,0 +1,22 @@ +//// [tests/cases/compiler/moduleResolutionWithSymlinks_referenceTypes.ts] //// + +//// [index.d.ts] +// Symlinks are always resolved for type reference directives. +// NOTE: This test would still compile without errors even if they were not, +// because `processTypeReferenceDirective` also checks for textual equivalence of file contents. +// But the `moduleResolutionWithSymlinks_referenceTypes.trace.json` shows the difference. + + +declare class MyClass { private x: number; } + +//// [index.d.ts] +/// + +//// [app.ts] +/// +/// + + +//// [/app.js] +/// +/// diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.symbols b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.symbols new file mode 100644 index 00000000000..46806e5313f --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.symbols @@ -0,0 +1,19 @@ +=== /app.ts === +/// +No type information for this code./// +No type information for this code. +No type information for this code.=== /node_modules/@types/library-a/index.d.ts === +// Symlinks are always resolved for type reference directives. +// NOTE: This test would still compile without errors even if they were not, +// because `processTypeReferenceDirective` also checks for textual equivalence of file contents. +// But the `moduleResolutionWithSymlinks_referenceTypes.trace.json` shows the difference. + + +declare class MyClass { private x: number; } +>MyClass : Symbol(MyClass, Decl(index.d.ts, 0, 0)) +>x : Symbol(MyClass.x, Decl(index.d.ts, 6, 23)) + +=== /node_modules/@types/library-b/index.d.ts === +/// +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.trace.json b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.trace.json new file mode 100644 index 00000000000..3e0609ee325 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.trace.json @@ -0,0 +1,35 @@ +[ + "======== Resolving type reference directive 'library-a', containing file '/app.ts', root directory ''. ========", + "Root directory cannot be determined, skipping primary search paths.", + "Looking up in 'node_modules' folder, initial location '/'", + "File '/node_modules/library-a.d.ts' does not exist.", + "File '/node_modules/library-a/package.json' does not exist.", + "File '/node_modules/library-a/index.d.ts' does not exist.", + "File '/node_modules/@types/library-a.d.ts' does not exist.", + "File '/node_modules/@types/library-a/package.json' does not exist.", + "File '/node_modules/@types/library-a/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/library-a/index.d.ts', result '/node_modules/@types/library-a/index.d.ts'", + "======== Type reference directive 'library-a' was successfully resolved to '/node_modules/@types/library-a/index.d.ts', primary: false. ========", + "======== Resolving type reference directive 'library-b', containing file '/app.ts', root directory ''. ========", + "Root directory cannot be determined, skipping primary search paths.", + "Looking up in 'node_modules' folder, initial location '/'", + "File '/node_modules/library-b.d.ts' does not exist.", + "File '/node_modules/library-b/package.json' does not exist.", + "File '/node_modules/library-b/index.d.ts' does not exist.", + "File '/node_modules/@types/library-b.d.ts' does not exist.", + "File '/node_modules/@types/library-b/package.json' does not exist.", + "File '/node_modules/@types/library-b/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/library-b/index.d.ts', result '/node_modules/@types/library-b/index.d.ts'", + "======== Type reference directive 'library-b' was successfully resolved to '/node_modules/@types/library-b/index.d.ts', primary: false. ========", + "======== Resolving type reference directive 'library-a', containing file '/node_modules/@types/library-b/index.d.ts', root directory ''. ========", + "Root directory cannot be determined, skipping primary search paths.", + "Looking up in 'node_modules' folder, initial location '/node_modules/@types/library-b'", + "File '/node_modules/@types/library-b/node_modules/library-a.d.ts' does not exist.", + "File '/node_modules/@types/library-b/node_modules/library-a/package.json' does not exist.", + "File '/node_modules/@types/library-b/node_modules/library-a/index.d.ts' does not exist.", + "File '/node_modules/@types/library-b/node_modules/@types/library-a.d.ts' does not exist.", + "File '/node_modules/@types/library-b/node_modules/@types/library-a/package.json' does not exist.", + "File '/node_modules/@types/library-b/node_modules/@types/library-a/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/library-b/node_modules/@types/library-a/index.d.ts', result '/node_modules/@types/library-a/index.d.ts'", + "======== Type reference directive 'library-a' was successfully resolved to '/node_modules/@types/library-a/index.d.ts', primary: false. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.types b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.types new file mode 100644 index 00000000000..2094265709f --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_referenceTypes.types @@ -0,0 +1,19 @@ +=== /app.ts === +/// +No type information for this code./// +No type information for this code. +No type information for this code.=== /node_modules/@types/library-a/index.d.ts === +// Symlinks are always resolved for type reference directives. +// NOTE: This test would still compile without errors even if they were not, +// because `processTypeReferenceDirective` also checks for textual equivalence of file contents. +// But the `moduleResolutionWithSymlinks_referenceTypes.trace.json` shows the difference. + + +declare class MyClass { private x: number; } +>MyClass : MyClass +>x : number + +=== /node_modules/@types/library-b/index.d.ts === +/// +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.js b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.js new file mode 100644 index 00000000000..312bcf4c174 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.js @@ -0,0 +1,40 @@ +//// [tests/cases/compiler/moduleResolutionWithSymlinks_withOutDir.ts] //// + +//// [index.ts] +// Same as moduleResolutionWithSymlinks.ts, but with outDir + +export class MyClass { private x: number; } + +//// [index.ts] +import {MyClass} from "library-a"; +export { MyClass as MyClass2 } + +//// [app.ts] +import { MyClass } from "./library-a"; +import { MyClass2 } from "./library-b"; + +let x: MyClass; +let y: MyClass2; +x = y; +y = x; + + +//// [/src/bin/library-a/index.js] +// Same as moduleResolutionWithSymlinks.ts, but with outDir +"use strict"; +var MyClass = (function () { + function MyClass() { + } + return MyClass; +}()); +exports.MyClass = MyClass; +//// [/src/bin/library-b/index.js] +"use strict"; +var library_a_1 = require("library-a"); +exports.MyClass2 = library_a_1.MyClass; +//// [/src/bin/app.js] +"use strict"; +var x; +var y; +x = y; +y = x; diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.symbols b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.symbols new file mode 100644 index 00000000000..3e7598815de --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.symbols @@ -0,0 +1,38 @@ +=== /src/app.ts === +import { MyClass } from "./library-a"; +>MyClass : Symbol(MyClass, Decl(app.ts, 0, 8)) + +import { MyClass2 } from "./library-b"; +>MyClass2 : Symbol(MyClass2, Decl(app.ts, 1, 8)) + +let x: MyClass; +>x : Symbol(x, Decl(app.ts, 3, 3)) +>MyClass : Symbol(MyClass, Decl(app.ts, 0, 8)) + +let y: MyClass2; +>y : Symbol(y, Decl(app.ts, 4, 3)) +>MyClass2 : Symbol(MyClass2, Decl(app.ts, 1, 8)) + +x = y; +>x : Symbol(x, Decl(app.ts, 3, 3)) +>y : Symbol(y, Decl(app.ts, 4, 3)) + +y = x; +>y : Symbol(y, Decl(app.ts, 4, 3)) +>x : Symbol(x, Decl(app.ts, 3, 3)) + +=== /src/library-a/index.ts === +// Same as moduleResolutionWithSymlinks.ts, but with outDir + +export class MyClass { private x: number; } +>MyClass : Symbol(MyClass, Decl(index.ts, 0, 0)) +>x : Symbol(MyClass.x, Decl(index.ts, 2, 22)) + +=== /src/library-b/index.ts === +import {MyClass} from "library-a"; +>MyClass : Symbol(MyClass, Decl(index.ts, 0, 8)) + +export { MyClass as MyClass2 } +>MyClass : Symbol(MyClass2, Decl(index.ts, 1, 8)) +>MyClass2 : Symbol(MyClass2, Decl(index.ts, 1, 8)) + diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.trace.json b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.trace.json new file mode 100644 index 00000000000..bd23ccdb366 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.trace.json @@ -0,0 +1,30 @@ +[ + "======== Resolving module './library-a' from '/src/app.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/src/library-a'.", + "File '/src/library-a.ts' does not exist.", + "File '/src/library-a.tsx' does not exist.", + "File '/src/library-a.d.ts' does not exist.", + "File '/src/library-a/package.json' does not exist.", + "File '/src/library-a/index.ts' exist - use it as a name resolution result.", + "======== Module name './library-a' was successfully resolved to '/src/library-a/index.ts'. ========", + "======== Resolving module './library-b' from '/src/app.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location '/src/library-b'.", + "File '/src/library-b.ts' does not exist.", + "File '/src/library-b.tsx' does not exist.", + "File '/src/library-b.d.ts' does not exist.", + "File '/src/library-b/package.json' does not exist.", + "File '/src/library-b/index.ts' exist - use it as a name resolution result.", + "======== Module name './library-b' was successfully resolved to '/src/library-b/index.ts'. ========", + "======== Resolving module 'library-a' from '/src/library-b/index.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'library-a' from 'node_modules' folder.", + "File '/src/library-b/node_modules/library-a.ts' does not exist.", + "File '/src/library-b/node_modules/library-a.tsx' does not exist.", + "File '/src/library-b/node_modules/library-a.d.ts' does not exist.", + "File '/src/library-b/node_modules/library-a/package.json' does not exist.", + "File '/src/library-b/node_modules/library-a/index.ts' exist - use it as a name resolution result.", + "Resolving real path for '/src/library-b/node_modules/library-a/index.ts', result '/src/library-a/index.ts'", + "======== Module name 'library-a' was successfully resolved to '/src/library-a/index.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.types b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.types new file mode 100644 index 00000000000..35fa2167920 --- /dev/null +++ b/tests/baselines/reference/moduleResolutionWithSymlinks_withOutDir.types @@ -0,0 +1,40 @@ +=== /src/app.ts === +import { MyClass } from "./library-a"; +>MyClass : typeof MyClass + +import { MyClass2 } from "./library-b"; +>MyClass2 : typeof MyClass + +let x: MyClass; +>x : MyClass +>MyClass : MyClass + +let y: MyClass2; +>y : MyClass +>MyClass2 : MyClass + +x = y; +>x = y : MyClass +>x : MyClass +>y : MyClass + +y = x; +>y = x : MyClass +>y : MyClass +>x : MyClass + +=== /src/library-a/index.ts === +// Same as moduleResolutionWithSymlinks.ts, but with outDir + +export class MyClass { private x: number; } +>MyClass : MyClass +>x : number + +=== /src/library-b/index.ts === +import {MyClass} from "library-a"; +>MyClass : typeof MyClass + +export { MyClass as MyClass2 } +>MyClass : typeof MyClass +>MyClass2 : typeof MyClass + diff --git a/tests/baselines/reference/moduleSameValueDuplicateExportedBindings2.js b/tests/baselines/reference/moduleSameValueDuplicateExportedBindings2.js index 99a09af149a..208e90c69d8 100644 --- a/tests/baselines/reference/moduleSameValueDuplicateExportedBindings2.js +++ b/tests/baselines/reference/moduleSameValueDuplicateExportedBindings2.js @@ -15,11 +15,11 @@ export enum Animals { //// [c.js] "use strict"; +var Animals; (function (Animals) { Animals[Animals["Cat"] = 0] = "Cat"; Animals[Animals["Dog"] = 1] = "Dog"; -})(exports.Animals || (exports.Animals = {})); -var Animals = exports.Animals; +})(Animals = exports.Animals || (exports.Animals = {})); ; //// [b.js] "use strict"; diff --git a/tests/baselines/reference/moduleVisibilityTest1.js b/tests/baselines/reference/moduleVisibilityTest1.js index 52afcf169d9..537ec23b393 100644 --- a/tests/baselines/reference/moduleVisibilityTest1.js +++ b/tests/baselines/reference/moduleVisibilityTest1.js @@ -86,12 +86,12 @@ var M; function someExportedInnerFunc() { return -2; } InnerMod.someExportedInnerFunc = someExportedInnerFunc; })(InnerMod = M.InnerMod || (M.InnerMod = {})); + var E; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; - })(M.E || (M.E = {})); - var E = M.E; + })(E = M.E || (M.E = {})); M.x = 5; var y = M.x + M.x; var B = (function () { diff --git a/tests/baselines/reference/moduleWithStatementsOfEveryKind.js b/tests/baselines/reference/moduleWithStatementsOfEveryKind.js index 1558ef742ab..4243c9849cf 100644 --- a/tests/baselines/reference/moduleWithStatementsOfEveryKind.js +++ b/tests/baselines/reference/moduleWithStatementsOfEveryKind.js @@ -151,11 +151,11 @@ var Y; return A; }()); })(Module = Y.Module || (Y.Module = {})); + var Color; (function (Color) { Color[Color["Blue"] = 0] = "Blue"; Color[Color["Red"] = 1] = "Red"; - })(Y.Color || (Y.Color = {})); - var Color = Y.Color; + })(Color = Y.Color || (Y.Color = {})); Y.x = 12; function F(s) { return 2; diff --git a/tests/baselines/reference/nameCollision.js b/tests/baselines/reference/nameCollision.js index e51bd5e7c69..bb4f4a092f9 100644 --- a/tests/baselines/reference/nameCollision.js +++ b/tests/baselines/reference/nameCollision.js @@ -85,11 +85,11 @@ var Y; (function (Y_2) { var Y; (function (Y_3) { + var Y; (function (Y) { Y[Y["Red"] = 0] = "Red"; Y[Y["Blue"] = 1] = "Blue"; - })(Y_3.Y || (Y_3.Y = {})); - var Y = Y_3.Y; + })(Y = Y_3.Y || (Y_3.Y = {})); })(Y = Y_2.Y || (Y_2.Y = {})); })(Y || (Y = {})); // no collision, since interface doesn't diff --git a/tests/baselines/reference/narrowedConstInMethod.js b/tests/baselines/reference/narrowedConstInMethod.js new file mode 100644 index 00000000000..f4cdc3def91 --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.js @@ -0,0 +1,40 @@ +//// [narrowedConstInMethod.ts] + +function f() { + const x: string | null = {}; + if (x !== null) { + return { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +function f2() { + const x: string | null = {}; + if (x !== null) { + return class { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +//// [narrowedConstInMethod.js] +function f() { + var x = {}; + if (x !== null) { + return { + bar: function () { return x.length; } // Error: possibly null x + }; + } +} +function f2() { + var x = {}; + if (x !== null) { + return (function () { + function class_1() { + } + class_1.prototype.bar = function () { return x.length; }; // Error: possibly null x + return class_1; + }()); + } +} diff --git a/tests/baselines/reference/narrowedConstInMethod.symbols b/tests/baselines/reference/narrowedConstInMethod.symbols new file mode 100644 index 00000000000..1fd05dcea5e --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.symbols @@ -0,0 +1,41 @@ +=== tests/cases/compiler/narrowedConstInMethod.ts === + +function f() { +>f : Symbol(f, Decl(narrowedConstInMethod.ts, 0, 0)) + + const x: string | null = {}; +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) + + if (x !== null) { +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) + + return { + bar() { return x.length; } // Error: possibly null x +>bar : Symbol(bar, Decl(narrowedConstInMethod.ts, 4, 16)) +>x.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + }; + } +} + +function f2() { +>f2 : Symbol(f2, Decl(narrowedConstInMethod.ts, 8, 1)) + + const x: string | null = {}; +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) + + if (x !== null) { +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) + + return class { + bar() { return x.length; } // Error: possibly null x +>bar : Symbol((Anonymous class).bar, Decl(narrowedConstInMethod.ts, 13, 22)) +>x.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + }; + } +} diff --git a/tests/baselines/reference/narrowedConstInMethod.types b/tests/baselines/reference/narrowedConstInMethod.types new file mode 100644 index 00000000000..a73f2edfccb --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.types @@ -0,0 +1,55 @@ +=== tests/cases/compiler/narrowedConstInMethod.ts === + +function f() { +>f : () => { bar(): number; } | undefined + + const x: string | null = {}; +>x : string | null +>null : null +>{} : any +>{} : {} + + if (x !== null) { +>x !== null : boolean +>x : string | null +>null : null + + return { +>{ bar() { return x.length; } // Error: possibly null x } : { bar(): number; } + + bar() { return x.length; } // Error: possibly null x +>bar : () => number +>x.length : number +>x : string +>length : number + + }; + } +} + +function f2() { +>f2 : () => typeof (Anonymous class) | undefined + + const x: string | null = {}; +>x : string | null +>null : null +>{} : any +>{} : {} + + if (x !== null) { +>x !== null : boolean +>x : string | null +>null : null + + return class { +>class { bar() { return x.length; } // Error: possibly null x } : typeof (Anonymous class) + + bar() { return x.length; } // Error: possibly null x +>bar : () => number +>x.length : number +>x : string +>length : number + + }; + } +} diff --git a/tests/baselines/reference/nestedBlockScopedBindings3.types b/tests/baselines/reference/nestedBlockScopedBindings3.types index ca13759bac4..0de8123861d 100644 --- a/tests/baselines/reference/nestedBlockScopedBindings3.types +++ b/tests/baselines/reference/nestedBlockScopedBindings3.types @@ -31,7 +31,7 @@ function a1() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : undefined +>x : any >1 : 1 () => x; @@ -53,24 +53,24 @@ function a2() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 } for (let x;;) { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 } } @@ -82,14 +82,14 @@ function a3() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 } switch (1) { @@ -111,14 +111,14 @@ function a4() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 () => x; @@ -145,14 +145,14 @@ function a5() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 () => x; diff --git a/tests/baselines/reference/nestedBlockScopedBindings4.types b/tests/baselines/reference/nestedBlockScopedBindings4.types index 9e0147f25f7..65b5d73db9d 100644 --- a/tests/baselines/reference/nestedBlockScopedBindings4.types +++ b/tests/baselines/reference/nestedBlockScopedBindings4.types @@ -5,24 +5,24 @@ function a0() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 } for (let x;;) { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 } } @@ -33,14 +33,14 @@ function a1() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 () => x; @@ -51,10 +51,10 @@ function a1() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 } } @@ -65,24 +65,24 @@ function a2() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 } for (let x;;) { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 () => x; @@ -98,14 +98,14 @@ function a3() { for (let x; x < 1;) { >x : any >x < 1 : boolean ->x : number +>x : any >1 : 1 x = x + 1; ->x = x + 1 : number +>x = x + 1 : any +>x : any +>x + 1 : any >x : any ->x + 1 : number ->x : number >1 : 1 () => x; @@ -116,10 +116,10 @@ function a3() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 () => x; diff --git a/tests/baselines/reference/nestedBlockScopedBindings6.types b/tests/baselines/reference/nestedBlockScopedBindings6.types index bf38f46d508..865dea31e37 100644 --- a/tests/baselines/reference/nestedBlockScopedBindings6.types +++ b/tests/baselines/reference/nestedBlockScopedBindings6.types @@ -18,10 +18,10 @@ function a0() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 } } @@ -49,10 +49,10 @@ function a1() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 } } @@ -76,10 +76,10 @@ function a2() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 () => x; @@ -111,10 +111,10 @@ function a3() { >x : any x = x + 2; ->x = x + 2 : number +>x = x + 2 : any +>x : any +>x + 2 : any >x : any ->x + 2 : number ->x : number >2 : 2 () => x; diff --git a/tests/baselines/reference/nestedClassDeclaration.js b/tests/baselines/reference/nestedClassDeclaration.js index 04e2f6348ef..cc300ec75a3 100644 --- a/tests/baselines/reference/nestedClassDeclaration.js +++ b/tests/baselines/reference/nestedClassDeclaration.js @@ -38,5 +38,5 @@ function foo() { }()); } var x = { - class: C4 + "class": C4 }, _a = void 0; diff --git a/tests/baselines/reference/nestedFreshLiteral.errors.txt b/tests/baselines/reference/nestedFreshLiteral.errors.txt new file mode 100644 index 00000000000..6aff94ac0a6 --- /dev/null +++ b/tests/baselines/reference/nestedFreshLiteral.errors.txt @@ -0,0 +1,31 @@ +tests/cases/compiler/nestedFreshLiteral.ts(12,21): error TS2322: Type '{ nested: { prop: { colour: string; }; }; }' is not assignable to type 'NestedCSSProps'. + Types of property 'nested' are incompatible. + Type '{ prop: { colour: string; }; }' is not assignable to type 'NestedSelector | undefined'. + Type '{ prop: { colour: string; }; }' is not assignable to type 'NestedSelector'. + Types of property 'prop' are incompatible. + Type '{ colour: string; }' is not assignable to type 'CSSProps'. + Object literal may only specify known properties, and 'colour' does not exist in type 'CSSProps'. + + +==== tests/cases/compiler/nestedFreshLiteral.ts (1 errors) ==== + interface CSSProps { + color?: string + } + interface NestedCSSProps { + nested?: NestedSelector + } + interface NestedSelector { + prop: CSSProps; + } + + let stylen: NestedCSSProps = { + nested: { prop: { colour: 'red' } } + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ nested: { prop: { colour: string; }; }; }' is not assignable to type 'NestedCSSProps'. +!!! error TS2322: Types of property 'nested' are incompatible. +!!! error TS2322: Type '{ prop: { colour: string; }; }' is not assignable to type 'NestedSelector | undefined'. +!!! error TS2322: Type '{ prop: { colour: string; }; }' is not assignable to type 'NestedSelector'. +!!! error TS2322: Types of property 'prop' are incompatible. +!!! error TS2322: Type '{ colour: string; }' is not assignable to type 'CSSProps'. +!!! error TS2322: Object literal may only specify known properties, and 'colour' does not exist in type 'CSSProps'. + } \ No newline at end of file diff --git a/tests/baselines/reference/nestedFreshLiteral.js b/tests/baselines/reference/nestedFreshLiteral.js new file mode 100644 index 00000000000..36d4743deae --- /dev/null +++ b/tests/baselines/reference/nestedFreshLiteral.js @@ -0,0 +1,19 @@ +//// [nestedFreshLiteral.ts] +interface CSSProps { + color?: string +} +interface NestedCSSProps { + nested?: NestedSelector +} +interface NestedSelector { + prop: CSSProps; +} + +let stylen: NestedCSSProps = { + nested: { prop: { colour: 'red' } } +} + +//// [nestedFreshLiteral.js] +var stylen = { + nested: { prop: { colour: 'red' } } +}; diff --git a/tests/baselines/reference/nestedLoops.js b/tests/baselines/reference/nestedLoops.js new file mode 100644 index 00000000000..c29311c38de --- /dev/null +++ b/tests/baselines/reference/nestedLoops.js @@ -0,0 +1,47 @@ +//// [nestedLoops.ts] +export class Test { + constructor() { + + let outerArray: Array = [1, 2, 3]; + let innerArray: Array = [1, 2, 3]; + + for (let outer of outerArray) + for (let inner of innerArray) { + this.aFunction((newValue, oldValue) => { + let x = outer + inner + newValue; + }); + } + } + + public aFunction(func: (newValue: any, oldValue: any) => void): void { + } +} + +//// [nestedLoops.js] +"use strict"; +var Test = (function () { + function Test() { + var outerArray = [1, 2, 3]; + var innerArray = [1, 2, 3]; + var _loop_1 = function (outer) { + var _loop_2 = function (inner) { + this_1.aFunction(function (newValue, oldValue) { + var x = outer + inner + newValue; + }); + }; + for (var _i = 0, innerArray_1 = innerArray; _i < innerArray_1.length; _i++) { + var inner = innerArray_1[_i]; + _loop_2(inner); + } + }; + var this_1 = this; + for (var _i = 0, outerArray_1 = outerArray; _i < outerArray_1.length; _i++) { + var outer = outerArray_1[_i]; + _loop_1(outer); + } + } + Test.prototype.aFunction = function (func) { + }; + return Test; +}()); +exports.Test = Test; diff --git a/tests/baselines/reference/nestedLoops.symbols b/tests/baselines/reference/nestedLoops.symbols new file mode 100644 index 00000000000..0ab1c4651a6 --- /dev/null +++ b/tests/baselines/reference/nestedLoops.symbols @@ -0,0 +1,46 @@ +=== tests/cases/compiler/nestedLoops.ts === +export class Test { +>Test : Symbol(Test, Decl(nestedLoops.ts, 0, 0)) + + constructor() { + + let outerArray: Array = [1, 2, 3]; +>outerArray : Symbol(outerArray, Decl(nestedLoops.ts, 3, 11)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + + let innerArray: Array = [1, 2, 3]; +>innerArray : Symbol(innerArray, Decl(nestedLoops.ts, 4, 11)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + + for (let outer of outerArray) +>outer : Symbol(outer, Decl(nestedLoops.ts, 6, 16)) +>outerArray : Symbol(outerArray, Decl(nestedLoops.ts, 3, 11)) + + for (let inner of innerArray) { +>inner : Symbol(inner, Decl(nestedLoops.ts, 7, 20)) +>innerArray : Symbol(innerArray, Decl(nestedLoops.ts, 4, 11)) + + this.aFunction((newValue, oldValue) => { +>this.aFunction : Symbol(Test.aFunction, Decl(nestedLoops.ts, 12, 5)) +>this : Symbol(Test, Decl(nestedLoops.ts, 0, 0)) +>aFunction : Symbol(Test.aFunction, Decl(nestedLoops.ts, 12, 5)) +>newValue : Symbol(newValue, Decl(nestedLoops.ts, 8, 32)) +>oldValue : Symbol(oldValue, Decl(nestedLoops.ts, 8, 41)) + + let x = outer + inner + newValue; +>x : Symbol(x, Decl(nestedLoops.ts, 9, 23)) +>outer : Symbol(outer, Decl(nestedLoops.ts, 6, 16)) +>inner : Symbol(inner, Decl(nestedLoops.ts, 7, 20)) +>newValue : Symbol(newValue, Decl(nestedLoops.ts, 8, 32)) + + }); + } + } + + public aFunction(func: (newValue: any, oldValue: any) => void): void { +>aFunction : Symbol(Test.aFunction, Decl(nestedLoops.ts, 12, 5)) +>func : Symbol(func, Decl(nestedLoops.ts, 14, 21)) +>newValue : Symbol(newValue, Decl(nestedLoops.ts, 14, 28)) +>oldValue : Symbol(oldValue, Decl(nestedLoops.ts, 14, 42)) + } +} diff --git a/tests/baselines/reference/nestedLoops.types b/tests/baselines/reference/nestedLoops.types new file mode 100644 index 00000000000..f4a743f4aaf --- /dev/null +++ b/tests/baselines/reference/nestedLoops.types @@ -0,0 +1,58 @@ +=== tests/cases/compiler/nestedLoops.ts === +export class Test { +>Test : Test + + constructor() { + + let outerArray: Array = [1, 2, 3]; +>outerArray : number[] +>Array : T[] +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + + let innerArray: Array = [1, 2, 3]; +>innerArray : number[] +>Array : T[] +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + + for (let outer of outerArray) +>outer : number +>outerArray : number[] + + for (let inner of innerArray) { +>inner : number +>innerArray : number[] + + this.aFunction((newValue, oldValue) => { +>this.aFunction((newValue, oldValue) => { let x = outer + inner + newValue; }) : void +>this.aFunction : (func: (newValue: any, oldValue: any) => void) => void +>this : this +>aFunction : (func: (newValue: any, oldValue: any) => void) => void +>(newValue, oldValue) => { let x = outer + inner + newValue; } : (newValue: any, oldValue: any) => void +>newValue : any +>oldValue : any + + let x = outer + inner + newValue; +>x : any +>outer + inner + newValue : any +>outer + inner : number +>outer : number +>inner : number +>newValue : any + + }); + } + } + + public aFunction(func: (newValue: any, oldValue: any) => void): void { +>aFunction : (func: (newValue: any, oldValue: any) => void) => void +>func : (newValue: any, oldValue: any) => void +>newValue : any +>oldValue : any + } +} diff --git a/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.js b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.js new file mode 100644 index 00000000000..8525352d415 --- /dev/null +++ b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.js @@ -0,0 +1,31 @@ +//// [newLexicalEnvironmentForConvertedLoop.ts] +function baz(x: any) { + return [[x, x]]; +} + +function foo(set: any) { + for (const [value, i] of baz(set.values)) { + const bar: any = []; + (() => bar); + + set.values.push(...[]); + } +}; + +//// [newLexicalEnvironmentForConvertedLoop.js] +function baz(x) { + return [[x, x]]; +} +function foo(set) { + var _loop_1 = function (value, i) { + var bar = []; + (function () { return bar; }); + (_a = set.values).push.apply(_a, []); + var _a; + }; + for (var _i = 0, _a = baz(set.values); _i < _a.length; _i++) { + var _b = _a[_i], value = _b[0], i = _b[1]; + _loop_1(value, i); + } +} +; diff --git a/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.symbols b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.symbols new file mode 100644 index 00000000000..19d657218d6 --- /dev/null +++ b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.symbols @@ -0,0 +1,30 @@ +=== tests/cases/compiler/newLexicalEnvironmentForConvertedLoop.ts === +function baz(x: any) { +>baz : Symbol(baz, Decl(newLexicalEnvironmentForConvertedLoop.ts, 0, 0)) +>x : Symbol(x, Decl(newLexicalEnvironmentForConvertedLoop.ts, 0, 13)) + + return [[x, x]]; +>x : Symbol(x, Decl(newLexicalEnvironmentForConvertedLoop.ts, 0, 13)) +>x : Symbol(x, Decl(newLexicalEnvironmentForConvertedLoop.ts, 0, 13)) +} + +function foo(set: any) { +>foo : Symbol(foo, Decl(newLexicalEnvironmentForConvertedLoop.ts, 2, 1)) +>set : Symbol(set, Decl(newLexicalEnvironmentForConvertedLoop.ts, 4, 13)) + + for (const [value, i] of baz(set.values)) { +>value : Symbol(value, Decl(newLexicalEnvironmentForConvertedLoop.ts, 5, 14)) +>i : Symbol(i, Decl(newLexicalEnvironmentForConvertedLoop.ts, 5, 20)) +>baz : Symbol(baz, Decl(newLexicalEnvironmentForConvertedLoop.ts, 0, 0)) +>set : Symbol(set, Decl(newLexicalEnvironmentForConvertedLoop.ts, 4, 13)) + + const bar: any = []; +>bar : Symbol(bar, Decl(newLexicalEnvironmentForConvertedLoop.ts, 6, 9)) + + (() => bar); +>bar : Symbol(bar, Decl(newLexicalEnvironmentForConvertedLoop.ts, 6, 9)) + + set.values.push(...[]); +>set : Symbol(set, Decl(newLexicalEnvironmentForConvertedLoop.ts, 4, 13)) + } +}; diff --git a/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.types b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.types new file mode 100644 index 00000000000..dcc6f1375a3 --- /dev/null +++ b/tests/baselines/reference/newLexicalEnvironmentForConvertedLoop.types @@ -0,0 +1,45 @@ +=== tests/cases/compiler/newLexicalEnvironmentForConvertedLoop.ts === +function baz(x: any) { +>baz : (x: any) => any[][] +>x : any + + return [[x, x]]; +>[[x, x]] : any[][] +>[x, x] : any[] +>x : any +>x : any +} + +function foo(set: any) { +>foo : (set: any) => void +>set : any + + for (const [value, i] of baz(set.values)) { +>value : any +>i : any +>baz(set.values) : any[][] +>baz : (x: any) => any[][] +>set.values : any +>set : any +>values : any + + const bar: any = []; +>bar : any +>[] : undefined[] + + (() => bar); +>(() => bar) : () => any +>() => bar : () => any +>bar : any + + set.values.push(...[]); +>set.values.push(...[]) : any +>set.values.push : any +>set.values : any +>set : any +>values : any +>push : any +>...[] : undefined +>[] : undefined[] + } +}; diff --git a/tests/baselines/reference/newWithSpread.js b/tests/baselines/reference/newWithSpread.js index 91c502e50b9..c6ea3b44c15 100644 --- a/tests/baselines/reference/newWithSpread.js +++ b/tests/baselines/reference/newWithSpread.js @@ -107,7 +107,7 @@ function f(x, y) { function f2() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var B = (function () { diff --git a/tests/baselines/reference/newWithSpreadES5.js b/tests/baselines/reference/newWithSpreadES5.js index 92904062d0a..125ac9f0412 100644 --- a/tests/baselines/reference/newWithSpreadES5.js +++ b/tests/baselines/reference/newWithSpreadES5.js @@ -106,7 +106,7 @@ function f(x, y) { function f2() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var B = (function () { diff --git a/tests/baselines/reference/noErrorTruncation.errors.txt b/tests/baselines/reference/noErrorTruncation.errors.txt index af3acb54bba..d5244df81a8 100644 --- a/tests/baselines/reference/noErrorTruncation.errors.txt +++ b/tests/baselines/reference/noErrorTruncation.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/noErrorTruncation.ts(10,7): error TS2322: Type '42' is not assignable to type '{ someLongOptionA: string; } | { someLongOptionB: string; } | { someLongOptionC: string; } | { someLongOptionD: string; } | { someLongOptionE: string; } | { someLongOptionF: string; }'. +tests/cases/compiler/noErrorTruncation.ts(10,7): error TS2322: Type '42' is not assignable to type 'SomeLongOptionA | SomeLongOptionB | SomeLongOptionC | SomeLongOptionD | SomeLongOptionE | SomeLongOptionF'. ==== tests/cases/compiler/noErrorTruncation.ts (1 errors) ==== @@ -13,7 +13,7 @@ tests/cases/compiler/noErrorTruncation.ts(10,7): error TS2322: Type '42' is not const x: SomeLongOptionA ~ -!!! error TS2322: Type '42' is not assignable to type '{ someLongOptionA: string; } | { someLongOptionB: string; } | { someLongOptionC: string; } | { someLongOptionD: string; } | { someLongOptionE: string; } | { someLongOptionF: string; }'. +!!! error TS2322: Type '42' is not assignable to type 'SomeLongOptionA | SomeLongOptionB | SomeLongOptionC | SomeLongOptionD | SomeLongOptionE | SomeLongOptionF'. | SomeLongOptionB | SomeLongOptionC | SomeLongOptionD diff --git a/tests/baselines/reference/noImplicitAnyForIn.errors.txt b/tests/baselines/reference/noImplicitAnyForIn.errors.txt index 69b5cd34906..3db1c260d51 100644 --- a/tests/baselines/reference/noImplicitAnyForIn.errors.txt +++ b/tests/baselines/reference/noImplicitAnyForIn.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/noImplicitAnyForIn.ts(8,18): error TS7017: Index signature of object type implicitly has an 'any' type. -tests/cases/compiler/noImplicitAnyForIn.ts(15,18): error TS7017: Index signature of object type implicitly has an 'any' type. +tests/cases/compiler/noImplicitAnyForIn.ts(8,18): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. +tests/cases/compiler/noImplicitAnyForIn.ts(15,18): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. tests/cases/compiler/noImplicitAnyForIn.ts(29,5): error TS7005: Variable 'n' implicitly has an 'any[][]' type. tests/cases/compiler/noImplicitAnyForIn.ts(31,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. @@ -14,7 +14,7 @@ tests/cases/compiler/noImplicitAnyForIn.ts(31,6): error TS2405: The left-hand si //Should yield an implicit 'any' error var _j = x[i][j]; ~~~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. } for (var k in x[0]) { @@ -23,7 +23,7 @@ tests/cases/compiler/noImplicitAnyForIn.ts(31,6): error TS2405: The left-hand si //Should yield an implicit 'any' error var k2 = k1[k]; ~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. } } diff --git a/tests/baselines/reference/noImplicitAnyIndexing.errors.txt b/tests/baselines/reference/noImplicitAnyIndexing.errors.txt index 8f4cf616bda..3274bec5aae 100644 --- a/tests/baselines/reference/noImplicitAnyIndexing.errors.txt +++ b/tests/baselines/reference/noImplicitAnyIndexing.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/noImplicitAnyIndexing.ts(13,26): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. -tests/cases/compiler/noImplicitAnyIndexing.ts(20,9): error TS7017: Index signature of object type implicitly has an 'any' type. -tests/cases/compiler/noImplicitAnyIndexing.ts(23,9): error TS7017: Index signature of object type implicitly has an 'any' type. -tests/cases/compiler/noImplicitAnyIndexing.ts(31,10): error TS7017: Index signature of object type implicitly has an 'any' type. +tests/cases/compiler/noImplicitAnyIndexing.ts(13,37): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. +tests/cases/compiler/noImplicitAnyIndexing.ts(20,9): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. +tests/cases/compiler/noImplicitAnyIndexing.ts(23,9): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. +tests/cases/compiler/noImplicitAnyIndexing.ts(31,10): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. ==== tests/cases/compiler/noImplicitAnyIndexing.ts (4 errors) ==== @@ -18,7 +18,7 @@ tests/cases/compiler/noImplicitAnyIndexing.ts(31,10): error TS7017: Index signat // Should be implicit 'any' ; property access fails, no string indexer. var strRepresentation3 = MyEmusEnum["monehh"]; - ~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~ !!! error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. // Should be okay; should be a MyEmusEnum @@ -28,12 +28,12 @@ tests/cases/compiler/noImplicitAnyIndexing.ts(31,10): error TS7017: Index signat // Should report an implicit 'any'. var x = {}["hi"]; ~~~~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. // Should report an implicit 'any'. var y = {}[10]; ~~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. var hi: any = "hi"; @@ -43,7 +43,7 @@ tests/cases/compiler/noImplicitAnyIndexing.ts(31,10): error TS7017: Index signat // Should report an implicit 'any'. var z1 = emptyObj[hi]; ~~~~~~~~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. var z2 = (emptyObj)[hi]; interface MyMap { diff --git a/tests/baselines/reference/noImplicitAnyParametersInBareFunctions.js b/tests/baselines/reference/noImplicitAnyParametersInBareFunctions.js index 8efe32d3140..3b0b630b537 100644 --- a/tests/baselines/reference/noImplicitAnyParametersInBareFunctions.js +++ b/tests/baselines/reference/noImplicitAnyParametersInBareFunctions.js @@ -59,7 +59,7 @@ function f5(x, y, z) { } function f6() { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } } // Implicit-'any'/'any[]' errors for x, r. @@ -82,7 +82,7 @@ var f12 = function (x, y, z) { return ""; }; var f13 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } return ""; }; diff --git a/tests/baselines/reference/noImplicitAnyParametersInClass.js b/tests/baselines/reference/noImplicitAnyParametersInClass.js index 0e247936529..4ad093f56be 100644 --- a/tests/baselines/reference/noImplicitAnyParametersInClass.js +++ b/tests/baselines/reference/noImplicitAnyParametersInClass.js @@ -107,7 +107,7 @@ var C = (function () { this.pub_f13 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } return ""; }; @@ -131,7 +131,7 @@ var C = (function () { this.priv_f13 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } return ""; }; @@ -158,7 +158,7 @@ var C = (function () { C.prototype.pub_f6 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } }; // Implicit-'any'/'any[]' errors for x, r. @@ -184,7 +184,7 @@ var C = (function () { C.prototype.priv_f6 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } }; // Implicit-'any'/'any[]' errors for x, r. diff --git a/tests/baselines/reference/noImplicitAnyParametersInModule.js b/tests/baselines/reference/noImplicitAnyParametersInModule.js index e7f30205559..1866696fe34 100644 --- a/tests/baselines/reference/noImplicitAnyParametersInModule.js +++ b/tests/baselines/reference/noImplicitAnyParametersInModule.js @@ -63,7 +63,7 @@ var M; function m_f6() { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } } // Implicit-'any'/'any[]' errors for x and r. @@ -86,7 +86,7 @@ var M; var m_f13 = function () { var r = []; for (var _i = 0; _i < arguments.length; _i++) { - r[_i - 0] = arguments[_i]; + r[_i] = arguments[_i]; } return ""; }; diff --git a/tests/baselines/reference/noImplicitAnyStringIndexerOnObject.errors.txt b/tests/baselines/reference/noImplicitAnyStringIndexerOnObject.errors.txt index 5c0878f8ab9..c66a0a83108 100644 --- a/tests/baselines/reference/noImplicitAnyStringIndexerOnObject.errors.txt +++ b/tests/baselines/reference/noImplicitAnyStringIndexerOnObject.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/noImplicitAnyStringIndexerOnObject.ts(2,9): error TS7017: Index signature of object type implicitly has an 'any' type. +tests/cases/compiler/noImplicitAnyStringIndexerOnObject.ts(2,9): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. ==== tests/cases/compiler/noImplicitAnyStringIndexerOnObject.ts (1 errors) ==== var x = {}["hello"]; ~~~~~~~~~~~ -!!! error TS7017: Index signature of object type implicitly has an 'any' type. \ No newline at end of file +!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. \ No newline at end of file diff --git a/tests/baselines/reference/noImplicitReturnsInAsync1.js b/tests/baselines/reference/noImplicitReturnsInAsync1.js index 5274264a6b1..5ab86a91d3b 100644 --- a/tests/baselines/reference/noImplicitReturnsInAsync1.js +++ b/tests/baselines/reference/noImplicitReturnsInAsync1.js @@ -13,7 +13,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function test(isError = false) { diff --git a/tests/baselines/reference/noImplicitReturnsInAsync2.js b/tests/baselines/reference/noImplicitReturnsInAsync2.js index 93f8c97d1fb..7e7f22bd691 100644 --- a/tests/baselines/reference/noImplicitReturnsInAsync2.js +++ b/tests/baselines/reference/noImplicitReturnsInAsync2.js @@ -42,7 +42,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // Should be an error, Promise, currently retorted correctly diff --git a/tests/baselines/reference/nonArrayRestArgs.js b/tests/baselines/reference/nonArrayRestArgs.js index d16b7dea346..813f7141b5c 100644 --- a/tests/baselines/reference/nonArrayRestArgs.js +++ b/tests/baselines/reference/nonArrayRestArgs.js @@ -8,7 +8,7 @@ function foo(...rest: number) { // error function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } var x = rest[0]; return x; diff --git a/tests/baselines/reference/nounusedTypeParameterConstraint.js b/tests/baselines/reference/nounusedTypeParameterConstraint.js new file mode 100644 index 00000000000..aa403187f7a --- /dev/null +++ b/tests/baselines/reference/nounusedTypeParameterConstraint.js @@ -0,0 +1,14 @@ +//// [tests/cases/compiler/nounusedTypeParameterConstraint.ts] //// + +//// [bar.ts] + +export interface IEventSourcedEntity { } + +//// [test.ts] +import { IEventSourcedEntity } from "./bar"; +export type DomainEntityConstructor = { new(): TEntity; }; + +//// [bar.js] +"use strict"; +//// [test.js] +"use strict"; diff --git a/tests/baselines/reference/nounusedTypeParameterConstraint.symbols b/tests/baselines/reference/nounusedTypeParameterConstraint.symbols new file mode 100644 index 00000000000..40364460f50 --- /dev/null +++ b/tests/baselines/reference/nounusedTypeParameterConstraint.symbols @@ -0,0 +1,15 @@ +=== tests/cases/compiler/bar.ts === + +export interface IEventSourcedEntity { } +>IEventSourcedEntity : Symbol(IEventSourcedEntity, Decl(bar.ts, 0, 0)) + +=== tests/cases/compiler/test.ts === +import { IEventSourcedEntity } from "./bar"; +>IEventSourcedEntity : Symbol(IEventSourcedEntity, Decl(test.ts, 0, 8)) + +export type DomainEntityConstructor = { new(): TEntity; }; +>DomainEntityConstructor : Symbol(DomainEntityConstructor, Decl(test.ts, 0, 44)) +>TEntity : Symbol(TEntity, Decl(test.ts, 1, 36)) +>IEventSourcedEntity : Symbol(IEventSourcedEntity, Decl(test.ts, 0, 8)) +>TEntity : Symbol(TEntity, Decl(test.ts, 1, 36)) + diff --git a/tests/baselines/reference/nounusedTypeParameterConstraint.types b/tests/baselines/reference/nounusedTypeParameterConstraint.types new file mode 100644 index 00000000000..0ded5540092 --- /dev/null +++ b/tests/baselines/reference/nounusedTypeParameterConstraint.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/bar.ts === + +export interface IEventSourcedEntity { } +>IEventSourcedEntity : IEventSourcedEntity + +=== tests/cases/compiler/test.ts === +import { IEventSourcedEntity } from "./bar"; +>IEventSourcedEntity : any + +export type DomainEntityConstructor = { new(): TEntity; }; +>DomainEntityConstructor : DomainEntityConstructor +>TEntity : TEntity +>IEventSourcedEntity : IEventSourcedEntity +>TEntity : TEntity + diff --git a/tests/baselines/reference/null.types b/tests/baselines/reference/null.types index ab5ae728dea..35c084c3cbf 100644 --- a/tests/baselines/reference/null.types +++ b/tests/baselines/reference/null.types @@ -5,10 +5,10 @@ var x=null; >null : null var y=3+x; ->y : number ->3+x : number +>y : any +>3+x : any >3 : 3 ->x : null +>x : any var z=3+null; >z : number diff --git a/tests/baselines/reference/nullAssignedToUndefined.errors.txt b/tests/baselines/reference/nullAssignedToUndefined.errors.txt index 5f9921b5809..88bd04a1e62 100644 --- a/tests/baselines/reference/nullAssignedToUndefined.errors.txt +++ b/tests/baselines/reference/nullAssignedToUndefined.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/nullAssignedToUndefined.ts(1,9): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/nullAssignedToUndefined.ts(1,9): error TS2539: Cannot assign to 'undefined' because it is not a variable. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/nullAssignedToUndefined.ts (1 errors) ==== var x = undefined = null; // error ~~~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'undefined' because it is not a variable. var y: typeof undefined = null; // ok, widened \ No newline at end of file diff --git a/tests/baselines/reference/numericLiteralTypes1.types b/tests/baselines/reference/numericLiteralTypes1.types index 56e4bcc0f3f..49c521ad15f 100644 --- a/tests/baselines/reference/numericLiteralTypes1.types +++ b/tests/baselines/reference/numericLiteralTypes1.types @@ -202,11 +202,11 @@ function f4(a: 1, b: 0 | 1 | 2) { a++; >a++ : number ->a : 1 +>a : number b++; >b++ : number ->b : 0 | 1 | 2 +>b : number } declare function g(x: 0): string; diff --git a/tests/baselines/reference/numericLiteralTypes2.types b/tests/baselines/reference/numericLiteralTypes2.types index b8e2526a221..4c67154ad41 100644 --- a/tests/baselines/reference/numericLiteralTypes2.types +++ b/tests/baselines/reference/numericLiteralTypes2.types @@ -203,11 +203,11 @@ function f4(a: 1, b: 0 | 1 | 2) { a++; >a++ : number ->a : 1 +>a : number b++; >b++ : number ->b : 0 | 1 | 2 +>b : number } declare function g(x: 0): string; diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js index cd339bb5907..a905e53f221 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js @@ -3,4 +3,4 @@ var { while } = { while: 1 } //// [objectBindingPatternKeywordIdentifiers01.js] -var = { while: 1 }.while; +var = { "while": 1 }["while"]; diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.js b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.js index 0286a78ba82..5bc6e1f9963 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.js +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.js @@ -3,4 +3,4 @@ var { while: while } = { while: 1 } //// [objectBindingPatternKeywordIdentifiers02.js] -var _a = { while: 1 }, = _a.while, = _a.while; +var _a = { "while": 1 }, = _a["while"], = _a["while"]; diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers03.js b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers03.js index 4bbb1afb4cb..3d8643d63ce 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers03.js +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers03.js @@ -3,4 +3,4 @@ var { "while" } = { while: 1 } //// [objectBindingPatternKeywordIdentifiers03.js] -var = { while: 1 }["while"]; +var = { "while": 1 }["while"]; diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.js b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.js index 4e53b13c0a6..de7608a77d2 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.js +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.js @@ -3,4 +3,4 @@ var { "while": while } = { while: 1 } //// [objectBindingPatternKeywordIdentifiers04.js] -var _a = { while: 1 }, = _a["while"], = _a.while; +var _a = { "while": 1 }, = _a["while"], = _a["while"]; diff --git a/tests/baselines/reference/objectCreationOfElementAccessExpression.errors.txt b/tests/baselines/reference/objectCreationOfElementAccessExpression.errors.txt index ef50db9e4e5..fecbee27b58 100644 --- a/tests/baselines/reference/objectCreationOfElementAccessExpression.errors.txt +++ b/tests/baselines/reference/objectCreationOfElementAccessExpression.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/objectCreationOfElementAccessExpression.ts(53,17): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/objectCreationOfElementAccessExpression.ts(53,25): error TS2538: Type 'Cookie' cannot be used as an index type. tests/cases/compiler/objectCreationOfElementAccessExpression.ts(53,63): error TS2348: Value of type 'typeof Cookie' is not callable. Did you mean to include 'new'? -tests/cases/compiler/objectCreationOfElementAccessExpression.ts(54,33): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/objectCreationOfElementAccessExpression.ts(54,41): error TS2538: Type 'Cookie' cannot be used as an index type. tests/cases/compiler/objectCreationOfElementAccessExpression.ts(54,79): error TS2348: Value of type 'typeof Cookie' is not callable. Did you mean to include 'new'? @@ -58,13 +58,13 @@ tests/cases/compiler/objectCreationOfElementAccessExpression.ts(54,79): error TS // ElementAccessExpressions can only contain one expression. There should be a parse error here. var foods = new PetFood[new IceCream('Mint chocolate chip') , Cookie('Chocolate chip', false) , new Cookie('Peanut butter', true)]; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2538: Type 'Cookie' cannot be used as an index type. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2348: Value of type 'typeof Cookie' is not callable. Did you mean to include 'new'? var foods2: MonsterFood[] = new PetFood[new IceCream('Mint chocolate chip') , Cookie('Chocolate chip', false) , new Cookie('Peanut butter', true)]; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2538: Type 'Cookie' cannot be used as an index type. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2348: Value of type 'typeof Cookie' is not callable. Did you mean to include 'new'? \ No newline at end of file diff --git a/tests/baselines/reference/objectFreeze.errors.txt b/tests/baselines/reference/objectFreeze.errors.txt new file mode 100644 index 00000000000..9c28c62f534 --- /dev/null +++ b/tests/baselines/reference/objectFreeze.errors.txt @@ -0,0 +1,22 @@ +tests/cases/compiler/objectFreeze.ts(9,1): error TS2542: Index signature in type 'ReadonlyArray' only permits reading. +tests/cases/compiler/objectFreeze.ts(12,3): error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. + + +==== tests/cases/compiler/objectFreeze.ts (2 errors) ==== + const f = Object.freeze(function foo(a: number, b: string) { return false; }); + f(1, "") === false; + + class C { constructor(a: number) { } } + const c = Object.freeze(C); + new c(1); + + const a = Object.freeze([1, 2, 3]); + a[0] = a[2].toString(); + ~~~~ +!!! error TS2542: Index signature in type 'ReadonlyArray' only permits reading. + + const o = Object.freeze({ a: 1, b: "string" }); + o.b = o.a.toString(); + ~ +!!! error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. + \ No newline at end of file diff --git a/tests/baselines/reference/objectFreeze.js b/tests/baselines/reference/objectFreeze.js new file mode 100644 index 00000000000..4c37631bb10 --- /dev/null +++ b/tests/baselines/reference/objectFreeze.js @@ -0,0 +1,29 @@ +//// [objectFreeze.ts] +const f = Object.freeze(function foo(a: number, b: string) { return false; }); +f(1, "") === false; + +class C { constructor(a: number) { } } +const c = Object.freeze(C); +new c(1); + +const a = Object.freeze([1, 2, 3]); +a[0] = a[2].toString(); + +const o = Object.freeze({ a: 1, b: "string" }); +o.b = o.a.toString(); + + +//// [objectFreeze.js] +var f = Object.freeze(function foo(a, b) { return false; }); +f(1, "") === false; +var C = (function () { + function C(a) { + } + return C; +}()); +var c = Object.freeze(C); +new c(1); +var a = Object.freeze([1, 2, 3]); +a[0] = a[2].toString(); +var o = Object.freeze({ a: 1, b: "string" }); +o.b = o.a.toString(); diff --git a/tests/baselines/reference/objectLiteralErrors.errors.txt b/tests/baselines/reference/objectLiteralErrors.errors.txt index 234ac24a8fd..03b4b74eacd 100644 --- a/tests/baselines/reference/objectLiteralErrors.errors.txt +++ b/tests/baselines/reference/objectLiteralErrors.errors.txt @@ -12,7 +12,7 @@ tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(13,21) tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(14,19): error TS2300: Duplicate identifier '0'. tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(15,19): error TS2300: Duplicate identifier '0'. tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(16,19): error TS2300: Duplicate identifier '0x0'. -tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(17,19): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(17,19): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o0'. tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(17,19): error TS2300: Duplicate identifier '000'. tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(18,23): error TS2300: Duplicate identifier '1e2'. tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(19,22): error TS2300: Duplicate identifier '3.2e1'. @@ -125,7 +125,7 @@ tests/cases/conformance/expressions/objectLiterals/objectLiteralErrors.ts(45,55) !!! error TS2300: Duplicate identifier '0x0'. var e14 = { 0: 0, 000: 0 }; ~~~ -!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o0'. ~~~ !!! error TS2300: Duplicate identifier '000'. var e15 = { "100": 0, 1e2: 0 }; diff --git a/tests/baselines/reference/objectLiteralShorthandProperties.types b/tests/baselines/reference/objectLiteralShorthandProperties.types index 168fcc07af7..4f4482906aa 100644 --- a/tests/baselines/reference/objectLiteralShorthandProperties.types +++ b/tests/baselines/reference/objectLiteralShorthandProperties.types @@ -5,35 +5,35 @@ var a, b, c; >c : any var x1 = { ->x1 : { a: undefined; } ->{ a} : { a: undefined; } +>x1 : { a: any; } +>{ a} : { a: any; } a ->a : undefined +>a : any }; var x2 = { ->x2 : { a: undefined; } ->{ a,} : { a: undefined; } +>x2 : { a: any; } +>{ a,} : { a: any; } a, ->a : undefined +>a : any } var x3 = { >x3 : any ->{ a: 0, b, c, d() { }, x3, parent: x3} : { a: number; b: undefined; c: undefined; d(): void; x3: any; parent: any; } +>{ a: 0, b, c, d() { }, x3, parent: x3} : { a: number; b: any; c: any; d(): void; x3: any; parent: any; } a: 0, >a : number >0 : 0 b, ->b : undefined +>b : any c, ->c : undefined +>c : any d() { }, >d : () => void diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesES6.types b/tests/baselines/reference/objectLiteralShorthandPropertiesES6.types index 80cbe304040..1565be04625 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesES6.types +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesES6.types @@ -5,35 +5,35 @@ var a, b, c; >c : any var x1 = { ->x1 : { a: undefined; } ->{ a} : { a: undefined; } +>x1 : { a: any; } +>{ a} : { a: any; } a ->a : undefined +>a : any }; var x2 = { ->x2 : { a: undefined; } ->{ a,} : { a: undefined; } +>x2 : { a: any; } +>{ a,} : { a: any; } a, ->a : undefined +>a : any } var x3 = { >x3 : any ->{ a: 0, b, c, d() { }, x3, parent: x3} : { a: number; b: undefined; c: undefined; d(): void; x3: any; parent: any; } +>{ a: 0, b, c, d() { }, x3, parent: x3} : { a: number; b: any; c: any; d(): void; x3: any; parent: any; } a: 0, >a : number >0 : 0 b, ->b : undefined +>b : any c, ->c : undefined +>c : any d() { }, >d : () => void diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js index b72f0351b9c..7b9c9f5d328 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js @@ -27,15 +27,15 @@ var y = { 42: , get e() { }, set f() { }, - this: , - super: , - var: , - class: , - typeof: + "this": , + "super": , + "var": , + "class": , + "typeof": }; var x = { a: .b, a: ["ss"], a: [1] }; -var v = { class: }; // error +var v = { "class": }; // error diff --git a/tests/baselines/reference/objectRest.js b/tests/baselines/reference/objectRest.js new file mode 100644 index 00000000000..48a1bf8daf8 --- /dev/null +++ b/tests/baselines/reference/objectRest.js @@ -0,0 +1,85 @@ +//// [objectRest.ts] +var o = { a: 1, b: 'no' } +var { ...clone } = o; +var { a, ...justB } = o; +var { a, b: renamed, ...empty } = o; +var { ['b']: renamed, ...justA } = o; +var { 'b': renamed, ...justA } = o; +var { b: { '0': n, '1': oooo }, ...justA } = o; + +let o2 = { c: 'terrible idea?', d: 'yes' }; +var { d: renamed, ...d } = o2; + +let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; +var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; + +let complex: { x: { ka, ki }, y: number }; +var { x: { ka, ...nested }, y: other, ...rest } = complex; +({x: { ka, ...nested }, y: other, ...rest} = complex); +var { x, ...fresh } = { x: 1, y: 2 }; +({ x, ...fresh } = { x: 1, y: 2 }); + +class Removable { + private x: number; + protected y: number; + set z(value: number) { } + get both(): number { return 12 } + set both(value: number) { } + m() { } + removed: string; + remainder: string; +} +var removable = new Removable(); +var { removed, ...removableRest } = removable; + +let computed = 'b'; +let computed2 = 'a'; +var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; +({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject['anythingGoes']; + + +//// [objectRest.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var o = { a: 1, b: 'no' }; +var clone = __rest(o, []); +var { a } = o, justB = __rest(o, ["a"]); +var { a, b: renamed } = o, empty = __rest(o, ["a", "b"]); +var { ['b']: renamed } = o, justA = __rest(o, ['b']); +var { 'b': renamed } = o, justA = __rest(o, ['b']); +var { b: { '0': n, '1': oooo } } = o, justA = __rest(o, ["b"]); +let o2 = { c: 'terrible idea?', d: 'yes' }; +var { d: renamed } = o2, d = __rest(o2, ["d"]); +let nestedrest; +var { x } = nestedrest, _a = nestedrest.n1, { y } = _a, _b = _a.n2, { z } = _b, nr = __rest(_b.n3, []), restrest = __rest(nestedrest, ["x", "n1"]); +let complex; +var _c = complex.x, { ka } = _c, nested = __rest(_c, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]); +(_d = complex.x, { ka } = _d, nested = __rest(_d, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"])); +var _e = { x: 1, y: 2 }, { x } = _e, fresh = __rest(_e, ["x"]); +(_f = { x: 1, y: 2 }, { x } = _f, fresh = __rest(_f, ["x"])); +class Removable { + set z(value) { } + get both() { return 12; } + set both(value) { } + m() { } +} +var removable = new Removable(); +var { removed } = removable, removableRest = __rest(removable, ["removed"]); +let computed = 'b'; +let computed2 = 'a'; +var _g = computed, stillNotGreat = o[_g], _h = computed2, soSo = o[_h], o = __rest(o, [typeof _g === "symbol" ? _g : _g + "", typeof _h === "symbol" ? _h : _h + ""]); +(_j = computed, stillNotGreat = o[_j], _k = computed2, soSo = o[_k], o = __rest(o, [typeof _j === "symbol" ? _j : _j + "", typeof _k === "symbol" ? _k : _k + ""])); +var noContextualType = (_a) => { + var { aNumber = 12 } = _a, notEmptyObject = __rest(_a, ["aNumber"]); + return aNumber + notEmptyObject['anythingGoes']; +}; +var _d, _f, _j, _k; diff --git a/tests/baselines/reference/objectRest.symbols b/tests/baselines/reference/objectRest.symbols new file mode 100644 index 00000000000..46309392135 --- /dev/null +++ b/tests/baselines/reference/objectRest.symbols @@ -0,0 +1,178 @@ +=== tests/cases/conformance/types/rest/objectRest.ts === +var o = { a: 1, b: 'no' } +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) +>a : Symbol(a, Decl(objectRest.ts, 0, 9)) +>b : Symbol(b, Decl(objectRest.ts, 0, 15)) + +var { ...clone } = o; +>clone : Symbol(clone, Decl(objectRest.ts, 1, 5)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var { a, ...justB } = o; +>a : Symbol(a, Decl(objectRest.ts, 2, 5), Decl(objectRest.ts, 3, 5)) +>justB : Symbol(justB, Decl(objectRest.ts, 2, 8)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var { a, b: renamed, ...empty } = o; +>a : Symbol(a, Decl(objectRest.ts, 2, 5), Decl(objectRest.ts, 3, 5)) +>b : Symbol(b, Decl(objectRest.ts, 0, 15)) +>renamed : Symbol(renamed, Decl(objectRest.ts, 3, 8), Decl(objectRest.ts, 4, 5), Decl(objectRest.ts, 5, 5), Decl(objectRest.ts, 9, 5)) +>empty : Symbol(empty, Decl(objectRest.ts, 3, 20)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var { ['b']: renamed, ...justA } = o; +>'b' : Symbol(renamed, Decl(objectRest.ts, 3, 8), Decl(objectRest.ts, 4, 5), Decl(objectRest.ts, 5, 5), Decl(objectRest.ts, 9, 5)) +>renamed : Symbol(renamed, Decl(objectRest.ts, 3, 8), Decl(objectRest.ts, 4, 5), Decl(objectRest.ts, 5, 5), Decl(objectRest.ts, 9, 5)) +>justA : Symbol(justA, Decl(objectRest.ts, 4, 21), Decl(objectRest.ts, 5, 19), Decl(objectRest.ts, 6, 31)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var { 'b': renamed, ...justA } = o; +>renamed : Symbol(renamed, Decl(objectRest.ts, 3, 8), Decl(objectRest.ts, 4, 5), Decl(objectRest.ts, 5, 5), Decl(objectRest.ts, 9, 5)) +>justA : Symbol(justA, Decl(objectRest.ts, 4, 21), Decl(objectRest.ts, 5, 19), Decl(objectRest.ts, 6, 31)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var { b: { '0': n, '1': oooo }, ...justA } = o; +>b : Symbol(b, Decl(objectRest.ts, 0, 15)) +>n : Symbol(n, Decl(objectRest.ts, 6, 10)) +>oooo : Symbol(oooo, Decl(objectRest.ts, 6, 18)) +>justA : Symbol(justA, Decl(objectRest.ts, 4, 21), Decl(objectRest.ts, 5, 19), Decl(objectRest.ts, 6, 31)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +let o2 = { c: 'terrible idea?', d: 'yes' }; +>o2 : Symbol(o2, Decl(objectRest.ts, 8, 3)) +>c : Symbol(c, Decl(objectRest.ts, 8, 10)) +>d : Symbol(d, Decl(objectRest.ts, 8, 31)) + +var { d: renamed, ...d } = o2; +>d : Symbol(d, Decl(objectRest.ts, 8, 31)) +>renamed : Symbol(renamed, Decl(objectRest.ts, 3, 8), Decl(objectRest.ts, 4, 5), Decl(objectRest.ts, 5, 5), Decl(objectRest.ts, 9, 5)) +>d : Symbol(d, Decl(objectRest.ts, 9, 17)) +>o2 : Symbol(o2, Decl(objectRest.ts, 8, 3)) + +let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; +>nestedrest : Symbol(nestedrest, Decl(objectRest.ts, 11, 3)) +>x : Symbol(x, Decl(objectRest.ts, 11, 17)) +>n1 : Symbol(n1, Decl(objectRest.ts, 11, 28)) +>y : Symbol(y, Decl(objectRest.ts, 11, 34)) +>n2 : Symbol(n2, Decl(objectRest.ts, 11, 45)) +>z : Symbol(z, Decl(objectRest.ts, 11, 51)) +>n3 : Symbol(n3, Decl(objectRest.ts, 11, 62)) +>n4 : Symbol(n4, Decl(objectRest.ts, 11, 68)) +>rest : Symbol(rest, Decl(objectRest.ts, 11, 86)) +>restrest : Symbol(restrest, Decl(objectRest.ts, 11, 100)) + +var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; +>x : Symbol(x, Decl(objectRest.ts, 12, 5), Decl(objectRest.ts, 17, 5)) +>n1 : Symbol(n1, Decl(objectRest.ts, 11, 28)) +>y : Symbol(y, Decl(objectRest.ts, 12, 14)) +>n2 : Symbol(n2, Decl(objectRest.ts, 11, 45)) +>z : Symbol(z, Decl(objectRest.ts, 12, 23)) +>n3 : Symbol(n3, Decl(objectRest.ts, 11, 62)) +>nr : Symbol(nr, Decl(objectRest.ts, 12, 32)) +>restrest : Symbol(restrest, Decl(objectRest.ts, 12, 45)) +>nestedrest : Symbol(nestedrest, Decl(objectRest.ts, 11, 3)) + +let complex: { x: { ka, ki }, y: number }; +>complex : Symbol(complex, Decl(objectRest.ts, 14, 3)) +>x : Symbol(x, Decl(objectRest.ts, 14, 14)) +>ka : Symbol(ka, Decl(objectRest.ts, 14, 19)) +>ki : Symbol(ki, Decl(objectRest.ts, 14, 23)) +>y : Symbol(y, Decl(objectRest.ts, 14, 29)) + +var { x: { ka, ...nested }, y: other, ...rest } = complex; +>x : Symbol(x, Decl(objectRest.ts, 14, 14)) +>ka : Symbol(ka, Decl(objectRest.ts, 15, 10)) +>nested : Symbol(nested, Decl(objectRest.ts, 15, 14)) +>y : Symbol(y, Decl(objectRest.ts, 14, 29)) +>other : Symbol(other, Decl(objectRest.ts, 15, 27)) +>rest : Symbol(rest, Decl(objectRest.ts, 15, 37)) +>complex : Symbol(complex, Decl(objectRest.ts, 14, 3)) + +({x: { ka, ...nested }, y: other, ...rest} = complex); +>x : Symbol(x, Decl(objectRest.ts, 16, 2)) +>ka : Symbol(ka, Decl(objectRest.ts, 16, 6)) +>nested : Symbol(nested, Decl(objectRest.ts, 15, 14)) +>y : Symbol(y, Decl(objectRest.ts, 16, 23)) +>other : Symbol(other, Decl(objectRest.ts, 15, 27)) +>rest : Symbol(rest, Decl(objectRest.ts, 15, 37)) +>complex : Symbol(complex, Decl(objectRest.ts, 14, 3)) + +var { x, ...fresh } = { x: 1, y: 2 }; +>x : Symbol(x, Decl(objectRest.ts, 12, 5), Decl(objectRest.ts, 17, 5)) +>fresh : Symbol(fresh, Decl(objectRest.ts, 17, 8)) +>x : Symbol(x, Decl(objectRest.ts, 17, 23)) +>y : Symbol(y, Decl(objectRest.ts, 17, 29)) + +({ x, ...fresh } = { x: 1, y: 2 }); +>x : Symbol(x, Decl(objectRest.ts, 18, 2)) +>fresh : Symbol(fresh, Decl(objectRest.ts, 17, 8)) +>x : Symbol(x, Decl(objectRest.ts, 18, 20)) +>y : Symbol(y, Decl(objectRest.ts, 18, 26)) + +class Removable { +>Removable : Symbol(Removable, Decl(objectRest.ts, 18, 35)) + + private x: number; +>x : Symbol(Removable.x, Decl(objectRest.ts, 20, 17)) + + protected y: number; +>y : Symbol(Removable.y, Decl(objectRest.ts, 21, 22)) + + set z(value: number) { } +>z : Symbol(Removable.z, Decl(objectRest.ts, 22, 24)) +>value : Symbol(value, Decl(objectRest.ts, 23, 10)) + + get both(): number { return 12 } +>both : Symbol(Removable.both, Decl(objectRest.ts, 23, 28), Decl(objectRest.ts, 24, 36)) + + set both(value: number) { } +>both : Symbol(Removable.both, Decl(objectRest.ts, 23, 28), Decl(objectRest.ts, 24, 36)) +>value : Symbol(value, Decl(objectRest.ts, 25, 13)) + + m() { } +>m : Symbol(Removable.m, Decl(objectRest.ts, 25, 31)) + + removed: string; +>removed : Symbol(Removable.removed, Decl(objectRest.ts, 26, 11)) + + remainder: string; +>remainder : Symbol(Removable.remainder, Decl(objectRest.ts, 27, 20)) +} +var removable = new Removable(); +>removable : Symbol(removable, Decl(objectRest.ts, 30, 3)) +>Removable : Symbol(Removable, Decl(objectRest.ts, 18, 35)) + +var { removed, ...removableRest } = removable; +>removed : Symbol(removed, Decl(objectRest.ts, 31, 5)) +>removableRest : Symbol(removableRest, Decl(objectRest.ts, 31, 14)) +>removable : Symbol(removable, Decl(objectRest.ts, 30, 3)) + +let computed = 'b'; +>computed : Symbol(computed, Decl(objectRest.ts, 33, 3)) + +let computed2 = 'a'; +>computed2 : Symbol(computed2, Decl(objectRest.ts, 34, 3)) + +var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; +>computed : Symbol(computed, Decl(objectRest.ts, 33, 3)) +>stillNotGreat : Symbol(stillNotGreat, Decl(objectRest.ts, 35, 5)) +>computed2 : Symbol(computed2, Decl(objectRest.ts, 34, 3)) +>soSo : Symbol(soSo, Decl(objectRest.ts, 35, 32)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); +>computed : Symbol(computed, Decl(objectRest.ts, 33, 3)) +>stillNotGreat : Symbol(stillNotGreat, Decl(objectRest.ts, 35, 5)) +>computed2 : Symbol(computed2, Decl(objectRest.ts, 34, 3)) +>soSo : Symbol(soSo, Decl(objectRest.ts, 35, 32)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) +>o : Symbol(o, Decl(objectRest.ts, 0, 3), Decl(objectRest.ts, 35, 51)) + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject['anythingGoes']; +>noContextualType : Symbol(noContextualType, Decl(objectRest.ts, 38, 3)) +>aNumber : Symbol(aNumber, Decl(objectRest.ts, 38, 25)) +>notEmptyObject : Symbol(notEmptyObject, Decl(objectRest.ts, 38, 39)) +>aNumber : Symbol(aNumber, Decl(objectRest.ts, 38, 25)) +>notEmptyObject : Symbol(notEmptyObject, Decl(objectRest.ts, 38, 39)) + diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types new file mode 100644 index 00000000000..1dc05741713 --- /dev/null +++ b/tests/baselines/reference/objectRest.types @@ -0,0 +1,209 @@ +=== tests/cases/conformance/types/rest/objectRest.ts === +var o = { a: 1, b: 'no' } +>o : { a: number; b: string; } +>{ a: 1, b: 'no' } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>'no' : "no" + +var { ...clone } = o; +>clone : { a: number; b: string; } +>o : { a: number; b: string; } + +var { a, ...justB } = o; +>a : number +>justB : { b: string; } +>o : { a: number; b: string; } + +var { a, b: renamed, ...empty } = o; +>a : number +>b : any +>renamed : string +>empty : {} +>o : { a: number; b: string; } + +var { ['b']: renamed, ...justA } = o; +>'b' : "b" +>renamed : string +>justA : { a: number; } +>o : { a: number; b: string; } + +var { 'b': renamed, ...justA } = o; +>renamed : string +>justA : { a: number; } +>o : { a: number; b: string; } + +var { b: { '0': n, '1': oooo }, ...justA } = o; +>b : any +>n : string +>oooo : string +>justA : { a: number; } +>o : { a: number; b: string; } + +let o2 = { c: 'terrible idea?', d: 'yes' }; +>o2 : { c: string; d: string; } +>{ c: 'terrible idea?', d: 'yes' } : { c: string; d: string; } +>c : string +>'terrible idea?' : "terrible idea?" +>d : string +>'yes' : "yes" + +var { d: renamed, ...d } = o2; +>d : any +>renamed : string +>d : { c: string; } +>o2 : { c: string; d: string; } + +let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; +>nestedrest : { x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; } +>x : number +>n1 : { y: number; n2: { z: number; n3: { n4: number; }; }; } +>y : number +>n2 : { z: number; n3: { n4: number; }; } +>z : number +>n3 : { n4: number; } +>n4 : number +>rest : number +>restrest : number + +var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; +>x : number +>n1 : any +>y : number +>n2 : any +>z : number +>n3 : any +>nr : { n4: number; } +>restrest : { rest: number; restrest: number; } +>nestedrest : { x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; } + +let complex: { x: { ka, ki }, y: number }; +>complex : { x: { ka: any; ki: any; }; y: number; } +>x : { ka: any; ki: any; } +>ka : any +>ki : any +>y : number + +var { x: { ka, ...nested }, y: other, ...rest } = complex; +>x : any +>ka : any +>nested : { ki: any; } +>y : any +>other : number +>rest : {} +>complex : { x: { ka: any; ki: any; }; y: number; } + +({x: { ka, ...nested }, y: other, ...rest} = complex); +>({x: { ka, ...nested }, y: other, ...rest} = complex) : { x: { ka: any; ki: any; }; y: number; } +>{x: { ka, ...nested }, y: other, ...rest} = complex : { x: { ka: any; ki: any; }; y: number; } +>{x: { ka, ...nested }, y: other, ...rest} : { x: { ki: any; ka: any; }; y: number; } +>x : { ki: any; ka: any; } +>{ ka, ...nested } : { ki: any; ka: any; } +>ka : any +>nested : { ki: any; } +>y : number +>other : number +>rest : {} +>complex : { x: { ka: any; ki: any; }; y: number; } + +var { x, ...fresh } = { x: 1, y: 2 }; +>x : number +>fresh : { y: number; } +>{ x: 1, y: 2 } : { x: number; y: number; } +>x : number +>1 : 1 +>y : number +>2 : 2 + +({ x, ...fresh } = { x: 1, y: 2 }); +>({ x, ...fresh } = { x: 1, y: 2 }) : { x: number; y: number; } +>{ x, ...fresh } = { x: 1, y: 2 } : { x: number; y: number; } +>{ x, ...fresh } : { y: number; x: number; } +>x : number +>fresh : { y: number; } +>{ x: 1, y: 2 } : { x: number; y: number; } +>x : number +>1 : 1 +>y : number +>2 : 2 + +class Removable { +>Removable : Removable + + private x: number; +>x : number + + protected y: number; +>y : number + + set z(value: number) { } +>z : number +>value : number + + get both(): number { return 12 } +>both : number +>12 : 12 + + set both(value: number) { } +>both : number +>value : number + + m() { } +>m : () => void + + removed: string; +>removed : string + + remainder: string; +>remainder : string +} +var removable = new Removable(); +>removable : Removable +>new Removable() : Removable +>Removable : typeof Removable + +var { removed, ...removableRest } = removable; +>removed : string +>removableRest : { both: number; remainder: string; } +>removable : Removable + +let computed = 'b'; +>computed : string +>'b' : "b" + +let computed2 = 'a'; +>computed2 : string +>'a' : "a" + +var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; +>computed : string +>stillNotGreat : any +>computed2 : string +>soSo : any +>o : { a: number; b: string; } +>o : { a: number; b: string; } + +({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); +>({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o) : { a: number; b: string; } +>{ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o : { a: number; b: string; } +>{ [computed]: stillNotGreat, [computed2]: soSo, ...o } : { a: number; b: string; } +>computed : string +>stillNotGreat : any +>computed2 : string +>soSo : any +>o : { a: number; b: string; } +>o : { a: number; b: string; } + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject['anythingGoes']; +>noContextualType : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any +>({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject['anythingGoes'] : ({aNumber, ...notEmptyObject}: { [x: string]: any; aNumber?: number; }) => any +>aNumber : number +>12 : 12 +>notEmptyObject : { [x: string]: any; } +>aNumber + notEmptyObject['anythingGoes'] : any +>aNumber : number +>notEmptyObject['anythingGoes'] : any +>notEmptyObject : { [x: string]: any; } +>'anythingGoes' : "anythingGoes" + diff --git a/tests/baselines/reference/objectRest2.js b/tests/baselines/reference/objectRest2.js new file mode 100644 index 00000000000..6abff9e56a1 --- /dev/null +++ b/tests/baselines/reference/objectRest2.js @@ -0,0 +1,42 @@ +//// [objectRest2.ts] +// test for #12203 +declare function connectionFromArray(objects: number, args: any): {}; +function rootConnection(name: string) { + return { + resolve: async (context, args) => { + const { objects } = await { objects: 12 }; + return { + ...connectionFromArray(objects, args) + }; + } + }; +} +rootConnection('test'); + + +//// [objectRest2.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +function rootConnection(name) { + return { + resolve: (context, args) => __awaiter(this, void 0, void 0, function* () { + const { objects } = yield { objects: 12 }; + return __assign({}, connectionFromArray(objects, args)); + }) + }; +} +rootConnection('test'); diff --git a/tests/baselines/reference/objectRest2.symbols b/tests/baselines/reference/objectRest2.symbols new file mode 100644 index 00000000000..42532f5d183 --- /dev/null +++ b/tests/baselines/reference/objectRest2.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/types/rest/objectRest2.ts === +// test for #12203 +declare function connectionFromArray(objects: number, args: any): {}; +>connectionFromArray : Symbol(connectionFromArray, Decl(objectRest2.ts, 0, 0)) +>objects : Symbol(objects, Decl(objectRest2.ts, 1, 37)) +>args : Symbol(args, Decl(objectRest2.ts, 1, 53)) + +function rootConnection(name: string) { +>rootConnection : Symbol(rootConnection, Decl(objectRest2.ts, 1, 69)) +>name : Symbol(name, Decl(objectRest2.ts, 2, 24)) + + return { + resolve: async (context, args) => { +>resolve : Symbol(resolve, Decl(objectRest2.ts, 3, 10)) +>context : Symbol(context, Decl(objectRest2.ts, 4, 20)) +>args : Symbol(args, Decl(objectRest2.ts, 4, 28)) + + const { objects } = await { objects: 12 }; +>objects : Symbol(objects, Decl(objectRest2.ts, 5, 15)) +>objects : Symbol(objects, Decl(objectRest2.ts, 5, 35)) + + return { + ...connectionFromArray(objects, args) +>connectionFromArray : Symbol(connectionFromArray, Decl(objectRest2.ts, 0, 0)) +>objects : Symbol(objects, Decl(objectRest2.ts, 5, 15)) +>args : Symbol(args, Decl(objectRest2.ts, 4, 28)) + + }; + } + }; +} +rootConnection('test'); +>rootConnection : Symbol(rootConnection, Decl(objectRest2.ts, 1, 69)) + diff --git a/tests/baselines/reference/objectRest2.types b/tests/baselines/reference/objectRest2.types new file mode 100644 index 00000000000..8e89a3cb573 --- /dev/null +++ b/tests/baselines/reference/objectRest2.types @@ -0,0 +1,45 @@ +=== tests/cases/conformance/types/rest/objectRest2.ts === +// test for #12203 +declare function connectionFromArray(objects: number, args: any): {}; +>connectionFromArray : (objects: number, args: any) => {} +>objects : number +>args : any + +function rootConnection(name: string) { +>rootConnection : (name: string) => { resolve: (context: any, args: any) => Promise<{}>; } +>name : string + + return { +>{ resolve: async (context, args) => { const { objects } = await { objects: 12 }; return { ...connectionFromArray(objects, args) }; } } : { resolve: (context: any, args: any) => Promise<{}>; } + + resolve: async (context, args) => { +>resolve : (context: any, args: any) => Promise<{}> +>async (context, args) => { const { objects } = await { objects: 12 }; return { ...connectionFromArray(objects, args) }; } : (context: any, args: any) => Promise<{}> +>context : any +>args : any + + const { objects } = await { objects: 12 }; +>objects : number +>await { objects: 12 } : { objects: number; } +>{ objects: 12 } : { objects: number; } +>objects : number +>12 : 12 + + return { +>{ ...connectionFromArray(objects, args) } : {} + + ...connectionFromArray(objects, args) +>connectionFromArray(objects, args) : {} +>connectionFromArray : (objects: number, args: any) => {} +>objects : number +>args : any + + }; + } + }; +} +rootConnection('test'); +>rootConnection('test') : { resolve: (context: any, args: any) => Promise<{}>; } +>rootConnection : (name: string) => { resolve: (context: any, args: any) => Promise<{}>; } +>'test' : "test" + diff --git a/tests/baselines/reference/objectRestAssignment.js b/tests/baselines/reference/objectRestAssignment.js new file mode 100644 index 00000000000..cbdff663c26 --- /dev/null +++ b/tests/baselines/reference/objectRestAssignment.js @@ -0,0 +1,38 @@ +//// [objectRestAssignment.ts] +let ka: any; +let nested: { ki }; +let other: number; +let rest: { }; +let complex: { x: { ka, ki }, y: number }; +({x: { ka, ...nested }, y: other, ...rest} = complex); + +// should be: +let overEmit: { a: { ka: string, x: string }[], b: { z: string, ki: string, ku: string }, ke: string, ko: string }; + +// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; +({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); + + +//// [objectRestAssignment.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +let ka; +let nested; +let other; +let rest; +let complex; +(_a = complex.x, { ka } = _a, nested = __rest(_a, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"])); +// should be: +let overEmit; +// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +var [_b, ...y] = overEmit.a, nested2 = __rest(_b, []), _c = overEmit.b, { z } = _c, c = __rest(_c, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +([_d, ...y] = overEmit.a, nested2 = __rest(_d, []), _e = overEmit.b, { z } = _e, c = __rest(_e, ["z"]), rest2 = __rest(overEmit, ["a", "b"])); +var _a, _d, _e; diff --git a/tests/baselines/reference/objectRestAssignment.symbols b/tests/baselines/reference/objectRestAssignment.symbols new file mode 100644 index 00000000000..82324873283 --- /dev/null +++ b/tests/baselines/reference/objectRestAssignment.symbols @@ -0,0 +1,64 @@ +=== tests/cases/conformance/types/rest/objectRestAssignment.ts === +let ka: any; +>ka : Symbol(ka, Decl(objectRestAssignment.ts, 0, 3)) + +let nested: { ki }; +>nested : Symbol(nested, Decl(objectRestAssignment.ts, 1, 3)) +>ki : Symbol(ki, Decl(objectRestAssignment.ts, 1, 13)) + +let other: number; +>other : Symbol(other, Decl(objectRestAssignment.ts, 2, 3)) + +let rest: { }; +>rest : Symbol(rest, Decl(objectRestAssignment.ts, 3, 3)) + +let complex: { x: { ka, ki }, y: number }; +>complex : Symbol(complex, Decl(objectRestAssignment.ts, 4, 3)) +>x : Symbol(x, Decl(objectRestAssignment.ts, 4, 14)) +>ka : Symbol(ka, Decl(objectRestAssignment.ts, 4, 19)) +>ki : Symbol(ki, Decl(objectRestAssignment.ts, 4, 23)) +>y : Symbol(y, Decl(objectRestAssignment.ts, 4, 29)) + +({x: { ka, ...nested }, y: other, ...rest} = complex); +>x : Symbol(x, Decl(objectRestAssignment.ts, 5, 2)) +>ka : Symbol(ka, Decl(objectRestAssignment.ts, 5, 6)) +>nested : Symbol(nested, Decl(objectRestAssignment.ts, 1, 3)) +>y : Symbol(y, Decl(objectRestAssignment.ts, 5, 23)) +>other : Symbol(other, Decl(objectRestAssignment.ts, 2, 3)) +>rest : Symbol(rest, Decl(objectRestAssignment.ts, 3, 3)) +>complex : Symbol(complex, Decl(objectRestAssignment.ts, 4, 3)) + +// should be: +let overEmit: { a: { ka: string, x: string }[], b: { z: string, ki: string, ku: string }, ke: string, ko: string }; +>overEmit : Symbol(overEmit, Decl(objectRestAssignment.ts, 8, 3)) +>a : Symbol(a, Decl(objectRestAssignment.ts, 8, 15)) +>ka : Symbol(ka, Decl(objectRestAssignment.ts, 8, 20)) +>x : Symbol(x, Decl(objectRestAssignment.ts, 8, 32)) +>b : Symbol(b, Decl(objectRestAssignment.ts, 8, 47)) +>z : Symbol(z, Decl(objectRestAssignment.ts, 8, 52)) +>ki : Symbol(ki, Decl(objectRestAssignment.ts, 8, 63)) +>ku : Symbol(ku, Decl(objectRestAssignment.ts, 8, 75)) +>ke : Symbol(ke, Decl(objectRestAssignment.ts, 8, 89)) +>ko : Symbol(ko, Decl(objectRestAssignment.ts, 8, 101)) + +// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; +>a : Symbol(a, Decl(objectRestAssignment.ts, 8, 15)) +>nested2 : Symbol(nested2, Decl(objectRestAssignment.ts, 11, 11)) +>y : Symbol(y, Decl(objectRestAssignment.ts, 11, 25)) +>b : Symbol(b, Decl(objectRestAssignment.ts, 8, 47)) +>z : Symbol(z, Decl(objectRestAssignment.ts, 11, 37)) +>c : Symbol(c, Decl(objectRestAssignment.ts, 11, 40)) +>rest2 : Symbol(rest2, Decl(objectRestAssignment.ts, 11, 48)) +>overEmit : Symbol(overEmit, Decl(objectRestAssignment.ts, 8, 3)) + +({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); +>a : Symbol(a, Decl(objectRestAssignment.ts, 12, 2)) +>nested2 : Symbol(nested2, Decl(objectRestAssignment.ts, 11, 11)) +>y : Symbol(y, Decl(objectRestAssignment.ts, 11, 25)) +>b : Symbol(b, Decl(objectRestAssignment.ts, 12, 29)) +>z : Symbol(z, Decl(objectRestAssignment.ts, 12, 34)) +>c : Symbol(c, Decl(objectRestAssignment.ts, 11, 40)) +>rest2 : Symbol(rest2, Decl(objectRestAssignment.ts, 11, 48)) +>overEmit : Symbol(overEmit, Decl(objectRestAssignment.ts, 8, 3)) + diff --git a/tests/baselines/reference/objectRestAssignment.types b/tests/baselines/reference/objectRestAssignment.types new file mode 100644 index 00000000000..b51260736ad --- /dev/null +++ b/tests/baselines/reference/objectRestAssignment.types @@ -0,0 +1,75 @@ +=== tests/cases/conformance/types/rest/objectRestAssignment.ts === +let ka: any; +>ka : any + +let nested: { ki }; +>nested : { ki: any; } +>ki : any + +let other: number; +>other : number + +let rest: { }; +>rest : {} + +let complex: { x: { ka, ki }, y: number }; +>complex : { x: { ka: any; ki: any; }; y: number; } +>x : { ka: any; ki: any; } +>ka : any +>ki : any +>y : number + +({x: { ka, ...nested }, y: other, ...rest} = complex); +>({x: { ka, ...nested }, y: other, ...rest} = complex) : { x: { ka: any; ki: any; }; y: number; } +>{x: { ka, ...nested }, y: other, ...rest} = complex : { x: { ka: any; ki: any; }; y: number; } +>{x: { ka, ...nested }, y: other, ...rest} : { x: { ki: any; ka: any; }; y: number; } +>x : { ki: any; ka: any; } +>{ ka, ...nested } : { ki: any; ka: any; } +>ka : any +>nested : { ki: any; } +>y : number +>other : number +>rest : {} +>complex : { x: { ka: any; ki: any; }; y: number; } + +// should be: +let overEmit: { a: { ka: string, x: string }[], b: { z: string, ki: string, ku: string }, ke: string, ko: string }; +>overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } +>a : { ka: string; x: string; }[] +>ka : string +>x : string +>b : { z: string; ki: string; ku: string; } +>z : string +>ki : string +>ku : string +>ke : string +>ko : string + +// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; +>a : any +>nested2 : { ka: string; x: string; } +>y : { ka: string; x: string; }[] +>b : any +>z : string +>c : { ki: string; ku: string; } +>rest2 : { ke: string; ko: string; } +>overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } + +({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); +>({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit) : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } +>{ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } +>{ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } : { ke: string; ko: string; a: { ka: string; x: string; }[]; b: { ki: string; ku: string; z: string; }; } +>a : { ka: string; x: string; }[] +>[{ ...nested2 }, ...y] : { ka: string; x: string; }[] +>{ ...nested2 } : { ka: string; x: string; } +>nested2 : { ka: string; x: string; } +>...y : { ka: string; x: string; } +>y : { ka: string; x: string; }[] +>b : { ki: string; ku: string; z: string; } +>{ z, ...c } : { ki: string; ku: string; z: string; } +>z : string +>c : { ki: string; ku: string; } +>rest2 : { ke: string; ko: string; } +>overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } + diff --git a/tests/baselines/reference/objectRestForOf.js b/tests/baselines/reference/objectRestForOf.js new file mode 100644 index 00000000000..fd81f77512e --- /dev/null +++ b/tests/baselines/reference/objectRestForOf.js @@ -0,0 +1,48 @@ +//// [objectRestForOf.ts] +let array: { x: number, y: string }[]; +for (let { x, ...restOf } of array) { + [x, restOf]; +} +let xx: number; +let rrestOff: { y: string }; +for ({ x: xx, ...rrestOff } of array ) { + [xx, rrestOff]; +} +for (const norest of array.map(a => ({ ...a, x: 'a string' }))) { + [norest.x, norest.y]; + // x is now a string. who knows why. +} + + +//// [objectRestForOf.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +let array; +for (let _a of array) { + let { x } = _a, restOf = __rest(_a, ["x"]); + [x, restOf]; +} +let xx; +let rrestOff; +for (let _b of array) { + ({ x: xx } = _b, rrestOff = __rest(_b, ["x"])); + [xx, rrestOff]; +} +for (const norest of array.map(a => (__assign({}, a, { x: 'a string' })))) { + [norest.x, norest.y]; +} diff --git a/tests/baselines/reference/objectRestForOf.symbols b/tests/baselines/reference/objectRestForOf.symbols new file mode 100644 index 00000000000..f3786fed55f --- /dev/null +++ b/tests/baselines/reference/objectRestForOf.symbols @@ -0,0 +1,52 @@ +=== tests/cases/conformance/types/rest/objectRestForOf.ts === +let array: { x: number, y: string }[]; +>array : Symbol(array, Decl(objectRestForOf.ts, 0, 3)) +>x : Symbol(x, Decl(objectRestForOf.ts, 0, 12)) +>y : Symbol(y, Decl(objectRestForOf.ts, 0, 23)) + +for (let { x, ...restOf } of array) { +>x : Symbol(x, Decl(objectRestForOf.ts, 1, 10)) +>restOf : Symbol(restOf, Decl(objectRestForOf.ts, 1, 13)) +>array : Symbol(array, Decl(objectRestForOf.ts, 0, 3)) + + [x, restOf]; +>x : Symbol(x, Decl(objectRestForOf.ts, 1, 10)) +>restOf : Symbol(restOf, Decl(objectRestForOf.ts, 1, 13)) +} +let xx: number; +>xx : Symbol(xx, Decl(objectRestForOf.ts, 4, 3)) + +let rrestOff: { y: string }; +>rrestOff : Symbol(rrestOff, Decl(objectRestForOf.ts, 5, 3)) +>y : Symbol(y, Decl(objectRestForOf.ts, 5, 15)) + +for ({ x: xx, ...rrestOff } of array ) { +>x : Symbol(x, Decl(objectRestForOf.ts, 6, 6)) +>xx : Symbol(xx, Decl(objectRestForOf.ts, 4, 3)) +>rrestOff : Symbol(rrestOff, Decl(objectRestForOf.ts, 5, 3)) +>array : Symbol(array, Decl(objectRestForOf.ts, 0, 3)) + + [xx, rrestOff]; +>xx : Symbol(xx, Decl(objectRestForOf.ts, 4, 3)) +>rrestOff : Symbol(rrestOff, Decl(objectRestForOf.ts, 5, 3)) +} +for (const norest of array.map(a => ({ ...a, x: 'a string' }))) { +>norest : Symbol(norest, Decl(objectRestForOf.ts, 9, 10)) +>array.map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>array : Symbol(array, Decl(objectRestForOf.ts, 0, 3)) +>map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>a : Symbol(a, Decl(objectRestForOf.ts, 9, 31)) +>a : Symbol(a, Decl(objectRestForOf.ts, 9, 31)) +>x : Symbol(x, Decl(objectRestForOf.ts, 9, 44)) + + [norest.x, norest.y]; +>norest.x : Symbol(x, Decl(objectRestForOf.ts, 9, 44)) +>norest : Symbol(norest, Decl(objectRestForOf.ts, 9, 10)) +>x : Symbol(x, Decl(objectRestForOf.ts, 9, 44)) +>norest.y : Symbol(y, Decl(objectRestForOf.ts, 0, 23)) +>norest : Symbol(norest, Decl(objectRestForOf.ts, 9, 10)) +>y : Symbol(y, Decl(objectRestForOf.ts, 0, 23)) + + // x is now a string. who knows why. +} + diff --git a/tests/baselines/reference/objectRestForOf.types b/tests/baselines/reference/objectRestForOf.types new file mode 100644 index 00000000000..2fde7566c74 --- /dev/null +++ b/tests/baselines/reference/objectRestForOf.types @@ -0,0 +1,61 @@ +=== tests/cases/conformance/types/rest/objectRestForOf.ts === +let array: { x: number, y: string }[]; +>array : { x: number; y: string; }[] +>x : number +>y : string + +for (let { x, ...restOf } of array) { +>x : number +>restOf : { y: string; } +>array : { x: number; y: string; }[] + + [x, restOf]; +>[x, restOf] : (number | { y: string; })[] +>x : number +>restOf : { y: string; } +} +let xx: number; +>xx : number + +let rrestOff: { y: string }; +>rrestOff : { y: string; } +>y : string + +for ({ x: xx, ...rrestOff } of array ) { +>{ x: xx, ...rrestOff } : { y: string; x: number; } +>x : { x: number; y: string; } +>xx : number +>rrestOff : { y: string; } +>array : { x: number; y: string; }[] + + [xx, rrestOff]; +>[xx, rrestOff] : (number | { y: string; })[] +>xx : number +>rrestOff : { y: string; } +} +for (const norest of array.map(a => ({ ...a, x: 'a string' }))) { +>norest : { x: string; y: string; } +>array.map(a => ({ ...a, x: 'a string' })) : { x: string; y: string; }[] +>array.map : { (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): U[]; } +>array : { x: number; y: string; }[] +>map : { (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U, U]; (this: [{ x: number; y: string; }, { x: number; y: string; }], callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: { x: number; y: string; }, index: number, array: { x: number; y: string; }[]) => U, thisArg?: any): U[]; } +>a => ({ ...a, x: 'a string' }) : (a: { x: number; y: string; }) => { x: string; y: string; } +>a : { x: number; y: string; } +>({ ...a, x: 'a string' }) : { x: string; y: string; } +>{ ...a, x: 'a string' } : { x: string; y: string; } +>a : { x: number; y: string; } +>x : string +>'a string' : "a string" + + [norest.x, norest.y]; +>[norest.x, norest.y] : string[] +>norest.x : string +>norest : { x: string; y: string; } +>x : string +>norest.y : string +>norest : { x: string; y: string; } +>y : string + + // x is now a string. who knows why. +} + diff --git a/tests/baselines/reference/objectRestNegative.errors.txt b/tests/baselines/reference/objectRestNegative.errors.txt new file mode 100644 index 00000000000..6e65af4bdc1 --- /dev/null +++ b/tests/baselines/reference/objectRestNegative.errors.txt @@ -0,0 +1,51 @@ +tests/cases/conformance/types/rest/objectRestNegative.ts(2,10): error TS2462: A rest element must be last in a destructuring pattern +tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. + Types of property 'a' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/conformance/types/rest/objectRestNegative.ts(9,31): error TS2462: A rest element must be last in a destructuring pattern +tests/cases/conformance/types/rest/objectRestNegative.ts(11,30): error TS7008: Member 'x' implicitly has an 'any' type. +tests/cases/conformance/types/rest/objectRestNegative.ts(11,33): error TS7008: Member 'y' implicitly has an 'any' type. +tests/cases/conformance/types/rest/objectRestNegative.ts(12,17): error TS2700: Rest types may only be created from object types. +tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: The target of an object rest assignment must be a variable or a property access. +tests/cases/conformance/types/rest/objectRestNegative.ts(19,90): error TS2339: Property 'anythingGoes' does not exist on type '{ [x: string]: any; }'. + + +==== tests/cases/conformance/types/rest/objectRestNegative.ts (8 errors) ==== + let o = { a: 1, b: 'no' }; + var { ...mustBeLast, a } = o; + ~~~~~~~~~~ +!!! error TS2462: A rest element must be last in a destructuring pattern + + var b: string; + let notAssignable: { a: string }; + ({ b, ...notAssignable } = o); + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. +!!! error TS2322: Types of property 'a' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. + + + function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { + ~~~~~~~~~~ +!!! error TS2462: A rest element must be last in a destructuring pattern + } + function generic(t: T) { + ~~ +!!! error TS7008: Member 'x' implicitly has an 'any' type. + ~ +!!! error TS7008: Member 'y' implicitly has an 'any' type. + let { x, ...rest } = t; + ~~~~ +!!! error TS2700: Rest types may only be created from object types. + return rest; + } + + let rest: { b: string } + ({a, ...rest.b + rest.b} = o); + ~~~~~~~~~~~~~~~ +!!! error TS2701: The target of an object rest assignment must be a variable or a property access. + + var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; + ~~~~~~~~~~~~ +!!! error TS2339: Property 'anythingGoes' does not exist on type '{ [x: string]: any; }'. + \ No newline at end of file diff --git a/tests/baselines/reference/objectRestNegative.js b/tests/baselines/reference/objectRestNegative.js new file mode 100644 index 00000000000..19559e865f2 --- /dev/null +++ b/tests/baselines/reference/objectRestNegative.js @@ -0,0 +1,50 @@ +//// [objectRestNegative.ts] +let o = { a: 1, b: 'no' }; +var { ...mustBeLast, a } = o; + +var b: string; +let notAssignable: { a: string }; +({ b, ...notAssignable } = o); + + +function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { +} +function generic(t: T) { + let { x, ...rest } = t; + return rest; +} + +let rest: { b: string } +({a, ...rest.b + rest.b} = o); + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; + + +//// [objectRestNegative.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var o = { a: 1, b: 'no' }; +var a = o.a; +var b; +var notAssignable; +(b = o.b, o, notAssignable = __rest(o, ["b"])); +function stillMustBeLast(_a) { + var a = _a.a; +} +function generic(t) { + var x = t.x, rest = __rest(t, ["x"]); + return rest; +} +var rest; +(a = o.a, o, rest.b + rest.b = __rest(o, ["a"])); +var noContextualType = function (_a) { + var _b = _a.aNumber, aNumber = _b === void 0 ? 12 : _b, notEmptyObject = __rest(_a, ["aNumber"]); + return aNumber + notEmptyObject.anythingGoes; +}; diff --git a/tests/baselines/reference/objectRestParameter.js b/tests/baselines/reference/objectRestParameter.js new file mode 100644 index 00000000000..14e84eddfce --- /dev/null +++ b/tests/baselines/reference/objectRestParameter.js @@ -0,0 +1,50 @@ +//// [objectRestParameter.ts] +function cloneAgain({ a, ...clone }: { a: number, b: string }): void { +} + +declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); +suddenly(({ x: a, ...rest }) => rest.y); +suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); + +class C { + m({ a, ...clone }: { a: number, b: string}): void { + // actually, never mind, don't clone + } + set p({ a, ...clone }: { a: number, b: string}) { + // actually, never mind, don't clone + } +} + + + +//// [objectRestParameter.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +function cloneAgain(_a) { + var { a } = _a, clone = __rest(_a, ["a"]); +} +suddenly((_a) => { + var { x: a } = _a, rest = __rest(_a, ["x"]); + return rest.y; +}); +suddenly((_a = { x: { z: 1, ka: 1 }, y: 'noo' }) => { + var _b = _a.x, { z = 12 } = _b, nested = __rest(_b, ["z"]), rest = __rest(_a, ["x"]); + return rest.y + nested.ka; +}); +class C { + m(_a) { + var { a } = _a, clone = __rest(_a, ["a"]); + // actually, never mind, don't clone + } + set p(_a) { + var { a } = _a, clone = __rest(_a, ["a"]); + // actually, never mind, don't clone + } +} diff --git a/tests/baselines/reference/objectRestParameter.symbols b/tests/baselines/reference/objectRestParameter.symbols new file mode 100644 index 00000000000..c43a8ba5a04 --- /dev/null +++ b/tests/baselines/reference/objectRestParameter.symbols @@ -0,0 +1,68 @@ +=== tests/cases/conformance/types/rest/objectRestParameter.ts === +function cloneAgain({ a, ...clone }: { a: number, b: string }): void { +>cloneAgain : Symbol(cloneAgain, Decl(objectRestParameter.ts, 0, 0)) +>a : Symbol(a, Decl(objectRestParameter.ts, 0, 21)) +>clone : Symbol(clone, Decl(objectRestParameter.ts, 0, 24)) +>a : Symbol(a, Decl(objectRestParameter.ts, 0, 38)) +>b : Symbol(b, Decl(objectRestParameter.ts, 0, 49)) +} + +declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); +>suddenly : Symbol(suddenly, Decl(objectRestParameter.ts, 1, 1)) +>f : Symbol(f, Decl(objectRestParameter.ts, 3, 26)) +>a : Symbol(a, Decl(objectRestParameter.ts, 3, 30)) +>x : Symbol(x, Decl(objectRestParameter.ts, 3, 34)) +>z : Symbol(z, Decl(objectRestParameter.ts, 3, 39)) +>ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) +>y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) + +suddenly(({ x: a, ...rest }) => rest.y); +>suddenly : Symbol(suddenly, Decl(objectRestParameter.ts, 1, 1)) +>x : Symbol(x, Decl(objectRestParameter.ts, 3, 34)) +>a : Symbol(a, Decl(objectRestParameter.ts, 4, 11)) +>rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) +>rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) +>y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) + +suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); +>suddenly : Symbol(suddenly, Decl(objectRestParameter.ts, 1, 1)) +>x : Symbol(x, Decl(objectRestParameter.ts, 3, 34)) +>z : Symbol(z, Decl(objectRestParameter.ts, 5, 16)) +>nested : Symbol(nested, Decl(objectRestParameter.ts, 5, 24)) +>rest : Symbol(rest, Decl(objectRestParameter.ts, 5, 37)) +>x : Symbol(x, Decl(objectRestParameter.ts, 5, 51)) +>z : Symbol(z, Decl(objectRestParameter.ts, 5, 56)) +>ka : Symbol(ka, Decl(objectRestParameter.ts, 5, 62)) +>y : Symbol(y, Decl(objectRestParameter.ts, 5, 71)) +>rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>rest : Symbol(rest, Decl(objectRestParameter.ts, 5, 37)) +>y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>nested.ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) +>nested : Symbol(nested, Decl(objectRestParameter.ts, 5, 24)) +>ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) + +class C { +>C : Symbol(C, Decl(objectRestParameter.ts, 5, 107)) + + m({ a, ...clone }: { a: number, b: string}): void { +>m : Symbol(C.m, Decl(objectRestParameter.ts, 7, 9)) +>a : Symbol(a, Decl(objectRestParameter.ts, 8, 7)) +>clone : Symbol(clone, Decl(objectRestParameter.ts, 8, 10)) +>a : Symbol(a, Decl(objectRestParameter.ts, 8, 24)) +>b : Symbol(b, Decl(objectRestParameter.ts, 8, 35)) + + // actually, never mind, don't clone + } + set p({ a, ...clone }: { a: number, b: string}) { +>p : Symbol(C.p, Decl(objectRestParameter.ts, 10, 5)) +>a : Symbol(a, Decl(objectRestParameter.ts, 11, 11)) +>clone : Symbol(clone, Decl(objectRestParameter.ts, 11, 14)) +>a : Symbol(a, Decl(objectRestParameter.ts, 11, 28)) +>b : Symbol(b, Decl(objectRestParameter.ts, 11, 39)) + + // actually, never mind, don't clone + } +} + + diff --git a/tests/baselines/reference/objectRestParameter.types b/tests/baselines/reference/objectRestParameter.types new file mode 100644 index 00000000000..56e7352870f --- /dev/null +++ b/tests/baselines/reference/objectRestParameter.types @@ -0,0 +1,79 @@ +=== tests/cases/conformance/types/rest/objectRestParameter.ts === +function cloneAgain({ a, ...clone }: { a: number, b: string }): void { +>cloneAgain : ({a, ...clone}: { a: number; b: string; }) => void +>a : number +>clone : { b: string; } +>a : number +>b : string +} + +declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); +>suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any +>f : (a: { x: { z: any; ka: any; }; y: string; }) => void +>a : { x: { z: any; ka: any; }; y: string; } +>x : { z: any; ka: any; } +>z : any +>ka : any +>y : string + +suddenly(({ x: a, ...rest }) => rest.y); +>suddenly(({ x: a, ...rest }) => rest.y) : any +>suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any +>({ x: a, ...rest }) => rest.y : ({x: a, ...rest}: { x: { z: any; ka: any; }; y: string; }) => string +>x : any +>a : { z: any; ka: any; } +>rest : { y: string; } +>rest.y : string +>rest : { y: string; } +>y : string + +suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); +>suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka) : any +>suddenly : (f: (a: { x: { z: any; ka: any; }; y: string; }) => void) => any +>({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka : ({x: {z, ...nested}, ...rest}?: { x: { z: any; ka: any; }; y: string; }) => string +>x : any +>z : any +>12 : 12 +>nested : { ka: any; } +>rest : { y: string; } +>{ x: { z: 1, ka: 1 }, y: 'noo' } : { x: { z: number; ka: number; }; y: string; } +>x : { z: number; ka: number; } +>{ z: 1, ka: 1 } : { z: number; ka: number; } +>z : number +>1 : 1 +>ka : number +>1 : 1 +>y : string +>'noo' : "noo" +>rest.y + nested.ka : string +>rest.y : string +>rest : { y: string; } +>y : string +>nested.ka : any +>nested : { ka: any; } +>ka : any + +class C { +>C : C + + m({ a, ...clone }: { a: number, b: string}): void { +>m : ({a, ...clone}: { a: number; b: string; }) => void +>a : number +>clone : { b: string; } +>a : number +>b : string + + // actually, never mind, don't clone + } + set p({ a, ...clone }: { a: number, b: string}) { +>p : { a: number; b: string; } +>a : number +>clone : { b: string; } +>a : number +>b : string + + // actually, never mind, don't clone + } +} + + diff --git a/tests/baselines/reference/objectSpread.js b/tests/baselines/reference/objectSpread.js new file mode 100644 index 00000000000..4305e17ab31 --- /dev/null +++ b/tests/baselines/reference/objectSpread.js @@ -0,0 +1,151 @@ +//// [objectSpread.ts] +let o = { a: 1, b: 'no' } +let o2 = { b: 'yes', c: true } +let swap = { a: 'yes', b: -1 }; + +let addAfter: { a: number, b: string, c: boolean } = + { ...o, c: false } +let addBefore: { a: number, b: string, c: boolean } = + { c: false, ...o } +// Note: ignore still changes the order that properties are printed +let ignore: { a: number, b: string } = + { b: 'ignored', ...o } +let override: { a: number, b: string } = + { ...o, b: 'override' } +let nested: { a: number, b: boolean, c: string } = + { ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' } +let combined: { a: number, b: string, c: boolean } = + { ...o, ...o2 } +let combinedBefore: { a: number, b: string, c: boolean } = + { b: 'ok', ...o, ...o2 } +let combinedMid: { a: number, b: string, c: boolean } = + { ...o, b: 'ok', ...o2 } +let combinedAfter: { a: number, b: string, c: boolean } = + { ...o, ...o2, b: 'ok' } +let combinedNested: { a: number, b: boolean, c: string, d: string } = + { ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } } +let combinedNestedChangeType: { a: number, b: boolean, c: number } = + { ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } +let propertyNested: { a: { a: number, b: string } } = + { a: { ... o } } +// accessors don't copy the descriptor +// (which means that readonly getters become read/write properties) +let op = { get a () { return 6 } }; +let getter: { a: number, c: number } = + { ...op, c: 7 } +getter.a = 12; + +// functions result in { } +let spreadFunc = { ...(function () { }) }; + +// any results in any +let anything: any; +let spreadAny = { ...anything }; + +// methods are not enumerable +class C { p = 1; m() { } } +let c: C = new C() +let spreadC: { p: number } = { ...c } + +// own methods are enumerable +let cplus: { p: number, plus(): void } = { ...c, plus() { return this.p + 1; } }; +cplus.plus(); + +// new field's type conflicting with existing field is OK +let changeTypeAfter: { a: string, b: string } = + { ...o, a: 'wrong type?' } +let changeTypeBefore: { a: number, b: string } = + { a: 'wrong type?', ...o }; +let changeTypeBoth: { a: string, b: number } = + { ...o, ...swap }; + +// optional +let definiteBoolean: { sn: boolean }; +let definiteString: { sn: string }; +let optionalString: { sn?: string }; +let optionalNumber: { sn?: number }; +let optionalUnionStops: { sn: string | number | boolean } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + +// computed property +let computedFirst: { a: number, b: string, "before everything": number } = + { ['before everything']: 12, ...o, b: 'yes' } +let computedMiddle: { a: number, b: string, c: boolean, "in the middle": number } = + { ...o, ['in the middle']: 13, b: 'maybe?', ...o2 } +let computedAfter: { a: number, b: string, "at the end": number } = + { ...o, b: 'yeah', ['at the end']: 14 } +// shortcut syntax +let a = 12; +let shortCutted: { a: number, b: string } = { ...o, a } + + + +//// [objectSpread.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var o = { a: 1, b: 'no' }; +var o2 = { b: 'yes', c: true }; +var swap = { a: 'yes', b: -1 }; +var addAfter = __assign({}, o, { c: false }); +var addBefore = __assign({ c: false }, o); +// Note: ignore still changes the order that properties are printed +var ignore = __assign({ b: 'ignored' }, o); +var override = __assign({}, o, { b: 'override' }); +var nested = __assign({}, __assign({ a: 3 }, { b: false, c: 'overriden' }), { c: 'whatever' }); +var combined = __assign({}, o, o2); +var combinedBefore = __assign({ b: 'ok' }, o, o2); +var combinedMid = __assign({}, o, { b: 'ok' }, o2); +var combinedAfter = __assign({}, o, o2, { b: 'ok' }); +var combinedNested = __assign({}, __assign({ a: 4 }, { b: false, c: 'overriden' }), { d: 'actually new' }, { a: 5, d: 'maybe new' }); +var combinedNestedChangeType = __assign({}, __assign({ a: 1 }, { b: false, c: 'overriden' }), { c: -1 }); +var propertyNested = { a: __assign({}, o) }; +// accessors don't copy the descriptor +// (which means that readonly getters become read/write properties) +var op = { get a() { return 6; } }; +var getter = __assign({}, op, { c: 7 }); +getter.a = 12; +// functions result in { } +var spreadFunc = __assign({}, (function () { })); +// any results in any +var anything; +var spreadAny = __assign({}, anything); +// methods are not enumerable +var C = (function () { + function C() { + this.p = 1; + } + C.prototype.m = function () { }; + return C; +}()); +var c = new C(); +var spreadC = __assign({}, c); +// own methods are enumerable +var cplus = __assign({}, c, { plus: function () { return this.p + 1; } }); +cplus.plus(); +// new field's type conflicting with existing field is OK +var changeTypeAfter = __assign({}, o, { a: 'wrong type?' }); +var changeTypeBefore = __assign({ a: 'wrong type?' }, o); +var changeTypeBoth = __assign({}, o, swap); +// optional +var definiteBoolean; +var definiteString; +var optionalString; +var optionalNumber; +var optionalUnionStops = __assign({}, definiteBoolean, definiteString, optionalNumber); +var optionalUnionDuplicates = __assign({}, definiteBoolean, definiteString, optionalString, optionalNumber); +var allOptional = __assign({}, optionalString, optionalNumber); +// computed property +var computedFirst = __assign((_a = {}, _a['before everything'] = 12, _a), o, { b: 'yes' }); +var computedMiddle = __assign({}, o, (_b = {}, _b['in the middle'] = 13, _b.b = 'maybe?', _b), o2); +var computedAfter = __assign({}, o, (_c = { b: 'yeah' }, _c['at the end'] = 14, _c)); +// shortcut syntax +var a = 12; +var shortCutted = __assign({}, o, { a: a }); +var _a, _b, _c; diff --git a/tests/baselines/reference/objectSpread.symbols b/tests/baselines/reference/objectSpread.symbols new file mode 100644 index 00000000000..35c10faa9c0 --- /dev/null +++ b/tests/baselines/reference/objectSpread.symbols @@ -0,0 +1,319 @@ +=== tests/cases/conformance/types/spread/objectSpread.ts === +let o = { a: 1, b: 'no' } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 0, 9)) +>b : Symbol(b, Decl(objectSpread.ts, 0, 15)) + +let o2 = { b: 'yes', c: true } +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 1, 10)) +>c : Symbol(c, Decl(objectSpread.ts, 1, 20)) + +let swap = { a: 'yes', b: -1 }; +>swap : Symbol(swap, Decl(objectSpread.ts, 2, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 2, 12)) +>b : Symbol(b, Decl(objectSpread.ts, 2, 22)) + +let addAfter: { a: number, b: string, c: boolean } = +>addAfter : Symbol(addAfter, Decl(objectSpread.ts, 4, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 4, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 4, 26)) +>c : Symbol(c, Decl(objectSpread.ts, 4, 37)) + + { ...o, c: false } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>c : Symbol(c, Decl(objectSpread.ts, 5, 11)) + +let addBefore: { a: number, b: string, c: boolean } = +>addBefore : Symbol(addBefore, Decl(objectSpread.ts, 6, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 6, 16)) +>b : Symbol(b, Decl(objectSpread.ts, 6, 27)) +>c : Symbol(c, Decl(objectSpread.ts, 6, 38)) + + { c: false, ...o } +>c : Symbol(c, Decl(objectSpread.ts, 7, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) + +// Note: ignore still changes the order that properties are printed +let ignore: { a: number, b: string } = +>ignore : Symbol(ignore, Decl(objectSpread.ts, 9, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 9, 13)) +>b : Symbol(b, Decl(objectSpread.ts, 9, 24)) + + { b: 'ignored', ...o } +>b : Symbol(b, Decl(objectSpread.ts, 10, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) + +let override: { a: number, b: string } = +>override : Symbol(override, Decl(objectSpread.ts, 11, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 11, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 11, 26)) + + { ...o, b: 'override' } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 12, 11)) + +let nested: { a: number, b: boolean, c: string } = +>nested : Symbol(nested, Decl(objectSpread.ts, 13, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 13, 13)) +>b : Symbol(b, Decl(objectSpread.ts, 13, 24)) +>c : Symbol(c, Decl(objectSpread.ts, 13, 36)) + + { ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' } +>a : Symbol(a, Decl(objectSpread.ts, 14, 10)) +>b : Symbol(b, Decl(objectSpread.ts, 14, 21)) +>c : Symbol(c, Decl(objectSpread.ts, 14, 31)) +>c : Symbol(c, Decl(objectSpread.ts, 14, 51)) + +let combined: { a: number, b: string, c: boolean } = +>combined : Symbol(combined, Decl(objectSpread.ts, 15, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 15, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 15, 26)) +>c : Symbol(c, Decl(objectSpread.ts, 15, 37)) + + { ...o, ...o2 } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) + +let combinedBefore: { a: number, b: string, c: boolean } = +>combinedBefore : Symbol(combinedBefore, Decl(objectSpread.ts, 17, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 17, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 17, 32)) +>c : Symbol(c, Decl(objectSpread.ts, 17, 43)) + + { b: 'ok', ...o, ...o2 } +>b : Symbol(b, Decl(objectSpread.ts, 18, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) + +let combinedMid: { a: number, b: string, c: boolean } = +>combinedMid : Symbol(combinedMid, Decl(objectSpread.ts, 19, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 19, 18)) +>b : Symbol(b, Decl(objectSpread.ts, 19, 29)) +>c : Symbol(c, Decl(objectSpread.ts, 19, 40)) + + { ...o, b: 'ok', ...o2 } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 20, 11)) +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) + +let combinedAfter: { a: number, b: string, c: boolean } = +>combinedAfter : Symbol(combinedAfter, Decl(objectSpread.ts, 21, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 21, 20)) +>b : Symbol(b, Decl(objectSpread.ts, 21, 31)) +>c : Symbol(c, Decl(objectSpread.ts, 21, 42)) + + { ...o, ...o2, b: 'ok' } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 22, 18)) + +let combinedNested: { a: number, b: boolean, c: string, d: string } = +>combinedNested : Symbol(combinedNested, Decl(objectSpread.ts, 23, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 23, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 23, 32)) +>c : Symbol(c, Decl(objectSpread.ts, 23, 44)) +>d : Symbol(d, Decl(objectSpread.ts, 23, 55)) + + { ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } } +>a : Symbol(a, Decl(objectSpread.ts, 24, 10)) +>b : Symbol(b, Decl(objectSpread.ts, 24, 21)) +>c : Symbol(c, Decl(objectSpread.ts, 24, 31)) +>d : Symbol(d, Decl(objectSpread.ts, 24, 51)) +>a : Symbol(a, Decl(objectSpread.ts, 24, 75)) +>d : Symbol(d, Decl(objectSpread.ts, 24, 81)) + +let combinedNestedChangeType: { a: number, b: boolean, c: number } = +>combinedNestedChangeType : Symbol(combinedNestedChangeType, Decl(objectSpread.ts, 25, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 25, 31)) +>b : Symbol(b, Decl(objectSpread.ts, 25, 42)) +>c : Symbol(c, Decl(objectSpread.ts, 25, 54)) + + { ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } +>a : Symbol(a, Decl(objectSpread.ts, 26, 10)) +>b : Symbol(b, Decl(objectSpread.ts, 26, 21)) +>c : Symbol(c, Decl(objectSpread.ts, 26, 31)) +>c : Symbol(c, Decl(objectSpread.ts, 26, 51)) + +let propertyNested: { a: { a: number, b: string } } = +>propertyNested : Symbol(propertyNested, Decl(objectSpread.ts, 27, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 27, 21)) +>a : Symbol(a, Decl(objectSpread.ts, 27, 26)) +>b : Symbol(b, Decl(objectSpread.ts, 27, 37)) + + { a: { ... o } } +>a : Symbol(a, Decl(objectSpread.ts, 28, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) + +// accessors don't copy the descriptor +// (which means that readonly getters become read/write properties) +let op = { get a () { return 6 } }; +>op : Symbol(op, Decl(objectSpread.ts, 31, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 31, 10)) + +let getter: { a: number, c: number } = +>getter : Symbol(getter, Decl(objectSpread.ts, 32, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 32, 13)) +>c : Symbol(c, Decl(objectSpread.ts, 32, 24)) + + { ...op, c: 7 } +>op : Symbol(op, Decl(objectSpread.ts, 31, 3)) +>c : Symbol(c, Decl(objectSpread.ts, 33, 12)) + +getter.a = 12; +>getter.a : Symbol(a, Decl(objectSpread.ts, 32, 13)) +>getter : Symbol(getter, Decl(objectSpread.ts, 32, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 32, 13)) + +// functions result in { } +let spreadFunc = { ...(function () { }) }; +>spreadFunc : Symbol(spreadFunc, Decl(objectSpread.ts, 37, 3)) + +// any results in any +let anything: any; +>anything : Symbol(anything, Decl(objectSpread.ts, 40, 3)) + +let spreadAny = { ...anything }; +>spreadAny : Symbol(spreadAny, Decl(objectSpread.ts, 41, 3)) +>anything : Symbol(anything, Decl(objectSpread.ts, 40, 3)) + +// methods are not enumerable +class C { p = 1; m() { } } +>C : Symbol(C, Decl(objectSpread.ts, 41, 32)) +>p : Symbol(C.p, Decl(objectSpread.ts, 44, 9)) +>m : Symbol(C.m, Decl(objectSpread.ts, 44, 16)) + +let c: C = new C() +>c : Symbol(c, Decl(objectSpread.ts, 45, 3)) +>C : Symbol(C, Decl(objectSpread.ts, 41, 32)) +>C : Symbol(C, Decl(objectSpread.ts, 41, 32)) + +let spreadC: { p: number } = { ...c } +>spreadC : Symbol(spreadC, Decl(objectSpread.ts, 46, 3)) +>p : Symbol(p, Decl(objectSpread.ts, 46, 14)) +>c : Symbol(c, Decl(objectSpread.ts, 45, 3)) + +// own methods are enumerable +let cplus: { p: number, plus(): void } = { ...c, plus() { return this.p + 1; } }; +>cplus : Symbol(cplus, Decl(objectSpread.ts, 49, 3)) +>p : Symbol(p, Decl(objectSpread.ts, 49, 12)) +>plus : Symbol(plus, Decl(objectSpread.ts, 49, 23)) +>c : Symbol(c, Decl(objectSpread.ts, 45, 3)) +>plus : Symbol(plus, Decl(objectSpread.ts, 49, 48)) + +cplus.plus(); +>cplus.plus : Symbol(plus, Decl(objectSpread.ts, 49, 23)) +>cplus : Symbol(cplus, Decl(objectSpread.ts, 49, 3)) +>plus : Symbol(plus, Decl(objectSpread.ts, 49, 23)) + +// new field's type conflicting with existing field is OK +let changeTypeAfter: { a: string, b: string } = +>changeTypeAfter : Symbol(changeTypeAfter, Decl(objectSpread.ts, 53, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 53, 22)) +>b : Symbol(b, Decl(objectSpread.ts, 53, 33)) + + { ...o, a: 'wrong type?' } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 54, 11)) + +let changeTypeBefore: { a: number, b: string } = +>changeTypeBefore : Symbol(changeTypeBefore, Decl(objectSpread.ts, 55, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 55, 23)) +>b : Symbol(b, Decl(objectSpread.ts, 55, 34)) + + { a: 'wrong type?', ...o }; +>a : Symbol(a, Decl(objectSpread.ts, 56, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) + +let changeTypeBoth: { a: string, b: number } = +>changeTypeBoth : Symbol(changeTypeBoth, Decl(objectSpread.ts, 57, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 57, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 57, 32)) + + { ...o, ...swap }; +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>swap : Symbol(swap, Decl(objectSpread.ts, 2, 3)) + +// optional +let definiteBoolean: { sn: boolean }; +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpread.ts, 61, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 61, 22)) + +let definiteString: { sn: string }; +>definiteString : Symbol(definiteString, Decl(objectSpread.ts, 62, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 62, 21)) + +let optionalString: { sn?: string }; +>optionalString : Symbol(optionalString, Decl(objectSpread.ts, 63, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 63, 21)) + +let optionalNumber: { sn?: number }; +>optionalNumber : Symbol(optionalNumber, Decl(objectSpread.ts, 64, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 64, 21)) + +let optionalUnionStops: { sn: string | number | boolean } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +>optionalUnionStops : Symbol(optionalUnionStops, Decl(objectSpread.ts, 65, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 65, 25)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpread.ts, 61, 3)) +>definiteString : Symbol(definiteString, Decl(objectSpread.ts, 62, 3)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpread.ts, 64, 3)) + +let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +>optionalUnionDuplicates : Symbol(optionalUnionDuplicates, Decl(objectSpread.ts, 66, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 66, 30)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpread.ts, 61, 3)) +>definiteString : Symbol(definiteString, Decl(objectSpread.ts, 62, 3)) +>optionalString : Symbol(optionalString, Decl(objectSpread.ts, 63, 3)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpread.ts, 64, 3)) + +let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; +>allOptional : Symbol(allOptional, Decl(objectSpread.ts, 67, 3)) +>sn : Symbol(sn, Decl(objectSpread.ts, 67, 18)) +>optionalString : Symbol(optionalString, Decl(objectSpread.ts, 63, 3)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpread.ts, 64, 3)) + +// computed property +let computedFirst: { a: number, b: string, "before everything": number } = +>computedFirst : Symbol(computedFirst, Decl(objectSpread.ts, 70, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 70, 20)) +>b : Symbol(b, Decl(objectSpread.ts, 70, 31)) + + { ['before everything']: 12, ...o, b: 'yes' } +>'before everything' : Symbol(['before everything'], Decl(objectSpread.ts, 71, 5)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 71, 38)) + +let computedMiddle: { a: number, b: string, c: boolean, "in the middle": number } = +>computedMiddle : Symbol(computedMiddle, Decl(objectSpread.ts, 72, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 72, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 72, 32)) +>c : Symbol(c, Decl(objectSpread.ts, 72, 43)) + + { ...o, ['in the middle']: 13, b: 'maybe?', ...o2 } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>'in the middle' : Symbol(['in the middle'], Decl(objectSpread.ts, 73, 11)) +>b : Symbol(b, Decl(objectSpread.ts, 73, 34)) +>o2 : Symbol(o2, Decl(objectSpread.ts, 1, 3)) + +let computedAfter: { a: number, b: string, "at the end": number } = +>computedAfter : Symbol(computedAfter, Decl(objectSpread.ts, 74, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 74, 20)) +>b : Symbol(b, Decl(objectSpread.ts, 74, 31)) + + { ...o, b: 'yeah', ['at the end']: 14 } +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>b : Symbol(b, Decl(objectSpread.ts, 75, 11)) +>'at the end' : Symbol(['at the end'], Decl(objectSpread.ts, 75, 22)) + +// shortcut syntax +let a = 12; +>a : Symbol(a, Decl(objectSpread.ts, 77, 3)) + +let shortCutted: { a: number, b: string } = { ...o, a } +>shortCutted : Symbol(shortCutted, Decl(objectSpread.ts, 78, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 78, 18)) +>b : Symbol(b, Decl(objectSpread.ts, 78, 29)) +>o : Symbol(o, Decl(objectSpread.ts, 0, 3)) +>a : Symbol(a, Decl(objectSpread.ts, 78, 51)) + + diff --git a/tests/baselines/reference/objectSpread.types b/tests/baselines/reference/objectSpread.types new file mode 100644 index 00000000000..a571bd0bb63 --- /dev/null +++ b/tests/baselines/reference/objectSpread.types @@ -0,0 +1,410 @@ +=== tests/cases/conformance/types/spread/objectSpread.ts === +let o = { a: 1, b: 'no' } +>o : { a: number; b: string; } +>{ a: 1, b: 'no' } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>'no' : "no" + +let o2 = { b: 'yes', c: true } +>o2 : { b: string; c: boolean; } +>{ b: 'yes', c: true } : { b: string; c: boolean; } +>b : string +>'yes' : "yes" +>c : boolean +>true : true + +let swap = { a: 'yes', b: -1 }; +>swap : { a: string; b: number; } +>{ a: 'yes', b: -1 } : { a: string; b: number; } +>a : string +>'yes' : "yes" +>b : number +>-1 : -1 +>1 : 1 + +let addAfter: { a: number, b: string, c: boolean } = +>addAfter : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { ...o, c: false } +>{ ...o, c: false } : { c: false; a: number; b: string; } +>o : { a: number; b: string; } +>c : boolean +>false : false + +let addBefore: { a: number, b: string, c: boolean } = +>addBefore : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { c: false, ...o } +>{ c: false, ...o } : { a: number; b: string; c: false; } +>c : boolean +>false : false +>o : { a: number; b: string; } + +// Note: ignore still changes the order that properties are printed +let ignore: { a: number, b: string } = +>ignore : { a: number; b: string; } +>a : number +>b : string + + { b: 'ignored', ...o } +>{ b: 'ignored', ...o } : { a: number; b: string; } +>b : string +>'ignored' : "ignored" +>o : { a: number; b: string; } + +let override: { a: number, b: string } = +>override : { a: number; b: string; } +>a : number +>b : string + + { ...o, b: 'override' } +>{ ...o, b: 'override' } : { b: string; a: number; } +>o : { a: number; b: string; } +>b : string +>'override' : "override" + +let nested: { a: number, b: boolean, c: string } = +>nested : { a: number; b: boolean; c: string; } +>a : number +>b : boolean +>c : string + + { ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' } +>{ ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' } : { c: string; b: boolean; a: number; } +>{ a: 3, ...{ b: false, c: 'overriden' } } : { b: boolean; c: string; a: number; } +>a : number +>3 : 3 +>{ b: false, c: 'overriden' } : { b: boolean; c: string; } +>b : boolean +>false : false +>c : string +>'overriden' : "overriden" +>c : string +>'whatever' : "whatever" + +let combined: { a: number, b: string, c: boolean } = +>combined : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { ...o, ...o2 } +>{ ...o, ...o2 } : { b: string; c: boolean; a: number; } +>o : { a: number; b: string; } +>o2 : { b: string; c: boolean; } + +let combinedBefore: { a: number, b: string, c: boolean } = +>combinedBefore : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { b: 'ok', ...o, ...o2 } +>{ b: 'ok', ...o, ...o2 } : { b: string; c: boolean; a: number; } +>b : string +>'ok' : "ok" +>o : { a: number; b: string; } +>o2 : { b: string; c: boolean; } + +let combinedMid: { a: number, b: string, c: boolean } = +>combinedMid : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { ...o, b: 'ok', ...o2 } +>{ ...o, b: 'ok', ...o2 } : { b: string; c: boolean; a: number; } +>o : { a: number; b: string; } +>b : string +>'ok' : "ok" +>o2 : { b: string; c: boolean; } + +let combinedAfter: { a: number, b: string, c: boolean } = +>combinedAfter : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + + { ...o, ...o2, b: 'ok' } +>{ ...o, ...o2, b: 'ok' } : { b: string; c: boolean; a: number; } +>o : { a: number; b: string; } +>o2 : { b: string; c: boolean; } +>b : string +>'ok' : "ok" + +let combinedNested: { a: number, b: boolean, c: string, d: string } = +>combinedNested : { a: number; b: boolean; c: string; d: string; } +>a : number +>b : boolean +>c : string +>d : string + + { ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } } +>{ ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } } : { a: number; d: string; b: boolean; c: string; } +>{ a: 4, ...{ b: false, c: 'overriden' } } : { b: boolean; c: string; a: number; } +>a : number +>4 : 4 +>{ b: false, c: 'overriden' } : { b: boolean; c: string; } +>b : boolean +>false : false +>c : string +>'overriden' : "overriden" +>d : string +>'actually new' : "actually new" +>{ a: 5, d: 'maybe new' } : { a: number; d: string; } +>a : number +>5 : 5 +>d : string +>'maybe new' : "maybe new" + +let combinedNestedChangeType: { a: number, b: boolean, c: number } = +>combinedNestedChangeType : { a: number; b: boolean; c: number; } +>a : number +>b : boolean +>c : number + + { ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } +>{ ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } : { c: number; b: boolean; a: number; } +>{ a: 1, ...{ b: false, c: 'overriden' } } : { b: boolean; c: string; a: number; } +>a : number +>1 : 1 +>{ b: false, c: 'overriden' } : { b: boolean; c: string; } +>b : boolean +>false : false +>c : string +>'overriden' : "overriden" +>c : number +>-1 : -1 +>1 : 1 + +let propertyNested: { a: { a: number, b: string } } = +>propertyNested : { a: { a: number; b: string; }; } +>a : { a: number; b: string; } +>a : number +>b : string + + { a: { ... o } } +>{ a: { ... o } } : { a: { a: number; b: string; }; } +>a : { a: number; b: string; } +>{ ... o } : { a: number; b: string; } +>o : { a: number; b: string; } + +// accessors don't copy the descriptor +// (which means that readonly getters become read/write properties) +let op = { get a () { return 6 } }; +>op : { readonly a: number; } +>{ get a () { return 6 } } : { readonly a: number; } +>a : number +>6 : 6 + +let getter: { a: number, c: number } = +>getter : { a: number; c: number; } +>a : number +>c : number + + { ...op, c: 7 } +>{ ...op, c: 7 } : { c: number; readonly a: number; } +>op : { readonly a: number; } +>c : number +>7 : 7 + +getter.a = 12; +>getter.a = 12 : 12 +>getter.a : number +>getter : { a: number; c: number; } +>a : number +>12 : 12 + +// functions result in { } +let spreadFunc = { ...(function () { }) }; +>spreadFunc : {} +>{ ...(function () { }) } : {} +>(function () { }) : () => void +>function () { } : () => void + +// any results in any +let anything: any; +>anything : any + +let spreadAny = { ...anything }; +>spreadAny : any +>{ ...anything } : any +>anything : any + +// methods are not enumerable +class C { p = 1; m() { } } +>C : C +>p : number +>1 : 1 +>m : () => void + +let c: C = new C() +>c : C +>C : C +>new C() : C +>C : typeof C + +let spreadC: { p: number } = { ...c } +>spreadC : { p: number; } +>p : number +>{ ...c } : { p: number; } +>c : C + +// own methods are enumerable +let cplus: { p: number, plus(): void } = { ...c, plus() { return this.p + 1; } }; +>cplus : { p: number; plus(): void; } +>p : number +>plus : () => void +>{ ...c, plus() { return this.p + 1; } } : { plus(): any; p: number; } +>c : C +>plus : () => any +>this.p + 1 : any +>this.p : any +>this : any +>p : any +>1 : 1 + +cplus.plus(); +>cplus.plus() : void +>cplus.plus : () => void +>cplus : { p: number; plus(): void; } +>plus : () => void + +// new field's type conflicting with existing field is OK +let changeTypeAfter: { a: string, b: string } = +>changeTypeAfter : { a: string; b: string; } +>a : string +>b : string + + { ...o, a: 'wrong type?' } +>{ ...o, a: 'wrong type?' } : { a: string; b: string; } +>o : { a: number; b: string; } +>a : string +>'wrong type?' : "wrong type?" + +let changeTypeBefore: { a: number, b: string } = +>changeTypeBefore : { a: number; b: string; } +>a : number +>b : string + + { a: 'wrong type?', ...o }; +>{ a: 'wrong type?', ...o } : { a: number; b: string; } +>a : string +>'wrong type?' : "wrong type?" +>o : { a: number; b: string; } + +let changeTypeBoth: { a: string, b: number } = +>changeTypeBoth : { a: string; b: number; } +>a : string +>b : number + + { ...o, ...swap }; +>{ ...o, ...swap } : { a: string; b: number; } +>o : { a: number; b: string; } +>swap : { a: string; b: number; } + +// optional +let definiteBoolean: { sn: boolean }; +>definiteBoolean : { sn: boolean; } +>sn : boolean + +let definiteString: { sn: string }; +>definiteString : { sn: string; } +>sn : string + +let optionalString: { sn?: string }; +>optionalString : { sn?: string; } +>sn : string + +let optionalNumber: { sn?: number }; +>optionalNumber : { sn?: number; } +>sn : number + +let optionalUnionStops: { sn: string | number | boolean } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +>optionalUnionStops : { sn: string | number | boolean; } +>sn : string | number | boolean +>{ ...definiteBoolean, ...definiteString, ...optionalNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>optionalNumber : { sn?: number; } + +let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +>optionalUnionDuplicates : { sn: string | number; } +>sn : string | number +>{ ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>optionalString : { sn?: string; } +>optionalNumber : { sn?: number; } + +let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; +>allOptional : { sn?: string | number; } +>sn : string | number +>{ ...optionalString, ...optionalNumber } : { sn?: string | number; } +>optionalString : { sn?: string; } +>optionalNumber : { sn?: number; } + +// computed property +let computedFirst: { a: number, b: string, "before everything": number } = +>computedFirst : { a: number; b: string; "before everything": number; } +>a : number +>b : string + + { ['before everything']: 12, ...o, b: 'yes' } +>{ ['before everything']: 12, ...o, b: 'yes' } : { b: string; a: number; ['before everything']: number; } +>'before everything' : "before everything" +>12 : 12 +>o : { a: number; b: string; } +>b : string +>'yes' : "yes" + +let computedMiddle: { a: number, b: string, c: boolean, "in the middle": number } = +>computedMiddle : { a: number; b: string; c: boolean; "in the middle": number; } +>a : number +>b : string +>c : boolean + + { ...o, ['in the middle']: 13, b: 'maybe?', ...o2 } +>{ ...o, ['in the middle']: 13, b: 'maybe?', ...o2 } : { b: string; c: boolean; ['in the middle']: number; a: number; } +>o : { a: number; b: string; } +>'in the middle' : "in the middle" +>13 : 13 +>b : string +>'maybe?' : "maybe?" +>o2 : { b: string; c: boolean; } + +let computedAfter: { a: number, b: string, "at the end": number } = +>computedAfter : { a: number; b: string; "at the end": number; } +>a : number +>b : string + + { ...o, b: 'yeah', ['at the end']: 14 } +>{ ...o, b: 'yeah', ['at the end']: 14 } : { b: string; ['at the end']: number; a: number; } +>o : { a: number; b: string; } +>b : string +>'yeah' : "yeah" +>'at the end' : "at the end" +>14 : 14 + +// shortcut syntax +let a = 12; +>a : number +>12 : 12 + +let shortCutted: { a: number, b: string } = { ...o, a } +>shortCutted : { a: number; b: string; } +>a : number +>b : string +>{ ...o, a } : { a: number; b: string; } +>o : { a: number; b: string; } +>a : number + + diff --git a/tests/baselines/reference/objectSpreadComputedProperty.js b/tests/baselines/reference/objectSpreadComputedProperty.js new file mode 100644 index 00000000000..90a22ce6ff5 --- /dev/null +++ b/tests/baselines/reference/objectSpreadComputedProperty.js @@ -0,0 +1,31 @@ +//// [objectSpreadComputedProperty.ts] +// fixes #12200 +function f() { + let n: number = 12; + let m: number = 13; + let a: any = null; + const o1 = { ...{}, [n]: n }; + const o2 = { ...{}, [a]: n }; + const o3 = { [a]: n, ...{}, [n]: n, ...{}, [m]: m }; +} + + +//// [objectSpreadComputedProperty.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +// fixes #12200 +function f() { + var n = 12; + var m = 13; + var a = null; + var o1 = __assign({}, (_a = {}, _a[n] = n, _a)); + var o2 = __assign({}, (_b = {}, _b[a] = n, _b)); + var o3 = __assign((_c = {}, _c[a] = n, _c), {}, (_d = {}, _d[n] = n, _d), {}, (_e = {}, _e[m] = m, _e)); + var _a, _b, _c, _d, _e; +} diff --git a/tests/baselines/reference/objectSpreadComputedProperty.symbols b/tests/baselines/reference/objectSpreadComputedProperty.symbols new file mode 100644 index 00000000000..57a0db0962b --- /dev/null +++ b/tests/baselines/reference/objectSpreadComputedProperty.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/types/spread/objectSpreadComputedProperty.ts === +// fixes #12200 +function f() { +>f : Symbol(f, Decl(objectSpreadComputedProperty.ts, 0, 0)) + + let n: number = 12; +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) + + let m: number = 13; +>m : Symbol(m, Decl(objectSpreadComputedProperty.ts, 3, 7)) + + let a: any = null; +>a : Symbol(a, Decl(objectSpreadComputedProperty.ts, 4, 7)) + + const o1 = { ...{}, [n]: n }; +>o1 : Symbol(o1, Decl(objectSpreadComputedProperty.ts, 5, 9)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) + + const o2 = { ...{}, [a]: n }; +>o2 : Symbol(o2, Decl(objectSpreadComputedProperty.ts, 6, 9)) +>a : Symbol(a, Decl(objectSpreadComputedProperty.ts, 4, 7)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) + + const o3 = { [a]: n, ...{}, [n]: n, ...{}, [m]: m }; +>o3 : Symbol(o3, Decl(objectSpreadComputedProperty.ts, 7, 9)) +>a : Symbol(a, Decl(objectSpreadComputedProperty.ts, 4, 7)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) +>n : Symbol(n, Decl(objectSpreadComputedProperty.ts, 2, 7)) +>m : Symbol(m, Decl(objectSpreadComputedProperty.ts, 3, 7)) +>m : Symbol(m, Decl(objectSpreadComputedProperty.ts, 3, 7)) +} + diff --git a/tests/baselines/reference/objectSpreadComputedProperty.types b/tests/baselines/reference/objectSpreadComputedProperty.types new file mode 100644 index 00000000000..287936d4354 --- /dev/null +++ b/tests/baselines/reference/objectSpreadComputedProperty.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/types/spread/objectSpreadComputedProperty.ts === +// fixes #12200 +function f() { +>f : () => void + + let n: number = 12; +>n : number +>12 : 12 + + let m: number = 13; +>m : number +>13 : 13 + + let a: any = null; +>a : any +>null : null + + const o1 = { ...{}, [n]: n }; +>o1 : {} +>{ ...{}, [n]: n } : {} +>{} : {} +>n : number +>n : number + + const o2 = { ...{}, [a]: n }; +>o2 : {} +>{ ...{}, [a]: n } : {} +>{} : {} +>a : any +>n : number + + const o3 = { [a]: n, ...{}, [n]: n, ...{}, [m]: m }; +>o3 : {} +>{ [a]: n, ...{}, [n]: n, ...{}, [m]: m } : {} +>a : any +>n : number +>{} : {} +>n : number +>n : number +>{} : {} +>m : number +>m : number +} + diff --git a/tests/baselines/reference/objectSpreadIndexSignature.js b/tests/baselines/reference/objectSpreadIndexSignature.js new file mode 100644 index 00000000000..22e92e6a844 --- /dev/null +++ b/tests/baselines/reference/objectSpreadIndexSignature.js @@ -0,0 +1,36 @@ +//// [objectSpreadIndexSignature.ts] +interface Indexed { + [n: string]: number; + a: number; +} +interface Indexed2 { + [n: string]: boolean; + c: boolean; +} +let indexed: Indexed; +let indexed2: Indexed2; +let i = { ...indexed, b: 11 }; +// only indexed has indexer, so i[101]: any +i[101]; +let ii = { ...indexed, ...indexed2 }; +// both have indexer, so i[1001]: number | boolean +ii[1001]; + + +//// [objectSpreadIndexSignature.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var indexed; +var indexed2; +var i = __assign({}, indexed, { b: 11 }); +// only indexed has indexer, so i[101]: any +i[101]; +var ii = __assign({}, indexed, indexed2); +// both have indexer, so i[1001]: number | boolean +ii[1001]; diff --git a/tests/baselines/reference/objectSpreadIndexSignature.symbols b/tests/baselines/reference/objectSpreadIndexSignature.symbols new file mode 100644 index 00000000000..cd64b157196 --- /dev/null +++ b/tests/baselines/reference/objectSpreadIndexSignature.symbols @@ -0,0 +1,45 @@ +=== tests/cases/conformance/types/spread/objectSpreadIndexSignature.ts === +interface Indexed { +>Indexed : Symbol(Indexed, Decl(objectSpreadIndexSignature.ts, 0, 0)) + + [n: string]: number; +>n : Symbol(n, Decl(objectSpreadIndexSignature.ts, 1, 5)) + + a: number; +>a : Symbol(Indexed.a, Decl(objectSpreadIndexSignature.ts, 1, 24)) +} +interface Indexed2 { +>Indexed2 : Symbol(Indexed2, Decl(objectSpreadIndexSignature.ts, 3, 1)) + + [n: string]: boolean; +>n : Symbol(n, Decl(objectSpreadIndexSignature.ts, 5, 5)) + + c: boolean; +>c : Symbol(Indexed2.c, Decl(objectSpreadIndexSignature.ts, 5, 25)) +} +let indexed: Indexed; +>indexed : Symbol(indexed, Decl(objectSpreadIndexSignature.ts, 8, 3)) +>Indexed : Symbol(Indexed, Decl(objectSpreadIndexSignature.ts, 0, 0)) + +let indexed2: Indexed2; +>indexed2 : Symbol(indexed2, Decl(objectSpreadIndexSignature.ts, 9, 3)) +>Indexed2 : Symbol(Indexed2, Decl(objectSpreadIndexSignature.ts, 3, 1)) + +let i = { ...indexed, b: 11 }; +>i : Symbol(i, Decl(objectSpreadIndexSignature.ts, 10, 3)) +>indexed : Symbol(indexed, Decl(objectSpreadIndexSignature.ts, 8, 3)) +>b : Symbol(b, Decl(objectSpreadIndexSignature.ts, 10, 21)) + +// only indexed has indexer, so i[101]: any +i[101]; +>i : Symbol(i, Decl(objectSpreadIndexSignature.ts, 10, 3)) + +let ii = { ...indexed, ...indexed2 }; +>ii : Symbol(ii, Decl(objectSpreadIndexSignature.ts, 13, 3)) +>indexed : Symbol(indexed, Decl(objectSpreadIndexSignature.ts, 8, 3)) +>indexed2 : Symbol(indexed2, Decl(objectSpreadIndexSignature.ts, 9, 3)) + +// both have indexer, so i[1001]: number | boolean +ii[1001]; +>ii : Symbol(ii, Decl(objectSpreadIndexSignature.ts, 13, 3)) + diff --git a/tests/baselines/reference/objectSpreadIndexSignature.types b/tests/baselines/reference/objectSpreadIndexSignature.types new file mode 100644 index 00000000000..5eebc2ffa02 --- /dev/null +++ b/tests/baselines/reference/objectSpreadIndexSignature.types @@ -0,0 +1,52 @@ +=== tests/cases/conformance/types/spread/objectSpreadIndexSignature.ts === +interface Indexed { +>Indexed : Indexed + + [n: string]: number; +>n : string + + a: number; +>a : number +} +interface Indexed2 { +>Indexed2 : Indexed2 + + [n: string]: boolean; +>n : string + + c: boolean; +>c : boolean +} +let indexed: Indexed; +>indexed : Indexed +>Indexed : Indexed + +let indexed2: Indexed2; +>indexed2 : Indexed2 +>Indexed2 : Indexed2 + +let i = { ...indexed, b: 11 }; +>i : { b: number; a: number; } +>{ ...indexed, b: 11 } : { b: number; a: number; } +>indexed : Indexed +>b : number +>11 : 11 + +// only indexed has indexer, so i[101]: any +i[101]; +>i[101] : any +>i : { b: number; a: number; } +>101 : 101 + +let ii = { ...indexed, ...indexed2 }; +>ii : { [x: string]: number | boolean; c: boolean; a: number; } +>{ ...indexed, ...indexed2 } : { [x: string]: number | boolean; c: boolean; a: number; } +>indexed : Indexed +>indexed2 : Indexed2 + +// both have indexer, so i[1001]: number | boolean +ii[1001]; +>ii[1001] : number | boolean +>ii : { [x: string]: number | boolean; c: boolean; a: number; } +>1001 : 1001 + diff --git a/tests/baselines/reference/objectSpreadInference.js b/tests/baselines/reference/objectSpreadInference.js new file mode 100644 index 00000000000..77930e56511 --- /dev/null +++ b/tests/baselines/reference/objectSpreadInference.js @@ -0,0 +1,43 @@ +//// [objectSpreadInference.ts] +interface Result { + t: T; + u: U; + v: V; +} +declare function infer(tuv: { ...T, ...U, a: V }): { t: T, u: U, v: V }; +declare function infer2(utv: { ...U, a: V, ...T }): { t: T, u: U, v: V }; +function generic(w: W, x: X, y: Y) { + // should infer { t: {}, u: {}, v: {} } because there is no trailing type parameter + return infer({ ...w, ...x, a: y, b: "different type" }); +} +let b: { b: number }; +let c: { c: number }; +// can only infer { t: {}, u: {}, v: {} } +let i1 = infer({ ...b, ...c, a: 12 }); +// can only infer { t: {}, u: {}, v: {} } +let i2 = infer2({ ...b, ...c, a: 12 }); +// can only infer { t: {}, u: {}, v: {} } +let i3 = generic(b, c, { a: 12 }); + + +//// [objectSpreadInference.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +function generic(w, x, y) { + // should infer { t: {}, u: {}, v: {} } because there is no trailing type parameter + return infer(__assign({}, w, x, { a: y, b: "different type" })); +} +var b; +var c; +// can only infer { t: {}, u: {}, v: {} } +var i1 = infer(__assign({}, b, c, { a: 12 })); +// can only infer { t: {}, u: {}, v: {} } +var i2 = infer2(__assign({}, b, c, { a: 12 })); +// can only infer { t: {}, u: {}, v: {} } +var i3 = generic(b, c, { a: 12 }); diff --git a/tests/baselines/reference/objectSpreadInference.symbols b/tests/baselines/reference/objectSpreadInference.symbols new file mode 100644 index 00000000000..ddecc4d7e5d --- /dev/null +++ b/tests/baselines/reference/objectSpreadInference.symbols @@ -0,0 +1,100 @@ +=== tests/cases/conformance/types/spread/objectSpreadInference.ts === +interface Result { +>Result : Symbol(Result, Decl(objectSpreadInference.ts, 0, 0)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 0, 17)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 0, 19)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 0, 21)) + + t: T; +>t : Symbol(Result.t, Decl(objectSpreadInference.ts, 0, 25)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 0, 17)) + + u: U; +>u : Symbol(Result.u, Decl(objectSpreadInference.ts, 1, 9)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 0, 19)) + + v: V; +>v : Symbol(Result.v, Decl(objectSpreadInference.ts, 2, 9)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 0, 21)) +} +declare function infer(tuv: { ...T, ...U, a: V }): { t: T, u: U, v: V }; +>infer : Symbol(infer, Decl(objectSpreadInference.ts, 4, 1)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 5, 23)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 5, 25)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 5, 27)) +>tuv : Symbol(tuv, Decl(objectSpreadInference.ts, 5, 30)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 5, 23)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 5, 25)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 5, 48)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 5, 27)) +>t : Symbol(t, Decl(objectSpreadInference.ts, 5, 59)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 5, 23)) +>u : Symbol(u, Decl(objectSpreadInference.ts, 5, 65)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 5, 25)) +>v : Symbol(v, Decl(objectSpreadInference.ts, 5, 71)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 5, 27)) + +declare function infer2(utv: { ...U, a: V, ...T }): { t: T, u: U, v: V }; +>infer2 : Symbol(infer2, Decl(objectSpreadInference.ts, 5, 79)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 6, 24)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 6, 26)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 6, 28)) +>utv : Symbol(utv, Decl(objectSpreadInference.ts, 6, 31)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 6, 26)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 6, 43)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 6, 28)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 6, 24)) +>t : Symbol(t, Decl(objectSpreadInference.ts, 6, 60)) +>T : Symbol(T, Decl(objectSpreadInference.ts, 6, 24)) +>u : Symbol(u, Decl(objectSpreadInference.ts, 6, 66)) +>U : Symbol(U, Decl(objectSpreadInference.ts, 6, 26)) +>v : Symbol(v, Decl(objectSpreadInference.ts, 6, 72)) +>V : Symbol(V, Decl(objectSpreadInference.ts, 6, 28)) + +function generic(w: W, x: X, y: Y) { +>generic : Symbol(generic, Decl(objectSpreadInference.ts, 6, 80)) +>W : Symbol(W, Decl(objectSpreadInference.ts, 7, 17)) +>X : Symbol(X, Decl(objectSpreadInference.ts, 7, 19)) +>Y : Symbol(Y, Decl(objectSpreadInference.ts, 7, 22)) +>w : Symbol(w, Decl(objectSpreadInference.ts, 7, 26)) +>W : Symbol(W, Decl(objectSpreadInference.ts, 7, 17)) +>x : Symbol(x, Decl(objectSpreadInference.ts, 7, 31)) +>X : Symbol(X, Decl(objectSpreadInference.ts, 7, 19)) +>y : Symbol(y, Decl(objectSpreadInference.ts, 7, 37)) +>Y : Symbol(Y, Decl(objectSpreadInference.ts, 7, 22)) + + // should infer { t: {}, u: {}, v: {} } because there is no trailing type parameter + return infer({ ...w, ...x, a: y, b: "different type" }); +>infer : Symbol(infer, Decl(objectSpreadInference.ts, 4, 1)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 9, 30)) +>y : Symbol(y, Decl(objectSpreadInference.ts, 7, 37)) +>b : Symbol(b, Decl(objectSpreadInference.ts, 9, 36)) +} +let b: { b: number }; +>b : Symbol(b, Decl(objectSpreadInference.ts, 11, 3)) +>b : Symbol(b, Decl(objectSpreadInference.ts, 11, 8)) + +let c: { c: number }; +>c : Symbol(c, Decl(objectSpreadInference.ts, 12, 3)) +>c : Symbol(c, Decl(objectSpreadInference.ts, 12, 8)) + +// can only infer { t: {}, u: {}, v: {} } +let i1 = infer({ ...b, ...c, a: 12 }); +>i1 : Symbol(i1, Decl(objectSpreadInference.ts, 14, 3)) +>infer : Symbol(infer, Decl(objectSpreadInference.ts, 4, 1)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 14, 28)) + +// can only infer { t: {}, u: {}, v: {} } +let i2 = infer2({ ...b, ...c, a: 12 }); +>i2 : Symbol(i2, Decl(objectSpreadInference.ts, 16, 3)) +>infer2 : Symbol(infer2, Decl(objectSpreadInference.ts, 5, 79)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 16, 29)) + +// can only infer { t: {}, u: {}, v: {} } +let i3 = generic(b, c, { a: 12 }); +>i3 : Symbol(i3, Decl(objectSpreadInference.ts, 18, 3)) +>generic : Symbol(generic, Decl(objectSpreadInference.ts, 6, 80)) +>b : Symbol(b, Decl(objectSpreadInference.ts, 11, 3)) +>c : Symbol(c, Decl(objectSpreadInference.ts, 12, 3)) +>a : Symbol(a, Decl(objectSpreadInference.ts, 18, 24)) + diff --git a/tests/baselines/reference/objectSpreadInference.types b/tests/baselines/reference/objectSpreadInference.types new file mode 100644 index 00000000000..3e71e29b83c --- /dev/null +++ b/tests/baselines/reference/objectSpreadInference.types @@ -0,0 +1,118 @@ +=== tests/cases/conformance/types/spread/objectSpreadInference.ts === +interface Result { +>Result : Result +>T : T +>U : U +>V : V + + t: T; +>t : T +>T : T + + u: U; +>u : U +>U : U + + v: V; +>v : V +>V : V +} +declare function infer(tuv: { ...T, ...U, a: V }): { t: T, u: U, v: V }; +>infer : (tuv: { ...T; ...U; a: V; }) => { t: T; u: U; v: V; } +>T : T +>U : U +>V : V +>tuv : { ...T; ...U; a: V; } +>T : T +>U : U +>a : V +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + +declare function infer2(utv: { ...U, a: V, ...T }): { t: T, u: U, v: V }; +>infer2 : (utv: { ...U; a: V; ...T }) => { t: T; u: U; v: V; } +>T : T +>U : U +>V : V +>utv : { ...U; a: V; ...T } +>U : U +>a : V +>V : V +>T : T +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + +function generic(w: W, x: X, y: Y) { +>generic : (w: W, x: X, y: Y) => { t: {}; u: {}; v: {}; } +>W : W +>X : X +>Y : Y +>w : W +>W : W +>x : X +>X : X +>y : Y +>Y : Y + + // should infer { t: {}, u: {}, v: {} } because there is no trailing type parameter + return infer({ ...w, ...x, a: y, b: "different type" }); +>infer({ ...w, ...x, a: y, b: "different type" }) : { t: {}; u: {}; v: {}; } +>infer : (tuv: { ...T; ...U; a: V; }) => { t: T; u: U; v: V; } +>{ ...w, ...x, a: y, b: "different type" } : { ...W; ...X; a: Y; b: string; } +>w : any +>x : any +>a : Y +>y : Y +>b : string +>"different type" : "different type" +} +let b: { b: number }; +>b : { b: number; } +>b : number + +let c: { c: number }; +>c : { c: number; } +>c : number + +// can only infer { t: {}, u: {}, v: {} } +let i1 = infer({ ...b, ...c, a: 12 }); +>i1 : { t: {}; u: {}; v: {}; } +>infer({ ...b, ...c, a: 12 }) : { t: {}; u: {}; v: {}; } +>infer : (tuv: { ...T; ...U; a: V; }) => { t: T; u: U; v: V; } +>{ ...b, ...c, a: 12 } : { a: number; c: number; b: number; } +>b : any +>c : any +>a : number +>12 : 12 + +// can only infer { t: {}, u: {}, v: {} } +let i2 = infer2({ ...b, ...c, a: 12 }); +>i2 : { t: {}; u: {}; v: {}; } +>infer2({ ...b, ...c, a: 12 }) : { t: {}; u: {}; v: {}; } +>infer2 : (utv: { ...U; a: V; ...T }) => { t: T; u: U; v: V; } +>{ ...b, ...c, a: 12 } : { a: number; c: number; b: number; } +>b : any +>c : any +>a : number +>12 : 12 + +// can only infer { t: {}, u: {}, v: {} } +let i3 = generic(b, c, { a: 12 }); +>i3 : { t: {}; u: {}; v: {}; } +>generic(b, c, { a: 12 }) : { t: {}; u: {}; v: {}; } +>generic : (w: W, x: X, y: Y) => { t: {}; u: {}; v: {}; } +>b : { b: number; } +>c : { c: number; } +>{ a: 12 } : { a: number; } +>a : number +>12 : 12 + diff --git a/tests/baselines/reference/objectSpreadIntersection.js b/tests/baselines/reference/objectSpreadIntersection.js new file mode 100644 index 00000000000..2ec6ad35413 --- /dev/null +++ b/tests/baselines/reference/objectSpreadIntersection.js @@ -0,0 +1,77 @@ +//// [objectSpreadIntersection.ts] +function iteratedUnionIntersection(t: T, u: U, v: V): void { + let tu: T | U; + let uv: U & V; + let result = { ...tu, ...uv, id: 'foo' }; + let assignable: { ...(T | U), ...(U & V), id: string } = result; +} +// concrete types work +interface A1 { a: number } +interface A2 { a: string } +interface B1 { b: number } +interface B2 { b: string } +let a12: A1 & A2; +let b12: B1 & B2; +let result = { ...a12, ...b12 }; +let sn: number & string = result.a; +sn = result.b; +let assignable: { ...(A1 & A2), ...(B1 & B2) } = result; + +function tripleIntersection(t: T, u: U, v: V): void { + let tuv: T & U & V; + let result = { ...tuv, id: 'bar' }; + let assignable: { ...(T & U & V), id: string } = result; +} +function iteratedDoubleIntersection(t: T, u: U, v: V): void { + let tu: T & U; + let uv: U & V; + let result = { ...tu, ...uv, id: 'baz' }; + let assignable: { ...(T & U), ...(U & V), id: string } = result; +} +function iteratedIntersectionUnion(t: T, u: U, v: V): void { + let tu: T & U; + let uv: U | V; + let result = { ...tu, ...uv, id: 'qux' }; + let assignable: { ...(T & U), ...(U | V), id: string } = result; +} + + + +//// [objectSpreadIntersection.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +function iteratedUnionIntersection(t, u, v) { + var tu; + var uv; + var result = __assign({}, tu, uv, { id: 'foo' }); + var assignable = result; +} +var a12; +var b12; +var result = __assign({}, a12, b12); +var sn = result.a; +sn = result.b; +var assignable = result; +function tripleIntersection(t, u, v) { + var tuv; + var result = __assign({}, tuv, { id: 'bar' }); + var assignable = result; +} +function iteratedDoubleIntersection(t, u, v) { + var tu; + var uv; + var result = __assign({}, tu, uv, { id: 'baz' }); + var assignable = result; +} +function iteratedIntersectionUnion(t, u, v) { + var tu; + var uv; + var result = __assign({}, tu, uv, { id: 'qux' }); + var assignable = result; +} diff --git a/tests/baselines/reference/objectSpreadIntersection.symbols b/tests/baselines/reference/objectSpreadIntersection.symbols new file mode 100644 index 00000000000..bc63cb11348 --- /dev/null +++ b/tests/baselines/reference/objectSpreadIntersection.symbols @@ -0,0 +1,188 @@ +=== tests/cases/conformance/types/spread/objectSpreadIntersection.ts === +function iteratedUnionIntersection(t: T, u: U, v: V): void { +>iteratedUnionIntersection : Symbol(iteratedUnionIntersection, Decl(objectSpreadIntersection.ts, 0, 0)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 0, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 0, 40)) +>t : Symbol(t, Decl(objectSpreadIntersection.ts, 0, 44)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 0, 35)) +>u : Symbol(u, Decl(objectSpreadIntersection.ts, 0, 49)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) +>v : Symbol(v, Decl(objectSpreadIntersection.ts, 0, 55)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 0, 40)) + + let tu: T | U; +>tu : Symbol(tu, Decl(objectSpreadIntersection.ts, 1, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 0, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) + + let uv: U & V; +>uv : Symbol(uv, Decl(objectSpreadIntersection.ts, 2, 7)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 0, 40)) + + let result = { ...tu, ...uv, id: 'foo' }; +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 3, 7)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 3, 32)) + + let assignable: { ...(T | U), ...(U & V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadIntersection.ts, 4, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 0, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 0, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 0, 40)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 4, 45)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 3, 7)) +} +// concrete types work +interface A1 { a: number } +>A1 : Symbol(A1, Decl(objectSpreadIntersection.ts, 5, 1)) +>a : Symbol(A1.a, Decl(objectSpreadIntersection.ts, 7, 14)) + +interface A2 { a: string } +>A2 : Symbol(A2, Decl(objectSpreadIntersection.ts, 7, 26)) +>a : Symbol(A2.a, Decl(objectSpreadIntersection.ts, 8, 14)) + +interface B1 { b: number } +>B1 : Symbol(B1, Decl(objectSpreadIntersection.ts, 8, 26)) +>b : Symbol(B1.b, Decl(objectSpreadIntersection.ts, 9, 14)) + +interface B2 { b: string } +>B2 : Symbol(B2, Decl(objectSpreadIntersection.ts, 9, 26)) +>b : Symbol(B2.b, Decl(objectSpreadIntersection.ts, 10, 14)) + +let a12: A1 & A2; +>a12 : Symbol(a12, Decl(objectSpreadIntersection.ts, 11, 3)) +>A1 : Symbol(A1, Decl(objectSpreadIntersection.ts, 5, 1)) +>A2 : Symbol(A2, Decl(objectSpreadIntersection.ts, 7, 26)) + +let b12: B1 & B2; +>b12 : Symbol(b12, Decl(objectSpreadIntersection.ts, 12, 3)) +>B1 : Symbol(B1, Decl(objectSpreadIntersection.ts, 8, 26)) +>B2 : Symbol(B2, Decl(objectSpreadIntersection.ts, 9, 26)) + +let result = { ...a12, ...b12 }; +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 13, 3)) + +let sn: number & string = result.a; +>sn : Symbol(sn, Decl(objectSpreadIntersection.ts, 14, 3)) +>result.a : Symbol(a, Decl(objectSpreadIntersection.ts, 7, 14), Decl(objectSpreadIntersection.ts, 8, 14)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 13, 3)) +>a : Symbol(a, Decl(objectSpreadIntersection.ts, 7, 14), Decl(objectSpreadIntersection.ts, 8, 14)) + +sn = result.b; +>sn : Symbol(sn, Decl(objectSpreadIntersection.ts, 14, 3)) +>result.b : Symbol(b, Decl(objectSpreadIntersection.ts, 9, 14), Decl(objectSpreadIntersection.ts, 10, 14)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 13, 3)) +>b : Symbol(b, Decl(objectSpreadIntersection.ts, 9, 14), Decl(objectSpreadIntersection.ts, 10, 14)) + +let assignable: { ...(A1 & A2), ...(B1 & B2) } = result; +>assignable : Symbol(assignable, Decl(objectSpreadIntersection.ts, 16, 3)) +>A1 : Symbol(A1, Decl(objectSpreadIntersection.ts, 5, 1)) +>A2 : Symbol(A2, Decl(objectSpreadIntersection.ts, 7, 26)) +>B1 : Symbol(B1, Decl(objectSpreadIntersection.ts, 8, 26)) +>B2 : Symbol(B2, Decl(objectSpreadIntersection.ts, 9, 26)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 13, 3)) + +function tripleIntersection(t: T, u: U, v: V): void { +>tripleIntersection : Symbol(tripleIntersection, Decl(objectSpreadIntersection.ts, 16, 56)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 18, 28)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 18, 30)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 18, 33)) +>t : Symbol(t, Decl(objectSpreadIntersection.ts, 18, 37)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 18, 28)) +>u : Symbol(u, Decl(objectSpreadIntersection.ts, 18, 42)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 18, 30)) +>v : Symbol(v, Decl(objectSpreadIntersection.ts, 18, 48)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 18, 33)) + + let tuv: T & U & V; +>tuv : Symbol(tuv, Decl(objectSpreadIntersection.ts, 19, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 18, 28)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 18, 30)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 18, 33)) + + let result = { ...tuv, id: 'bar' }; +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 20, 7)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 20, 26)) + + let assignable: { ...(T & U & V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadIntersection.ts, 21, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 18, 28)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 18, 30)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 18, 33)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 21, 37)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 20, 7)) +} +function iteratedDoubleIntersection(t: T, u: U, v: V): void { +>iteratedDoubleIntersection : Symbol(iteratedDoubleIntersection, Decl(objectSpreadIntersection.ts, 22, 1)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 23, 36)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 23, 41)) +>t : Symbol(t, Decl(objectSpreadIntersection.ts, 23, 45)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 23, 36)) +>u : Symbol(u, Decl(objectSpreadIntersection.ts, 23, 50)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) +>v : Symbol(v, Decl(objectSpreadIntersection.ts, 23, 56)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 23, 41)) + + let tu: T & U; +>tu : Symbol(tu, Decl(objectSpreadIntersection.ts, 24, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 23, 36)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) + + let uv: U & V; +>uv : Symbol(uv, Decl(objectSpreadIntersection.ts, 25, 7)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 23, 41)) + + let result = { ...tu, ...uv, id: 'baz' }; +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 26, 7)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 26, 32)) + + let assignable: { ...(T & U), ...(U & V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadIntersection.ts, 27, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 23, 36)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 23, 38)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 23, 41)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 27, 45)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 26, 7)) +} +function iteratedIntersectionUnion(t: T, u: U, v: V): void { +>iteratedIntersectionUnion : Symbol(iteratedIntersectionUnion, Decl(objectSpreadIntersection.ts, 28, 1)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 29, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 29, 40)) +>t : Symbol(t, Decl(objectSpreadIntersection.ts, 29, 44)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 29, 35)) +>u : Symbol(u, Decl(objectSpreadIntersection.ts, 29, 49)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) +>v : Symbol(v, Decl(objectSpreadIntersection.ts, 29, 55)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 29, 40)) + + let tu: T & U; +>tu : Symbol(tu, Decl(objectSpreadIntersection.ts, 30, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 29, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) + + let uv: U | V; +>uv : Symbol(uv, Decl(objectSpreadIntersection.ts, 31, 7)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 29, 40)) + + let result = { ...tu, ...uv, id: 'qux' }; +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 32, 7)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 32, 32)) + + let assignable: { ...(T & U), ...(U | V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadIntersection.ts, 33, 7)) +>T : Symbol(T, Decl(objectSpreadIntersection.ts, 29, 35)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) +>U : Symbol(U, Decl(objectSpreadIntersection.ts, 29, 37)) +>V : Symbol(V, Decl(objectSpreadIntersection.ts, 29, 40)) +>id : Symbol(id, Decl(objectSpreadIntersection.ts, 33, 45)) +>result : Symbol(result, Decl(objectSpreadIntersection.ts, 32, 7)) +} + + diff --git a/tests/baselines/reference/objectSpreadIntersection.types b/tests/baselines/reference/objectSpreadIntersection.types new file mode 100644 index 00000000000..e6a7b7c19ee --- /dev/null +++ b/tests/baselines/reference/objectSpreadIntersection.types @@ -0,0 +1,207 @@ +=== tests/cases/conformance/types/spread/objectSpreadIntersection.ts === +function iteratedUnionIntersection(t: T, u: U, v: V): void { +>iteratedUnionIntersection : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tu: T | U; +>tu : T | U +>T : T +>U : U + + let uv: U & V; +>uv : U & V +>U : U +>V : V + + let result = { ...tu, ...uv, id: 'foo' }; +>result : { ...T; ...U & V; id: string; } | { ...U; ...U & V; id: string; } +>{ ...tu, ...uv, id: 'foo' } : { ...T; ...U & V; id: string; } | { ...U; ...U & V; id: string; } +>tu : any +>uv : any +>id : string +>'foo' : "foo" + + let assignable: { ...(T | U), ...(U & V), id: string } = result; +>assignable : { ...T; ...U & V; id: string; } | { ...U; ...U & V; id: string; } +>T : T +>U : U +>U : U +>V : V +>id : string +>result : { ...T; ...U & V; id: string; } | { ...U; ...U & V; id: string; } +} +// concrete types work +interface A1 { a: number } +>A1 : A1 +>a : number + +interface A2 { a: string } +>A2 : A2 +>a : string + +interface B1 { b: number } +>B1 : B1 +>b : number + +interface B2 { b: string } +>B2 : B2 +>b : string + +let a12: A1 & A2; +>a12 : A1 & A2 +>A1 : A1 +>A2 : A2 + +let b12: B1 & B2; +>b12 : B1 & B2 +>B1 : B1 +>B2 : B2 + +let result = { ...a12, ...b12 }; +>result : { b: number & string; a: number & string; } +>{ ...a12, ...b12 } : { b: number & string; a: number & string; } +>a12 : any +>b12 : any + +let sn: number & string = result.a; +>sn : number & string +>result.a : number & string +>result : { b: number & string; a: number & string; } +>a : number & string + +sn = result.b; +>sn = result.b : number & string +>sn : number & string +>result.b : number & string +>result : { b: number & string; a: number & string; } +>b : number & string + +let assignable: { ...(A1 & A2), ...(B1 & B2) } = result; +>assignable : { b: number & string; a: number & string; } +>A1 : A1 +>A2 : A2 +>B1 : B1 +>B2 : B2 +>result : { b: number & string; a: number & string; } + +function tripleIntersection(t: T, u: U, v: V): void { +>tripleIntersection : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tuv: T & U & V; +>tuv : T & U & V +>T : T +>U : U +>V : V + + let result = { ...tuv, id: 'bar' }; +>result : { ...T & U & V; id: string; } +>{ ...tuv, id: 'bar' } : { ...T & U & V; id: string; } +>tuv : any +>id : string +>'bar' : "bar" + + let assignable: { ...(T & U & V), id: string } = result; +>assignable : { ...T & U & V; id: string; } +>T : T +>U : U +>V : V +>id : string +>result : { ...T & U & V; id: string; } +} +function iteratedDoubleIntersection(t: T, u: U, v: V): void { +>iteratedDoubleIntersection : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tu: T & U; +>tu : T & U +>T : T +>U : U + + let uv: U & V; +>uv : U & V +>U : U +>V : V + + let result = { ...tu, ...uv, id: 'baz' }; +>result : { ...T & U; ...U & V; id: string; } +>{ ...tu, ...uv, id: 'baz' } : { ...T & U; ...U & V; id: string; } +>tu : any +>uv : any +>id : string +>'baz' : "baz" + + let assignable: { ...(T & U), ...(U & V), id: string } = result; +>assignable : { ...T & U; ...U & V; id: string; } +>T : T +>U : U +>U : U +>V : V +>id : string +>result : { ...T & U; ...U & V; id: string; } +} +function iteratedIntersectionUnion(t: T, u: U, v: V): void { +>iteratedIntersectionUnion : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tu: T & U; +>tu : T & U +>T : T +>U : U + + let uv: U | V; +>uv : U | V +>U : U +>V : V + + let result = { ...tu, ...uv, id: 'qux' }; +>result : { ...T & U; ...U; id: string; } | { ...T & U; ...V; id: string; } +>{ ...tu, ...uv, id: 'qux' } : { ...T & U; ...U; id: string; } | { ...T & U; ...V; id: string; } +>tu : any +>uv : any +>id : string +>'qux' : "qux" + + let assignable: { ...(T & U), ...(U | V), id: string } = result; +>assignable : { ...T & U; ...U; id: string; } | { ...T & U; ...V; id: string; } +>T : T +>U : U +>U : U +>V : V +>id : string +>result : { ...T & U; ...U; id: string; } | { ...T & U; ...V; id: string; } +} + + diff --git a/tests/baselines/reference/objectSpreadNegative.errors.txt b/tests/baselines/reference/objectSpreadNegative.errors.txt new file mode 100644 index 00000000000..17f07bc06a2 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNegative.errors.txt @@ -0,0 +1,123 @@ +tests/cases/conformance/types/spread/objectSpreadNegative.ts(13,21): error TS2339: Property 'x' does not exist on type '{}'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(16,5): error TS2322: Type '{ sn?: string | number; }' is not assignable to type '{ sn: string | number; }'. + Property 'sn' is optional in type '{ sn?: string | number; }' but required in type '{ sn: string | number; }'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(23,1): error TS2322: Type '{ s: string; }' is not assignable to type '{ s: string; b: boolean; }'. + Property 'b' is missing in type '{ s: string; }'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(25,1): error TS2322: Type '{ b: boolean; }' is not assignable to type '{ s: string; b: boolean; }'. + Property 's' is missing in type '{ b: boolean; }'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(28,36): error TS2300: Duplicate identifier 'b'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(28,53): error TS2300: Duplicate identifier 'b'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(32,19): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(33,19): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(35,20): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(37,19): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(42,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(46,12): error TS2339: Property 'b' does not exist on type '{}'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(52,9): error TS2339: Property 'm' does not exist on type '{ p: number; }'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(56,14): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(59,14): error TS2698: Spread types may only be created from object types. + + +==== tests/cases/conformance/types/spread/objectSpreadNegative.ts (15 errors) ==== + let o = { a: 1, b: 'no' } + + /// private propagates + class PrivateOptionalX { + private x?: number; + } + class PublicX { + public x: number; + } + let publicX: PublicX; + let privateOptionalX: PrivateOptionalX; + let o2 = { ...publicX, ...privateOptionalX }; + let sn: number = o2.x; // error, x is private + ~ +!!! error TS2339: Property 'x' does not exist on type '{}'. + let optionalString: { sn?: string }; + let optionalNumber: { sn?: number }; + let allOptional: { sn: string | number } = { ...optionalString, ...optionalNumber }; + ~~~~~~~~~~~ +!!! error TS2322: Type '{ sn?: string | number; }' is not assignable to type '{ sn: string | number; }'. +!!! error TS2322: Property 'sn' is optional in type '{ sn?: string | number; }' but required in type '{ sn: string | number; }'. + // error, 'sn' is optional in source, required in target + + // assignability as target + interface Bool { b: boolean }; + interface Str { s: string }; + let spread = { ...{ b: true }, ...{s: "foo" } }; + spread = { s: "foo" }; // error, missing 'b' + ~~~~~~ +!!! error TS2322: Type '{ s: string; }' is not assignable to type '{ s: string; b: boolean; }'. +!!! error TS2322: Property 'b' is missing in type '{ s: string; }'. + let b = { b: false }; + spread = b; // error, missing 's' + ~~~~~~ +!!! error TS2322: Type '{ b: boolean; }' is not assignable to type '{ s: string; b: boolean; }'. +!!! error TS2322: Property 's' is missing in type '{ b: boolean; }'. + + // literal repeats are not allowed, but spread repeats are fine + let duplicated = { b: 'bad', ...o, b: 'bad', ...o2, b: 'bad' } + ~ +!!! error TS2300: Duplicate identifier 'b'. + ~ +!!! error TS2300: Duplicate identifier 'b'. + let duplicatedSpread = { ...o, ...o } + + // primitives are not allowed + let spreadNum = { ...12 }; + ~~~~~ +!!! error TS2698: Spread types may only be created from object types. + let spreadSum = { ...1 + 1 }; + ~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + spreadSum.toFixed(); // error, no methods from number + let spreadBool = { ...false }; + ~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + spreadBool.valueOf(); // error, what were you thinking? + let spreadStr = { ...'foo' }; + ~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + spreadStr.length; // error, no 'length' + spreadStr.charAt(1); // error, no methods either + // functions are skipped + let spreadFunc = { ...function () { } } + spreadFunc(); // error, no call signature + ~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. + + // write-only properties get skipped + let setterOnly = { ...{ set b (bad: number) { } } }; + setterOnly.b = 12; // error, 'b' does not exist + ~ +!!! error TS2339: Property 'b' does not exist on type '{}'. + + // methods are skipped because they aren't enumerable + class C { p = 1; m() { } } + let c: C = new C() + let spreadC = { ...c } + spreadC.m(); // error 'm' is not in '{ ... c }' + ~ +!!! error TS2339: Property 'm' does not exist on type '{ p: number; }'. + + // generics + function f(t: T, u: U) { + return { ...t, ...u, id: 'id' }; + ~~~~ +!!! error TS2698: Spread types may only be created from object types. + } + function override(initial: U, override: U): U { + return { ...initial, ...override }; + ~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + } + let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) + let overlap: { id: string, a: number, b: string } = + f({ a: 1 }, { a: 2, b: 'extra' }) + let overlapConflict: { id:string, a: string } = + f({ a: 1 }, { a: 'mismatch' }) + let overwriteId: { id: string, a: number, c: number, d: string } = + f({ a: 1, id: true }, { c: 1, d: 'no' }) + \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadNegative.js b/tests/baselines/reference/objectSpreadNegative.js new file mode 100644 index 00000000000..dff84355370 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNegative.js @@ -0,0 +1,145 @@ +//// [objectSpreadNegative.ts] +let o = { a: 1, b: 'no' } + +/// private propagates +class PrivateOptionalX { + private x?: number; +} +class PublicX { + public x: number; +} +let publicX: PublicX; +let privateOptionalX: PrivateOptionalX; +let o2 = { ...publicX, ...privateOptionalX }; +let sn: number = o2.x; // error, x is private +let optionalString: { sn?: string }; +let optionalNumber: { sn?: number }; +let allOptional: { sn: string | number } = { ...optionalString, ...optionalNumber }; +// error, 'sn' is optional in source, required in target + +// assignability as target +interface Bool { b: boolean }; +interface Str { s: string }; +let spread = { ...{ b: true }, ...{s: "foo" } }; +spread = { s: "foo" }; // error, missing 'b' +let b = { b: false }; +spread = b; // error, missing 's' + +// literal repeats are not allowed, but spread repeats are fine +let duplicated = { b: 'bad', ...o, b: 'bad', ...o2, b: 'bad' } +let duplicatedSpread = { ...o, ...o } + +// primitives are not allowed +let spreadNum = { ...12 }; +let spreadSum = { ...1 + 1 }; +spreadSum.toFixed(); // error, no methods from number +let spreadBool = { ...false }; +spreadBool.valueOf(); // error, what were you thinking? +let spreadStr = { ...'foo' }; +spreadStr.length; // error, no 'length' +spreadStr.charAt(1); // error, no methods either +// functions are skipped +let spreadFunc = { ...function () { } } +spreadFunc(); // error, no call signature + +// write-only properties get skipped +let setterOnly = { ...{ set b (bad: number) { } } }; +setterOnly.b = 12; // error, 'b' does not exist + +// methods are skipped because they aren't enumerable +class C { p = 1; m() { } } +let c: C = new C() +let spreadC = { ...c } +spreadC.m(); // error 'm' is not in '{ ... c }' + +// generics +function f(t: T, u: U) { + return { ...t, ...u, id: 'id' }; +} +function override(initial: U, override: U): U { + return { ...initial, ...override }; +} +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +let overlap: { id: string, a: number, b: string } = + f({ a: 1 }, { a: 2, b: 'extra' }) +let overlapConflict: { id:string, a: string } = + f({ a: 1 }, { a: 'mismatch' }) +let overwriteId: { id: string, a: number, c: number, d: string } = + f({ a: 1, id: true }, { c: 1, d: 'no' }) + + +//// [objectSpreadNegative.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var o = { a: 1, b: 'no' }; +/// private propagates +var PrivateOptionalX = (function () { + function PrivateOptionalX() { + } + return PrivateOptionalX; +}()); +var PublicX = (function () { + function PublicX() { + } + return PublicX; +}()); +var publicX; +var privateOptionalX; +var o2 = __assign({}, publicX, privateOptionalX); +var sn = o2.x; // error, x is private +var optionalString; +var optionalNumber; +var allOptional = __assign({}, optionalString, optionalNumber); +; +; +var spread = __assign({ b: true }, { s: "foo" }); +spread = { s: "foo" }; // error, missing 'b' +var b = { b: false }; +spread = b; // error, missing 's' +// literal repeats are not allowed, but spread repeats are fine +var duplicated = __assign({ b: 'bad' }, o, { b: 'bad' }, o2, { b: 'bad' }); +var duplicatedSpread = __assign({}, o, o); +// primitives are not allowed +var spreadNum = __assign({}, 12); +var spreadSum = __assign({}, 1 + 1); +spreadSum.toFixed(); // error, no methods from number +var spreadBool = __assign({}, false); +spreadBool.valueOf(); // error, what were you thinking? +var spreadStr = __assign({}, 'foo'); +spreadStr.length; // error, no 'length' +spreadStr.charAt(1); // error, no methods either +// functions are skipped +var spreadFunc = __assign({}, function () { }); +spreadFunc(); // error, no call signature +// write-only properties get skipped +var setterOnly = __assign({ set b(bad) { } }); +setterOnly.b = 12; // error, 'b' does not exist +// methods are skipped because they aren't enumerable +var C = (function () { + function C() { + this.p = 1; + } + C.prototype.m = function () { }; + return C; +}()); +var c = new C(); +var spreadC = __assign({}, c); +spreadC.m(); // error 'm' is not in '{ ... c }' +// generics +function f(t, u) { + return __assign({}, t, u, { id: 'id' }); +} +function override(initial, override) { + return __assign({}, initial, override); +} +var exclusive = f({ a: 1, b: 'yes' }, { c: 'no', d: false }); +var overlap = f({ a: 1 }, { a: 2, b: 'extra' }); +var overlapConflict = f({ a: 1 }, { a: 'mismatch' }); +var overwriteId = f({ a: 1, id: true }, { c: 1, d: 'no' }); diff --git a/tests/baselines/reference/objectSpreadNegativeParse.errors.txt b/tests/baselines/reference/objectSpreadNegativeParse.errors.txt new file mode 100644 index 00000000000..b37200c4f02 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNegativeParse.errors.txt @@ -0,0 +1,38 @@ +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(1,15): error TS2304: Cannot find name 'o'. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(1,18): error TS1109: Expression expected. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(2,12): error TS2698: Spread types may only be created from object types. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(2,15): error TS1109: Expression expected. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(2,16): error TS2304: Cannot find name 'o'. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(3,15): error TS2304: Cannot find name 'matchMedia'. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(3,28): error TS1005: ',' expected. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(3,31): error TS1128: Declaration or statement expected. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(4,16): error TS2304: Cannot find name 'get'. +tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(4,20): error TS1005: ',' expected. + + +==== tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts (10 errors) ==== + let o7 = { ...o? }; + ~ +!!! error TS2304: Cannot find name 'o'. + ~ +!!! error TS1109: Expression expected. + let o8 = { ...*o }; + ~~~~~ +!!! error TS2698: Spread types may only be created from object types. + ~ +!!! error TS1109: Expression expected. + ~ +!!! error TS2304: Cannot find name 'o'. + let o9 = { ...matchMedia() { }}; + ~~~~~~~~~~ +!!! error TS2304: Cannot find name 'matchMedia'. + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS1128: Declaration or statement expected. + let o10 = { ...get x() { return 12; }}; + ~~~ +!!! error TS2304: Cannot find name 'get'. + ~ +!!! error TS1005: ',' expected. + \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadNegativeParse.js b/tests/baselines/reference/objectSpreadNegativeParse.js new file mode 100644 index 00000000000..297c56c3e62 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNegativeParse.js @@ -0,0 +1,21 @@ +//// [objectSpreadNegativeParse.ts] +let o7 = { ...o? }; +let o8 = { ...*o }; +let o9 = { ...matchMedia() { }}; +let o10 = { ...get x() { return 12; }}; + + +//// [objectSpreadNegativeParse.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var o7 = __assign({}, o ? : ); +var o8 = __assign({}, * o); +var o9 = __assign({}, matchMedia()), _a = void 0; +; +var o10 = __assign({}, get, { x: function () { return 12; } }); diff --git a/tests/baselines/reference/objectSpreadNoTransform.js b/tests/baselines/reference/objectSpreadNoTransform.js new file mode 100644 index 00000000000..5ad9c01e599 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNoTransform.js @@ -0,0 +1,14 @@ +//// [objectSpreadNoTransform.ts] +const y = { a: 'yes', b: 'no' }; +const o = { x: 1, ...y }; +var b; +var rest: any; +({ b, ...rest } = o); + + +//// [objectSpreadNoTransform.js] +const y = { a: 'yes', b: 'no' }; +const o = { x: 1, ...y }; +var b; +var rest; +({ b, ...rest } = o); diff --git a/tests/baselines/reference/objectSpreadNoTransform.symbols b/tests/baselines/reference/objectSpreadNoTransform.symbols new file mode 100644 index 00000000000..b2062697cdd --- /dev/null +++ b/tests/baselines/reference/objectSpreadNoTransform.symbols @@ -0,0 +1,22 @@ +=== tests/cases/conformance/types/spread/objectSpreadNoTransform.ts === +const y = { a: 'yes', b: 'no' }; +>y : Symbol(y, Decl(objectSpreadNoTransform.ts, 0, 5)) +>a : Symbol(a, Decl(objectSpreadNoTransform.ts, 0, 11)) +>b : Symbol(b, Decl(objectSpreadNoTransform.ts, 0, 21)) + +const o = { x: 1, ...y }; +>o : Symbol(o, Decl(objectSpreadNoTransform.ts, 1, 5)) +>x : Symbol(x, Decl(objectSpreadNoTransform.ts, 1, 11)) +>y : Symbol(y, Decl(objectSpreadNoTransform.ts, 0, 5)) + +var b; +>b : Symbol(b, Decl(objectSpreadNoTransform.ts, 2, 3)) + +var rest: any; +>rest : Symbol(rest, Decl(objectSpreadNoTransform.ts, 3, 3)) + +({ b, ...rest } = o); +>b : Symbol(b, Decl(objectSpreadNoTransform.ts, 4, 2)) +>rest : Symbol(rest, Decl(objectSpreadNoTransform.ts, 3, 3)) +>o : Symbol(o, Decl(objectSpreadNoTransform.ts, 1, 5)) + diff --git a/tests/baselines/reference/objectSpreadNoTransform.types b/tests/baselines/reference/objectSpreadNoTransform.types new file mode 100644 index 00000000000..bb09fd418c2 --- /dev/null +++ b/tests/baselines/reference/objectSpreadNoTransform.types @@ -0,0 +1,30 @@ +=== tests/cases/conformance/types/spread/objectSpreadNoTransform.ts === +const y = { a: 'yes', b: 'no' }; +>y : { a: string; b: string; } +>{ a: 'yes', b: 'no' } : { a: string; b: string; } +>a : string +>'yes' : "yes" +>b : string +>'no' : "no" + +const o = { x: 1, ...y }; +>o : { a: string; b: string; x: number; } +>{ x: 1, ...y } : { a: string; b: string; x: number; } +>x : number +>1 : 1 +>y : { a: string; b: string; } + +var b; +>b : any + +var rest: any; +>rest : any + +({ b, ...rest } = o); +>({ b, ...rest } = o) : { a: string; b: string; x: number; } +>{ b, ...rest } = o : { a: string; b: string; x: number; } +>{ b, ...rest } : any +>b : any +>rest : any +>o : { a: string; b: string; x: number; } + diff --git a/tests/baselines/reference/objectSpreadScenarios.js b/tests/baselines/reference/objectSpreadScenarios.js new file mode 100644 index 00000000000..96ac98d2d35 --- /dev/null +++ b/tests/baselines/reference/objectSpreadScenarios.js @@ -0,0 +1,45 @@ +//// [objectSpreadScenarios.ts] +interface A1 { a: boolean } +interface B1 { b: number }; +function override(initial: U, override: U): { ...U, ...U } { + return { ...initial, ...override }; +} +function update(this: { u: { ...U } }, override: U): void { + this.u = { ...this.u, ...override }; +} +function mixin(one: T, two: U): { ...T, ...U } { + return { ...one, ...two }; +} +let a1: A1 = { a: true }; +let b1: B1 = { b: 101 }; +a1 = override(a1, { a: false }); +let host = { u: a1, update }; +host.update({ a: false }); +let mixed = mixin(a1, b1); + + +//// [objectSpreadScenarios.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +; +function override(initial, override) { + return __assign({}, initial, override); +} +function update(override) { + this.u = __assign({}, this.u, override); +} +function mixin(one, two) { + return __assign({}, one, two); +} +var a1 = { a: true }; +var b1 = { b: 101 }; +a1 = override(a1, { a: false }); +var host = { u: a1, update: update }; +host.update({ a: false }); +var mixed = mixin(a1, b1); diff --git a/tests/baselines/reference/objectSpreadScenarios.symbols b/tests/baselines/reference/objectSpreadScenarios.symbols new file mode 100644 index 00000000000..cf1e1833ac9 --- /dev/null +++ b/tests/baselines/reference/objectSpreadScenarios.symbols @@ -0,0 +1,85 @@ +=== tests/cases/conformance/types/spread/objectSpreadScenarios.ts === +interface A1 { a: boolean } +>A1 : Symbol(A1, Decl(objectSpreadScenarios.ts, 0, 0)) +>a : Symbol(A1.a, Decl(objectSpreadScenarios.ts, 0, 14)) + +interface B1 { b: number }; +>B1 : Symbol(B1, Decl(objectSpreadScenarios.ts, 0, 27)) +>b : Symbol(B1.b, Decl(objectSpreadScenarios.ts, 1, 14)) + +function override(initial: U, override: U): { ...U, ...U } { +>override : Symbol(override, Decl(objectSpreadScenarios.ts, 1, 27)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 2, 18)) +>initial : Symbol(initial, Decl(objectSpreadScenarios.ts, 2, 21)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 2, 18)) +>override : Symbol(override, Decl(objectSpreadScenarios.ts, 2, 32)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 2, 18)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 2, 18)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 2, 18)) + + return { ...initial, ...override }; +} +function update(this: { u: { ...U } }, override: U): void { +>update : Symbol(update, Decl(objectSpreadScenarios.ts, 4, 1)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 5, 16)) +>this : Symbol(this, Decl(objectSpreadScenarios.ts, 5, 19)) +>u : Symbol(u, Decl(objectSpreadScenarios.ts, 5, 26)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 5, 16)) +>override : Symbol(override, Decl(objectSpreadScenarios.ts, 5, 41)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 5, 16)) + + this.u = { ...this.u, ...override }; +>this.u : Symbol(u, Decl(objectSpreadScenarios.ts, 5, 26)) +>this : Symbol(this, Decl(objectSpreadScenarios.ts, 5, 19)) +>u : Symbol(u, Decl(objectSpreadScenarios.ts, 5, 26)) +>this.u : Symbol(u, Decl(objectSpreadScenarios.ts, 5, 26)) +>this : Symbol(this, Decl(objectSpreadScenarios.ts, 5, 19)) +>u : Symbol(u, Decl(objectSpreadScenarios.ts, 5, 26)) +} +function mixin(one: T, two: U): { ...T, ...U } { +>mixin : Symbol(mixin, Decl(objectSpreadScenarios.ts, 7, 1)) +>T : Symbol(T, Decl(objectSpreadScenarios.ts, 8, 15)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 8, 17)) +>one : Symbol(one, Decl(objectSpreadScenarios.ts, 8, 21)) +>T : Symbol(T, Decl(objectSpreadScenarios.ts, 8, 15)) +>two : Symbol(two, Decl(objectSpreadScenarios.ts, 8, 28)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 8, 17)) +>T : Symbol(T, Decl(objectSpreadScenarios.ts, 8, 15)) +>U : Symbol(U, Decl(objectSpreadScenarios.ts, 8, 17)) + + return { ...one, ...two }; +} +let a1: A1 = { a: true }; +>a1 : Symbol(a1, Decl(objectSpreadScenarios.ts, 11, 3)) +>A1 : Symbol(A1, Decl(objectSpreadScenarios.ts, 0, 0)) +>a : Symbol(a, Decl(objectSpreadScenarios.ts, 11, 14)) + +let b1: B1 = { b: 101 }; +>b1 : Symbol(b1, Decl(objectSpreadScenarios.ts, 12, 3)) +>B1 : Symbol(B1, Decl(objectSpreadScenarios.ts, 0, 27)) +>b : Symbol(b, Decl(objectSpreadScenarios.ts, 12, 14)) + +a1 = override(a1, { a: false }); +>a1 : Symbol(a1, Decl(objectSpreadScenarios.ts, 11, 3)) +>override : Symbol(override, Decl(objectSpreadScenarios.ts, 1, 27)) +>a1 : Symbol(a1, Decl(objectSpreadScenarios.ts, 11, 3)) +>a : Symbol(a, Decl(objectSpreadScenarios.ts, 13, 19)) + +let host = { u: a1, update }; +>host : Symbol(host, Decl(objectSpreadScenarios.ts, 14, 3)) +>u : Symbol(u, Decl(objectSpreadScenarios.ts, 14, 12)) +>a1 : Symbol(a1, Decl(objectSpreadScenarios.ts, 11, 3)) +>update : Symbol(update, Decl(objectSpreadScenarios.ts, 14, 19)) + +host.update({ a: false }); +>host.update : Symbol(update, Decl(objectSpreadScenarios.ts, 14, 19)) +>host : Symbol(host, Decl(objectSpreadScenarios.ts, 14, 3)) +>update : Symbol(update, Decl(objectSpreadScenarios.ts, 14, 19)) +>a : Symbol(a, Decl(objectSpreadScenarios.ts, 15, 13)) + +let mixed = mixin(a1, b1); +>mixed : Symbol(mixed, Decl(objectSpreadScenarios.ts, 16, 3)) +>mixin : Symbol(mixin, Decl(objectSpreadScenarios.ts, 7, 1)) +>a1 : Symbol(a1, Decl(objectSpreadScenarios.ts, 11, 3)) +>b1 : Symbol(b1, Decl(objectSpreadScenarios.ts, 12, 3)) + diff --git a/tests/baselines/reference/objectSpreadScenarios.types b/tests/baselines/reference/objectSpreadScenarios.types new file mode 100644 index 00000000000..2d1aa47bd50 --- /dev/null +++ b/tests/baselines/reference/objectSpreadScenarios.types @@ -0,0 +1,107 @@ +=== tests/cases/conformance/types/spread/objectSpreadScenarios.ts === +interface A1 { a: boolean } +>A1 : A1 +>a : boolean + +interface B1 { b: number }; +>B1 : B1 +>b : number + +function override(initial: U, override: U): { ...U, ...U } { +>override : (initial: U, override: U) => { ...U } +>U : U +>initial : U +>U : U +>override : U +>U : U +>U : U +>U : U + + return { ...initial, ...override }; +>{ ...initial, ...override } : { ...U } +>initial : any +>override : any +} +function update(this: { u: { ...U } }, override: U): void { +>update : (this: { u: { ...U }; }, override: U) => void +>U : U +>this : { u: { ...U }; } +>u : { ...U } +>U : U +>override : U +>U : U + + this.u = { ...this.u, ...override }; +>this.u = { ...this.u, ...override } : { ...U } +>this.u : { ...U } +>this : { u: { ...U }; } +>u : { ...U } +>{ ...this.u, ...override } : { ...U } +>this.u : { ...U } +>this : { u: { ...U }; } +>u : { ...U } +>override : any +} +function mixin(one: T, two: U): { ...T, ...U } { +>mixin : (one: T, two: U) => { ...T; ...U } +>T : T +>U : U +>one : T +>T : T +>two : U +>U : U +>T : T +>U : U + + return { ...one, ...two }; +>{ ...one, ...two } : { ...T; ...U } +>one : any +>two : any +} +let a1: A1 = { a: true }; +>a1 : A1 +>A1 : A1 +>{ a: true } : { a: true; } +>a : boolean +>true : true + +let b1: B1 = { b: 101 }; +>b1 : B1 +>B1 : B1 +>{ b: 101 } : { b: number; } +>b : number +>101 : 101 + +a1 = override(a1, { a: false }); +>a1 = override(a1, { a: false }) : { a: boolean; } +>a1 : A1 +>override(a1, { a: false }) : { a: boolean; } +>override : (initial: U, override: U) => { ...U } +>a1 : A1 +>{ a: false } : { a: false; } +>a : boolean +>false : false + +let host = { u: a1, update }; +>host : { u: A1; update: (this: { u: { ...U }; }, override: U) => void; } +>{ u: a1, update } : { u: A1; update: (this: { u: { ...U }; }, override: U) => void; } +>u : A1 +>a1 : A1 +>update : (this: { u: { ...U }; }, override: U) => void + +host.update({ a: false }); +>host.update({ a: false }) : void +>host.update : (this: { u: { ...U }; }, override: U) => void +>host : { u: A1; update: (this: { u: { ...U }; }, override: U) => void; } +>update : (this: { u: { ...U }; }, override: U) => void +>{ a: false } : { a: false; } +>a : boolean +>false : false + +let mixed = mixin(a1, b1); +>mixed : { b: number; a: boolean; } +>mixin(a1, b1) : { b: number; a: boolean; } +>mixin : (one: T, two: U) => { ...T; ...U } +>a1 : A1 +>b1 : B1 + diff --git a/tests/baselines/reference/objectSpreadStrictNull.js b/tests/baselines/reference/objectSpreadStrictNull.js new file mode 100644 index 00000000000..84604d728cd --- /dev/null +++ b/tests/baselines/reference/objectSpreadStrictNull.js @@ -0,0 +1,43 @@ +//// [objectSpreadStrictNull.ts] + +function f( + definiteBoolean: { sn: boolean }, + definiteString: { sn: string }, + optionalString: { sn?: string }, + optionalNumber: { sn?: number }, + undefinedString: { sn: string | undefined }, + undefinedNumber: { sn: number | undefined }) { + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; +} + + +//// [objectSpreadStrictNull.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +function f(definiteBoolean, definiteString, optionalString, optionalNumber, undefinedString, undefinedNumber) { + // optional + var optionalUnionStops = __assign({}, definiteBoolean, definiteString, optionalNumber); + var optionalUnionDuplicates = __assign({}, definiteBoolean, definiteString, optionalString, optionalNumber); + var allOptional = __assign({}, optionalString, optionalNumber); + // undefined + var undefinedUnionStops = __assign({}, definiteBoolean, definiteString, undefinedNumber); + var undefinedUnionDuplicates = __assign({}, definiteBoolean, definiteString, undefinedString, undefinedNumber); + var allUndefined = __assign({}, undefinedString, undefinedNumber); + var undefinedWithOptionalContinues = __assign({}, definiteBoolean, undefinedString, optionalNumber); +} diff --git a/tests/baselines/reference/objectSpreadStrictNull.symbols b/tests/baselines/reference/objectSpreadStrictNull.symbols new file mode 100644 index 00000000000..2586d4ddbd3 --- /dev/null +++ b/tests/baselines/reference/objectSpreadStrictNull.symbols @@ -0,0 +1,81 @@ +=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === + +function f( +>f : Symbol(f, Decl(objectSpreadStrictNull.ts, 0, 0)) + + definiteBoolean: { sn: boolean }, +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 2, 22)) + + definiteString: { sn: string }, +>definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 2, 37)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 3, 21)) + + optionalString: { sn?: string }, +>optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 3, 35)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 4, 21)) + + optionalNumber: { sn?: number }, +>optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 4, 36)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 5, 21)) + + undefinedString: { sn: string | undefined }, +>undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 5, 36)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 6, 22)) + + undefinedNumber: { sn: number | undefined }) { +>undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 6, 48)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 7, 22)) + + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +>optionalUnionStops : Symbol(optionalUnionStops, Decl(objectSpreadStrictNull.ts, 9, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 9, 29)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 2, 37)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 4, 36)) + + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +>optionalUnionDuplicates : Symbol(optionalUnionDuplicates, Decl(objectSpreadStrictNull.ts, 10, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 10, 34)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 2, 37)) +>optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 3, 35)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 4, 36)) + + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; +>allOptional : Symbol(allOptional, Decl(objectSpreadStrictNull.ts, 11, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 11, 22)) +>optionalString : Symbol(optionalString, Decl(objectSpreadStrictNull.ts, 3, 35)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 4, 36)) + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; +>undefinedUnionStops : Symbol(undefinedUnionStops, Decl(objectSpreadStrictNull.ts, 14, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 14, 30)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 2, 37)) +>undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 6, 48)) + + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; +>undefinedUnionDuplicates : Symbol(undefinedUnionDuplicates, Decl(objectSpreadStrictNull.ts, 15, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 15, 35)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>definiteString : Symbol(definiteString, Decl(objectSpreadStrictNull.ts, 2, 37)) +>undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 5, 36)) +>undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 6, 48)) + + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; +>allUndefined : Symbol(allUndefined, Decl(objectSpreadStrictNull.ts, 16, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 16, 23)) +>undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 5, 36)) +>undefinedNumber : Symbol(undefinedNumber, Decl(objectSpreadStrictNull.ts, 6, 48)) + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; +>undefinedWithOptionalContinues : Symbol(undefinedWithOptionalContinues, Decl(objectSpreadStrictNull.ts, 18, 7)) +>sn : Symbol(sn, Decl(objectSpreadStrictNull.ts, 18, 41)) +>definiteBoolean : Symbol(definiteBoolean, Decl(objectSpreadStrictNull.ts, 1, 11)) +>undefinedString : Symbol(undefinedString, Decl(objectSpreadStrictNull.ts, 5, 36)) +>optionalNumber : Symbol(optionalNumber, Decl(objectSpreadStrictNull.ts, 4, 36)) +} + diff --git a/tests/baselines/reference/objectSpreadStrictNull.types b/tests/baselines/reference/objectSpreadStrictNull.types new file mode 100644 index 00000000000..c9ed742c6b6 --- /dev/null +++ b/tests/baselines/reference/objectSpreadStrictNull.types @@ -0,0 +1,88 @@ +=== tests/cases/conformance/types/spread/objectSpreadStrictNull.ts === + +function f( +>f : (definiteBoolean: { sn: boolean; }, definiteString: { sn: string; }, optionalString: { sn?: string | undefined; }, optionalNumber: { sn?: number | undefined; }, undefinedString: { sn: string | undefined; }, undefinedNumber: { sn: number | undefined; }) => void + + definiteBoolean: { sn: boolean }, +>definiteBoolean : { sn: boolean; } +>sn : boolean + + definiteString: { sn: string }, +>definiteString : { sn: string; } +>sn : string + + optionalString: { sn?: string }, +>optionalString : { sn?: string | undefined; } +>sn : string | undefined + + optionalNumber: { sn?: number }, +>optionalNumber : { sn?: number | undefined; } +>sn : number | undefined + + undefinedString: { sn: string | undefined }, +>undefinedString : { sn: string | undefined; } +>sn : string | undefined + + undefinedNumber: { sn: number | undefined }) { +>undefinedNumber : { sn: number | undefined; } +>sn : number | undefined + + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +>optionalUnionStops : { sn: string | number; } +>sn : string | number +>{ ...definiteBoolean, ...definiteString, ...optionalNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>optionalNumber : { sn?: number | undefined; } + + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +>optionalUnionDuplicates : { sn: string | number; } +>sn : string | number +>{ ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>optionalString : { sn?: string | undefined; } +>optionalNumber : { sn?: number | undefined; } + + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; +>allOptional : { sn?: string | number | undefined; } +>sn : string | number | undefined +>{ ...optionalString, ...optionalNumber } : { sn?: string | number | undefined; } +>optionalString : { sn?: string | undefined; } +>optionalNumber : { sn?: number | undefined; } + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; +>undefinedUnionStops : { sn: string | number; } +>sn : string | number +>{ ...definiteBoolean, ...definiteString, ...undefinedNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>undefinedNumber : { sn: number | undefined; } + + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; +>undefinedUnionDuplicates : { sn: string | number; } +>sn : string | number +>{ ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber } : { sn: string | number; } +>definiteBoolean : { sn: boolean; } +>definiteString : { sn: string; } +>undefinedString : { sn: string | undefined; } +>undefinedNumber : { sn: number | undefined; } + + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; +>allUndefined : { sn: string | number | undefined; } +>sn : string | number | undefined +>{ ...undefinedString, ...undefinedNumber } : { sn: string | number | undefined; } +>undefinedString : { sn: string | undefined; } +>undefinedNumber : { sn: number | undefined; } + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; +>undefinedWithOptionalContinues : { sn: string | number | boolean; } +>sn : string | number | boolean +>{ ...definiteBoolean, ...undefinedString, ...optionalNumber } : { sn: string | number | boolean; } +>definiteBoolean : { sn: boolean; } +>undefinedString : { sn: string | undefined; } +>optionalNumber : { sn?: number | undefined; } +} + diff --git a/tests/baselines/reference/objectSpreadUnion.js b/tests/baselines/reference/objectSpreadUnion.js new file mode 100644 index 00000000000..b3a114c7722 --- /dev/null +++ b/tests/baselines/reference/objectSpreadUnion.js @@ -0,0 +1,52 @@ +//// [objectSpreadUnion.ts] +// concrete types work +interface A1 { a: number } +interface A2 { a: string } +let a12: A1 | A2; +let result = { ...a12 }; +let sn: number | string = result.a; +let assignable: { ...(A1 | A2) } = result; + +function tripleUnion(t: T, u: U, v: V): void { + let tuv: T | U | V; + let result = { ...tuv, id: 'foo' }; + let expected: { ...T, id: string } | { ...U, id: string } | { ...V, id: string } = result; + let assignable: { ...(T | U | V), id: string } = result; +} +function iteratedDoubleUnion(t: T, u: U, v: V): void { + let tu: T | U; + let uv: U | V; + let result = { ...tu, ...uv, id: 'bar' }; + let expected: { ...T, ...U, id: string } | { ...T, ...V, id: string } | { ...U, id: string } | { ...U, ...V, id: string }; + let assignable: { ...(T | U), ...(U | V), id: string } = result; +} + + + + +//// [objectSpreadUnion.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var a12; +var result = __assign({}, a12); +var sn = result.a; +var assignable = result; +function tripleUnion(t, u, v) { + var tuv; + var result = __assign({}, tuv, { id: 'foo' }); + var expected = result; + var assignable = result; +} +function iteratedDoubleUnion(t, u, v) { + var tu; + var uv; + var result = __assign({}, tu, uv, { id: 'bar' }); + var expected; + var assignable = result; +} diff --git a/tests/baselines/reference/objectSpreadUnion.symbols b/tests/baselines/reference/objectSpreadUnion.symbols new file mode 100644 index 00000000000..d630fde518b --- /dev/null +++ b/tests/baselines/reference/objectSpreadUnion.symbols @@ -0,0 +1,122 @@ +=== tests/cases/conformance/types/spread/objectSpreadUnion.ts === +// concrete types work +interface A1 { a: number } +>A1 : Symbol(A1, Decl(objectSpreadUnion.ts, 0, 0)) +>a : Symbol(A1.a, Decl(objectSpreadUnion.ts, 1, 14)) + +interface A2 { a: string } +>A2 : Symbol(A2, Decl(objectSpreadUnion.ts, 1, 26)) +>a : Symbol(A2.a, Decl(objectSpreadUnion.ts, 2, 14)) + +let a12: A1 | A2; +>a12 : Symbol(a12, Decl(objectSpreadUnion.ts, 3, 3)) +>A1 : Symbol(A1, Decl(objectSpreadUnion.ts, 0, 0)) +>A2 : Symbol(A2, Decl(objectSpreadUnion.ts, 1, 26)) + +let result = { ...a12 }; +>result : Symbol(result, Decl(objectSpreadUnion.ts, 4, 3)) + +let sn: number | string = result.a; +>sn : Symbol(sn, Decl(objectSpreadUnion.ts, 5, 3)) +>result.a : Symbol(a, Decl(objectSpreadUnion.ts, 1, 14), Decl(objectSpreadUnion.ts, 2, 14)) +>result : Symbol(result, Decl(objectSpreadUnion.ts, 4, 3)) +>a : Symbol(a, Decl(objectSpreadUnion.ts, 1, 14), Decl(objectSpreadUnion.ts, 2, 14)) + +let assignable: { ...(A1 | A2) } = result; +>assignable : Symbol(assignable, Decl(objectSpreadUnion.ts, 6, 3)) +>A1 : Symbol(A1, Decl(objectSpreadUnion.ts, 0, 0)) +>A2 : Symbol(A2, Decl(objectSpreadUnion.ts, 1, 26)) +>result : Symbol(result, Decl(objectSpreadUnion.ts, 4, 3)) + +function tripleUnion(t: T, u: U, v: V): void { +>tripleUnion : Symbol(tripleUnion, Decl(objectSpreadUnion.ts, 6, 42)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 8, 21)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 8, 23)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 8, 26)) +>t : Symbol(t, Decl(objectSpreadUnion.ts, 8, 30)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 8, 21)) +>u : Symbol(u, Decl(objectSpreadUnion.ts, 8, 35)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 8, 23)) +>v : Symbol(v, Decl(objectSpreadUnion.ts, 8, 41)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 8, 26)) + + let tuv: T | U | V; +>tuv : Symbol(tuv, Decl(objectSpreadUnion.ts, 9, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 8, 21)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 8, 23)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 8, 26)) + + let result = { ...tuv, id: 'foo' }; +>result : Symbol(result, Decl(objectSpreadUnion.ts, 10, 7)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 10, 26)) + + let expected: { ...T, id: string } | { ...U, id: string } | { ...V, id: string } = result; +>expected : Symbol(expected, Decl(objectSpreadUnion.ts, 11, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 8, 21)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 11, 25)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 8, 23)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 11, 48)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 8, 26)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 11, 71)) +>result : Symbol(result, Decl(objectSpreadUnion.ts, 10, 7)) + + let assignable: { ...(T | U | V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadUnion.ts, 12, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 8, 21)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 8, 23)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 8, 26)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 12, 37)) +>result : Symbol(result, Decl(objectSpreadUnion.ts, 10, 7)) +} +function iteratedDoubleUnion(t: T, u: U, v: V): void { +>iteratedDoubleUnion : Symbol(iteratedDoubleUnion, Decl(objectSpreadUnion.ts, 13, 1)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) +>t : Symbol(t, Decl(objectSpreadUnion.ts, 14, 38)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>u : Symbol(u, Decl(objectSpreadUnion.ts, 14, 43)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>v : Symbol(v, Decl(objectSpreadUnion.ts, 14, 49)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) + + let tu: T | U; +>tu : Symbol(tu, Decl(objectSpreadUnion.ts, 15, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) + + let uv: U | V; +>uv : Symbol(uv, Decl(objectSpreadUnion.ts, 16, 7)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) + + let result = { ...tu, ...uv, id: 'bar' }; +>result : Symbol(result, Decl(objectSpreadUnion.ts, 17, 7)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 17, 32)) + + let expected: { ...T, ...U, id: string } | { ...T, ...V, id: string } | { ...U, id: string } | { ...U, ...V, id: string }; +>expected : Symbol(expected, Decl(objectSpreadUnion.ts, 18, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 18, 31)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 18, 60)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 18, 83)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 18, 112)) + + let assignable: { ...(T | U), ...(U | V), id: string } = result; +>assignable : Symbol(assignable, Decl(objectSpreadUnion.ts, 19, 7)) +>T : Symbol(T, Decl(objectSpreadUnion.ts, 14, 29)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>U : Symbol(U, Decl(objectSpreadUnion.ts, 14, 31)) +>V : Symbol(V, Decl(objectSpreadUnion.ts, 14, 34)) +>id : Symbol(id, Decl(objectSpreadUnion.ts, 19, 45)) +>result : Symbol(result, Decl(objectSpreadUnion.ts, 17, 7)) +} + + + diff --git a/tests/baselines/reference/objectSpreadUnion.types b/tests/baselines/reference/objectSpreadUnion.types new file mode 100644 index 00000000000..20633295acb --- /dev/null +++ b/tests/baselines/reference/objectSpreadUnion.types @@ -0,0 +1,131 @@ +=== tests/cases/conformance/types/spread/objectSpreadUnion.ts === +// concrete types work +interface A1 { a: number } +>A1 : A1 +>a : number + +interface A2 { a: string } +>A2 : A2 +>a : string + +let a12: A1 | A2; +>a12 : A1 | A2 +>A1 : A1 +>A2 : A2 + +let result = { ...a12 }; +>result : { a: number; } | { a: string; } +>{ ...a12 } : { a: number; } | { a: string; } +>a12 : any + +let sn: number | string = result.a; +>sn : string | number +>result.a : string | number +>result : { a: number; } | { a: string; } +>a : string | number + +let assignable: { ...(A1 | A2) } = result; +>assignable : { a: number; } | { a: string; } +>A1 : A1 +>A2 : A2 +>result : { a: number; } | { a: string; } + +function tripleUnion(t: T, u: U, v: V): void { +>tripleUnion : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tuv: T | U | V; +>tuv : T | U | V +>T : T +>U : U +>V : V + + let result = { ...tuv, id: 'foo' }; +>result : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } +>{ ...tuv, id: 'foo' } : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } +>tuv : any +>id : string +>'foo' : "foo" + + let expected: { ...T, id: string } | { ...U, id: string } | { ...V, id: string } = result; +>expected : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } +>T : T +>id : string +>U : U +>id : string +>V : V +>id : string +>result : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } + + let assignable: { ...(T | U | V), id: string } = result; +>assignable : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } +>T : T +>U : U +>V : V +>id : string +>result : { ...T; id: string; } | { ...U; id: string; } | { ...V; id: string; } +} +function iteratedDoubleUnion(t: T, u: U, v: V): void { +>iteratedDoubleUnion : (t: T, u: U, v: V) => void +>T : T +>U : U +>V : V +>t : T +>T : T +>u : U +>U : U +>v : V +>V : V + + let tu: T | U; +>tu : T | U +>T : T +>U : U + + let uv: U | V; +>uv : U | V +>U : U +>V : V + + let result = { ...tu, ...uv, id: 'bar' }; +>result : { ...U; id: string; } | { ...T; ...U; id: string; } | { ...T; ...V; id: string; } | { ...U; ...V; id: string; } +>{ ...tu, ...uv, id: 'bar' } : { ...U; id: string; } | { ...T; ...U; id: string; } | { ...T; ...V; id: string; } | { ...U; ...V; id: string; } +>tu : any +>uv : any +>id : string +>'bar' : "bar" + + let expected: { ...T, ...U, id: string } | { ...T, ...V, id: string } | { ...U, id: string } | { ...U, ...V, id: string }; +>expected : { ...T; ...U; id: string; } | { ...T; ...V; id: string; } | { ...U; id: string; } | { ...U; ...V; id: string; } +>T : T +>U : U +>id : string +>T : T +>V : V +>id : string +>U : U +>id : string +>U : U +>V : V +>id : string + + let assignable: { ...(T | U), ...(U | V), id: string } = result; +>assignable : { ...U; id: string; } | { ...T; ...U; id: string; } | { ...T; ...V; id: string; } | { ...U; ...V; id: string; } +>T : T +>U : U +>U : U +>V : V +>id : string +>result : { ...U; id: string; } | { ...T; ...U; id: string; } | { ...T; ...V; id: string; } | { ...U; ...V; id: string; } +} + + + diff --git a/tests/baselines/reference/objectTypeWithStringNamedNumericProperty.types b/tests/baselines/reference/objectTypeWithStringNamedNumericProperty.types index 5e664fadd20..e050d33024c 100644 --- a/tests/baselines/reference/objectTypeWithStringNamedNumericProperty.types +++ b/tests/baselines/reference/objectTypeWithStringNamedNumericProperty.types @@ -84,15 +84,15 @@ var r3 = c[1.0]; // same as indexing by 1 when done numerically // BUG 823822 var r7 = i[-1]; ->r7 : any ->i[-1] : any +>r7 : Date +>i[-1] : Date >i : I >-1 : -1 >1 : 1 var r7 = i[-1.0]; ->r7 : any ->i[-1.0] : any +>r7 : Date +>i[-1.0] : Date >i : I >-1.0 : -1 >1.0 : 1 @@ -116,8 +116,8 @@ var r10 = i[0x1] >0x1 : 1 var r11 = i[-0x1] ->r11 : any ->i[-0x1] : any +>r11 : Date +>i[-0x1] : Date >i : I >-0x1 : -1 >0x1 : 1 @@ -129,8 +129,8 @@ var r12 = i[01] >01 : 1 var r13 = i[-01] ->r13 : any ->i[-01] : any +>r13 : Date +>i[-01] : Date >i : I >-01 : -1 >01 : 1 @@ -215,15 +215,15 @@ var r3 = c[1.0]; // same as indexing by 1 when done numerically // BUG 823822 var r7 = i[-1]; ->r7 : any ->i[-1] : any +>r7 : Date +>i[-1] : Date >i : I >-1 : -1 >1 : 1 var r7 = i[-1.0]; ->r7 : any ->i[-1.0] : any +>r7 : Date +>i[-1.0] : Date >i : I >-1.0 : -1 >1.0 : 1 @@ -247,8 +247,8 @@ var r10 = i[0x1] >0x1 : 1 var r11 = i[-0x1] ->r11 : any ->i[-0x1] : any +>r11 : Date +>i[-0x1] : Date >i : I >-0x1 : -1 >0x1 : 1 @@ -260,8 +260,8 @@ var r12 = i[01] >01 : 1 var r13 = i[-01] ->r13 : any ->i[-01] : any +>r13 : Date +>i[-01] : Date >i : I >-01 : -1 >01 : 1 @@ -342,15 +342,15 @@ var r3 = c[1.0]; // same as indexing by 1 when done numerically // BUG 823822 var r7 = i[-1]; ->r7 : any ->i[-1] : any +>r7 : Date +>i[-1] : Date >i : I >-1 : -1 >1 : 1 var r7 = i[-1.0]; ->r7 : any ->i[-1.0] : any +>r7 : Date +>i[-1.0] : Date >i : I >-1.0 : -1 >1.0 : 1 @@ -374,8 +374,8 @@ var r10 = i[0x1] >0x1 : 1 var r11 = i[-0x1] ->r11 : any ->i[-0x1] : any +>r11 : Date +>i[-0x1] : Date >i : I >-0x1 : -1 >0x1 : 1 @@ -387,8 +387,8 @@ var r12 = i[01] >01 : 1 var r13 = i[-01] ->r13 : any ->i[-01] : any +>r13 : Date +>i[-01] : Date >i : I >-01 : -1 >01 : 1 @@ -482,15 +482,15 @@ var r3 = c[1.0]; // same as indexing by 1 when done numerically // BUG 823822 var r7 = i[-1]; ->r7 : any ->i[-1] : any +>r7 : Date +>i[-1] : Date >i : I >-1 : -1 >1 : 1 var r7 = i[-1.0]; ->r7 : any ->i[-1.0] : any +>r7 : Date +>i[-1.0] : Date >i : I >-1.0 : -1 >1.0 : 1 @@ -514,8 +514,8 @@ var r10 = i[0x1] >0x1 : 1 var r11 = i[-0x1] ->r11 : any ->i[-0x1] : any +>r11 : Date +>i[-0x1] : Date >i : I >-0x1 : -1 >0x1 : 1 @@ -527,8 +527,8 @@ var r12 = i[01] >01 : 1 var r13 = i[-01] ->r13 : any ->i[-01] : any +>r13 : Date +>i[-01] : Date >i : I >-01 : -1 >01 : 1 diff --git a/tests/baselines/reference/objectTypesIdentityWithConstructSignatures2.js b/tests/baselines/reference/objectTypesIdentityWithConstructSignatures2.js index 315e079d429..0a422dbda6f 100644 --- a/tests/baselines/reference/objectTypesIdentityWithConstructSignatures2.js +++ b/tests/baselines/reference/objectTypesIdentityWithConstructSignatures2.js @@ -91,7 +91,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return ''; } }; // not a construct signature, function called new +var b = { "new": function (x) { return ''; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithConstructSignaturesDifferingParamCounts.js b/tests/baselines/reference/objectTypesIdentityWithConstructSignaturesDifferingParamCounts.js index a61bedfd52f..5fa148b541d 100644 --- a/tests/baselines/reference/objectTypesIdentityWithConstructSignaturesDifferingParamCounts.js +++ b/tests/baselines/reference/objectTypesIdentityWithConstructSignaturesDifferingParamCounts.js @@ -91,7 +91,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return ''; } }; // not a construct signature, function called new +var b = { "new": function (x) { return ''; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints.js index c15c53b9bf8..6a66e8bbda3 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints.js @@ -92,7 +92,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return ''; } }; // not a construct signature, function called new +var b = { "new": function (x) { return ''; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints2.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints2.js index f8aff596dc9..e19837a9f7f 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints2.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints2.js @@ -109,7 +109,7 @@ var D = (function () { return D; }()); var a; -var b = { new: function (x, y) { return ''; } }; // not a construct signature, function called new +var b = { "new": function (x, y) { return ''; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints3.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints3.js index 141aa86823b..735c5bdc2d6 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints3.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByConstraints3.js @@ -128,7 +128,7 @@ var D = (function () { return D; }()); var a; -var b = { new: function (x, y) { return ''; } }; // not a construct signature, function called new +var b = { "new": function (x, y) { return ''; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType.js index b651d368f33..6eab84a49dd 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType.js @@ -99,7 +99,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return null; } }; // not a construct signature, function called new +var b = { "new": function (x) { return null; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.js index ff7095c4ea1..d927a8e082a 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.js @@ -95,7 +95,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return null; } }; // not a construct signature, function called new +var b = { "new": function (x) { return null; } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterCounts.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterCounts.js index 314eb700c4b..512bebb3b0e 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterCounts.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterCounts.js @@ -87,7 +87,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return x; } }; +var b = { "new": function (x) { return x; } }; function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterNames.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterNames.js index 182cf8263b7..80cfcd23ec9 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterNames.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterNames.js @@ -87,7 +87,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x) { return new C(x); } }; +var b = { "new": function (x) { return new C(x); } }; function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams.js index 5c5dd26c331..87cb0b33531 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams.js @@ -91,7 +91,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x, y) { return new C(x, y); } }; // not a construct signature, function called new +var b = { "new": function (x, y) { return new C(x, y); } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams2.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams2.js index 14b2ec3c0ca..6b0e91f817f 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams2.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams2.js @@ -91,7 +91,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x, y) { return new C(x, y); } }; // not a construct signature, function called new +var b = { "new": function (x, y) { return new C(x, y); } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.js b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.js index ffc238cacae..55f2a0217e9 100644 --- a/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.js +++ b/tests/baselines/reference/objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.js @@ -91,7 +91,7 @@ var C = (function () { return C; }()); var a; -var b = { new: function (x, y) { return new C(x, y); } }; // not a construct signature, function called new +var b = { "new": function (x, y) { return new C(x, y); } }; // not a construct signature, function called new function foo1b(x) { } function foo1c(x) { } function foo2(x) { } diff --git a/tests/baselines/reference/oldStyleOctalLiteralTypes.errors.txt b/tests/baselines/reference/oldStyleOctalLiteralTypes.errors.txt new file mode 100644 index 00000000000..7d42963b05d --- /dev/null +++ b/tests/baselines/reference/oldStyleOctalLiteralTypes.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/oldStyleOctalLiteralTypes.ts(1,8): error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '0o10'. +tests/cases/compiler/oldStyleOctalLiteralTypes.ts(2,8): error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '-0o20'. + + +==== tests/cases/compiler/oldStyleOctalLiteralTypes.ts (2 errors) ==== + let x: 010; + ~~~ +!!! error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '0o10'. + let y: -020; + ~~~~ +!!! error TS8017: Octal literal types must use ES2015 syntax. Use the syntax '-0o20'. + \ No newline at end of file diff --git a/tests/baselines/reference/oldStyleOctalLiteralTypes.js b/tests/baselines/reference/oldStyleOctalLiteralTypes.js new file mode 100644 index 00000000000..28b275774c3 --- /dev/null +++ b/tests/baselines/reference/oldStyleOctalLiteralTypes.js @@ -0,0 +1,8 @@ +//// [oldStyleOctalLiteralTypes.ts] +let x: 010; +let y: -020; + + +//// [oldStyleOctalLiteralTypes.js] +var x; +var y; diff --git a/tests/baselines/reference/optionalBindingParametersInOverloads1.js b/tests/baselines/reference/optionalBindingParametersInOverloads1.js index 3658efa72c6..9fd64d0da9e 100644 --- a/tests/baselines/reference/optionalBindingParametersInOverloads1.js +++ b/tests/baselines/reference/optionalBindingParametersInOverloads1.js @@ -13,7 +13,7 @@ foo([false, 0, ""]); function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } foo(["", 0, false]); diff --git a/tests/baselines/reference/optionalBindingParametersInOverloads2.js b/tests/baselines/reference/optionalBindingParametersInOverloads2.js index 1ddfdae4f07..033d81993f5 100644 --- a/tests/baselines/reference/optionalBindingParametersInOverloads2.js +++ b/tests/baselines/reference/optionalBindingParametersInOverloads2.js @@ -13,7 +13,7 @@ foo({ x: false, y: 0, z: "" }); function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } foo({ x: "", y: 0, z: false }); diff --git a/tests/baselines/reference/optionalProperties01.js b/tests/baselines/reference/optionalProperties01.js new file mode 100644 index 00000000000..a614b9e7e37 --- /dev/null +++ b/tests/baselines/reference/optionalProperties01.js @@ -0,0 +1,25 @@ +//// [optionalProperties01.ts] + +interface Foo { + required1: string; + required2: string; + optional?: string; +} + +const foo1 = { required1: "hello" } as Foo; +const foo2 = { required1: "hello", optional: "bar" } as Foo; + + +//// [optionalProperties01.js] +var foo1 = { required1: "hello" }; +var foo2 = { required1: "hello", optional: "bar" }; + + +//// [optionalProperties01.d.ts] +interface Foo { + required1: string; + required2: string; + optional?: string; +} +declare const foo1: Foo; +declare const foo2: Foo; diff --git a/tests/baselines/reference/optionalProperties01.symbols b/tests/baselines/reference/optionalProperties01.symbols new file mode 100644 index 00000000000..95c53626f6e --- /dev/null +++ b/tests/baselines/reference/optionalProperties01.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/types/typeRelationships/comparable/optionalProperties01.ts === + +interface Foo { +>Foo : Symbol(Foo, Decl(optionalProperties01.ts, 0, 0)) + + required1: string; +>required1 : Symbol(Foo.required1, Decl(optionalProperties01.ts, 1, 15)) + + required2: string; +>required2 : Symbol(Foo.required2, Decl(optionalProperties01.ts, 2, 20)) + + optional?: string; +>optional : Symbol(Foo.optional, Decl(optionalProperties01.ts, 3, 20)) +} + +const foo1 = { required1: "hello" } as Foo; +>foo1 : Symbol(foo1, Decl(optionalProperties01.ts, 7, 5)) +>required1 : Symbol(required1, Decl(optionalProperties01.ts, 7, 14)) +>Foo : Symbol(Foo, Decl(optionalProperties01.ts, 0, 0)) + +const foo2 = { required1: "hello", optional: "bar" } as Foo; +>foo2 : Symbol(foo2, Decl(optionalProperties01.ts, 8, 5)) +>required1 : Symbol(required1, Decl(optionalProperties01.ts, 8, 14)) +>optional : Symbol(optional, Decl(optionalProperties01.ts, 8, 34)) +>Foo : Symbol(Foo, Decl(optionalProperties01.ts, 0, 0)) + diff --git a/tests/baselines/reference/optionalProperties01.types b/tests/baselines/reference/optionalProperties01.types new file mode 100644 index 00000000000..20d16d4071e --- /dev/null +++ b/tests/baselines/reference/optionalProperties01.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/types/typeRelationships/comparable/optionalProperties01.ts === + +interface Foo { +>Foo : Foo + + required1: string; +>required1 : string + + required2: string; +>required2 : string + + optional?: string; +>optional : string | undefined +} + +const foo1 = { required1: "hello" } as Foo; +>foo1 : Foo +>{ required1: "hello" } as Foo : Foo +>{ required1: "hello" } : { required1: string; } +>required1 : string +>"hello" : "hello" +>Foo : Foo + +const foo2 = { required1: "hello", optional: "bar" } as Foo; +>foo2 : Foo +>{ required1: "hello", optional: "bar" } as Foo : Foo +>{ required1: "hello", optional: "bar" } : { required1: string; optional: string; } +>required1 : string +>"hello" : "hello" +>optional : string +>"bar" : "bar" +>Foo : Foo + diff --git a/tests/baselines/reference/optionalProperties02.js b/tests/baselines/reference/optionalProperties02.js new file mode 100644 index 00000000000..f632c5d67a8 --- /dev/null +++ b/tests/baselines/reference/optionalProperties02.js @@ -0,0 +1,18 @@ +//// [optionalProperties02.ts] + +interface Foo { + a?: string; + b: string; +} + +{ a: undefined }; + +//// [optionalProperties02.js] +({ a: undefined }); + + +//// [optionalProperties02.d.ts] +interface Foo { + a?: string; + b: string; +} diff --git a/tests/baselines/reference/optionalProperties02.symbols b/tests/baselines/reference/optionalProperties02.symbols new file mode 100644 index 00000000000..b88f9ad7429 --- /dev/null +++ b/tests/baselines/reference/optionalProperties02.symbols @@ -0,0 +1,17 @@ +=== tests/cases/conformance/types/typeRelationships/comparable/optionalProperties02.ts === + +interface Foo { +>Foo : Symbol(Foo, Decl(optionalProperties02.ts, 0, 0)) + + a?: string; +>a : Symbol(Foo.a, Decl(optionalProperties02.ts, 1, 15)) + + b: string; +>b : Symbol(Foo.b, Decl(optionalProperties02.ts, 2, 15)) +} + +{ a: undefined }; +>Foo : Symbol(Foo, Decl(optionalProperties02.ts, 0, 0)) +>a : Symbol(a, Decl(optionalProperties02.ts, 6, 6)) +>undefined : Symbol(undefined) + diff --git a/tests/baselines/reference/optionalProperties02.types b/tests/baselines/reference/optionalProperties02.types new file mode 100644 index 00000000000..05e979b3972 --- /dev/null +++ b/tests/baselines/reference/optionalProperties02.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/types/typeRelationships/comparable/optionalProperties02.ts === + +interface Foo { +>Foo : Foo + + a?: string; +>a : string | undefined + + b: string; +>b : string +} + +{ a: undefined }; +>{ a: undefined } : Foo +>Foo : Foo +>{ a: undefined } : { a: undefined; } +>a : undefined +>undefined : undefined + diff --git a/tests/baselines/reference/outFilerootDirModuleNamesSystem.js b/tests/baselines/reference/outFilerootDirModuleNamesSystem.js index 6754f3ef89a..efc49f90209 100644 --- a/tests/baselines/reference/outFilerootDirModuleNamesSystem.js +++ b/tests/baselines/reference/outFilerootDirModuleNamesSystem.js @@ -15,8 +15,8 @@ System.register("b", ["a"], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function foo() { new a_1.default(); } - var a_1; exports_1("default", foo); + var a_1; return { setters: [ function (a_1_1) { diff --git a/tests/baselines/reference/outModuleConcatAmd.js.map b/tests/baselines/reference/outModuleConcatAmd.js.map index e987d5deb8a..9187aca0646 100644 --- a/tests/baselines/reference/outModuleConcatAmd.js.map +++ b/tests/baselines/reference/outModuleConcatAmd.js.map @@ -1,2 +1,2 @@ //// [all.js.map] -{"version":3,"file":"all.js","sourceRoot":"","sources":["tests/cases/compiler/ref/a.ts","tests/cases/compiler/b.ts"],"names":[],"mappings":";;;;;;;IACA;QAAA;QAAiB,CAAC;QAAD,QAAC;IAAD,CAAC,AAAlB,IAAkB;IAAlB,cAAkB;;;;ICAlB;QAAuB,qBAAC;QAAxB;;QAA2B,CAAC;QAAD,QAAC;IAAD,CAAC,AAA5B,CAAuB,KAAC,GAAI;IAA5B,cAA4B"} \ No newline at end of file +{"version":3,"file":"all.js","sourceRoot":"","sources":["tests/cases/compiler/ref/a.ts","tests/cases/compiler/b.ts"],"names":[],"mappings":";;;;;;;IACA;QAAA;QAAiB,CAAC;QAAD,QAAC;IAAD,CAAC,AAAlB,IAAkB;IAAL,cAAC;;;;ICAd;QAAuB,qBAAC;QAAxB;;QAA2B,CAAC;QAAD,QAAC;IAAD,CAAC,AAA5B,CAAuB,KAAC,GAAI;IAAf,cAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/outModuleConcatAmd.sourcemap.txt b/tests/baselines/reference/outModuleConcatAmd.sourcemap.txt index 1bfda049776..34ab74816ad 100644 --- a/tests/baselines/reference/outModuleConcatAmd.sourcemap.txt +++ b/tests/baselines/reference/outModuleConcatAmd.sourcemap.txt @@ -64,9 +64,9 @@ sourceFile:tests/cases/compiler/ref/a.ts 1->^^^^ 2 > ^^^^^^^^^^^^^^ 1-> -2 > export class A { } -1->Emitted(13, 5) Source(2, 1) + SourceIndex(0) -2 >Emitted(13, 19) Source(2, 19) + SourceIndex(0) +2 > A +1->Emitted(13, 5) Source(2, 14) + SourceIndex(0) +2 >Emitted(13, 19) Source(2, 15) + SourceIndex(0) --- ------------------------------------------------------------------- emittedFile:all.js @@ -139,9 +139,9 @@ sourceFile:tests/cases/compiler/b.ts 1->^^^^ 2 > ^^^^^^^^^^^^^^ 1-> -2 > export class B extends A { } -1->Emitted(24, 5) Source(2, 1) + SourceIndex(1) -2 >Emitted(24, 19) Source(2, 29) + SourceIndex(1) +2 > B +1->Emitted(24, 5) Source(2, 14) + SourceIndex(1) +2 >Emitted(24, 19) Source(2, 15) + SourceIndex(1) --- >>>}); >>>//# sourceMappingURL=all.js.map \ No newline at end of file diff --git a/tests/baselines/reference/outModuleTripleSlashRefs.js.map b/tests/baselines/reference/outModuleTripleSlashRefs.js.map index 45d57990450..5ccc59aeabf 100644 --- a/tests/baselines/reference/outModuleTripleSlashRefs.js.map +++ b/tests/baselines/reference/outModuleTripleSlashRefs.js.map @@ -1,2 +1,2 @@ //// [all.js.map] -{"version":3,"file":"all.js","sourceRoot":"","sources":["tests/cases/compiler/ref/b.ts","tests/cases/compiler/ref/a.ts","tests/cases/compiler/b.ts"],"names":[],"mappings":";;;;;AAAA,iCAAiC;AACjC;IAAA;IAEA,CAAC;IAAD,UAAC;AAAD,CAAC,AAFD,IAEC;;;ICFD,+BAA+B;IAC/B;QAAA;QAEA,CAAC;QAAD,QAAC;IAAD,CAAC,AAFD,IAEC;IAFD,cAEC;;;;ICHD;QAAuB,qBAAC;QAAxB;;QAA2B,CAAC;QAAD,QAAC;IAAD,CAAC,AAA5B,CAAuB,KAAC,GAAI;IAA5B,cAA4B"} \ No newline at end of file +{"version":3,"file":"all.js","sourceRoot":"","sources":["tests/cases/compiler/ref/b.ts","tests/cases/compiler/ref/a.ts","tests/cases/compiler/b.ts"],"names":[],"mappings":";;;;;AAAA,iCAAiC;AACjC;IAAA;IAEA,CAAC;IAAD,UAAC;AAAD,CAAC,AAFD,IAEC;;;ICFD,+BAA+B;IAC/B;QAAA;QAEA,CAAC;QAAD,QAAC;IAAD,CAAC,AAFD,IAEC;IAFY,cAAC;;;;ICDd;QAAuB,qBAAC;QAAxB;;QAA2B,CAAC;QAAD,QAAC;IAAD,CAAC,AAA5B,CAAuB,KAAC,GAAI;IAAf,cAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/outModuleTripleSlashRefs.sourcemap.txt b/tests/baselines/reference/outModuleTripleSlashRefs.sourcemap.txt index 482c898e0cb..ce41bae6de3 100644 --- a/tests/baselines/reference/outModuleTripleSlashRefs.sourcemap.txt +++ b/tests/baselines/reference/outModuleTripleSlashRefs.sourcemap.txt @@ -138,11 +138,9 @@ sourceFile:tests/cases/compiler/ref/a.ts 1->^^^^ 2 > ^^^^^^^^^^^^^^ 1-> -2 > export class A { - > member: typeof GlobalFoo; - > } -1->Emitted(20, 5) Source(3, 1) + SourceIndex(1) -2 >Emitted(20, 19) Source(5, 2) + SourceIndex(1) +2 > A +1->Emitted(20, 5) Source(3, 14) + SourceIndex(1) +2 >Emitted(20, 19) Source(3, 15) + SourceIndex(1) --- ------------------------------------------------------------------- emittedFile:all.js @@ -215,9 +213,9 @@ sourceFile:tests/cases/compiler/b.ts 1->^^^^ 2 > ^^^^^^^^^^^^^^ 1-> -2 > export class B extends A { } -1->Emitted(31, 5) Source(2, 1) + SourceIndex(2) -2 >Emitted(31, 19) Source(2, 29) + SourceIndex(2) +2 > B +1->Emitted(31, 5) Source(2, 14) + SourceIndex(2) +2 >Emitted(31, 19) Source(2, 15) + SourceIndex(2) --- >>>}); >>>//# sourceMappingURL=all.js.map \ No newline at end of file diff --git a/tests/baselines/reference/overloadGenericFunctionWithRestArgs.js b/tests/baselines/reference/overloadGenericFunctionWithRestArgs.js index 356cece5ab6..e83f33f3ad0 100644 --- a/tests/baselines/reference/overloadGenericFunctionWithRestArgs.js +++ b/tests/baselines/reference/overloadGenericFunctionWithRestArgs.js @@ -24,7 +24,7 @@ var A = (function () { function Choice() { var v_args = []; for (var _i = 0; _i < arguments.length; _i++) { - v_args[_i - 0] = arguments[_i]; + v_args[_i] = arguments[_i]; } return new A(); } diff --git a/tests/baselines/reference/parenthesizedContexualTyping2.js b/tests/baselines/reference/parenthesizedContexualTyping2.js index 993a10ba49c..48b9355ca31 100644 --- a/tests/baselines/reference/parenthesizedContexualTyping2.js +++ b/tests/baselines/reference/parenthesizedContexualTyping2.js @@ -45,7 +45,7 @@ var obj2: ObjType = ({ x: x => (x, undefined), y: y => (y, undefined) }); function fun() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } return undefined; } diff --git a/tests/baselines/reference/parser509668.js b/tests/baselines/reference/parser509668.js index c767aea676a..5dfdc7d1e31 100644 --- a/tests/baselines/reference/parser509668.js +++ b/tests/baselines/reference/parser509668.js @@ -10,7 +10,7 @@ var Foo3 = (function () { function Foo3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } this.args = args; } diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator1.types b/tests/baselines/reference/parserAmbiguityWithBinaryOperator1.types index ca7d65c9c34..234375fb46d 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator1.types +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator1.types @@ -10,12 +10,12 @@ function f1() { if (a < b || b > (c + 1)) { } >a < b || b > (c + 1) : boolean >a < b : boolean ->a : undefined ->b : undefined +>a : any +>b : any >b > (c + 1) : boolean ->b : undefined ->(c + 1) : number ->c + 1 : number ->c : undefined +>b : any +>(c + 1) : any +>c + 1 : any +>c : any >1 : 1 } diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator2.types b/tests/baselines/reference/parserAmbiguityWithBinaryOperator2.types index f4c1c2ac690..ed3b4b903bb 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator2.types +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator2.types @@ -10,12 +10,12 @@ function f() { if (a < b && b > (c + 1)) { } >a < b && b > (c + 1) : boolean >a < b : boolean ->a : undefined ->b : undefined +>a : any +>b : any >b > (c + 1) : boolean ->b : undefined ->(c + 1) : number ->c + 1 : number ->c : undefined +>b : any +>(c + 1) : any +>c + 1 : any +>c : any >1 : 1 } diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator3.types b/tests/baselines/reference/parserAmbiguityWithBinaryOperator3.types index b1129656342..61601d8bdf6 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator3.types +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator3.types @@ -10,13 +10,13 @@ function f() { if (a < b && b < (c + 1)) { } >a < b && b < (c + 1) : boolean >a < b : boolean ->a : undefined ->b : undefined +>a : any +>b : any >b < (c + 1) : boolean ->b : undefined ->(c + 1) : number ->c + 1 : number ->c : undefined +>b : any +>(c + 1) : any +>c + 1 : any +>c : any >1 : 1 } diff --git a/tests/baselines/reference/parserAssignmentExpression1.errors.txt b/tests/baselines/reference/parserAssignmentExpression1.errors.txt index 70eecd81b39..4a5891eb6a9 100644 --- a/tests/baselines/reference/parserAssignmentExpression1.errors.txt +++ b/tests/baselines/reference/parserAssignmentExpression1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpression1.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpression1.ts(1,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpression1.ts(1,2): error TS2304: Cannot find name 'foo'. tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpression1.ts(1,11): error TS2304: Cannot find name 'bar'. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpressio ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserAssignmentExpression1.ts (3 errors) ==== (foo()) = bar; ~~~~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ~~~ !!! error TS2304: Cannot find name 'foo'. ~~~ diff --git a/tests/baselines/reference/parserES5ForOfStatement19.errors.txt b/tests/baselines/reference/parserES5ForOfStatement19.errors.txt deleted file mode 100644 index 9d0bb02f1ef..00000000000 --- a/tests/baselines/reference/parserES5ForOfStatement19.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement19.ts(1,16): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. - - -==== tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement19.ts (1 errors) ==== - for (var of in of) { } - ~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. \ No newline at end of file diff --git a/tests/baselines/reference/parserES5ForOfStatement19.symbols b/tests/baselines/reference/parserES5ForOfStatement19.symbols new file mode 100644 index 00000000000..93ba77e3db9 --- /dev/null +++ b/tests/baselines/reference/parserES5ForOfStatement19.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement19.ts === +for (var of in of) { } +>of : Symbol(of, Decl(parserES5ForOfStatement19.ts, 0, 8)) +>of : Symbol(of, Decl(parserES5ForOfStatement19.ts, 0, 8)) + diff --git a/tests/baselines/reference/parserES5ForOfStatement19.types b/tests/baselines/reference/parserES5ForOfStatement19.types new file mode 100644 index 00000000000..13abc7ae757 --- /dev/null +++ b/tests/baselines/reference/parserES5ForOfStatement19.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement19.ts === +for (var of in of) { } +>of : any +>of : any + diff --git a/tests/baselines/reference/parserES5ForOfStatement20.errors.txt b/tests/baselines/reference/parserES5ForOfStatement20.errors.txt index 2bfc54590ad..4aee32394b6 100644 --- a/tests/baselines/reference/parserES5ForOfStatement20.errors.txt +++ b/tests/baselines/reference/parserES5ForOfStatement20.errors.txt @@ -1,10 +1,7 @@ tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement20.ts(1,10): error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. -tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement20.ts(1,20): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -==== tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement20.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement20.ts (1 errors) ==== for (var of = 0 in of) { } ~~ -!!! error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. - ~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. \ No newline at end of file +!!! error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/parserEnum1.js b/tests/baselines/reference/parserEnum1.js index e54fff50c73..d2c29d847cd 100644 --- a/tests/baselines/reference/parserEnum1.js +++ b/tests/baselines/reference/parserEnum1.js @@ -10,10 +10,10 @@ //// [parserEnum1.js] "use strict"; +var SignatureFlags; (function (SignatureFlags) { SignatureFlags[SignatureFlags["None"] = 0] = "None"; SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; SignatureFlags[SignatureFlags["IsStringIndexer"] = 2] = "IsStringIndexer"; SignatureFlags[SignatureFlags["IsNumberIndexer"] = 4] = "IsNumberIndexer"; -})(exports.SignatureFlags || (exports.SignatureFlags = {})); -var SignatureFlags = exports.SignatureFlags; +})(SignatureFlags = exports.SignatureFlags || (exports.SignatureFlags = {})); diff --git a/tests/baselines/reference/parserEnum2.js b/tests/baselines/reference/parserEnum2.js index 8e7da5c73cd..f5888addf75 100644 --- a/tests/baselines/reference/parserEnum2.js +++ b/tests/baselines/reference/parserEnum2.js @@ -10,10 +10,10 @@ //// [parserEnum2.js] "use strict"; +var SignatureFlags; (function (SignatureFlags) { SignatureFlags[SignatureFlags["None"] = 0] = "None"; SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; SignatureFlags[SignatureFlags["IsStringIndexer"] = 2] = "IsStringIndexer"; SignatureFlags[SignatureFlags["IsNumberIndexer"] = 4] = "IsNumberIndexer"; -})(exports.SignatureFlags || (exports.SignatureFlags = {})); -var SignatureFlags = exports.SignatureFlags; +})(SignatureFlags = exports.SignatureFlags || (exports.SignatureFlags = {})); diff --git a/tests/baselines/reference/parserEnum3.js b/tests/baselines/reference/parserEnum3.js index 1d0c445d3a0..602171e8d94 100644 --- a/tests/baselines/reference/parserEnum3.js +++ b/tests/baselines/reference/parserEnum3.js @@ -6,6 +6,6 @@ //// [parserEnum3.js] "use strict"; +var SignatureFlags; (function (SignatureFlags) { -})(exports.SignatureFlags || (exports.SignatureFlags = {})); -var SignatureFlags = exports.SignatureFlags; +})(SignatureFlags = exports.SignatureFlags || (exports.SignatureFlags = {})); diff --git a/tests/baselines/reference/parserEnum4.js b/tests/baselines/reference/parserEnum4.js index 1a207960714..6af07b0a1c7 100644 --- a/tests/baselines/reference/parserEnum4.js +++ b/tests/baselines/reference/parserEnum4.js @@ -7,6 +7,6 @@ //// [parserEnum4.js] "use strict"; +var SignatureFlags; (function (SignatureFlags) { -})(exports.SignatureFlags || (exports.SignatureFlags = {})); -var SignatureFlags = exports.SignatureFlags; +})(SignatureFlags = exports.SignatureFlags || (exports.SignatureFlags = {})); diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js index 6a703759fff..c206a30237a 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js @@ -4,4 +4,4 @@ return; //// [parserErrorRecovery_ObjectLiteral2.js] var v = { a: , - return: }; + "return": }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js index eecf45fea4f..6cee2b42725 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js @@ -4,4 +4,4 @@ return; //// [parserErrorRecovery_ObjectLiteral3.js] var v = { a: , - return: }; + "return": }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js index 87a1a31437e..23d17c8047b 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js @@ -4,4 +4,4 @@ return; //// [parserErrorRecovery_ObjectLiteral4.js] var v = { a: 1, - return: }; + "return": }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js index 97e618946a0..7b83132bf0f 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js @@ -4,4 +4,4 @@ return; //// [parserErrorRecovery_ObjectLiteral5.js] var v = { a: 1, - return: }; + "return": }; diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList6.js b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js index c3d5a838f88..7c221aaa20a 100644 --- a/tests/baselines/reference/parserErrorRecovery_ParameterList6.js +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js @@ -7,7 +7,6 @@ class Foo { var Foo = (function () { function Foo() { } - Foo.prototype.banana = function (x) { }; return Foo; }()); break ; diff --git a/tests/baselines/reference/parserExportAsFunctionIdentifier.js b/tests/baselines/reference/parserExportAsFunctionIdentifier.js index 7ed76bb87d9..62429c76855 100644 --- a/tests/baselines/reference/parserExportAsFunctionIdentifier.js +++ b/tests/baselines/reference/parserExportAsFunctionIdentifier.js @@ -9,4 +9,4 @@ var x = f.export(); //// [parserExportAsFunctionIdentifier.js] var f; -var x = f.export(); +var x = f["export"](); diff --git a/tests/baselines/reference/parserExportAssignment7.js b/tests/baselines/reference/parserExportAssignment7.js index f359ada1e91..dd6750bec32 100644 --- a/tests/baselines/reference/parserExportAssignment7.js +++ b/tests/baselines/reference/parserExportAssignment7.js @@ -11,5 +11,4 @@ var C = (function () { } return C; }()); -exports.C = C; module.exports = B; diff --git a/tests/baselines/reference/parserExportAssignment8.js b/tests/baselines/reference/parserExportAssignment8.js index 16a50a30b3c..07ff257fb61 100644 --- a/tests/baselines/reference/parserExportAssignment8.js +++ b/tests/baselines/reference/parserExportAssignment8.js @@ -11,5 +11,4 @@ var C = (function () { } return C; }()); -exports.C = C; module.exports = B; diff --git a/tests/baselines/reference/parserExportAssignment9.errors.txt b/tests/baselines/reference/parserExportAssignment9.errors.txt new file mode 100644 index 00000000000..818b60cfc98 --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment9.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts(2,3): error TS1319: A default export can only be used in an ECMAScript-style module. +tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts(6,3): error TS1319: A default export can only be used in an ECMAScript-style module. + + +==== tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts (2 errors) ==== + namespace Foo { + export default foo; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS1319: A default export can only be used in an ECMAScript-style module. + } + + module Bar { + export default bar; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS1319: A default export can only be used in an ECMAScript-style module. + } \ No newline at end of file diff --git a/tests/baselines/reference/parserExportAssignment9.js b/tests/baselines/reference/parserExportAssignment9.js new file mode 100644 index 00000000000..2600ae629e9 --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment9.js @@ -0,0 +1,18 @@ +//// [parserExportAssignment9.ts] +namespace Foo { + export default foo; +} + +module Bar { + export default bar; +} + +//// [parserExportAssignment9.js] +var Foo; +(function (Foo) { + export default foo; +})(Foo || (Foo = {})); +var Bar; +(function (Bar) { + export default bar; +})(Bar || (Bar = {})); diff --git a/tests/baselines/reference/parserForOfStatement19.errors.txt b/tests/baselines/reference/parserForOfStatement19.errors.txt deleted file mode 100644 index a111498efe7..00000000000 --- a/tests/baselines/reference/parserForOfStatement19.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement19.ts(1,16): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. - - -==== tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement19.ts (1 errors) ==== - for (var of in of) { } - ~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. \ No newline at end of file diff --git a/tests/baselines/reference/parserForOfStatement19.symbols b/tests/baselines/reference/parserForOfStatement19.symbols new file mode 100644 index 00000000000..1e123349e13 --- /dev/null +++ b/tests/baselines/reference/parserForOfStatement19.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement19.ts === +for (var of in of) { } +>of : Symbol(of, Decl(parserForOfStatement19.ts, 0, 8)) +>of : Symbol(of, Decl(parserForOfStatement19.ts, 0, 8)) + diff --git a/tests/baselines/reference/parserForOfStatement19.types b/tests/baselines/reference/parserForOfStatement19.types new file mode 100644 index 00000000000..6fcc5e8f792 --- /dev/null +++ b/tests/baselines/reference/parserForOfStatement19.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement19.ts === +for (var of in of) { } +>of : any +>of : any + diff --git a/tests/baselines/reference/parserForOfStatement20.errors.txt b/tests/baselines/reference/parserForOfStatement20.errors.txt index f2b6ac39a83..461f307f6b9 100644 --- a/tests/baselines/reference/parserForOfStatement20.errors.txt +++ b/tests/baselines/reference/parserForOfStatement20.errors.txt @@ -1,10 +1,7 @@ tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement20.ts(1,10): error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. -tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement20.ts(1,20): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. -==== tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement20.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement20.ts (1 errors) ==== for (var of = 0 in of) { } ~~ -!!! error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. - ~~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. \ No newline at end of file +!!! error TS1189: The variable declaration of a 'for...in' statement cannot have an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/parserForStatement6.errors.txt b/tests/baselines/reference/parserForStatement6.errors.txt index a41f103e929..808a166afad 100644 --- a/tests/baselines/reference/parserForStatement6.errors.txt +++ b/tests/baselines/reference/parserForStatement6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement6.ts(1,6): error TS2304: Cannot find name 'foo'. -tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement6.ts(1,6): error TS2406: Invalid left-hand side in 'for...in' statement. +tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement6.ts(1,6): error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement6.ts(1,15): error TS2304: Cannot find name 'b'. @@ -8,7 +8,7 @@ tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement6.ts(1,1 ~~~ !!! error TS2304: Cannot find name 'foo'. ~~~~~ -!!! error TS2406: Invalid left-hand side in 'for...in' statement. +!!! error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. ~ !!! error TS2304: Cannot find name 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserForStatement7.errors.txt b/tests/baselines/reference/parserForStatement7.errors.txt index 3aa67480105..1fd36480744 100644 --- a/tests/baselines/reference/parserForStatement7.errors.txt +++ b/tests/baselines/reference/parserForStatement7.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts(1,6): error TS2406: Invalid left-hand side in 'for...in' statement. +tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts(1,6): error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts(1,10): error TS2304: Cannot find name 'foo'. tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts(1,19): error TS2304: Cannot find name 'b'. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts(1,1 ==== tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement7.ts (3 errors) ==== for (new foo() in b) { ~~~~~~~~~ -!!! error TS2406: Invalid left-hand side in 'for...in' statement. +!!! error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. ~~~ !!! error TS2304: Cannot find name 'foo'. ~ diff --git a/tests/baselines/reference/parserForStatement8.errors.txt b/tests/baselines/reference/parserForStatement8.errors.txt index 72c7901aa8c..21ea55e3b09 100644 --- a/tests/baselines/reference/parserForStatement8.errors.txt +++ b/tests/baselines/reference/parserForStatement8.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,6): error TS2406: Invalid left-hand side in 'for...in' statement. +tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,6): error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,14): error TS2304: Cannot find name 'b'. ==== tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts (2 errors) ==== for (this in b) { ~~~~ -!!! error TS2406: Invalid left-hand side in 'for...in' statement. +!!! error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. ~ !!! error TS2304: Cannot find name 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity11.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity11.errors.txt index 8ccafdaf094..2c179256c77 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity11.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity11.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity11.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity11.ts(1,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity11.ts (1 errors) ==== 1 >>= 2; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.errors.txt index 12bba7ec8f5..3c2c9c45d33 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity15.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity15.ts(1,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity15.ts (1 errors) ==== 1 ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // before >>= // after 2; \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity16.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity16.errors.txt index eb31b49621e..fd2f07bda81 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity16.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity16.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity16.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity16.ts(1,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity16.ts (1 errors) ==== 1 >>>= 2; ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.errors.txt index ee2d3666682..30ede342a85 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity2.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity2.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity2.ts(1,5): error TS1109: Expression expected. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity2.ts (2 errors) ==== 1 > > 2; ~~~~~~~ -!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.errors.txt index c464bc37ff8..d5aa2b1269b 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity20.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity20.ts(1,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity20.ts (1 errors) ==== 1 ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. // Before >>>= // after 2; \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.errors.txt index 1651009bf0d..baebfd81304 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity3.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity3.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity3.ts(1,8): error TS1109: Expression expected. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity3.ts (2 errors) ==== 1 >/**/> 2; ~~~~~~~~~~ -!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.errors.txt b/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.errors.txt index dff69b37612..924c9440d16 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.errors.txt +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity4.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity4.ts(1,1): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbiguity4.ts(2,1): error TS1109: Expression expected. @@ -7,6 +7,6 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGreaterThanTokenAmbigu ~~~ > 2; ~~~ -!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and '2'. +!!! error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. ~ !!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserKeywordsAsIdentifierName1.js b/tests/baselines/reference/parserKeywordsAsIdentifierName1.js index c0c8c844364..a717abcc08b 100644 --- a/tests/baselines/reference/parserKeywordsAsIdentifierName1.js +++ b/tests/baselines/reference/parserKeywordsAsIdentifierName1.js @@ -8,7 +8,7 @@ var big = { //// [parserKeywordsAsIdentifierName1.js] var big = { - break: 0, - super: 0, - const: 0 + "break": 0, + "super": 0, + "const": 0 }; diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration18.js b/tests/baselines/reference/parserMemberAccessorDeclaration18.js index e25aa69f465..c6c902d4915 100644 --- a/tests/baselines/reference/parserMemberAccessorDeclaration18.js +++ b/tests/baselines/reference/parserMemberAccessorDeclaration18.js @@ -11,7 +11,7 @@ var C = (function () { set: function () { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } }, enumerable: true, diff --git a/tests/baselines/reference/parserParameterList10.js b/tests/baselines/reference/parserParameterList10.js index 93ed8c60e8b..f899901728c 100644 --- a/tests/baselines/reference/parserParameterList10.js +++ b/tests/baselines/reference/parserParameterList10.js @@ -10,7 +10,7 @@ var C = (function () { C.prototype.foo = function () { var bar = []; for (var _i = 0; _i < arguments.length; _i++) { - bar[_i - 0] = arguments[_i]; + bar[_i] = arguments[_i]; } }; return C; diff --git a/tests/baselines/reference/parserParameterList11.js b/tests/baselines/reference/parserParameterList11.js index a56e8b58c20..c736e5fddb6 100644 --- a/tests/baselines/reference/parserParameterList11.js +++ b/tests/baselines/reference/parserParameterList11.js @@ -5,7 +5,7 @@ (function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } return 102; }); diff --git a/tests/baselines/reference/parserParameterList9.js b/tests/baselines/reference/parserParameterList9.js index ec08b48f572..3ccc1d02025 100644 --- a/tests/baselines/reference/parserParameterList9.js +++ b/tests/baselines/reference/parserParameterList9.js @@ -10,7 +10,7 @@ var C = (function () { C.prototype.foo = function () { var bar = []; for (var _i = 0; _i < arguments.length; _i++) { - bar[_i - 0] = arguments[_i]; + bar[_i] = arguments[_i]; } }; return C; diff --git a/tests/baselines/reference/parserRealSource10.js b/tests/baselines/reference/parserRealSource10.js index 253f856a990..11cfbdfa1f2 100644 --- a/tests/baselines/reference/parserRealSource10.js +++ b/tests/baselines/reference/parserRealSource10.js @@ -466,6 +466,7 @@ var __extends = (this && this.__extends) || function (d, b) { /// var TypeScript; (function (TypeScript) { + var TokenID; (function (TokenID) { // Keywords TokenID[TokenID["Any"] = 0] = "Any"; @@ -584,8 +585,7 @@ var TypeScript; TokenID[TokenID["Lim"] = 112] = "Lim"; TokenID[TokenID["LimFixed"] = 105] = "LimFixed"; TokenID[TokenID["LimKeyword"] = 53] = "LimKeyword"; - })(TypeScript.TokenID || (TypeScript.TokenID = {})); - var TokenID = TypeScript.TokenID; + })(TokenID = TypeScript.TokenID || (TypeScript.TokenID = {})); TypeScript.tokenTable = new TokenInfo[]; TypeScript.nodeTypeTable = new string[]; TypeScript.nodeTypeToTokTable = new number[]; @@ -602,6 +602,7 @@ var TypeScript; TypeScript.noRegexTable[TokenID.CloseBrace] = true; TypeScript.noRegexTable[TokenID.True] = true; TypeScript.noRegexTable[TokenID.False] = true; + var OperatorPrecedence; (function (OperatorPrecedence) { OperatorPrecedence[OperatorPrecedence["None"] = 0] = "None"; OperatorPrecedence[OperatorPrecedence["Comma"] = 1] = "Comma"; @@ -619,8 +620,8 @@ var TypeScript; OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 13] = "Multiplicative"; OperatorPrecedence[OperatorPrecedence["Unary"] = 14] = "Unary"; OperatorPrecedence[OperatorPrecedence["Lim"] = 15] = "Lim"; - })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); - var OperatorPrecedence = TypeScript.OperatorPrecedence; + })(OperatorPrecedence = TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var Reservation; (function (Reservation) { Reservation[Reservation["None"] = 0] = "None"; Reservation[Reservation["Javascript"] = 1] = "Javascript"; @@ -630,8 +631,7 @@ var TypeScript; Reservation[Reservation["TypeScriptAndJS"] = 5] = "TypeScriptAndJS"; Reservation[Reservation["TypeScriptAndJSFuture"] = 6] = "TypeScriptAndJSFuture"; Reservation[Reservation["TypeScriptAndJSFutureStrict"] = 12] = "TypeScriptAndJSFutureStrict"; - })(TypeScript.Reservation || (TypeScript.Reservation = {})); - var Reservation = TypeScript.Reservation; + })(Reservation = TypeScript.Reservation || (TypeScript.Reservation = {})); var TokenInfo = (function () { function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { this.tokenId = tokenId; @@ -773,6 +773,7 @@ var TypeScript; return TypeScript.tokenTable[tokenId]; } TypeScript.lookupToken = lookupToken; + var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -781,8 +782,7 @@ var TypeScript; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["Literal"] = 6] = "Literal"; - })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); - var TokenClass = TypeScript.TokenClass; + })(TokenClass = TypeScript.TokenClass || (TypeScript.TokenClass = {})); var SavedToken = (function () { function SavedToken(tok, minChar, limChar) { this.tok = tok; diff --git a/tests/baselines/reference/parserRealSource14.js b/tests/baselines/reference/parserRealSource14.js index c31a9dd6c72..907efc6f26a 100644 --- a/tests/baselines/reference/parserRealSource14.js +++ b/tests/baselines/reference/parserRealSource14.js @@ -957,6 +957,7 @@ var TypeScript; return AstPathContext; }()); TypeScript.AstPathContext = AstPathContext; + var GetAstPathOptions; (function (GetAstPathOptions) { GetAstPathOptions[GetAstPathOptions["Default"] = 0] = "Default"; GetAstPathOptions[GetAstPathOptions["EdgeInclusive"] = 1] = "EdgeInclusive"; @@ -968,8 +969,7 @@ var TypeScript; // we don't find the "precomment" attached to the errorneous empty stmt. //TODO: It would be nice to be able to get rid of this. GetAstPathOptions[GetAstPathOptions["DontPruneSearchBasedOnPosition"] = 2] = "DontPruneSearchBasedOnPosition"; - })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); - var GetAstPathOptions = TypeScript.GetAstPathOptions; + })(GetAstPathOptions = TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); /// /// Return the stack of AST nodes containing "position" /// diff --git a/tests/baselines/reference/parserRealSource2.js b/tests/baselines/reference/parserRealSource2.js index c41f88bc9c2..2028cbd4efe 100644 --- a/tests/baselines/reference/parserRealSource2.js +++ b/tests/baselines/reference/parserRealSource2.js @@ -281,6 +281,7 @@ var TypeScript; return (val & flag) != 0; } TypeScript.hasFlag = hasFlag; + var ErrorRecoverySet; (function (ErrorRecoverySet) { ErrorRecoverySet[ErrorRecoverySet["None"] = 0] = "None"; ErrorRecoverySet[ErrorRecoverySet["Comma"] = 1] = "Comma"; @@ -320,8 +321,8 @@ var TypeScript; ErrorRecoverySet[ErrorRecoverySet["ExprStart"] = 520158210] = "ExprStart"; ErrorRecoverySet[ErrorRecoverySet["StmtStart"] = 1608580098] = "StmtStart"; ErrorRecoverySet[ErrorRecoverySet["Postfix"] = 49280] = "Postfix"; - })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); - var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + })(ErrorRecoverySet = TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var AllowedElements; (function (AllowedElements) { AllowedElements[AllowedElements["None"] = 0] = "None"; AllowedElements[AllowedElements["ModuleDeclarations"] = 4] = "ModuleDeclarations"; @@ -331,8 +332,8 @@ var TypeScript; AllowedElements[AllowedElements["Properties"] = 2048] = "Properties"; AllowedElements[AllowedElements["Global"] = 1052] = "Global"; AllowedElements[AllowedElements["QuickParse"] = 3100] = "QuickParse"; - })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); - var AllowedElements = TypeScript.AllowedElements; + })(AllowedElements = TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var Modifiers; (function (Modifiers) { Modifiers[Modifiers["None"] = 0] = "None"; Modifiers[Modifiers["Private"] = 1] = "Private"; @@ -343,8 +344,8 @@ var TypeScript; Modifiers[Modifiers["Getter"] = 32] = "Getter"; Modifiers[Modifiers["Setter"] = 64] = "Setter"; Modifiers[Modifiers["Static"] = 128] = "Static"; - })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); - var Modifiers = TypeScript.Modifiers; + })(Modifiers = TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var ASTFlags; (function (ASTFlags) { ASTFlags[ASTFlags["None"] = 0] = "None"; ASTFlags[ASTFlags["ExplicitSemicolon"] = 1] = "ExplicitSemicolon"; @@ -362,8 +363,8 @@ var TypeScript; // The flag is used to communicate this piece of information to the calling parseTerm, which intern will remove it. // Once we have a better way to associate information with nodes, this flag should not be used. ASTFlags[ASTFlags["SkipNextRParen"] = 2048] = "SkipNextRParen"; - })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); - var ASTFlags = TypeScript.ASTFlags; + })(ASTFlags = TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var DeclFlags; (function (DeclFlags) { DeclFlags[DeclFlags["None"] = 0] = "None"; DeclFlags[DeclFlags["Exported"] = 1] = "Exported"; @@ -374,8 +375,8 @@ var TypeScript; DeclFlags[DeclFlags["LocalStatic"] = 32] = "LocalStatic"; DeclFlags[DeclFlags["GetAccessor"] = 64] = "GetAccessor"; DeclFlags[DeclFlags["SetAccessor"] = 128] = "SetAccessor"; - })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); - var DeclFlags = TypeScript.DeclFlags; + })(DeclFlags = TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var ModuleFlags; (function (ModuleFlags) { ModuleFlags[ModuleFlags["None"] = 0] = "None"; ModuleFlags[ModuleFlags["Exported"] = 1] = "Exported"; @@ -391,8 +392,8 @@ var TypeScript; ModuleFlags[ModuleFlags["IsWholeFile"] = 1024] = "IsWholeFile"; ModuleFlags[ModuleFlags["IsDynamic"] = 2048] = "IsDynamic"; ModuleFlags[ModuleFlags["MustCaptureThis"] = 4096] = "MustCaptureThis"; - })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); - var ModuleFlags = TypeScript.ModuleFlags; + })(ModuleFlags = TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var SymbolFlags; (function (SymbolFlags) { SymbolFlags[SymbolFlags["None"] = 0] = "None"; SymbolFlags[SymbolFlags["Exported"] = 1] = "Exported"; @@ -415,8 +416,8 @@ var TypeScript; SymbolFlags[SymbolFlags["RecursivelyReferenced"] = 131072] = "RecursivelyReferenced"; SymbolFlags[SymbolFlags["Bound"] = 262144] = "Bound"; SymbolFlags[SymbolFlags["CompilerGenerated"] = 524288] = "CompilerGenerated"; - })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); - var SymbolFlags = TypeScript.SymbolFlags; + })(SymbolFlags = TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var VarFlags; (function (VarFlags) { VarFlags[VarFlags["None"] = 0] = "None"; VarFlags[VarFlags["Exported"] = 1] = "Exported"; @@ -437,8 +438,8 @@ var TypeScript; VarFlags[VarFlags["ClassSuperMustBeFirstCallInConstructor"] = 32768] = "ClassSuperMustBeFirstCallInConstructor"; VarFlags[VarFlags["Constant"] = 65536] = "Constant"; VarFlags[VarFlags["MustCaptureThis"] = 131072] = "MustCaptureThis"; - })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); - var VarFlags = TypeScript.VarFlags; + })(VarFlags = TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var FncFlags; (function (FncFlags) { FncFlags[FncFlags["None"] = 0] = "None"; FncFlags[FncFlags["Exported"] = 1] = "Exported"; @@ -461,19 +462,19 @@ var TypeScript; FncFlags[FncFlags["IsFunctionExpression"] = 131072] = "IsFunctionExpression"; FncFlags[FncFlags["ClassMethod"] = 262144] = "ClassMethod"; FncFlags[FncFlags["ClassPropertyMethodExported"] = 524288] = "ClassPropertyMethodExported"; - })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); - var FncFlags = TypeScript.FncFlags; + })(FncFlags = TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var SignatureFlags; (function (SignatureFlags) { SignatureFlags[SignatureFlags["None"] = 0] = "None"; SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; SignatureFlags[SignatureFlags["IsStringIndexer"] = 2] = "IsStringIndexer"; SignatureFlags[SignatureFlags["IsNumberIndexer"] = 4] = "IsNumberIndexer"; - })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); - var SignatureFlags = TypeScript.SignatureFlags; + })(SignatureFlags = TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { return fncOrVarOrSymbolOrModuleFlags; } TypeScript.ToDeclFlags = ToDeclFlags; + var TypeFlags; (function (TypeFlags) { TypeFlags[TypeFlags["None"] = 0] = "None"; TypeFlags[TypeFlags["HasImplementation"] = 1] = "HasImplementation"; @@ -484,8 +485,8 @@ var TypeScript; TypeFlags[TypeFlags["HasBaseType"] = 32] = "HasBaseType"; TypeFlags[TypeFlags["HasBaseTypeOfObject"] = 64] = "HasBaseTypeOfObject"; TypeFlags[TypeFlags["IsClass"] = 128] = "IsClass"; - })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); - var TypeFlags = TypeScript.TypeFlags; + })(TypeFlags = TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeRelationshipFlags; (function (TypeRelationshipFlags) { TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; TypeRelationshipFlags[TypeRelationshipFlags["SourceIsNullTargetIsVoidOrUndefined"] = 1] = "SourceIsNullTargetIsVoidOrUndefined"; @@ -495,19 +496,18 @@ var TypeScript; TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 16] = "IncompatibleReturnTypes"; TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 32] = "IncompatiblePropertyTypes"; TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 64] = "IncompatibleParameterTypes"; - })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); - var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + })(TypeRelationshipFlags = TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var CodeGenTarget; (function (CodeGenTarget) { CodeGenTarget[CodeGenTarget["ES3"] = 0] = "ES3"; CodeGenTarget[CodeGenTarget["ES5"] = 1] = "ES5"; - })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); - var CodeGenTarget = TypeScript.CodeGenTarget; + })(CodeGenTarget = TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var ModuleGenTarget; (function (ModuleGenTarget) { ModuleGenTarget[ModuleGenTarget["Synchronous"] = 0] = "Synchronous"; ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 1] = "Asynchronous"; ModuleGenTarget[ModuleGenTarget["Local"] = 2] = "Local"; - })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); - var ModuleGenTarget = TypeScript.ModuleGenTarget; + })(ModuleGenTarget = TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); // Compiler defaults to generating ES5-compliant code for // - getters and setters TypeScript.codeGenTarget = CodeGenTarget.ES3; diff --git a/tests/baselines/reference/parserRealSource3.js b/tests/baselines/reference/parserRealSource3.js index 38e9028297b..f0e22395cfe 100644 --- a/tests/baselines/reference/parserRealSource3.js +++ b/tests/baselines/reference/parserRealSource3.js @@ -126,6 +126,7 @@ module TypeScript { var TypeScript; (function (TypeScript) { // Note: Any addition to the NodeType should also be supported with addition to AstWalkerDetailCallback + var NodeType; (function (NodeType) { NodeType[NodeType["None"] = 0] = "None"; NodeType[NodeType["Empty"] = 1] = "Empty"; @@ -236,6 +237,5 @@ var TypeScript; NodeType[NodeType["Debugger"] = 106] = "Debugger"; NodeType[NodeType["GeneralNode"] = 71] = "GeneralNode"; NodeType[NodeType["LastAsg"] = 41] = "LastAsg"; - })(TypeScript.NodeType || (TypeScript.NodeType = {})); - var NodeType = TypeScript.NodeType; + })(NodeType = TypeScript.NodeType || (TypeScript.NodeType = {})); })(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserShorthandPropertyAssignment2.js b/tests/baselines/reference/parserShorthandPropertyAssignment2.js index 0de0fa3829f..95d2f32ffad 100644 --- a/tests/baselines/reference/parserShorthandPropertyAssignment2.js +++ b/tests/baselines/reference/parserShorthandPropertyAssignment2.js @@ -2,4 +2,4 @@ var v = { class }; //// [parserShorthandPropertyAssignment2.js] -var v = { class: }; +var v = { "class": }; diff --git a/tests/baselines/reference/parserStrictMode3-negative.errors.txt b/tests/baselines/reference/parserStrictMode3-negative.errors.txt index 464f6859de6..4ea779d5fdc 100644 --- a/tests/baselines/reference/parserStrictMode3-negative.errors.txt +++ b/tests/baselines/reference/parserStrictMode3-negative.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3-negative.ts(1,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3-negative.ts(1,1): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3-negative.ts (1 errors) ==== eval = 1; ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserStrictMode3.errors.txt b/tests/baselines/reference/parserStrictMode3.errors.txt index b8f1e0f54b8..688aa6e462b 100644 --- a/tests/baselines/reference/parserStrictMode3.errors.txt +++ b/tests/baselines/reference/parserStrictMode3.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3.ts(2,1): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3.ts(2,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3.ts(2,1): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode3.ts(2,1): ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserStrictMode5.errors.txt b/tests/baselines/reference/parserStrictMode5.errors.txt index e541963a1fb..d3b0ab3f44a 100644 --- a/tests/baselines/reference/parserStrictMode5.errors.txt +++ b/tests/baselines/reference/parserStrictMode5.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode5.ts(2,1): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode5.ts(2,1): error TS2365: Operator '+=' cannot be applied to types '(x: string) => any' and '1'. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode5.ts(2,1): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode5.ts (2 errors) ==== @@ -7,5 +7,5 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode5.ts(2,1): eval += 1; ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. - ~~~~~~~~~ -!!! error TS2365: Operator '+=' cannot be applied to types '(x: string) => any' and '1'. \ No newline at end of file + ~~~~ +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserStrictMode6-negative.errors.txt b/tests/baselines/reference/parserStrictMode6-negative.errors.txt index 69d7d131729..df373be0301 100644 --- a/tests/baselines/reference/parserStrictMode6-negative.errors.txt +++ b/tests/baselines/reference/parserStrictMode6-negative.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6-negative.ts(1,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6-negative.ts(1,1): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6-negative.ts (1 errors) ==== eval++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserStrictMode6.errors.txt b/tests/baselines/reference/parserStrictMode6.errors.txt index 7ac0e7fdb4d..2a8fda7f62f 100644 --- a/tests/baselines/reference/parserStrictMode6.errors.txt +++ b/tests/baselines/reference/parserStrictMode6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6.ts(2,1): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6.ts(2,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6.ts(2,1): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode6.ts(2,1): ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserStrictMode7.errors.txt b/tests/baselines/reference/parserStrictMode7.errors.txt index 6ee6ca43042..b4ea09f14d4 100644 --- a/tests/baselines/reference/parserStrictMode7.errors.txt +++ b/tests/baselines/reference/parserStrictMode7.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts(2,3): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts(2,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts(2,3): error TS2539: Cannot assign to 'eval' because it is not a variable. ==== tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts (2 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode7.ts(2,3): ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/parserSuperExpression3.js b/tests/baselines/reference/parserSuperExpression3.js index f311efcd0f6..064353669c8 100644 --- a/tests/baselines/reference/parserSuperExpression3.js +++ b/tests/baselines/reference/parserSuperExpression3.js @@ -10,7 +10,7 @@ var C = (function () { function C() { } C.prototype.M = function () { - this.super(0); + this["super"](0); }; return C; }()); diff --git a/tests/baselines/reference/parserUnaryExpression1.errors.txt b/tests/baselines/reference/parserUnaryExpression1.errors.txt index 16900ea6160..278960d53f3 100644 --- a/tests/baselines/reference/parserUnaryExpression1.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts(1,3): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts(1,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts (1 errors) ==== ++this; ~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. \ No newline at end of file +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnaryExpression7.errors.txt b/tests/baselines/reference/parserUnaryExpression7.errors.txt index 32967d2e0b8..f69f8e88252 100644 --- a/tests/baselines/reference/parserUnaryExpression7.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression7.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression7.ts(1,4): error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression7.ts(1,4): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression7.ts(1,8): error TS2304: Cannot find name 'Foo'. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression7.ts (2 errors) ==== ++ new Foo(); ~~~~~~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable, property or indexer. +!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ~~~ !!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index 90ac8e0e760..d3d0c4056a1 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -25,9 +25,6 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(820,31): error TS2339: Property 'length' does not exist on type 'null'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(976,28): error TS2339: Property 'length' does not exist on type 'null'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(977,82): error TS2339: Property 'join' does not exist on type 'null'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. @@ -113,7 +110,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,68): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2304: Cannot find name 'Diff'. -==== tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts (113 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts (110 errors) ==== // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -988,8 +985,6 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): }) return errors.length === 0; - ~~~~~~ -!!! error TS2339: Property 'length' does not exist on type 'null'. } public isSubtypeOf(other: Type) { @@ -1146,11 +1141,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): }) if (errors.length > 0) - ~~~~~~ -!!! error TS2339: Property 'length' does not exist on type 'null'. throw new Error("Type definition contains errors: " + errors.join(",")); - ~~~~ -!!! error TS2339: Property 'join' does not exist on type 'null'. var matchingIdentifiers: Type[] = []; diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.errors.txt b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.errors.txt new file mode 100644 index 00000000000..a6a45245929 --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.errors.txt @@ -0,0 +1,27 @@ +tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts(12,11): error TS2345: Argument of type '(t1: D, t2: any, t3: any) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. +tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts(13,11): error TS2345: Argument of type '(t1: any, t2: D, t3: any) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. +tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts(14,11): error TS2345: Argument of type '(t1: any, t2: any, t3: D) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. + + +==== tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts (3 errors) ==== + class C { + test: string + } + + class D extends C { + test2: string + } + + declare function testError(a: (t: T, t1: T) => void): T + + // more args + testError((t1: D, t2, t3) => {}) + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '(t1: D, t2: any, t3: any) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. + testError((t1, t2: D, t3) => {}) + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '(t1: any, t2: D, t3: any) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. + testError((t1, t2, t3: D) => {}) + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '(t1: any, t2: any, t3: D) => void' is not assignable to parameter of type '(t: any, t1: any) => void'. + \ No newline at end of file diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.js b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.js new file mode 100644 index 00000000000..9702595fffb --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceError.js @@ -0,0 +1,39 @@ +//// [partiallyAnnotatedFunctionInferenceError.ts] +class C { + test: string +} + +class D extends C { + test2: string +} + +declare function testError(a: (t: T, t1: T) => void): T + +// more args +testError((t1: D, t2, t3) => {}) +testError((t1, t2: D, t3) => {}) +testError((t1, t2, t3: D) => {}) + + +//// [partiallyAnnotatedFunctionInferenceError.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C = (function () { + function C() { + } + return C; +}()); +var D = (function (_super) { + __extends(D, _super); + function D() { + return _super.apply(this, arguments) || this; + } + return D; +}(C)); +// more args +testError(function (t1, t2, t3) { }); +testError(function (t1, t2, t3) { }); +testError(function (t1, t2, t3) { }); diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.js b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.js new file mode 100644 index 00000000000..d20b35625e9 --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.js @@ -0,0 +1,85 @@ +//// [partiallyAnnotatedFunctionInferenceWithTypeParameter.ts] +class C { + test: string +} + +class D extends C { + test2: string +} + +declare function test(a: (t: T, t1: T) => void): T + +declare function testRest(a: (t: T, t1: T, ...ts: T[]) => void): T + + +// exactly +test((t1: D, t2) => { t2.test2 }) +test((t1, t2: D) => { t2.test2 }) + +// zero arg +test(() => {}) + +// fewer args +test((t1: D) => {}) + +// rest arg +test((...ts: D[]) => {}) + +// source function has rest arg +testRest((t1: D) => {}) +testRest((t1, t2, t3) => {}) +testRest((t1: D, t2, t3) => {}) +testRest((t1, t2: D, t3) => {}) +testRest((t2: D, ...t3) => {}) +testRest((t2, ...t3: D[]) => {}) + + +//// [partiallyAnnotatedFunctionInferenceWithTypeParameter.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C = (function () { + function C() { + } + return C; +}()); +var D = (function (_super) { + __extends(D, _super); + function D() { + return _super.apply(this, arguments) || this; + } + return D; +}(C)); +// exactly +test(function (t1, t2) { t2.test2; }); +test(function (t1, t2) { t2.test2; }); +// zero arg +test(function () { }); +// fewer args +test(function (t1) { }); +// rest arg +test(function () { + var ts = []; + for (var _i = 0; _i < arguments.length; _i++) { + ts[_i] = arguments[_i]; + } +}); +// source function has rest arg +testRest(function (t1) { }); +testRest(function (t1, t2, t3) { }); +testRest(function (t1, t2, t3) { }); +testRest(function (t1, t2, t3) { }); +testRest(function (t2) { + var t3 = []; + for (var _i = 1; _i < arguments.length; _i++) { + t3[_i - 1] = arguments[_i]; + } +}); +testRest(function (t2) { + var t3 = []; + for (var _i = 1; _i < arguments.length; _i++) { + t3[_i - 1] = arguments[_i]; + } +}); diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.symbols b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.symbols new file mode 100644 index 00000000000..b3c66f8f8cd --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.symbols @@ -0,0 +1,114 @@ +=== tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceWithTypeParameter.ts === +class C { +>C : Symbol(C, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 0, 0)) + + test: string +>test : Symbol(C.test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 0, 9)) +} + +class D extends C { +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>C : Symbol(C, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 0, 0)) + + test2: string +>test2 : Symbol(D.test2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 4, 19)) +} + +declare function test(a: (t: T, t1: T) => void): T +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 22)) +>C : Symbol(C, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 0, 0)) +>a : Symbol(a, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 35)) +>t : Symbol(t, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 39)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 22)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 44)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 22)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 22)) + +declare function testRest(a: (t: T, t1: T, ...ts: T[]) => void): T +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 26)) +>C : Symbol(C, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 0, 0)) +>a : Symbol(a, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 39)) +>t : Symbol(t, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 43)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 26)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 48)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 26)) +>ts : Symbol(ts, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 55)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 26)) +>T : Symbol(T, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 10, 26)) + + +// exactly +test((t1: D, t2) => { t2.test2 }) +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 14, 6)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 14, 12)) +>t2.test2 : Symbol(D.test2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 4, 19)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 14, 12)) +>test2 : Symbol(D.test2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 4, 19)) + +test((t1, t2: D) => { t2.test2 }) +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 15, 6)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 15, 9)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>t2.test2 : Symbol(D.test2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 4, 19)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 15, 9)) +>test2 : Symbol(D.test2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 4, 19)) + +// zero arg +test(() => {}) +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) + +// fewer args +test((t1: D) => {}) +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 21, 6)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) + +// rest arg +test((...ts: D[]) => {}) +>test : Symbol(test, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 6, 1)) +>ts : Symbol(ts, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 24, 6)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) + +// source function has rest arg +testRest((t1: D) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 27, 10)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) + +testRest((t1, t2, t3) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 28, 10)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 28, 13)) +>t3 : Symbol(t3, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 28, 17)) + +testRest((t1: D, t2, t3) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 29, 10)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 29, 16)) +>t3 : Symbol(t3, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 29, 20)) + +testRest((t1, t2: D, t3) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t1 : Symbol(t1, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 30, 10)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 30, 13)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>t3 : Symbol(t3, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 30, 20)) + +testRest((t2: D, ...t3) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 31, 10)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) +>t3 : Symbol(t3, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 31, 16)) + +testRest((t2, ...t3: D[]) => {}) +>testRest : Symbol(testRest, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 8, 63)) +>t2 : Symbol(t2, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 32, 10)) +>t3 : Symbol(t3, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 32, 13)) +>D : Symbol(D, Decl(partiallyAnnotatedFunctionInferenceWithTypeParameter.ts, 2, 1)) + diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.types b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.types new file mode 100644 index 00000000000..c2113ae4d75 --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionInferenceWithTypeParameter.types @@ -0,0 +1,136 @@ +=== tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceWithTypeParameter.ts === +class C { +>C : C + + test: string +>test : string +} + +class D extends C { +>D : D +>C : C + + test2: string +>test2 : string +} + +declare function test(a: (t: T, t1: T) => void): T +>test : (a: (t: T, t1: T) => void) => T +>T : T +>C : C +>a : (t: T, t1: T) => void +>t : T +>T : T +>t1 : T +>T : T +>T : T + +declare function testRest(a: (t: T, t1: T, ...ts: T[]) => void): T +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>T : T +>C : C +>a : (t: T, t1: T, ...ts: T[]) => void +>t : T +>T : T +>t1 : T +>T : T +>ts : T[] +>T : T +>T : T + + +// exactly +test((t1: D, t2) => { t2.test2 }) +>test((t1: D, t2) => { t2.test2 }) : D +>test : (a: (t: T, t1: T) => void) => T +>(t1: D, t2) => { t2.test2 } : (t1: D, t2: D) => void +>t1 : D +>D : D +>t2 : D +>t2.test2 : string +>t2 : D +>test2 : string + +test((t1, t2: D) => { t2.test2 }) +>test((t1, t2: D) => { t2.test2 }) : D +>test : (a: (t: T, t1: T) => void) => T +>(t1, t2: D) => { t2.test2 } : (t1: D, t2: D) => void +>t1 : D +>t2 : D +>D : D +>t2.test2 : string +>t2 : D +>test2 : string + +// zero arg +test(() => {}) +>test(() => {}) : C +>test : (a: (t: T, t1: T) => void) => T +>() => {} : () => void + +// fewer args +test((t1: D) => {}) +>test((t1: D) => {}) : D +>test : (a: (t: T, t1: T) => void) => T +>(t1: D) => {} : (t1: D) => void +>t1 : D +>D : D + +// rest arg +test((...ts: D[]) => {}) +>test((...ts: D[]) => {}) : D +>test : (a: (t: T, t1: T) => void) => T +>(...ts: D[]) => {} : (...ts: D[]) => void +>ts : D[] +>D : D + +// source function has rest arg +testRest((t1: D) => {}) +>testRest((t1: D) => {}) : D +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t1: D) => {} : (t1: D) => void +>t1 : D +>D : D + +testRest((t1, t2, t3) => {}) +>testRest((t1, t2, t3) => {}) : C +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t1, t2, t3) => {} : (t1: C, t2: C, t3: C) => void +>t1 : C +>t2 : C +>t3 : C + +testRest((t1: D, t2, t3) => {}) +>testRest((t1: D, t2, t3) => {}) : D +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t1: D, t2, t3) => {} : (t1: D, t2: D, t3: D) => void +>t1 : D +>D : D +>t2 : D +>t3 : D + +testRest((t1, t2: D, t3) => {}) +>testRest((t1, t2: D, t3) => {}) : D +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t1, t2: D, t3) => {} : (t1: D, t2: D, t3: D) => void +>t1 : D +>t2 : D +>D : D +>t3 : D + +testRest((t2: D, ...t3) => {}) +>testRest((t2: D, ...t3) => {}) : any +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t2: D, ...t3) => {} : (t2: D, ...t3: any[]) => void +>t2 : D +>D : D +>t3 : any[] + +testRest((t2, ...t3: D[]) => {}) +>testRest((t2, ...t3: D[]) => {}) : C +>testRest : (a: (t: T, t1: T, ...ts: T[]) => void) => T +>(t2, ...t3: D[]) => {} : (t2: C, ...t3: D[]) => void +>t2 : C +>t3 : D[] +>D : D + diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.js b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.js new file mode 100644 index 00000000000..8b81ff506fe --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.js @@ -0,0 +1,12 @@ +//// [partiallyAnnotatedFunctionWitoutTypeParameter.ts] + +// simple case +declare function simple(f: (a: number, b: number) => void): {} + +simple((a: number, b) => {}) +simple((a, b: number) => {}) + + +//// [partiallyAnnotatedFunctionWitoutTypeParameter.js] +simple(function (a, b) { }); +simple(function (a, b) { }); diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.symbols b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.symbols new file mode 100644 index 00000000000..a7ed6b67d83 --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionWitoutTypeParameter.ts === + +// simple case +declare function simple(f: (a: number, b: number) => void): {} +>simple : Symbol(simple, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 0, 0)) +>f : Symbol(f, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 2, 24)) +>a : Symbol(a, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 2, 28)) +>b : Symbol(b, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 2, 38)) + +simple((a: number, b) => {}) +>simple : Symbol(simple, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 0, 0)) +>a : Symbol(a, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 4, 8)) +>b : Symbol(b, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 4, 18)) + +simple((a, b: number) => {}) +>simple : Symbol(simple, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 0, 0)) +>a : Symbol(a, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 5, 8)) +>b : Symbol(b, Decl(partiallyAnnotatedFunctionWitoutTypeParameter.ts, 5, 10)) + diff --git a/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.types b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.types new file mode 100644 index 00000000000..f07cd5a8928 --- /dev/null +++ b/tests/baselines/reference/partiallyAnnotatedFunctionWitoutTypeParameter.types @@ -0,0 +1,23 @@ +=== tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionWitoutTypeParameter.ts === + +// simple case +declare function simple(f: (a: number, b: number) => void): {} +>simple : (f: (a: number, b: number) => void) => {} +>f : (a: number, b: number) => void +>a : number +>b : number + +simple((a: number, b) => {}) +>simple((a: number, b) => {}) : {} +>simple : (f: (a: number, b: number) => void) => {} +>(a: number, b) => {} : (a: number, b: number) => void +>a : number +>b : number + +simple((a, b: number) => {}) +>simple((a, b: number) => {}) : {} +>simple : (f: (a: number, b: number) => void) => {} +>(a, b: number) => {} : (a: number, b: number) => void +>a : number +>b : number + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution3_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution3_classic.trace.json index 8b003e05e8f..90b8620e36c 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution3_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution3_classic.trace.json @@ -14,10 +14,13 @@ "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'file4'", "Resolving module name 'file4' relative to base url 'c:/root' - 'c:/root/file4'.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "File 'c:/root/folder2/file4.ts' does not exist.", + "File 'c:/root/folder2/file4.tsx' does not exist.", "File 'c:/root/folder2/file4.d.ts' does not exist.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "File 'c:/file4.ts' exist - use it as a name resolution result.", "======== Module name 'file4' was successfully resolved to 'c:/file4.ts'. ========" diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution3_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution3_node.trace.json index ab7210d7d02..5c7c143f604 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution3_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution3_node.trace.json @@ -5,13 +5,11 @@ "Resolving module name 'folder2/file2' relative to base url 'c:/root' - 'c:/root/folder2/file2'.", "Loading module as file / folder, candidate module location 'c:/root/folder2/file2'.", "File 'c:/root/folder2/file2.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/folder2/file2.ts', result 'c:/root/folder2/file2.ts'", "======== Module name 'folder2/file2' was successfully resolved to 'c:/root/folder2/file2.ts'. ========", "======== Resolving module './file3' from 'c:/root/folder2/file2.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location 'c:/root/folder2/file3'.", "File 'c:/root/folder2/file3.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/folder2/file3.ts', result 'c:/root/folder2/file3.ts'", "======== Module name './file3' was successfully resolved to 'c:/root/folder2/file3.ts'. ========", "======== Resolving module 'file4' from 'c:/root/folder2/file2.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", @@ -33,12 +31,8 @@ "File 'c:/root/folder2/node_modules/file4/index.ts' does not exist.", "File 'c:/root/folder2/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/folder2/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/root/node_modules/file4.ts' does not exist.", "File 'c:/root/node_modules/file4.tsx' does not exist.", @@ -47,12 +41,8 @@ "File 'c:/root/node_modules/file4/index.ts' does not exist.", "File 'c:/root/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/node_modules/file4.ts' does not exist.", "File 'c:/node_modules/file4.tsx' does not exist.", diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution4_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution4_classic.trace.json index 8b003e05e8f..90b8620e36c 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution4_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution4_classic.trace.json @@ -14,10 +14,13 @@ "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'file4'", "Resolving module name 'file4' relative to base url 'c:/root' - 'c:/root/file4'.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "File 'c:/root/folder2/file4.ts' does not exist.", + "File 'c:/root/folder2/file4.tsx' does not exist.", "File 'c:/root/folder2/file4.d.ts' does not exist.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "File 'c:/file4.ts' exist - use it as a name resolution result.", "======== Module name 'file4' was successfully resolved to 'c:/file4.ts'. ========" diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution4_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution4_node.trace.json index ab7210d7d02..5c7c143f604 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution4_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution4_node.trace.json @@ -5,13 +5,11 @@ "Resolving module name 'folder2/file2' relative to base url 'c:/root' - 'c:/root/folder2/file2'.", "Loading module as file / folder, candidate module location 'c:/root/folder2/file2'.", "File 'c:/root/folder2/file2.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/folder2/file2.ts', result 'c:/root/folder2/file2.ts'", "======== Module name 'folder2/file2' was successfully resolved to 'c:/root/folder2/file2.ts'. ========", "======== Resolving module './file3' from 'c:/root/folder2/file2.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", "Loading module as file / folder, candidate module location 'c:/root/folder2/file3'.", "File 'c:/root/folder2/file3.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/folder2/file3.ts', result 'c:/root/folder2/file3.ts'", "======== Module name './file3' was successfully resolved to 'c:/root/folder2/file3.ts'. ========", "======== Resolving module 'file4' from 'c:/root/folder2/file2.ts'. ========", "Explicitly specified module resolution kind: 'NodeJs'.", @@ -33,12 +31,8 @@ "File 'c:/root/folder2/node_modules/file4/index.ts' does not exist.", "File 'c:/root/folder2/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/folder2/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/folder2/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/folder2/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/root/node_modules/file4.ts' does not exist.", "File 'c:/root/node_modules/file4.tsx' does not exist.", @@ -47,12 +41,8 @@ "File 'c:/root/node_modules/file4/index.ts' does not exist.", "File 'c:/root/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/node_modules/file4.ts' does not exist.", "File 'c:/node_modules/file4.tsx' does not exist.", diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution5_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution5_classic.trace.json index d1709c82dc6..6c899bf028e 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution5_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution5_classic.trace.json @@ -14,6 +14,7 @@ "Module name 'folder3/file2', matched pattern '*'.", "Trying substitution '*', candidate module location: 'folder3/file2'.", "File 'c:/root/folder3/file2.ts' does not exist.", + "File 'c:/root/folder3/file2.tsx' does not exist.", "File 'c:/root/folder3/file2.d.ts' does not exist.", "Trying substitution 'generated/*', candidate module location: 'generated/folder3/file2'.", "File 'c:/root/generated/folder3/file2.ts' exist - use it as a name resolution result.", @@ -33,13 +34,17 @@ "Module name 'file4', matched pattern '*'.", "Trying substitution '*', candidate module location: 'file4'.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "Trying substitution 'generated/*', candidate module location: 'generated/file4'.", "File 'c:/root/generated/file4.ts' does not exist.", + "File 'c:/root/generated/file4.tsx' does not exist.", "File 'c:/root/generated/file4.d.ts' does not exist.", "File 'c:/root/folder1/file4.ts' does not exist.", + "File 'c:/root/folder1/file4.tsx' does not exist.", "File 'c:/root/folder1/file4.d.ts' does not exist.", "File 'c:/root/file4.ts' does not exist.", + "File 'c:/root/file4.tsx' does not exist.", "File 'c:/root/file4.d.ts' does not exist.", "File 'c:/file4.ts' exist - use it as a name resolution result.", "======== Module name 'file4' was successfully resolved to 'c:/file4.ts'. ========" diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution5_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution5_node.trace.json index 2efeefa24e5..ebef311d2a6 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution5_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution5_node.trace.json @@ -7,7 +7,6 @@ "Trying substitution '*', candidate module location: 'folder2/file1'.", "Loading module as file / folder, candidate module location 'c:/root/folder2/file1'.", "File 'c:/root/folder2/file1.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/folder2/file1.ts', result 'c:/root/folder2/file1.ts'", "======== Module name 'folder2/file1' was successfully resolved to 'c:/root/folder2/file1.ts'. ========", "======== Resolving module 'folder3/file2' from 'c:/root/folder1/file1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -26,7 +25,6 @@ "Trying substitution 'generated/*', candidate module location: 'generated/folder3/file2'.", "Loading module as file / folder, candidate module location 'c:/root/generated/folder3/file2'.", "File 'c:/root/generated/folder3/file2.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/generated/folder3/file2.ts', result 'c:/root/generated/folder3/file2.ts'", "======== Module name 'folder3/file2' was successfully resolved to 'c:/root/generated/folder3/file2.ts'. ========", "======== Resolving module 'components/file3' from 'c:/root/folder1/file1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -42,7 +40,6 @@ "File 'c:/root/shared/components/file3/index.ts' does not exist.", "File 'c:/root/shared/components/file3/index.tsx' does not exist.", "File 'c:/root/shared/components/file3/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/shared/components/file3/index.d.ts', result 'c:/root/shared/components/file3/index.d.ts'", "======== Module name 'components/file3' was successfully resolved to 'c:/root/shared/components/file3/index.d.ts'. ========", "======== Resolving module 'file4' from 'c:/root/folder1/file1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -75,12 +72,8 @@ "File 'c:/root/folder1/node_modules/file4/index.ts' does not exist.", "File 'c:/root/folder1/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/folder1/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/folder1/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/folder1/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/folder1/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/folder1/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/folder1/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/folder1/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/folder1/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/root/node_modules/file4.ts' does not exist.", "File 'c:/root/node_modules/file4.tsx' does not exist.", @@ -89,12 +82,8 @@ "File 'c:/root/node_modules/file4/index.ts' does not exist.", "File 'c:/root/node_modules/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/file4/index.d.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4.d.ts' does not exist.", "File 'c:/root/node_modules/@types/file4/package.json' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.ts' does not exist.", - "File 'c:/root/node_modules/@types/file4/index.tsx' does not exist.", "File 'c:/root/node_modules/@types/file4/index.d.ts' does not exist.", "File 'c:/node_modules/file4.ts' exist - use it as a name resolution result.", "Resolving real path for 'c:/node_modules/file4.ts', result 'c:/node_modules/file4.ts'", diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution6_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution6_classic.trace.json index 20fc416ccd4..d50a6c78ed7 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution6_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution6_classic.trace.json @@ -7,6 +7,7 @@ "Longest matching prefix for 'c:/root/src/project/file3' is 'c:/root/src/'", "Loading 'project/file3' from the root dir 'c:/root/src/', candidate location 'c:/root/src/project/file3'", "File 'c:/root/src/project/file3.ts' does not exist.", + "File 'c:/root/src/project/file3.tsx' does not exist.", "File 'c:/root/src/project/file3.d.ts' does not exist.", "Trying other entries in 'rootDirs'", "Loading 'project/file3' from the root dir 'c:/root/generated/src', candidate location 'c:/root/generated/src/project/file3'", @@ -20,10 +21,12 @@ "Longest matching prefix for 'c:/root/generated/src/file2' is 'c:/root/generated/src/'", "Loading 'file2' from the root dir 'c:/root/generated/src/', candidate location 'c:/root/generated/src/file2'", "File 'c:/root/generated/src/file2.ts' does not exist.", + "File 'c:/root/generated/src/file2.tsx' does not exist.", "File 'c:/root/generated/src/file2.d.ts' does not exist.", "Trying other entries in 'rootDirs'", "Loading 'file2' from the root dir 'c:/root/src', candidate location 'c:/root/src/file2'", "File 'c:/root/src/file2.ts' does not exist.", + "File 'c:/root/src/file2.tsx' does not exist.", "File 'c:/root/src/file2.d.ts' exist - use it as a name resolution result.", "======== Module name '../file2' was successfully resolved to 'c:/root/src/file2.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution6_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution6_node.trace.json index 28e51a11915..7c5e76a2847 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution6_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution6_node.trace.json @@ -18,7 +18,6 @@ "Loading 'project/file3' from the root dir 'c:/root/generated/src', candidate location 'c:/root/generated/src/project/file3'", "Loading module as file / folder, candidate module location 'c:/root/generated/src/project/file3'.", "File 'c:/root/generated/src/project/file3.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/generated/src/project/file3.ts', result 'c:/root/generated/src/project/file3.ts'", "======== Module name './project/file3' was successfully resolved to 'c:/root/generated/src/project/file3.ts'. ========", "======== Resolving module '../file2' from 'c:/root/generated/src/project/file3.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -45,6 +44,5 @@ "File 'c:/root/src/file2/index.ts' does not exist.", "File 'c:/root/src/file2/index.tsx' does not exist.", "File 'c:/root/src/file2/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/src/file2/index.d.ts', result 'c:/root/src/file2/index.d.ts'", "======== Module name '../file2' was successfully resolved to 'c:/root/src/file2/index.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json index a8cadb8f067..85373855eb5 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json @@ -7,6 +7,7 @@ "Longest matching prefix for 'c:/root/src/project/file2' is 'c:/root/src/'", "Loading 'project/file2' from the root dir 'c:/root/src/', candidate location 'c:/root/src/project/file2'", "File 'c:/root/src/project/file2.ts' does not exist.", + "File 'c:/root/src/project/file2.tsx' does not exist.", "File 'c:/root/src/project/file2.d.ts' does not exist.", "Trying other entries in 'rootDirs'", "Loading 'project/file2' from the root dir 'c:/root/generated/src', candidate location 'c:/root/generated/src/project/file2'", @@ -19,15 +20,20 @@ "Module name 'module3', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module3'.", "File 'c:/root/module3.ts' does not exist.", + "File 'c:/root/module3.tsx' does not exist.", "File 'c:/root/module3.d.ts' does not exist.", "Trying substitution 'c:/shared/*', candidate module location: 'c:/shared/module3'.", "File 'c:/shared/module3.ts' does not exist.", + "File 'c:/shared/module3.tsx' does not exist.", "File 'c:/shared/module3.d.ts' does not exist.", "File 'c:/root/src/module3.ts' does not exist.", + "File 'c:/root/src/module3.tsx' does not exist.", "File 'c:/root/src/module3.d.ts' does not exist.", "File 'c:/root/module3.ts' does not exist.", + "File 'c:/root/module3.tsx' does not exist.", "File 'c:/root/module3.d.ts' does not exist.", "File 'c:/module3.ts' does not exist.", + "File 'c:/module3.tsx' does not exist.", "File 'c:/module3.d.ts' exist - use it as a name resolution result.", "======== Module name 'module3' was successfully resolved to 'c:/module3.d.ts'. ========", "======== Resolving module 'module1' from 'c:/root/generated/src/project/file2.ts'. ========", @@ -37,9 +43,11 @@ "Module name 'module1', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module1'.", "File 'c:/root/module1.ts' does not exist.", + "File 'c:/root/module1.tsx' does not exist.", "File 'c:/root/module1.d.ts' does not exist.", "Trying substitution 'c:/shared/*', candidate module location: 'c:/shared/module1'.", "File 'c:/shared/module1.ts' does not exist.", + "File 'c:/shared/module1.tsx' does not exist.", "File 'c:/shared/module1.d.ts' exist - use it as a name resolution result.", "======== Module name 'module1' was successfully resolved to 'c:/shared/module1.d.ts'. ========", "======== Resolving module 'templates/module2' from 'c:/root/generated/src/project/file2.ts'. ========", @@ -58,10 +66,12 @@ "Longest matching prefix for 'c:/root/generated/src/file3' is 'c:/root/generated/src/'", "Loading 'file3' from the root dir 'c:/root/generated/src/', candidate location 'c:/root/generated/src/file3'", "File 'c:/root/generated/src/file3.ts' does not exist.", + "File 'c:/root/generated/src/file3.tsx' does not exist.", "File 'c:/root/generated/src/file3.d.ts' does not exist.", "Trying other entries in 'rootDirs'", "Loading 'file3' from the root dir 'c:/root/src', candidate location 'c:/root/src/file3'", "File 'c:/root/src/file3.ts' does not exist.", + "File 'c:/root/src/file3.tsx' does not exist.", "File 'c:/root/src/file3.d.ts' exist - use it as a name resolution result.", "======== Module name '../file3' was successfully resolved to 'c:/root/src/file3.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json index 48633c85e3b..31440cca28e 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json @@ -18,7 +18,6 @@ "Loading 'project/file2' from the root dir 'c:/root/generated/src', candidate location 'c:/root/generated/src/project/file2'", "Loading module as file / folder, candidate module location 'c:/root/generated/src/project/file2'.", "File 'c:/root/generated/src/project/file2.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/generated/src/project/file2.ts', result 'c:/root/generated/src/project/file2.ts'", "======== Module name './project/file2' was successfully resolved to 'c:/root/generated/src/project/file2.ts'. ========", "======== Resolving module 'module3' from 'c:/root/src/file1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -51,12 +50,8 @@ "File 'c:/root/src/node_modules/module3/index.ts' does not exist.", "File 'c:/root/src/node_modules/module3/index.tsx' does not exist.", "File 'c:/root/src/node_modules/module3/index.d.ts' does not exist.", - "File 'c:/root/src/node_modules/@types/module3.ts' does not exist.", - "File 'c:/root/src/node_modules/@types/module3.tsx' does not exist.", "File 'c:/root/src/node_modules/@types/module3.d.ts' does not exist.", "File 'c:/root/src/node_modules/@types/module3/package.json' does not exist.", - "File 'c:/root/src/node_modules/@types/module3/index.ts' does not exist.", - "File 'c:/root/src/node_modules/@types/module3/index.tsx' does not exist.", "File 'c:/root/src/node_modules/@types/module3/index.d.ts' does not exist.", "File 'c:/root/node_modules/module3.ts' does not exist.", "File 'c:/root/node_modules/module3.tsx' does not exist.", @@ -65,12 +60,8 @@ "File 'c:/root/node_modules/module3/index.ts' does not exist.", "File 'c:/root/node_modules/module3/index.tsx' does not exist.", "File 'c:/root/node_modules/module3/index.d.ts' does not exist.", - "File 'c:/root/node_modules/@types/module3.ts' does not exist.", - "File 'c:/root/node_modules/@types/module3.tsx' does not exist.", "File 'c:/root/node_modules/@types/module3.d.ts' does not exist.", "File 'c:/root/node_modules/@types/module3/package.json' does not exist.", - "File 'c:/root/node_modules/@types/module3/index.ts' does not exist.", - "File 'c:/root/node_modules/@types/module3/index.tsx' does not exist.", "File 'c:/root/node_modules/@types/module3/index.d.ts' does not exist.", "File 'c:/node_modules/module3.ts' does not exist.", "File 'c:/node_modules/module3.tsx' does not exist.", @@ -100,7 +91,6 @@ "File 'c:/shared/module1/index.ts' does not exist.", "File 'c:/shared/module1/index.tsx' does not exist.", "File 'c:/shared/module1/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/shared/module1/index.d.ts', result 'c:/shared/module1/index.d.ts'", "======== Module name 'module1' was successfully resolved to 'c:/shared/module1/index.d.ts'. ========", "======== Resolving module 'templates/module2' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -110,7 +100,6 @@ "Trying substitution 'generated/src/templates/*', candidate module location: 'generated/src/templates/module2'.", "Loading module as file / folder, candidate module location 'c:/root/generated/src/templates/module2'.", "File 'c:/root/generated/src/templates/module2.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/generated/src/templates/module2.ts', result 'c:/root/generated/src/templates/module2.ts'", "======== Module name 'templates/module2' was successfully resolved to 'c:/root/generated/src/templates/module2.ts'. ========", "======== Resolving module '../file3' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -137,6 +126,5 @@ "File 'c:/root/src/file3/index.ts' does not exist.", "File 'c:/root/src/file3/index.tsx' does not exist.", "File 'c:/root/src/file3/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'c:/root/src/file3/index.d.ts', result 'c:/root/src/file3/index.d.ts'", "======== Module name '../file3' was successfully resolved to 'c:/root/src/file3/index.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.js b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.js new file mode 100644 index 00000000000..06f6b50e4a0 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.js @@ -0,0 +1,24 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_withExtension.ts] //// + +//// [foo.ts] + +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "foo"; +import { bar } from "bar"; + + +//// [foo.js] +"use strict"; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.symbols new file mode 100644 index 00000000000..717660067ec --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.symbols @@ -0,0 +1,16 @@ +=== /a.ts === +import { foo } from "foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /foo/foo.ts === + +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /bar/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.trace.json new file mode 100644 index 00000000000..a761414eb42 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.trace.json @@ -0,0 +1,18 @@ +[ + "======== Resolving module 'foo' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'foo'", + "'paths' option is specified, looking for a pattern to match module name 'foo'.", + "Module name 'foo', matched pattern 'foo'.", + "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", + "File '/foo/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'foo' was successfully resolved to '/foo/foo.ts'. ========", + "======== Resolving module 'bar' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'bar'", + "'paths' option is specified, looking for a pattern to match module name 'bar'.", + "Module name 'bar', matched pattern 'bar'.", + "Trying substitution 'bar/bar.js', candidate module location: 'bar/bar.js'.", + "File '/bar/bar.js' exist - use it as a name resolution result.", + "======== Module name 'bar' was successfully resolved to '/bar/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.types b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.types new file mode 100644 index 00000000000..8d7c57b1d27 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension.types @@ -0,0 +1,16 @@ +=== /a.ts === +import { foo } from "foo"; +>foo : () => void + +import { bar } from "bar"; +>bar : () => void + +=== /foo/foo.ts === + +export function foo() {} +>foo : () => void + +=== /bar/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.errors.txt b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.errors.txt new file mode 100644 index 00000000000..7578f730c33 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.errors.txt @@ -0,0 +1,9 @@ +/a.ts(2,21): error TS2307: Cannot find module 'foo'. + + +==== /a.ts (1 errors) ==== + + import { foo } from "foo"; + ~~~~~ +!!! error TS2307: Cannot find module 'foo'. + \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.js b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.js new file mode 100644 index 00000000000..1774876911f --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.js @@ -0,0 +1,7 @@ +//// [a.ts] + +import { foo } from "foo"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json new file mode 100644 index 00000000000..face88d225e --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_withExtension_failedLookup.trace.json @@ -0,0 +1,32 @@ +[ + "======== Resolving module 'foo' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'foo'", + "'paths' option is specified, looking for a pattern to match module name 'foo'.", + "Module name 'foo', matched pattern 'foo'.", + "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", + "File '/foo/foo.ts' does not exist.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/node_modules/foo.ts' does not exist.", + "File '/node_modules/foo.tsx' does not exist.", + "File '/node_modules/foo.d.ts' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.ts' does not exist.", + "File '/node_modules/foo/index.tsx' does not exist.", + "File '/node_modules/foo/index.d.ts' does not exist.", + "File '/node_modules/@types/foo.d.ts' does not exist.", + "File '/node_modules/@types/foo/package.json' does not exist.", + "File '/node_modules/@types/foo/index.d.ts' does not exist.", + "'baseUrl' option is set to '/', using this value to resolve non-relative module name 'foo'", + "'paths' option is specified, looking for a pattern to match module name 'foo'.", + "Module name 'foo', matched pattern 'foo'.", + "Trying substitution 'foo/foo.ts', candidate module location: 'foo/foo.ts'.", + "File '/foo/foo.ts' does not exist.", + "Loading module 'foo' from 'node_modules' folder.", + "File '/node_modules/foo.js' does not exist.", + "File '/node_modules/foo.jsx' does not exist.", + "File '/node_modules/foo/package.json' does not exist.", + "File '/node_modules/foo/index.js' does not exist.", + "File '/node_modules/foo/index.jsx' does not exist.", + "======== Module name 'foo' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js b/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js index cebf700aa59..c139b6279fd 100644 --- a/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js +++ b/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js @@ -161,11 +161,11 @@ var publicClassWithWithPrivatePropertyTypes = (function () { } return publicClassWithWithPrivatePropertyTypes; }()); -exports.publicClassWithWithPrivatePropertyTypes = publicClassWithWithPrivatePropertyTypes; publicClassWithWithPrivatePropertyTypes.myPublicStaticProperty = exporter.createExportedWidget1(); // Error publicClassWithWithPrivatePropertyTypes.myPrivateStaticProperty = exporter.createExportedWidget1(); publicClassWithWithPrivatePropertyTypes.myPublicStaticProperty1 = exporter.createExportedWidget3(); // Error publicClassWithWithPrivatePropertyTypes.myPrivateStaticProperty1 = exporter.createExportedWidget3(); +exports.publicClassWithWithPrivatePropertyTypes = publicClassWithWithPrivatePropertyTypes; var privateClassWithWithPrivatePropertyTypes = (function () { function privateClassWithWithPrivatePropertyTypes() { this.myPublicProperty = exporter.createExportedWidget1(); @@ -190,9 +190,9 @@ var publicClassWithPrivateModulePropertyTypes = (function () { } return publicClassWithPrivateModulePropertyTypes; }()); -exports.publicClassWithPrivateModulePropertyTypes = publicClassWithPrivateModulePropertyTypes; publicClassWithPrivateModulePropertyTypes.myPublicStaticProperty = exporter.createExportedWidget2(); // Error publicClassWithPrivateModulePropertyTypes.myPublicStaticProperty1 = exporter.createExportedWidget4(); // Error +exports.publicClassWithPrivateModulePropertyTypes = publicClassWithPrivateModulePropertyTypes; exports.publicVarWithPrivateModulePropertyTypes = exporter.createExportedWidget2(); // Error exports.publicVarWithPrivateModulePropertyTypes1 = exporter.createExportedWidget4(); // Error var privateClassWithPrivateModulePropertyTypes = (function () { diff --git a/tests/baselines/reference/privacyLocalInternalReferenceImportWithExport.js b/tests/baselines/reference/privacyLocalInternalReferenceImportWithExport.js index 0ab6d3e531e..b328e8b3036 100644 --- a/tests/baselines/reference/privacyLocalInternalReferenceImportWithExport.js +++ b/tests/baselines/reference/privacyLocalInternalReferenceImportWithExport.js @@ -163,11 +163,11 @@ var m_private; return c_private; }()); m_private.c_private = c_private; + var e_private; (function (e_private) { e_private[e_private["Happy"] = 0] = "Happy"; e_private[e_private["Grumpy"] = 1] = "Grumpy"; - })(m_private.e_private || (m_private.e_private = {})); - var e_private = m_private.e_private; + })(e_private = m_private.e_private || (m_private.e_private = {})); function f_private() { return new c_private(); } @@ -192,11 +192,11 @@ var m_public; return c_public; }()); m_public.c_public = c_public; + var e_public; (function (e_public) { e_public[e_public["Happy"] = 0] = "Happy"; e_public[e_public["Grumpy"] = 1] = "Grumpy"; - })(m_public.e_public || (m_public.e_public = {})); - var e_public = m_public.e_public; + })(e_public = m_public.e_public || (m_public.e_public = {})); function f_public() { return new c_public(); } diff --git a/tests/baselines/reference/privacyLocalInternalReferenceImportWithoutExport.js b/tests/baselines/reference/privacyLocalInternalReferenceImportWithoutExport.js index 96f7b74b474..7d4a80a0d29 100644 --- a/tests/baselines/reference/privacyLocalInternalReferenceImportWithoutExport.js +++ b/tests/baselines/reference/privacyLocalInternalReferenceImportWithoutExport.js @@ -164,11 +164,11 @@ define(["require", "exports"], function (require, exports) { return c_private; }()); m_private.c_private = c_private; + var e_private; (function (e_private) { e_private[e_private["Happy"] = 0] = "Happy"; e_private[e_private["Grumpy"] = 1] = "Grumpy"; - })(m_private.e_private || (m_private.e_private = {})); - var e_private = m_private.e_private; + })(e_private = m_private.e_private || (m_private.e_private = {})); function f_private() { return new c_private(); } @@ -193,11 +193,11 @@ define(["require", "exports"], function (require, exports) { return c_public; }()); m_public.c_public = c_public; + var e_public; (function (e_public) { e_public[e_public["Happy"] = 0] = "Happy"; e_public[e_public["Grumpy"] = 1] = "Grumpy"; - })(m_public.e_public || (m_public.e_public = {})); - var e_public = m_public.e_public; + })(e_public = m_public.e_public || (m_public.e_public = {})); function f_public() { return new c_public(); } diff --git a/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithExport.js b/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithExport.js index 852ae4d3f19..a01f1ef611f 100644 --- a/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithExport.js +++ b/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithExport.js @@ -111,11 +111,11 @@ define(["require", "exports"], function (require, exports) { return c_private; }()); m_private.c_private = c_private; + var e_private; (function (e_private) { e_private[e_private["Happy"] = 0] = "Happy"; e_private[e_private["Grumpy"] = 1] = "Grumpy"; - })(m_private.e_private || (m_private.e_private = {})); - var e_private = m_private.e_private; + })(e_private = m_private.e_private || (m_private.e_private = {})); function f_private() { return new c_private(); } @@ -140,11 +140,11 @@ define(["require", "exports"], function (require, exports) { return c_public; }()); m_public.c_public = c_public; + var e_public; (function (e_public) { e_public[e_public["Happy"] = 0] = "Happy"; e_public[e_public["Grumpy"] = 1] = "Grumpy"; - })(m_public.e_public || (m_public.e_public = {})); - var e_public = m_public.e_public; + })(e_public = m_public.e_public || (m_public.e_public = {})); function f_public() { return new c_public(); } diff --git a/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithoutExport.js b/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithoutExport.js index 1241165a8dc..2554085b94b 100644 --- a/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithoutExport.js +++ b/tests/baselines/reference/privacyTopLevelInternalReferenceImportWithoutExport.js @@ -112,11 +112,11 @@ define(["require", "exports"], function (require, exports) { return c_private; }()); m_private.c_private = c_private; + var e_private; (function (e_private) { e_private[e_private["Happy"] = 0] = "Happy"; e_private[e_private["Grumpy"] = 1] = "Grumpy"; - })(m_private.e_private || (m_private.e_private = {})); - var e_private = m_private.e_private; + })(e_private = m_private.e_private || (m_private.e_private = {})); function f_private() { return new c_private(); } @@ -141,11 +141,11 @@ define(["require", "exports"], function (require, exports) { return c_public; }()); m_public.c_public = c_public; + var e_public; (function (e_public) { e_public[e_public["Happy"] = 0] = "Happy"; e_public[e_public["Grumpy"] = 1] = "Grumpy"; - })(m_public.e_public || (m_public.e_public = {})); - var e_public = m_public.e_public; + })(e_public = m_public.e_public || (m_public.e_public = {})); function f_public() { return new c_public(); } diff --git a/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/amd/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt b/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/amd/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt index ac25edc1bd5..668f037a03b 100644 --- a/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/amd/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt +++ b/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/amd/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt @@ -1,9 +1,11 @@ error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. error TS5055: Cannot write file 'SameNameDTsNotSpecifiedWithAllowJs/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. !!! error TS5055: Cannot write file 'SameNameDTsNotSpecifiedWithAllowJs/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== SameNameDTsNotSpecifiedWithAllowJs/a.d.ts (0 errors) ==== declare var a: number; ==== SameNameDTsNotSpecifiedWithAllowJs/a.js (0 errors) ==== diff --git a/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/node/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt b/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/node/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt index ac25edc1bd5..668f037a03b 100644 --- a/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/node/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt +++ b/tests/baselines/reference/project/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs/node/jsFileCompilationSameNameDtsNotSpecifiedWithAllowJs.errors.txt @@ -1,9 +1,11 @@ error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. error TS5055: Cannot write file 'SameNameDTsNotSpecifiedWithAllowJs/a.js' because it would overwrite input file. + Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig !!! error TS5053: Option 'allowJs' cannot be specified with option 'declaration'. !!! error TS5055: Cannot write file 'SameNameDTsNotSpecifiedWithAllowJs/a.js' because it would overwrite input file. +!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig ==== SameNameDTsNotSpecifiedWithAllowJs/a.d.ts (0 errors) ==== declare var a: number; ==== SameNameDTsNotSpecifiedWithAllowJs/a.js (0 errors) ==== diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map index c0e40d9e56c..891c03b13f2 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map index 5f6fc59aa0e..30f6e242bc8 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index c0e40d9e56c..891c03b13f2 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index 5f6fc59aa0e..30f6e242bc8 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 06567a4fddd..dce282ee37f 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index d3c0e8697cd..1316ec74659 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map index 048c2816811..5db5f8f1bfb 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map index 8e4c69b85ca..28136d8ffc3 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map index adc497fc60f..dd409b9f2c3 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map index 3c11f6387b3..78b4b9fcfe1 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map index f102ba902d9..f5f5dfcd793 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map index c84a8f5c835..6ba04afda9e 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 8e4c69b85ca..28136d8ffc3 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index adc497fc60f..dd409b9f2c3 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 048c2816811..5db5f8f1bfb 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index f102ba902d9..f5f5dfcd793 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index c84a8f5c835..6ba04afda9e 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 3c11f6387b3..78b4b9fcfe1 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index 51320616653..d9151baabe4 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../../outputdir_module_multifolder_ref/m2.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../../outputdir_module_multifolder_ref/m2.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map index cb20dafd0e6..43b1caa625e 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map index 379e5b9d7b2..ba491a3c6fa 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map index 2a7d88eea53..02f7bbcbb67 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map index 99658249a09..766ff607b54 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index cb20dafd0e6..43b1caa625e 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 379e5b9d7b2..ba491a3c6fa 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 2a7d88eea53..02f7bbcbb67 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 99658249a09..766ff607b54 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 105ebefb06e..a910ecda80e 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map index 9eb482b6438..a6d24f0f020 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map index 379e5b9d7b2..ba491a3c6fa 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map index 764cd7db3b4..a23c1871126 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map index 48a5bd9efa8..a758d2a1cd0 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 9eb482b6438..a6d24f0f020 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 379e5b9d7b2..ba491a3c6fa 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index 764cd7db3b4..a23c1871126 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index 48a5bd9efa8..a758d2a1cd0 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index 12c15dd7143..a3532b9e4ce 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map index 26b3342e168..0dab1514706 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map index 2137f48e86b..14104ec68b9 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index 26b3342e168..0dab1514706 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index 2137f48e86b..14104ec68b9 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 6e903b7c370..d8fff48f73e 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_mixed_subfolder/ref/m1.ts","../outputdir_mixed_subfolder/ref/m2.ts","../outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_mixed_subfolder/ref/m1.ts","../outputdir_mixed_subfolder/ref/m2.ts","../outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 4767cb6f425..bb9e992d471 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../outputdir_mixed_subfolder/ref/m1.ts","../outputdir_mixed_subfolder/ref/m2.ts","../outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../outputdir_mixed_subfolder/ref/m1.ts","../outputdir_mixed_subfolder/ref/m2.ts","../outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map index 60700ad9d17..4f51d470c82 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map index 1c3270c1034..ee8a26cafcf 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map index eb045bec338..e60e0fbfa7a 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map index 4b491bfe9bb..3c653ded700 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map index 70285d9fdb4..5f97087307d 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/test.js.map index 3b815b52961..8c64bacf533 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 1c3270c1034..ee8a26cafcf 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index eb045bec338..e60e0fbfa7a 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 60700ad9d17..4f51d470c82 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 70285d9fdb4..5f97087307d 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index 3b815b52961..8c64bacf533 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 4b491bfe9bb..3c653ded700 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index e5f2d235179..ae1d6457599 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../projects/outputdir_module_multifolder/ref/m1.ts","../projects/outputdir_module_multifolder_ref/m2.ts","../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../projects/outputdir_module_multifolder/ref/m1.ts","../projects/outputdir_module_multifolder_ref/m2.ts","../projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map index a623d2caaa6..611b73c5c7d 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/test.js.map index 579a6a187e3..a6d5cebe7f1 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/m1.js.map index 3a1b7b27c58..733fa0fc069 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/test.js.map index a9589e1fed8..86cfbeb5b63 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index a623d2caaa6..611b73c5c7d 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 579a6a187e3..a6d5cebe7f1 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 3a1b7b27c58..733fa0fc069 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index a9589e1fed8..86cfbeb5b63 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 5ac4a707e39..3542da2fe04 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts","../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_simple/m1.ts","../outputdir_module_simple/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map index 943ae3c5b8e..dbfe0b5d927 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map index 478bae202d6..a8d6293492c 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map index 9fea18a6b02..172c4d4804a 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/test.js.map index e96624acd65..ef62267d957 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 943ae3c5b8e..dbfe0b5d927 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 478bae202d6..a8d6293492c 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index 9fea18a6b02..172c4d4804a 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index e96624acd65..ef62267d957 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index 4c60ddd29d4..3096c610237 100644 --- a/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/mapRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/ref/m1.ts","../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../outputdir_module_subfolder/ref/m1.ts","../outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map index a1de0913da5..c657ed8edce 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map index 861972de209..56f12c22903 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index a1de0913da5..c657ed8edce 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index 861972de209..56f12c22903 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 64ad8eb1642..eececdeabfd 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 63bc893832b..4bdde308824 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/ref/m2.ts","file:///tests/cases/projects/outputdir_mixed_subfolder/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map index 7a409515607..3c1c9b64dc2 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map index 3343670eb84..9bdc7ad5504 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/test.js.map index 57bb373e054..3a4d618044a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map index 2da721ff1a0..4103e499cbd 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map index c1f7e172c9d..49f97b88a38 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/test.js.map index 474dd107529..830a0ddd3e5 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 3343670eb84..9bdc7ad5504 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index 57bb373e054..3a4d618044a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 7a409515607..3c1c9b64dc2 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index c1f7e172c9d..49f97b88a38 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index 474dd107529..830a0ddd3e5 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 2da721ff1a0..4103e499cbd 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index 155baf7912b..6b934e00e04 100644 --- a/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts","file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts","file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_multifolder/ref/m1.ts","file:///tests/cases/projects/outputdir_module_multifolder_ref/m2.ts","file:///tests/cases/projects/outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/m1.js.map index e9f1d54cc87..eceec7b450a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/test.js.map index 4c83678dafd..d68dbf6eb9e 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/m1.js.map index e96a1a904e7..b9de639cb1d 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/test.js.map index e0513a8b07b..826729aba87 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index e9f1d54cc87..eceec7b450a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 4c83678dafd..d68dbf6eb9e 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index e96a1a904e7..b9de639cb1d 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index e0513a8b07b..826729aba87 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index ecbd039578c..5396cab1d7c 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts","file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_simple/m1.ts","file:///tests/cases/projects/outputdir_module_simple/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map index 94b0fd005cb..755cc1d0aaf 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/test.js.map index 76cc81a74f4..957a73c648a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map index 637153a8c7a..f7e43883048 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/test.js.map index 99312830f1c..8baefdad92b 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 94b0fd005cb..755cc1d0aaf 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 76cc81a74f4..957a73c648a 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index 637153a8c7a..f7e43883048 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index 99312830f1c..8baefdad92b 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index d962fcf11cb..308dbbfaa67 100644 --- a/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_module_subfolder/ref/m1.ts","file:///tests/cases/projects/outputdir_module_subfolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map index e68a248d5d7..a1c9985be48 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map index c6ff2cc27ce..9ccd44f3a01 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index e68a248d5d7..a1c9985be48 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index c6ff2cc27ce..9ccd44f3a01 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 35e555688e0..26353fdf396 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 19bcc3ee32a..ec57587014d 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map index a8c35bc15c6..59ebd34cfe3 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map index f1623c531a6..9afdf343f77 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map index b199c0dc1ad..5000f3a49b9 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map index ef338fcc887..866e1007e24 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map index 10777c25bd4..0f5e28ddbf7 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/test.js.map index dbab2cdf457..a39cd29ba77 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index f1623c531a6..9afdf343f77 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index b199c0dc1ad..5000f3a49b9 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index a8c35bc15c6..59ebd34cfe3 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 10777c25bd4..0f5e28ddbf7 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index dbab2cdf457..a39cd29ba77 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index ef338fcc887..866e1007e24 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index 5a120cbe800..c4facdba936 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map index 26e7b01ccdb..1706ba76817 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/m1.js.map index 1b563cf259d..d134ab774af 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/test.js.map index 46e8000caa0..d07c1aa0678 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index 26e7b01ccdb..1706ba76817 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 1b563cf259d..d134ab774af 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 46e8000caa0..d07c1aa0678 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 28d5511a5ee..64c90d05e88 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map index 88ce97eeeff..7e2762b41a4 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map index e28d378dfc0..eb883275568 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/test.js.map index c956b034f6f..4f024886c03 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 88ce97eeeff..7e2762b41a4 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index e28d378dfc0..eb883275568 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index c956b034f6f..4f024886c03 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index a46d68e9b05..6d26d850e19 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/amd/nodeModulesMaxDepthExceeded.errors.txt b/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/amd/nodeModulesMaxDepthExceeded.errors.txt index 6d95ac42c8f..99e7b193f0c 100644 --- a/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/amd/nodeModulesMaxDepthExceeded.errors.txt +++ b/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/amd/nodeModulesMaxDepthExceeded.errors.txt @@ -1,5 +1,5 @@ maxDepthExceeded/root.ts(3,1): error TS2322: Type '"10"' is not assignable to type 'number'. -maxDepthExceeded/root.ts(4,1): error TS2322: Type '42' is not assignable to type 'true'. +maxDepthExceeded/root.ts(4,4): error TS2540: Cannot assign to 'rel' because it is a constant or a read-only property. ==== entry.js (0 errors) ==== @@ -36,8 +36,8 @@ maxDepthExceeded/root.ts(4,1): error TS2322: Type '42' is not assignable to type ~~~~~~~ !!! error TS2322: Type '"10"' is not assignable to type 'number'. m1.rel = 42; // Error: Should be boolean - ~~~~~~ -!!! error TS2322: Type '42' is not assignable to type 'true'. + ~~~ +!!! error TS2540: Cannot assign to 'rel' because it is a constant or a read-only property. m1.f2.person.age = "10"; // OK if stopped at 2 modules: person will be "any". \ No newline at end of file diff --git a/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/node/nodeModulesMaxDepthExceeded.errors.txt b/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/node/nodeModulesMaxDepthExceeded.errors.txt index 6d95ac42c8f..99e7b193f0c 100644 --- a/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/node/nodeModulesMaxDepthExceeded.errors.txt +++ b/tests/baselines/reference/project/nodeModulesMaxDepthExceeded/node/nodeModulesMaxDepthExceeded.errors.txt @@ -1,5 +1,5 @@ maxDepthExceeded/root.ts(3,1): error TS2322: Type '"10"' is not assignable to type 'number'. -maxDepthExceeded/root.ts(4,1): error TS2322: Type '42' is not assignable to type 'true'. +maxDepthExceeded/root.ts(4,4): error TS2540: Cannot assign to 'rel' because it is a constant or a read-only property. ==== entry.js (0 errors) ==== @@ -36,8 +36,8 @@ maxDepthExceeded/root.ts(4,1): error TS2322: Type '42' is not assignable to type ~~~~~~~ !!! error TS2322: Type '"10"' is not assignable to type 'number'. m1.rel = 42; // Error: Should be boolean - ~~~~~~ -!!! error TS2322: Type '42' is not assignable to type 'true'. + ~~~ +!!! error TS2540: Cannot assign to 'rel' because it is a constant or a read-only property. m1.f2.person.age = "10"; // OK if stopped at 2 modules: person will be "any". \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map index fa8f5c4613e..e9a80c428b2 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map index 3d7c6263ee6..9f1206b5b14 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index fa8f5c4613e..e9a80c428b2 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index 3d7c6263ee6..9f1206b5b14 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 28783dfb983..650c9d1e5d5 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 1361d34702b..6113c44d85d 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"/tests/cases/projects/outputdir_mixed_subfolder/src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map index 90860d39fe5..ab7082a2e8e 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map index b9400dc5624..6bebdd113b6 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map index c50aee154a2..21c996978fd 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map index 11747238b4e..06c30f32eaf 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map index 186a8fb3753..b757263c866 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map index 450cff64fa1..b123ccf13c8 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index b9400dc5624..6bebdd113b6 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index c50aee154a2..21c996978fd 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 90860d39fe5..ab7082a2e8e 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 186a8fb3753..b757263c866 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index 450cff64fa1..b123ccf13c8 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 11747238b4e..06c30f32eaf 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index c1afcd019cc..baeea1e93dc 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_multifolder/src/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map index 3539fcb8d17..ffc39be8044 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map index 6355e109114..6366b8c2d85 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map index 4347d2eb3ea..04bd4e10a3b 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map index 647c302260c..9dc457a0167 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index 3539fcb8d17..ffc39be8044 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 6355e109114..6366b8c2d85 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 4347d2eb3ea..04bd4e10a3b 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 647c302260c..9dc457a0167 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 13c43235b2b..aa0c2ca28b2 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_simple/src/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map index d39589e4f3e..cd798e72d89 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map index 63351122f3e..6738a871942 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map index 4cd2a39d1c1..81d64320d78 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map index 993894958b0..b2ea9133dfc 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index d39589e4f3e..cd798e72d89 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index 63351122f3e..6738a871942 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index 4cd2a39d1c1..81d64320d78 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index 993894958b0..b2ea9133dfc 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index 8dca8ba1a6c..27b41a837a9 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"/tests/cases/projects/outputdir_module_subfolder/src/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map index 5685e41f2bb..560075530f1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map index ea96dcd448f..27abb47a45b 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index 5685e41f2bb..560075530f1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index ea96dcd448f..27abb47a45b 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index f9f1f0cd10e..9a9586bd20d 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 19977a8159b..16e3437b61c 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"../src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"../src/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map index 0f5e1f6de5c..6b4ece94c15 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map index 453bd036286..8271bf25be1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map index 019c9ca53da..8be239f3553 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map index d32dfbe0fa3..c7ae549832a 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map index a923e39f3eb..37adc61e54f 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/test.js.map index faf9a0a8d50..79b428ca3a1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 453bd036286..8271bf25be1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index 019c9ca53da..8be239f3553 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 0f5e1f6de5c..6b4ece94c15 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index a923e39f3eb..37adc61e54f 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index faf9a0a8d50..79b428ca3a1 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index d32dfbe0fa3..c7ae549832a 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index bb8c756a0b9..4d37f7bfbf5 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map index 05d9f8cb3da..29c8533aded 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/test.js.map index e446b64679d..d713f6b7f5e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/m1.js.map index cca0e50d762..8086d9c04da 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/test.js.map index 46798ce7bb4..0d24a0e332a 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index 05d9f8cb3da..29c8533aded 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index e446b64679d..d713f6b7f5e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index cca0e50d762..8086d9c04da 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 46798ce7bb4..0d24a0e332a 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index d70e1816041..7e83d4cd269 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map index 43194290d9d..91793ab1002 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map index e446b64679d..d713f6b7f5e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map index cd7b5d10db4..00e388b171e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/test.js.map index b77575bb8b5..07178ab519f 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 43194290d9d..91793ab1002 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index e446b64679d..d713f6b7f5e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index cd7b5d10db4..00e388b171e 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"../src/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index b77575bb8b5..07178ab519f 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index 3c2cbaf1342..223d2cfdad3 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourceRootRelativePathModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"../src/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/amd/ref/m2.js.map index b7c7a763318..c4bc3c32708 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/node/ref/m2.js.map index 57aea3578c6..208dd329040 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index af5f11f8dd3..c0b56df8d90 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index 3d8629098dc..5e34d4494dd 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 06567a4fddd..dce282ee37f 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index d3c0e8697cd..1316ec74659 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"","sources":["../ref/m1.ts","../ref/m2.ts","../test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/diskFile0.js.map index b7c7a763318..c4bc3c32708 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/ref/m1.js.map index 41a7fb93ee6..dcdf5faf897 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/test.js.map index dc6ab342a51..096386e968d 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/diskFile0.js.map index 57aea3578c6..208dd329040 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/ref/m1.js.map index 6af45080bd6..87fa414a454 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/test.js.map index c51718c91d8..a9dba1be1dd 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index a77c789e625..2293c1a7c96 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index 5890568ea24..d21a585cc41 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../../test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 502b9145dc8..5d8cf325d52 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 1bc2118f2b7..49bb95f32d5 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index 48cc4f7aa98..a48d929a860 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index 476d3d93966..b9e5ddb335f 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"","sources":["../../../../outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index 51320616653..d9151baabe4 100644 --- a/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../../outputdir_module_multifolder_ref/m2.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../../outputdir_module_multifolder_ref/m2.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/m1.js.map index 41a7fb93ee6..dcdf5faf897 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/test.js.map index 0deeb01864d..9a899efce64 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/m1.js.map index 6af45080bd6..87fa414a454 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/test.js.map index 40fdb33821b..57b2f0a9935 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index 761471d9d82..128c9957bf4 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index d3fedc589bf..50263c64897 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 2923aa0a014..40d0111893e 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 8cd970cb557..cc2b2e9b918 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 105ebefb06e..a910ecda80e 100644 --- a/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/ref/m1.js.map index 41a7fb93ee6..dcdf5faf897 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/test.js.map index 0deeb01864d..9a899efce64 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/ref/m1.js.map index 6af45080bd6..87fa414a454 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/test.js.map index 92ae347312c..6f71fb82f4c 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 8e4c69b85ca..28136d8ffc3 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index d3fedc589bf..50263c64897 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index f102ba902d9..f5f5dfcd793 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index be65d1d02a5..9c9d3ffec92 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../../test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index 12c15dd7143..a3532b9e4ce 100644 --- a/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"","sources":["../ref/m1.ts","../test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map index e68a248d5d7..a1c9985be48 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/amd/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map index c6ff2cc27ce..9ccd44f3a01 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderNoOutdir/node/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map index e68a248d5d7..a1c9985be48 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map index c6ff2cc27ce..9ccd44f3a01 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map index 35e555688e0..26353fdf396 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map index 19bcc3ee32a..ec57587014d 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/amd/bin/outAndOutDirFile.js.map @@ -1 +1 @@ -{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file +{"version":3,"file":"outAndOutDirFile.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","ref/m2.ts","test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;ACRD,iCAAiC;AACjC,iCAAiC;AACjC,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map index a8c35bc15c6..59ebd34cfe3 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map index f1623c531a6..9afdf343f77 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map index b199c0dc1ad..5000f3a49b9 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map index ef338fcc887..866e1007e24 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/diskFile0.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map index 10777c25bd4..0f5e28ddbf7 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/test.js.map index dbab2cdf457..a39cd29ba77 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index f1623c531a6..9afdf343f77 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map index b199c0dc1ad..5000f3a49b9 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAEW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index a8c35bc15c6..59ebd34cfe3 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/amd/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map index 10777c25bd4..0f5e28ddbf7 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map index dbab2cdf457..a39cd29ba77 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,2DAA8D;AACnD,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;AACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map index ef338fcc887..866e1007e24 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputDirectory/node/outdir/simple/outputdir_module_multifolder_ref/m2.js.map @@ -1 +1 @@ -{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m2.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder_ref/m2.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map index 5a120cbe800..c4facdba936 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleMultifolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["outputdir_module_multifolder/ref/m1.ts","outputdir_module_multifolder_ref/m2.ts","outputdir_module_multifolder/test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICRU,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICNU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACd,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map index 26e7b01ccdb..1706ba76817 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/m1.js.map index 1b563cf259d..d134ab774af 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/test.js.map index 46e8000caa0..d07c1aa0678 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map index 26e7b01ccdb..1706ba76817 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map index 1b563cf259d..d134ab774af 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map index 46e8000caa0..d07c1aa0678 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,uBAA0B;AACf,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map index 28d5511a5ee..64c90d05e88 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSimpleSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map index 88ce97eeeff..7e2762b41a4 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/amd/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map index e28d378dfc0..eb883275568 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/test.js.map index c956b034f6f..4f024886c03 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderNoOutdir/node/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map index 88ce97eeeff..7e2762b41a4 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map index f92c491640f..07e9825a93a 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";;IACW,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map index e28d378dfc0..eb883275568 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js.map @@ -1 +1 @@ -{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFD,sBAEC;AAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file +{"version":3,"file":"m1.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts"],"names":[],"mappings":";AAAW,QAAA,KAAK,GAAG,EAAE,CAAC;AACtB;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAFY,sBAAK;AAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AACtC;IACI,MAAM,CAAC,oBAAY,CAAC;AACxB,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map index c956b034f6f..4f024886c03 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputDirectory/node/outdir/simple/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFD,gBAEC;AAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["test.ts"],"names":[],"mappings":";AAAA,2BAA8B;AACnB,QAAA,EAAE,GAAG,EAAE,CAAC;AACnB;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAFY,gBAAE;AAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AAChC;IACI,MAAM,CAAC,iBAAS,CAAC;AACrB,CAAC;AAFD,gBAEC;AAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map index a46d68e9b05..6d26d850e19 100644 --- a/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map +++ b/tests/baselines/reference/project/sourcerootUrlModuleSubfolderSpecifyOutputFile/amd/bin/test.js.map @@ -1 +1 @@ -{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFD,sBAEC;IAEU,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFD,gBAEC;IAEU,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file +{"version":3,"file":"test.js","sourceRoot":"http://typescript.codeplex.com/","sources":["ref/m1.ts","test.ts"],"names":[],"mappings":";;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC;;;;ICPU,QAAA,EAAE,GAAG,EAAE,CAAC;IACnB;QAAA;QAEA,CAAC;QAAD,SAAC;IAAD,CAAC,AAFD,IAEC;IAFY,gBAAE;IAIJ,QAAA,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;IAChC;QACI,MAAM,CAAC,iBAAS,CAAC;IACrB,CAAC;IAFD,gBAEC;IAEU,QAAA,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/promisePermutations.errors.txt b/tests/baselines/reference/promisePermutations.errors.txt index 65fa0981643..13fc0718596 100644 --- a/tests/baselines/reference/promisePermutations.errors.txt +++ b/tests/baselines/reference/promisePermutations.errors.txt @@ -25,8 +25,6 @@ tests/cases/compiler/promisePermutations.ts(106,19): error TS2345: Argument of t Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations.ts(109,19): error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. - Types of parameters 'cb' and 'value' are incompatible. - Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations.ts(110,19): error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. @@ -229,8 +227,6 @@ tests/cases/compiler/promisePermutations.ts(160,21): error TS2345: Argument of t var s7a = r7.then(testFunction7, testFunction7, testFunction7); // error ~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. -!!! error TS2345: Types of parameters 'cb' and 'value' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type '(a: T) => T'. var s7b = r7.then(testFunction7P, testFunction7P, testFunction7P); // error ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. diff --git a/tests/baselines/reference/promisePermutations2.errors.txt b/tests/baselines/reference/promisePermutations2.errors.txt index 0fc6f04911a..b21a3a39208 100644 --- a/tests/baselines/reference/promisePermutations2.errors.txt +++ b/tests/baselines/reference/promisePermutations2.errors.txt @@ -25,8 +25,6 @@ tests/cases/compiler/promisePermutations2.ts(105,19): error TS2345: Argument of Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations2.ts(108,19): error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. - Types of parameters 'cb' and 'value' are incompatible. - Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations2.ts(109,19): error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. @@ -228,8 +226,6 @@ tests/cases/compiler/promisePermutations2.ts(159,21): error TS2345: Argument of var s7a = r7.then(testFunction7, testFunction7, testFunction7); // error ~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. -!!! error TS2345: Types of parameters 'cb' and 'value' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type '(a: T) => T'. var s7b = r7.then(testFunction7P, testFunction7P, testFunction7P); // error ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. diff --git a/tests/baselines/reference/promisePermutations3.errors.txt b/tests/baselines/reference/promisePermutations3.errors.txt index a1a1b3f493f..1a33d1083aa 100644 --- a/tests/baselines/reference/promisePermutations3.errors.txt +++ b/tests/baselines/reference/promisePermutations3.errors.txt @@ -28,8 +28,6 @@ tests/cases/compiler/promisePermutations3.ts(105,19): error TS2345: Argument of Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations3.ts(108,19): error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. - Types of parameters 'cb' and 'value' are incompatible. - Type 'string' is not assignable to type '(a: T) => T'. tests/cases/compiler/promisePermutations3.ts(109,19): error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. Types of parameters 'cb' and 'value' are incompatible. Type 'string' is not assignable to type '(a: T) => T'. @@ -240,8 +238,6 @@ tests/cases/compiler/promisePermutations3.ts(165,21): error TS2345: Argument of var s7a = r7.then(testFunction7, testFunction7, testFunction7); // error ~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => IPromise' is not assignable to parameter of type '(value: string) => IPromise'. -!!! error TS2345: Types of parameters 'cb' and 'value' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type '(a: T) => T'. var s7b = r7.then(testFunction7P, testFunction7P, testFunction7P); // error ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(cb: (a: T) => T) => Promise' is not assignable to parameter of type '(value: string) => Promise'. diff --git a/tests/baselines/reference/promiseType.js b/tests/baselines/reference/promiseType.js index 9fbdb2ab2b6..4e42ea24073 100644 --- a/tests/baselines/reference/promiseType.js +++ b/tests/baselines/reference/promiseType.js @@ -161,7 +161,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const a = p.then(); diff --git a/tests/baselines/reference/promiseTypeStrictNull.js b/tests/baselines/reference/promiseTypeStrictNull.js index 8c5cef4c7c4..4aefeb3403e 100644 --- a/tests/baselines/reference/promiseTypeStrictNull.js +++ b/tests/baselines/reference/promiseTypeStrictNull.js @@ -161,7 +161,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const a = p.then(); diff --git a/tests/baselines/reference/propertyAccess.errors.txt b/tests/baselines/reference/propertyAccess.errors.txt index b3244956174..a183ad79c11 100644 --- a/tests/baselines/reference/propertyAccess.errors.txt +++ b/tests/baselines/reference/propertyAccess.errors.txt @@ -1,12 +1,13 @@ tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(11,55): error TS2322: Type '{ 3: string; 'three': string; }' is not assignable to type '{ [n: number]: string; }'. Object literal may only specify known properties, and ''three'' does not exist in type '{ [n: number]: string; }'. tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(45,14): error TS2339: Property 'qqq' does not exist on type '{ 10: string; x: string; y: number; z: { n: string; m: number; o: () => boolean; }; 'literal property': number; }'. -tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(80,10): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. -tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(117,10): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. -tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,12): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(80,19): error TS2538: Type '{ name: string; }' cannot be used as an index type. +tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(117,18): error TS2538: Type '{ name: string; }' cannot be used as an index type. +tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,22): error TS2538: Type '{ name: string; }' cannot be used as an index type. +tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(149,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'x3' must be of type 'A | B', but here has type 'A'. -==== tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts (5 errors) ==== +==== tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts (6 errors) ==== class A { a: number; } @@ -92,8 +93,8 @@ tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,12): er // Bracket notation property access using value of other type on type with numeric index signature and no string index signature var ll = numIndex[someObject]; // Error - ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~~ +!!! error TS2538: Type '{ name: string; }' cannot be used as an index type. // Bracket notation property access using string value on type with string index signature and no numeric index signature var mm = strIndex['N']; @@ -131,8 +132,8 @@ tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,12): er // Bracket notation property access using values of other types on type with no index signatures var uu = noIndex[someObject]; // Error - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~~ +!!! error TS2538: Type '{ name: string; }' cannot be used as an index type. // Bracket notation property access using numeric value on type with numeric index signature and string index signature var vv = noIndex[32]; @@ -156,8 +157,8 @@ tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,12): er // Bracket notation property access using value of other type on type with numeric index signature and no string index signature and string index signature var zzzz = bothIndex[someObject]; // Error - ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~~~~~~~~ +!!! error TS2538: Type '{ name: string; }' cannot be used as an index type. var x1 = numIndex[stringOrNumber]; var x1: any; @@ -167,4 +168,6 @@ tests/cases/conformance/expressions/propertyAccess/propertyAccess.ts(140,12): er var x3 = bothIndex[stringOrNumber]; var x3: A; + ~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'x3' must be of type 'A | B', but here has type 'A'. \ No newline at end of file diff --git a/tests/baselines/reference/protoAsIndexInIndexExpression.types b/tests/baselines/reference/protoAsIndexInIndexExpression.types index 6d1374d1f78..b761aa2c7a7 100644 --- a/tests/baselines/reference/protoAsIndexInIndexExpression.types +++ b/tests/baselines/reference/protoAsIndexInIndexExpression.types @@ -14,11 +14,11 @@ var WorkspacePrototype = { } }; WorkspacePrototype['__proto__'] = EntityPrototype; ->WorkspacePrototype['__proto__'] = EntityPrototype : undefined +>WorkspacePrototype['__proto__'] = EntityPrototype : any >WorkspacePrototype['__proto__'] : any >WorkspacePrototype : { serialize: () => any; } >'__proto__' : "___proto__" ->EntityPrototype : undefined +>EntityPrototype : any var o = { >o : { "__proto__": number; } diff --git a/tests/baselines/reference/prototypeOnConstructorFunctions.js b/tests/baselines/reference/prototypeOnConstructorFunctions.js index d2e5ddde925..de1fec1f7e8 100644 --- a/tests/baselines/reference/prototypeOnConstructorFunctions.js +++ b/tests/baselines/reference/prototypeOnConstructorFunctions.js @@ -12,4 +12,4 @@ i.const.prototype.prop = "yo"; //// [prototypeOnConstructorFunctions.js] var i; -i.const.prototype.prop = "yo"; +i["const"].prototype.prop = "yo"; diff --git a/tests/baselines/reference/reachabilityChecks7.js b/tests/baselines/reference/reachabilityChecks7.js index b8334f4276b..c17472205a4 100644 --- a/tests/baselines/reference/reachabilityChecks7.js +++ b/tests/baselines/reference/reachabilityChecks7.js @@ -36,7 +36,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // async function without return type annotation - error diff --git a/tests/baselines/reference/readonlyConstructorAssignment.errors.txt b/tests/baselines/reference/readonlyConstructorAssignment.errors.txt index e764fe21eda..31b4ad969cb 100644 --- a/tests/baselines/reference/readonlyConstructorAssignment.errors.txt +++ b/tests/baselines/reference/readonlyConstructorAssignment.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts(13,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts(13,14): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts(33,7): error TS2415: Class 'E' incorrectly extends base class 'D'. Property 'x' is private in type 'D' but not in type 'E'. @@ -17,8 +17,8 @@ tests/cases/conformance/classes/constructorDeclarations/constructorParameters/re super(x); // Fails, x is readonly this.x = 1; - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. } } diff --git a/tests/baselines/reference/readonlyInConstructorParameters.errors.txt b/tests/baselines/reference/readonlyInConstructorParameters.errors.txt index 6e4b549ce74..15d0d0be8eb 100644 --- a/tests/baselines/reference/readonlyInConstructorParameters.errors.txt +++ b/tests/baselines/reference/readonlyInConstructorParameters.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyInConstructorParameters.ts(4,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyInConstructorParameters.ts(4,10): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyInConstructorParameters.ts(7,26): error TS1029: 'public' modifier must precede 'readonly' modifier. tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyInConstructorParameters.ts(13,10): error TS2341: Property 'x' is private and only accessible within class 'F'. @@ -8,8 +8,8 @@ tests/cases/conformance/classes/constructorDeclarations/constructorParameters/re constructor(readonly x: number) {} } new C(1).x = 2; - ~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'x' because it is a constant or a read-only property. class E { constructor(readonly public x: number) {} diff --git a/tests/baselines/reference/readonlyMembers.errors.txt b/tests/baselines/reference/readonlyMembers.errors.txt index 7bc10aa3746..7a6b74359d1 100644 --- a/tests/baselines/reference/readonlyMembers.errors.txt +++ b/tests/baselines/reference/readonlyMembers.errors.txt @@ -1,18 +1,18 @@ -tests/cases/compiler/readonlyMembers.ts(7,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(8,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(17,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(19,13): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(20,13): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(21,13): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(25,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(26,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(27,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(36,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(40,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(49,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(56,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(62,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(7,3): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(8,3): error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(17,14): error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(19,18): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(20,18): error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(21,18): error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(25,14): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(26,14): error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(27,14): error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(36,3): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(40,3): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(49,3): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(56,3): error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. +tests/cases/compiler/readonlyMembers.ts(62,1): error TS2542: Index signature in type '{ readonly [x: string]: string; }' only permits reading. +tests/cases/compiler/readonlyMembers.ts(65,1): error TS2542: Index signature in type '{ [x: string]: string; readonly [x: number]: string; }' only permits reading. ==== tests/cases/compiler/readonlyMembers.ts (15 errors) ==== @@ -23,11 +23,11 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a } var x: X = { a: 0 }; x.a = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. x.b = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. class C { readonly a: number; @@ -37,30 +37,30 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a this.a = 1; // Ok this.b = 1; // Ok this.c = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. const f = () => { this.a = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. this.b = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. this.c = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. } } foo() { this.a = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. this.b = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'b' because it is a constant or a read-only property. this.c = 1; // Error - ~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'c' because it is a constant or a read-only property. } } @@ -70,14 +70,14 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a set b(value) { } }; o.a = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. o.b = 1; var p: { readonly a: number, b: number } = { a: 1, b: 1 }; p.a = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. p.b = 1; var q: { a: number, b: number } = p; q.a = 1; @@ -87,8 +87,8 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a A, B, C } E.A = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. namespace N { export const a = 1; @@ -96,8 +96,8 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a export var c = 1; } N.a = 1; // Error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'a' because it is a constant or a read-only property. N.b = 1; N.c = 1; @@ -105,10 +105,10 @@ tests/cases/compiler/readonlyMembers.ts(65,1): error TS2450: Left-hand side of a let s = xx["foo"]; xx["foo"] = "abc"; // Error ~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2542: Index signature in type '{ readonly [x: string]: string; }' only permits reading. let yy: { readonly [x: number]: string, [x: string]: string }; yy[1] = "abc"; // Error ~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +!!! error TS2542: Index signature in type '{ [x: string]: string; readonly [x: number]: string; }' only permits reading. yy["foo"] = "abc"; \ No newline at end of file diff --git a/tests/baselines/reference/recursiveLetConst.errors.txt b/tests/baselines/reference/recursiveLetConst.errors.txt index 6d3f15880bb..88ecb379e5e 100644 --- a/tests/baselines/reference/recursiveLetConst.errors.txt +++ b/tests/baselines/reference/recursiveLetConst.errors.txt @@ -5,14 +5,13 @@ tests/cases/compiler/recursiveLetConst.ts(5,14): error TS2448: Block-scoped vari tests/cases/compiler/recursiveLetConst.ts(6,14): error TS2448: Block-scoped variable 'v' used before its declaration. tests/cases/compiler/recursiveLetConst.ts(7,1): error TS7027: Unreachable code detected. tests/cases/compiler/recursiveLetConst.ts(7,16): error TS2448: Block-scoped variable 'v' used before its declaration. -tests/cases/compiler/recursiveLetConst.ts(8,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/compiler/recursiveLetConst.ts(8,15): error TS2448: Block-scoped variable 'v' used before its declaration. tests/cases/compiler/recursiveLetConst.ts(9,15): error TS2448: Block-scoped variable 'v' used before its declaration. tests/cases/compiler/recursiveLetConst.ts(10,17): error TS2448: Block-scoped variable 'v' used before its declaration. tests/cases/compiler/recursiveLetConst.ts(11,11): error TS2448: Block-scoped variable 'x2' used before its declaration. -==== tests/cases/compiler/recursiveLetConst.ts (12 errors) ==== +==== tests/cases/compiler/recursiveLetConst.ts (11 errors) ==== 'use strict' let x = x + 1; ~ @@ -36,8 +35,6 @@ tests/cases/compiler/recursiveLetConst.ts(11,11): error TS2448: Block-scoped var !!! error TS2448: Block-scoped variable 'v' used before its declaration. for (let v in v) { } ~ -!!! error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. - ~ !!! error TS2448: Block-scoped variable 'v' used before its declaration. for (let v of v) { } ~ diff --git a/tests/baselines/reference/recursiveMappedTypes.errors.txt b/tests/baselines/reference/recursiveMappedTypes.errors.txt new file mode 100644 index 00000000000..3dd6a55cf8c --- /dev/null +++ b/tests/baselines/reference/recursiveMappedTypes.errors.txt @@ -0,0 +1,26 @@ +tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(4,6): error TS2456: Type alias 'Recurse' circularly references itself. +tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(8,6): error TS2456: Type alias 'Recurse1' circularly references itself. +tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(12,6): error TS2456: Type alias 'Recurse2' circularly references itself. + + +==== tests/cases/conformance/types/mapped/recursiveMappedTypes.ts (3 errors) ==== + + // Recursive mapped types simply appear empty + + type Recurse = { + ~~~~~~~ +!!! error TS2456: Type alias 'Recurse' circularly references itself. + [K in keyof Recurse]: Recurse[K] + } + + type Recurse1 = { + ~~~~~~~~ +!!! error TS2456: Type alias 'Recurse1' circularly references itself. + [K in keyof Recurse2]: Recurse2[K] + } + + type Recurse2 = { + ~~~~~~~~ +!!! error TS2456: Type alias 'Recurse2' circularly references itself. + [K in keyof Recurse1]: Recurse1[K] + } \ No newline at end of file diff --git a/tests/baselines/reference/recursiveMappedTypes.js b/tests/baselines/reference/recursiveMappedTypes.js new file mode 100644 index 00000000000..dfe69457ed7 --- /dev/null +++ b/tests/baselines/reference/recursiveMappedTypes.js @@ -0,0 +1,30 @@ +//// [recursiveMappedTypes.ts] + +// Recursive mapped types simply appear empty + +type Recurse = { + [K in keyof Recurse]: Recurse[K] +} + +type Recurse1 = { + [K in keyof Recurse2]: Recurse2[K] +} + +type Recurse2 = { + [K in keyof Recurse1]: Recurse1[K] +} + +//// [recursiveMappedTypes.js] +// Recursive mapped types simply appear empty + + +//// [recursiveMappedTypes.d.ts] +declare type Recurse = { + [K in keyof Recurse]: Recurse[K]; +}; +declare type Recurse1 = { + [K in keyof Recurse2]: Recurse2[K]; +}; +declare type Recurse2 = { + [K in keyof Recurse1]: Recurse1[K]; +}; diff --git a/tests/baselines/reference/recursiveMappedTypes.symbols b/tests/baselines/reference/recursiveMappedTypes.symbols new file mode 100644 index 00000000000..ae4ca8d9cc9 --- /dev/null +++ b/tests/baselines/reference/recursiveMappedTypes.symbols @@ -0,0 +1,33 @@ +=== tests/cases/conformance/types/mapped/recursiveMappedTypes.ts === + +// Recursive mapped types simply appear empty + +type Recurse = { +>Recurse : Symbol(Recurse, Decl(recursiveMappedTypes.ts, 0, 0)) + + [K in keyof Recurse]: Recurse[K] +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 4, 5)) +>Recurse : Symbol(Recurse, Decl(recursiveMappedTypes.ts, 0, 0)) +>Recurse : Symbol(Recurse, Decl(recursiveMappedTypes.ts, 0, 0)) +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 4, 5)) +} + +type Recurse1 = { +>Recurse1 : Symbol(Recurse1, Decl(recursiveMappedTypes.ts, 5, 1)) + + [K in keyof Recurse2]: Recurse2[K] +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 8, 5)) +>Recurse2 : Symbol(Recurse2, Decl(recursiveMappedTypes.ts, 9, 1)) +>Recurse2 : Symbol(Recurse2, Decl(recursiveMappedTypes.ts, 9, 1)) +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 8, 5)) +} + +type Recurse2 = { +>Recurse2 : Symbol(Recurse2, Decl(recursiveMappedTypes.ts, 9, 1)) + + [K in keyof Recurse1]: Recurse1[K] +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 12, 5)) +>Recurse1 : Symbol(Recurse1, Decl(recursiveMappedTypes.ts, 5, 1)) +>Recurse1 : Symbol(Recurse1, Decl(recursiveMappedTypes.ts, 5, 1)) +>K : Symbol(K, Decl(recursiveMappedTypes.ts, 12, 5)) +} diff --git a/tests/baselines/reference/recursiveMappedTypes.types b/tests/baselines/reference/recursiveMappedTypes.types new file mode 100644 index 00000000000..2c60bc8b68a --- /dev/null +++ b/tests/baselines/reference/recursiveMappedTypes.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/types/mapped/recursiveMappedTypes.ts === + +// Recursive mapped types simply appear empty + +type Recurse = { +>Recurse : Recurse + + [K in keyof Recurse]: Recurse[K] +>K : K +>Recurse : Recurse +>Recurse : Recurse +>K : K +} + +type Recurse1 = { +>Recurse1 : Recurse1 + + [K in keyof Recurse2]: Recurse2[K] +>K : K +>Recurse2 : Recurse2 +>Recurse2 : Recurse2 +>K : K +} + +type Recurse2 = { +>Recurse2 : Recurse2 + + [K in keyof Recurse1]: Recurse1[K] +>K : K +>Recurse1 : Recurse1 +>Recurse1 : Recurse1 +>K : K +} diff --git a/tests/baselines/reference/redeclareParameterInCatchBlock.errors.txt b/tests/baselines/reference/redeclareParameterInCatchBlock.errors.txt index bd307bb89ae..9fd4c63f02f 100644 --- a/tests/baselines/reference/redeclareParameterInCatchBlock.errors.txt +++ b/tests/baselines/reference/redeclareParameterInCatchBlock.errors.txt @@ -1,8 +1,11 @@ tests/cases/compiler/redeclareParameterInCatchBlock.ts(5,11): error TS2492: Cannot redeclare identifier 'e' in catch clause tests/cases/compiler/redeclareParameterInCatchBlock.ts(11,9): error TS2492: Cannot redeclare identifier 'e' in catch clause +tests/cases/compiler/redeclareParameterInCatchBlock.ts(17,15): error TS2492: Cannot redeclare identifier 'b' in catch clause +tests/cases/compiler/redeclareParameterInCatchBlock.ts(22,15): error TS2451: Cannot redeclare block-scoped variable 'x'. +tests/cases/compiler/redeclareParameterInCatchBlock.ts(22,21): error TS2451: Cannot redeclare block-scoped variable 'x'. -==== tests/cases/compiler/redeclareParameterInCatchBlock.ts (2 errors) ==== +==== tests/cases/compiler/redeclareParameterInCatchBlock.ts (5 errors) ==== try { @@ -22,10 +25,27 @@ tests/cases/compiler/redeclareParameterInCatchBlock.ts(11,9): error TS2492: Cann try { + } catch ([a, b]) { + const [c, b] = [0, 1]; + ~ +!!! error TS2492: Cannot redeclare identifier 'b' in catch clause + } + + try { + + } catch ({ a: x, b: x }) { + ~ +!!! error TS2451: Cannot redeclare block-scoped variable 'x'. + ~ +!!! error TS2451: Cannot redeclare block-scoped variable 'x'. + + } + + try { + } catch(e) { function test() { let e; } } - \ No newline at end of file diff --git a/tests/baselines/reference/redeclareParameterInCatchBlock.js b/tests/baselines/reference/redeclareParameterInCatchBlock.js index 704d56676bf..9fafe0b17be 100644 --- a/tests/baselines/reference/redeclareParameterInCatchBlock.js +++ b/tests/baselines/reference/redeclareParameterInCatchBlock.js @@ -14,12 +14,23 @@ try { try { +} catch ([a, b]) { + const [c, b] = [0, 1]; +} + +try { + +} catch ({ a: x, b: x }) { + +} + +try { + } catch(e) { function test() { let e; } } - //// [redeclareParameterInCatchBlock.js] @@ -35,6 +46,15 @@ catch (e) { } try { } +catch ([a, b]) { + const [c, b] = [0, 1]; +} +try { +} +catch ({ a: x, b: x }) { +} +try { +} catch (e) { function test() { let e; diff --git a/tests/baselines/reference/redefineArray.errors.txt b/tests/baselines/reference/redefineArray.errors.txt index 82ef91807c2..6a9cf954798 100644 --- a/tests/baselines/reference/redefineArray.errors.txt +++ b/tests/baselines/reference/redefineArray.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/redefineArray.ts(1,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/compiler/redefineArray.ts(1,1): error TS2540: Cannot assign to 'Array' because it is a constant or a read-only property. ==== tests/cases/compiler/redefineArray.ts (1 errors) ==== Array = function (n:number, s:string) {return n;}; ~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. \ No newline at end of file +!!! error TS2540: Cannot assign to 'Array' because it is a constant or a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/relationalOperatorComparable.errors.txt b/tests/baselines/reference/relationalOperatorComparable.errors.txt new file mode 100644 index 00000000000..bc48eaf92c0 --- /dev/null +++ b/tests/baselines/reference/relationalOperatorComparable.errors.txt @@ -0,0 +1,40 @@ +tests/cases/compiler/relationalOperatorComparable.ts(5,14): error TS2365: Operator '<' cannot be applied to types 'number' and 'boolean'. +tests/cases/compiler/relationalOperatorComparable.ts(6,14): error TS2365: Operator '<=' cannot be applied to types 'number' and 'boolean'. +tests/cases/compiler/relationalOperatorComparable.ts(7,14): error TS2365: Operator '>=' cannot be applied to types 'number' and 'boolean'. +tests/cases/compiler/relationalOperatorComparable.ts(8,14): error TS2365: Operator '>' cannot be applied to types 'number' and 'boolean'. +tests/cases/compiler/relationalOperatorComparable.ts(9,14): error TS2365: Operator '<' cannot be applied to types 'boolean' and 'number'. +tests/cases/compiler/relationalOperatorComparable.ts(10,14): error TS2365: Operator '<' cannot be applied to types 'boolean' and 'number'. +tests/cases/compiler/relationalOperatorComparable.ts(11,14): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. + + +==== tests/cases/compiler/relationalOperatorComparable.ts (7 errors) ==== + function f(onethree: 1 | 3, two: 2) { + const t = true; + const f = false; + let a1 = onethree < two; // ok + let a2 = onethree < true; // error, number and boolean + ~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '<' cannot be applied to types 'number' and 'boolean'. + let a3 = onethree <= false; // error, number and boolean + ~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '<=' cannot be applied to types 'number' and 'boolean'. + let a4 = onethree >= t; // error, number and boolean + ~~~~~~~~~~~~~ +!!! error TS2365: Operator '>=' cannot be applied to types 'number' and 'boolean'. + let a5 = onethree > f; // error, number and boolean + ~~~~~~~~~~~~ +!!! error TS2365: Operator '>' cannot be applied to types 'number' and 'boolean'. + let a6 = true < onethree; // error, boolean and number + ~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '<' cannot be applied to types 'boolean' and 'number'. + let a7 = false < two; // error, boolean and number + ~~~~~~~~~~~ +!!! error TS2365: Operator '<' cannot be applied to types 'boolean' and 'number'. + let a8 = 'foo' < onethree; // error, string and number + ~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. + let a9 = onethree < 1; // ok + let a10 = 1 < two; // ok + let a11 = 2 < 1; // ok + } + \ No newline at end of file diff --git a/tests/baselines/reference/relationalOperatorComparable.js b/tests/baselines/reference/relationalOperatorComparable.js new file mode 100644 index 00000000000..019c257fe7d --- /dev/null +++ b/tests/baselines/reference/relationalOperatorComparable.js @@ -0,0 +1,34 @@ +//// [relationalOperatorComparable.ts] +function f(onethree: 1 | 3, two: 2) { + const t = true; + const f = false; + let a1 = onethree < two; // ok + let a2 = onethree < true; // error, number and boolean + let a3 = onethree <= false; // error, number and boolean + let a4 = onethree >= t; // error, number and boolean + let a5 = onethree > f; // error, number and boolean + let a6 = true < onethree; // error, boolean and number + let a7 = false < two; // error, boolean and number + let a8 = 'foo' < onethree; // error, string and number + let a9 = onethree < 1; // ok + let a10 = 1 < two; // ok + let a11 = 2 < 1; // ok +} + + +//// [relationalOperatorComparable.js] +function f(onethree, two) { + var t = true; + var f = false; + var a1 = onethree < two; // ok + var a2 = onethree < true; // error, number and boolean + var a3 = onethree <= false; // error, number and boolean + var a4 = onethree >= t; // error, number and boolean + var a5 = onethree > f; // error, number and boolean + var a6 = true < onethree; // error, boolean and number + var a7 = false < two; // error, boolean and number + var a8 = 'foo' < onethree; // error, string and number + var a9 = onethree < 1; // ok + var a10 = 1 < two; // ok + var a11 = 2 < 1; // ok +} diff --git a/tests/baselines/reference/requireAsFunctionInExternalModule.js b/tests/baselines/reference/requireAsFunctionInExternalModule.js new file mode 100644 index 00000000000..a8b14db3138 --- /dev/null +++ b/tests/baselines/reference/requireAsFunctionInExternalModule.js @@ -0,0 +1,37 @@ +//// [tests/cases/compiler/requireAsFunctionInExternalModule.ts] //// + +//// [c.js] +export default function require(a) { } +export function has(a) { return true } + +//// [m.js] +import require, { has } from "./c" +export function hello() { } +if (has('ember-debug')) { + require('ember-debug'); +} + +//// [m2.ts] +import { hello } from "./m"; +hello(); + + +//// [c.js] +"use strict"; +function require(a) { } +exports.__esModule = true; +exports["default"] = require; +function has(a) { return true; } +exports.has = has; +//// [m.js] +"use strict"; +var c_1 = require("./c"); +function hello() { } +exports.hello = hello; +if (c_1.has('ember-debug')) { + c_1["default"]('ember-debug'); +} +//// [m2.js] +"use strict"; +var m_1 = require("./m"); +m_1.hello(); diff --git a/tests/baselines/reference/requireAsFunctionInExternalModule.symbols b/tests/baselines/reference/requireAsFunctionInExternalModule.symbols new file mode 100644 index 00000000000..2f44d6b6611 --- /dev/null +++ b/tests/baselines/reference/requireAsFunctionInExternalModule.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/c.js === +export default function require(a) { } +>require : Symbol(require, Decl(c.js, 0, 0)) +>a : Symbol(a, Decl(c.js, 0, 32)) + +export function has(a) { return true } +>has : Symbol(has, Decl(c.js, 0, 38)) +>a : Symbol(a, Decl(c.js, 1, 20)) + +=== tests/cases/compiler/m.js === +import require, { has } from "./c" +>require : Symbol(require, Decl(m.js, 0, 6)) +>has : Symbol(has, Decl(m.js, 0, 17)) + +export function hello() { } +>hello : Symbol(hello, Decl(m.js, 0, 34)) + +if (has('ember-debug')) { +>has : Symbol(has, Decl(m.js, 0, 17)) + + require('ember-debug'); +>require : Symbol(require, Decl(m.js, 0, 6)) +} + +=== tests/cases/compiler/m2.ts === +import { hello } from "./m"; +>hello : Symbol(hello, Decl(m2.ts, 0, 8)) + +hello(); +>hello : Symbol(hello, Decl(m2.ts, 0, 8)) + diff --git a/tests/baselines/reference/requireAsFunctionInExternalModule.types b/tests/baselines/reference/requireAsFunctionInExternalModule.types new file mode 100644 index 00000000000..2ce5f3aed38 --- /dev/null +++ b/tests/baselines/reference/requireAsFunctionInExternalModule.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/c.js === +export default function require(a) { } +>require : (a: any) => void +>a : any + +export function has(a) { return true } +>has : (a: any) => boolean +>a : any +>true : true + +=== tests/cases/compiler/m.js === +import require, { has } from "./c" +>require : (a: any) => void +>has : (a: any) => boolean + +export function hello() { } +>hello : () => void + +if (has('ember-debug')) { +>has('ember-debug') : boolean +>has : (a: any) => boolean +>'ember-debug' : "ember-debug" + + require('ember-debug'); +>require('ember-debug') : void +>require : (a: any) => void +>'ember-debug' : "ember-debug" +} + +=== tests/cases/compiler/m2.ts === +import { hello } from "./m"; +>hello : () => void + +hello(); +>hello() : void +>hello : () => void + diff --git a/tests/baselines/reference/reservedWords.js b/tests/baselines/reference/reservedWords.js index 12fbcae0c65..3424c054181 100644 --- a/tests/baselines/reference/reservedWords.js +++ b/tests/baselines/reference/reservedWords.js @@ -19,16 +19,16 @@ var obj2 = { //// [reservedWords.js] var obj = { - if: 0, - debugger: 2, - break: 3, - function: 4 + "if": 0, + "debugger": 2, + "break": 3, + "function": 4 }; //This compiles. var obj2 = { - if: 0, - while: 1, - debugger: 2, - break: 3, - function: 4 + "if": 0, + "while": 1, + "debugger": 2, + "break": 3, + "function": 4 }; diff --git a/tests/baselines/reference/reservedWords2.js b/tests/baselines/reference/reservedWords2.js index a79a0564c78..d9c8105c35f 100644 --- a/tests/baselines/reference/reservedWords2.js +++ b/tests/baselines/reference/reservedWords2.js @@ -27,8 +27,8 @@ function () { } throw function () { }; module; void {}; -var _a = { while: 1, return: 2 }, = _a.while, = _a.return; -var _b = { this: 1, switch: { continue: 2 } }, = _b.this, = _b.switch.continue; +var _a = { "while": 1, "return": 2 }, = _a["while"], = _a["return"]; +var _b = { "this": 1, "switch": { "continue": 2 } }, = _b["this"], = _b["switch"]["continue"]; var _c = void 0; debugger; if () diff --git a/tests/baselines/reference/restArgAssignmentCompat.js b/tests/baselines/reference/restArgAssignmentCompat.js index 3f8749f332d..b679f56a881 100644 --- a/tests/baselines/reference/restArgAssignmentCompat.js +++ b/tests/baselines/reference/restArgAssignmentCompat.js @@ -13,7 +13,7 @@ n([4], 'foo'); function f() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } x.forEach(function (n, i) { return void ('item ' + i + ' = ' + n); }); } diff --git a/tests/baselines/reference/restArgMissingName.js b/tests/baselines/reference/restArgMissingName.js index b87800c7dac..f4ec647f7e4 100644 --- a/tests/baselines/reference/restArgMissingName.js +++ b/tests/baselines/reference/restArgMissingName.js @@ -6,6 +6,6 @@ function sum (...) {} function sum() { var = []; for (var _i = 0; _i < arguments.length; _i++) { - [_i - 0] = arguments[_i]; + [_i] = arguments[_i]; } } diff --git a/tests/baselines/reference/restElementMustBeLast.errors.txt b/tests/baselines/reference/restElementMustBeLast.errors.txt index 269d984bc00..5eb5a4cd208 100644 --- a/tests/baselines/reference/restElementMustBeLast.errors.txt +++ b/tests/baselines/reference/restElementMustBeLast.errors.txt @@ -1,12 +1,12 @@ -tests/cases/conformance/es6/destructuring/restElementMustBeLast.ts(1,9): error TS2462: A rest element must be last in an array destructuring pattern -tests/cases/conformance/es6/destructuring/restElementMustBeLast.ts(2,2): error TS2462: A rest element must be last in an array destructuring pattern +tests/cases/conformance/types/rest/restElementMustBeLast.ts(1,9): error TS2462: A rest element must be last in a destructuring pattern +tests/cases/conformance/types/rest/restElementMustBeLast.ts(2,2): error TS2462: A rest element must be last in a destructuring pattern -==== tests/cases/conformance/es6/destructuring/restElementMustBeLast.ts (2 errors) ==== +==== tests/cases/conformance/types/rest/restElementMustBeLast.ts (2 errors) ==== var [...a, x] = [1, 2, 3]; // Error, rest must be last element ~ -!!! error TS2462: A rest element must be last in an array destructuring pattern +!!! error TS2462: A rest element must be last in a destructuring pattern [...a, x] = [1, 2, 3]; // Error, rest must be last element ~~~~ -!!! error TS2462: A rest element must be last in an array destructuring pattern +!!! error TS2462: A rest element must be last in a destructuring pattern \ No newline at end of file diff --git a/tests/baselines/reference/restIntersection.js b/tests/baselines/reference/restIntersection.js new file mode 100644 index 00000000000..d1f9aa3094c --- /dev/null +++ b/tests/baselines/reference/restIntersection.js @@ -0,0 +1,20 @@ +//// [restIntersection.ts] +var intersection: { x: number, y: number } & { w: string, z: string }; + +var rest1: { y: number, w: string, z: string }; +var {x, ...rest1 } = intersection; + + +//// [restIntersection.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var intersection; +var rest1; +var x = intersection.x, rest1 = __rest(intersection, ["x"]); diff --git a/tests/baselines/reference/restIntersection.symbols b/tests/baselines/reference/restIntersection.symbols new file mode 100644 index 00000000000..75f91d243e2 --- /dev/null +++ b/tests/baselines/reference/restIntersection.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/restIntersection.ts === +var intersection: { x: number, y: number } & { w: string, z: string }; +>intersection : Symbol(intersection, Decl(restIntersection.ts, 0, 3)) +>x : Symbol(x, Decl(restIntersection.ts, 0, 19)) +>y : Symbol(y, Decl(restIntersection.ts, 0, 30)) +>w : Symbol(w, Decl(restIntersection.ts, 0, 46)) +>z : Symbol(z, Decl(restIntersection.ts, 0, 57)) + +var rest1: { y: number, w: string, z: string }; +>rest1 : Symbol(rest1, Decl(restIntersection.ts, 2, 3), Decl(restIntersection.ts, 3, 7)) +>y : Symbol(y, Decl(restIntersection.ts, 2, 12)) +>w : Symbol(w, Decl(restIntersection.ts, 2, 23)) +>z : Symbol(z, Decl(restIntersection.ts, 2, 34)) + +var {x, ...rest1 } = intersection; +>x : Symbol(x, Decl(restIntersection.ts, 3, 5)) +>rest1 : Symbol(rest1, Decl(restIntersection.ts, 2, 3), Decl(restIntersection.ts, 3, 7)) +>intersection : Symbol(intersection, Decl(restIntersection.ts, 0, 3)) + diff --git a/tests/baselines/reference/restIntersection.types b/tests/baselines/reference/restIntersection.types new file mode 100644 index 00000000000..5779349ba29 --- /dev/null +++ b/tests/baselines/reference/restIntersection.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/restIntersection.ts === +var intersection: { x: number, y: number } & { w: string, z: string }; +>intersection : { x: number; y: number; } & { w: string; z: string; } +>x : number +>y : number +>w : string +>z : string + +var rest1: { y: number, w: string, z: string }; +>rest1 : { y: number; w: string; z: string; } +>y : number +>w : string +>z : string + +var {x, ...rest1 } = intersection; +>x : number +>rest1 : { y: number; w: string; z: string; } +>intersection : { x: number; y: number; } & { w: string; z: string; } + diff --git a/tests/baselines/reference/restInvalidArgumentType.errors.txt b/tests/baselines/reference/restInvalidArgumentType.errors.txt new file mode 100644 index 00000000000..fff2c7b3563 --- /dev/null +++ b/tests/baselines/reference/restInvalidArgumentType.errors.txt @@ -0,0 +1,104 @@ +tests/cases/compiler/restInvalidArgumentType.ts(31,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(33,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(35,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(36,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(38,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(41,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(42,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(44,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(45,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(47,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(48,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(55,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(56,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(58,13): error TS2700: Rest types may only be created from object types. + + +==== tests/cases/compiler/restInvalidArgumentType.ts (14 errors) ==== + enum E { v1, v2 }; + + function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var {...r1} = p1; // Error, generic type paramterre + ~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r2} = p2; // OK + var {...r3} = t; // Error, generic type paramter + ~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r4} = i; // Error, index access + ~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r5} = k; // Error, index + ~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r6} = mapped_generic; // Error, generic mapped object type + ~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r7} = mapped; // OK, non-generic mapped type + + var {...r8} = union_generic; // Error, union with generic type parameter + ~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r9} = union_primitive; // Error, union with generic type parameter + ~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r10} = intersection_generic; // Error, intersection with generic type parameter + ~~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r11} = intersection_premitive; // Error, intersection with generic type parameter + ~~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r12} = num; // Error + ~~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r13} = str; // Error + ~~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r14} = u; // OK + var {...r15} = n; // OK + + var {...r16} = a; // OK + + var {...r17} = literal_string; // Error + ~~~ +!!! error TS2700: Rest types may only be created from object types. + var {...r18} = literal_number; // Error + ~~~ +!!! error TS2700: Rest types may only be created from object types. + + var {...r19} = e; // Error, enum + ~~~ +!!! error TS2700: Rest types may only be created from object types. + } \ No newline at end of file diff --git a/tests/baselines/reference/restInvalidArgumentType.js b/tests/baselines/reference/restInvalidArgumentType.js new file mode 100644 index 00000000000..48e4e11e805 --- /dev/null +++ b/tests/baselines/reference/restInvalidArgumentType.js @@ -0,0 +1,115 @@ +//// [restInvalidArgumentType.ts] +enum E { v1, v2 }; + +function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var {...r1} = p1; // Error, generic type paramterre + var {...r2} = p2; // OK + var {...r3} = t; // Error, generic type paramter + + var {...r4} = i; // Error, index access + var {...r5} = k; // Error, index + + var {...r6} = mapped_generic; // Error, generic mapped object type + var {...r7} = mapped; // OK, non-generic mapped type + + var {...r8} = union_generic; // Error, union with generic type parameter + var {...r9} = union_primitive; // Error, union with generic type parameter + + var {...r10} = intersection_generic; // Error, intersection with generic type parameter + var {...r11} = intersection_premitive; // Error, intersection with generic type parameter + + var {...r12} = num; // Error + var {...r13} = str; // Error + + var {...r14} = u; // OK + var {...r15} = n; // OK + + var {...r16} = a; // OK + + var {...r17} = literal_string; // Error + var {...r18} = literal_number; // Error + + var {...r19} = e; // Error, enum +} + +//// [restInvalidArgumentType.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var E; +(function (E) { + E[E["v1"] = 0] = "v1"; + E[E["v2"] = 1] = "v2"; +})(E || (E = {})); +; +function f(p1, p2) { + var t; + var i; + var k; + var mapped_generic; + var mapped; + var union_generic; + var union_primitive; + var intersection_generic; + var intersection_premitive; + var num; + var str; + var u; + var n; + var a; + var literal_string; + var literal_number; + var e; + var r1 = __rest(p1, []); // Error, generic type paramterre + var r2 = __rest(p2, []); // OK + var r3 = __rest(t, []); // Error, generic type paramter + var r4 = __rest(i, []); // Error, index access + var r5 = __rest(k, []); // Error, index + var r6 = __rest(mapped_generic, []); // Error, generic mapped object type + var r7 = __rest(mapped, []); // OK, non-generic mapped type + var r8 = __rest(union_generic, []); // Error, union with generic type parameter + var r9 = __rest(union_primitive, []); // Error, union with generic type parameter + var r10 = __rest(intersection_generic, []); // Error, intersection with generic type parameter + var r11 = __rest(intersection_premitive, []); // Error, intersection with generic type parameter + var r12 = __rest(num, []); // Error + var r13 = __rest(str, []); // Error + var r14 = __rest(u, []); // OK + var r15 = __rest(n, []); // OK + var r16 = __rest(a, []); // OK + var r17 = __rest(literal_string, []); // Error + var r18 = __rest(literal_number, []); // Error + var r19 = __rest(e, []); // Error, enum +} diff --git a/tests/baselines/reference/restParamAsOptional.js b/tests/baselines/reference/restParamAsOptional.js index eb224b84c33..2f6da684c0e 100644 --- a/tests/baselines/reference/restParamAsOptional.js +++ b/tests/baselines/reference/restParamAsOptional.js @@ -6,12 +6,12 @@ function f2(...x = []) { } function f() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } function f2() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } diff --git a/tests/baselines/reference/restParamModifier2.js b/tests/baselines/reference/restParamModifier2.js index a11b78a2376..e98aef3f9ad 100644 --- a/tests/baselines/reference/restParamModifier2.js +++ b/tests/baselines/reference/restParamModifier2.js @@ -8,7 +8,7 @@ var C = (function () { function C() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } this.rest = rest; } diff --git a/tests/baselines/reference/restParameterAssignmentCompatibility.js b/tests/baselines/reference/restParameterAssignmentCompatibility.js index 0821cf18277..01472c78c1e 100644 --- a/tests/baselines/reference/restParameterAssignmentCompatibility.js +++ b/tests/baselines/reference/restParameterAssignmentCompatibility.js @@ -33,7 +33,7 @@ var T = (function () { T.prototype.m = function () { var p3 = []; for (var _i = 0; _i < arguments.length; _i++) { - p3[_i - 0] = arguments[_i]; + p3[_i] = arguments[_i]; } }; return T; diff --git a/tests/baselines/reference/restParameterNoTypeAnnotation.js b/tests/baselines/reference/restParameterNoTypeAnnotation.js index 95e092fdd43..b22b531675d 100644 --- a/tests/baselines/reference/restParameterNoTypeAnnotation.js +++ b/tests/baselines/reference/restParameterNoTypeAnnotation.js @@ -9,7 +9,7 @@ function foo(...rest) { function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } var x = rest[0]; return x; diff --git a/tests/baselines/reference/restParameterWithoutAnnotationIsAnyArray.js b/tests/baselines/reference/restParameterWithoutAnnotationIsAnyArray.js index c6b5fa2ae41..5c1db2c62e1 100644 --- a/tests/baselines/reference/restParameterWithoutAnnotationIsAnyArray.js +++ b/tests/baselines/reference/restParameterWithoutAnnotationIsAnyArray.js @@ -31,13 +31,13 @@ var b = { function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f2 = function () { @@ -52,7 +52,7 @@ var C = (function () { C.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C; @@ -62,7 +62,7 @@ var b = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -74,7 +74,7 @@ var b = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; diff --git a/tests/baselines/reference/restParametersOfNonArrayTypes.js b/tests/baselines/reference/restParametersOfNonArrayTypes.js index 5400a8b43cc..67145167720 100644 --- a/tests/baselines/reference/restParametersOfNonArrayTypes.js +++ b/tests/baselines/reference/restParametersOfNonArrayTypes.js @@ -30,13 +30,13 @@ var b = { function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f2 = function () { @@ -51,7 +51,7 @@ var C = (function () { C.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C; @@ -61,7 +61,7 @@ var b = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -73,7 +73,7 @@ var b = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; diff --git a/tests/baselines/reference/restParametersOfNonArrayTypes2.js b/tests/baselines/reference/restParametersOfNonArrayTypes2.js index d405c13db5a..7df2458a27b 100644 --- a/tests/baselines/reference/restParametersOfNonArrayTypes2.js +++ b/tests/baselines/reference/restParametersOfNonArrayTypes2.js @@ -62,13 +62,13 @@ var b2 = { function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f2 = function () { @@ -83,7 +83,7 @@ var C = (function () { C.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C; @@ -93,7 +93,7 @@ var b = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -105,20 +105,20 @@ var b = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; function foo2() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f3 = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f4 = function () { @@ -133,7 +133,7 @@ var C2 = (function () { C2.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C2; @@ -143,7 +143,7 @@ var b2 = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -155,7 +155,7 @@ var b2 = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; diff --git a/tests/baselines/reference/restParametersWithArrayTypeAnnotations.js b/tests/baselines/reference/restParametersWithArrayTypeAnnotations.js index 3f1cf33e7ba..1004fdfcbcb 100644 --- a/tests/baselines/reference/restParametersWithArrayTypeAnnotations.js +++ b/tests/baselines/reference/restParametersWithArrayTypeAnnotations.js @@ -57,13 +57,13 @@ var b2 = { function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f2 = function () { @@ -78,7 +78,7 @@ var C = (function () { C.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C; @@ -88,7 +88,7 @@ var b = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -100,20 +100,20 @@ var b = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; function foo2() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } var f3 = function foo() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; var f4 = function () { @@ -128,7 +128,7 @@ var C2 = (function () { C2.prototype.foo = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }; return C2; @@ -138,7 +138,7 @@ var b2 = { foo: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } }, a: function foo() { @@ -150,7 +150,7 @@ var b2 = { b: function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } }; diff --git a/tests/baselines/reference/restParamsWithNonRestParams.js b/tests/baselines/reference/restParamsWithNonRestParams.js index 6b0caa72394..7b16959143a 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.js +++ b/tests/baselines/reference/restParamsWithNonRestParams.js @@ -10,7 +10,7 @@ foo3(); // error but shouldn't be function foo() { var b = []; for (var _i = 0; _i < arguments.length; _i++) { - b[_i - 0] = arguments[_i]; + b[_i] = arguments[_i]; } } foo(); // ok diff --git a/tests/baselines/reference/restUnion.js b/tests/baselines/reference/restUnion.js new file mode 100644 index 00000000000..09a6243d2a9 --- /dev/null +++ b/tests/baselines/reference/restUnion.js @@ -0,0 +1,36 @@ +//// [restUnion.ts] +var union: { a: number, c: boolean } | { a: string, b: string }; + +var rest1: { c: boolean } | { b: string }; +var {a, ...rest1 } = union; + + +var undefinedUnion: { n: number } | undefined; +var rest2: {}; +var {n, ...rest2 } = undefinedUnion; + + +var nullUnion: { n: number } | null; +var rest3: {}; +var {n, ...rest3 } = nullUnion; + + +//// [restUnion.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var union; +var rest1; +var a = union.a, rest1 = __rest(union, ["a"]); +var undefinedUnion; +var rest2; +var n = undefinedUnion.n, rest2 = __rest(undefinedUnion, ["n"]); +var nullUnion; +var rest3; +var n = nullUnion.n, rest3 = __rest(nullUnion, ["n"]); diff --git a/tests/baselines/reference/restUnion.symbols b/tests/baselines/reference/restUnion.symbols new file mode 100644 index 00000000000..660c85badb4 --- /dev/null +++ b/tests/baselines/reference/restUnion.symbols @@ -0,0 +1,44 @@ +=== tests/cases/compiler/restUnion.ts === +var union: { a: number, c: boolean } | { a: string, b: string }; +>union : Symbol(union, Decl(restUnion.ts, 0, 3)) +>a : Symbol(a, Decl(restUnion.ts, 0, 12)) +>c : Symbol(c, Decl(restUnion.ts, 0, 23)) +>a : Symbol(a, Decl(restUnion.ts, 0, 40)) +>b : Symbol(b, Decl(restUnion.ts, 0, 51)) + +var rest1: { c: boolean } | { b: string }; +>rest1 : Symbol(rest1, Decl(restUnion.ts, 2, 3), Decl(restUnion.ts, 3, 7)) +>c : Symbol(c, Decl(restUnion.ts, 2, 12)) +>b : Symbol(b, Decl(restUnion.ts, 2, 29)) + +var {a, ...rest1 } = union; +>a : Symbol(a, Decl(restUnion.ts, 3, 5)) +>rest1 : Symbol(rest1, Decl(restUnion.ts, 2, 3), Decl(restUnion.ts, 3, 7)) +>union : Symbol(union, Decl(restUnion.ts, 0, 3)) + + +var undefinedUnion: { n: number } | undefined; +>undefinedUnion : Symbol(undefinedUnion, Decl(restUnion.ts, 6, 3)) +>n : Symbol(n, Decl(restUnion.ts, 6, 21)) + +var rest2: {}; +>rest2 : Symbol(rest2, Decl(restUnion.ts, 7, 3), Decl(restUnion.ts, 8, 7)) + +var {n, ...rest2 } = undefinedUnion; +>n : Symbol(n, Decl(restUnion.ts, 8, 5), Decl(restUnion.ts, 13, 5)) +>rest2 : Symbol(rest2, Decl(restUnion.ts, 7, 3), Decl(restUnion.ts, 8, 7)) +>undefinedUnion : Symbol(undefinedUnion, Decl(restUnion.ts, 6, 3)) + + +var nullUnion: { n: number } | null; +>nullUnion : Symbol(nullUnion, Decl(restUnion.ts, 11, 3)) +>n : Symbol(n, Decl(restUnion.ts, 11, 16)) + +var rest3: {}; +>rest3 : Symbol(rest3, Decl(restUnion.ts, 12, 3), Decl(restUnion.ts, 13, 7)) + +var {n, ...rest3 } = nullUnion; +>n : Symbol(n, Decl(restUnion.ts, 8, 5), Decl(restUnion.ts, 13, 5)) +>rest3 : Symbol(rest3, Decl(restUnion.ts, 12, 3), Decl(restUnion.ts, 13, 7)) +>nullUnion : Symbol(nullUnion, Decl(restUnion.ts, 11, 3)) + diff --git a/tests/baselines/reference/restUnion.types b/tests/baselines/reference/restUnion.types new file mode 100644 index 00000000000..9837466684b --- /dev/null +++ b/tests/baselines/reference/restUnion.types @@ -0,0 +1,45 @@ +=== tests/cases/compiler/restUnion.ts === +var union: { a: number, c: boolean } | { a: string, b: string }; +>union : { a: number; c: boolean; } | { a: string; b: string; } +>a : number +>c : boolean +>a : string +>b : string + +var rest1: { c: boolean } | { b: string }; +>rest1 : { c: boolean; } | { b: string; } +>c : boolean +>b : string + +var {a, ...rest1 } = union; +>a : string | number +>rest1 : { c: boolean; } | { b: string; } +>union : { a: number; c: boolean; } | { a: string; b: string; } + + +var undefinedUnion: { n: number } | undefined; +>undefinedUnion : { n: number; } +>n : number + +var rest2: {}; +>rest2 : {} + +var {n, ...rest2 } = undefinedUnion; +>n : number +>rest2 : {} +>undefinedUnion : { n: number; } + + +var nullUnion: { n: number } | null; +>nullUnion : { n: number; } +>n : number +>null : null + +var rest3: {}; +>rest3 : {} + +var {n, ...rest3 } = nullUnion; +>n : number +>rest3 : {} +>nullUnion : { n: number; } + diff --git a/tests/baselines/reference/restUnion2.js b/tests/baselines/reference/restUnion2.js new file mode 100644 index 00000000000..44a0acfbcf8 --- /dev/null +++ b/tests/baselines/reference/restUnion2.js @@ -0,0 +1,38 @@ +//// [restUnion2.ts] + +declare const undefinedUnion: { n: number } | undefined; +var rest2: { n: number }; +var {...rest2 } = undefinedUnion; + + +declare const nullUnion: { n: number } | null; +var rest3: { n: number }; +var {...rest3 } = nullUnion; + + +declare const nullAndUndefinedUnion: null | undefined; +var rest4: { }; +var {...rest4 } = nullAndUndefinedUnion; + +declare const unionWithIntersection: ({ n: number } & { s: string }) & undefined | null; +var rest5: { n: number, s: string }; +var {...rest5 } = unionWithIntersection; + +//// [restUnion2.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var rest2; +var rest2 = __rest(undefinedUnion, []); +var rest3; +var rest3 = __rest(nullUnion, []); +var rest4; +var rest4 = __rest(nullAndUndefinedUnion, []); +var rest5; +var rest5 = __rest(unionWithIntersection, []); diff --git a/tests/baselines/reference/restUnion2.symbols b/tests/baselines/reference/restUnion2.symbols new file mode 100644 index 00000000000..20a113a23b4 --- /dev/null +++ b/tests/baselines/reference/restUnion2.symbols @@ -0,0 +1,52 @@ +=== tests/cases/compiler/restUnion2.ts === + +declare const undefinedUnion: { n: number } | undefined; +>undefinedUnion : Symbol(undefinedUnion, Decl(restUnion2.ts, 1, 13)) +>n : Symbol(n, Decl(restUnion2.ts, 1, 31)) + +var rest2: { n: number }; +>rest2 : Symbol(rest2, Decl(restUnion2.ts, 2, 3), Decl(restUnion2.ts, 3, 5)) +>n : Symbol(n, Decl(restUnion2.ts, 2, 12)) + +var {...rest2 } = undefinedUnion; +>rest2 : Symbol(rest2, Decl(restUnion2.ts, 2, 3), Decl(restUnion2.ts, 3, 5)) +>undefinedUnion : Symbol(undefinedUnion, Decl(restUnion2.ts, 1, 13)) + + +declare const nullUnion: { n: number } | null; +>nullUnion : Symbol(nullUnion, Decl(restUnion2.ts, 6, 13)) +>n : Symbol(n, Decl(restUnion2.ts, 6, 26)) + +var rest3: { n: number }; +>rest3 : Symbol(rest3, Decl(restUnion2.ts, 7, 3), Decl(restUnion2.ts, 8, 5)) +>n : Symbol(n, Decl(restUnion2.ts, 7, 12)) + +var {...rest3 } = nullUnion; +>rest3 : Symbol(rest3, Decl(restUnion2.ts, 7, 3), Decl(restUnion2.ts, 8, 5)) +>nullUnion : Symbol(nullUnion, Decl(restUnion2.ts, 6, 13)) + + +declare const nullAndUndefinedUnion: null | undefined; +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(restUnion2.ts, 11, 13)) + +var rest4: { }; +>rest4 : Symbol(rest4, Decl(restUnion2.ts, 12, 3), Decl(restUnion2.ts, 13, 5)) + +var {...rest4 } = nullAndUndefinedUnion; +>rest4 : Symbol(rest4, Decl(restUnion2.ts, 12, 3), Decl(restUnion2.ts, 13, 5)) +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(restUnion2.ts, 11, 13)) + +declare const unionWithIntersection: ({ n: number } & { s: string }) & undefined | null; +>unionWithIntersection : Symbol(unionWithIntersection, Decl(restUnion2.ts, 15, 13)) +>n : Symbol(n, Decl(restUnion2.ts, 15, 39)) +>s : Symbol(s, Decl(restUnion2.ts, 15, 55)) + +var rest5: { n: number, s: string }; +>rest5 : Symbol(rest5, Decl(restUnion2.ts, 16, 3), Decl(restUnion2.ts, 17, 5)) +>n : Symbol(n, Decl(restUnion2.ts, 16, 12)) +>s : Symbol(s, Decl(restUnion2.ts, 16, 23)) + +var {...rest5 } = unionWithIntersection; +>rest5 : Symbol(rest5, Decl(restUnion2.ts, 16, 3), Decl(restUnion2.ts, 17, 5)) +>unionWithIntersection : Symbol(unionWithIntersection, Decl(restUnion2.ts, 15, 13)) + diff --git a/tests/baselines/reference/restUnion2.types b/tests/baselines/reference/restUnion2.types new file mode 100644 index 00000000000..81b768777fd --- /dev/null +++ b/tests/baselines/reference/restUnion2.types @@ -0,0 +1,55 @@ +=== tests/cases/compiler/restUnion2.ts === + +declare const undefinedUnion: { n: number } | undefined; +>undefinedUnion : { n: number; } | undefined +>n : number + +var rest2: { n: number }; +>rest2 : { n: number; } +>n : number + +var {...rest2 } = undefinedUnion; +>rest2 : { n: number; } +>undefinedUnion : { n: number; } | undefined + + +declare const nullUnion: { n: number } | null; +>nullUnion : { n: number; } | null +>n : number +>null : null + +var rest3: { n: number }; +>rest3 : { n: number; } +>n : number + +var {...rest3 } = nullUnion; +>rest3 : { n: number; } +>nullUnion : { n: number; } | null + + +declare const nullAndUndefinedUnion: null | undefined; +>nullAndUndefinedUnion : null | undefined +>null : null + +var rest4: { }; +>rest4 : {} + +var {...rest4 } = nullAndUndefinedUnion; +>rest4 : {} +>nullAndUndefinedUnion : null | undefined + +declare const unionWithIntersection: ({ n: number } & { s: string }) & undefined | null; +>unionWithIntersection : ({ n: number; } & { s: string; } & undefined) | null +>n : number +>s : string +>null : null + +var rest5: { n: number, s: string }; +>rest5 : { n: number; s: string; } +>n : number +>s : string + +var {...rest5 } = unionWithIntersection; +>rest5 : { n: number; s: string; } +>unionWithIntersection : ({ n: number; } & { s: string; } & undefined) | null + diff --git a/tests/baselines/reference/scannerEnum1.js b/tests/baselines/reference/scannerEnum1.js index e785a07ace2..5d8b506e62f 100644 --- a/tests/baselines/reference/scannerEnum1.js +++ b/tests/baselines/reference/scannerEnum1.js @@ -6,8 +6,8 @@ //// [scannerEnum1.js] "use strict"; +var CodeGenTarget; (function (CodeGenTarget) { CodeGenTarget[CodeGenTarget["ES3"] = 0] = "ES3"; CodeGenTarget[CodeGenTarget["ES5"] = 1] = "ES5"; -})(exports.CodeGenTarget || (exports.CodeGenTarget = {})); -var CodeGenTarget = exports.CodeGenTarget; +})(CodeGenTarget = exports.CodeGenTarget || (exports.CodeGenTarget = {})); diff --git a/tests/baselines/reference/scannerNumericLiteral2.errors.txt b/tests/baselines/reference/scannerNumericLiteral2.errors.txt index 5860be78c1b..faf5429f8b7 100644 --- a/tests/baselines/reference/scannerNumericLiteral2.errors.txt +++ b/tests/baselines/reference/scannerNumericLiteral2.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral2.ts(1,1): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral2.ts(1,1): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o1'. ==== tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral2.ts (1 errors) ==== 01 ~~ -!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. \ No newline at end of file +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o1'. \ No newline at end of file diff --git a/tests/baselines/reference/scannerNumericLiteral8.errors.txt b/tests/baselines/reference/scannerNumericLiteral8.errors.txt index 94916626fe6..6545050afc2 100644 --- a/tests/baselines/reference/scannerNumericLiteral8.errors.txt +++ b/tests/baselines/reference/scannerNumericLiteral8.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral8.ts(1,2): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. +tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral8.ts(1,1): error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o3'. ==== tests/cases/conformance/scanner/ecmascript5/scannerNumericLiteral8.ts (1 errors) ==== -03 - ~~ -!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. \ No newline at end of file + ~~~ +!!! error TS1085: Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '-0o3'. \ No newline at end of file diff --git a/tests/baselines/reference/selfReferencingSpreadInLoop.errors.txt b/tests/baselines/reference/selfReferencingSpreadInLoop.errors.txt new file mode 100644 index 00000000000..599c9fbedb0 --- /dev/null +++ b/tests/baselines/reference/selfReferencingSpreadInLoop.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/selfReferencingSpreadInLoop.ts(1,5): error TS7034: Variable 'additional' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/selfReferencingSpreadInLoop.ts(3,22): error TS7005: Variable 'additional' implicitly has an 'any[]' type. + + +==== tests/cases/compiler/selfReferencingSpreadInLoop.ts (2 errors) ==== + let additional = []; + ~~~~~~~~~~ +!!! error TS7034: Variable 'additional' implicitly has type 'any[]' in some locations where its type cannot be determined. + for (const subcomponent of [1, 2, 3]) { + additional = [...additional, subcomponent]; + ~~~~~~~~~~ +!!! error TS7005: Variable 'additional' implicitly has an 'any[]' type. + } + \ No newline at end of file diff --git a/tests/baselines/reference/selfReferencingSpreadInLoop.js b/tests/baselines/reference/selfReferencingSpreadInLoop.js new file mode 100644 index 00000000000..1b8d5ace4f3 --- /dev/null +++ b/tests/baselines/reference/selfReferencingSpreadInLoop.js @@ -0,0 +1,13 @@ +//// [selfReferencingSpreadInLoop.ts] +let additional = []; +for (const subcomponent of [1, 2, 3]) { + additional = [...additional, subcomponent]; +} + + +//// [selfReferencingSpreadInLoop.js] +var additional = []; +for (var _i = 0, _a = [1, 2, 3]; _i < _a.length; _i++) { + var subcomponent = _a[_i]; + additional = additional.concat([subcomponent]); +} diff --git a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.js b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.js index 981ee08e20c..6be02246e39 100644 --- a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.js +++ b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.js @@ -176,63 +176,63 @@ function foo({a = 4, b = { x: 5 }}) { }); (function () { var y; - (_a = { y: 1 }, _b = _a.y, y = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = { y: 1 }.y, y = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y; - (_a = { y: 1 }, _b = _a.y, y = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = { y: 1 }.y, y = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y0; - (_a = { y0: 1 }, _b = _a.y0, y0 = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = { y0: 1 }.y0, y0 = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y0; - (_a = { y0: 1 }, _b = _a.y0, y0 = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = { y0: 1 }.y0, y0 = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y1; - (_a = {}, _b = _a.y1, y1 = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = {}.y1, y1 = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y1; - (_a = {}, _b = _a.y1, y1 = _b === void 0 ? 5 : _b, _a); - var _a, _b; + (_a = {}.y1, y1 = _a === void 0 ? 5 : _a); + var _a; }); (function () { var y2, y3; - (_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c, _a); + (_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c); var _a, _b, _c; }); (function () { var y2, y3; - (_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c, _a); + (_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c); var _a, _b, _c; }); (function () { var y4, y5; - (_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c, _a); + (_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c); var _a, _b, _c; }); (function () { var y4, y5; - (_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c, _a); + (_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c); var _a, _b, _c; }); (function () { var z; - (_a = { z: { x: 1 } }, _b = _a.z, z = _b === void 0 ? { x: 5 } : _b, _a); - var _a, _b; + (_a = { z: { x: 1 } }.z, z = _a === void 0 ? { x: 5 } : _a); + var _a; }); (function () { var z; - (_a = { z: { x: 1 } }, _b = _a.z, z = _b === void 0 ? { x: 5 } : _b, _a); - var _a, _b; + (_a = { z: { x: 1 } }.z, z = _a === void 0 ? { x: 5 } : _a); + var _a; }); (function () { var a = { s: s }; diff --git a/tests/baselines/reference/sourceMapValidationDecorators.js.map b/tests/baselines/reference/sourceMapValidationDecorators.js.map index 535d6603d8c..ac635a518f1 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.js.map +++ b/tests/baselines/reference/sourceMapValidationDecorators.js.map @@ -1,2 +1,2 @@ //// [sourceMapValidationDecorators.js.map] -{"version":3,"file":"sourceMapValidationDecorators.js","sourceRoot":"","sources":["sourceMapValidationDecorators.ts"],"names":[],"mappings":";;;;;;;;;AASA;IACI,iBAGS,QAAgB;QAIvB,WAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,0BAAc;;QAJP,aAAQ,GAAR,QAAQ,CAAQ;IAKzB,CAAC;IAID,uBAAK,GAAL;QACI,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC5C,CAAC;IAUO,oBAAE,GAAV,UAGE,CAAS;QACP,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAID,sBAAI,8BAAS;aAAb;YACI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QACzB,CAAC;aAED,UAGE,SAAiB;YACf,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC9B,CAAC;;;OAPA;IAQL,cAAC;AAAD,CAAC,AA5CD,IA4CC;AArBkB,UAAE,GAAW,EAAE,CAAC;AAV/B;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;oCAGtB;AAID;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;kCACL;AAMlB;IACG,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;iCAGzB;AAID;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;IAMpB,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;wCAJzB;AAbD;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;yBACQ;AAvBnC;IAFC,eAAe;IACf,eAAe,CAAC,EAAE,CAAC;IAGb,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;IAGvB,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;WAqC7B"} \ No newline at end of file +{"version":3,"file":"sourceMapValidationDecorators.js","sourceRoot":"","sources":["sourceMapValidationDecorators.ts"],"names":[],"mappings":";;;;;;;;;AASA,IAAM,OAAO;IACT,iBAGS,QAAgB;QAIvB,WAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,0BAAc;;QAJP,aAAQ,GAAR,QAAQ,CAAQ;IAKzB,CAAC;IAID,uBAAK,GAAL;QACI,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC5C,CAAC;IAUO,oBAAE,GAAV,UAGE,CAAS;QACP,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAID,sBAAI,8BAAS;aAAb;YACI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QACzB,CAAC;aAED,UAGE,SAAiB;YACf,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC9B,CAAC;;;OAPA;IAQL,cAAC;AAAD,CAAC,AA5CD,IA4CC;AArBkB,UAAE,GAAW,EAAE,CAAC;AAV/B;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;oCAGtB;AAID;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;kCACL;AAMlB;IACG,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;iCAGzB;AAID;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;IAMpB,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;wCAJzB;AAbD;IAFC,kBAAkB;IAClB,kBAAkB,CAAC,EAAE,CAAC;yBACQ;AAvB7B,OAAO;IAFZ,eAAe;IACf,eAAe,CAAC,EAAE,CAAC;IAGb,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;IAGvB,WAAA,mBAAmB,CAAA;IACnB,WAAA,mBAAmB,CAAC,EAAE,CAAC,CAAA;GAPxB,OAAO,CA4CZ"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt b/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt index 37f6a4bea08..d581fdef886 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt @@ -19,7 +19,9 @@ sourceFile:sourceMapValidationDecorators.ts >>>}; >>>var Greeter = (function () { 1 > -2 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +2 >^^^^ +3 > ^^^^^^^ +4 > ^^^^^^^^^^^^^^^^^^^^^^-> 1 >declare function ClassDecorator1(target: Function): void; >declare function ClassDecorator2(x: number): (target: Function) => void; >declare function PropertyDecorator1(target: Object, key: string | symbol, descriptor?: PropertyDescriptor): void; @@ -30,13 +32,17 @@ sourceFile:sourceMapValidationDecorators.ts >@ClassDecorator1 >@ClassDecorator2(10) > +2 >class +3 > Greeter 1 >Emitted(10, 1) Source(10, 1) + SourceIndex(0) +2 >Emitted(10, 5) Source(10, 7) + SourceIndex(0) +3 >Emitted(10, 12) Source(10, 14) + SourceIndex(0) --- >>> function Greeter(greeting) { 1->^^^^ 2 > ^^^^^^^^^^^^^^^^^ 3 > ^^^^^^^^ -1->class Greeter { +1-> { > 2 > constructor( > @ParameterDecorator1 @@ -729,9 +735,12 @@ sourceFile:sourceMapValidationDecorators.ts --- >>>Greeter = __decorate([ 1 > -2 >^^^^^^^^^^^^^^^^^^^^^-> +2 >^^^^^^^ +3 > ^^^^^^^^^^^^^^-> 1 > -1 >Emitted(59, 1) Source(10, 1) + SourceIndex(0) +2 >Greeter +1 >Emitted(59, 1) Source(10, 7) + SourceIndex(0) +2 >Emitted(59, 8) Source(10, 14) + SourceIndex(0) --- >>> ClassDecorator1, 1->^^^^ @@ -846,46 +855,59 @@ sourceFile:sourceMapValidationDecorators.ts 7 >Emitted(65, 40) Source(17, 31) + SourceIndex(0) --- >>>], Greeter); -1 >^^^^^^^^^^^ -2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> -1 > - > ...b: string[]) { - > } - > - > @PropertyDecorator1 - > @PropertyDecorator2(40) - > greet() { - > return "

" + this.greeting + "

"; - > } - > - > @PropertyDecorator1 - > @PropertyDecorator2(50) - > private x: string; - > - > @PropertyDecorator1 - > @PropertyDecorator2(60) - > private static x1: number = 10; - > - > private fn( - > @ParameterDecorator1 - > @ParameterDecorator2(70) - > x: number) { - > return this.greeting; - > } - > - > @PropertyDecorator1 - > @PropertyDecorator2(80) - > get greetings() { - > return this.greeting; - > } - > - > set greetings( - > @ParameterDecorator1 - > @ParameterDecorator2(90) - > greetings: string) { - > this.greeting = greetings; - > } - >} -1 >Emitted(66, 12) Source(54, 2) + SourceIndex(0) +1 >^^^ +2 > ^^^^^^^ +3 > ^ +4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > +2 > Greeter +3 > { + > constructor( + > @ParameterDecorator1 + > @ParameterDecorator2(20) + > public greeting: string, + > + > @ParameterDecorator1 + > @ParameterDecorator2(30) + > ...b: string[]) { + > } + > + > @PropertyDecorator1 + > @PropertyDecorator2(40) + > greet() { + > return "

" + this.greeting + "

"; + > } + > + > @PropertyDecorator1 + > @PropertyDecorator2(50) + > private x: string; + > + > @PropertyDecorator1 + > @PropertyDecorator2(60) + > private static x1: number = 10; + > + > private fn( + > @ParameterDecorator1 + > @ParameterDecorator2(70) + > x: number) { + > return this.greeting; + > } + > + > @PropertyDecorator1 + > @PropertyDecorator2(80) + > get greetings() { + > return this.greeting; + > } + > + > set greetings( + > @ParameterDecorator1 + > @ParameterDecorator2(90) + > greetings: string) { + > this.greeting = greetings; + > } + > } +1 >Emitted(66, 4) Source(10, 7) + SourceIndex(0) +2 >Emitted(66, 11) Source(10, 14) + SourceIndex(0) +3 >Emitted(66, 12) Source(54, 2) + SourceIndex(0) --- >>>//# sourceMappingURL=sourceMapValidationDecorators.js.map \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationStatements.js.map b/tests/baselines/reference/sourceMapValidationStatements.js.map index 464ab4dc002..5841f329e5e 100644 --- a/tests/baselines/reference/sourceMapValidationStatements.js.map +++ b/tests/baselines/reference/sourceMapValidationStatements.js.map @@ -1,2 +1,2 @@ //// [sourceMapValidationStatements.js.map] -{"version":3,"file":"sourceMapValidationStatements.js","sourceRoot":"","sources":["sourceMapValidationStatements.ts"],"names":[],"mappings":"AAAA;IACI,IAAI,CAAC,CAAC;IACN,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;QAC1B,CAAC,IAAI,CAAC,CAAC;QACP,CAAC,IAAI,CAAC,CAAC;IACX,CAAC;IACD,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACT,CAAC,IAAI,CAAC,CAAC;IACX,CAAC;IAAC,IAAI,CAAC,CAAC;QACJ,CAAC,IAAI,EAAE,CAAC;QACR,CAAC,EAAE,CAAC;IACR,CAAC;IACD,IAAI,CAAC,GAAG;QACJ,CAAC;QACD,CAAC;QACD,CAAC;KACJ,CAAC;IACF,IAAI,GAAG,GAAG;QACN,CAAC,EAAE,CAAC;QACJ,CAAC,EAAE,OAAO;KACb,CAAC;IACF,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACb,IAAI,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;IACD,IAAI,CAAC;QACD,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC;IACnB,CAAE;IAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACT,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YACb,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACf,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;QAClB,CAAC;IACL,CAAC;IACD,IAAI,CAAC;QACD,MAAM,IAAI,KAAK,EAAE,CAAC;IACtB,CAAE;IAAA,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACV,IAAI,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;YAAS,CAAC;QACP,CAAC,GAAG,EAAE,CAAC;IACX,CAAC;IACD,MAAM,GAAG,EAAE,CAAC;QACR,CAAC,GAAG,CAAC,CAAC;QACN,CAAC,GAAG,EAAE,CAAC;IACX,CAAC;IACD,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACZ,KAAK,CAAC,EAAE,CAAC;YACL,CAAC,EAAE,CAAC;YACJ,KAAK,CAAC;QAEV,CAAC;QACD,KAAK,CAAC,EAAE,CAAC;YACL,CAAC,EAAE,CAAC;YACJ,KAAK,CAAC;QAEV,CAAC;QACD,SAAS,CAAC;YACN,CAAC,IAAI,CAAC,CAAC;YACP,CAAC,GAAG,EAAE,CAAC;YACP,KAAK,CAAC;QAEV,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;QACZ,CAAC,EAAE,CAAC;IACR,CAAC;IACD,GAAG,CAAC;QACA,CAAC,EAAE,CAAC;IACR,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAC;IACf,CAAC,GAAG,CAAC,CAAC;IACN,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC,KAAK,CAAC,CAAC;IACR,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IACX,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,CAAC;AACX,CAAC;AACD,IAAI,CAAC,GAAG;IACJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC,CAAC;AACF,CAAC,EAAE,CAAC"} \ No newline at end of file +{"version":3,"file":"sourceMapValidationStatements.js","sourceRoot":"","sources":["sourceMapValidationStatements.ts"],"names":[],"mappings":"AAAA;IACI,IAAI,CAAC,CAAC;IACN,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;QAC1B,CAAC,IAAI,CAAC,CAAC;QACP,CAAC,IAAI,CAAC,CAAC;IACX,CAAC;IACD,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACT,CAAC,IAAI,CAAC,CAAC;IACX,CAAC;IAAC,IAAI,CAAC,CAAC;QACJ,CAAC,IAAI,EAAE,CAAC;QACR,CAAC,EAAE,CAAC;IACR,CAAC;IACD,IAAI,CAAC,GAAG;QACJ,CAAC;QACD,CAAC;QACD,CAAC;KACJ,CAAC;IACF,IAAI,GAAG,GAAG;QACN,CAAC,EAAE,CAAC;QACJ,CAAC,EAAE,OAAO;KACb,CAAC;IACF,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACb,IAAI,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;IACD,IAAI,CAAC;QACD,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC;IACnB,CAAC;IAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACT,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YACb,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACf,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;QAClB,CAAC;IACL,CAAC;IACD,IAAI,CAAC;QACD,MAAM,IAAI,KAAK,EAAE,CAAC;IACtB,CAAC;IAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACV,IAAI,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;YAAS,CAAC;QACP,CAAC,GAAG,EAAE,CAAC;IACX,CAAC;IACD,MAAM,GAAG,EAAE,CAAC;QACR,CAAC,GAAG,CAAC,CAAC;QACN,CAAC,GAAG,EAAE,CAAC;IACX,CAAC;IACD,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACZ,KAAK,CAAC,EAAE,CAAC;YACL,CAAC,EAAE,CAAC;YACJ,KAAK,CAAC;QAEV,CAAC;QACD,KAAK,CAAC,EAAE,CAAC;YACL,CAAC,EAAE,CAAC;YACJ,KAAK,CAAC;QAEV,CAAC;QACD,SAAS,CAAC;YACN,CAAC,IAAI,CAAC,CAAC;YACP,CAAC,GAAG,EAAE,CAAC;YACP,KAAK,CAAC;QAEV,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;QACZ,CAAC,EAAE,CAAC;IACR,CAAC;IACD,GAAG,CAAC;QACA,CAAC,EAAE,CAAC;IACR,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAC;IACf,CAAC,GAAG,CAAC,CAAC;IACN,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC,KAAK,CAAC,CAAC;IACR,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IACX,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,CAAC;AACX,CAAC;AACD,IAAI,CAAC,GAAG;IACJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC,CAAC;AACF,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt b/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt index ed7c9395d2f..7c5c5bfcfeb 100644 --- a/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt @@ -525,9 +525,9 @@ sourceFile:sourceMapValidationStatements.ts 3 > ^^^^^^^^^^^-> 1 > > -2 > } +2 > } 1 >Emitted(30, 5) Source(29, 5) + SourceIndex(0) -2 >Emitted(30, 6) Source(29, 7) + SourceIndex(0) +2 >Emitted(30, 6) Source(29, 6) + SourceIndex(0) --- >>> catch (e) { 1->^^^^ @@ -539,7 +539,7 @@ sourceFile:sourceMapValidationStatements.ts 7 > ^ 8 > ^ 9 > ^^^^^^^^^^^-> -1-> +1-> 2 > catch 3 > 4 > ( @@ -727,9 +727,9 @@ sourceFile:sourceMapValidationStatements.ts 3 > ^^^^^^^^^^^^-> 1 > > -2 > } +2 > } 1 >Emitted(41, 5) Source(38, 5) + SourceIndex(0) -2 >Emitted(41, 6) Source(38, 7) + SourceIndex(0) +2 >Emitted(41, 6) Source(38, 6) + SourceIndex(0) --- >>> catch (e1) { 1->^^^^ @@ -741,7 +741,7 @@ sourceFile:sourceMapValidationStatements.ts 7 > ^ 8 > ^ 9 > ^^^^-> -1-> +1-> 2 > catch 3 > 4 > ( diff --git a/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map b/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map index 46506410856..8b8690b470d 100644 --- a/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map +++ b/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map @@ -1,2 +1,2 @@ //// [sourceMapValidationTryCatchFinally.js.map] -{"version":3,"file":"sourceMapValidationTryCatchFinally.js","sourceRoot":"","sources":["sourceMapValidationTryCatchFinally.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC,GAAG,EAAE,CAAC;AACX,IAAI,CAAC;IACD,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAE;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACT,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAAS,CAAC;IACP,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC;AACD,IACA,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,IAAI,KAAK,EAAE,CAAC;AACtB,CACA;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CACT,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAED,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC"} \ No newline at end of file +{"version":3,"file":"sourceMapValidationTryCatchFinally.js","sourceRoot":"","sources":["sourceMapValidationTryCatchFinally.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC,GAAG,EAAE,CAAC;AACX,IAAI,CAAC;IACD,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACT,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAAS,CAAC;IACP,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC;AACD,IACA,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,IAAI,KAAK,EAAE,CAAC;AACtB,CAAC;AACD,KAAK,CAAC,CAAC,CAAC,CAAC,CACT,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAED,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt b/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt index d625e74c262..845ec5eeb27 100644 --- a/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt @@ -71,9 +71,9 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 3 > ^^^^^^^^^^^-> 1 > > -2 >} +2 >} 1 >Emitted(4, 1) Source(4, 1) + SourceIndex(0) -2 >Emitted(4, 2) Source(4, 3) + SourceIndex(0) +2 >Emitted(4, 2) Source(4, 2) + SourceIndex(0) --- >>>catch (e) { 1-> @@ -85,7 +85,7 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 7 > ^ 8 > ^ 9 > ^^^^-> -1-> +1-> 2 >catch 3 > 4 > ( @@ -245,10 +245,9 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 3 > ^^^^^^^^^^^-> 1 > > -2 >} - > +2 >} 1 >Emitted(14, 1) Source(13, 1) + SourceIndex(0) -2 >Emitted(14, 2) Source(14, 1) + SourceIndex(0) +2 >Emitted(14, 2) Source(13, 2) + SourceIndex(0) --- >>>catch (e) { 1-> @@ -260,7 +259,8 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 7 > ^ 8 > ^ 9 > ^^^^-> -1-> +1-> + > 2 >catch 3 > 4 > ( diff --git a/tests/baselines/reference/spreadIntersection.js b/tests/baselines/reference/spreadIntersection.js new file mode 100644 index 00000000000..b3fa9f0c2fb --- /dev/null +++ b/tests/baselines/reference/spreadIntersection.js @@ -0,0 +1,23 @@ +//// [spreadIntersection.ts] +var intersection: { a: number } & { b: string }; + +var o1: { a: number, b: string }; +var o1 = { ...intersection }; + +var o2: { a: number, b: string, c: boolean }; +var o2 = { ...intersection, c: false }; + +//// [spreadIntersection.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var intersection; +var o1; +var o1 = __assign({}, intersection); +var o2; +var o2 = __assign({}, intersection, { c: false }); diff --git a/tests/baselines/reference/spreadIntersection.symbols b/tests/baselines/reference/spreadIntersection.symbols new file mode 100644 index 00000000000..1f6b3c12de1 --- /dev/null +++ b/tests/baselines/reference/spreadIntersection.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/spreadIntersection.ts === +var intersection: { a: number } & { b: string }; +>intersection : Symbol(intersection, Decl(spreadIntersection.ts, 0, 3)) +>a : Symbol(a, Decl(spreadIntersection.ts, 0, 19)) +>b : Symbol(b, Decl(spreadIntersection.ts, 0, 35)) + +var o1: { a: number, b: string }; +>o1 : Symbol(o1, Decl(spreadIntersection.ts, 2, 3), Decl(spreadIntersection.ts, 3, 3)) +>a : Symbol(a, Decl(spreadIntersection.ts, 2, 9)) +>b : Symbol(b, Decl(spreadIntersection.ts, 2, 20)) + +var o1 = { ...intersection }; +>o1 : Symbol(o1, Decl(spreadIntersection.ts, 2, 3), Decl(spreadIntersection.ts, 3, 3)) +>intersection : Symbol(intersection, Decl(spreadIntersection.ts, 0, 3)) + +var o2: { a: number, b: string, c: boolean }; +>o2 : Symbol(o2, Decl(spreadIntersection.ts, 5, 3), Decl(spreadIntersection.ts, 6, 3)) +>a : Symbol(a, Decl(spreadIntersection.ts, 5, 9)) +>b : Symbol(b, Decl(spreadIntersection.ts, 5, 20)) +>c : Symbol(c, Decl(spreadIntersection.ts, 5, 31)) + +var o2 = { ...intersection, c: false }; +>o2 : Symbol(o2, Decl(spreadIntersection.ts, 5, 3), Decl(spreadIntersection.ts, 6, 3)) +>intersection : Symbol(intersection, Decl(spreadIntersection.ts, 0, 3)) +>c : Symbol(c, Decl(spreadIntersection.ts, 6, 27)) + diff --git a/tests/baselines/reference/spreadIntersection.types b/tests/baselines/reference/spreadIntersection.types new file mode 100644 index 00000000000..c3c6b99adee --- /dev/null +++ b/tests/baselines/reference/spreadIntersection.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/spreadIntersection.ts === +var intersection: { a: number } & { b: string }; +>intersection : { a: number; } & { b: string; } +>a : number +>b : string + +var o1: { a: number, b: string }; +>o1 : { a: number; b: string; } +>a : number +>b : string + +var o1 = { ...intersection }; +>o1 : { a: number; b: string; } +>{ ...intersection } : { a: number; b: string; } +>intersection : { a: number; } & { b: string; } + +var o2: { a: number, b: string, c: boolean }; +>o2 : { a: number; b: string; c: boolean; } +>a : number +>b : string +>c : boolean + +var o2 = { ...intersection, c: false }; +>o2 : { a: number; b: string; c: boolean; } +>{ ...intersection, c: false } : { c: boolean; a: number; b: string; } +>intersection : { a: number; } & { b: string; } +>c : boolean +>false : false + diff --git a/tests/baselines/reference/spreadInvalidArgumentType.errors.txt b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt new file mode 100644 index 00000000000..5088390f9ee --- /dev/null +++ b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt @@ -0,0 +1,104 @@ +tests/cases/compiler/spreadInvalidArgumentType.ts(31,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(33,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(35,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(36,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(38,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(41,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(42,16): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(44,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(45,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(47,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(48,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(55,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(56,17): error TS2698: Spread types may only be created from object types. +tests/cases/compiler/spreadInvalidArgumentType.ts(58,17): error TS2698: Spread types may only be created from object types. + + +==== tests/cases/compiler/spreadInvalidArgumentType.ts (14 errors) ==== + enum E { v1, v2 }; + + function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var o1 = { ...p1 }; // Error, generic type paramterre + ~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // Error, generic type paramter + ~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o4 = { ...i }; // Error, index access + ~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o5 = { ...k }; // Error, index + ~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o6 = { ...mapped_generic }; // Error, generic mapped object type + ~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o7 = { ...mapped }; // OK, non-generic mapped type + + var o8 = { ...union_generic }; // Error, union with generic type parameter + ~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o9 = { ...union_primitive }; // Error, union with generic type parameter + ~~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + ~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o11 = { ...intersection_premitive }; // Error, intersection with generic type parameter + ~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o12 = { ...num }; // Error + ~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o13 = { ...str }; // Error + ~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o14 = { ...u }; // OK + var o15 = { ...n }; // OK + + var o16 = { ...a }; // OK + + var o17 = { ...literal_string }; // Error + ~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + var o18 = { ...literal_number }; // Error + ~~~~~~~~~~~~~~~~~ +!!! error TS2698: Spread types may only be created from object types. + + var o19 = { ...e }; // Error, enum + ~~~~ +!!! error TS2698: Spread types may only be created from object types. + } \ No newline at end of file diff --git a/tests/baselines/reference/spreadInvalidArgumentType.js b/tests/baselines/reference/spreadInvalidArgumentType.js new file mode 100644 index 00000000000..26f958f224d --- /dev/null +++ b/tests/baselines/reference/spreadInvalidArgumentType.js @@ -0,0 +1,114 @@ +//// [spreadInvalidArgumentType.ts] +enum E { v1, v2 }; + +function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var o1 = { ...p1 }; // Error, generic type paramterre + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // Error, generic type paramter + + var o4 = { ...i }; // Error, index access + var o5 = { ...k }; // Error, index + + var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o7 = { ...mapped }; // OK, non-generic mapped type + + var o8 = { ...union_generic }; // Error, union with generic type parameter + var o9 = { ...union_primitive }; // Error, union with generic type parameter + + var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o11 = { ...intersection_premitive }; // Error, intersection with generic type parameter + + var o12 = { ...num }; // Error + var o13 = { ...str }; // Error + + var o14 = { ...u }; // OK + var o15 = { ...n }; // OK + + var o16 = { ...a }; // OK + + var o17 = { ...literal_string }; // Error + var o18 = { ...literal_number }; // Error + + var o19 = { ...e }; // Error, enum +} + +//// [spreadInvalidArgumentType.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var E; +(function (E) { + E[E["v1"] = 0] = "v1"; + E[E["v2"] = 1] = "v2"; +})(E || (E = {})); +; +function f(p1, p2) { + var t; + var i; + var k; + var mapped_generic; + var mapped; + var union_generic; + var union_primitive; + var intersection_generic; + var intersection_premitive; + var num; + var str; + var u; + var n; + var a; + var literal_string; + var literal_number; + var e; + var o1 = __assign({}, p1); // Error, generic type paramterre + var o2 = __assign({}, p2); // OK + var o3 = __assign({}, t); // Error, generic type paramter + var o4 = __assign({}, i); // Error, index access + var o5 = __assign({}, k); // Error, index + var o6 = __assign({}, mapped_generic); // Error, generic mapped object type + var o7 = __assign({}, mapped); // OK, non-generic mapped type + var o8 = __assign({}, union_generic); // Error, union with generic type parameter + var o9 = __assign({}, union_primitive); // Error, union with generic type parameter + var o10 = __assign({}, intersection_generic); // Error, intersection with generic type parameter + var o11 = __assign({}, intersection_premitive); // Error, intersection with generic type parameter + var o12 = __assign({}, num); // Error + var o13 = __assign({}, str); // Error + var o14 = __assign({}, u); // OK + var o15 = __assign({}, n); // OK + var o16 = __assign({}, a); // OK + var o17 = __assign({}, literal_string); // Error + var o18 = __assign({}, literal_number); // Error + var o19 = __assign({}, e); // Error, enum +} diff --git a/tests/baselines/reference/spreadUnion.js b/tests/baselines/reference/spreadUnion.js new file mode 100644 index 00000000000..2691a3acdcc --- /dev/null +++ b/tests/baselines/reference/spreadUnion.js @@ -0,0 +1,28 @@ +//// [spreadUnion.ts] +var union: { a: number } | { b: string }; + +var o3: { a: number } | { b: string }; +var o3 = { ...union }; + +var o4: { a: boolean } | { b: string , a: boolean}; +var o4 = { ...union, a: false }; + +var o5: { a: number } | { b: string } | { a: number, b: string }; +var o5 = { ...union, ...union }; + +//// [spreadUnion.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var union; +var o3; +var o3 = __assign({}, union); +var o4; +var o4 = __assign({}, union, { a: false }); +var o5; +var o5 = __assign({}, union, union); diff --git a/tests/baselines/reference/spreadUnion.symbols b/tests/baselines/reference/spreadUnion.symbols new file mode 100644 index 00000000000..40a63d56d49 --- /dev/null +++ b/tests/baselines/reference/spreadUnion.symbols @@ -0,0 +1,38 @@ +=== tests/cases/compiler/spreadUnion.ts === +var union: { a: number } | { b: string }; +>union : Symbol(union, Decl(spreadUnion.ts, 0, 3)) +>a : Symbol(a, Decl(spreadUnion.ts, 0, 12)) +>b : Symbol(b, Decl(spreadUnion.ts, 0, 28)) + +var o3: { a: number } | { b: string }; +>o3 : Symbol(o3, Decl(spreadUnion.ts, 2, 3), Decl(spreadUnion.ts, 3, 3)) +>a : Symbol(a, Decl(spreadUnion.ts, 2, 9)) +>b : Symbol(b, Decl(spreadUnion.ts, 2, 25)) + +var o3 = { ...union }; +>o3 : Symbol(o3, Decl(spreadUnion.ts, 2, 3), Decl(spreadUnion.ts, 3, 3)) +>union : Symbol(union, Decl(spreadUnion.ts, 0, 3)) + +var o4: { a: boolean } | { b: string , a: boolean}; +>o4 : Symbol(o4, Decl(spreadUnion.ts, 5, 3), Decl(spreadUnion.ts, 6, 3)) +>a : Symbol(a, Decl(spreadUnion.ts, 5, 9)) +>b : Symbol(b, Decl(spreadUnion.ts, 5, 26)) +>a : Symbol(a, Decl(spreadUnion.ts, 5, 38)) + +var o4 = { ...union, a: false }; +>o4 : Symbol(o4, Decl(spreadUnion.ts, 5, 3), Decl(spreadUnion.ts, 6, 3)) +>union : Symbol(union, Decl(spreadUnion.ts, 0, 3)) +>a : Symbol(a, Decl(spreadUnion.ts, 6, 21)) + +var o5: { a: number } | { b: string } | { a: number, b: string }; +>o5 : Symbol(o5, Decl(spreadUnion.ts, 8, 3), Decl(spreadUnion.ts, 9, 3)) +>a : Symbol(a, Decl(spreadUnion.ts, 8, 9)) +>b : Symbol(b, Decl(spreadUnion.ts, 8, 25)) +>a : Symbol(a, Decl(spreadUnion.ts, 8, 41)) +>b : Symbol(b, Decl(spreadUnion.ts, 8, 52)) + +var o5 = { ...union, ...union }; +>o5 : Symbol(o5, Decl(spreadUnion.ts, 8, 3), Decl(spreadUnion.ts, 9, 3)) +>union : Symbol(union, Decl(spreadUnion.ts, 0, 3)) +>union : Symbol(union, Decl(spreadUnion.ts, 0, 3)) + diff --git a/tests/baselines/reference/spreadUnion.types b/tests/baselines/reference/spreadUnion.types new file mode 100644 index 00000000000..9e5ac1cffd5 --- /dev/null +++ b/tests/baselines/reference/spreadUnion.types @@ -0,0 +1,42 @@ +=== tests/cases/compiler/spreadUnion.ts === +var union: { a: number } | { b: string }; +>union : { a: number; } | { b: string; } +>a : number +>b : string + +var o3: { a: number } | { b: string }; +>o3 : { a: number; } | { b: string; } +>a : number +>b : string + +var o3 = { ...union }; +>o3 : { a: number; } | { b: string; } +>{ ...union } : { a: number; } | { b: string; } +>union : { a: number; } | { b: string; } + +var o4: { a: boolean } | { b: string , a: boolean}; +>o4 : { a: boolean; } | { b: string; a: boolean; } +>a : boolean +>b : string +>a : boolean + +var o4 = { ...union, a: false }; +>o4 : { a: boolean; } | { b: string; a: boolean; } +>{ ...union, a: false } : { a: boolean; } | { a: boolean; b: string; } +>union : { a: number; } | { b: string; } +>a : boolean +>false : false + +var o5: { a: number } | { b: string } | { a: number, b: string }; +>o5 : { a: number; } | { b: string; } | { a: number; b: string; } +>a : number +>b : string +>a : number +>b : string + +var o5 = { ...union, ...union }; +>o5 : { a: number; } | { b: string; } | { a: number; b: string; } +>{ ...union, ...union } : { a: number; } | { b: string; a: number; } | { a: number; b: string; } | { b: string; } +>union : { a: number; } | { b: string; } +>union : { a: number; } | { b: string; } + diff --git a/tests/baselines/reference/spreadUnion2.js b/tests/baselines/reference/spreadUnion2.js new file mode 100644 index 00000000000..6c7527af9dd --- /dev/null +++ b/tests/baselines/reference/spreadUnion2.js @@ -0,0 +1,49 @@ +//// [spreadUnion2.ts] + +declare const undefinedUnion: { a: number } | undefined; +declare const nullUnion: { b: number } | null; +declare const nullAndUndefinedUnion: null | undefined; + +var o1: { a: number }; +var o1 = { ...undefinedUnion }; + +var o2: { b: number }; +var o2 = { ...nullUnion }; + +var o3: { a: number, b: number }; +var o3 = { ...undefinedUnion, ...nullUnion }; +var o3 = { ...nullUnion, ...undefinedUnion }; + +var o4: { a: number }; +var o4 = { ...undefinedUnion, ...undefinedUnion }; + +var o5: { b: number }; +var o5 = { ...nullUnion, ...nullUnion }; + +var o6: { }; +var o6 = { ...nullAndUndefinedUnion, ...nullAndUndefinedUnion }; +var o6 = { ...nullAndUndefinedUnion }; + +//// [spreadUnion2.js] +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +var o1; +var o1 = __assign({}, undefinedUnion); +var o2; +var o2 = __assign({}, nullUnion); +var o3; +var o3 = __assign({}, undefinedUnion, nullUnion); +var o3 = __assign({}, nullUnion, undefinedUnion); +var o4; +var o4 = __assign({}, undefinedUnion, undefinedUnion); +var o5; +var o5 = __assign({}, nullUnion, nullUnion); +var o6; +var o6 = __assign({}, nullAndUndefinedUnion, nullAndUndefinedUnion); +var o6 = __assign({}, nullAndUndefinedUnion); diff --git a/tests/baselines/reference/spreadUnion2.symbols b/tests/baselines/reference/spreadUnion2.symbols new file mode 100644 index 00000000000..cc2c194f2a6 --- /dev/null +++ b/tests/baselines/reference/spreadUnion2.symbols @@ -0,0 +1,74 @@ +=== tests/cases/compiler/spreadUnion2.ts === + +declare const undefinedUnion: { a: number } | undefined; +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) +>a : Symbol(a, Decl(spreadUnion2.ts, 1, 31)) + +declare const nullUnion: { b: number } | null; +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) +>b : Symbol(b, Decl(spreadUnion2.ts, 2, 26)) + +declare const nullAndUndefinedUnion: null | undefined; +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(spreadUnion2.ts, 3, 13)) + +var o1: { a: number }; +>o1 : Symbol(o1, Decl(spreadUnion2.ts, 5, 3), Decl(spreadUnion2.ts, 6, 3)) +>a : Symbol(a, Decl(spreadUnion2.ts, 5, 9)) + +var o1 = { ...undefinedUnion }; +>o1 : Symbol(o1, Decl(spreadUnion2.ts, 5, 3), Decl(spreadUnion2.ts, 6, 3)) +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) + +var o2: { b: number }; +>o2 : Symbol(o2, Decl(spreadUnion2.ts, 8, 3), Decl(spreadUnion2.ts, 9, 3)) +>b : Symbol(b, Decl(spreadUnion2.ts, 8, 9)) + +var o2 = { ...nullUnion }; +>o2 : Symbol(o2, Decl(spreadUnion2.ts, 8, 3), Decl(spreadUnion2.ts, 9, 3)) +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) + +var o3: { a: number, b: number }; +>o3 : Symbol(o3, Decl(spreadUnion2.ts, 11, 3), Decl(spreadUnion2.ts, 12, 3), Decl(spreadUnion2.ts, 13, 3)) +>a : Symbol(a, Decl(spreadUnion2.ts, 11, 9)) +>b : Symbol(b, Decl(spreadUnion2.ts, 11, 20)) + +var o3 = { ...undefinedUnion, ...nullUnion }; +>o3 : Symbol(o3, Decl(spreadUnion2.ts, 11, 3), Decl(spreadUnion2.ts, 12, 3), Decl(spreadUnion2.ts, 13, 3)) +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) + +var o3 = { ...nullUnion, ...undefinedUnion }; +>o3 : Symbol(o3, Decl(spreadUnion2.ts, 11, 3), Decl(spreadUnion2.ts, 12, 3), Decl(spreadUnion2.ts, 13, 3)) +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) + +var o4: { a: number }; +>o4 : Symbol(o4, Decl(spreadUnion2.ts, 15, 3), Decl(spreadUnion2.ts, 16, 3)) +>a : Symbol(a, Decl(spreadUnion2.ts, 15, 9)) + +var o4 = { ...undefinedUnion, ...undefinedUnion }; +>o4 : Symbol(o4, Decl(spreadUnion2.ts, 15, 3), Decl(spreadUnion2.ts, 16, 3)) +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) +>undefinedUnion : Symbol(undefinedUnion, Decl(spreadUnion2.ts, 1, 13)) + +var o5: { b: number }; +>o5 : Symbol(o5, Decl(spreadUnion2.ts, 18, 3), Decl(spreadUnion2.ts, 19, 3)) +>b : Symbol(b, Decl(spreadUnion2.ts, 18, 9)) + +var o5 = { ...nullUnion, ...nullUnion }; +>o5 : Symbol(o5, Decl(spreadUnion2.ts, 18, 3), Decl(spreadUnion2.ts, 19, 3)) +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) +>nullUnion : Symbol(nullUnion, Decl(spreadUnion2.ts, 2, 13)) + +var o6: { }; +>o6 : Symbol(o6, Decl(spreadUnion2.ts, 21, 3), Decl(spreadUnion2.ts, 22, 3), Decl(spreadUnion2.ts, 23, 3)) + +var o6 = { ...nullAndUndefinedUnion, ...nullAndUndefinedUnion }; +>o6 : Symbol(o6, Decl(spreadUnion2.ts, 21, 3), Decl(spreadUnion2.ts, 22, 3), Decl(spreadUnion2.ts, 23, 3)) +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(spreadUnion2.ts, 3, 13)) +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(spreadUnion2.ts, 3, 13)) + +var o6 = { ...nullAndUndefinedUnion }; +>o6 : Symbol(o6, Decl(spreadUnion2.ts, 21, 3), Decl(spreadUnion2.ts, 22, 3), Decl(spreadUnion2.ts, 23, 3)) +>nullAndUndefinedUnion : Symbol(nullAndUndefinedUnion, Decl(spreadUnion2.ts, 3, 13)) + diff --git a/tests/baselines/reference/spreadUnion2.types b/tests/baselines/reference/spreadUnion2.types new file mode 100644 index 00000000000..cf90381ca77 --- /dev/null +++ b/tests/baselines/reference/spreadUnion2.types @@ -0,0 +1,84 @@ +=== tests/cases/compiler/spreadUnion2.ts === + +declare const undefinedUnion: { a: number } | undefined; +>undefinedUnion : { a: number; } | undefined +>a : number + +declare const nullUnion: { b: number } | null; +>nullUnion : { b: number; } | null +>b : number +>null : null + +declare const nullAndUndefinedUnion: null | undefined; +>nullAndUndefinedUnion : null | undefined +>null : null + +var o1: { a: number }; +>o1 : { a: number; } +>a : number + +var o1 = { ...undefinedUnion }; +>o1 : { a: number; } +>{ ...undefinedUnion } : { a: number; } +>undefinedUnion : { a: number; } | undefined + +var o2: { b: number }; +>o2 : { b: number; } +>b : number + +var o2 = { ...nullUnion }; +>o2 : { b: number; } +>{ ...nullUnion } : { b: number; } +>nullUnion : { b: number; } | null + +var o3: { a: number, b: number }; +>o3 : { a: number; b: number; } +>a : number +>b : number + +var o3 = { ...undefinedUnion, ...nullUnion }; +>o3 : { a: number; b: number; } +>{ ...undefinedUnion, ...nullUnion } : { b: number; a: number; } +>undefinedUnion : { a: number; } | undefined +>nullUnion : { b: number; } | null + +var o3 = { ...nullUnion, ...undefinedUnion }; +>o3 : { a: number; b: number; } +>{ ...nullUnion, ...undefinedUnion } : { a: number; b: number; } +>nullUnion : { b: number; } | null +>undefinedUnion : { a: number; } | undefined + +var o4: { a: number }; +>o4 : { a: number; } +>a : number + +var o4 = { ...undefinedUnion, ...undefinedUnion }; +>o4 : { a: number; } +>{ ...undefinedUnion, ...undefinedUnion } : { a: number; } +>undefinedUnion : { a: number; } | undefined +>undefinedUnion : { a: number; } | undefined + +var o5: { b: number }; +>o5 : { b: number; } +>b : number + +var o5 = { ...nullUnion, ...nullUnion }; +>o5 : { b: number; } +>{ ...nullUnion, ...nullUnion } : { b: number; } +>nullUnion : { b: number; } | null +>nullUnion : { b: number; } | null + +var o6: { }; +>o6 : {} + +var o6 = { ...nullAndUndefinedUnion, ...nullAndUndefinedUnion }; +>o6 : {} +>{ ...nullAndUndefinedUnion, ...nullAndUndefinedUnion } : {} +>nullAndUndefinedUnion : null | undefined +>nullAndUndefinedUnion : null | undefined + +var o6 = { ...nullAndUndefinedUnion }; +>o6 : {} +>{ ...nullAndUndefinedUnion } : {} +>nullAndUndefinedUnion : null | undefined + diff --git a/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt b/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt index 0dff64c9a31..fafffb563ea 100644 --- a/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt +++ b/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt @@ -16,9 +16,9 @@ tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(21,9): error TS tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(21,17): error TS1213: Identifier expected. 'private' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(23,20): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS2693: 'public' only refers to a type, but is being used as a value here. +tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS2702: 'public' only refers to a type, but is being used as a namespace here. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS2693: 'public' only refers to a type, but is being used as a value here. +tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS2702: 'public' only refers to a type, but is being used as a namespace here. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(27,17): error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(27,17): error TS2304: Cannot find name 'package'. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. @@ -88,12 +88,12 @@ tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error T ~~~~~~ !!! error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. ~~~~~~ -!!! error TS2693: 'public' only refers to a type, but is being used as a value here. +!!! error TS2702: 'public' only refers to a type, but is being used as a namespace here. class F1 implements public.private.implements { } ~~~~~~ !!! error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. ~~~~~~ -!!! error TS2693: 'public' only refers to a type, but is being used as a value here. +!!! error TS2702: 'public' only refers to a type, but is being used as a namespace here. class G extends package { } ~~~~~~~ !!! error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. diff --git a/tests/baselines/reference/strictNullChecksNoWidening.types b/tests/baselines/reference/strictNullChecksNoWidening.types index 375977ae375..a544f9cef94 100644 --- a/tests/baselines/reference/strictNullChecksNoWidening.types +++ b/tests/baselines/reference/strictNullChecksNoWidening.types @@ -1,11 +1,11 @@ === tests/cases/conformance/types/typeRelationships/widenedTypes/strictNullChecksNoWidening.ts === var a1 = null; ->a1 : any +>a1 : null >null : null var a2 = undefined; ->a2 : any +>a2 : undefined >undefined : undefined var a3 = void 0; diff --git a/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.js b/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.js index 78417b9a082..55ea1335771 100644 --- a/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.js +++ b/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.js @@ -120,7 +120,7 @@ var C = (function () { C.prototype.concat = function () { var strings = []; for (var _i = 0; _i < arguments.length; _i++) { - strings[_i - 0] = arguments[_i]; + strings[_i] = arguments[_i]; } return null; }; diff --git a/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types b/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types index 0be891ade44..85378108298 100644 --- a/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types +++ b/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types @@ -19,7 +19,7 @@ if (x === "foo") { let a = x; >a : string ->x : string +>x : "foo" } else if (x !== "bar") { >x !== "bar" : boolean @@ -35,7 +35,7 @@ else if (x !== "bar") { else { let c = x; >c : string ->x : string +>x : "bar" let d = y; >d : string @@ -43,7 +43,7 @@ else { let e: (typeof x) | (typeof y) = c || d; >e : string ->x : string +>x : "bar" >y : string >c || d : string >c : string diff --git a/tests/baselines/reference/stringLiteralTypesOverloads03.js b/tests/baselines/reference/stringLiteralTypesOverloads03.js index c1e79160880..4fdfd4f85d0 100644 --- a/tests/baselines/reference/stringLiteralTypesOverloads03.js +++ b/tests/baselines/reference/stringLiteralTypesOverloads03.js @@ -52,7 +52,7 @@ var helloOrWorld; function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return undefined; } @@ -62,7 +62,7 @@ var fResult3 = f(helloOrWorld); function g() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return undefined; } diff --git a/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt b/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt index a51469baa93..a4944f7f163 100644 --- a/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt +++ b/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt @@ -7,12 +7,11 @@ tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperato tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(13,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(14,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(15,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(16,9): error TS2365: Operator '<' cannot be applied to types '"ABC"' and '"XYZ"'. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(17,9): error TS2365: Operator '===' cannot be applied to types '"ABC"' and '"XYZ"'. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(18,9): error TS2365: Operator '!=' cannot be applied to types '"ABC"' and '"XYZ"'. -==== tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts (12 errors) ==== +==== tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts (11 errors) ==== let abc: "ABC" = "ABC"; let xyz: "XYZ" = "XYZ"; @@ -47,8 +46,6 @@ tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperato ~~~~~~~~~~~~~~~~ !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. let j = abc < xyz; - ~~~~~~~~~ -!!! error TS2365: Operator '<' cannot be applied to types '"ABC"' and '"XYZ"'. let k = abc === xyz; ~~~~~~~~~~~ !!! error TS2365: Operator '===' cannot be applied to types '"ABC"' and '"XYZ"'. diff --git a/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.js b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.js new file mode 100644 index 00000000000..15d6fc70da5 --- /dev/null +++ b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.js @@ -0,0 +1,51 @@ +//// [subSubClassCanAccessProtectedConstructor.ts] +class Base { + protected constructor() { } + public instance1 = new Base(); // allowed +} + +class Subclass extends Base { + public instance1_1 = new Base(); // allowed + public instance1_2 = new Subclass(); // allowed +} + +class SubclassOfSubclass extends Subclass { + public instance2_1 = new Base(); // allowed + public instance2_2 = new Subclass(); // allowed + public instance2_3 = new SubclassOfSubclass(); // allowed +} + + +//// [subSubClassCanAccessProtectedConstructor.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Base = (function () { + function Base() { + this.instance1 = new Base(); // allowed + } + return Base; +}()); +var Subclass = (function (_super) { + __extends(Subclass, _super); + function Subclass() { + var _this = _super.apply(this, arguments) || this; + _this.instance1_1 = new Base(); // allowed + _this.instance1_2 = new Subclass(); // allowed + return _this; + } + return Subclass; +}(Base)); +var SubclassOfSubclass = (function (_super) { + __extends(SubclassOfSubclass, _super); + function SubclassOfSubclass() { + var _this = _super.apply(this, arguments) || this; + _this.instance2_1 = new Base(); // allowed + _this.instance2_2 = new Subclass(); // allowed + _this.instance2_3 = new SubclassOfSubclass(); // allowed + return _this; + } + return SubclassOfSubclass; +}(Subclass)); diff --git a/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.symbols b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.symbols new file mode 100644 index 00000000000..8a09e1d742f --- /dev/null +++ b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.symbols @@ -0,0 +1,40 @@ +=== tests/cases/compiler/subSubClassCanAccessProtectedConstructor.ts === +class Base { +>Base : Symbol(Base, Decl(subSubClassCanAccessProtectedConstructor.ts, 0, 0)) + + protected constructor() { } + public instance1 = new Base(); // allowed +>instance1 : Symbol(Base.instance1, Decl(subSubClassCanAccessProtectedConstructor.ts, 1, 31)) +>Base : Symbol(Base, Decl(subSubClassCanAccessProtectedConstructor.ts, 0, 0)) +} + +class Subclass extends Base { +>Subclass : Symbol(Subclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 3, 1)) +>Base : Symbol(Base, Decl(subSubClassCanAccessProtectedConstructor.ts, 0, 0)) + + public instance1_1 = new Base(); // allowed +>instance1_1 : Symbol(Subclass.instance1_1, Decl(subSubClassCanAccessProtectedConstructor.ts, 5, 29)) +>Base : Symbol(Base, Decl(subSubClassCanAccessProtectedConstructor.ts, 0, 0)) + + public instance1_2 = new Subclass(); // allowed +>instance1_2 : Symbol(Subclass.instance1_2, Decl(subSubClassCanAccessProtectedConstructor.ts, 6, 36)) +>Subclass : Symbol(Subclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 3, 1)) +} + +class SubclassOfSubclass extends Subclass { +>SubclassOfSubclass : Symbol(SubclassOfSubclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 8, 1)) +>Subclass : Symbol(Subclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 3, 1)) + + public instance2_1 = new Base(); // allowed +>instance2_1 : Symbol(SubclassOfSubclass.instance2_1, Decl(subSubClassCanAccessProtectedConstructor.ts, 10, 43)) +>Base : Symbol(Base, Decl(subSubClassCanAccessProtectedConstructor.ts, 0, 0)) + + public instance2_2 = new Subclass(); // allowed +>instance2_2 : Symbol(SubclassOfSubclass.instance2_2, Decl(subSubClassCanAccessProtectedConstructor.ts, 11, 36)) +>Subclass : Symbol(Subclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 3, 1)) + + public instance2_3 = new SubclassOfSubclass(); // allowed +>instance2_3 : Symbol(SubclassOfSubclass.instance2_3, Decl(subSubClassCanAccessProtectedConstructor.ts, 12, 40)) +>SubclassOfSubclass : Symbol(SubclassOfSubclass, Decl(subSubClassCanAccessProtectedConstructor.ts, 8, 1)) +} + diff --git a/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.types b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.types new file mode 100644 index 00000000000..253f6221c78 --- /dev/null +++ b/tests/baselines/reference/subSubClassCanAccessProtectedConstructor.types @@ -0,0 +1,46 @@ +=== tests/cases/compiler/subSubClassCanAccessProtectedConstructor.ts === +class Base { +>Base : Base + + protected constructor() { } + public instance1 = new Base(); // allowed +>instance1 : Base +>new Base() : Base +>Base : typeof Base +} + +class Subclass extends Base { +>Subclass : Subclass +>Base : Base + + public instance1_1 = new Base(); // allowed +>instance1_1 : Base +>new Base() : Base +>Base : typeof Base + + public instance1_2 = new Subclass(); // allowed +>instance1_2 : Subclass +>new Subclass() : Subclass +>Subclass : typeof Subclass +} + +class SubclassOfSubclass extends Subclass { +>SubclassOfSubclass : SubclassOfSubclass +>Subclass : Subclass + + public instance2_1 = new Base(); // allowed +>instance2_1 : Base +>new Base() : Base +>Base : typeof Base + + public instance2_2 = new Subclass(); // allowed +>instance2_2 : Subclass +>new Subclass() : Subclass +>Subclass : typeof Subclass + + public instance2_3 = new SubclassOfSubclass(); // allowed +>instance2_3 : SubclassOfSubclass +>new SubclassOfSubclass() : SubclassOfSubclass +>SubclassOfSubclass : typeof SubclassOfSubclass +} + diff --git a/tests/baselines/reference/subtypingWithCallSignatures2.js b/tests/baselines/reference/subtypingWithCallSignatures2.js index 843a727c33e..3b5fada2012 100644 --- a/tests/baselines/reference/subtypingWithCallSignatures2.js +++ b/tests/baselines/reference/subtypingWithCallSignatures2.js @@ -253,14 +253,14 @@ var r9b = [r9arg2, r9arg1]; var r10arg1 = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } return x[0]; }; var r10arg2 = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } return null; }; diff --git a/tests/baselines/reference/subtypingWithCallSignatures3.js b/tests/baselines/reference/subtypingWithCallSignatures3.js index a9e7d01aab6..4ac7d3a7f24 100644 --- a/tests/baselines/reference/subtypingWithCallSignatures3.js +++ b/tests/baselines/reference/subtypingWithCallSignatures3.js @@ -170,14 +170,14 @@ var Errors; var r4arg = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } return null; }; var r4arg2 = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } return null; }; diff --git a/tests/baselines/reference/super1.js b/tests/baselines/reference/super1.js index 9f1289dce55..0094f696faf 100644 --- a/tests/baselines/reference/super1.js +++ b/tests/baselines/reference/super1.js @@ -97,7 +97,7 @@ var SubSub1 = (function (_super) { return _super.apply(this, arguments) || this; } SubSub1.prototype.bar = function () { - return _super.prototype.super.foo; + return _super.prototype["super"].foo; }; return SubSub1; }(Sub1)); diff --git a/tests/baselines/reference/superAccess2.errors.txt b/tests/baselines/reference/superAccess2.errors.txt index d8b39284f65..edcd4031c47 100644 --- a/tests/baselines/reference/superAccess2.errors.txt +++ b/tests/baselines/reference/superAccess2.errors.txt @@ -2,10 +2,13 @@ tests/cases/compiler/superAccess2.ts(7,15): error TS1034: 'super' must be follow tests/cases/compiler/superAccess2.ts(8,17): error TS2338: 'super' property access is permitted only in a constructor, member function, or member accessor of a derived class. tests/cases/compiler/superAccess2.ts(8,22): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/compiler/superAccess2.ts(11,28): error TS2336: 'super' cannot be referenced in constructor arguments. +tests/cases/compiler/superAccess2.ts(11,28): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superAccess2.ts(11,33): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/compiler/superAccess2.ts(11,40): error TS2336: 'super' cannot be referenced in constructor arguments. +tests/cases/compiler/superAccess2.ts(11,40): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superAccess2.ts(11,45): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/compiler/superAccess2.ts(11,59): error TS2336: 'super' cannot be referenced in constructor arguments. +tests/cases/compiler/superAccess2.ts(11,59): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superAccess2.ts(11,64): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/compiler/superAccess2.ts(15,19): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/compiler/superAccess2.ts(17,15): error TS2339: Property 'y' does not exist on type 'P'. @@ -13,7 +16,7 @@ tests/cases/compiler/superAccess2.ts(20,26): error TS1034: 'super' must be follo tests/cases/compiler/superAccess2.ts(21,15): error TS2339: Property 'x' does not exist on type 'typeof P'. -==== tests/cases/compiler/superAccess2.ts (13 errors) ==== +==== tests/cases/compiler/superAccess2.ts (16 errors) ==== class P { x() { } static y() { } @@ -33,14 +36,20 @@ tests/cases/compiler/superAccess2.ts(21,15): error TS2339: Property 'x' does not constructor(public z = super, zz = super, zzz = () => super) { ~~~~~ !!! error TS2336: 'super' cannot be referenced in constructor arguments. + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. ~~~~~ !!! error TS2336: 'super' cannot be referenced in constructor arguments. + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. ~~~~~ !!! error TS2336: 'super' cannot be referenced in constructor arguments. + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. super(); diff --git a/tests/baselines/reference/superCallBeforeThisAccessing2.js b/tests/baselines/reference/superCallBeforeThisAccessing2.js index 7331718a9ed..91cc3d28dd6 100644 --- a/tests/baselines/reference/superCallBeforeThisAccessing2.js +++ b/tests/baselines/reference/superCallBeforeThisAccessing2.js @@ -24,7 +24,8 @@ var Base = (function () { var D = (function (_super) { __extends(D, _super); function D() { - return _super.call(this, function () { _this._t; }) || this; + var _this = _super.call(this, function () { _this._t; }) || this; + return _this; } return D; }(Base)); diff --git a/tests/baselines/reference/superCallBeforeThisAccessing6.js b/tests/baselines/reference/superCallBeforeThisAccessing6.js index e4dfb3f714a..4eb8e5266c2 100644 --- a/tests/baselines/reference/superCallBeforeThisAccessing6.js +++ b/tests/baselines/reference/superCallBeforeThisAccessing6.js @@ -24,7 +24,8 @@ var Base = (function () { var D = (function (_super) { __extends(D, _super); function D() { - return _super.call(this, this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return D; }(Base)); diff --git a/tests/baselines/reference/superCallWithCommentEmit01.js b/tests/baselines/reference/superCallWithCommentEmit01.js new file mode 100644 index 00000000000..c7ea3cc8b85 --- /dev/null +++ b/tests/baselines/reference/superCallWithCommentEmit01.js @@ -0,0 +1,32 @@ +//// [superCallWithCommentEmit01.ts] +class A { + constructor(public text: string) { } +} + +class B extends A { + constructor(text: string) { + // this is subclass constructor + super(text) + } +} + +//// [superCallWithCommentEmit01.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var A = (function () { + function A(text) { + this.text = text; + } + return A; +}()); +var B = (function (_super) { + __extends(B, _super); + function B(text) { + // this is subclass constructor + return _super.call(this, text) || this; + } + return B; +}(A)); diff --git a/tests/baselines/reference/superCallWithCommentEmit01.symbols b/tests/baselines/reference/superCallWithCommentEmit01.symbols new file mode 100644 index 00000000000..9476ee1c4e5 --- /dev/null +++ b/tests/baselines/reference/superCallWithCommentEmit01.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/superCallWithCommentEmit01.ts === +class A { +>A : Symbol(A, Decl(superCallWithCommentEmit01.ts, 0, 0)) + + constructor(public text: string) { } +>text : Symbol(A.text, Decl(superCallWithCommentEmit01.ts, 1, 16)) +} + +class B extends A { +>B : Symbol(B, Decl(superCallWithCommentEmit01.ts, 2, 1)) +>A : Symbol(A, Decl(superCallWithCommentEmit01.ts, 0, 0)) + + constructor(text: string) { +>text : Symbol(text, Decl(superCallWithCommentEmit01.ts, 5, 16)) + + // this is subclass constructor + super(text) +>super : Symbol(A, Decl(superCallWithCommentEmit01.ts, 0, 0)) +>text : Symbol(text, Decl(superCallWithCommentEmit01.ts, 5, 16)) + } +} diff --git a/tests/baselines/reference/superCallWithCommentEmit01.types b/tests/baselines/reference/superCallWithCommentEmit01.types new file mode 100644 index 00000000000..dfa0b1ce333 --- /dev/null +++ b/tests/baselines/reference/superCallWithCommentEmit01.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/superCallWithCommentEmit01.ts === +class A { +>A : A + + constructor(public text: string) { } +>text : string +} + +class B extends A { +>B : B +>A : A + + constructor(text: string) { +>text : string + + // this is subclass constructor + super(text) +>super(text) : void +>super : typeof A +>text : string + } +} diff --git a/tests/baselines/reference/superInConstructorParam1.errors.txt b/tests/baselines/reference/superInConstructorParam1.errors.txt index 96735c92547..4220fcb9b0e 100644 --- a/tests/baselines/reference/superInConstructorParam1.errors.txt +++ b/tests/baselines/reference/superInConstructorParam1.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/superInConstructorParam1.ts(8,3): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/superInConstructorParam1.ts(8,19): error TS2336: 'super' cannot be referenced in constructor arguments. +tests/cases/compiler/superInConstructorParam1.ts(8,19): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. -==== tests/cases/compiler/superInConstructorParam1.ts (2 errors) ==== +==== tests/cases/compiler/superInConstructorParam1.ts (3 errors) ==== class B { public foo(): number { return 0; @@ -14,6 +15,8 @@ tests/cases/compiler/superInConstructorParam1.ts(8,19): error TS2336: 'super' ca ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~ !!! error TS2336: 'super' cannot be referenced in constructor arguments. + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. } ~~~ !!! error TS2377: Constructors for derived classes must contain a 'super' call. diff --git a/tests/baselines/reference/superNewCall1.errors.txt b/tests/baselines/reference/superNewCall1.errors.txt index 2b104e7d647..c8fd5c471fb 100644 --- a/tests/baselines/reference/superNewCall1.errors.txt +++ b/tests/baselines/reference/superNewCall1.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/superNewCall1.ts(9,5): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/superNewCall1.ts(10,9): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +tests/cases/compiler/superNewCall1.ts(10,13): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. -==== tests/cases/compiler/superNewCall1.ts (2 errors) ==== +==== tests/cases/compiler/superNewCall1.ts (3 errors) ==== class A { constructor(private map: (value: T1) => T2) { @@ -17,6 +18,8 @@ tests/cases/compiler/superNewCall1.ts(10,9): error TS2351: Cannot use 'new' with ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. } ~~~~~ !!! error TS2377: Constructors for derived classes must contain a 'super' call. diff --git a/tests/baselines/reference/superPropertyAccessInSuperCall01.errors.txt b/tests/baselines/reference/superPropertyAccessInSuperCall01.errors.txt new file mode 100644 index 00000000000..f7449a26d5a --- /dev/null +++ b/tests/baselines/reference/superPropertyAccessInSuperCall01.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/superPropertyAccessInSuperCall01.ts(9,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + + +==== tests/cases/compiler/superPropertyAccessInSuperCall01.ts (1 errors) ==== + class A { + constructor(f: string) { + } + public blah(): string { return ""; } + } + + class B extends A { + constructor() { + super(super.blah()) + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/superPropertyAccessInSuperCall01.js b/tests/baselines/reference/superPropertyAccessInSuperCall01.js new file mode 100644 index 00000000000..f0dc925682c --- /dev/null +++ b/tests/baselines/reference/superPropertyAccessInSuperCall01.js @@ -0,0 +1,33 @@ +//// [superPropertyAccessInSuperCall01.ts] +class A { + constructor(f: string) { + } + public blah(): string { return ""; } +} + +class B extends A { + constructor() { + super(super.blah()) + } +} + +//// [superPropertyAccessInSuperCall01.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var A = (function () { + function A(f) { + } + A.prototype.blah = function () { return ""; }; + return A; +}()); +var B = (function (_super) { + __extends(B, _super); + function B() { + var _this = _super.call(this, _super.blah.call(_this)) || this; + return _this; + } + return B; +}(A)); diff --git a/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.errors.txt b/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.errors.txt new file mode 100644 index 00000000000..407e984c5d1 --- /dev/null +++ b/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.errors.txt @@ -0,0 +1,24 @@ +tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts(7,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. +tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts(13,15): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + + +==== tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts (2 errors) ==== + class B { + constructor(x?: string) {} + x(): string { return ""; } + } + class C1 extends B { + constructor() { + super.x(); + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + super(); + } + } + class C2 extends B { + constructor() { + super(super.x()); + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.js b/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.js new file mode 100644 index 00000000000..3fcf7167ee5 --- /dev/null +++ b/tests/baselines/reference/superPropertyInConstructorBeforeSuperCall.js @@ -0,0 +1,47 @@ +//// [superPropertyInConstructorBeforeSuperCall.ts] +class B { + constructor(x?: string) {} + x(): string { return ""; } +} +class C1 extends B { + constructor() { + super.x(); + super(); + } +} +class C2 extends B { + constructor() { + super(super.x()); + } +} + +//// [superPropertyInConstructorBeforeSuperCall.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var B = (function () { + function B(x) { + } + B.prototype.x = function () { return ""; }; + return B; +}()); +var C1 = (function (_super) { + __extends(C1, _super); + function C1() { + var _this; + _super.prototype.x.call(_this); + _this = _super.call(this) || this; + return _this; + } + return C1; +}(B)); +var C2 = (function (_super) { + __extends(C2, _super); + function C2() { + var _this = _super.call(this, _super.x.call(_this)) || this; + return _this; + } + return C2; +}(B)); diff --git a/tests/baselines/reference/superSymbolIndexedAccess3.errors.txt b/tests/baselines/reference/superSymbolIndexedAccess3.errors.txt index 1cac31dec40..a7011e66910 100644 --- a/tests/baselines/reference/superSymbolIndexedAccess3.errors.txt +++ b/tests/baselines/reference/superSymbolIndexedAccess3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/expressions/superPropertyAccess/superSymbolIndexedAccess3.ts(11,16): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/conformance/expressions/superPropertyAccess/superSymbolIndexedAccess3.ts(11,22): error TS2538: Type 'typeof Bar' cannot be used as an index type. ==== tests/cases/conformance/expressions/superPropertyAccess/superSymbolIndexedAccess3.ts (1 errors) ==== @@ -13,7 +13,7 @@ tests/cases/conformance/expressions/superPropertyAccess/superSymbolIndexedAccess class Bar extends Foo { [symbol]() { return super[Bar](); - ~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. + ~~~ +!!! error TS2538: Type 'typeof Bar' cannot be used as an index type. } } \ No newline at end of file diff --git a/tests/baselines/reference/superWithTypeArgument.errors.txt b/tests/baselines/reference/superWithTypeArgument.errors.txt index d749cbd5157..5860cb466d9 100644 --- a/tests/baselines/reference/superWithTypeArgument.errors.txt +++ b/tests/baselines/reference/superWithTypeArgument.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/superWithTypeArgument.ts(6,5): error TS2377: Constructors for derived classes must contain a 'super' call. +tests/cases/compiler/superWithTypeArgument.ts(7,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superWithTypeArgument.ts(7,14): error TS1034: 'super' must be followed by an argument list or member access. -==== tests/cases/compiler/superWithTypeArgument.ts (2 errors) ==== +==== tests/cases/compiler/superWithTypeArgument.ts (3 errors) ==== class C { } @@ -12,6 +13,8 @@ tests/cases/compiler/superWithTypeArgument.ts(7,14): error TS1034: 'super' must ~~~~~~~~~~~~~~~ super(); ~~~~~~~~~~~~~~~~~~~ + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. } diff --git a/tests/baselines/reference/superWithTypeArgument2.errors.txt b/tests/baselines/reference/superWithTypeArgument2.errors.txt index 766327c5c81..473e7f3b7ad 100644 --- a/tests/baselines/reference/superWithTypeArgument2.errors.txt +++ b/tests/baselines/reference/superWithTypeArgument2.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/superWithTypeArgument2.ts(6,5): error TS2377: Constructors for derived classes must contain a 'super' call. +tests/cases/compiler/superWithTypeArgument2.ts(7,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superWithTypeArgument2.ts(7,14): error TS1034: 'super' must be followed by an argument list or member access. -==== tests/cases/compiler/superWithTypeArgument2.ts (2 errors) ==== +==== tests/cases/compiler/superWithTypeArgument2.ts (3 errors) ==== class C { foo: T; } @@ -12,6 +13,8 @@ tests/cases/compiler/superWithTypeArgument2.ts(7,14): error TS1034: 'super' must ~~~~~~~~~~~~~~~~ super(x); ~~~~~~~~~~~~~~~~~~~~ + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. } diff --git a/tests/baselines/reference/superWithTypeArgument3.errors.txt b/tests/baselines/reference/superWithTypeArgument3.errors.txt index 323b2958fcb..37e6681d770 100644 --- a/tests/baselines/reference/superWithTypeArgument3.errors.txt +++ b/tests/baselines/reference/superWithTypeArgument3.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/superWithTypeArgument3.ts(7,5): error TS2377: Constructors for derived classes must contain a 'super' call. +tests/cases/compiler/superWithTypeArgument3.ts(8,9): error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. tests/cases/compiler/superWithTypeArgument3.ts(8,14): error TS1034: 'super' must be followed by an argument list or member access. -==== tests/cases/compiler/superWithTypeArgument3.ts (2 errors) ==== +==== tests/cases/compiler/superWithTypeArgument3.ts (3 errors) ==== class C { foo: T; bar(x: U) { } @@ -13,6 +14,8 @@ tests/cases/compiler/superWithTypeArgument3.ts(8,14): error TS1034: 'super' must ~~~~~~~~~~~~~~~ super(); ~~~~~~~~~~~~~~~~~~~ + ~~~~~ +!!! error TS17011: 'super' must be called before accessing a property of 'super' in the constructor of a derived class. ~ !!! error TS1034: 'super' must be followed by an argument list or member access. } diff --git a/tests/baselines/reference/switchAssignmentCompat.errors.txt b/tests/baselines/reference/switchAssignmentCompat.errors.txt index 46c89fa5b52..747a1035b68 100644 --- a/tests/baselines/reference/switchAssignmentCompat.errors.txt +++ b/tests/baselines/reference/switchAssignmentCompat.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/switchAssignmentCompat.ts(4,10): error TS2678: Type 'typeof Foo' is not comparable to type '0'. +tests/cases/compiler/switchAssignmentCompat.ts(4,10): error TS2678: Type 'typeof Foo' is not comparable to type 'number'. ==== tests/cases/compiler/switchAssignmentCompat.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/switchAssignmentCompat.ts(4,10): error TS2678: Type 'typeof switch (0) { case Foo: break; // Error expected ~~~ -!!! error TS2678: Type 'typeof Foo' is not comparable to type '0'. +!!! error TS2678: Type 'typeof Foo' is not comparable to type 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/switchCaseCircularRefeference.errors.txt b/tests/baselines/reference/switchCaseCircularRefeference.errors.txt index 9ee571de468..bc576f8e723 100644 --- a/tests/baselines/reference/switchCaseCircularRefeference.errors.txt +++ b/tests/baselines/reference/switchCaseCircularRefeference.errors.txt @@ -1,6 +1,5 @@ -tests/cases/compiler/switchCaseCircularRefeference.ts(5,10): error TS2678: Type '{ a: "A"; b: any; } | { a: "C"; e: any; }' is not comparable to type '"A" | "C"'. - Type '{ a: "C"; e: any; }' is not comparable to type '"A" | "C"'. - Type '{ a: "C"; e: any; }' is not comparable to type '"C"'. +tests/cases/compiler/switchCaseCircularRefeference.ts(5,10): error TS2678: Type '{ a: "A"; b: any; } | { a: "C"; e: any; }' is not comparable to type 'string'. + Type '{ a: "C"; e: any; }' is not comparable to type 'string'. ==== tests/cases/compiler/switchCaseCircularRefeference.ts (1 errors) ==== @@ -10,9 +9,8 @@ tests/cases/compiler/switchCaseCircularRefeference.ts(5,10): error TS2678: Type switch (x.a) { case x: ~ -!!! error TS2678: Type '{ a: "A"; b: any; } | { a: "C"; e: any; }' is not comparable to type '"A" | "C"'. -!!! error TS2678: Type '{ a: "C"; e: any; }' is not comparable to type '"A" | "C"'. -!!! error TS2678: Type '{ a: "C"; e: any; }' is not comparable to type '"C"'. +!!! error TS2678: Type '{ a: "A"; b: any; } | { a: "C"; e: any; }' is not comparable to type 'string'. +!!! error TS2678: Type '{ a: "C"; e: any; }' is not comparable to type 'string'. break; } } \ No newline at end of file diff --git a/tests/baselines/reference/switchCaseWithIntersectionTypes01.errors.txt b/tests/baselines/reference/switchCaseWithIntersectionTypes01.errors.txt index ad2ca8bc123..d31a005842c 100644 --- a/tests/baselines/reference/switchCaseWithIntersectionTypes01.errors.txt +++ b/tests/baselines/reference/switchCaseWithIntersectionTypes01.errors.txt @@ -1,5 +1,6 @@ -tests/cases/conformance/types/typeRelationships/comparable/switchCaseWithIntersectionTypes01.ts(19,10): error TS2678: Type 'number & boolean' is not comparable to type 'string & number'. - Type 'number & boolean' is not comparable to type 'string'. +tests/cases/conformance/types/typeRelationships/comparable/switchCaseWithIntersectionTypes01.ts(19,10): error TS2678: Type '(number & true) | (number & false)' is not comparable to type 'string & number'. + Type 'number & false' is not comparable to type 'string & number'. + Type 'number & false' is not comparable to type 'string'. tests/cases/conformance/types/typeRelationships/comparable/switchCaseWithIntersectionTypes01.ts(23,10): error TS2678: Type 'boolean' is not comparable to type 'string & number'. @@ -24,8 +25,9 @@ tests/cases/conformance/types/typeRelationships/comparable/switchCaseWithInterse // Overlap in constituents case numAndBool: ~~~~~~~~~~ -!!! error TS2678: Type 'number & boolean' is not comparable to type 'string & number'. -!!! error TS2678: Type 'number & boolean' is not comparable to type 'string'. +!!! error TS2678: Type '(number & true) | (number & false)' is not comparable to type 'string & number'. +!!! error TS2678: Type 'number & false' is not comparable to type 'string & number'. +!!! error TS2678: Type 'number & false' is not comparable to type 'string'. break; // No relation diff --git a/tests/baselines/reference/switchCasesExpressionTypeMismatch.errors.txt b/tests/baselines/reference/switchCasesExpressionTypeMismatch.errors.txt index 3ea12e2460f..7a5fd12182e 100644 --- a/tests/baselines/reference/switchCasesExpressionTypeMismatch.errors.txt +++ b/tests/baselines/reference/switchCasesExpressionTypeMismatch.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(4,10): error TS2678: Type 'typeof Foo' is not comparable to type '0'. +tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(4,10): error TS2678: Type 'typeof Foo' is not comparable to type 'number'. tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(5,10): error TS2678: Type '"sss"' is not comparable to type '0'. tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(6,10): error TS2678: Type '123' is not comparable to type '0'. tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(7,10): error TS2678: Type 'true' is not comparable to type '0'. @@ -10,11 +10,11 @@ tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(7,10): error TS2678: T switch (0) { case Foo: break; // Error ~~~ -!!! error TS2678: Type 'typeof Foo' is not comparable to type '0'. +!!! error TS2678: Type 'typeof Foo' is not comparable to type 'number'. case "sss": break; // Error ~~~~~ !!! error TS2678: Type '"sss"' is not comparable to type '0'. - case 123: break; // No Error + case 123: break; // Error ~~~ !!! error TS2678: Type '123' is not comparable to type '0'. case true: break; // Error @@ -30,4 +30,5 @@ tests/cases/compiler/switchCasesExpressionTypeMismatch.ts(7,10): error TS2678: T case "sss": break; case 123: break; case true: break; - } \ No newline at end of file + } + \ No newline at end of file diff --git a/tests/baselines/reference/switchCasesExpressionTypeMismatch.js b/tests/baselines/reference/switchCasesExpressionTypeMismatch.js index ba929691d25..43a43224579 100644 --- a/tests/baselines/reference/switchCasesExpressionTypeMismatch.js +++ b/tests/baselines/reference/switchCasesExpressionTypeMismatch.js @@ -4,7 +4,7 @@ class Foo { } switch (0) { case Foo: break; // Error case "sss": break; // Error - case 123: break; // No Error + case 123: break; // Error case true: break; // Error } @@ -16,7 +16,8 @@ switch (s) { case "sss": break; case 123: break; case true: break; -} +} + //// [switchCasesExpressionTypeMismatch.js] var Foo = (function () { @@ -27,7 +28,7 @@ var Foo = (function () { switch (0) { case Foo: break; // Error case "sss": break; // Error - case 123: break; // No Error + case 123: break; // Error case true: break; // Error } var s = 0; diff --git a/tests/baselines/reference/switchComparableCompatForBrands.js b/tests/baselines/reference/switchComparableCompatForBrands.js new file mode 100644 index 00000000000..316edfc9c31 --- /dev/null +++ b/tests/baselines/reference/switchComparableCompatForBrands.js @@ -0,0 +1,29 @@ +//// [switchComparableCompatForBrands.ts] +class MyBrand +{ + private _a: number; +} + +function test(strInput: string & MyBrand) { + switch(strInput) + { + case "a": + return 1; + } + return 0; +} + + +//// [switchComparableCompatForBrands.js] +var MyBrand = (function () { + function MyBrand() { + } + return MyBrand; +}()); +function test(strInput) { + switch (strInput) { + case "a": + return 1; + } + return 0; +} diff --git a/tests/baselines/reference/switchComparableCompatForBrands.symbols b/tests/baselines/reference/switchComparableCompatForBrands.symbols new file mode 100644 index 00000000000..adf6a5174ad --- /dev/null +++ b/tests/baselines/reference/switchComparableCompatForBrands.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/switchComparableCompatForBrands.ts === +class MyBrand +>MyBrand : Symbol(MyBrand, Decl(switchComparableCompatForBrands.ts, 0, 0)) +{ + private _a: number; +>_a : Symbol(MyBrand._a, Decl(switchComparableCompatForBrands.ts, 1, 1)) +} + +function test(strInput: string & MyBrand) { +>test : Symbol(test, Decl(switchComparableCompatForBrands.ts, 3, 1)) +>strInput : Symbol(strInput, Decl(switchComparableCompatForBrands.ts, 5, 14)) +>MyBrand : Symbol(MyBrand, Decl(switchComparableCompatForBrands.ts, 0, 0)) + + switch(strInput) +>strInput : Symbol(strInput, Decl(switchComparableCompatForBrands.ts, 5, 14)) + { + case "a": + return 1; + } + return 0; +} + diff --git a/tests/baselines/reference/switchComparableCompatForBrands.types b/tests/baselines/reference/switchComparableCompatForBrands.types new file mode 100644 index 00000000000..5e479ee29dc --- /dev/null +++ b/tests/baselines/reference/switchComparableCompatForBrands.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/switchComparableCompatForBrands.ts === +class MyBrand +>MyBrand : MyBrand +{ + private _a: number; +>_a : number +} + +function test(strInput: string & MyBrand) { +>test : (strInput: string & MyBrand) => 1 | 0 +>strInput : string & MyBrand +>MyBrand : MyBrand + + switch(strInput) +>strInput : string & MyBrand + { + case "a": +>"a" : "a" + + return 1; +>1 : 1 + } + return 0; +>0 : 0 +} + diff --git a/tests/baselines/reference/symbolProperty53.errors.txt b/tests/baselines/reference/symbolProperty53.errors.txt index 03002cd92b2..faea8413587 100644 --- a/tests/baselines/reference/symbolProperty53.errors.txt +++ b/tests/baselines/reference/symbolProperty53.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty53.ts(2,5): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. -tests/cases/conformance/es6/Symbols/symbolProperty53.ts(5,1): error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/conformance/es6/Symbols/symbolProperty53.ts(5,5): error TS2538: Type '(key: string) => symbol' cannot be used as an index type. ==== tests/cases/conformance/es6/Symbols/symbolProperty53.ts (2 errors) ==== @@ -10,5 +10,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty53.ts(5,1): error TS2342: An i }; obj[Symbol.for]; - ~~~~~~~~~~~~~~~ -!!! error TS2342: An index expression argument must be of type 'string', 'number', 'symbol', or 'any'. \ No newline at end of file + ~~~~~~~~~~ +!!! error TS2538: Type '(key: string) => symbol' cannot be used as an index type. \ No newline at end of file diff --git a/tests/baselines/reference/systemModule10.js b/tests/baselines/reference/systemModule10.js index 10afa784ebb..a54afee15d7 100644 --- a/tests/baselines/reference/systemModule10.js +++ b/tests/baselines/reference/systemModule10.js @@ -24,10 +24,10 @@ System.register(["file1", "file2"], function (exports_1, context_1) { } ], execute: function () { - exports_1("x", file1_1.x); - exports_1("y", file1_1.x); exports_1("n", file1_1["default"]); exports_1("n1", file1_1["default"]); + exports_1("x", file1_1.x); + exports_1("y", file1_1.x); exports_1("n2", n2); exports_1("n3", n2); } diff --git a/tests/baselines/reference/systemModule10_ES5.js b/tests/baselines/reference/systemModule10_ES5.js index 830c611bd38..bac2a6003a4 100644 --- a/tests/baselines/reference/systemModule10_ES5.js +++ b/tests/baselines/reference/systemModule10_ES5.js @@ -24,10 +24,10 @@ System.register(["file1", "file2"], function (exports_1, context_1) { } ], execute: function () { - exports_1("x", file1_1.x); - exports_1("y", file1_1.x); exports_1("n", file1_1.default); exports_1("n1", file1_1.default); + exports_1("x", file1_1.x); + exports_1("y", file1_1.x); exports_1("n2", n2); exports_1("n3", n2); } diff --git a/tests/baselines/reference/systemModule11.js b/tests/baselines/reference/systemModule11.js index 7f120cec40d..212a24b5e20 100644 --- a/tests/baselines/reference/systemModule11.js +++ b/tests/baselines/reference/systemModule11.js @@ -46,8 +46,8 @@ System.register(["bar"], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function foo() { } - var x; exports_1("foo", foo); + var x; var exportedNames_1 = { "x": true, "foo": true @@ -55,8 +55,7 @@ System.register(["bar"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) - exports[n] = m[n]; + if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n]; } exports_1(exports); } @@ -83,8 +82,7 @@ System.register(["bar"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) - exports[n] = m[n]; + if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n]; } exports_1(exports); } @@ -95,8 +93,6 @@ System.register(["bar"], function (exports_1, context_1) { } ], execute: function () { - exports_1("x", x); - exports_1("y1", y); } }; }); @@ -113,8 +109,7 @@ System.register(["a", "bar"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) - exports[n] = m[n]; + if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n]; } exports_1(exports); } @@ -139,10 +134,10 @@ System.register(["a"], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function foo() { } - function default_1() { } - var x, z, z1; exports_1("foo", foo); + function default_1() { } exports_1("default", default_1); + var x, z, z1; return { setters: [ function (a_1_1) { @@ -153,8 +148,6 @@ System.register(["a"], function (exports_1, context_1) { } ], execute: function () { - exports_1("z", z); - exports_1("z2", z1); } }; }); @@ -166,8 +159,7 @@ System.register(["a"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default") - exports[n] = m[n]; + if (n !== "default") exports[n] = m[n]; } exports_1(exports); } diff --git a/tests/baselines/reference/systemModule13.js b/tests/baselines/reference/systemModule13.js index c527fd3e811..d3fee049e04 100644 --- a/tests/baselines/reference/systemModule13.js +++ b/tests/baselines/reference/systemModule13.js @@ -8,12 +8,12 @@ for ([x] of [[1]]) {} System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; - var x, y, z, _a, z0, z1, _b; + var x, y, z, z0, z1, _a, _b; return { setters: [], execute: function () { - _a = [1, 2, 3], exports_1("x", x = _a[0]), exports_1("y", y = _a[1]), exports_1("z", z = _a[2]); - _b = { a: true, b: { c: "123" } }, exports_1("z0", z0 = _b.a), exports_1("z1", z1 = _b.b.c); + exports_1("x", x = (_a = [1, 2, 3], _a[0])), exports_1("y", y = _a[1]), exports_1("z", z = _a[2]); + exports_1("z0", z0 = (_b = { a: true, b: { c: "123" } }, _b.a)), exports_1("z1", z1 = _b.b.c); for (var _i = 0, _a = [[1]]; _i < _a.length; _i++) { exports_1("x", x = _a[_i][0]); } diff --git a/tests/baselines/reference/systemModule14.js b/tests/baselines/reference/systemModule14.js index bebe9244e07..ba4adc7aabc 100644 --- a/tests/baselines/reference/systemModule14.js +++ b/tests/baselines/reference/systemModule14.js @@ -17,6 +17,8 @@ System.register(["foo"], function (exports_1, context_1) { function foo() { return foo_1.a; } + exports_1("foo", foo); + exports_1("b", foo); var foo_1, x; return { setters: [ @@ -25,9 +27,7 @@ System.register(["foo"], function (exports_1, context_1) { } ], execute: function () { - exports_1("foo", foo); x = 1; - exports_1("b", foo); } }; }); diff --git a/tests/baselines/reference/systemModule16.js b/tests/baselines/reference/systemModule16.js index 8058e0f2ea1..86b6a448215 100644 --- a/tests/baselines/reference/systemModule16.js +++ b/tests/baselines/reference/systemModule16.js @@ -27,8 +27,7 @@ System.register(["foo", "bar"], function (exports_1, context_1) { function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) - exports[n] = m[n]; + if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n]; } exports_1(exports); } diff --git a/tests/baselines/reference/systemModule17.js b/tests/baselines/reference/systemModule17.js index df3d722f3d2..bcdf6612356 100644 --- a/tests/baselines/reference/systemModule17.js +++ b/tests/baselines/reference/systemModule17.js @@ -71,18 +71,18 @@ System.register(["f1"], function (exports_1, context_1) { ], execute: function () { x = 1; + exports_1("x", x); + exports_1("x1", x); (function (N) { N.x = 1; })(N || (N = {})); IX = N.x; - exports_1("x", x); - exports_1("x1", x); + exports_1("IX", IX); + exports_1("IX1", IX); exports_1("A", f1_1.A); exports_1("A1", f1_1.A); exports_1("EA", f1_1.A); exports_1("EA1", f1_1.A); - exports_1("IX", IX); - exports_1("IX1", IX); } }; }); diff --git a/tests/baselines/reference/systemModule3.js b/tests/baselines/reference/systemModule3.js index a8f93941c89..109cbb7187c 100644 --- a/tests/baselines/reference/systemModule3.js +++ b/tests/baselines/reference/systemModule3.js @@ -67,9 +67,9 @@ System.register([], function (exports_1, context_1) { setters: [], execute: function () { default_1 = (function () { - function class_1() { + function default_1() { } - return class_1; + return default_1; }()); exports_1("default", default_1); } diff --git a/tests/baselines/reference/systemModule7.js b/tests/baselines/reference/systemModule7.js index bf34e3f786c..d25ca627e44 100644 --- a/tests/baselines/reference/systemModule7.js +++ b/tests/baselines/reference/systemModule7.js @@ -21,7 +21,7 @@ System.register([], function (exports_1, context_1) { // filename: instantiatedModule.ts (function (M) { var x = 1; - })(M = M || (M = {})); + })(M || (M = {})); exports_1("M", M); } }; diff --git a/tests/baselines/reference/systemModule8.js b/tests/baselines/reference/systemModule8.js index 467c52298fb..3065d4f35b3 100644 --- a/tests/baselines/reference/systemModule8.js +++ b/tests/baselines/reference/systemModule8.js @@ -62,7 +62,7 @@ System.register([], function (exports_1, context_1) { for (exports_1("x", x = 18);; exports_1("x", --x)) { } for (var x_1 = 50;;) { } exports_1("y", y = [1][0]); - _a = { a: true, b: { c: "123" } }, exports_1("z0", z0 = _a.a), exports_1("z1", z1 = _a.b.c); + exports_1("z0", z0 = (_a = { a: true, b: { c: "123" } }, _a.a)), exports_1("z1", z1 = _a.b.c); for (var _i = 0, _a = [[1]]; _i < _a.length; _i++) { exports_1("x", x = _a[_i][0]); } diff --git a/tests/baselines/reference/systemModule9.js b/tests/baselines/reference/systemModule9.js index e46b97a71a2..fce3aa1bdf4 100644 --- a/tests/baselines/reference/systemModule9.js +++ b/tests/baselines/reference/systemModule9.js @@ -33,8 +33,7 @@ System.register(["file1", "file2", "file3", "file4", "file5", "file6", "file7"], function exportStar_1(m) { var exports = {}; for (var n in m) { - if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) - exports[n] = m[n]; + if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n]; } exports_1(exports); } @@ -70,7 +69,6 @@ System.register(["file1", "file2", "file3", "file4", "file5", "file6", "file7"], ns2.f(); ns3.f(); y = true; - exports_1("x", x); exports_1("z", y); } }; diff --git a/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.js b/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.js index 0cd6f472bdb..132d27a4ea0 100644 --- a/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.js +++ b/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.js @@ -20,8 +20,8 @@ System.register([], function (exports_1, context_1) { use(TopLevelConstEnum.X); use(M.NonTopLevelConstEnum.X); } - var TopLevelConstEnum, M; exports_1("foo", foo); + var TopLevelConstEnum, M; return { setters: [], execute: function () { @@ -29,10 +29,10 @@ System.register([], function (exports_1, context_1) { TopLevelConstEnum[TopLevelConstEnum["X"] = 0] = "X"; })(TopLevelConstEnum || (TopLevelConstEnum = {})); (function (M) { + var NonTopLevelConstEnum; (function (NonTopLevelConstEnum) { NonTopLevelConstEnum[NonTopLevelConstEnum["X"] = 0] = "X"; - })(M.NonTopLevelConstEnum || (M.NonTopLevelConstEnum = {})); - var NonTopLevelConstEnum = M.NonTopLevelConstEnum; + })(NonTopLevelConstEnum = M.NonTopLevelConstEnum || (M.NonTopLevelConstEnum = {})); })(M || (M = {})); } }; diff --git a/tests/baselines/reference/systemModuleDeclarationMerging.js b/tests/baselines/reference/systemModuleDeclarationMerging.js index 4dac69c2641..d60a315b0a6 100644 --- a/tests/baselines/reference/systemModuleDeclarationMerging.js +++ b/tests/baselines/reference/systemModuleDeclarationMerging.js @@ -14,14 +14,14 @@ System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function F() { } - var C, E; exports_1("F", F); + var C, E; return { setters: [], execute: function () { (function (F) { var x; - })(F = F || (F = {})); + })(F || (F = {})); exports_1("F", F); C = (function () { function C() { @@ -31,14 +31,14 @@ System.register([], function (exports_1, context_1) { exports_1("C", C); (function (C) { var x; - })(C = C || (C = {})); + })(C || (C = {})); exports_1("C", C); (function (E) { })(E || (E = {})); exports_1("E", E); (function (E) { var x; - })(E = E || (E = {})); + })(E || (E = {})); exports_1("E", E); } }; diff --git a/tests/baselines/reference/systemModuleExportDefault.js b/tests/baselines/reference/systemModuleExportDefault.js index 53f63ecb027..67341a04a0b 100644 --- a/tests/baselines/reference/systemModuleExportDefault.js +++ b/tests/baselines/reference/systemModuleExportDefault.js @@ -48,9 +48,9 @@ System.register([], function (exports_1, context_1) { setters: [], execute: function () { default_1 = (function () { - function class_1() { + function default_1() { } - return class_1; + return default_1; }()); exports_1("default", default_1); } diff --git a/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.js b/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.js index b0498b23f79..df68f32b3bd 100644 --- a/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.js +++ b/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.js @@ -17,8 +17,8 @@ System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function TopLevelFunction() { } - var TopLevelClass, TopLevelModule, TopLevelEnum, TopLevelModule2; exports_1("TopLevelFunction", TopLevelFunction); + var TopLevelClass, TopLevelModule, TopLevelEnum, TopLevelModule2; return { setters: [], execute: function () { @@ -30,7 +30,7 @@ System.register([], function (exports_1, context_1) { exports_1("TopLevelClass", TopLevelClass); (function (TopLevelModule) { var v; - })(TopLevelModule = TopLevelModule || (TopLevelModule = {})); + })(TopLevelModule || (TopLevelModule = {})); exports_1("TopLevelModule", TopLevelModule); (function (TopLevelEnum) { TopLevelEnum[TopLevelEnum["E"] = 0] = "E"; @@ -49,11 +49,11 @@ System.register([], function (exports_1, context_1) { })(NonTopLevelModule = TopLevelModule2.NonTopLevelModule || (TopLevelModule2.NonTopLevelModule = {})); function NonTopLevelFunction() { } TopLevelModule2.NonTopLevelFunction = NonTopLevelFunction; + var NonTopLevelEnum; (function (NonTopLevelEnum) { NonTopLevelEnum[NonTopLevelEnum["E"] = 0] = "E"; - })(TopLevelModule2.NonTopLevelEnum || (TopLevelModule2.NonTopLevelEnum = {})); - var NonTopLevelEnum = TopLevelModule2.NonTopLevelEnum; - })(TopLevelModule2 = TopLevelModule2 || (TopLevelModule2 = {})); + })(NonTopLevelEnum = TopLevelModule2.NonTopLevelEnum || (TopLevelModule2.NonTopLevelEnum = {})); + })(TopLevelModule2 || (TopLevelModule2 = {})); exports_1("TopLevelModule2", TopLevelModule2); } }; diff --git a/tests/baselines/reference/systemModuleTargetES6.js b/tests/baselines/reference/systemModuleTargetES6.js index a049ea78395..2fe48f4c57b 100644 --- a/tests/baselines/reference/systemModuleTargetES6.js +++ b/tests/baselines/reference/systemModuleTargetES6.js @@ -20,12 +20,12 @@ System.register([], function (exports_1, context_1) { function myFunction() { return new MyClass(); } + exports_1("myFunction", myFunction); function myFunction2() { return new MyClass2(); } - var MyClass, MyClass2; - exports_1("myFunction", myFunction); exports_1("myFunction2", myFunction2); + var MyClass, MyClass2; return { setters: [], execute: function () { @@ -35,8 +35,8 @@ System.register([], function (exports_1, context_1) { MyClass2 = class MyClass2 { static getInstance() { return MyClass2.value; } }; - exports_1("MyClass2", MyClass2); MyClass2.value = 42; + exports_1("MyClass2", MyClass2); } }; }); diff --git a/tests/baselines/reference/systemModuleTrailingComments.js b/tests/baselines/reference/systemModuleTrailingComments.js new file mode 100644 index 00000000000..41b0bd299a0 --- /dev/null +++ b/tests/baselines/reference/systemModuleTrailingComments.js @@ -0,0 +1,18 @@ +//// [systemModuleTrailingComments.ts] +export const test = "TEST"; + +//some comment + +//// [systemModuleTrailingComments.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + var test; + return { + setters: [], + execute: function () { + exports_1("test", test = "TEST"); + //some comment + } + }; +}); diff --git a/tests/baselines/reference/systemModuleTrailingComments.symbols b/tests/baselines/reference/systemModuleTrailingComments.symbols new file mode 100644 index 00000000000..4df59b45faa --- /dev/null +++ b/tests/baselines/reference/systemModuleTrailingComments.symbols @@ -0,0 +1,5 @@ +=== tests/cases/compiler/systemModuleTrailingComments.ts === +export const test = "TEST"; +>test : Symbol(test, Decl(systemModuleTrailingComments.ts, 0, 12)) + +//some comment diff --git a/tests/baselines/reference/systemModuleTrailingComments.types b/tests/baselines/reference/systemModuleTrailingComments.types new file mode 100644 index 00000000000..235b46e6e8f --- /dev/null +++ b/tests/baselines/reference/systemModuleTrailingComments.types @@ -0,0 +1,6 @@ +=== tests/cases/compiler/systemModuleTrailingComments.ts === +export const test = "TEST"; +>test : "TEST" +>"TEST" : "TEST" + +//some comment diff --git a/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapes.js b/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapes.js index e4482ded0c2..3df09abb2db 100644 --- a/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapes.js +++ b/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapes.js @@ -8,7 +8,7 @@ f `\x0D${ "Interrupted CRLF" }\x0A`; function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } (_a = ["\r", "\n"], _a.raw = ["\\x0D", "\\x0A"], f(_a, "Interrupted CRLF")); diff --git a/tests/baselines/reference/taggedTemplateStringsPlainCharactersThatArePartsOfEscapes01.js b/tests/baselines/reference/taggedTemplateStringsPlainCharactersThatArePartsOfEscapes01.js index 9450e939f2f..33c2914e3e8 100644 --- a/tests/baselines/reference/taggedTemplateStringsPlainCharactersThatArePartsOfEscapes01.js +++ b/tests/baselines/reference/taggedTemplateStringsPlainCharactersThatArePartsOfEscapes01.js @@ -11,7 +11,7 @@ f `0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2028 2029 0085 t v f b r function f() { var x = []; for (var _i = 0; _i < arguments.length; _i++) { - x[_i - 0] = arguments[_i]; + x[_i] = arguments[_i]; } } (_a = ["0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2028 2029 0085 t v f b r n"], _a.raw = ["0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2028 2029 0085 t v f b r n"], f(_a)); diff --git a/tests/baselines/reference/taggedTemplateStringsWithMultilineTemplate.js b/tests/baselines/reference/taggedTemplateStringsWithMultilineTemplate.js index cee9d1efce4..9ffc0cadfef 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithMultilineTemplate.js +++ b/tests/baselines/reference/taggedTemplateStringsWithMultilineTemplate.js @@ -11,7 +11,7 @@ f ` function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } (_a = ["\n\n"], _a.raw = ["\n\\\n\n"], f(_a)); diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.js b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.js index 4245b0cb0f4..19211c2fa8a 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.js +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution1.js @@ -26,7 +26,7 @@ var z = foo `${1}${2}${3}`; // any (with error) function foo() { var stuff = []; for (var _i = 0; _i < arguments.length; _i++) { - stuff[_i - 0] = arguments[_i]; + stuff[_i] = arguments[_i]; } return undefined; } diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution2.js b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution2.js index c16bfa5454f..fdac55da181 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution2.js +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution2.js @@ -22,7 +22,7 @@ var d = foo2([], 1); function foo1() { var stuff = []; for (var _i = 0; _i < arguments.length; _i++) { - stuff[_i - 0] = arguments[_i]; + stuff[_i] = arguments[_i]; } return undefined; } @@ -31,7 +31,7 @@ var b = foo1([], 1); function foo2() { var stuff = []; for (var _i = 0; _i < arguments.length; _i++) { - stuff[_i - 0] = arguments[_i]; + stuff[_i] = arguments[_i]; } return undefined; } diff --git a/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js index f7523eb9870..334f61e453d 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js +++ b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js @@ -10,7 +10,7 @@ foo `${function (x: number) { x = "bad"; } }`; function foo() { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } } (_a = ["", ""], _a.raw = ["", ""], foo(_a, function (x) { x = "bad"; })); diff --git a/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapes.js b/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapes.js index ae73b0b227e..6a04b082e1f 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapes.js +++ b/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapes.js @@ -8,7 +8,7 @@ f `'\u{1f4a9}'${ " should be converted to " }'\uD83D\uDCA9'`; function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } (_a = ["'\uD83D\uDCA9'", "'\uD83D\uDCA9'"], _a.raw = ["'\\u{1f4a9}'", "'\\uD83D\\uDCA9'"], f(_a, " should be converted to ")); diff --git a/tests/baselines/reference/taggedTemplateStringsWithWhitespaceEscapes.js b/tests/baselines/reference/taggedTemplateStringsWithWhitespaceEscapes.js index 65af8da59f9..e8f219fd125 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithWhitespaceEscapes.js +++ b/tests/baselines/reference/taggedTemplateStringsWithWhitespaceEscapes.js @@ -8,7 +8,7 @@ f `\t\n\v\f\r\\`; function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } (_a = ["\t\n\v\f\r\\"], _a.raw = ["\\t\\n\\v\\f\\r\\\\"], f(_a)); diff --git a/tests/baselines/reference/thisInInvalidContexts.js b/tests/baselines/reference/thisInInvalidContexts.js index 1fc1c734639..7f299fd7e10 100644 --- a/tests/baselines/reference/thisInInvalidContexts.js +++ b/tests/baselines/reference/thisInInvalidContexts.js @@ -70,7 +70,8 @@ var ClassWithNoInitializer = (function (_super) { __extends(ClassWithNoInitializer, _super); //'this' in optional super call function ClassWithNoInitializer() { - return _super.call(this, _this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return ClassWithNoInitializer; }(BaseErrClass)); diff --git a/tests/baselines/reference/thisInInvalidContextsExternalModule.js b/tests/baselines/reference/thisInInvalidContextsExternalModule.js index f8cb6d695dc..65a1ef1eee9 100644 --- a/tests/baselines/reference/thisInInvalidContextsExternalModule.js +++ b/tests/baselines/reference/thisInInvalidContextsExternalModule.js @@ -71,7 +71,8 @@ var ClassWithNoInitializer = (function (_super) { __extends(ClassWithNoInitializer, _super); //'this' in optional super call function ClassWithNoInitializer() { - return _super.call(this, _this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return ClassWithNoInitializer; }(BaseErrClass)); diff --git a/tests/baselines/reference/thisInSuperCall.js b/tests/baselines/reference/thisInSuperCall.js index 2a4d15973ab..1c1f11ffbc8 100644 --- a/tests/baselines/reference/thisInSuperCall.js +++ b/tests/baselines/reference/thisInSuperCall.js @@ -36,7 +36,8 @@ var Base = (function () { var Foo = (function (_super) { __extends(Foo, _super); function Foo() { - return _super.call(this, _this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return Foo; }(Base)); diff --git a/tests/baselines/reference/thisInSuperCall2.js b/tests/baselines/reference/thisInSuperCall2.js index eabfa9d562c..6288082ed64 100644 --- a/tests/baselines/reference/thisInSuperCall2.js +++ b/tests/baselines/reference/thisInSuperCall2.js @@ -33,7 +33,8 @@ var Base = (function () { var Foo = (function (_super) { __extends(Foo, _super); function Foo() { - return _super.call(this, _this) || this; + var _this = _super.call(this, _this) || this; + return _this; } return Foo; }(Base)); diff --git a/tests/baselines/reference/thisTypeInFunctions.types b/tests/baselines/reference/thisTypeInFunctions.types index 44bf23ad509..a2aaba4cdd7 100644 --- a/tests/baselines/reference/thisTypeInFunctions.types +++ b/tests/baselines/reference/thisTypeInFunctions.types @@ -453,7 +453,7 @@ let anyToSpecified: (this: { y: number }, x: number) => number = function(x: num >this : { y: number; } >y : number >x : number ->function(x: number): number { return x + 12; } : (x: number) => number +>function(x: number): number { return x + 12; } : (this: { y: number; }, x: number) => number >x : number >x + 12 : number >x : number diff --git a/tests/baselines/reference/throwInEnclosingStatements.types b/tests/baselines/reference/throwInEnclosingStatements.types index 4955b9243ae..2d99ac435ae 100644 --- a/tests/baselines/reference/throwInEnclosingStatements.types +++ b/tests/baselines/reference/throwInEnclosingStatements.types @@ -25,7 +25,7 @@ switch (y) { >'a' : "a" throw y; ->y : string +>y : "a" default: throw y; diff --git a/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.js b/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.js index 6f30140c63e..495e9354024 100644 --- a/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.js +++ b/tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.js @@ -35,7 +35,7 @@ f1(1); function f2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } f2.apply(void 0, []); diff --git a/tests/baselines/reference/transformNestedGeneratorsWithTry.js b/tests/baselines/reference/transformNestedGeneratorsWithTry.js index 69273e62633..7c3597ddc4b 100644 --- a/tests/baselines/reference/transformNestedGeneratorsWithTry.js +++ b/tests/baselines/reference/transformNestedGeneratorsWithTry.js @@ -29,7 +29,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments)).next()); + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.js b/tests/baselines/reference/transformsElideNullUndefinedType.js new file mode 100644 index 00000000000..63bc77559c1 --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.js @@ -0,0 +1,108 @@ +//// [transformsElideNullUndefinedType.ts] + +var v0: null; +var v1: undefined; + +function f0(): null { return null; } +function f1(): undefined { return undefined; } + +var f2 = function (): null { return null; } +var f3 = function (): undefined { return undefined; } + +var f4 = (): null => null; +var f5 = (): undefined => undefined; + +function f6(p0: null) { } +function f7(p1: undefined) { } + +var f8 = function (p2: null) { } +var f9 = function (p3: undefined) { } + +var f10 = (p4: null) => { } +var f11 = (p5: undefined) => { } + +class C1 { + m0(): null { return null; } + m1(): undefined { return undefined; } + + m3(p6: null) { } + m4(p7: undefined) { } + + get a0(): null { return null; } + get a1(): undefined { return undefined; } + + set a2(p8: null) { } + set a3(p9: undefined) { } +} + +class C2 { constructor(p10: null) { } } +class C3 { constructor(p11: undefined) { } } + +class C4 { + f1; + constructor(p12: null) { } +} + +class C5 { + f2; + constructor(p13: undefined) { } +} + +var C6 = class { constructor(p12: null) { } } +var C7 = class { constructor(p13: undefined) { } } + +declare function fn(); +fn(); +fn(); + +declare class D {} +new D(); +new D(); + +//// [transformsElideNullUndefinedType.js] +var v0; +var v1; +function f0() { return null; } +function f1() { return undefined; } +var f2 = function () { return null; }; +var f3 = function () { return undefined; }; +var f4 = () => null; +var f5 = () => undefined; +function f6(p0) { } +function f7(p1) { } +var f8 = function (p2) { }; +var f9 = function (p3) { }; +var f10 = (p4) => { }; +var f11 = (p5) => { }; +class C1 { + m0() { return null; } + m1() { return undefined; } + m3(p6) { } + m4(p7) { } + get a0() { return null; } + get a1() { return undefined; } + set a2(p8) { } + set a3(p9) { } +} +class C2 { + constructor(p10) { } +} +class C3 { + constructor(p11) { } +} +class C4 { + constructor(p12) { } +} +class C5 { + constructor(p13) { } +} +var C6 = class { + constructor(p12) { } +}; +var C7 = class { + constructor(p13) { } +}; +fn(); +fn(); +new D(); +new D(); diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.symbols b/tests/baselines/reference/transformsElideNullUndefinedType.symbols new file mode 100644 index 00000000000..b651784a61c --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.symbols @@ -0,0 +1,143 @@ +=== tests/cases/compiler/transformsElideNullUndefinedType.ts === + +var v0: null; +>v0 : Symbol(v0, Decl(transformsElideNullUndefinedType.ts, 1, 3)) + +var v1: undefined; +>v1 : Symbol(v1, Decl(transformsElideNullUndefinedType.ts, 2, 3)) + +function f0(): null { return null; } +>f0 : Symbol(f0, Decl(transformsElideNullUndefinedType.ts, 2, 18)) + +function f1(): undefined { return undefined; } +>f1 : Symbol(f1, Decl(transformsElideNullUndefinedType.ts, 4, 36)) +>undefined : Symbol(undefined) + +var f2 = function (): null { return null; } +>f2 : Symbol(f2, Decl(transformsElideNullUndefinedType.ts, 7, 3)) + +var f3 = function (): undefined { return undefined; } +>f3 : Symbol(f3, Decl(transformsElideNullUndefinedType.ts, 8, 3)) +>undefined : Symbol(undefined) + +var f4 = (): null => null; +>f4 : Symbol(f4, Decl(transformsElideNullUndefinedType.ts, 10, 3)) + +var f5 = (): undefined => undefined; +>f5 : Symbol(f5, Decl(transformsElideNullUndefinedType.ts, 11, 3)) +>undefined : Symbol(undefined) + +function f6(p0: null) { } +>f6 : Symbol(f6, Decl(transformsElideNullUndefinedType.ts, 11, 36)) +>p0 : Symbol(p0, Decl(transformsElideNullUndefinedType.ts, 13, 12)) + +function f7(p1: undefined) { } +>f7 : Symbol(f7, Decl(transformsElideNullUndefinedType.ts, 13, 25)) +>p1 : Symbol(p1, Decl(transformsElideNullUndefinedType.ts, 14, 12)) + +var f8 = function (p2: null) { } +>f8 : Symbol(f8, Decl(transformsElideNullUndefinedType.ts, 16, 3)) +>p2 : Symbol(p2, Decl(transformsElideNullUndefinedType.ts, 16, 19)) + +var f9 = function (p3: undefined) { } +>f9 : Symbol(f9, Decl(transformsElideNullUndefinedType.ts, 17, 3)) +>p3 : Symbol(p3, Decl(transformsElideNullUndefinedType.ts, 17, 19)) + +var f10 = (p4: null) => { } +>f10 : Symbol(f10, Decl(transformsElideNullUndefinedType.ts, 19, 3)) +>p4 : Symbol(p4, Decl(transformsElideNullUndefinedType.ts, 19, 11)) + +var f11 = (p5: undefined) => { } +>f11 : Symbol(f11, Decl(transformsElideNullUndefinedType.ts, 20, 3)) +>p5 : Symbol(p5, Decl(transformsElideNullUndefinedType.ts, 20, 11)) + +class C1 { +>C1 : Symbol(C1, Decl(transformsElideNullUndefinedType.ts, 20, 32)) + + m0(): null { return null; } +>m0 : Symbol(C1.m0, Decl(transformsElideNullUndefinedType.ts, 22, 10)) + + m1(): undefined { return undefined; } +>m1 : Symbol(C1.m1, Decl(transformsElideNullUndefinedType.ts, 23, 31)) +>undefined : Symbol(undefined) + + m3(p6: null) { } +>m3 : Symbol(C1.m3, Decl(transformsElideNullUndefinedType.ts, 24, 41)) +>p6 : Symbol(p6, Decl(transformsElideNullUndefinedType.ts, 26, 7)) + + m4(p7: undefined) { } +>m4 : Symbol(C1.m4, Decl(transformsElideNullUndefinedType.ts, 26, 20)) +>p7 : Symbol(p7, Decl(transformsElideNullUndefinedType.ts, 27, 7)) + + get a0(): null { return null; } +>a0 : Symbol(C1.a0, Decl(transformsElideNullUndefinedType.ts, 27, 25)) + + get a1(): undefined { return undefined; } +>a1 : Symbol(C1.a1, Decl(transformsElideNullUndefinedType.ts, 29, 35)) +>undefined : Symbol(undefined) + + set a2(p8: null) { } +>a2 : Symbol(C1.a2, Decl(transformsElideNullUndefinedType.ts, 30, 45)) +>p8 : Symbol(p8, Decl(transformsElideNullUndefinedType.ts, 32, 11)) + + set a3(p9: undefined) { } +>a3 : Symbol(C1.a3, Decl(transformsElideNullUndefinedType.ts, 32, 24)) +>p9 : Symbol(p9, Decl(transformsElideNullUndefinedType.ts, 33, 11)) +} + +class C2 { constructor(p10: null) { } } +>C2 : Symbol(C2, Decl(transformsElideNullUndefinedType.ts, 34, 1)) +>p10 : Symbol(p10, Decl(transformsElideNullUndefinedType.ts, 36, 23)) + +class C3 { constructor(p11: undefined) { } } +>C3 : Symbol(C3, Decl(transformsElideNullUndefinedType.ts, 36, 39)) +>p11 : Symbol(p11, Decl(transformsElideNullUndefinedType.ts, 37, 23)) + +class C4 { +>C4 : Symbol(C4, Decl(transformsElideNullUndefinedType.ts, 37, 44)) + + f1; +>f1 : Symbol(C4.f1, Decl(transformsElideNullUndefinedType.ts, 39, 10)) + + constructor(p12: null) { } +>p12 : Symbol(p12, Decl(transformsElideNullUndefinedType.ts, 41, 16)) +} + +class C5 { +>C5 : Symbol(C5, Decl(transformsElideNullUndefinedType.ts, 42, 1)) + + f2; +>f2 : Symbol(C5.f2, Decl(transformsElideNullUndefinedType.ts, 44, 10)) + + constructor(p13: undefined) { } +>p13 : Symbol(p13, Decl(transformsElideNullUndefinedType.ts, 46, 16)) +} + +var C6 = class { constructor(p12: null) { } } +>C6 : Symbol(C6, Decl(transformsElideNullUndefinedType.ts, 49, 3)) +>p12 : Symbol(p12, Decl(transformsElideNullUndefinedType.ts, 49, 29)) + +var C7 = class { constructor(p13: undefined) { } } +>C7 : Symbol(C7, Decl(transformsElideNullUndefinedType.ts, 50, 3)) +>p13 : Symbol(p13, Decl(transformsElideNullUndefinedType.ts, 50, 29)) + +declare function fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 52, 20)) + +fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) + +fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) + +declare class D {} +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 56, 16)) + +new D(); +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) + +new D(); +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) + diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.types b/tests/baselines/reference/transformsElideNullUndefinedType.types new file mode 100644 index 00000000000..7f48d8a00e9 --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.types @@ -0,0 +1,178 @@ +=== tests/cases/compiler/transformsElideNullUndefinedType.ts === + +var v0: null; +>v0 : null +>null : null + +var v1: undefined; +>v1 : undefined + +function f0(): null { return null; } +>f0 : () => null +>null : null +>null : null + +function f1(): undefined { return undefined; } +>f1 : () => undefined +>undefined : undefined + +var f2 = function (): null { return null; } +>f2 : () => null +>function (): null { return null; } : () => null +>null : null +>null : null + +var f3 = function (): undefined { return undefined; } +>f3 : () => undefined +>function (): undefined { return undefined; } : () => undefined +>undefined : undefined + +var f4 = (): null => null; +>f4 : () => null +>(): null => null : () => null +>null : null +>null : null + +var f5 = (): undefined => undefined; +>f5 : () => undefined +>(): undefined => undefined : () => undefined +>undefined : undefined + +function f6(p0: null) { } +>f6 : (p0: null) => void +>p0 : null +>null : null + +function f7(p1: undefined) { } +>f7 : (p1: undefined) => void +>p1 : undefined + +var f8 = function (p2: null) { } +>f8 : (p2: null) => void +>function (p2: null) { } : (p2: null) => void +>p2 : null +>null : null + +var f9 = function (p3: undefined) { } +>f9 : (p3: undefined) => void +>function (p3: undefined) { } : (p3: undefined) => void +>p3 : undefined + +var f10 = (p4: null) => { } +>f10 : (p4: null) => void +>(p4: null) => { } : (p4: null) => void +>p4 : null +>null : null + +var f11 = (p5: undefined) => { } +>f11 : (p5: undefined) => void +>(p5: undefined) => { } : (p5: undefined) => void +>p5 : undefined + +class C1 { +>C1 : C1 + + m0(): null { return null; } +>m0 : () => null +>null : null +>null : null + + m1(): undefined { return undefined; } +>m1 : () => undefined +>undefined : undefined + + m3(p6: null) { } +>m3 : (p6: null) => void +>p6 : null +>null : null + + m4(p7: undefined) { } +>m4 : (p7: undefined) => void +>p7 : undefined + + get a0(): null { return null; } +>a0 : null +>null : null +>null : null + + get a1(): undefined { return undefined; } +>a1 : undefined +>undefined : undefined + + set a2(p8: null) { } +>a2 : null +>p8 : null +>null : null + + set a3(p9: undefined) { } +>a3 : undefined +>p9 : undefined +} + +class C2 { constructor(p10: null) { } } +>C2 : C2 +>p10 : null +>null : null + +class C3 { constructor(p11: undefined) { } } +>C3 : C3 +>p11 : undefined + +class C4 { +>C4 : C4 + + f1; +>f1 : any + + constructor(p12: null) { } +>p12 : null +>null : null +} + +class C5 { +>C5 : C5 + + f2; +>f2 : any + + constructor(p13: undefined) { } +>p13 : undefined +} + +var C6 = class { constructor(p12: null) { } } +>C6 : typeof (Anonymous class) +>class { constructor(p12: null) { } } : typeof (Anonymous class) +>p12 : null +>null : null + +var C7 = class { constructor(p13: undefined) { } } +>C7 : typeof (Anonymous class) +>class { constructor(p13: undefined) { } } : typeof (Anonymous class) +>p13 : undefined + +declare function fn(); +>fn : () => any +>T : T + +fn(); +>fn() : any +>fn : () => any +>null : null + +fn(); +>fn() : any +>fn : () => any + +declare class D {} +>D : D +>T : T + +new D(); +>new D() : D +>D : typeof D +>null : null + +new D(); +>new D() : D +>D : typeof D + diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.errors.txt b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.errors.txt index d7d6eb69300..7778f6c23c5 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.errors.txt +++ b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.errors.txt @@ -1,6 +1,6 @@ -error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' +error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' -!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' +!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' ==== file.ts (0 errors) ==== \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js index c7570e81192..1ceb1bcd146 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js +++ b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js @@ -1 +1,2 @@ +"use strict"; //# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.errors.txt b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.errors.txt index d7d6eb69300..7778f6c23c5 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.errors.txt +++ b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.errors.txt @@ -1,6 +1,6 @@ -error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' +error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' -!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' +!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' ==== file.ts (0 errors) ==== \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js index c7570e81192..1ceb1bcd146 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js +++ b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js @@ -1 +1,2 @@ +"use strict"; //# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Supports setting alwaysStrict.js b/tests/baselines/reference/transpile/Supports setting alwaysStrict.js new file mode 100644 index 00000000000..8d91090453b --- /dev/null +++ b/tests/baselines/reference/transpile/Supports setting alwaysStrict.js @@ -0,0 +1,3 @@ +"use strict"; +x; +//# sourceMappingURL=input.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Supports setting jsxFactory.js b/tests/baselines/reference/transpile/Supports setting jsxFactory.js new file mode 100644 index 00000000000..8d91090453b --- /dev/null +++ b/tests/baselines/reference/transpile/Supports setting jsxFactory.js @@ -0,0 +1,3 @@ +"use strict"; +x; +//# sourceMappingURL=input.js.map \ No newline at end of file diff --git a/tests/baselines/reference/tsxDefaultImports.js b/tests/baselines/reference/tsxDefaultImports.js index e7e0a13860d..46a94dea92f 100644 --- a/tests/baselines/reference/tsxDefaultImports.js +++ b/tests/baselines/reference/tsxDefaultImports.js @@ -25,9 +25,9 @@ var SomeClass = (function () { } return SomeClass; }()); +SomeClass.E = SomeEnum; exports.__esModule = true; exports["default"] = SomeClass; -SomeClass.E = SomeEnum; //// [b.js] "use strict"; var a_1 = require("./a"); diff --git a/tests/baselines/reference/tsxEmit1.types b/tests/baselines/reference/tsxEmit1.types index c3ca7a2b1b0..84f00b4758a 100644 --- a/tests/baselines/reference/tsxEmit1.types +++ b/tests/baselines/reference/tsxEmit1.types @@ -61,7 +61,7 @@ var selfClosed7 =
; >
: JSX.Element >div : any >x : any ->p : undefined +>p : any >y : any var openClosed1 =
; @@ -82,7 +82,7 @@ var openClosed3 =
{p}
; >
{p}
: JSX.Element >div : any >n : any ->p : undefined +>p : any >div : any var openClosed4 =
{p < p}
; @@ -91,8 +91,8 @@ var openClosed4 =
{p < p}
; >div : any >n : any >p < p : boolean ->p : undefined ->p : undefined +>p : any +>p : any >div : any var openClosed5 =
{p > p}
; @@ -101,8 +101,8 @@ var openClosed5 =
{p > p}
; >div : any >n : any >p > p : boolean ->p : undefined ->p : undefined +>p : any +>p : any >div : any class SomeClass { @@ -180,7 +180,7 @@ var whitespace2 =
{p}
; >whitespace2 : JSX.Element >
{p}
: JSX.Element >div : any ->p : undefined +>p : any >div : any var whitespace3 =
@@ -189,7 +189,7 @@ var whitespace3 =
>div : any {p} ->p : undefined +>p : any
; >div : any diff --git a/tests/baselines/reference/tsxEmit2.types b/tests/baselines/reference/tsxEmit2.types index d306dc9ffe0..5b267d8b802 100644 --- a/tests/baselines/reference/tsxEmit2.types +++ b/tests/baselines/reference/tsxEmit2.types @@ -22,16 +22,16 @@ var spreads1 =
{p2}
; >spreads1 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined ->p2 : undefined +>p1 : any +>p2 : any >div : any var spreads2 =
{p2}
; >spreads2 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined ->p2 : undefined +>p1 : any +>p2 : any >div : any var spreads3 =
{p2}
; @@ -39,19 +39,19 @@ var spreads3 =
{p2}
; >
{p2}
: JSX.Element >div : any >x : any ->p3 : undefined ->p1 : undefined ->p2 : undefined +>p3 : any +>p1 : any +>p2 : any >div : any var spreads4 =
{p2}
; >spreads4 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined +>p1 : any >x : any ->p3 : undefined ->p2 : undefined +>p3 : any +>p2 : any >div : any var spreads5 =
{p2}
; @@ -59,10 +59,10 @@ var spreads5 =
{p2}
; >
{p2}
: JSX.Element >div : any >x : any ->p2 : undefined ->p1 : undefined +>p2 : any +>p1 : any >y : any ->p3 : undefined ->p2 : undefined +>p3 : any +>p2 : any >div : any diff --git a/tests/baselines/reference/tsxReactEmit1.types b/tests/baselines/reference/tsxReactEmit1.types index b2cb2f73eba..8eb14e91963 100644 --- a/tests/baselines/reference/tsxReactEmit1.types +++ b/tests/baselines/reference/tsxReactEmit1.types @@ -63,7 +63,7 @@ var selfClosed7 =
; >
: JSX.Element >div : any >x : any ->p : undefined +>p : any >y : any >b : any @@ -85,7 +85,7 @@ var openClosed3 =
{p}
; >
{p}
: JSX.Element >div : any >n : any ->p : undefined +>p : any >div : any var openClosed4 =
{p < p}
; @@ -94,8 +94,8 @@ var openClosed4 =
{p < p}
; >div : any >n : any >p < p : boolean ->p : undefined ->p : undefined +>p : any +>p : any >div : any var openClosed5 =
{p > p}
; @@ -105,8 +105,8 @@ var openClosed5 =
{p > p}
; >n : any >b : any >p > p : boolean ->p : undefined ->p : undefined +>p : any +>p : any >div : any class SomeClass { @@ -184,7 +184,7 @@ var whitespace2 =
{p}
; >whitespace2 : JSX.Element >
{p}
: JSX.Element >div : any ->p : undefined +>p : any >div : any var whitespace3 =
@@ -193,7 +193,7 @@ var whitespace3 =
>div : any {p} ->p : undefined +>p : any
; >div : any diff --git a/tests/baselines/reference/tsxReactEmit2.types b/tests/baselines/reference/tsxReactEmit2.types index b05764e996f..928eeecadfa 100644 --- a/tests/baselines/reference/tsxReactEmit2.types +++ b/tests/baselines/reference/tsxReactEmit2.types @@ -24,16 +24,16 @@ var spreads1 =
{p2}
; >spreads1 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined ->p2 : undefined +>p1 : any +>p2 : any >div : any var spreads2 =
{p2}
; >spreads2 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined ->p2 : undefined +>p1 : any +>p2 : any >div : any var spreads3 =
{p2}
; @@ -41,19 +41,19 @@ var spreads3 =
{p2}
; >
{p2}
: JSX.Element >div : any >x : any ->p3 : undefined ->p1 : undefined ->p2 : undefined +>p3 : any +>p1 : any +>p2 : any >div : any var spreads4 =
{p2}
; >spreads4 : JSX.Element >
{p2}
: JSX.Element >div : any ->p1 : undefined +>p1 : any >x : any ->p3 : undefined ->p2 : undefined +>p3 : any +>p2 : any >div : any var spreads5 =
{p2}
; @@ -61,10 +61,10 @@ var spreads5 =
{p2}
; >
{p2}
: JSX.Element >div : any >x : any ->p2 : undefined ->p1 : undefined +>p2 : any +>p1 : any >y : any ->p3 : undefined ->p2 : undefined +>p3 : any +>p2 : any >div : any diff --git a/tests/baselines/reference/tsxReactEmit5.types b/tests/baselines/reference/tsxReactEmit5.types index 73e7e6ff391..fb1c6594f30 100644 --- a/tests/baselines/reference/tsxReactEmit5.types +++ b/tests/baselines/reference/tsxReactEmit5.types @@ -32,6 +32,6 @@ var spread1 =
; >
: JSX.Element >div : any >x : any ->foo : undefined +>foo : any >y : any diff --git a/tests/baselines/reference/tsxReactEmit6.types b/tests/baselines/reference/tsxReactEmit6.types index ae56de052cc..b8a307eb9d7 100644 --- a/tests/baselines/reference/tsxReactEmit6.types +++ b/tests/baselines/reference/tsxReactEmit6.types @@ -35,7 +35,7 @@ namespace M { >
: JSX.Element >div : any >x : any ->foo : undefined +>foo : any >y : any // Quotes diff --git a/tests/baselines/reference/tsxReactEmitNesting.js b/tests/baselines/reference/tsxReactEmitNesting.js index 29e948f687b..eaee315c340 100644 --- a/tests/baselines/reference/tsxReactEmitNesting.js +++ b/tests/baselines/reference/tsxReactEmitNesting.js @@ -38,21 +38,21 @@ let render = (ctrl, model) => //// [file.js] // A simple render function with nesting and control statements var render = function (ctrl, model) { - return vdom.createElement("section", { class: "todoapp" }, - vdom.createElement("header", { class: "header" }, + return vdom.createElement("section", { "class": "todoapp" }, + vdom.createElement("header", { "class": "header" }, vdom.createElement("h1", null, "todos "), - vdom.createElement("input", { class: "new-todo", autofocus: true, autocomplete: "off", placeholder: "What needs to be done?", value: model.newTodo, onKeyup: ctrl.addTodo.bind(ctrl, model) })), - vdom.createElement("section", { class: "main", style: { display: (model.todos && model.todos.length) ? "block" : "none" } }, - vdom.createElement("input", { class: "toggle-all", type: "checkbox", onChange: ctrl.toggleAll.bind(ctrl) }), - vdom.createElement("ul", { class: "todo-list" }, model.filteredTodos.map(function (todo) { - return vdom.createElement("li", { class: { todo: true, completed: todo.completed, editing: todo == model.editedTodo } }, - vdom.createElement("div", { class: "view" }, + vdom.createElement("input", { "class": "new-todo", autofocus: true, autocomplete: "off", placeholder: "What needs to be done?", value: model.newTodo, onKeyup: ctrl.addTodo.bind(ctrl, model) })), + vdom.createElement("section", { "class": "main", style: { display: (model.todos && model.todos.length) ? "block" : "none" } }, + vdom.createElement("input", { "class": "toggle-all", type: "checkbox", onChange: ctrl.toggleAll.bind(ctrl) }), + vdom.createElement("ul", { "class": "todo-list" }, model.filteredTodos.map(function (todo) { + return vdom.createElement("li", { "class": { todo: true, completed: todo.completed, editing: todo == model.editedTodo } }, + vdom.createElement("div", { "class": "view" }, (!todo.editable) ? - vdom.createElement("input", { class: "toggle", type: "checkbox" }) + vdom.createElement("input", { "class": "toggle", type: "checkbox" }) : null, vdom.createElement("label", { onDoubleClick: function () { ctrl.editTodo(todo); } }, todo.title), - vdom.createElement("button", { class: "destroy", onClick: ctrl.removeTodo.bind(ctrl, todo) }), - vdom.createElement("div", { class: "iconBorder" }, - vdom.createElement("div", { class: "icon" })))); + vdom.createElement("button", { "class": "destroy", onClick: ctrl.removeTodo.bind(ctrl, todo) }), + vdom.createElement("div", { "class": "iconBorder" }, + vdom.createElement("div", { "class": "icon" })))); })))); }; diff --git a/tests/baselines/reference/typeAliasDeclarationEmit.errors.txt b/tests/baselines/reference/typeAliasDeclarationEmit.errors.txt new file mode 100644 index 00000000000..2fd71844dc4 --- /dev/null +++ b/tests/baselines/reference/typeAliasDeclarationEmit.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/typeAliasDeclarationEmit.ts(4,37): error TS2314: Generic type 'callback' requires 1 type argument(s). + + +==== tests/cases/compiler/typeAliasDeclarationEmit.ts (1 errors) ==== + + export type callback = () => T; + + export type CallbackArray = () => T; + ~~~~~~~~ +!!! error TS2314: Generic type 'callback' requires 1 type argument(s). \ No newline at end of file diff --git a/tests/baselines/reference/typeAliasDeclarationEmit.js b/tests/baselines/reference/typeAliasDeclarationEmit.js index 6e82fe4b07d..1f72e1d1b00 100644 --- a/tests/baselines/reference/typeAliasDeclarationEmit.js +++ b/tests/baselines/reference/typeAliasDeclarationEmit.js @@ -6,6 +6,7 @@ export type CallbackArray = () => T; //// [typeAliasDeclarationEmit.js] define(["require", "exports"], function (require, exports) { + "use strict"; }); diff --git a/tests/baselines/reference/typeAliasDeclarationEmit2.js b/tests/baselines/reference/typeAliasDeclarationEmit2.js index 4bb1bd3efd9..b94eb56a2a2 100644 --- a/tests/baselines/reference/typeAliasDeclarationEmit2.js +++ b/tests/baselines/reference/typeAliasDeclarationEmit2.js @@ -4,6 +4,7 @@ export type A = { value: a }; //// [typeAliasDeclarationEmit2.js] define(["require", "exports"], function (require, exports) { + "use strict"; }); diff --git a/tests/baselines/reference/typeAliasDeclarationEmit2.types b/tests/baselines/reference/typeAliasDeclarationEmit2.types index bc8bd30935e..2cbee5aae4c 100644 --- a/tests/baselines/reference/typeAliasDeclarationEmit2.types +++ b/tests/baselines/reference/typeAliasDeclarationEmit2.types @@ -1,7 +1,7 @@ === tests/cases/compiler/typeAliasDeclarationEmit2.ts === export type A = { value: a }; ->A : { value: a; } +>A : A >a : a >value : a >a : a diff --git a/tests/baselines/reference/typeAliases.types b/tests/baselines/reference/typeAliases.types index 1d798bc14a6..6c8e897480c 100644 --- a/tests/baselines/reference/typeAliases.types +++ b/tests/baselines/reference/typeAliases.types @@ -104,7 +104,7 @@ var x9: T9; >T9 : T9 type T10 = { x: number }; ->T10 : { x: number; } +>T10 : T10 >x : number var x10: { x: number }; @@ -113,17 +113,17 @@ var x10: { x: number }; var x10: T10; >x10 : { x: number; } ->T10 : { x: number; } +>T10 : T10 type T11 = { new(): boolean }; ->T11 : new () => boolean +>T11 : T11 var x11: { new(): boolean }; >x11 : new () => boolean var x11: T11; >x11 : new () => boolean ->T11 : new () => boolean +>T11 : T11 interface I13 { x: string }; >I13 : I13 diff --git a/tests/baselines/reference/typeArgumentInferenceWithRecursivelyReferencedTypeAliasToTypeLiteral02.types b/tests/baselines/reference/typeArgumentInferenceWithRecursivelyReferencedTypeAliasToTypeLiteral02.types index 6e3997c2d1f..a75a997eb78 100644 --- a/tests/baselines/reference/typeArgumentInferenceWithRecursivelyReferencedTypeAliasToTypeLiteral02.types +++ b/tests/baselines/reference/typeArgumentInferenceWithRecursivelyReferencedTypeAliasToTypeLiteral02.types @@ -11,7 +11,7 @@ type TreeNode = { } type TreeNodeMiddleman = { ->TreeNodeMiddleman : { name: string; parent: TreeNode; } +>TreeNodeMiddleman : TreeNodeMiddleman name: string; >name : string @@ -22,17 +22,17 @@ type TreeNodeMiddleman = { } var nodes: TreeNodeMiddleman[]; ->nodes : { name: string; parent: TreeNode; }[] ->TreeNodeMiddleman : { name: string; parent: TreeNode; } +>nodes : TreeNodeMiddleman[] +>TreeNodeMiddleman : TreeNodeMiddleman nodes.map(n => n.name); >nodes.map(n => n.name) : string[] ->nodes.map : { (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): U[]; } ->nodes : { name: string; parent: TreeNode; }[] ->map : { (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U, U]; (this: [{ name: string; parent: TreeNode; }, { name: string; parent: TreeNode; }], callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: { name: string; parent: TreeNode; }, index: number, array: { name: string; parent: TreeNode; }[]) => U, thisArg?: any): U[]; } ->n => n.name : (n: { name: string; parent: TreeNode; }) => string ->n : { name: string; parent: TreeNode; } +>nodes.map : { (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): U[]; } +>nodes : TreeNodeMiddleman[] +>map : { (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U, U]; (this: [TreeNodeMiddleman, TreeNodeMiddleman], callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): [U, U]; (callbackfn: (value: TreeNodeMiddleman, index: number, array: TreeNodeMiddleman[]) => U, thisArg?: any): U[]; } +>n => n.name : (n: TreeNodeMiddleman) => string +>n : TreeNodeMiddleman >n.name : string ->n : { name: string; parent: TreeNode; } +>n : TreeNodeMiddleman >name : string diff --git a/tests/baselines/reference/typeArgumentsWithStringLiteralTypes01.js b/tests/baselines/reference/typeArgumentsWithStringLiteralTypes01.js index c07dd225396..74a609694aa 100644 --- a/tests/baselines/reference/typeArgumentsWithStringLiteralTypes01.js +++ b/tests/baselines/reference/typeArgumentsWithStringLiteralTypes01.js @@ -122,7 +122,7 @@ function fun2(x, y) { function fun3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } return args[+randBool()]; } diff --git a/tests/baselines/reference/typeCheckObjectCreationExpressionWithUndefinedCallResolutionData.errors.txt b/tests/baselines/reference/typeCheckObjectCreationExpressionWithUndefinedCallResolutionData.errors.txt deleted file mode 100644 index 3f8cdf56c3d..00000000000 --- a/tests/baselines/reference/typeCheckObjectCreationExpressionWithUndefinedCallResolutionData.errors.txt +++ /dev/null @@ -1,15 +0,0 @@ -tests/cases/compiler/file1.ts(3,12): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. - - -==== tests/cases/compiler/file2.ts (0 errors) ==== - import f = require('./file1'); - f.foo(); - -==== tests/cases/compiler/file1.ts (1 errors) ==== - export function foo() { - var classes = undefined; - return new classes(null); - ~~~~~~~~~~~~~~~~~ -!!! error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. - } - \ No newline at end of file diff --git a/tests/baselines/reference/typeGuardFunctionErrors.js b/tests/baselines/reference/typeGuardFunctionErrors.js index 6f0880ad7f5..99c25faaa88 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.js +++ b/tests/baselines/reference/typeGuardFunctionErrors.js @@ -171,7 +171,6 @@ var C = (function (_super) { function hasANonBooleanReturnStatement(x) { return ''; } -function hasTypeGuardTypeInsideTypeGuardType(x) { } is; A; { @@ -232,7 +231,6 @@ function b2(a, A) { if (a === void 0) { a = is; } } ; -function b3() { } is; A; { @@ -266,7 +264,7 @@ C; function b4() { var a = []; for (var _i = 0; _i < arguments.length; _i++) { - a[_i - 0] = arguments[_i]; + a[_i] = arguments[_i]; } return true; } diff --git a/tests/baselines/reference/typeGuardNarrowsPrimitiveIntersection.types b/tests/baselines/reference/typeGuardNarrowsPrimitiveIntersection.types index 478363669b4..f793ca34548 100644 --- a/tests/baselines/reference/typeGuardNarrowsPrimitiveIntersection.types +++ b/tests/baselines/reference/typeGuardNarrowsPrimitiveIntersection.types @@ -1,18 +1,18 @@ === tests/cases/conformance/expressions/typeGuards/typeGuardNarrowsPrimitiveIntersection.ts === type Tag = {__tag: any}; ->Tag : { __tag: any; } +>Tag : Tag >__tag : any declare function isNonBlank(value: string) : value is (string & Tag); ->isNonBlank : (value: string) => value is string & { __tag: any; } +>isNonBlank : (value: string) => value is string & Tag >value : string >value : any ->Tag : { __tag: any; } +>Tag : Tag declare function doThis(value: string & Tag): void; ->doThis : (value: string & { __tag: any; }) => void ->value : string & { __tag: any; } ->Tag : { __tag: any; } +>doThis : (value: string & Tag) => void +>value : string & Tag +>Tag : Tag declare function doThat(value: string) : void; >doThat : (value: string) => void @@ -23,13 +23,13 @@ let value: string; if (isNonBlank(value)) { >isNonBlank(value) : boolean ->isNonBlank : (value: string) => value is string & { __tag: any; } +>isNonBlank : (value: string) => value is string & Tag >value : string doThis(value); >doThis(value) : void ->doThis : (value: string & { __tag: any; }) => void ->value : string & { __tag: any; } +>doThis : (value: string & Tag) => void +>value : string & Tag } else { doThat(value); diff --git a/tests/baselines/reference/typeGuardsWithInstanceOf.types b/tests/baselines/reference/typeGuardsWithInstanceOf.types index f54498f93c8..7fce8cd4559 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOf.types +++ b/tests/baselines/reference/typeGuardsWithInstanceOf.types @@ -25,7 +25,7 @@ if (!(result instanceof RegExp)) { } else if (!result.global) { >!result.global : boolean ->result.global : string & boolean +>result.global : (string & true) | (string & false) >result : I & RegExp ->global : string & boolean +>global : (string & true) | (string & false) } diff --git a/tests/baselines/reference/typePredicateInLoop.js b/tests/baselines/reference/typePredicateInLoop.js new file mode 100644 index 00000000000..0a1e621cb50 --- /dev/null +++ b/tests/baselines/reference/typePredicateInLoop.js @@ -0,0 +1,38 @@ +//// [typePredicateInLoop.ts] +// Repro from #12101 + +interface Type { + type: number; +} + +interface TypeExt extends Type { + arr: Type[]; +} + +const guard = (arg: Type): arg is TypeExt => arg.type === 1; +const otherFunc = (arg1: Type, arg2: TypeExt): void => {}; + +export function y(arg: Type): void { + if (guard(arg)) { + for (const ITEM of arg.arr) { + if (otherFunc(ITEM, arg)) { + } + } + } +} + +//// [typePredicateInLoop.js] +// Repro from #12101 +"use strict"; +var guard = function (arg) { return arg.type === 1; }; +var otherFunc = function (arg1, arg2) { }; +function y(arg) { + if (guard(arg)) { + for (var _i = 0, _a = arg.arr; _i < _a.length; _i++) { + var ITEM = _a[_i]; + if (otherFunc(ITEM, arg)) { + } + } + } +} +exports.y = y; diff --git a/tests/baselines/reference/typePredicateInLoop.symbols b/tests/baselines/reference/typePredicateInLoop.symbols new file mode 100644 index 00000000000..1cc57b36c6d --- /dev/null +++ b/tests/baselines/reference/typePredicateInLoop.symbols @@ -0,0 +1,59 @@ +=== tests/cases/compiler/typePredicateInLoop.ts === +// Repro from #12101 + +interface Type { +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) + + type: number; +>type : Symbol(Type.type, Decl(typePredicateInLoop.ts, 2, 16)) +} + +interface TypeExt extends Type { +>TypeExt : Symbol(TypeExt, Decl(typePredicateInLoop.ts, 4, 1)) +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) + + arr: Type[]; +>arr : Symbol(TypeExt.arr, Decl(typePredicateInLoop.ts, 6, 32)) +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) +} + +const guard = (arg: Type): arg is TypeExt => arg.type === 1; +>guard : Symbol(guard, Decl(typePredicateInLoop.ts, 10, 5)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 10, 15)) +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 10, 15)) +>TypeExt : Symbol(TypeExt, Decl(typePredicateInLoop.ts, 4, 1)) +>arg.type : Symbol(Type.type, Decl(typePredicateInLoop.ts, 2, 16)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 10, 15)) +>type : Symbol(Type.type, Decl(typePredicateInLoop.ts, 2, 16)) + +const otherFunc = (arg1: Type, arg2: TypeExt): void => {}; +>otherFunc : Symbol(otherFunc, Decl(typePredicateInLoop.ts, 11, 5)) +>arg1 : Symbol(arg1, Decl(typePredicateInLoop.ts, 11, 19)) +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) +>arg2 : Symbol(arg2, Decl(typePredicateInLoop.ts, 11, 30)) +>TypeExt : Symbol(TypeExt, Decl(typePredicateInLoop.ts, 4, 1)) + +export function y(arg: Type): void { +>y : Symbol(y, Decl(typePredicateInLoop.ts, 11, 58)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 13, 18)) +>Type : Symbol(Type, Decl(typePredicateInLoop.ts, 0, 0)) + + if (guard(arg)) { +>guard : Symbol(guard, Decl(typePredicateInLoop.ts, 10, 5)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 13, 18)) + + for (const ITEM of arg.arr) { +>ITEM : Symbol(ITEM, Decl(typePredicateInLoop.ts, 15, 14)) +>arg.arr : Symbol(TypeExt.arr, Decl(typePredicateInLoop.ts, 6, 32)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 13, 18)) +>arr : Symbol(TypeExt.arr, Decl(typePredicateInLoop.ts, 6, 32)) + + if (otherFunc(ITEM, arg)) { +>otherFunc : Symbol(otherFunc, Decl(typePredicateInLoop.ts, 11, 5)) +>ITEM : Symbol(ITEM, Decl(typePredicateInLoop.ts, 15, 14)) +>arg : Symbol(arg, Decl(typePredicateInLoop.ts, 13, 18)) + } + } + } +} diff --git a/tests/baselines/reference/typePredicateInLoop.types b/tests/baselines/reference/typePredicateInLoop.types new file mode 100644 index 00000000000..7ffe887e91d --- /dev/null +++ b/tests/baselines/reference/typePredicateInLoop.types @@ -0,0 +1,65 @@ +=== tests/cases/compiler/typePredicateInLoop.ts === +// Repro from #12101 + +interface Type { +>Type : Type + + type: number; +>type : number +} + +interface TypeExt extends Type { +>TypeExt : TypeExt +>Type : Type + + arr: Type[]; +>arr : Type[] +>Type : Type +} + +const guard = (arg: Type): arg is TypeExt => arg.type === 1; +>guard : (arg: Type) => arg is TypeExt +>(arg: Type): arg is TypeExt => arg.type === 1 : (arg: Type) => arg is TypeExt +>arg : Type +>Type : Type +>arg : any +>TypeExt : TypeExt +>arg.type === 1 : boolean +>arg.type : number +>arg : Type +>type : number +>1 : 1 + +const otherFunc = (arg1: Type, arg2: TypeExt): void => {}; +>otherFunc : (arg1: Type, arg2: TypeExt) => void +>(arg1: Type, arg2: TypeExt): void => {} : (arg1: Type, arg2: TypeExt) => void +>arg1 : Type +>Type : Type +>arg2 : TypeExt +>TypeExt : TypeExt + +export function y(arg: Type): void { +>y : (arg: Type) => void +>arg : Type +>Type : Type + + if (guard(arg)) { +>guard(arg) : boolean +>guard : (arg: Type) => arg is TypeExt +>arg : Type + + for (const ITEM of arg.arr) { +>ITEM : Type +>arg.arr : Type[] +>arg : TypeExt +>arr : Type[] + + if (otherFunc(ITEM, arg)) { +>otherFunc(ITEM, arg) : void +>otherFunc : (arg1: Type, arg2: TypeExt) => void +>ITEM : Type +>arg : TypeExt + } + } + } +} diff --git a/tests/baselines/reference/typePredicateStructuralMatch.js b/tests/baselines/reference/typePredicateStructuralMatch.js new file mode 100644 index 00000000000..682fac5536e --- /dev/null +++ b/tests/baselines/reference/typePredicateStructuralMatch.js @@ -0,0 +1,46 @@ +//// [typePredicateStructuralMatch.ts] +// Repro from #12235 + +getResults1([]); +getResults1({data: []}); + +getResults2([]); +getResults2({data: []}); + +type Result = { value: string }; +type Results = Result[]; + +function isResponseInData(value: T | { data: T}): value is { data: T } { + return value.hasOwnProperty('data'); +} + +function getResults1(value: Results | { data: Results }): Results { + return isResponseInData(value) ? value.data : value; +} + +function isPlainResponse(value: T | { data: T}): value is T { + return !value.hasOwnProperty('data'); +} + +function getResults2(value: Results | { data: Results }): Results { + return isPlainResponse(value) ? value : value.data; +} + +//// [typePredicateStructuralMatch.js] +// Repro from #12235 +getResults1([]); +getResults1({ data: [] }); +getResults2([]); +getResults2({ data: [] }); +function isResponseInData(value) { + return value.hasOwnProperty('data'); +} +function getResults1(value) { + return isResponseInData(value) ? value.data : value; +} +function isPlainResponse(value) { + return !value.hasOwnProperty('data'); +} +function getResults2(value) { + return isPlainResponse(value) ? value : value.data; +} diff --git a/tests/baselines/reference/typePredicateStructuralMatch.symbols b/tests/baselines/reference/typePredicateStructuralMatch.symbols new file mode 100644 index 00000000000..59d548d4bfc --- /dev/null +++ b/tests/baselines/reference/typePredicateStructuralMatch.symbols @@ -0,0 +1,91 @@ +=== tests/cases/compiler/typePredicateStructuralMatch.ts === +// Repro from #12235 + +getResults1([]); +>getResults1 : Symbol(getResults1, Decl(typePredicateStructuralMatch.ts, 13, 1)) + +getResults1({data: []}); +>getResults1 : Symbol(getResults1, Decl(typePredicateStructuralMatch.ts, 13, 1)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 3, 13)) + +getResults2([]); +>getResults2 : Symbol(getResults2, Decl(typePredicateStructuralMatch.ts, 21, 1)) + +getResults2({data: []}); +>getResults2 : Symbol(getResults2, Decl(typePredicateStructuralMatch.ts, 21, 1)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 6, 13)) + +type Result = { value: string }; +>Result : Symbol(Result, Decl(typePredicateStructuralMatch.ts, 6, 24)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 8, 15)) + +type Results = Result[]; +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) +>Result : Symbol(Result, Decl(typePredicateStructuralMatch.ts, 6, 24)) + +function isResponseInData(value: T | { data: T}): value is { data: T } { +>isResponseInData : Symbol(isResponseInData, Decl(typePredicateStructuralMatch.ts, 9, 24)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 11, 26)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 11, 29)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 11, 26)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 11, 41)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 11, 26)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 11, 29)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 11, 63)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 11, 26)) + + return value.hasOwnProperty('data'); +>value.hasOwnProperty : Symbol(Object.hasOwnProperty, Decl(lib.d.ts, --, --)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 11, 29)) +>hasOwnProperty : Symbol(Object.hasOwnProperty, Decl(lib.d.ts, --, --)) +} + +function getResults1(value: Results | { data: Results }): Results { +>getResults1 : Symbol(getResults1, Decl(typePredicateStructuralMatch.ts, 13, 1)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 15, 21)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 15, 39)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) + + return isResponseInData(value) ? value.data : value; +>isResponseInData : Symbol(isResponseInData, Decl(typePredicateStructuralMatch.ts, 9, 24)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 15, 21)) +>value.data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 15, 39)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 15, 21)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 15, 39)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 15, 21)) +} + +function isPlainResponse(value: T | { data: T}): value is T { +>isPlainResponse : Symbol(isPlainResponse, Decl(typePredicateStructuralMatch.ts, 17, 1)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 19, 25)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 19, 28)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 19, 25)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 19, 40)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 19, 25)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 19, 28)) +>T : Symbol(T, Decl(typePredicateStructuralMatch.ts, 19, 25)) + + return !value.hasOwnProperty('data'); +>value.hasOwnProperty : Symbol(Object.hasOwnProperty, Decl(lib.d.ts, --, --)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 19, 28)) +>hasOwnProperty : Symbol(Object.hasOwnProperty, Decl(lib.d.ts, --, --)) +} + +function getResults2(value: Results | { data: Results }): Results { +>getResults2 : Symbol(getResults2, Decl(typePredicateStructuralMatch.ts, 21, 1)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 23, 21)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 23, 39)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) +>Results : Symbol(Results, Decl(typePredicateStructuralMatch.ts, 8, 32)) + + return isPlainResponse(value) ? value : value.data; +>isPlainResponse : Symbol(isPlainResponse, Decl(typePredicateStructuralMatch.ts, 17, 1)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 23, 21)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 23, 21)) +>value.data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 23, 39)) +>value : Symbol(value, Decl(typePredicateStructuralMatch.ts, 23, 21)) +>data : Symbol(data, Decl(typePredicateStructuralMatch.ts, 23, 39)) +} diff --git a/tests/baselines/reference/typePredicateStructuralMatch.types b/tests/baselines/reference/typePredicateStructuralMatch.types new file mode 100644 index 00000000000..9f7a129da15 --- /dev/null +++ b/tests/baselines/reference/typePredicateStructuralMatch.types @@ -0,0 +1,110 @@ +=== tests/cases/compiler/typePredicateStructuralMatch.ts === +// Repro from #12235 + +getResults1([]); +>getResults1([]) : Result[] +>getResults1 : (value: Result[] | { data: Result[]; }) => Result[] +>[] : undefined[] + +getResults1({data: []}); +>getResults1({data: []}) : Result[] +>getResults1 : (value: Result[] | { data: Result[]; }) => Result[] +>{data: []} : { data: undefined[]; } +>data : undefined[] +>[] : undefined[] + +getResults2([]); +>getResults2([]) : Result[] +>getResults2 : (value: Result[] | { data: Result[]; }) => Result[] +>[] : undefined[] + +getResults2({data: []}); +>getResults2({data: []}) : Result[] +>getResults2 : (value: Result[] | { data: Result[]; }) => Result[] +>{data: []} : { data: undefined[]; } +>data : undefined[] +>[] : undefined[] + +type Result = { value: string }; +>Result : Result +>value : string + +type Results = Result[]; +>Results : Result[] +>Result : Result + +function isResponseInData(value: T | { data: T}): value is { data: T } { +>isResponseInData : (value: T | { data: T; }) => value is { data: T; } +>T : T +>value : T | { data: T; } +>T : T +>data : T +>T : T +>value : any +>data : T +>T : T + + return value.hasOwnProperty('data'); +>value.hasOwnProperty('data') : boolean +>value.hasOwnProperty : (v: string) => boolean +>value : T | { data: T; } +>hasOwnProperty : (v: string) => boolean +>'data' : "data" +} + +function getResults1(value: Results | { data: Results }): Results { +>getResults1 : (value: Result[] | { data: Result[]; }) => Result[] +>value : Result[] | { data: Result[]; } +>Results : Result[] +>data : Result[] +>Results : Result[] +>Results : Result[] + + return isResponseInData(value) ? value.data : value; +>isResponseInData(value) ? value.data : value : Result[] +>isResponseInData(value) : boolean +>isResponseInData : (value: T | { data: T; }) => value is { data: T; } +>value : Result[] | { data: Result[]; } +>value.data : Result[] +>value : { data: Result[]; } +>data : Result[] +>value : Result[] +} + +function isPlainResponse(value: T | { data: T}): value is T { +>isPlainResponse : (value: T | { data: T; }) => value is T +>T : T +>value : T | { data: T; } +>T : T +>data : T +>T : T +>value : any +>T : T + + return !value.hasOwnProperty('data'); +>!value.hasOwnProperty('data') : boolean +>value.hasOwnProperty('data') : boolean +>value.hasOwnProperty : (v: string) => boolean +>value : T | { data: T; } +>hasOwnProperty : (v: string) => boolean +>'data' : "data" +} + +function getResults2(value: Results | { data: Results }): Results { +>getResults2 : (value: Result[] | { data: Result[]; }) => Result[] +>value : Result[] | { data: Result[]; } +>Results : Result[] +>data : Result[] +>Results : Result[] +>Results : Result[] + + return isPlainResponse(value) ? value : value.data; +>isPlainResponse(value) ? value : value.data : Result[] +>isPlainResponse(value) : boolean +>isPlainResponse : (value: T | { data: T; }) => value is T +>value : Result[] | { data: Result[]; } +>value : Result[] +>value.data : Result[] +>value : { data: Result[]; } +>data : Result[] +} diff --git a/tests/baselines/reference/typeQueryWithReservedWords.js b/tests/baselines/reference/typeQueryWithReservedWords.js index 7561eeddb75..09c3b642a36 100644 --- a/tests/baselines/reference/typeQueryWithReservedWords.js +++ b/tests/baselines/reference/typeQueryWithReservedWords.js @@ -21,9 +21,9 @@ var Controller = (function () { } Controller.prototype.create = function () { }; - Controller.prototype.delete = function () { + Controller.prototype["delete"] = function () { }; - Controller.prototype.var = function () { + Controller.prototype["var"] = function () { }; return Controller; }()); diff --git a/tests/baselines/reference/typeReferenceDirectives1.trace.json b/tests/baselines/reference/typeReferenceDirectives1.trace.json index 58b23783b0b..8532d21da89 100644 --- a/tests/baselines/reference/typeReferenceDirectives1.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives1.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives10.trace.json b/tests/baselines/reference/typeReferenceDirectives10.trace.json index 61341afdab3..5bd31419793 100644 --- a/tests/baselines/reference/typeReferenceDirectives10.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives10.trace.json @@ -3,6 +3,7 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving module './ref' from '/app.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -10,11 +11,11 @@ "File '/ref.ts' does not exist.", "File '/ref.tsx' does not exist.", "File '/ref.d.ts' exist - use it as a name resolution result.", - "Resolving real path for '/ref.d.ts', result '/ref.d.ts'", "======== Module name './ref' was successfully resolved to '/ref.d.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives11.trace.json b/tests/baselines/reference/typeReferenceDirectives11.trace.json index 37fa7900a7c..a6ab6bc8d68 100644 --- a/tests/baselines/reference/typeReferenceDirectives11.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives11.trace.json @@ -3,11 +3,11 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/mod1'.", "File '/mod1.ts' exist - use it as a name resolution result.", - "Resolving real path for '/mod1.ts', result '/mod1.ts'", "======== Module name './mod1' was successfully resolved to '/mod1.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives12.trace.json b/tests/baselines/reference/typeReferenceDirectives12.trace.json index 1024b0cdef3..5f87ab7ea39 100644 --- a/tests/baselines/reference/typeReferenceDirectives12.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives12.trace.json @@ -3,28 +3,25 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/main'.", "File '/main.ts' exist - use it as a name resolution result.", - "Resolving real path for '/main.ts', result '/main.ts'", "======== Module name './main' was successfully resolved to '/main.ts'. ========", "======== Resolving module './mod1' from '/mod2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/mod1'.", "File '/mod1.ts' exist - use it as a name resolution result.", - "Resolving real path for '/mod1.ts', result '/mod1.ts'", "======== Module name './mod1' was successfully resolved to '/mod1.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/mod1.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving module './main' from '/mod1.ts'. ========", - "Module resolution kind is not specified, using 'NodeJs'.", - "Loading module as file / folder, candidate module location '/main'.", - "File '/main.ts' exist - use it as a name resolution result.", - "Resolving real path for '/main.ts', result '/main.ts'", + "Resolution for module './main' was found in cache", "======== Module name './main' was successfully resolved to '/main.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives13.trace.json b/tests/baselines/reference/typeReferenceDirectives13.trace.json index 61341afdab3..5bd31419793 100644 --- a/tests/baselines/reference/typeReferenceDirectives13.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives13.trace.json @@ -3,6 +3,7 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving module './ref' from '/app.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -10,11 +11,11 @@ "File '/ref.ts' does not exist.", "File '/ref.tsx' does not exist.", "File '/ref.d.ts' exist - use it as a name resolution result.", - "Resolving real path for '/ref.d.ts', result '/ref.d.ts'", "======== Module name './ref' was successfully resolved to '/ref.d.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives2.trace.json b/tests/baselines/reference/typeReferenceDirectives2.trace.json index 93d3658447d..1258ecdaa2b 100644 --- a/tests/baselines/reference/typeReferenceDirectives2.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives2.trace.json @@ -3,5 +3,6 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives3.trace.json b/tests/baselines/reference/typeReferenceDirectives3.trace.json index 58b23783b0b..8532d21da89 100644 --- a/tests/baselines/reference/typeReferenceDirectives3.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives3.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives4.trace.json b/tests/baselines/reference/typeReferenceDirectives4.trace.json index 58b23783b0b..8532d21da89 100644 --- a/tests/baselines/reference/typeReferenceDirectives4.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives4.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives5.trace.json b/tests/baselines/reference/typeReferenceDirectives5.trace.json index 61341afdab3..5bd31419793 100644 --- a/tests/baselines/reference/typeReferenceDirectives5.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives5.trace.json @@ -3,6 +3,7 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving module './ref' from '/app.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -10,11 +11,11 @@ "File '/ref.ts' does not exist.", "File '/ref.tsx' does not exist.", "File '/ref.d.ts' exist - use it as a name resolution result.", - "Resolving real path for '/ref.d.ts', result '/ref.d.ts'", "======== Module name './ref' was successfully resolved to '/ref.d.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives6.trace.json b/tests/baselines/reference/typeReferenceDirectives6.trace.json index 58b23783b0b..8532d21da89 100644 --- a/tests/baselines/reference/typeReferenceDirectives6.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives6.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives7.trace.json b/tests/baselines/reference/typeReferenceDirectives7.trace.json index 58b23783b0b..8532d21da89 100644 --- a/tests/baselines/reference/typeReferenceDirectives7.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives7.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives8.trace.json b/tests/baselines/reference/typeReferenceDirectives8.trace.json index 37fa7900a7c..a6ab6bc8d68 100644 --- a/tests/baselines/reference/typeReferenceDirectives8.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives8.trace.json @@ -3,11 +3,11 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/mod1'.", "File '/mod1.ts' exist - use it as a name resolution result.", - "Resolving real path for '/mod1.ts', result '/mod1.ts'", "======== Module name './mod1' was successfully resolved to '/mod1.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeReferenceDirectives9.trace.json b/tests/baselines/reference/typeReferenceDirectives9.trace.json index 1024b0cdef3..5f87ab7ea39 100644 --- a/tests/baselines/reference/typeReferenceDirectives9.trace.json +++ b/tests/baselines/reference/typeReferenceDirectives9.trace.json @@ -3,28 +3,25 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/main'.", "File '/main.ts' exist - use it as a name resolution result.", - "Resolving real path for '/main.ts', result '/main.ts'", "======== Module name './main' was successfully resolved to '/main.ts'. ========", "======== Resolving module './mod1' from '/mod2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module as file / folder, candidate module location '/mod1'.", "File '/mod1.ts' exist - use it as a name resolution result.", - "Resolving real path for '/mod1.ts', result '/mod1.ts'", "======== Module name './mod1' was successfully resolved to '/mod1.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/mod1.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========", "======== Resolving module './main' from '/mod1.ts'. ========", - "Module resolution kind is not specified, using 'NodeJs'.", - "Loading module as file / folder, candidate module location '/main'.", - "File '/main.ts' exist - use it as a name resolution result.", - "Resolving real path for '/main.ts', result '/main.ts'", + "Resolution for module './main' was found in cache", "======== Module name './main' was successfully resolved to '/main.ts'. ========", "======== Resolving type reference directive 'lib', containing file '/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'", "File '/types/lib/package.json' does not exist.", "File '/types/lib/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/types/lib/index.d.ts', result '/types/lib/index.d.ts'", "======== Type reference directive 'lib' was successfully resolved to '/types/lib/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeRootsFromMultipleNodeModulesDirectories.trace.json b/tests/baselines/reference/typeRootsFromMultipleNodeModulesDirectories.trace.json index c734e57cda2..b38bb7c0acd 100644 --- a/tests/baselines/reference/typeRootsFromMultipleNodeModulesDirectories.trace.json +++ b/tests/baselines/reference/typeRootsFromMultipleNodeModulesDirectories.trace.json @@ -9,12 +9,8 @@ "File '/foo/bar/node_modules/xyz/index.ts' does not exist.", "File '/foo/bar/node_modules/xyz/index.tsx' does not exist.", "File '/foo/bar/node_modules/xyz/index.d.ts' does not exist.", - "File '/foo/bar/node_modules/@types/xyz.ts' does not exist.", - "File '/foo/bar/node_modules/@types/xyz.tsx' does not exist.", "File '/foo/bar/node_modules/@types/xyz.d.ts' does not exist.", "File '/foo/bar/node_modules/@types/xyz/package.json' does not exist.", - "File '/foo/bar/node_modules/@types/xyz/index.ts' does not exist.", - "File '/foo/bar/node_modules/@types/xyz/index.tsx' does not exist.", "File '/foo/bar/node_modules/@types/xyz/index.d.ts' does not exist.", "File '/foo/node_modules/xyz.ts' does not exist.", "File '/foo/node_modules/xyz.tsx' does not exist.", @@ -23,12 +19,8 @@ "File '/foo/node_modules/xyz/index.ts' does not exist.", "File '/foo/node_modules/xyz/index.tsx' does not exist.", "File '/foo/node_modules/xyz/index.d.ts' does not exist.", - "File '/foo/node_modules/@types/xyz.ts' does not exist.", - "File '/foo/node_modules/@types/xyz.tsx' does not exist.", "File '/foo/node_modules/@types/xyz.d.ts' does not exist.", "File '/foo/node_modules/@types/xyz/package.json' does not exist.", - "File '/foo/node_modules/@types/xyz/index.ts' does not exist.", - "File '/foo/node_modules/@types/xyz/index.tsx' does not exist.", "File '/foo/node_modules/@types/xyz/index.d.ts' does not exist.", "File '/node_modules/xyz.ts' does not exist.", "File '/node_modules/xyz.tsx' does not exist.", @@ -37,13 +29,25 @@ "File '/node_modules/xyz/index.ts' does not exist.", "File '/node_modules/xyz/index.tsx' does not exist.", "File '/node_modules/xyz/index.d.ts' does not exist.", - "File '/node_modules/@types/xyz.ts' does not exist.", - "File '/node_modules/@types/xyz.tsx' does not exist.", "File '/node_modules/@types/xyz.d.ts' does not exist.", "File '/node_modules/@types/xyz/package.json' does not exist.", - "File '/node_modules/@types/xyz/index.ts' does not exist.", - "File '/node_modules/@types/xyz/index.tsx' does not exist.", "File '/node_modules/@types/xyz/index.d.ts' does not exist.", + "Loading module 'xyz' from 'node_modules' folder.", + "File '/foo/bar/node_modules/xyz.js' does not exist.", + "File '/foo/bar/node_modules/xyz.jsx' does not exist.", + "File '/foo/bar/node_modules/xyz/package.json' does not exist.", + "File '/foo/bar/node_modules/xyz/index.js' does not exist.", + "File '/foo/bar/node_modules/xyz/index.jsx' does not exist.", + "File '/foo/node_modules/xyz.js' does not exist.", + "File '/foo/node_modules/xyz.jsx' does not exist.", + "File '/foo/node_modules/xyz/package.json' does not exist.", + "File '/foo/node_modules/xyz/index.js' does not exist.", + "File '/foo/node_modules/xyz/index.jsx' does not exist.", + "File '/node_modules/xyz.js' does not exist.", + "File '/node_modules/xyz.jsx' does not exist.", + "File '/node_modules/xyz/package.json' does not exist.", + "File '/node_modules/xyz/index.js' does not exist.", + "File '/node_modules/xyz/index.jsx' does not exist.", "======== Module name 'xyz' was not resolved. ========", "======== Resolving module 'pdq' from '/foo/bar/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -55,12 +59,8 @@ "File '/foo/bar/node_modules/pdq/index.ts' does not exist.", "File '/foo/bar/node_modules/pdq/index.tsx' does not exist.", "File '/foo/bar/node_modules/pdq/index.d.ts' does not exist.", - "File '/foo/bar/node_modules/@types/pdq.ts' does not exist.", - "File '/foo/bar/node_modules/@types/pdq.tsx' does not exist.", "File '/foo/bar/node_modules/@types/pdq.d.ts' does not exist.", "File '/foo/bar/node_modules/@types/pdq/package.json' does not exist.", - "File '/foo/bar/node_modules/@types/pdq/index.ts' does not exist.", - "File '/foo/bar/node_modules/@types/pdq/index.tsx' does not exist.", "File '/foo/bar/node_modules/@types/pdq/index.d.ts' does not exist.", "File '/foo/node_modules/pdq.ts' does not exist.", "File '/foo/node_modules/pdq.tsx' does not exist.", @@ -69,12 +69,8 @@ "File '/foo/node_modules/pdq/index.ts' does not exist.", "File '/foo/node_modules/pdq/index.tsx' does not exist.", "File '/foo/node_modules/pdq/index.d.ts' does not exist.", - "File '/foo/node_modules/@types/pdq.ts' does not exist.", - "File '/foo/node_modules/@types/pdq.tsx' does not exist.", "File '/foo/node_modules/@types/pdq.d.ts' does not exist.", "File '/foo/node_modules/@types/pdq/package.json' does not exist.", - "File '/foo/node_modules/@types/pdq/index.ts' does not exist.", - "File '/foo/node_modules/@types/pdq/index.tsx' does not exist.", "File '/foo/node_modules/@types/pdq/index.d.ts' does not exist.", "File '/node_modules/pdq.ts' does not exist.", "File '/node_modules/pdq.tsx' does not exist.", @@ -83,13 +79,25 @@ "File '/node_modules/pdq/index.ts' does not exist.", "File '/node_modules/pdq/index.tsx' does not exist.", "File '/node_modules/pdq/index.d.ts' does not exist.", - "File '/node_modules/@types/pdq.ts' does not exist.", - "File '/node_modules/@types/pdq.tsx' does not exist.", "File '/node_modules/@types/pdq.d.ts' does not exist.", "File '/node_modules/@types/pdq/package.json' does not exist.", - "File '/node_modules/@types/pdq/index.ts' does not exist.", - "File '/node_modules/@types/pdq/index.tsx' does not exist.", "File '/node_modules/@types/pdq/index.d.ts' does not exist.", + "Loading module 'pdq' from 'node_modules' folder.", + "File '/foo/bar/node_modules/pdq.js' does not exist.", + "File '/foo/bar/node_modules/pdq.jsx' does not exist.", + "File '/foo/bar/node_modules/pdq/package.json' does not exist.", + "File '/foo/bar/node_modules/pdq/index.js' does not exist.", + "File '/foo/bar/node_modules/pdq/index.jsx' does not exist.", + "File '/foo/node_modules/pdq.js' does not exist.", + "File '/foo/node_modules/pdq.jsx' does not exist.", + "File '/foo/node_modules/pdq/package.json' does not exist.", + "File '/foo/node_modules/pdq/index.js' does not exist.", + "File '/foo/node_modules/pdq/index.jsx' does not exist.", + "File '/node_modules/pdq.js' does not exist.", + "File '/node_modules/pdq.jsx' does not exist.", + "File '/node_modules/pdq/package.json' does not exist.", + "File '/node_modules/pdq/index.js' does not exist.", + "File '/node_modules/pdq/index.jsx' does not exist.", "======== Module name 'pdq' was not resolved. ========", "======== Resolving module 'abc' from '/foo/bar/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", @@ -101,12 +109,8 @@ "File '/foo/bar/node_modules/abc/index.ts' does not exist.", "File '/foo/bar/node_modules/abc/index.tsx' does not exist.", "File '/foo/bar/node_modules/abc/index.d.ts' does not exist.", - "File '/foo/bar/node_modules/@types/abc.ts' does not exist.", - "File '/foo/bar/node_modules/@types/abc.tsx' does not exist.", "File '/foo/bar/node_modules/@types/abc.d.ts' does not exist.", "File '/foo/bar/node_modules/@types/abc/package.json' does not exist.", - "File '/foo/bar/node_modules/@types/abc/index.ts' does not exist.", - "File '/foo/bar/node_modules/@types/abc/index.tsx' does not exist.", "File '/foo/bar/node_modules/@types/abc/index.d.ts' does not exist.", "File '/foo/node_modules/abc.ts' does not exist.", "File '/foo/node_modules/abc.tsx' does not exist.", @@ -115,12 +119,8 @@ "File '/foo/node_modules/abc/index.ts' does not exist.", "File '/foo/node_modules/abc/index.tsx' does not exist.", "File '/foo/node_modules/abc/index.d.ts' does not exist.", - "File '/foo/node_modules/@types/abc.ts' does not exist.", - "File '/foo/node_modules/@types/abc.tsx' does not exist.", "File '/foo/node_modules/@types/abc.d.ts' does not exist.", "File '/foo/node_modules/@types/abc/package.json' does not exist.", - "File '/foo/node_modules/@types/abc/index.ts' does not exist.", - "File '/foo/node_modules/@types/abc/index.tsx' does not exist.", "File '/foo/node_modules/@types/abc/index.d.ts' does not exist.", "File '/node_modules/abc.ts' does not exist.", "File '/node_modules/abc.tsx' does not exist.", @@ -129,29 +129,44 @@ "File '/node_modules/abc/index.ts' does not exist.", "File '/node_modules/abc/index.tsx' does not exist.", "File '/node_modules/abc/index.d.ts' does not exist.", - "File '/node_modules/@types/abc.ts' does not exist.", - "File '/node_modules/@types/abc.tsx' does not exist.", "File '/node_modules/@types/abc.d.ts' does not exist.", "File '/node_modules/@types/abc/package.json' does not exist.", - "File '/node_modules/@types/abc/index.ts' does not exist.", - "File '/node_modules/@types/abc/index.tsx' does not exist.", "File '/node_modules/@types/abc/index.d.ts' does not exist.", + "Loading module 'abc' from 'node_modules' folder.", + "File '/foo/bar/node_modules/abc.js' does not exist.", + "File '/foo/bar/node_modules/abc.jsx' does not exist.", + "File '/foo/bar/node_modules/abc/package.json' does not exist.", + "File '/foo/bar/node_modules/abc/index.js' does not exist.", + "File '/foo/bar/node_modules/abc/index.jsx' does not exist.", + "File '/foo/node_modules/abc.js' does not exist.", + "File '/foo/node_modules/abc.jsx' does not exist.", + "File '/foo/node_modules/abc/package.json' does not exist.", + "File '/foo/node_modules/abc/index.js' does not exist.", + "File '/foo/node_modules/abc/index.jsx' does not exist.", + "File '/node_modules/abc.js' does not exist.", + "File '/node_modules/abc.jsx' does not exist.", + "File '/node_modules/abc/package.json' does not exist.", + "File '/node_modules/abc/index.js' does not exist.", + "File '/node_modules/abc/index.jsx' does not exist.", "======== Module name 'abc' was not resolved. ========", - "======== Resolving type reference directive 'grumpy', containing file '/src/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", + "======== Resolving type reference directive 'grumpy', containing file '/foo/bar/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", "Resolving with primary search path '/foo/node_modules/@types, /node_modules/@types'", "File '/foo/node_modules/@types/grumpy/package.json' does not exist.", "File '/foo/node_modules/@types/grumpy/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/foo/node_modules/@types/grumpy/index.d.ts', result '/foo/node_modules/@types/grumpy/index.d.ts'", "======== Type reference directive 'grumpy' was successfully resolved to '/foo/node_modules/@types/grumpy/index.d.ts', primary: true. ========", - "======== Resolving type reference directive 'sneezy', containing file '/src/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", + "======== Resolving type reference directive 'sneezy', containing file '/foo/bar/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", "Resolving with primary search path '/foo/node_modules/@types, /node_modules/@types'", "File '/foo/node_modules/@types/sneezy/package.json' does not exist.", "File '/foo/node_modules/@types/sneezy/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/foo/node_modules/@types/sneezy/index.d.ts', result '/foo/node_modules/@types/sneezy/index.d.ts'", "======== Type reference directive 'sneezy' was successfully resolved to '/foo/node_modules/@types/sneezy/index.d.ts', primary: true. ========", - "======== Resolving type reference directive 'dopey', containing file '/src/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", + "======== Resolving type reference directive 'dopey', containing file '/foo/bar/__inferred type names__.ts', root directory '/foo/node_modules/@types,/node_modules/@types'. ========", "Resolving with primary search path '/foo/node_modules/@types, /node_modules/@types'", "File '/foo/node_modules/@types/dopey/package.json' does not exist.", "File '/foo/node_modules/@types/dopey/index.d.ts' does not exist.", "File '/node_modules/@types/dopey/package.json' does not exist.", "File '/node_modules/@types/dopey/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/dopey/index.d.ts', result '/node_modules/@types/dopey/index.d.ts'", "======== Type reference directive 'dopey' was successfully resolved to '/node_modules/@types/dopey/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeRootsFromNodeModulesInParentDirectory.trace.json b/tests/baselines/reference/typeRootsFromNodeModulesInParentDirectory.trace.json index 7782ffc4ebf..6c2090e2b45 100644 --- a/tests/baselines/reference/typeRootsFromNodeModulesInParentDirectory.trace.json +++ b/tests/baselines/reference/typeRootsFromNodeModulesInParentDirectory.trace.json @@ -9,12 +9,8 @@ "File '/src/node_modules/xyz/index.ts' does not exist.", "File '/src/node_modules/xyz/index.tsx' does not exist.", "File '/src/node_modules/xyz/index.d.ts' does not exist.", - "File '/src/node_modules/@types/xyz.ts' does not exist.", - "File '/src/node_modules/@types/xyz.tsx' does not exist.", "File '/src/node_modules/@types/xyz.d.ts' does not exist.", "File '/src/node_modules/@types/xyz/package.json' does not exist.", - "File '/src/node_modules/@types/xyz/index.ts' does not exist.", - "File '/src/node_modules/@types/xyz/index.tsx' does not exist.", "File '/src/node_modules/@types/xyz/index.d.ts' does not exist.", "File '/node_modules/xyz.ts' does not exist.", "File '/node_modules/xyz.tsx' does not exist.", @@ -23,17 +19,25 @@ "File '/node_modules/xyz/index.ts' does not exist.", "File '/node_modules/xyz/index.tsx' does not exist.", "File '/node_modules/xyz/index.d.ts' does not exist.", - "File '/node_modules/@types/xyz.ts' does not exist.", - "File '/node_modules/@types/xyz.tsx' does not exist.", "File '/node_modules/@types/xyz.d.ts' does not exist.", "File '/node_modules/@types/xyz/package.json' does not exist.", - "File '/node_modules/@types/xyz/index.ts' does not exist.", - "File '/node_modules/@types/xyz/index.tsx' does not exist.", "File '/node_modules/@types/xyz/index.d.ts' does not exist.", + "Loading module 'xyz' from 'node_modules' folder.", + "File '/src/node_modules/xyz.js' does not exist.", + "File '/src/node_modules/xyz.jsx' does not exist.", + "File '/src/node_modules/xyz/package.json' does not exist.", + "File '/src/node_modules/xyz/index.js' does not exist.", + "File '/src/node_modules/xyz/index.jsx' does not exist.", + "File '/node_modules/xyz.js' does not exist.", + "File '/node_modules/xyz.jsx' does not exist.", + "File '/node_modules/xyz/package.json' does not exist.", + "File '/node_modules/xyz/index.js' does not exist.", + "File '/node_modules/xyz/index.jsx' does not exist.", "======== Module name 'xyz' was not resolved. ========", "======== Resolving type reference directive 'foo', containing file '/src/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/foo/package.json' does not exist.", "File '/node_modules/@types/foo/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/foo/index.d.ts', result '/node_modules/@types/foo/index.d.ts'", "======== Type reference directive 'foo' was successfully resolved to '/node_modules/@types/foo/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typeofAnExportedType.js b/tests/baselines/reference/typeofAnExportedType.js index 91b19d9bebd..69602d3e4c3 100644 --- a/tests/baselines/reference/typeofAnExportedType.js +++ b/tests/baselines/reference/typeofAnExportedType.js @@ -74,10 +74,10 @@ var M; M.C = C; })(M = exports.M || (exports.M = {})); exports.Z = M; +var E; (function (E) { E[E["A"] = 0] = "A"; -})(exports.E || (exports.E = {})); -var E = exports.E; +})(E = exports.E || (exports.E = {})); function foo() { } exports.foo = foo; (function (foo) { diff --git a/tests/baselines/reference/typingsLookup1.trace.json b/tests/baselines/reference/typingsLookup1.trace.json index 83b0e91d6c7..9445b8564d9 100644 --- a/tests/baselines/reference/typingsLookup1.trace.json +++ b/tests/baselines/reference/typingsLookup1.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/jquery/package.json' does not exist.", "File '/node_modules/@types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/index.d.ts', result '/node_modules/@types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/jquery/package.json' does not exist.", "File '/node_modules/@types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/index.d.ts', result '/node_modules/@types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typingsLookup3.trace.json b/tests/baselines/reference/typingsLookup3.trace.json index 83b0e91d6c7..9445b8564d9 100644 --- a/tests/baselines/reference/typingsLookup3.trace.json +++ b/tests/baselines/reference/typingsLookup3.trace.json @@ -3,10 +3,12 @@ "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/jquery/package.json' does not exist.", "File '/node_modules/@types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/index.d.ts', result '/node_modules/@types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/index.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/jquery/package.json' does not exist.", "File '/node_modules/@types/jquery/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/index.d.ts', result '/node_modules/@types/jquery/index.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json index 4bca8456f58..2b7de6a4286 100644 --- a/tests/baselines/reference/typingsLookup4.trace.json +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -9,8 +9,6 @@ "File '/node_modules/jquery/index.ts' does not exist.", "File '/node_modules/jquery/index.tsx' does not exist.", "File '/node_modules/jquery/index.d.ts' does not exist.", - "File '/node_modules/@types/jquery.ts' does not exist.", - "File '/node_modules/@types/jquery.tsx' does not exist.", "File '/node_modules/@types/jquery.d.ts' does not exist.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", @@ -27,8 +25,6 @@ "File '/node_modules/kquery/index.ts' does not exist.", "File '/node_modules/kquery/index.tsx' does not exist.", "File '/node_modules/kquery/index.d.ts' does not exist.", - "File '/node_modules/@types/kquery.ts' does not exist.", - "File '/node_modules/@types/kquery.tsx' does not exist.", "File '/node_modules/@types/kquery.d.ts' does not exist.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", @@ -48,8 +44,6 @@ "File '/node_modules/lquery/index.ts' does not exist.", "File '/node_modules/lquery/index.tsx' does not exist.", "File '/node_modules/lquery/index.d.ts' does not exist.", - "File '/node_modules/@types/lquery.ts' does not exist.", - "File '/node_modules/@types/lquery.tsx' does not exist.", "File '/node_modules/@types/lquery.d.ts' does not exist.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", @@ -62,32 +56,24 @@ "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/jquery.d.ts', result '/node_modules/@types/jquery/jquery.d.ts'", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "File '/node_modules/@types/kquery/kquery' does not exist.", + "File '/node_modules/@types/kquery/kquery.ts' does not exist.", + "File '/node_modules/@types/kquery/kquery.tsx' does not exist.", "File '/node_modules/@types/kquery/kquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/kquery/kquery.d.ts', result '/node_modules/@types/kquery/kquery.d.ts'", "======== Type reference directive 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "File '/node_modules/@types/lquery/lquery' does not exist.", - "File '/node_modules/@types/lquery/lquery.d.ts' does not exist.", - "File '/node_modules/@types/lquery/index.d.ts' does not exist.", - "Looking up in 'node_modules' folder, initial location '/'", - "File '/node_modules/lquery.ts' does not exist.", - "File '/node_modules/lquery.d.ts' does not exist.", - "File '/node_modules/lquery/package.json' does not exist.", - "File '/node_modules/lquery/index.ts' does not exist.", - "File '/node_modules/lquery/index.d.ts' does not exist.", - "File '/node_modules/@types/lquery.ts' does not exist.", - "File '/node_modules/@types/lquery.d.ts' does not exist.", - "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", - "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", - "File '/node_modules/@types/lquery/lquery' does not exist.", "File '/node_modules/@types/lquery/lquery.ts' exist - use it as a name resolution result.", - "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: false. ========" + "Resolving real path for '/node_modules/@types/lquery/lquery.ts', result '/node_modules/@types/lquery/lquery.ts'", + "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typingsLookupAmd.trace.json b/tests/baselines/reference/typingsLookupAmd.trace.json index 5c83757454c..6ad05d9cbf9 100644 --- a/tests/baselines/reference/typingsLookupAmd.trace.json +++ b/tests/baselines/reference/typingsLookupAmd.trace.json @@ -2,58 +2,55 @@ "======== Resolving module 'b' from '/x/y/foo.ts'. ========", "Module resolution kind is not specified, using 'Classic'.", "File '/x/y/b.ts' does not exist.", + "File '/x/y/b.tsx' does not exist.", "File '/x/y/b.d.ts' does not exist.", "File '/x/b.ts' does not exist.", + "File '/x/b.tsx' does not exist.", "File '/x/b.d.ts' does not exist.", "File '/b.ts' does not exist.", + "File '/b.tsx' does not exist.", "File '/b.d.ts' does not exist.", - "File '/x/y/node_modules/@types/b.ts' does not exist.", "File '/x/y/node_modules/@types/b.d.ts' does not exist.", "File '/x/y/node_modules/@types/b/package.json' does not exist.", - "File '/x/y/node_modules/@types/b/index.ts' does not exist.", "File '/x/y/node_modules/@types/b/index.d.ts' does not exist.", - "File '/x/node_modules/@types/b.ts' does not exist.", "File '/x/node_modules/@types/b.d.ts' does not exist.", "File '/x/node_modules/@types/b/package.json' does not exist.", - "File '/x/node_modules/@types/b/index.ts' does not exist.", "File '/x/node_modules/@types/b/index.d.ts' exist - use it as a name resolution result.", "======== Module name 'b' was successfully resolved to '/x/node_modules/@types/b/index.d.ts'. ========", "======== Resolving module 'a' from '/x/node_modules/@types/b/index.d.ts'. ========", "Module resolution kind is not specified, using 'Classic'.", "File '/x/node_modules/@types/b/a.ts' does not exist.", + "File '/x/node_modules/@types/b/a.tsx' does not exist.", "File '/x/node_modules/@types/b/a.d.ts' does not exist.", "File '/x/node_modules/@types/a.ts' does not exist.", + "File '/x/node_modules/@types/a.tsx' does not exist.", "File '/x/node_modules/@types/a.d.ts' does not exist.", "File '/x/node_modules/a.ts' does not exist.", + "File '/x/node_modules/a.tsx' does not exist.", "File '/x/node_modules/a.d.ts' does not exist.", "File '/x/a.ts' does not exist.", + "File '/x/a.tsx' does not exist.", "File '/x/a.d.ts' does not exist.", "File '/a.ts' does not exist.", + "File '/a.tsx' does not exist.", "File '/a.d.ts' does not exist.", - "File '/x/node_modules/@types/b/node_modules/@types/a.ts' does not exist.", "File '/x/node_modules/@types/b/node_modules/@types/a.d.ts' does not exist.", "File '/x/node_modules/@types/b/node_modules/@types/a/package.json' does not exist.", - "File '/x/node_modules/@types/b/node_modules/@types/a/index.ts' does not exist.", "File '/x/node_modules/@types/b/node_modules/@types/a/index.d.ts' does not exist.", - "File '/x/node_modules/@types/node_modules/@types/a.ts' does not exist.", "File '/x/node_modules/@types/node_modules/@types/a.d.ts' does not exist.", "File '/x/node_modules/@types/node_modules/@types/a/package.json' does not exist.", - "File '/x/node_modules/@types/node_modules/@types/a/index.ts' does not exist.", "File '/x/node_modules/@types/node_modules/@types/a/index.d.ts' does not exist.", - "File '/x/node_modules/@types/a.ts' does not exist.", "File '/x/node_modules/@types/a.d.ts' does not exist.", "File '/x/node_modules/@types/a/package.json' does not exist.", - "File '/x/node_modules/@types/a/index.ts' does not exist.", "File '/x/node_modules/@types/a/index.d.ts' does not exist.", - "File '/node_modules/@types/a.ts' does not exist.", "File '/node_modules/@types/a.d.ts' does not exist.", "File '/node_modules/@types/a/package.json' does not exist.", - "File '/node_modules/@types/a/index.ts' does not exist.", "File '/node_modules/@types/a/index.d.ts' exist - use it as a name resolution result.", "======== Module name 'a' was successfully resolved to '/node_modules/@types/a/index.d.ts'. ========", "======== Resolving type reference directive 'a', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'", "File '/node_modules/@types/a/package.json' does not exist.", "File '/node_modules/@types/a/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/a/index.d.ts', result '/node_modules/@types/a/index.d.ts'", "======== Type reference directive 'a' was successfully resolved to '/node_modules/@types/a/index.d.ts', primary: true. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/umd5.errors.txt b/tests/baselines/reference/umd5.errors.txt index 9628ad738db..5595de8de29 100644 --- a/tests/baselines/reference/umd5.errors.txt +++ b/tests/baselines/reference/umd5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: Identifier 'Foo' must be imported from a module +tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/a.ts (1 errors) ==== @@ -9,7 +9,7 @@ tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: Identifier 'Foo // should error let z = Foo; ~~~ -!!! error TS2686: Identifier 'Foo' must be imported from a module +!!! error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/foo.d.ts (0 errors) ==== diff --git a/tests/baselines/reference/umd8.errors.txt b/tests/baselines/reference/umd8.errors.txt index 9396c8c5450..26c8adef561 100644 --- a/tests/baselines/reference/umd8.errors.txt +++ b/tests/baselines/reference/umd8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: Identifier 'Foo' must be imported from a module +tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/a.ts (1 errors) ==== @@ -10,7 +10,7 @@ tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: Identifier 'Fo let z: Foo.SubThing; // OK in ns position let x: any = Foo; // Not OK in value position ~~~ -!!! error TS2686: Identifier 'Foo' must be imported from a module +!!! error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/foo.d.ts (0 errors) ==== diff --git a/tests/baselines/reference/unaryOperatorsInStrictMode.errors.txt b/tests/baselines/reference/unaryOperatorsInStrictMode.errors.txt index 53263e7c2e1..35963c05879 100644 --- a/tests/baselines/reference/unaryOperatorsInStrictMode.errors.txt +++ b/tests/baselines/reference/unaryOperatorsInStrictMode.errors.txt @@ -1,15 +1,15 @@ tests/cases/compiler/unaryOperatorsInStrictMode.ts(3,3): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/compiler/unaryOperatorsInStrictMode.ts(3,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/unaryOperatorsInStrictMode.ts(3,3): error TS2539: Cannot assign to 'eval' because it is not a variable. tests/cases/compiler/unaryOperatorsInStrictMode.ts(4,3): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/compiler/unaryOperatorsInStrictMode.ts(4,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/unaryOperatorsInStrictMode.ts(4,3): error TS2539: Cannot assign to 'eval' because it is not a variable. tests/cases/compiler/unaryOperatorsInStrictMode.ts(5,3): error TS1100: Invalid use of 'arguments' in strict mode. tests/cases/compiler/unaryOperatorsInStrictMode.ts(5,3): error TS2304: Cannot find name 'arguments'. tests/cases/compiler/unaryOperatorsInStrictMode.ts(6,3): error TS1100: Invalid use of 'arguments' in strict mode. tests/cases/compiler/unaryOperatorsInStrictMode.ts(6,3): error TS2304: Cannot find name 'arguments'. tests/cases/compiler/unaryOperatorsInStrictMode.ts(7,1): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/compiler/unaryOperatorsInStrictMode.ts(7,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/unaryOperatorsInStrictMode.ts(7,1): error TS2539: Cannot assign to 'eval' because it is not a variable. tests/cases/compiler/unaryOperatorsInStrictMode.ts(8,1): error TS1100: Invalid use of 'eval' in strict mode. -tests/cases/compiler/unaryOperatorsInStrictMode.ts(8,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/unaryOperatorsInStrictMode.ts(8,1): error TS2539: Cannot assign to 'eval' because it is not a variable. tests/cases/compiler/unaryOperatorsInStrictMode.ts(9,1): error TS1100: Invalid use of 'arguments' in strict mode. tests/cases/compiler/unaryOperatorsInStrictMode.ts(9,1): error TS2304: Cannot find name 'arguments'. tests/cases/compiler/unaryOperatorsInStrictMode.ts(10,1): error TS1100: Invalid use of 'arguments' in strict mode. @@ -23,12 +23,12 @@ tests/cases/compiler/unaryOperatorsInStrictMode.ts(10,1): error TS2304: Cannot f ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. --eval; ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. ++arguments; ~~~~~~~~~ !!! error TS1100: Invalid use of 'arguments' in strict mode. @@ -43,12 +43,12 @@ tests/cases/compiler/unaryOperatorsInStrictMode.ts(10,1): error TS2304: Cannot f ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. eval--; ~~~~ !!! error TS1100: Invalid use of 'eval' in strict mode. ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2539: Cannot assign to 'eval' because it is not a variable. arguments++; ~~~~~~~~~ !!! error TS1100: Invalid use of 'arguments' in strict mode. diff --git a/tests/baselines/reference/undeclaredModuleError.js b/tests/baselines/reference/undeclaredModuleError.js index c9a43ab4ce6..88f5e3ab352 100644 --- a/tests/baselines/reference/undeclaredModuleError.js +++ b/tests/baselines/reference/undeclaredModuleError.js @@ -22,7 +22,7 @@ define(["require", "exports", "fs"], function (require, exports, fs) { function join() { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { - paths[_i - 0] = arguments[_i]; + paths[_i] = arguments[_i]; } } function instrumentFile(covFileDir, covFileName, originalFilePath) { diff --git a/tests/baselines/reference/unionTypeCallSignatures3.js b/tests/baselines/reference/unionTypeCallSignatures3.js index 2dae152e474..b3c24a0e60a 100644 --- a/tests/baselines/reference/unionTypeCallSignatures3.js +++ b/tests/baselines/reference/unionTypeCallSignatures3.js @@ -18,7 +18,7 @@ function f2(s) { } function f3() { var s = []; for (var _i = 0; _i < arguments.length; _i++) { - s[_i - 0] = arguments[_i]; + s[_i] = arguments[_i]; } } function f4(s, s2) { } diff --git a/tests/baselines/reference/unionTypeReadonly.errors.txt b/tests/baselines/reference/unionTypeReadonly.errors.txt index ec660fc3a81..8248431a932 100644 --- a/tests/baselines/reference/unionTypeReadonly.errors.txt +++ b/tests/baselines/reference/unionTypeReadonly.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/union/unionTypeReadonly.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/union/unionTypeReadonly.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/union/unionTypeReadonly.ts(21,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/union/unionTypeReadonly.ts(23,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(17,6): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(19,11): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(21,9): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(23,15): error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. tests/cases/conformance/types/union/unionTypeReadonly.ts(25,15): error TS2339: Property 'value' does not exist on type 'Base | DifferentName'. Property 'value' does not exist on type 'DifferentName'. @@ -24,20 +24,20 @@ tests/cases/conformance/types/union/unionTypeReadonly.ts(25,15): error TS2339: P } let base: Base; base.value = 12 // error, lhs can't be a readonly property - ~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let identical: Base | Identical; identical.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let mutable: Base | Mutable; mutable.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let differentType: Base | DifferentType; differentType.value = 12; // error, lhs can't be a readonly property - ~~~~~~~~~~~~~~~~~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~~~~~ +!!! error TS2540: Cannot assign to 'value' because it is a constant or a read-only property. let differentName: Base | DifferentName; differentName.value = 12; // error, property 'value' doesn't exist ~~~~~ diff --git a/tests/baselines/reference/unionTypeWithLeadingOperator.js b/tests/baselines/reference/unionTypeWithLeadingOperator.js new file mode 100644 index 00000000000..0fb366d538e --- /dev/null +++ b/tests/baselines/reference/unionTypeWithLeadingOperator.js @@ -0,0 +1,10 @@ +//// [unionTypeWithLeadingOperator.ts] +type A = | string; +type B = + | { type: "INCREMENT" } + | { type: "DECREMENT" }; + +type C = [| 0 | 1, | "foo" | "bar"]; + + +//// [unionTypeWithLeadingOperator.js] diff --git a/tests/baselines/reference/unionTypeWithLeadingOperator.symbols b/tests/baselines/reference/unionTypeWithLeadingOperator.symbols new file mode 100644 index 00000000000..8c15d299c48 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithLeadingOperator.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/unionTypeWithLeadingOperator.ts === +type A = | string; +>A : Symbol(A, Decl(unionTypeWithLeadingOperator.ts, 0, 0)) + +type B = +>B : Symbol(B, Decl(unionTypeWithLeadingOperator.ts, 0, 18)) + + | { type: "INCREMENT" } +>type : Symbol(type, Decl(unionTypeWithLeadingOperator.ts, 2, 5)) + + | { type: "DECREMENT" }; +>type : Symbol(type, Decl(unionTypeWithLeadingOperator.ts, 3, 5)) + +type C = [| 0 | 1, | "foo" | "bar"]; +>C : Symbol(C, Decl(unionTypeWithLeadingOperator.ts, 3, 26)) + diff --git a/tests/baselines/reference/unionTypeWithLeadingOperator.types b/tests/baselines/reference/unionTypeWithLeadingOperator.types new file mode 100644 index 00000000000..2ca15fb54a2 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithLeadingOperator.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/unionTypeWithLeadingOperator.ts === +type A = | string; +>A : string + +type B = +>B : B + + | { type: "INCREMENT" } +>type : "INCREMENT" + + | { type: "DECREMENT" }; +>type : "DECREMENT" + +type C = [| 0 | 1, | "foo" | "bar"]; +>C : [0 | 1, "foo" | "bar"] + diff --git a/tests/baselines/reference/untypedModuleImport.js b/tests/baselines/reference/untypedModuleImport.js new file mode 100644 index 00000000000..e3548856411 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport.js @@ -0,0 +1,37 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport.ts] //// + +//// [index.js] +// This tests that importing from a JS file globally works in an untyped way. +// (Assuming we don't have `--noImplicitAny` or `--allowJs`.) + +This file is not processed. + +//// [a.ts] +import * as foo from "foo"; +foo.bar(); + +//// [b.ts] +import foo = require("foo"); +foo(); + +//// [c.ts] +import foo, { bar } from "foo"; +import "./a"; +import "./b"; +foo(bar()); + + +//// [a.js] +"use strict"; +var foo = require("foo"); +foo.bar(); +//// [b.js] +"use strict"; +var foo = require("foo"); +foo(); +//// [c.js] +"use strict"; +var foo_1 = require("foo"); +require("./a"); +require("./b"); +foo_1["default"](foo_1.bar()); diff --git a/tests/baselines/reference/untypedModuleImport.symbols b/tests/baselines/reference/untypedModuleImport.symbols new file mode 100644 index 00000000000..2cc04ed6efa --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport.symbols @@ -0,0 +1,25 @@ +=== /c.ts === +import foo, { bar } from "foo"; +>foo : Symbol(foo, Decl(c.ts, 0, 6)) +>bar : Symbol(bar, Decl(c.ts, 0, 13)) + +import "./a"; +import "./b"; +foo(bar()); +>foo : Symbol(foo, Decl(c.ts, 0, 6)) +>bar : Symbol(bar, Decl(c.ts, 0, 13)) + +=== /a.ts === +import * as foo from "foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 6)) + +foo.bar(); +>foo : Symbol(foo, Decl(a.ts, 0, 6)) + +=== /b.ts === +import foo = require("foo"); +>foo : Symbol(foo, Decl(b.ts, 0, 0)) + +foo(); +>foo : Symbol(foo, Decl(b.ts, 0, 0)) + diff --git a/tests/baselines/reference/untypedModuleImport.types b/tests/baselines/reference/untypedModuleImport.types new file mode 100644 index 00000000000..8a0c7e97ede --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport.types @@ -0,0 +1,31 @@ +=== /c.ts === +import foo, { bar } from "foo"; +>foo : any +>bar : any + +import "./a"; +import "./b"; +foo(bar()); +>foo(bar()) : any +>foo : any +>bar() : any +>bar : any + +=== /a.ts === +import * as foo from "foo"; +>foo : any + +foo.bar(); +>foo.bar() : any +>foo.bar : any +>foo : any +>bar : any + +=== /b.ts === +import foo = require("foo"); +>foo : any + +foo(); +>foo() : any +>foo : any + diff --git a/tests/baselines/reference/untypedModuleImport_allowJs.js b/tests/baselines/reference/untypedModuleImport_allowJs.js new file mode 100644 index 00000000000..8ca5115a386 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_allowJs.js @@ -0,0 +1,16 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport_allowJs.ts] //// + +//// [index.js] +// Same as untypedModuleImport.ts but with --allowJs, so the package will actually be typed. + +exports.default = { bar() { return 0; } } + +//// [a.ts] +import foo from "foo"; +foo.bar(); + + +//// [a.js] +"use strict"; +var foo_1 = require("foo"); +foo_1["default"].bar(); diff --git a/tests/baselines/reference/untypedModuleImport_allowJs.symbols b/tests/baselines/reference/untypedModuleImport_allowJs.symbols new file mode 100644 index 00000000000..d660e811630 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_allowJs.symbols @@ -0,0 +1,17 @@ +=== /a.ts === +import foo from "foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 6)) + +foo.bar(); +>foo.bar : Symbol(bar, Decl(index.js, 2, 19)) +>foo : Symbol(foo, Decl(a.ts, 0, 6)) +>bar : Symbol(bar, Decl(index.js, 2, 19)) + +=== /node_modules/foo/index.js === +// Same as untypedModuleImport.ts but with --allowJs, so the package will actually be typed. + +exports.default = { bar() { return 0; } } +>exports : Symbol(default, Decl(index.js, 0, 0)) +>default : Symbol(default, Decl(index.js, 0, 0)) +>bar : Symbol(bar, Decl(index.js, 2, 19)) + diff --git a/tests/baselines/reference/untypedModuleImport_allowJs.types b/tests/baselines/reference/untypedModuleImport_allowJs.types new file mode 100644 index 00000000000..5a34fdcb646 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_allowJs.types @@ -0,0 +1,22 @@ +=== /a.ts === +import foo from "foo"; +>foo : { bar(): number; } + +foo.bar(); +>foo.bar() : number +>foo.bar : () => number +>foo : { bar(): number; } +>bar : () => number + +=== /node_modules/foo/index.js === +// Same as untypedModuleImport.ts but with --allowJs, so the package will actually be typed. + +exports.default = { bar() { return 0; } } +>exports.default = { bar() { return 0; } } : { bar(): number; } +>exports.default : any +>exports : any +>default : any +>{ bar() { return 0; } } : { bar(): number; } +>bar : () => number +>0 : 0 + diff --git a/tests/baselines/reference/untypedModuleImport_noImplicitAny.errors.txt b/tests/baselines/reference/untypedModuleImport_noImplicitAny.errors.txt new file mode 100644 index 00000000000..349a944deeb --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_noImplicitAny.errors.txt @@ -0,0 +1,13 @@ +/a.ts(1,22): error TS7016: Could not find a declaration file for module 'foo'. '/node_modules/foo/index.js' implicitly has an 'any' type. + + +==== /a.ts (1 errors) ==== + import * as foo from "foo"; + ~~~~~ +!!! error TS7016: Could not find a declaration file for module 'foo'. '/node_modules/foo/index.js' implicitly has an 'any' type. + +==== /node_modules/foo/index.js (0 errors) ==== + // This tests that `--noImplicitAny` disables untyped modules. + + This file is not processed. + \ No newline at end of file diff --git a/tests/baselines/reference/untypedModuleImport_noImplicitAny.js b/tests/baselines/reference/untypedModuleImport_noImplicitAny.js new file mode 100644 index 00000000000..ab1e1940e36 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_noImplicitAny.js @@ -0,0 +1,13 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport_noImplicitAny.ts] //// + +//// [index.js] +// This tests that `--noImplicitAny` disables untyped modules. + +This file is not processed. + +//// [a.ts] +import * as foo from "foo"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/untypedModuleImport_noLocalImports.errors.txt b/tests/baselines/reference/untypedModuleImport_noLocalImports.errors.txt new file mode 100644 index 00000000000..0f376ea61ec --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_noLocalImports.errors.txt @@ -0,0 +1,13 @@ +/a.ts(1,22): error TS6143: Module './foo' was resolved to '/foo.js', but '--allowJs' is not set. + + +==== /a.ts (1 errors) ==== + import * as foo from "./foo"; + ~~~~~~~ +!!! error TS6143: Module './foo' was resolved to '/foo.js', but '--allowJs' is not set. + +==== /foo.js (0 errors) ==== + // This tests that untyped module imports don't happen with local imports. + + This file is not processed. + \ No newline at end of file diff --git a/tests/baselines/reference/untypedModuleImport_noLocalImports.js b/tests/baselines/reference/untypedModuleImport_noLocalImports.js new file mode 100644 index 00000000000..8fa67a0857f --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_noLocalImports.js @@ -0,0 +1,13 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport_noLocalImports.ts] //// + +//// [foo.js] +// This tests that untyped module imports don't happen with local imports. + +This file is not processed. + +//// [a.ts] +import * as foo from "./foo"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/untypedModuleImport_vsAmbient.js b/tests/baselines/reference/untypedModuleImport_vsAmbient.js new file mode 100644 index 00000000000..080cd443375 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_vsAmbient.js @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport_vsAmbient.ts] //// + +//// [index.js] +// This tests that an ambient module declaration overrides an untyped import. + +This file is not processed. + +//// [declarations.d.ts] +declare module "foo" { + export const x: number; +} + +//// [a.ts] +/// +import { x } from "foo"; +x; + + +//// [a.js] +"use strict"; +/// +var foo_1 = require("foo"); +foo_1.x; diff --git a/tests/baselines/reference/untypedModuleImport_vsAmbient.symbols b/tests/baselines/reference/untypedModuleImport_vsAmbient.symbols new file mode 100644 index 00000000000..8def3c6a09b --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_vsAmbient.symbols @@ -0,0 +1,14 @@ +=== /a.ts === +/// +import { x } from "foo"; +>x : Symbol(x, Decl(a.ts, 1, 8)) + +x; +>x : Symbol(x, Decl(a.ts, 1, 8)) + +=== /declarations.d.ts === +declare module "foo" { + export const x: number; +>x : Symbol(x, Decl(declarations.d.ts, 1, 16)) +} + diff --git a/tests/baselines/reference/untypedModuleImport_vsAmbient.types b/tests/baselines/reference/untypedModuleImport_vsAmbient.types new file mode 100644 index 00000000000..58b0eabefdf --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_vsAmbient.types @@ -0,0 +1,14 @@ +=== /a.ts === +/// +import { x } from "foo"; +>x : number + +x; +>x : number + +=== /declarations.d.ts === +declare module "foo" { + export const x: number; +>x : number +} + diff --git a/tests/baselines/reference/untypedModuleImport_withAugmentation.errors.txt b/tests/baselines/reference/untypedModuleImport_withAugmentation.errors.txt new file mode 100644 index 00000000000..290cfbc6cbd --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_withAugmentation.errors.txt @@ -0,0 +1,17 @@ +/a.ts(1,16): error TS2665: Invalid module name in augmentation. Module 'foo' resolves to an untyped module at '/node_modules/foo/index.js', which cannot be augmented. + + +==== /a.ts (1 errors) ==== + declare module "foo" { + ~~~~~ +!!! error TS2665: Invalid module name in augmentation. Module 'foo' resolves to an untyped module at '/node_modules/foo/index.js', which cannot be augmented. + export const x: number; + } + import { x } from "foo"; + x; + +==== /node_modules/foo/index.js (0 errors) ==== + // This tests that augmenting an untyped module is forbidden. + + This file is not processed. + \ No newline at end of file diff --git a/tests/baselines/reference/untypedModuleImport_withAugmentation.js b/tests/baselines/reference/untypedModuleImport_withAugmentation.js new file mode 100644 index 00000000000..17eda95aa8a --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_withAugmentation.js @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/moduleResolution/untypedModuleImport_withAugmentation.ts] //// + +//// [index.js] +// This tests that augmenting an untyped module is forbidden. + +This file is not processed. + +//// [a.ts] +declare module "foo" { + export const x: number; +} +import { x } from "foo"; +x; + + +//// [a.js] +"use strict"; +var foo_1 = require("foo"); +foo_1.x; diff --git a/tests/baselines/reference/untypedModuleImport_withAugmentation2.errors.txt b/tests/baselines/reference/untypedModuleImport_withAugmentation2.errors.txt new file mode 100644 index 00000000000..628533b93d5 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_withAugmentation2.errors.txt @@ -0,0 +1,19 @@ +/node_modules/augmenter/index.d.ts(3,16): error TS2665: Invalid module name in augmentation. Module 'js' resolves to an untyped module at '/node_modules/js/index.js', which cannot be augmented. + + +==== /a.ts (0 errors) ==== + import { } from "augmenter"; + +==== /node_modules/augmenter/index.d.ts (1 errors) ==== + // This tests that augmenting an untyped module is forbidden even in an ambient context. Contrast with `moduleAugmentationInDependency.ts`. + + declare module "js" { + ~~~~ +!!! error TS2665: Invalid module name in augmentation. Module 'js' resolves to an untyped module at '/node_modules/js/index.js', which cannot be augmented. + export const j: number; + } + export {}; + +==== /node_modules/js/index.js (0 errors) ==== + This file is not processed. + \ No newline at end of file diff --git a/tests/baselines/reference/untypedModuleImport_withAugmentation2.js b/tests/baselines/reference/untypedModuleImport_withAugmentation2.js new file mode 100644 index 00000000000..f9fa7443224 --- /dev/null +++ b/tests/baselines/reference/untypedModuleImport_withAugmentation2.js @@ -0,0 +1,19 @@ +//// [tests/cases/compiler/untypedModuleImport_withAugmentation2.ts] //// + +//// [index.d.ts] +// This tests that augmenting an untyped module is forbidden even in an ambient context. Contrast with `moduleAugmentationInDependency.ts`. + +declare module "js" { + export const j: number; +} +export {}; + +//// [index.js] +This file is not processed. + +//// [a.ts] +import { } from "augmenter"; + + +//// [a.js] +"use strict"; diff --git a/tests/baselines/reference/unusedDestructuringParameters.errors.txt b/tests/baselines/reference/unusedDestructuringParameters.errors.txt new file mode 100644 index 00000000000..b6814df6b7a --- /dev/null +++ b/tests/baselines/reference/unusedDestructuringParameters.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedDestructuringParameters.ts(1,13): error TS6133: 'a' is declared but never used. +tests/cases/compiler/unusedDestructuringParameters.ts(3,14): error TS6133: 'a' is declared but never used. + + +==== tests/cases/compiler/unusedDestructuringParameters.ts (2 errors) ==== + const f = ([a]) => { }; + ~ +!!! error TS6133: 'a' is declared but never used. + f([1]); + const f2 = ({a}) => { }; + ~ +!!! error TS6133: 'a' is declared but never used. + f2({ a: 10 }); + const f3 = ([_]) => { }; + f3([10]); \ No newline at end of file diff --git a/tests/baselines/reference/unusedDestructuringParameters.js b/tests/baselines/reference/unusedDestructuringParameters.js new file mode 100644 index 00000000000..ca0ab80b86e --- /dev/null +++ b/tests/baselines/reference/unusedDestructuringParameters.js @@ -0,0 +1,21 @@ +//// [unusedDestructuringParameters.ts] +const f = ([a]) => { }; +f([1]); +const f2 = ({a}) => { }; +f2({ a: 10 }); +const f3 = ([_]) => { }; +f3([10]); + +//// [unusedDestructuringParameters.js] +var f = function (_a) { + var a = _a[0]; +}; +f([1]); +var f2 = function (_a) { + var a = _a.a; +}; +f2({ a: 10 }); +var f3 = function (_a) { + var _ = _a[0]; +}; +f3([10]); diff --git a/tests/baselines/reference/unusedImports13.js b/tests/baselines/reference/unusedImports13.js new file mode 100644 index 00000000000..01e91abc14b --- /dev/null +++ b/tests/baselines/reference/unusedImports13.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/unusedImports13.ts] //// + +//// [foo.tsx] + +import React = require("react"); + +export const FooComponent =
+ +//// [index.d.ts] +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + + + +//// [foo.jsx] +"use strict"; +var React = require("react"); +exports.FooComponent =
; diff --git a/tests/baselines/reference/unusedImports13.symbols b/tests/baselines/reference/unusedImports13.symbols new file mode 100644 index 00000000000..3ac44d17533 --- /dev/null +++ b/tests/baselines/reference/unusedImports13.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/foo.tsx === + +import React = require("react"); +>React : Symbol(React, Decl(foo.tsx, 0, 0)) + +export const FooComponent =
+>FooComponent : Symbol(FooComponent, Decl(foo.tsx, 3, 12)) +>div : Symbol(unknown) +>div : Symbol(unknown) + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + +export as namespace React; +>React : Symbol(React, Decl(index.d.ts, 0, 15)) + +declare namespace React { +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + + function createClass(spec); +>createClass : Symbol(createClass, Decl(index.d.ts, 3, 25)) +>P : Symbol(P, Decl(index.d.ts, 4, 25)) +>S : Symbol(S, Decl(index.d.ts, 4, 27)) +>spec : Symbol(spec, Decl(index.d.ts, 4, 31)) +} +declare global { +>global : Symbol(global, Decl(index.d.ts, 5, 1)) + + namespace JSX { +>JSX : Symbol(JSX, Decl(index.d.ts, 6, 16)) + } +} + + + diff --git a/tests/baselines/reference/unusedImports13.types b/tests/baselines/reference/unusedImports13.types new file mode 100644 index 00000000000..b19531b3e2d --- /dev/null +++ b/tests/baselines/reference/unusedImports13.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/foo.tsx === + +import React = require("react"); +>React : typeof React + +export const FooComponent =
+>FooComponent : any +>
: any +>div : any +>div : any + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : typeof React + +export as namespace React; +>React : typeof React + +declare namespace React { +>React : typeof React + + function createClass(spec); +>createClass : (spec: any) => any +>P : P +>S : S +>spec : any +} +declare global { +>global : any + + namespace JSX { +>JSX : any + } +} + + + diff --git a/tests/baselines/reference/unusedImports14.js b/tests/baselines/reference/unusedImports14.js new file mode 100644 index 00000000000..f3c51590e49 --- /dev/null +++ b/tests/baselines/reference/unusedImports14.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/unusedImports14.ts] //// + +//// [foo.tsx] + +import React = require("react"); + +export const FooComponent =
+ +//// [index.d.ts] +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + + + +//// [foo.js] +"use strict"; +var React = require("react"); +exports.FooComponent = React.createElement("div", null); diff --git a/tests/baselines/reference/unusedImports14.symbols b/tests/baselines/reference/unusedImports14.symbols new file mode 100644 index 00000000000..3ac44d17533 --- /dev/null +++ b/tests/baselines/reference/unusedImports14.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/foo.tsx === + +import React = require("react"); +>React : Symbol(React, Decl(foo.tsx, 0, 0)) + +export const FooComponent =
+>FooComponent : Symbol(FooComponent, Decl(foo.tsx, 3, 12)) +>div : Symbol(unknown) +>div : Symbol(unknown) + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + +export as namespace React; +>React : Symbol(React, Decl(index.d.ts, 0, 15)) + +declare namespace React { +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + + function createClass(spec); +>createClass : Symbol(createClass, Decl(index.d.ts, 3, 25)) +>P : Symbol(P, Decl(index.d.ts, 4, 25)) +>S : Symbol(S, Decl(index.d.ts, 4, 27)) +>spec : Symbol(spec, Decl(index.d.ts, 4, 31)) +} +declare global { +>global : Symbol(global, Decl(index.d.ts, 5, 1)) + + namespace JSX { +>JSX : Symbol(JSX, Decl(index.d.ts, 6, 16)) + } +} + + + diff --git a/tests/baselines/reference/unusedImports14.types b/tests/baselines/reference/unusedImports14.types new file mode 100644 index 00000000000..b19531b3e2d --- /dev/null +++ b/tests/baselines/reference/unusedImports14.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/foo.tsx === + +import React = require("react"); +>React : typeof React + +export const FooComponent =
+>FooComponent : any +>
: any +>div : any +>div : any + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : typeof React + +export as namespace React; +>React : typeof React + +declare namespace React { +>React : typeof React + + function createClass(spec); +>createClass : (spec: any) => any +>P : P +>S : S +>spec : any +} +declare global { +>global : any + + namespace JSX { +>JSX : any + } +} + + + diff --git a/tests/baselines/reference/unusedImports15.js b/tests/baselines/reference/unusedImports15.js new file mode 100644 index 00000000000..01be756e0e5 --- /dev/null +++ b/tests/baselines/reference/unusedImports15.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/unusedImports15.ts] //// + +//// [foo.tsx] + +import Element = require("react"); + +export const FooComponent =
+ +//// [index.d.ts] +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + + + +//// [foo.jsx] +"use strict"; +var Element = require("react"); +exports.FooComponent =
; diff --git a/tests/baselines/reference/unusedImports15.symbols b/tests/baselines/reference/unusedImports15.symbols new file mode 100644 index 00000000000..a325dc7ed76 --- /dev/null +++ b/tests/baselines/reference/unusedImports15.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/foo.tsx === + +import Element = require("react"); +>Element : Symbol(Element, Decl(foo.tsx, 0, 0)) + +export const FooComponent =
+>FooComponent : Symbol(FooComponent, Decl(foo.tsx, 3, 12)) +>div : Symbol(unknown) +>div : Symbol(unknown) + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + +export as namespace React; +>React : Symbol(React, Decl(index.d.ts, 0, 15)) + +declare namespace React { +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + + function createClass(spec); +>createClass : Symbol(createClass, Decl(index.d.ts, 3, 25)) +>P : Symbol(P, Decl(index.d.ts, 4, 25)) +>S : Symbol(S, Decl(index.d.ts, 4, 27)) +>spec : Symbol(spec, Decl(index.d.ts, 4, 31)) +} +declare global { +>global : Symbol(global, Decl(index.d.ts, 5, 1)) + + namespace JSX { +>JSX : Symbol(JSX, Decl(index.d.ts, 6, 16)) + } +} + + + diff --git a/tests/baselines/reference/unusedImports15.types b/tests/baselines/reference/unusedImports15.types new file mode 100644 index 00000000000..c222eaa03a3 --- /dev/null +++ b/tests/baselines/reference/unusedImports15.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/foo.tsx === + +import Element = require("react"); +>Element : typeof Element + +export const FooComponent =
+>FooComponent : any +>
: any +>div : any +>div : any + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : typeof React + +export as namespace React; +>React : typeof React + +declare namespace React { +>React : typeof React + + function createClass(spec); +>createClass : (spec: any) => any +>P : P +>S : S +>spec : any +} +declare global { +>global : any + + namespace JSX { +>JSX : any + } +} + + + diff --git a/tests/baselines/reference/unusedImports16.js b/tests/baselines/reference/unusedImports16.js new file mode 100644 index 00000000000..1ce802d869a --- /dev/null +++ b/tests/baselines/reference/unusedImports16.js @@ -0,0 +1,27 @@ +//// [tests/cases/compiler/unusedImports16.ts] //// + +//// [foo.tsx] + +import Element = require("react"); + +export const FooComponent =
+ +//// [index.d.ts] +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + + + +//// [foo.js] +"use strict"; +var Element = require("react"); +exports.FooComponent = Element.createElement("div", null); diff --git a/tests/baselines/reference/unusedImports16.symbols b/tests/baselines/reference/unusedImports16.symbols new file mode 100644 index 00000000000..a325dc7ed76 --- /dev/null +++ b/tests/baselines/reference/unusedImports16.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/foo.tsx === + +import Element = require("react"); +>Element : Symbol(Element, Decl(foo.tsx, 0, 0)) + +export const FooComponent =
+>FooComponent : Symbol(FooComponent, Decl(foo.tsx, 3, 12)) +>div : Symbol(unknown) +>div : Symbol(unknown) + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + +export as namespace React; +>React : Symbol(React, Decl(index.d.ts, 0, 15)) + +declare namespace React { +>React : Symbol(React, Decl(index.d.ts, 1, 26)) + + function createClass(spec); +>createClass : Symbol(createClass, Decl(index.d.ts, 3, 25)) +>P : Symbol(P, Decl(index.d.ts, 4, 25)) +>S : Symbol(S, Decl(index.d.ts, 4, 27)) +>spec : Symbol(spec, Decl(index.d.ts, 4, 31)) +} +declare global { +>global : Symbol(global, Decl(index.d.ts, 5, 1)) + + namespace JSX { +>JSX : Symbol(JSX, Decl(index.d.ts, 6, 16)) + } +} + + + diff --git a/tests/baselines/reference/unusedImports16.types b/tests/baselines/reference/unusedImports16.types new file mode 100644 index 00000000000..c222eaa03a3 --- /dev/null +++ b/tests/baselines/reference/unusedImports16.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/foo.tsx === + +import Element = require("react"); +>Element : typeof Element + +export const FooComponent =
+>FooComponent : any +>
: any +>div : any +>div : any + +=== tests/cases/compiler/node_modules/@types/react/index.d.ts === +export = React; +>React : typeof React + +export as namespace React; +>React : typeof React + +declare namespace React { +>React : typeof React + + function createClass(spec); +>createClass : (spec: any) => any +>P : P +>S : S +>spec : any +} +declare global { +>global : any + + namespace JSX { +>JSX : any + } +} + + + diff --git a/tests/baselines/reference/unusedLocalProperty.js b/tests/baselines/reference/unusedLocalProperty.js new file mode 100644 index 00000000000..a124b752125 --- /dev/null +++ b/tests/baselines/reference/unusedLocalProperty.js @@ -0,0 +1,25 @@ +//// [unusedLocalProperty.ts] +declare var console: { log(msg: any): void; } +class Animal { + constructor(private species: string) { + } + + printSpecies() { + let { species } = this; + console.log(species); + } +} + + + +//// [unusedLocalProperty.js] +var Animal = (function () { + function Animal(species) { + this.species = species; + } + Animal.prototype.printSpecies = function () { + var species = this.species; + console.log(species); + }; + return Animal; +}()); diff --git a/tests/baselines/reference/unusedLocalProperty.symbols b/tests/baselines/reference/unusedLocalProperty.symbols new file mode 100644 index 00000000000..6a3343bd545 --- /dev/null +++ b/tests/baselines/reference/unusedLocalProperty.symbols @@ -0,0 +1,29 @@ +=== tests/cases/compiler/unusedLocalProperty.ts === +declare var console: { log(msg: any): void; } +>console : Symbol(console, Decl(unusedLocalProperty.ts, 0, 11)) +>log : Symbol(log, Decl(unusedLocalProperty.ts, 0, 22)) +>msg : Symbol(msg, Decl(unusedLocalProperty.ts, 0, 27)) + +class Animal { +>Animal : Symbol(Animal, Decl(unusedLocalProperty.ts, 0, 45)) + + constructor(private species: string) { +>species : Symbol(Animal.species, Decl(unusedLocalProperty.ts, 2, 16)) + } + + printSpecies() { +>printSpecies : Symbol(Animal.printSpecies, Decl(unusedLocalProperty.ts, 3, 5)) + + let { species } = this; +>species : Symbol(species, Decl(unusedLocalProperty.ts, 6, 13)) +>this : Symbol(Animal, Decl(unusedLocalProperty.ts, 0, 45)) + + console.log(species); +>console.log : Symbol(log, Decl(unusedLocalProperty.ts, 0, 22)) +>console : Symbol(console, Decl(unusedLocalProperty.ts, 0, 11)) +>log : Symbol(log, Decl(unusedLocalProperty.ts, 0, 22)) +>species : Symbol(species, Decl(unusedLocalProperty.ts, 6, 13)) + } +} + + diff --git a/tests/baselines/reference/unusedLocalProperty.types b/tests/baselines/reference/unusedLocalProperty.types new file mode 100644 index 00000000000..3cb8747957d --- /dev/null +++ b/tests/baselines/reference/unusedLocalProperty.types @@ -0,0 +1,30 @@ +=== tests/cases/compiler/unusedLocalProperty.ts === +declare var console: { log(msg: any): void; } +>console : { log(msg: any): void; } +>log : (msg: any) => void +>msg : any + +class Animal { +>Animal : Animal + + constructor(private species: string) { +>species : string + } + + printSpecies() { +>printSpecies : () => void + + let { species } = this; +>species : string +>this : this + + console.log(species); +>console.log(species) : void +>console.log : (msg: any) => void +>console : { log(msg: any): void; } +>log : (msg: any) => void +>species : string + } +} + + diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread.errors.txt b/tests/baselines/reference/unusedLocalsAndObjectSpread.errors.txt new file mode 100644 index 00000000000..56f2ba927fb --- /dev/null +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread.errors.txt @@ -0,0 +1,40 @@ +tests/cases/compiler/unusedLocalsAndObjectSpread.ts(21,18): error TS6133: 'bar' is declared but never used. +tests/cases/compiler/unusedLocalsAndObjectSpread.ts(28,21): error TS6133: 'bar' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsAndObjectSpread.ts (2 errors) ==== + + declare var console: { log(a: any): void }; + + function one() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; + console.log(bar); + } + + function two() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; + console.log(bar); + } + + function three() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; // bar should be unused + ~~~ +!!! error TS6133: 'bar' is declared but never used. + //console.log(bar); + } + + function four() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; // bar should be unused + ~~~ +!!! error TS6133: 'bar' is declared but never used. + //console.log(bar); + } + \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread.js b/tests/baselines/reference/unusedLocalsAndObjectSpread.js new file mode 100644 index 00000000000..2878f1b5c5c --- /dev/null +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread.js @@ -0,0 +1,67 @@ +//// [unusedLocalsAndObjectSpread.ts] + +declare var console: { log(a: any): void }; + +function one() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; + console.log(bar); +} + +function two() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; + console.log(bar); +} + +function three() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; // bar should be unused + //console.log(bar); +} + +function four() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; // bar should be unused + //console.log(bar); +} + + +//// [unusedLocalsAndObjectSpread.js] +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +function one() { + var foo = { a: 1, b: 2 }; + // 'a' is declared but never used + var a = foo.a, bar = __rest(foo, ["a"]); + console.log(bar); +} +function two() { + var foo = { a: 1, b: 2 }; + // '_' is declared but never used + var _ = foo.a, bar = __rest(foo, ["a"]); + console.log(bar); +} +function three() { + var foo = { a: 1, b: 2 }; + // 'a' is declared but never used + var a = foo.a, bar = __rest(foo, ["a"]); // bar should be unused + //console.log(bar); +} +function four() { + var foo = { a: 1, b: 2 }; + // '_' is declared but never used + var _ = foo.a, bar = __rest(foo, ["a"]); // bar should be unused + //console.log(bar); +} diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt b/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt new file mode 100644 index 00000000000..2d1c36d3cbf --- /dev/null +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.errors.txt @@ -0,0 +1,29 @@ +tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(6,6): error TS6133: 'rest' is declared but never used. +tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(9,10): error TS6133: 'foo' is declared but never used. +tests/cases/compiler/unusedLocalsAndObjectSpread2.ts(13,8): error TS6133: 'rest' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsAndObjectSpread2.ts (3 errors) ==== + + declare let props: any; + const { + children, // here! + active: _a, // here! + ...rest, + ~~~~ +!!! error TS6133: 'rest' is declared but never used. + } = props; + + function foo() { + ~~~ +!!! error TS6133: 'foo' is declared but never used. + const { + children, + active: _a, + ...rest, + ~~~~ +!!! error TS6133: 'rest' is declared but never used. + } = props; + } + + export const asdf = 123; \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread2.js b/tests/baselines/reference/unusedLocalsAndObjectSpread2.js new file mode 100644 index 00000000000..e6cd890abb7 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread2.js @@ -0,0 +1,37 @@ +//// [unusedLocalsAndObjectSpread2.ts] + +declare let props: any; +const { + children, // here! + active: _a, // here! + ...rest, +} = props; + +function foo() { + const { + children, + active: _a, + ...rest, + } = props; +} + +export const asdf = 123; + +//// [unusedLocalsAndObjectSpread2.js] +"use strict"; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +var children = props.children, // here! +_a = props.active, // here! +rest = __rest(props, ["children", "active"]); +function foo() { + var children = props.children, _a = props.active, rest = __rest(props, ["children", "active"]); +} +exports.asdf = 123; diff --git a/tests/baselines/reference/unusedLocalsStartingWithUnderscore.errors.txt b/tests/baselines/reference/unusedLocalsStartingWithUnderscore.errors.txt new file mode 100644 index 00000000000..ae72b6fcdd3 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsStartingWithUnderscore.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/unusedLocalsStartingWithUnderscore.ts(7,9): error TS6133: '_' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsStartingWithUnderscore.ts (1 errors) ==== + + for (const _ of []) { } + + for (const _ in []) { } + + namespace M { + let _; + ~ +!!! error TS6133: '_' is declared but never used. + for (const _ of []) { } + + for (const _ in []) { } + } + \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsStartingWithUnderscore.js b/tests/baselines/reference/unusedLocalsStartingWithUnderscore.js new file mode 100644 index 00000000000..cca16a97824 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsStartingWithUnderscore.js @@ -0,0 +1,27 @@ +//// [unusedLocalsStartingWithUnderscore.ts] + +for (const _ of []) { } + +for (const _ in []) { } + +namespace M { + let _; + for (const _ of []) { } + + for (const _ in []) { } +} + + +//// [unusedLocalsStartingWithUnderscore.js] +for (var _i = 0, _a = []; _i < _a.length; _i++) { + var _ = _a[_i]; +} +for (var _ in []) { } +var M; +(function (M) { + var _; + for (var _i = 0, _a = []; _i < _a.length; _i++) { + var _1 = _a[_i]; + } + for (var _2 in []) { } +})(M || (M = {})); diff --git a/tests/baselines/reference/unusedParametersWithUnderscore.errors.txt b/tests/baselines/reference/unusedParametersWithUnderscore.errors.txt index adfe7bb9bc1..5e9ffa993b0 100644 --- a/tests/baselines/reference/unusedParametersWithUnderscore.errors.txt +++ b/tests/baselines/reference/unusedParametersWithUnderscore.errors.txt @@ -2,15 +2,11 @@ tests/cases/compiler/unusedParametersWithUnderscore.ts(2,12): error TS6133: 'a' tests/cases/compiler/unusedParametersWithUnderscore.ts(2,19): error TS6133: 'c' is declared but never used. tests/cases/compiler/unusedParametersWithUnderscore.ts(2,27): error TS6133: 'd' is declared but never used. tests/cases/compiler/unusedParametersWithUnderscore.ts(2,29): error TS6133: 'e___' is declared but never used. -tests/cases/compiler/unusedParametersWithUnderscore.ts(6,14): error TS6133: '_a' is declared but never used. -tests/cases/compiler/unusedParametersWithUnderscore.ts(6,18): error TS6133: '___b' is declared but never used. -tests/cases/compiler/unusedParametersWithUnderscore.ts(9,14): error TS6133: '_a' is declared but never used. -tests/cases/compiler/unusedParametersWithUnderscore.ts(9,19): error TS6133: '___b' is declared but never used. tests/cases/compiler/unusedParametersWithUnderscore.ts(12,16): error TS6133: 'arg' is declared but never used. tests/cases/compiler/unusedParametersWithUnderscore.ts(18,13): error TS6133: 'arg' is declared but never used. -==== tests/cases/compiler/unusedParametersWithUnderscore.ts (10 errors) ==== +==== tests/cases/compiler/unusedParametersWithUnderscore.ts (6 errors) ==== function f(a, _b, c, ___, d,e___, _f) { ~ @@ -25,17 +21,9 @@ tests/cases/compiler/unusedParametersWithUnderscore.ts(18,13): error TS6133: 'ar function f2({_a, __b}) { - ~~ -!!! error TS6133: '_a' is declared but never used. - ~~~ -!!! error TS6133: '___b' is declared but never used. } function f3([_a, ,__b]) { - ~~ -!!! error TS6133: '_a' is declared but never used. - ~~~ -!!! error TS6133: '___b' is declared but never used. } function f4(...arg) { diff --git a/tests/baselines/reference/unusedParametersWithUnderscore.js b/tests/baselines/reference/unusedParametersWithUnderscore.js index 2899d347c66..02d5da33395 100644 --- a/tests/baselines/reference/unusedParametersWithUnderscore.js +++ b/tests/baselines/reference/unusedParametersWithUnderscore.js @@ -35,13 +35,13 @@ function f3(_c) { function f4() { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { - arg[_i - 0] = arguments[_i]; + arg[_i] = arguments[_i]; } } function f5() { var _arg = []; for (var _i = 0; _i < arguments.length; _i++) { - _arg[_i - 0] = arguments[_i]; + _arg[_i] = arguments[_i]; } } function f6(arg, _arg) { diff --git a/tests/baselines/reference/unusedSwitchStatment.errors.txt b/tests/baselines/reference/unusedSwitchStatment.errors.txt index 591e9deca7a..a22c252f60d 100644 --- a/tests/baselines/reference/unusedSwitchStatment.errors.txt +++ b/tests/baselines/reference/unusedSwitchStatment.errors.txt @@ -4,10 +4,9 @@ tests/cases/compiler/unusedSwitchStatment.ts(7,15): error TS6133: 'c' is declare tests/cases/compiler/unusedSwitchStatment.ts(10,13): error TS6133: 'z' is declared but never used. tests/cases/compiler/unusedSwitchStatment.ts(15,10): error TS2678: Type '0' is not comparable to type '2'. tests/cases/compiler/unusedSwitchStatment.ts(17,10): error TS2678: Type '1' is not comparable to type '2'. -tests/cases/compiler/unusedSwitchStatment.ts(18,9): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -==== tests/cases/compiler/unusedSwitchStatment.ts (7 errors) ==== +==== tests/cases/compiler/unusedSwitchStatment.ts (6 errors) ==== switch (1) { case 0: @@ -38,6 +37,4 @@ tests/cases/compiler/unusedSwitchStatment.ts(18,9): error TS2356: An arithmetic ~ !!! error TS2678: Type '1' is not comparable to type '2'. x++; - ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. } \ No newline at end of file diff --git a/tests/baselines/reference/useBeforeDeclaration.js b/tests/baselines/reference/useBeforeDeclaration.js new file mode 100644 index 00000000000..6eab8683aec --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration.js @@ -0,0 +1,38 @@ +//// [tests/cases/compiler/useBeforeDeclaration.ts] //// + +//// [A.ts] + +namespace ts { + export function printVersion():void { + log("Version: " + sys.version); // the call of sys.version is deferred, should not report an error. + } + + export function log(info:string):void { + + } +} + +//// [B.ts] +namespace ts { + + export let sys:{version:string} = {version: "2.0.5"}; + +} + + + +//// [test.js] +var ts; +(function (ts) { + function printVersion() { + log("Version: " + ts.sys.version); // the call of sys.version is deferred, should not report an error. + } + ts.printVersion = printVersion; + function log(info) { + } + ts.log = log; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.sys = { version: "2.0.5" }; +})(ts || (ts = {})); diff --git a/tests/baselines/reference/useBeforeDeclaration.symbols b/tests/baselines/reference/useBeforeDeclaration.symbols new file mode 100644 index 00000000000..484255c0c7d --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration.symbols @@ -0,0 +1,34 @@ +=== tests/cases/compiler/A.ts === + +namespace ts { +>ts : Symbol(ts, Decl(A.ts, 0, 0), Decl(B.ts, 0, 0)) + + export function printVersion():void { +>printVersion : Symbol(printVersion, Decl(A.ts, 1, 14)) + + log("Version: " + sys.version); // the call of sys.version is deferred, should not report an error. +>log : Symbol(log, Decl(A.ts, 4, 5)) +>sys.version : Symbol(version, Decl(B.ts, 2, 20)) +>sys : Symbol(sys, Decl(B.ts, 2, 14)) +>version : Symbol(version, Decl(B.ts, 2, 20)) + } + + export function log(info:string):void { +>log : Symbol(log, Decl(A.ts, 4, 5)) +>info : Symbol(info, Decl(A.ts, 6, 24)) + + } +} + +=== tests/cases/compiler/B.ts === +namespace ts { +>ts : Symbol(ts, Decl(A.ts, 0, 0), Decl(B.ts, 0, 0)) + + export let sys:{version:string} = {version: "2.0.5"}; +>sys : Symbol(sys, Decl(B.ts, 2, 14)) +>version : Symbol(version, Decl(B.ts, 2, 20)) +>version : Symbol(version, Decl(B.ts, 2, 39)) + +} + + diff --git a/tests/baselines/reference/useBeforeDeclaration.types b/tests/baselines/reference/useBeforeDeclaration.types new file mode 100644 index 00000000000..141826723cf --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration.types @@ -0,0 +1,39 @@ +=== tests/cases/compiler/A.ts === + +namespace ts { +>ts : typeof ts + + export function printVersion():void { +>printVersion : () => void + + log("Version: " + sys.version); // the call of sys.version is deferred, should not report an error. +>log("Version: " + sys.version) : void +>log : (info: string) => void +>"Version: " + sys.version : string +>"Version: " : "Version: " +>sys.version : string +>sys : { version: string; } +>version : string + } + + export function log(info:string):void { +>log : (info: string) => void +>info : string + + } +} + +=== tests/cases/compiler/B.ts === +namespace ts { +>ts : typeof ts + + export let sys:{version:string} = {version: "2.0.5"}; +>sys : { version: string; } +>version : string +>{version: "2.0.5"} : { version: string; } +>version : string +>"2.0.5" : "2.0.5" + +} + + diff --git a/tests/baselines/reference/useObjectValuesAndEntries1.js b/tests/baselines/reference/useObjectValuesAndEntries1.js index ee2c7115813..728e14e7463 100644 --- a/tests/baselines/reference/useObjectValuesAndEntries1.js +++ b/tests/baselines/reference/useObjectValuesAndEntries1.js @@ -6,8 +6,11 @@ for (var x of Object.values(o)) { let y = x; } -var entries = Object.entries(o); -var entries1 = Object.entries(1); // <-- entries: [string, any][] +var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] +var entries1 = Object.entries(1); // <-- entries: [string, any][] +var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', number | boolean][] +var entries3 = Object.entries({}) // [never, any][] + //// [useObjectValuesAndEntries1.js] var o = { a: 1, b: 2 }; @@ -15,5 +18,7 @@ for (var _i = 0, _a = Object.values(o); _i < _a.length; _i++) { var x = _a[_i]; var y = x; } -var entries = Object.entries(o); +var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] var entries1 = Object.entries(1); // <-- entries: [string, any][] +var entries2 = Object.entries({ a: true, b: 2 }); // ['a' | 'b', number | boolean][] +var entries3 = Object.entries({}); // [never, any][] diff --git a/tests/baselines/reference/useObjectValuesAndEntries1.symbols b/tests/baselines/reference/useObjectValuesAndEntries1.symbols index 55181e49bab..521d3ae722e 100644 --- a/tests/baselines/reference/useObjectValuesAndEntries1.symbols +++ b/tests/baselines/reference/useObjectValuesAndEntries1.symbols @@ -17,7 +17,7 @@ for (var x of Object.values(o)) { >x : Symbol(x, Decl(useObjectValuesAndEntries1.ts, 3, 8)) } -var entries = Object.entries(o); +var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] >entries : Symbol(entries, Decl(useObjectValuesAndEntries1.ts, 7, 3)) >Object.entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) @@ -30,3 +30,17 @@ var entries1 = Object.entries(1); // <-- entries: [string, any][] >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) +var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', number | boolean][] +>entries2 : Symbol(entries2, Decl(useObjectValuesAndEntries1.ts, 9, 3)) +>Object.entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) +>a : Symbol(a, Decl(useObjectValuesAndEntries1.ts, 9, 31)) +>b : Symbol(b, Decl(useObjectValuesAndEntries1.ts, 9, 39)) + +var entries3 = Object.entries({}) // [never, any][] +>entries3 : Symbol(entries3, Decl(useObjectValuesAndEntries1.ts, 10, 3)) +>Object.entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>entries : Symbol(ObjectConstructor.entries, Decl(lib.es2017.object.d.ts, --, --), Decl(lib.es2017.object.d.ts, --, --)) + diff --git a/tests/baselines/reference/useObjectValuesAndEntries1.types b/tests/baselines/reference/useObjectValuesAndEntries1.types index dba92e85583..d9ccc019f75 100644 --- a/tests/baselines/reference/useObjectValuesAndEntries1.types +++ b/tests/baselines/reference/useObjectValuesAndEntries1.types @@ -21,7 +21,7 @@ for (var x of Object.values(o)) { >x : number } -var entries = Object.entries(o); +var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] >entries : [string, number][] >Object.entries(o) : [string, number][] >Object.entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } @@ -37,3 +37,23 @@ var entries1 = Object.entries(1); // <-- entries: [string, any][] >entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } >1 : 1 +var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', number | boolean][] +>entries2 : [string, number | boolean][] +>Object.entries({a: true, b: 2}) : [string, number | boolean][] +>Object.entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } +>Object : ObjectConstructor +>entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } +>{a: true, b: 2} : { a: true; b: 2; } +>a : boolean +>true : true +>b : number +>2 : 2 + +var entries3 = Object.entries({}) // [never, any][] +>entries3 : [string, {}][] +>Object.entries({}) : [string, {}][] +>Object.entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } +>Object : ObjectConstructor +>entries : { (o: { [s: string]: T; }): [string, T][]; (o: any): [string, any][]; } +>{} : {} + diff --git a/tests/baselines/reference/validNullAssignments.errors.txt b/tests/baselines/reference/validNullAssignments.errors.txt index 1fcebdcbaa9..ae3b0695c9d 100644 --- a/tests/baselines/reference/validNullAssignments.errors.txt +++ b/tests/baselines/reference/validNullAssignments.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/primitives/null/validNullAssignments.ts(10,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. -tests/cases/conformance/types/primitives/null/validNullAssignments.ts(15,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/null/validNullAssignments.ts(10,3): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/types/primitives/null/validNullAssignments.ts(15,1): error TS2539: Cannot assign to 'C' because it is not a variable. tests/cases/conformance/types/primitives/null/validNullAssignments.ts(20,1): error TS2693: 'I' only refers to a type, but is being used as a value here. -tests/cases/conformance/types/primitives/null/validNullAssignments.ts(23,1): error TS2364: Invalid left-hand side of assignment expression. -tests/cases/conformance/types/primitives/null/validNullAssignments.ts(30,1): error TS2364: Invalid left-hand side of assignment expression. +tests/cases/conformance/types/primitives/null/validNullAssignments.ts(23,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/types/primitives/null/validNullAssignments.ts(30,1): error TS2539: Cannot assign to 'i' because it is not a variable. ==== tests/cases/conformance/types/primitives/null/validNullAssignments.ts (5 errors) ==== @@ -16,15 +16,15 @@ tests/cases/conformance/types/primitives/null/validNullAssignments.ts(30,1): err enum E { A } E.A = null; // error - ~~~ -!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + ~ +!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. class C { foo: string } var f: C; f = null; // ok C = null; // error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'C' because it is not a variable. interface I { foo: string } var g: I; @@ -36,7 +36,7 @@ tests/cases/conformance/types/primitives/null/validNullAssignments.ts(30,1): err module M { export var x = 1; } M = null; // error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. +!!! error TS2539: Cannot assign to 'M' because it is not a variable. var h: { f(): void } = null; @@ -45,4 +45,4 @@ tests/cases/conformance/types/primitives/null/validNullAssignments.ts(30,1): err } i = null; // error ~ -!!! error TS2364: Invalid left-hand side of assignment expression. \ No newline at end of file +!!! error TS2539: Cannot assign to 'i' because it is not a variable. \ No newline at end of file diff --git a/tests/baselines/reference/validUseOfThisInSuper.js b/tests/baselines/reference/validUseOfThisInSuper.js index 483e905b48a..bbd564db366 100644 --- a/tests/baselines/reference/validUseOfThisInSuper.js +++ b/tests/baselines/reference/validUseOfThisInSuper.js @@ -24,7 +24,8 @@ var Base = (function () { var Super = (function (_super) { __extends(Super, _super); function Super() { - return _super.call(this, (function () { return _this; })()) || this; + var _this = _super.call(this, (function () { return _this; })()) || this; + return _this; } return Super; }(Base)); diff --git a/tests/baselines/reference/varArgConstructorMemberParameter.js b/tests/baselines/reference/varArgConstructorMemberParameter.js index 2715ed9e542..0d80c2b4dbb 100644 --- a/tests/baselines/reference/varArgConstructorMemberParameter.js +++ b/tests/baselines/reference/varArgConstructorMemberParameter.js @@ -17,7 +17,7 @@ var Foo1 = (function () { function Foo1() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } } return Foo1; @@ -32,7 +32,7 @@ var Foo3 = (function () { function Foo3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + args[_i] = arguments[_i]; } this.args = args; } diff --git a/tests/baselines/reference/varArgParamTypeCheck.js b/tests/baselines/reference/varArgParamTypeCheck.js index c2a33416436..2807ca97058 100644 --- a/tests/baselines/reference/varArgParamTypeCheck.js +++ b/tests/baselines/reference/varArgParamTypeCheck.js @@ -25,7 +25,7 @@ sequence( function sequence() { var sequences = []; for (var _i = 0; _i < arguments.length; _i++) { - sequences[_i - 0] = arguments[_i]; + sequences[_i] = arguments[_i]; } } function callback(clb) { diff --git a/tests/baselines/reference/varArgWithNoParamName.js b/tests/baselines/reference/varArgWithNoParamName.js index 05a9695770a..3aa9fcbabb0 100644 --- a/tests/baselines/reference/varArgWithNoParamName.js +++ b/tests/baselines/reference/varArgWithNoParamName.js @@ -5,6 +5,6 @@ function t1(...) {} function t1() { var = []; for (var _i = 0; _i < arguments.length; _i++) { - [_i - 0] = arguments[_i]; + [_i] = arguments[_i]; } } diff --git a/tests/baselines/reference/vararg.js b/tests/baselines/reference/vararg.js index 015c8c9957a..bd4a79b4626 100644 --- a/tests/baselines/reference/vararg.js +++ b/tests/baselines/reference/vararg.js @@ -65,7 +65,7 @@ var M; C.prototype.fonly = function () { var rest = []; for (var _i = 0; _i < arguments.length; _i++) { - rest[_i - 0] = arguments[_i]; + rest[_i] = arguments[_i]; } builder = ""; for (var i = 0; i < rest.length; i++) { diff --git a/tests/baselines/reference/variableDeclarationInStrictMode1.errors.txt b/tests/baselines/reference/variableDeclarationInStrictMode1.errors.txt index 9dd9a8d41a1..46782aaa1d6 100644 --- a/tests/baselines/reference/variableDeclarationInStrictMode1.errors.txt +++ b/tests/baselines/reference/variableDeclarationInStrictMode1.errors.txt @@ -1,4 +1,4 @@ -lib.d.ts(28,18): error TS2300: Duplicate identifier 'eval'. +lib.d.ts(32,18): error TS2300: Duplicate identifier 'eval'. tests/cases/compiler/variableDeclarationInStrictMode1.ts(2,5): error TS1100: Invalid use of 'eval' in strict mode. tests/cases/compiler/variableDeclarationInStrictMode1.ts(2,5): error TS2300: Duplicate identifier 'eval'. diff --git a/tests/baselines/reference/widenedTypes.errors.txt b/tests/baselines/reference/widenedTypes.errors.txt index ea7c2b2f92a..5ea097acf2e 100644 --- a/tests/baselines/reference/widenedTypes.errors.txt +++ b/tests/baselines/reference/widenedTypes.errors.txt @@ -1,5 +1,4 @@ tests/cases/compiler/widenedTypes.ts(2,1): error TS2358: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter. -tests/cases/compiler/widenedTypes.ts(5,1): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/compiler/widenedTypes.ts(6,7): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter tests/cases/compiler/widenedTypes.ts(8,15): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter. tests/cases/compiler/widenedTypes.ts(10,14): error TS2695: Left side of comma operator is unused and has no side effects. @@ -12,7 +11,7 @@ tests/cases/compiler/widenedTypes.ts(24,5): error TS2322: Type '{ x: number; y: Type 'number' is not assignable to type 'string'. -==== tests/cases/compiler/widenedTypes.ts (9 errors) ==== +==== tests/cases/compiler/widenedTypes.ts (8 errors) ==== null instanceof (() => { }); ~~~~ @@ -20,8 +19,6 @@ tests/cases/compiler/widenedTypes.ts(24,5): error TS2322: Type '{ x: number; y: ({}) instanceof null; // Ok because null is a subtype of function null in {}; - ~~~~ -!!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. "" in null; ~~~~ !!! error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter diff --git a/tests/cases/compiler/APISample_linter.ts b/tests/cases/compiler/APISample_linter.ts index 89f0be7a0f5..dc5e2644b4f 100644 --- a/tests/cases/compiler/APISample_linter.ts +++ b/tests/cases/compiler/APISample_linter.ts @@ -61,7 +61,7 @@ export function delint(sourceFile: ts.SourceFile) { const fileNames: string[] = process.argv.slice(2); fileNames.forEach(fileName => { // Parse a file - let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); diff --git a/tests/cases/compiler/alwaysStrict.ts b/tests/cases/compiler/alwaysStrict.ts new file mode 100644 index 00000000000..22ec09c6e38 --- /dev/null +++ b/tests/cases/compiler/alwaysStrict.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true + +function f() { + var arguments = []; +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts b/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts new file mode 100644 index 00000000000..1d804a6cf90 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +"use strict" +function f() { + var a = []; +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictES6.ts b/tests/cases/compiler/alwaysStrictES6.ts new file mode 100644 index 00000000000..edb542fa86a --- /dev/null +++ b/tests/cases/compiler/alwaysStrictES6.ts @@ -0,0 +1,6 @@ +// @target: ES6 +// @alwaysStrict: true + +function f() { + var arguments = []; +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule.ts b/tests/cases/compiler/alwaysStrictModule.ts new file mode 100644 index 00000000000..b706f5869a6 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule.ts @@ -0,0 +1,8 @@ +// @module: commonjs +// @alwaysStrict: true + +module M { + export function f() { + var arguments = []; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule2.ts b/tests/cases/compiler/alwaysStrictModule2.ts new file mode 100644 index 00000000000..6afecb0e770 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule2.ts @@ -0,0 +1,16 @@ +// @alwaysStrict: true +// @outFile: out.js + +// @fileName: a.ts +module M { + export function f() { + var arguments = []; + } +} + +// @fileName: b.ts +module M { + export function f2() { + var arguments = []; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule3.ts b/tests/cases/compiler/alwaysStrictModule3.ts new file mode 100644 index 00000000000..adb93cede36 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule3.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +// @module: es2015 + +// module ES2015 +export const a = 1; \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule4.ts b/tests/cases/compiler/alwaysStrictModule4.ts new file mode 100644 index 00000000000..f731e6dd734 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule4.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +// @module: commonjs + +// Module commonjs +export const a = 1 \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule5.ts b/tests/cases/compiler/alwaysStrictModule5.ts new file mode 100644 index 00000000000..d1ac5288370 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule5.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +// @target: es6 + +// Targeting ES6 +export const a = 1; \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule6.ts b/tests/cases/compiler/alwaysStrictModule6.ts new file mode 100644 index 00000000000..064ece1a4e1 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule6.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +// @target: es5 + +// Targeting ES5 +export const a = 1; \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts b/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts new file mode 100644 index 00000000000..d3173df8ab5 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts @@ -0,0 +1,9 @@ +// @module: commonjs +// @alwaysStrict: true +// @noImplicitUseStrict: true + +module M { + export function f() { + var arguments = []; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/ambientRequireFunction.ts b/tests/cases/compiler/ambientRequireFunction.ts new file mode 100644 index 00000000000..ce9019e00bc --- /dev/null +++ b/tests/cases/compiler/ambientRequireFunction.ts @@ -0,0 +1,17 @@ +// @module: commonjs +// @allowJs: true +// @outDir: ./out/ + +// @filename: node.d.ts + +declare function require(moduleName: string): any; + +declare module "fs" { + export function readFileSync(s: string): string; +} + +// @filename: app.js +/// + +const fs = require("fs"); +const text = fs.readFileSync("/a/b/c"); \ No newline at end of file diff --git a/tests/cases/compiler/asyncIIFE.ts b/tests/cases/compiler/asyncIIFE.ts new file mode 100644 index 00000000000..904476d855c --- /dev/null +++ b/tests/cases/compiler/asyncIIFE.ts @@ -0,0 +1,10 @@ +// @target: ES6 + +function f1() { + (async () => { + await 10 + throw new Error(); + })(); + + var x = 1; +} diff --git a/tests/cases/compiler/cacheResolutions.ts b/tests/cases/compiler/cacheResolutions.ts new file mode 100644 index 00000000000..c6962e25db6 --- /dev/null +++ b/tests/cases/compiler/cacheResolutions.ts @@ -0,0 +1,12 @@ +// @module: amd +// @importHelpers: true +// @traceResolution: true + +// @filename: /a/b/c/app.ts +export let x = 1; + +// @filename: /a/b/c/lib1.ts +export let x = 1; + +// @filename: /a/b/c/lib2.ts +export let x = 1; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution1.ts b/tests/cases/compiler/cachedModuleResolution1.ts new file mode 100644 index 00000000000..3ef09ea0ea5 --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution1.ts @@ -0,0 +1,11 @@ +// @moduleResolution: node +// @traceResolution: true + +// @filename: /a/b/node_modules/foo.d.ts +export declare let x: number + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution2.ts b/tests/cases/compiler/cachedModuleResolution2.ts new file mode 100644 index 00000000000..38aaf4e609d --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution2.ts @@ -0,0 +1,11 @@ +// @moduleResolution: node +// @traceResolution: true + +// @filename: /a/b/node_modules/foo.d.ts +export declare let x: number + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; diff --git a/tests/cases/compiler/cachedModuleResolution3.ts b/tests/cases/compiler/cachedModuleResolution3.ts new file mode 100644 index 00000000000..e1e7aebbe86 --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution3.ts @@ -0,0 +1,11 @@ +// @moduleResolution: classic +// @traceResolution: true + +// @filename: /a/b/foo.d.ts +export declare let x: number + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution4.ts b/tests/cases/compiler/cachedModuleResolution4.ts new file mode 100644 index 00000000000..98cdd14189a --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution4.ts @@ -0,0 +1,11 @@ +// @moduleResolution: classic +// @traceResolution: true + +// @filename: /a/b/foo.d.ts +export declare let x: number + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; diff --git a/tests/cases/compiler/cachedModuleResolution5.ts b/tests/cases/compiler/cachedModuleResolution5.ts new file mode 100644 index 00000000000..e37b14fc1a0 --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution5.ts @@ -0,0 +1,11 @@ +// @moduleResolution: node +// @traceResolution: true + +// @filename: /a/b/node_modules/foo.d.ts +export declare let x: number + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; + +// @filename: /a/b/lib.ts +import {x} from "foo"; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution6.ts b/tests/cases/compiler/cachedModuleResolution6.ts new file mode 100644 index 00000000000..2c412e361c6 --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution6.ts @@ -0,0 +1,8 @@ +// @moduleResolution: node +// @traceResolution: true + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution7.ts b/tests/cases/compiler/cachedModuleResolution7.ts new file mode 100644 index 00000000000..d297e2a8ecd --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution7.ts @@ -0,0 +1,8 @@ +// @moduleResolution: node +// @traceResolution: true + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; diff --git a/tests/cases/compiler/cachedModuleResolution8.ts b/tests/cases/compiler/cachedModuleResolution8.ts new file mode 100644 index 00000000000..52c91be7753 --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution8.ts @@ -0,0 +1,8 @@ +// @moduleResolution: classic +// @traceResolution: true + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; \ No newline at end of file diff --git a/tests/cases/compiler/cachedModuleResolution9.ts b/tests/cases/compiler/cachedModuleResolution9.ts new file mode 100644 index 00000000000..26d71fa86ff --- /dev/null +++ b/tests/cases/compiler/cachedModuleResolution9.ts @@ -0,0 +1,9 @@ +// @moduleResolution: classic +// @traceResolution: true + +// @filename: /a/b/c/lib.ts +import {x} from "foo"; + + +// @filename: /a/b/c/d/e/app.ts +import {x} from "foo"; diff --git a/tests/cases/compiler/captureSuperPropertyAccessInSuperCall01.ts b/tests/cases/compiler/captureSuperPropertyAccessInSuperCall01.ts new file mode 100644 index 00000000000..e60b9801c02 --- /dev/null +++ b/tests/cases/compiler/captureSuperPropertyAccessInSuperCall01.ts @@ -0,0 +1,11 @@ +class A { + constructor(f: () => string) { + } + public blah(): string { return ""; } +} + +class B extends A { + constructor() { + super(() => { return super.blah(); }) + } +} \ No newline at end of file diff --git a/tests/cases/compiler/catchClauseWithBindingPattern1.ts b/tests/cases/compiler/catchClauseWithBindingPattern1.ts deleted file mode 100644 index dbd0f81c576..00000000000 --- a/tests/cases/compiler/catchClauseWithBindingPattern1.ts +++ /dev/null @@ -1,4 +0,0 @@ -try { -} -catch ({a}) { -} \ No newline at end of file diff --git a/tests/cases/compiler/circularReferenceInImport.ts b/tests/cases/compiler/circularReferenceInImport.ts new file mode 100644 index 00000000000..869beeaa3a9 --- /dev/null +++ b/tests/cases/compiler/circularReferenceInImport.ts @@ -0,0 +1,15 @@ +// @declaration: true + +// @filename: db.d.ts +declare namespace Db { + export import Types = Db; +} + +export = Db; + +// @filename: app.ts +import * as Db from "./db" + +export function foo() { + return new Object() +} \ No newline at end of file diff --git a/tests/cases/compiler/classDeclaredBeforeClassFactory.ts b/tests/cases/compiler/classDeclaredBeforeClassFactory.ts new file mode 100644 index 00000000000..27191ce7fd2 --- /dev/null +++ b/tests/cases/compiler/classDeclaredBeforeClassFactory.ts @@ -0,0 +1,6 @@ +// Should be OK due to hoisting +class Derived extends makeBaseClass() {} + +function makeBaseClass() { + return class Base {}; +} diff --git a/tests/cases/compiler/classExpressions.ts b/tests/cases/compiler/classExpressions.ts new file mode 100644 index 00000000000..fc7ce376469 --- /dev/null +++ b/tests/cases/compiler/classExpressions.ts @@ -0,0 +1,8 @@ +interface A {} +let x = class B implements A { + prop: number; + onStart(): void { + } + func = () => { + } +}; \ No newline at end of file diff --git a/tests/cases/compiler/commaOperatorInConditionalExpression.ts b/tests/cases/compiler/commaOperatorInConditionalExpression.ts new file mode 100644 index 00000000000..a65d8ba1882 --- /dev/null +++ b/tests/cases/compiler/commaOperatorInConditionalExpression.ts @@ -0,0 +1,5 @@ +function f (m: string) { + [1, 2, 3].map(i => { + return true? { [m]: i } : { [m]: i + 1 } + }) +} \ No newline at end of file diff --git a/tests/cases/compiler/commonSourceDirectory.ts b/tests/cases/compiler/commonSourceDirectory.ts new file mode 100644 index 00000000000..9baa27431a3 --- /dev/null +++ b/tests/cases/compiler/commonSourceDirectory.ts @@ -0,0 +1,30 @@ +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. +// @noImplicitReferences: true +// @moduleResolution: node +// @fullEmitPaths: true + +// @filename: /node_modules/foo/index.ts +export const x = 0; + +// @filename: /types/bar.d.ts +declare module "bar" { + export const y = 0; +} + +// @filename: /app/index.ts +/// +import { x } from "foo"; +import { y } from "bar"; +x + y; + +// @filename: /app/tsconfig.json +{ + "compilerOptions": { + "outDir": "bin", + "typeRoots": ["../types"], + "sourceMap": true, + "mapRoot": "myMapRoot", + "sourceRoot": "mySourceRoot", + "declaration": true + } +} diff --git a/tests/cases/compiler/commonSourceDirectory_dts.ts b/tests/cases/compiler/commonSourceDirectory_dts.ts new file mode 100644 index 00000000000..3a3dfea1772 --- /dev/null +++ b/tests/cases/compiler/commonSourceDirectory_dts.ts @@ -0,0 +1,22 @@ +// Test that importing a file from `node_modules` does not affect calculation of the common source directory. +// @noImplicitReferences: true +// @moduleResolution: node +// @fullEmitPaths: true + +// @filename: /app/lib/bar.d.ts +declare const y: number; + +// @filename: /app/src/index.ts +/// +export const x = y; + +// @filename: /app/tsconfig.json +{ + "compilerOptions": { + "outDir": "bin", + "sourceMap": true, + "mapRoot": "myMapRoot", + "sourceRoot": "mySourceRoot", + "declaration": true + } +} diff --git a/tests/cases/compiler/constructorWithCapturedSuper.ts b/tests/cases/compiler/constructorWithCapturedSuper.ts new file mode 100644 index 00000000000..942803e771d --- /dev/null +++ b/tests/cases/compiler/constructorWithCapturedSuper.ts @@ -0,0 +1,52 @@ +let oneA: A; + +class A { + constructor() { + return oneA; + } +} + +class B extends A { + constructor(x: number) { + super(); + if (x === 1) { + return; + } + while (x < 2) { + return; + } + try { + return + } + catch (e) { + return; + } + finally { + return; + } + } +} + +class C extends A { + constructor(x: number) { + super(); + for (let i = 0; i < 10; ++i) { + () => i + x; + if (x === 1) { + return; + } + } + } +} + +class D extends A { + constructor(x: number) { + super(); + () => { + return; + } + function foo() { + return; + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/contextualTypingOfTooShortOverloads.ts b/tests/cases/compiler/contextualTypingOfTooShortOverloads.ts new file mode 100644 index 00000000000..6fa88a1e559 --- /dev/null +++ b/tests/cases/compiler/contextualTypingOfTooShortOverloads.ts @@ -0,0 +1,49 @@ +// small repro from #11875 +var use: Overload; +use((req, res) => {}); + +interface Overload { + (handler1: (req1: string) => void): void; + (handler2: (req2: number, res2: number) => void): void; +} +// larger repro from #11875 +let app: MyApp; +app.use((err: any, req, res, next) => { return; }); + + +interface MyApp { + use: IRouterHandler & IRouterMatcher; +} + +interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; +} + +interface IRouterMatcher { + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +} + +type PathParams = string | RegExp | (string | RegExp)[]; +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + +interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; +} + +interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; +} + +interface Request { + method: string; +} + +interface Response { + statusCode: number; +} + +interface NextFunction { + (err?: any): void; +} diff --git a/tests/cases/compiler/controlFlowArrayErrors.ts b/tests/cases/compiler/controlFlowArrayErrors.ts new file mode 100644 index 00000000000..08107ff3659 --- /dev/null +++ b/tests/cases/compiler/controlFlowArrayErrors.ts @@ -0,0 +1,67 @@ +// @noImplicitAny: true + +declare function cond(): boolean; + +function f1() { + let x = []; // Implicit any[] error in some locations + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f2() { + let x; // Implicit any[] error in some locations + x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f3() { + let x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} + +function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} + +function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} + +function f8() { + const x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} \ No newline at end of file diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts new file mode 100644 index 00000000000..646c85f069f --- /dev/null +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -0,0 +1,181 @@ +// @strictNullChecks: true +// @noImplicitAny: true + +declare function cond(): boolean; + +function f1() { + let x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} + +function f2() { + let x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f3() { + let x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} + +function f4() { + let x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} + +function f5() { + let x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} + +function f6() { + let x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} + +function f7() { + let x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} + +function f8() { + let x = []; + x.push(5); + if (cond()) return x; // number[] + x.push("hello"); + if (cond()) return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} + +function f9() { + let x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} + +function f10() { + let x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} + +function f11() { + let x = []; + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; +} + +function f12() { + let x; + x = []; + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; +} + +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f14() { + const x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f15() { + let x = []; + while (cond()) { + while (cond()) {} + x.push("hello"); + } + return x; // string[] +} + +function f16() { + let x; + let y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] +} + +function f17() { + let x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} + +function f18() { + let x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] +} \ No newline at end of file diff --git a/tests/cases/compiler/controlFlowLetVar.ts b/tests/cases/compiler/controlFlowJavascript.ts similarity index 61% rename from tests/cases/compiler/controlFlowLetVar.ts rename to tests/cases/compiler/controlFlowJavascript.ts index a56a3382642..b2886a2233a 100644 --- a/tests/cases/compiler/controlFlowLetVar.ts +++ b/tests/cases/compiler/controlFlowJavascript.ts @@ -1,8 +1,10 @@ -// @strictNullChecks: true +// @allowJs: true +// @Filename: controlFlowJavascript.js +// @out: out.js -declare let cond: boolean; +let cond = true; -// CFA for 'let' with no type annotation and initializer +// CFA for 'let' and no initializer function f1() { let x; if (cond) { @@ -14,7 +16,7 @@ function f1() { const y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'undefined' initializer +// CFA for 'let' and 'undefined' initializer function f2() { let x = undefined; if (cond) { @@ -26,7 +28,7 @@ function f2() { const y = x; // string | number | undefined } -// CFA for 'let' with no type annotation and 'null' initializer +// CFA for 'let' and 'null' initializer function f3() { let x = null; if (cond) { @@ -38,19 +40,7 @@ function f3() { const y = x; // string | number | null } -// No CFA for 'let' with with type annotation -function f4() { - let x: any; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - const y = x; // any -} - -// CFA for 'var' with no type annotation and initializer +// CFA for 'var' with no initializer function f5() { var x; if (cond) { @@ -62,7 +52,7 @@ function f5() { const y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'undefined' initializer +// CFA for 'var' with 'undefined' initializer function f6() { var x = undefined; if (cond) { @@ -74,7 +64,7 @@ function f6() { const y = x; // string | number | undefined } -// CFA for 'var' with no type annotation and 'null' initializer +// CFA for 'var' with 'null' initializer function f7() { var x = null; if (cond) { @@ -86,18 +76,6 @@ function f7() { const y = x; // string | number | null } -// No CFA for 'var' with with type annotation -function f8() { - var x: any; - if (cond) { - x = 1; - } - if (cond) { - x = "hello"; - } - const y = x; // any -} - // No CFA for captured outer variables function f9() { let x; @@ -126,4 +104,4 @@ function f10() { const f = () => { const z = x; // any }; -} \ No newline at end of file +} diff --git a/tests/cases/compiler/controlFlowSelfReferentialLoop.ts b/tests/cases/compiler/controlFlowSelfReferentialLoop.ts new file mode 100644 index 00000000000..361d3a557b4 --- /dev/null +++ b/tests/cases/compiler/controlFlowSelfReferentialLoop.ts @@ -0,0 +1,102 @@ +// @noimplicitany: true + +// Repro from #12319 + +function md5(string:string): void { + + function FF(a,b,c,d,x,s,ac) { + return 0; + }; + + function GG(a,b,c,d,x,s,ac) { + return 0; + }; + + function HH(a,b,c,d,x,s,ac) { + return 0; + }; + + function II(a,b,c,d,x,s,ac) { + return 0; + }; + + var x=Array(); + var k,AA,BB,CC,DD,a,b,c,d; + var S11=7, S12=12, S13=17, S14=22; + var S21=5, S22=9 , S23=14, S24=20; + var S31=4, S32=11, S33=16, S34=23; + var S41=6, S42=10, S43=15, S44=21; + + x = [1]; + + a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; + + for (k=0;k = {} \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters2.ts b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters2.ts new file mode 100644 index 00000000000..de94ad4998d --- /dev/null +++ b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters2.ts @@ -0,0 +1,6 @@ +// @declaration: true + +export type Bar = () => [X, Y, Z]; +export type Baz = Bar; +export type Baa = Baz; +export const y = (x: Baa) => 1 \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters3.ts b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters3.ts new file mode 100644 index 00000000000..6c7d4799abc --- /dev/null +++ b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters3.ts @@ -0,0 +1,8 @@ +// @declaration: true + +type Foo = { + foo(): Foo +}; +function bar() { + return {} as Foo; +} diff --git a/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters4.ts b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters4.ts new file mode 100644 index 00000000000..42bb8097997 --- /dev/null +++ b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters4.ts @@ -0,0 +1,10 @@ +// @declaration: true + +type Foo = { + foo(): Foo +}; +type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} diff --git a/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters5.ts b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters5.ts new file mode 100644 index 00000000000..b6334e76337 --- /dev/null +++ b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters5.ts @@ -0,0 +1,10 @@ +// @declaration: true + +type Foo = { + foo(): Foo +}; +export type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} diff --git a/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters6.ts b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters6.ts new file mode 100644 index 00000000000..9b313027021 --- /dev/null +++ b/tests/cases/compiler/declarationEmitTypeAliasWithTypeParameters6.ts @@ -0,0 +1,10 @@ +// @declaration: true + +type Foo = { + foo(): Foo +}; +type SubFoo = Foo; + +function foo() { + return {} as SubFoo; +} diff --git a/tests/cases/compiler/declarationFilesWithTypeReferences1.ts b/tests/cases/compiler/declarationFilesWithTypeReferences1.ts new file mode 100644 index 00000000000..e499543057e --- /dev/null +++ b/tests/cases/compiler/declarationFilesWithTypeReferences1.ts @@ -0,0 +1,14 @@ +// @types: node +// @declaration: true +// @currentDirectory: / + +// @filename: /node_modules/@types/node/index.d.ts +interface Error { + stack2: string; +} + +// @filename: /app.ts + +function foo(): Error { + return undefined; +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationFilesWithTypeReferences2.ts b/tests/cases/compiler/declarationFilesWithTypeReferences2.ts new file mode 100644 index 00000000000..05148955637 --- /dev/null +++ b/tests/cases/compiler/declarationFilesWithTypeReferences2.ts @@ -0,0 +1,14 @@ +// @types: node +// @declaration: true +// @currentDirectory: / + +// @filename: /node_modules/@types/node/index.d.ts +interface Error2 { + stack2: string; +} + +// @filename: /app.ts + +function foo(): Error2 { + return undefined; +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationFilesWithTypeReferences3.ts b/tests/cases/compiler/declarationFilesWithTypeReferences3.ts new file mode 100644 index 00000000000..6653fb11f8b --- /dev/null +++ b/tests/cases/compiler/declarationFilesWithTypeReferences3.ts @@ -0,0 +1,12 @@ +// @declaration: true + +// @filename: /a/node_modules/@types/node/index.d.ts +interface Error2 { + stack2: string; +} + +// @filename: /a/app.ts +/// +function foo(): Error2 { + return undefined; +} \ No newline at end of file diff --git a/tests/cases/compiler/declarationFilesWithTypeReferences4.ts b/tests/cases/compiler/declarationFilesWithTypeReferences4.ts new file mode 100644 index 00000000000..4719feb5664 --- /dev/null +++ b/tests/cases/compiler/declarationFilesWithTypeReferences4.ts @@ -0,0 +1,12 @@ +// @declaration: true + +// @filename: /a/node_modules/@types/node/index.d.ts +interface Error { + stack2: string; +} + +// @filename: /a/app.ts +/// +function foo(): Error { + return undefined; +} \ No newline at end of file diff --git a/tests/cases/compiler/decoratorInJsFile.ts b/tests/cases/compiler/decoratorInJsFile.ts new file mode 100644 index 00000000000..611be319209 --- /dev/null +++ b/tests/cases/compiler/decoratorInJsFile.ts @@ -0,0 +1,12 @@ +// @experimentaldecorators: true +// @emitdecoratormetadata: true +// @allowjs: true +// @noEmit: true + +// @filename: a.js +@SomeDecorator +class SomeClass { + foo(x: number) { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/decoratorInJsFile1.ts b/tests/cases/compiler/decoratorInJsFile1.ts new file mode 100644 index 00000000000..6bbe38cb835 --- /dev/null +++ b/tests/cases/compiler/decoratorInJsFile1.ts @@ -0,0 +1,10 @@ +// @allowjs: true +// @noEmit: true + +// @filename: a.js +@SomeDecorator +class SomeClass { + foo(x: number) { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/decoratorMetadataRestParameterWithImportedType.ts b/tests/cases/compiler/decoratorMetadataRestParameterWithImportedType.ts new file mode 100644 index 00000000000..3bc22df8928 --- /dev/null +++ b/tests/cases/compiler/decoratorMetadataRestParameterWithImportedType.ts @@ -0,0 +1,42 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 + +// @filename: aux.ts +export class SomeClass { + field: string; +} + +// @filename: aux1.ts +export class SomeClass1 { + field: string; +} + +// @filename: aux2.ts +export class SomeClass2 { + field: string; +} +// @filename: main.ts +import { SomeClass } from './aux'; +import { SomeClass1 } from './aux1'; + +function annotation(): ClassDecorator { + return (target: any): void => { }; +} + +function annotation1(): MethodDecorator { + return (target: any): void => { }; +} + +@annotation() +export class ClassA { + array: SomeClass[]; + + constructor(...init: SomeClass[]) { + this.array = init; + } + + @annotation1() + foo(... args: SomeClass1[]) { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/decoratorWithUnderscoreMethod.ts b/tests/cases/compiler/decoratorWithUnderscoreMethod.ts new file mode 100644 index 00000000000..e6551c91284 --- /dev/null +++ b/tests/cases/compiler/decoratorWithUnderscoreMethod.ts @@ -0,0 +1,18 @@ +// @noemithelpers: true +// @experimentaldecorators: true + +declare var console : { log(arg: string): void }; +function dec(): Function { + return function (target: any, propKey: string, descr: PropertyDescriptor): void { + console.log(target[propKey]); + //logs undefined + //propKey has three underscores as prefix, but the method has only two underscores + }; +} + +class A { + @dec() + private __foo(bar: string): void { + // do something with bar + } +} \ No newline at end of file diff --git a/tests/cases/compiler/doWhileUnreachableCode.ts b/tests/cases/compiler/doWhileUnreachableCode.ts new file mode 100644 index 00000000000..e4b47fc1afb --- /dev/null +++ b/tests/cases/compiler/doWhileUnreachableCode.ts @@ -0,0 +1,12 @@ +function test() { + let foo = 0; + testLoop: do { + foo++; + continue testLoop; + } while (function() { + var x = 1; + return false; + }()); + + return foo; +} \ No newline at end of file diff --git a/tests/cases/compiler/es2017basicAsync.ts b/tests/cases/compiler/es2017basicAsync.ts new file mode 100644 index 00000000000..b08ee6a18ae --- /dev/null +++ b/tests/cases/compiler/es2017basicAsync.ts @@ -0,0 +1,49 @@ +// @target: es2017 +// @lib: es2017 +// @noEmitHelpers: true + +async (): Promise => { + await 0; +} + +async function asyncFunc() { + await 0; +} + +const asyncArrowFunc = async (): Promise => { + await 0; +} + +async function asyncIIFE() { + await 0; + + await (async function(): Promise { + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { + await 1; + })(); + + await (async (): Promise => { + await 1; + })(); +} + +class AsyncClass { + asyncPropFunc = async function(): Promise { + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { + await 2; + } + + asyncPropArrowFunc = async (): Promise => { + await 2; + } + + async asyncMethod(): Promise { + await 2; + } +} diff --git a/tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts b/tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts new file mode 100644 index 00000000000..93489ee4820 --- /dev/null +++ b/tests/cases/compiler/es3-oldStyleOctalLiteralInEnums.ts @@ -0,0 +1,5 @@ +// @target: ES3 +enum E { + x = -01, + y = 02, +} \ No newline at end of file diff --git a/tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts b/tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts new file mode 100644 index 00000000000..c5a5475e300 --- /dev/null +++ b/tests/cases/compiler/es3-oldStyleOctalLiteralTypes.ts @@ -0,0 +1,3 @@ +// @target: ES3 +let x: 010; +let y: -020; diff --git a/tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts b/tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts new file mode 100644 index 00000000000..42a95eff2a2 --- /dev/null +++ b/tests/cases/compiler/es5-oldStyleOctalLiteralInEnums.ts @@ -0,0 +1,5 @@ +// @target: ES5 +enum E { + x = -01, + y = 02, +} \ No newline at end of file diff --git a/tests/cases/compiler/exhaustiveSwitchWithWideningLiteralTypes.ts b/tests/cases/compiler/exhaustiveSwitchWithWideningLiteralTypes.ts new file mode 100644 index 00000000000..14183a5de59 --- /dev/null +++ b/tests/cases/compiler/exhaustiveSwitchWithWideningLiteralTypes.ts @@ -0,0 +1,18 @@ +// @strictNullChecks: true + +// Repro from #12529 + +class A { + readonly kind = "A"; // (property) A.kind: "A" +} + +class B { + readonly kind = "B"; // (property) B.kind: "B" +} + +function f(value: A | B): number { + switch(value.kind) { + case "A": return 0; + case "B": return 1; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/explicitAnyAfterSpreadNoImplicitAnyError.ts b/tests/cases/compiler/explicitAnyAfterSpreadNoImplicitAnyError.ts new file mode 100644 index 00000000000..1c5ebac3d91 --- /dev/null +++ b/tests/cases/compiler/explicitAnyAfterSpreadNoImplicitAnyError.ts @@ -0,0 +1,3 @@ +// @noImplicitAny: true +({ a: [], ...(null as any) }); +let x: any; diff --git a/tests/cases/compiler/exportAsNamespace.d.ts b/tests/cases/compiler/exportAsNamespace.d.ts new file mode 100644 index 00000000000..755d4fdb2a9 --- /dev/null +++ b/tests/cases/compiler/exportAsNamespace.d.ts @@ -0,0 +1,4 @@ +// issue: https://github.com/Microsoft/TypeScript/issues/11545 + +export var X; +export as namespace N \ No newline at end of file diff --git a/tests/cases/compiler/extendPrivateConstructorClass.ts b/tests/cases/compiler/extendPrivateConstructorClass.ts new file mode 100644 index 00000000000..90629657f76 --- /dev/null +++ b/tests/cases/compiler/extendPrivateConstructorClass.ts @@ -0,0 +1,8 @@ +declare namespace abc { + class XYZ { + private constructor(); + } +} + +class C extends abc.XYZ { +} diff --git a/tests/cases/compiler/flowInFinally1.ts b/tests/cases/compiler/flowInFinally1.ts new file mode 100644 index 00000000000..4ab2977e7df --- /dev/null +++ b/tests/cases/compiler/flowInFinally1.ts @@ -0,0 +1,16 @@ +// @strictNullChecks: true + +class A { + constructor() { } + method() { } +} + +let a: A | null = null; + +try { + a = new A(); +} finally { + if (a) { + a.method(); + } +} \ No newline at end of file diff --git a/tests/cases/compiler/forOfStringConstituents.ts b/tests/cases/compiler/forOfStringConstituents.ts new file mode 100644 index 00000000000..224fb5396bd --- /dev/null +++ b/tests/cases/compiler/forOfStringConstituents.ts @@ -0,0 +1,8 @@ +interface A { x: 0; y: C[]; } +interface B { x: 1; y: CD[]; } +interface C { x: 2; } +interface D { x: 3; } +type AB = A | B; +type CD = C | D; +declare let x: AB, y: CD; +for (y of x.y); \ No newline at end of file diff --git a/tests/cases/compiler/implicitAnyWidenToAny.ts b/tests/cases/compiler/implicitAnyWidenToAny.ts index b4f4b5eb312..dcbabd38b47 100644 --- a/tests/cases/compiler/implicitAnyWidenToAny.ts +++ b/tests/cases/compiler/implicitAnyWidenToAny.ts @@ -3,7 +3,7 @@ var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error class AnimalObj { diff --git a/tests/cases/compiler/importHelpersDeclarations.ts b/tests/cases/compiler/importHelpersDeclarations.ts new file mode 100644 index 00000000000..7b958cda789 --- /dev/null +++ b/tests/cases/compiler/importHelpersDeclarations.ts @@ -0,0 +1,9 @@ +// @importHelpers: true +// @target: es5 +// @module: commonjs +// @moduleResolution: classic +// @filename: declaration.d.ts +export declare class D { +} +export declare class E extends D { +} \ No newline at end of file diff --git a/tests/cases/compiler/importHelpersNoHelpers.ts b/tests/cases/compiler/importHelpersNoHelpers.ts index 82428552548..4ab48aba7df 100644 --- a/tests/cases/compiler/importHelpersNoHelpers.ts +++ b/tests/cases/compiler/importHelpersNoHelpers.ts @@ -16,6 +16,10 @@ class C { } } +const o = { a: 1 }; +const y = { ...o }; +const { ...x } = y; + // @filename: script.ts class A { } class B extends A { } @@ -29,4 +33,4 @@ class C { } // @filename: tslib.d.ts -export {} \ No newline at end of file +export {} diff --git a/tests/cases/compiler/incompatibleAssignmentOfIdenticallyNamedTypes.ts b/tests/cases/compiler/incompatibleAssignmentOfIdenticallyNamedTypes.ts new file mode 100644 index 00000000000..493feef1fd7 --- /dev/null +++ b/tests/cases/compiler/incompatibleAssignmentOfIdenticallyNamedTypes.ts @@ -0,0 +1,8 @@ +interface T { } +declare const a: T; +class Foo { + x: T; + fn() { + this.x = a; + } +} diff --git a/tests/cases/compiler/instantiatedTypeAliasDisplay.ts b/tests/cases/compiler/instantiatedTypeAliasDisplay.ts new file mode 100644 index 00000000000..8f7500e7830 --- /dev/null +++ b/tests/cases/compiler/instantiatedTypeAliasDisplay.ts @@ -0,0 +1,17 @@ +// @declaration: true + +// Repros from #12066 + +interface X
{ + a: A; +} +interface Y { + b: B; +} +type Z = X | Y; + +declare function f1(): Z; +declare function f2(a: A, b: B, c: C, d: D): Z; + +const x1 = f1(); // Z +const x2 = f2({}, {}, {}, {}); // Z<{}, string[]> \ No newline at end of file diff --git a/tests/cases/compiler/intersectionTypeNormalization.ts b/tests/cases/compiler/intersectionTypeNormalization.ts new file mode 100644 index 00000000000..3d07aeb1a23 --- /dev/null +++ b/tests/cases/compiler/intersectionTypeNormalization.ts @@ -0,0 +1,105 @@ +interface A { a: string } +interface B { b: string } +interface C { c: string } +interface D { d: string } + +// Identical ways of writing the same type +type X1 = (A | B) & (C | D); +type X2 = A & (C | D) | B & (C | D) +type X3 = A & C | A & D | B & C | B & D; + +var x: X1; +var x: X2; +var x: X3; + +interface X { x: string } +interface Y { y: string } + +// Identical ways of writing the same type +type Y1 = (A | X & Y) & (C | D); +type Y2 = A & (C | D) | X & Y & (C | D) +type Y3 = A & C | A & D | X & Y & C | X & Y & D; + +var y: Y1; +var y: Y2; +var y: Y3; + +interface M { m: string } +interface N { n: string } + +// Identical ways of writing the same type +type Z1 = (A | X & (M | N)) & (C | D); +type Z2 = A & (C | D) | X & (M | N) & (C | D) +type Z3 = A & C | A & D | X & (M | N) & C | X & (M | N) & D; +type Z4 = A & C | A & D | X & M & C | X & N & C | X & M & D | X & N & D; + +var z: Z1; +var z: Z2; +var z: Z3; +var z: Z4; + +// Repro from #9919 + +type ToString = { + toString(): string; +} + +type BoxedValue = { kind: 'int', num: number } + | { kind: 'string', str: string } + +type IntersectionFail = BoxedValue & ToString + +type IntersectionInline = { kind: 'int', num: number } & ToString + | { kind: 'string', str: string } & ToString + +function getValueAsString(value: IntersectionFail): string { + if (value.kind === 'int') { + return '' + value.num; + } + return value.str; +} + +// Repro from #12535 + +namespace enums { + export const enum A { + a1, + a2, + a3, + // ... elements omitted for the sake of clarity + a75, + a76, + a77, + } + export const enum B { + b1, + b2, + // ... elements omitted for the sake of clarity + b86, + b87, + } + export const enum C { + c1, + c2, + // ... elements omitted for the sake of clarity + c210, + c211, + } + export type Genre = A | B | C; +} + +type Foo = { + genreId: enums.Genre; +}; + +type Bar = { + genreId: enums.Genre; +}; + +type FooBar = Foo & Bar; + +function foo(so: any) { + const val = so as FooBar; + const isGenre = val.genreId; + return isGenre; +} \ No newline at end of file diff --git a/tests/cases/compiler/intersectionTypeWithLeadingOperator.ts b/tests/cases/compiler/intersectionTypeWithLeadingOperator.ts new file mode 100644 index 00000000000..4138dee4261 --- /dev/null +++ b/tests/cases/compiler/intersectionTypeWithLeadingOperator.ts @@ -0,0 +1,6 @@ +type A = & string; +type B = + & { foo: string } + & { bar: number }; + +type C = [& { foo: 1 } & { bar: 2 }, & { foo: 3 } & { bar: 4 }]; diff --git a/tests/cases/compiler/invalidUseOfTypeAsNamespace.ts b/tests/cases/compiler/invalidUseOfTypeAsNamespace.ts new file mode 100644 index 00000000000..5391715cb3a --- /dev/null +++ b/tests/cases/compiler/invalidUseOfTypeAsNamespace.ts @@ -0,0 +1,4 @@ +interface OhNo { +} + +declare let y: OhNo.hello; diff --git a/tests/cases/compiler/jsFileCompilationAbstractModifier.ts b/tests/cases/compiler/jsFileCompilationAbstractModifier.ts new file mode 100644 index 00000000000..ebd021e05a1 --- /dev/null +++ b/tests/cases/compiler/jsFileCompilationAbstractModifier.ts @@ -0,0 +1,5 @@ +// @allowJs: true +// @filename: a.js +abstract class c { + abstract x; +} \ No newline at end of file diff --git a/tests/cases/compiler/jsFileCompilationConstModifier.ts b/tests/cases/compiler/jsFileCompilationConstModifier.ts new file mode 100644 index 00000000000..4ffa62bb6a2 --- /dev/null +++ b/tests/cases/compiler/jsFileCompilationConstModifier.ts @@ -0,0 +1,4 @@ +// @allowJs: true +// @filename: a.js +// @noEmit: true +const c = 10; \ No newline at end of file diff --git a/tests/cases/compiler/jsxEmitWithAttributes.ts b/tests/cases/compiler/jsxEmitWithAttributes.ts new file mode 100644 index 00000000000..1fb7a9ccf8d --- /dev/null +++ b/tests/cases/compiler/jsxEmitWithAttributes.ts @@ -0,0 +1,53 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@reactNamespace: Element + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryAndReactNamespace.ts b/tests/cases/compiler/jsxFactoryAndReactNamespace.ts new file mode 100644 index 00000000000..2bdc954da3a --- /dev/null +++ b/tests/cases/compiler/jsxFactoryAndReactNamespace.ts @@ -0,0 +1,54 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@reactNamespace: Element +//@jsxFactory: Element.createElement + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryIdentifier.ts b/tests/cases/compiler/jsxFactoryIdentifier.ts new file mode 100644 index 00000000000..88caf27482e --- /dev/null +++ b/tests/cases/compiler/jsxFactoryIdentifier.ts @@ -0,0 +1,54 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: createElement +//@sourcemap: true + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; +let createElement = Element.createElement; +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryIdentifierAsParameter.ts b/tests/cases/compiler/jsxFactoryIdentifierAsParameter.ts new file mode 100644 index 00000000000..bd92a473428 --- /dev/null +++ b/tests/cases/compiler/jsxFactoryIdentifierAsParameter.ts @@ -0,0 +1,18 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: createElement +//@sourcemap: true + +// @filename: test.tsx +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render(createElement) { + return
; + } +} diff --git a/tests/cases/compiler/jsxFactoryIdentifierWithAbsentParameter.ts b/tests/cases/compiler/jsxFactoryIdentifierWithAbsentParameter.ts new file mode 100644 index 00000000000..49e485a1085 --- /dev/null +++ b/tests/cases/compiler/jsxFactoryIdentifierWithAbsentParameter.ts @@ -0,0 +1,18 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: createElement +//@sourcemap: true + +// @filename: test.tsx +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render() { + return
; + } +} diff --git a/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName.ts b/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName.ts new file mode 100644 index 00000000000..6f7c584d232 --- /dev/null +++ b/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName.ts @@ -0,0 +1,53 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: Element.createElement= + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName2.ts b/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName2.ts new file mode 100644 index 00000000000..610063f7d34 --- /dev/null +++ b/tests/cases/compiler/jsxFactoryNotIdentifierOrQualifiedName2.ts @@ -0,0 +1,53 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: id1 id2 + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryQualifiedName.ts b/tests/cases/compiler/jsxFactoryQualifiedName.ts new file mode 100644 index 00000000000..769b7cd566d --- /dev/null +++ b/tests/cases/compiler/jsxFactoryQualifiedName.ts @@ -0,0 +1,54 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: Element.createElement +//@sourcemap: true + +// @filename: Element.ts +declare namespace JSX { + interface Element { + name: string; + isIntrinsic: boolean; + isCustomElement: boolean; + toString(renderId?: number): string; + bindDOM(renderId?: number): number; + resetComponent(): void; + instantiateComponents(renderId?: number): number; + props: any; + } +} +export namespace Element { + export function isElement(el: any): el is JSX.Element { + return el.markAsChildOfRootElement !== undefined; + } + + export function createElement(args: any[]) { + + return { + } + } +} + +export let createElement = Element.createElement; + +function toCamelCase(text: string): string { + return text[0].toLowerCase() + text.substring(1); +} + +// @filename: test.tsx +import { Element} from './Element'; + +let c: { + a?: { + b: string + } +}; + +class A { + view() { + return [ + , + + ]; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryQualifiedNameResolutionError.ts b/tests/cases/compiler/jsxFactoryQualifiedNameResolutionError.ts new file mode 100644 index 00000000000..a8996245138 --- /dev/null +++ b/tests/cases/compiler/jsxFactoryQualifiedNameResolutionError.ts @@ -0,0 +1,18 @@ +//@jsx: react +//@target: es6 +//@module: commonjs +//@jsxFactory: MyElement.createElement +//@sourcemap: true + +// @filename: test.tsx +declare module JSX { + interface IntrinsicElements { + [s: string]: any; + } +} + +export class AppComponent { + render(createElement) { + return
; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxFactoryQualifiedNameWithEs5.ts b/tests/cases/compiler/jsxFactoryQualifiedNameWithEs5.ts new file mode 100644 index 00000000000..86fd9935a1f --- /dev/null +++ b/tests/cases/compiler/jsxFactoryQualifiedNameWithEs5.ts @@ -0,0 +1,17 @@ +//@module: commonjs +//@target: es5 +//@jsx: react +//@jsxFactory: skate.h +//@noEmit: false + +// @filename: index.tsx +import "./jsx"; + +var skate: any; +const React = { createElement: skate.h }; + +class Component { + renderCallback() { + return
test
; + } +}; \ No newline at end of file diff --git a/tests/cases/compiler/jsxViaImport.2.tsx b/tests/cases/compiler/jsxViaImport.2.tsx new file mode 100644 index 00000000000..1849fef6253 --- /dev/null +++ b/tests/cases/compiler/jsxViaImport.2.tsx @@ -0,0 +1,23 @@ +//@jsx: preserve +//@module: commonjs + +//@filename: component.d.ts +declare module JSX { + interface ElementAttributesProperty { props; } +} +declare module React { + class Component { } +} +declare module "BaseComponent" { + export default class extends React.Component { + } +} + +//@filename: consumer.tsx +/// +import BaseComponent from 'BaseComponent'; +class TestComponent extends React.Component { + render() { + return ; + } +} diff --git a/tests/cases/compiler/keyofIsLiteralContexualType.ts b/tests/cases/compiler/keyofIsLiteralContexualType.ts new file mode 100644 index 00000000000..dd14de92289 --- /dev/null +++ b/tests/cases/compiler/keyofIsLiteralContexualType.ts @@ -0,0 +1,13 @@ +// keyof T is a literal contextual type + +function foo() { + let a: (keyof T)[] = ["a", "b"]; + let b: (keyof T)[] = ["a", "b", "c"]; +} + +// Repro from #12455 + +declare function pick(obj: T, propNames: K[]): Pick; + +let x = pick({ a: 10, b: 20, c: 30 }, ["a", "c"]); +let b = x.b; // Error \ No newline at end of file diff --git a/tests/cases/compiler/localRequireFunction.ts b/tests/cases/compiler/localRequireFunction.ts new file mode 100644 index 00000000000..c8f3c2452ff --- /dev/null +++ b/tests/cases/compiler/localRequireFunction.ts @@ -0,0 +1,11 @@ +// @module: commonjs +// @allowJs: true +// @outDir: ./out/ + +// @filename: app.js +function require(a) { + return a; +} + +const fs = require("fs"); +const text = fs.readFileSync("/a/b/c"); \ No newline at end of file diff --git a/tests/cases/compiler/mappedTypeInferenceCircularity.ts b/tests/cases/compiler/mappedTypeInferenceCircularity.ts new file mode 100644 index 00000000000..56fe08c5fe2 --- /dev/null +++ b/tests/cases/compiler/mappedTypeInferenceCircularity.ts @@ -0,0 +1,7 @@ +// Repro from #12511 + +type HTML = { [K in 'div']: Block }; +type Block

= (func: HTML) => {}; + +declare var h: HTML; +h.div(h); \ No newline at end of file diff --git a/tests/cases/compiler/metadataOfClassFromModule.ts b/tests/cases/compiler/metadataOfClassFromModule.ts new file mode 100644 index 00000000000..aca356f2247 --- /dev/null +++ b/tests/cases/compiler/metadataOfClassFromModule.ts @@ -0,0 +1,14 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +// @target: es5 +module MyModule { + + export function inject(target: any, key: string): void { } + + export class Leg { } + + export class Person { + @inject leftLeg: Leg; + } + +} \ No newline at end of file diff --git a/tests/cases/compiler/metadataOfUnionWithNull.ts b/tests/cases/compiler/metadataOfUnionWithNull.ts new file mode 100644 index 00000000000..bb4d93189fc --- /dev/null +++ b/tests/cases/compiler/metadataOfUnionWithNull.ts @@ -0,0 +1,44 @@ +// @experimentalDecorators: true +// @emitDecoratorMetadata: true +function PropDeco(target: Object, propKey: string | symbol) { } + +class A { +} + +class B { + @PropDeco + x: "foo" | null; + + @PropDeco + y: true | never; + + @PropDeco + z: "foo" | undefined; + + @PropDeco + a: null; + + @PropDeco + b: never; + + @PropDeco + c: undefined; + + @PropDeco + d: undefined | null; + + @PropDeco + e: symbol | null; + + @PropDeco + f: symbol | A; + + @PropDeco + g: A | null; + + @PropDeco + h: null | B; + + @PropDeco + j: null | symbol; +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleResolutionNoTs.ts b/tests/cases/compiler/moduleResolutionNoTs.ts index 2051bc259bf..fc92d729464 100644 --- a/tests/cases/compiler/moduleResolutionNoTs.ts +++ b/tests/cases/compiler/moduleResolutionNoTs.ts @@ -1,3 +1,4 @@ +// @jsx: Preserve // @filename: x.ts export default 0; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_notSupported.ts b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported.ts new file mode 100644 index 00000000000..58b039ad8c2 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported.ts @@ -0,0 +1,13 @@ +// @noImplicitReferences: true +// @traceResolution: true + +// @Filename: /tsx.tsx + +// @Filename: /jsx.jsx + +// @Filename: /js.js + +// @Filename: /a.ts +import tsx from "./tsx"; +import jsx from "./jsx"; +import js from "./js"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_notSupported2.ts b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported2.ts new file mode 100644 index 00000000000..42741fabad6 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported2.ts @@ -0,0 +1,9 @@ +// @noImplicitReferences: true +// @allowJs: true +// @traceResolution: true +// Test the error message if we have `--allowJs` but not `--jsx`. + +// @Filename: /jsx.jsx + +// @Filename: /a.ts +import jsx from "./jsx"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_notSupported3.ts b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported3.ts new file mode 100644 index 00000000000..e06f603377c --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_notSupported3.ts @@ -0,0 +1,9 @@ +// @noImplicitReferences: true +// @jsx: preserve +// @traceResolution: true +// Test the error message if we have `--jsx` but not `--allowJw`. + +// @Filename: /jsx.jsx + +// @Filename: /a.ts +import jsx from "./jsx"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_preferTs.ts b/tests/cases/compiler/moduleResolutionWithExtensions_preferTs.ts new file mode 100644 index 00000000000..5688408b72b --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_preferTs.ts @@ -0,0 +1,10 @@ +// @noImplicitReferences: true +// @traceResolution: true + +// @Filename: /b.js + +// @Filename: /b/index.ts +export default 0; + +// @Filename: /a.ts +import b from "./b"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_unexpected.ts b/tests/cases/compiler/moduleResolutionWithExtensions_unexpected.ts new file mode 100644 index 00000000000..3af02eabb76 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_unexpected.ts @@ -0,0 +1,12 @@ +// @noImplicitReferences: true +// @traceResolution: true +// This tests that a package.json "main" with an unexpected extension is ignored. + +// @Filename: /node_modules/normalize.css/normalize.css +This file is not read. + +// @Filename: /node_modules/normalize.css/package.json +{ "main": "normalize.css" } + +// @Filename: /a.ts +import "normalize.css"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_unexpected2.ts b/tests/cases/compiler/moduleResolutionWithExtensions_unexpected2.ts new file mode 100644 index 00000000000..1c960fa67e9 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_unexpected2.ts @@ -0,0 +1,12 @@ +// @noImplicitReferences: true +// @traceResolution: true +// This tests that a package.json "types" with an unexpected extension is ignored. + +// @Filename: /node_modules/foo/foo.js +This file is not read. + +// @Filename: /node_modules/foo/package.json +{ "types": "foo.js" } + +// @Filename: /a.ts +import "foo"; diff --git a/tests/cases/compiler/moduleResolutionWithExtensions_withAmbientPresent.ts b/tests/cases/compiler/moduleResolutionWithExtensions_withAmbientPresent.ts new file mode 100644 index 00000000000..b41a7e52bd8 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithExtensions_withAmbientPresent.ts @@ -0,0 +1,14 @@ +// @noImplicitReferences: true +// @traceResolution: true +// Allowjs is false, but this should *not* warn about the unused 'index.js' + +// @Filename: /node_modules/js/index.js + +// @Filename: /declarations.d.ts +declare module "js" { + export const x = 0; +} + +// @Filename: /a.ts +/// +import { x } from "js"; diff --git a/tests/cases/compiler/moduleResolutionWithSymlinks.ts b/tests/cases/compiler/moduleResolutionWithSymlinks.ts index 8f6f1ca1fbd..069f11f85da 100644 --- a/tests/cases/compiler/moduleResolutionWithSymlinks.ts +++ b/tests/cases/compiler/moduleResolutionWithSymlinks.ts @@ -1,10 +1,12 @@ -// @module: commonjs +// When symlinked files are in node_modules, they are resolved with realpath; +// so a linked file does not create a duplicate SourceFile of the real one. // @noImplicitReferences: true // @traceResolution: true +// @fullEmitPaths: true // @filename: /src/library-a/index.ts // @symlink: /src/library-b/node_modules/library-a/index.ts -export class MyClass{} +export class MyClass { private x: number; } // @filename: /src/library-b/index.ts import {MyClass} from "library-a"; @@ -17,4 +19,23 @@ import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; -y = x; \ No newline at end of file +y = x; + +/* +# To reproduce in a real project: + +mkdir src; cd src +mkdir library-a +echo 'export class MyClass { private x: number; }' > library-a/index.ts + +mkdir library-b; cd library-b +echo 'import {MyClass} from "library-a"; export { MyClass as MyClass2 }' > index.ts +mkdir node_modules; cd node_modules + +ln -s ../../library-a library-a # Linux +# Windows: open command prompt as administrator and run: mklink /D library-a ..\..\library-a + +cd ../.. # back to src +echo 'import { MyClass } from "./library-a"; import { MyClass2 } from "./library-b"; let x: MyClass; let y: MyClass2; x = y; y = x;' > app.ts +tsc app.ts # Should write to library-a/index.js, library-b/index.js, and app.js +*/ diff --git a/tests/cases/compiler/moduleResolutionWithSymlinks_notInNodeModules.ts b/tests/cases/compiler/moduleResolutionWithSymlinks_notInNodeModules.ts new file mode 100644 index 00000000000..427fd4d7697 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithSymlinks_notInNodeModules.ts @@ -0,0 +1,38 @@ +// When symlinked files are not in node_modules, realpath is not used. +// A symlink file acts like the real thing. So, 2 symlinks act like 2 different files. +// See GH#10364. +// @noImplicitReferences: true +// @traceResolution: true +// @fullEmitPaths: true + +// @filename: /shared/abc.ts +// @symlink: /src/shared/abc.ts,/src/shared2/abc.ts +export const x = 0; + +// @filename: /src/app.ts +import { x } from "./shared/abc"; +import { x as x2 } from "./shared2/abc"; +x + x2; + +// @filename: /src/tsconfig.json +{ + "compilerOptions": { + "outDir": "bin" + } +} + +/* +# To reproduce in a real project: + +mkdir shared +echo 'export const x = 0;' > shared/abc.ts + +mkdir src; cd src +echo 'import { x } from "./shared/abc"; import { x as x2 } from "./shared2/abc"; x + x2;' > app.ts + +ln -s ../shared ./shared; ln -s ../shared ./shared2 # Linux +# Windows: Open command prompt as administrator and run: `mklink /D shared ..\shared; mklink /D shared2 ..\shared` + +echo '{ "compilerOptions": { "outDir": "bin" } }' > tsconfig.json +tsc # Should create `bin/app.js`, `bin/shared/abc.js`, and `bin/shared2/abc.js` +*/ diff --git a/tests/cases/compiler/moduleResolutionWithSymlinks_referenceTypes.ts b/tests/cases/compiler/moduleResolutionWithSymlinks_referenceTypes.ts new file mode 100644 index 00000000000..c0e25784c15 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithSymlinks_referenceTypes.ts @@ -0,0 +1,54 @@ +// Symlinks are always resolved for type reference directives. +// NOTE: This test would still compile without errors even if they were not, +// because `processTypeReferenceDirective` also checks for textual equivalence of file contents. +// But the `moduleResolutionWithSymlinks_referenceTypes.trace.json` shows the difference. + +// @noImplicitReferences: true +// @traceResolution: true +// @fullEmitPaths: true + +// @filename: /node_modules/@types/library-a/index.d.ts +// @symlink: /node_modules/@types/library-b/node_modules/@types/library-a/index.d.ts +declare class MyClass { private x: number; } + +// @filename: /node_modules/@types/library-b/index.d.ts +/// + +// @filename: /app.ts +/// +/// + +// @filename: tsconfig.json +{ + "compilerOptions": { + // If this is its default of node_modules/@types, + // node_modules/@types/library-a will be looked up be fore node_modules/@types/library-b/node_modules/@types/library-a + "typeRoots": [] + } +} + +/* +# To reproduce in a real project: + +echo '/// ' > app.ts +echo '/// ' >> app.ts + +mkdir node_modules/@types +cd mode_modules/@types +mkdir library-a +echo 'declare class MyClass { private x: number; }' > library-a/index.d.ts + +mkdir library-b +cd library-b +echo '/// ' > index.d.ts + +mkdir node_modules +cd node_modules + +ln -s ../../library-a ./library-a +# Windows: Open command prompt as administrator and run: `mklink /D library-a ..\..\library-a` + +cd ../../.. # back to root + +tsc app.ts # Should create `app.js` +*/ diff --git a/tests/cases/compiler/moduleResolutionWithSymlinks_withOutDir.ts b/tests/cases/compiler/moduleResolutionWithSymlinks_withOutDir.ts new file mode 100644 index 00000000000..c17e9091de4 --- /dev/null +++ b/tests/cases/compiler/moduleResolutionWithSymlinks_withOutDir.ts @@ -0,0 +1,22 @@ +// Same as moduleResolutionWithSymlinks.ts, but with outDir +// @noImplicitReferences: true +// @traceResolution: true +// @fullEmitPaths: true +// @outDir: /src/bin + +// @filename: /src/library-a/index.ts +// @symlink: /src/library-b/node_modules/library-a/index.ts +export class MyClass { private x: number; } + +// @filename: /src/library-b/index.ts +import {MyClass} from "library-a"; +export { MyClass as MyClass2 } + +// @filename: /src/app.ts +import { MyClass } from "./library-a"; +import { MyClass2 } from "./library-b"; + +let x: MyClass; +let y: MyClass2; +x = y; +y = x; diff --git a/tests/cases/compiler/narrowedConstInMethod.ts b/tests/cases/compiler/narrowedConstInMethod.ts new file mode 100644 index 00000000000..3ddf97a8df3 --- /dev/null +++ b/tests/cases/compiler/narrowedConstInMethod.ts @@ -0,0 +1,19 @@ +// @strictNullChecks: true + +function f() { + const x: string | null = {}; + if (x !== null) { + return { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +function f2() { + const x: string | null = {}; + if (x !== null) { + return class { + bar() { return x.length; } // Error: possibly null x + }; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/nestedFreshLiteral.ts b/tests/cases/compiler/nestedFreshLiteral.ts new file mode 100644 index 00000000000..bf3bf5df8d3 --- /dev/null +++ b/tests/cases/compiler/nestedFreshLiteral.ts @@ -0,0 +1,14 @@ +// @strictNullChecks: true +interface CSSProps { + color?: string +} +interface NestedCSSProps { + nested?: NestedSelector +} +interface NestedSelector { + prop: CSSProps; +} + +let stylen: NestedCSSProps = { + nested: { prop: { colour: 'red' } } +} \ No newline at end of file diff --git a/tests/cases/compiler/nestedLoops.ts b/tests/cases/compiler/nestedLoops.ts new file mode 100644 index 00000000000..c480b4b1c68 --- /dev/null +++ b/tests/cases/compiler/nestedLoops.ts @@ -0,0 +1,18 @@ +// @target: es5 +export class Test { + constructor() { + + let outerArray: Array = [1, 2, 3]; + let innerArray: Array = [1, 2, 3]; + + for (let outer of outerArray) + for (let inner of innerArray) { + this.aFunction((newValue, oldValue) => { + let x = outer + inner + newValue; + }); + } + } + + public aFunction(func: (newValue: any, oldValue: any) => void): void { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/newLexicalEnvironmentForConvertedLoop.ts b/tests/cases/compiler/newLexicalEnvironmentForConvertedLoop.ts new file mode 100644 index 00000000000..25b351d62a1 --- /dev/null +++ b/tests/cases/compiler/newLexicalEnvironmentForConvertedLoop.ts @@ -0,0 +1,13 @@ +// @target: es5 +function baz(x: any) { + return [[x, x]]; +} + +function foo(set: any) { + for (const [value, i] of baz(set.values)) { + const bar: any = []; + (() => bar); + + set.values.push(...[]); + } +}; \ No newline at end of file diff --git a/tests/cases/compiler/nounusedTypeParameterConstraint.ts b/tests/cases/compiler/nounusedTypeParameterConstraint.ts new file mode 100644 index 00000000000..d2c3a1677ee --- /dev/null +++ b/tests/cases/compiler/nounusedTypeParameterConstraint.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true + +//@filename: bar.ts +export interface IEventSourcedEntity { } + +//@filename: test.ts +import { IEventSourcedEntity } from "./bar"; +export type DomainEntityConstructor = { new(): TEntity; }; \ No newline at end of file diff --git a/tests/cases/compiler/objectFreeze.ts b/tests/cases/compiler/objectFreeze.ts new file mode 100644 index 00000000000..5e8539831b1 --- /dev/null +++ b/tests/cases/compiler/objectFreeze.ts @@ -0,0 +1,12 @@ +const f = Object.freeze(function foo(a: number, b: string) { return false; }); +f(1, "") === false; + +class C { constructor(a: number) { } } +const c = Object.freeze(C); +new c(1); + +const a = Object.freeze([1, 2, 3]); +a[0] = a[2].toString(); + +const o = Object.freeze({ a: 1, b: "string" }); +o.b = o.a.toString(); diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension.ts new file mode 100644 index 00000000000..e40c67e4ea3 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension.ts @@ -0,0 +1,26 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @Filename: /foo/foo.ts +export function foo() {} + +// @Filename: /bar/bar.js +export function bar() {} + +// @Filename: /a.ts +import { foo } from "foo"; +import { bar } from "bar"; + +// @Filename: /tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "foo": ["foo/foo.ts"], + "bar": ["bar/bar.js"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension_failedLookup.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension_failedLookup.ts new file mode 100644 index 00000000000..a983b6c4825 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_withExtension_failedLookup.ts @@ -0,0 +1,15 @@ +// @noImplicitReferences: true +// @traceResolution: true + +// @Filename: /a.ts +import { foo } from "foo"; + +// @Filename: /tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "foo": ["foo/foo.ts"] + } + } +} diff --git a/tests/cases/compiler/redeclareParameterInCatchBlock.ts b/tests/cases/compiler/redeclareParameterInCatchBlock.ts index 37ca5fc3a9e..7f98d68b29d 100644 --- a/tests/cases/compiler/redeclareParameterInCatchBlock.ts +++ b/tests/cases/compiler/redeclareParameterInCatchBlock.ts @@ -14,9 +14,20 @@ try { try { +} catch ([a, b]) { + const [c, b] = [0, 1]; +} + +try { + +} catch ({ a: x, b: x }) { + +} + +try { + } catch(e) { function test() { let e; } } - diff --git a/tests/cases/compiler/relationalOperatorComparable.ts b/tests/cases/compiler/relationalOperatorComparable.ts new file mode 100644 index 00000000000..e95bb6e71cc --- /dev/null +++ b/tests/cases/compiler/relationalOperatorComparable.ts @@ -0,0 +1,15 @@ +function f(onethree: 1 | 3, two: 2) { + const t = true; + const f = false; + let a1 = onethree < two; // ok + let a2 = onethree < true; // error, number and boolean + let a3 = onethree <= false; // error, number and boolean + let a4 = onethree >= t; // error, number and boolean + let a5 = onethree > f; // error, number and boolean + let a6 = true < onethree; // error, boolean and number + let a7 = false < two; // error, boolean and number + let a8 = 'foo' < onethree; // error, string and number + let a9 = onethree < 1; // ok + let a10 = 1 < two; // ok + let a11 = 2 < 1; // ok +} diff --git a/tests/cases/compiler/requireAsFunctionInExternalModule.ts b/tests/cases/compiler/requireAsFunctionInExternalModule.ts new file mode 100644 index 00000000000..1715090c329 --- /dev/null +++ b/tests/cases/compiler/requireAsFunctionInExternalModule.ts @@ -0,0 +1,16 @@ +// @allowjs: true +// @outDir: dist +// @Filename: c.js +export default function require(a) { } +export function has(a) { return true } + +// @Filename: m.js +import require, { has } from "./c" +export function hello() { } +if (has('ember-debug')) { + require('ember-debug'); +} + +// @Filename: m2.ts +import { hello } from "./m"; +hello(); diff --git a/tests/cases/compiler/restIntersection.ts b/tests/cases/compiler/restIntersection.ts new file mode 100644 index 00000000000..5fca2dafc36 --- /dev/null +++ b/tests/cases/compiler/restIntersection.ts @@ -0,0 +1,4 @@ +var intersection: { x: number, y: number } & { w: string, z: string }; + +var rest1: { y: number, w: string, z: string }; +var {x, ...rest1 } = intersection; diff --git a/tests/cases/compiler/restInvalidArgumentType.ts b/tests/cases/compiler/restInvalidArgumentType.ts new file mode 100644 index 00000000000..488f546e231 --- /dev/null +++ b/tests/cases/compiler/restInvalidArgumentType.ts @@ -0,0 +1,59 @@ +enum E { v1, v2 }; + +function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var {...r1} = p1; // Error, generic type paramterre + var {...r2} = p2; // OK + var {...r3} = t; // Error, generic type paramter + + var {...r4} = i; // Error, index access + var {...r5} = k; // Error, index + + var {...r6} = mapped_generic; // Error, generic mapped object type + var {...r7} = mapped; // OK, non-generic mapped type + + var {...r8} = union_generic; // Error, union with generic type parameter + var {...r9} = union_primitive; // Error, union with generic type parameter + + var {...r10} = intersection_generic; // Error, intersection with generic type parameter + var {...r11} = intersection_premitive; // Error, intersection with generic type parameter + + var {...r12} = num; // Error + var {...r13} = str; // Error + + var {...r14} = u; // OK + var {...r15} = n; // OK + + var {...r16} = a; // OK + + var {...r17} = literal_string; // Error + var {...r18} = literal_number; // Error + + var {...r19} = e; // Error, enum +} \ No newline at end of file diff --git a/tests/cases/compiler/restUnion.ts b/tests/cases/compiler/restUnion.ts new file mode 100644 index 00000000000..c838b37340f --- /dev/null +++ b/tests/cases/compiler/restUnion.ts @@ -0,0 +1,14 @@ +var union: { a: number, c: boolean } | { a: string, b: string }; + +var rest1: { c: boolean } | { b: string }; +var {a, ...rest1 } = union; + + +var undefinedUnion: { n: number } | undefined; +var rest2: {}; +var {n, ...rest2 } = undefinedUnion; + + +var nullUnion: { n: number } | null; +var rest3: {}; +var {n, ...rest3 } = nullUnion; diff --git a/tests/cases/compiler/restUnion2.ts b/tests/cases/compiler/restUnion2.ts new file mode 100644 index 00000000000..83d94e03a73 --- /dev/null +++ b/tests/cases/compiler/restUnion2.ts @@ -0,0 +1,19 @@ +// @strictNullChecks: true + +declare const undefinedUnion: { n: number } | undefined; +var rest2: { n: number }; +var {...rest2 } = undefinedUnion; + + +declare const nullUnion: { n: number } | null; +var rest3: { n: number }; +var {...rest3 } = nullUnion; + + +declare const nullAndUndefinedUnion: null | undefined; +var rest4: { }; +var {...rest4 } = nullAndUndefinedUnion; + +declare const unionWithIntersection: ({ n: number } & { s: string }) & undefined | null; +var rest5: { n: number, s: string }; +var {...rest5 } = unionWithIntersection; \ No newline at end of file diff --git a/tests/cases/compiler/selfReferencingSpreadInLoop.ts b/tests/cases/compiler/selfReferencingSpreadInLoop.ts new file mode 100644 index 00000000000..0900e6cad63 --- /dev/null +++ b/tests/cases/compiler/selfReferencingSpreadInLoop.ts @@ -0,0 +1,5 @@ +// @noImplicitAny: true +let additional = []; +for (const subcomponent of [1, 2, 3]) { + additional = [...additional, subcomponent]; +} diff --git a/tests/cases/compiler/spreadIntersection.ts b/tests/cases/compiler/spreadIntersection.ts new file mode 100644 index 00000000000..3b397dc40cc --- /dev/null +++ b/tests/cases/compiler/spreadIntersection.ts @@ -0,0 +1,7 @@ +var intersection: { a: number } & { b: string }; + +var o1: { a: number, b: string }; +var o1 = { ...intersection }; + +var o2: { a: number, b: string, c: boolean }; +var o2 = { ...intersection, c: false }; \ No newline at end of file diff --git a/tests/cases/compiler/spreadInvalidArgumentType.ts b/tests/cases/compiler/spreadInvalidArgumentType.ts new file mode 100644 index 00000000000..2ac6aa921f4 --- /dev/null +++ b/tests/cases/compiler/spreadInvalidArgumentType.ts @@ -0,0 +1,59 @@ +enum E { v1, v2 }; + +function f(p1: T, p2: T[]) { + var t: T; + + var i: T["b"]; + var k: keyof T; + + var mapped_generic: {[P in keyof T]: T[P]}; + var mapped: {[P in "b"]: T[P]}; + + var union_generic: T | { a: number }; + var union_primitive: { a: number } | number; + + var intersection_generic: T & { a: number }; + var intersection_premitive: { a: number } | string; + + var num: number; + var str: number; + + var u: undefined; + var n: null; + + var a: any; + + var literal_string: "string"; + var literal_number: 42; + + var e: E; + + var o1 = { ...p1 }; // Error, generic type paramterre + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // Error, generic type paramter + + var o4 = { ...i }; // Error, index access + var o5 = { ...k }; // Error, index + + var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o7 = { ...mapped }; // OK, non-generic mapped type + + var o8 = { ...union_generic }; // Error, union with generic type parameter + var o9 = { ...union_primitive }; // Error, union with generic type parameter + + var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o11 = { ...intersection_premitive }; // Error, intersection with generic type parameter + + var o12 = { ...num }; // Error + var o13 = { ...str }; // Error + + var o14 = { ...u }; // OK + var o15 = { ...n }; // OK + + var o16 = { ...a }; // OK + + var o17 = { ...literal_string }; // Error + var o18 = { ...literal_number }; // Error + + var o19 = { ...e }; // Error, enum +} \ No newline at end of file diff --git a/tests/cases/compiler/spreadUnion.ts b/tests/cases/compiler/spreadUnion.ts new file mode 100644 index 00000000000..ef8440122ed --- /dev/null +++ b/tests/cases/compiler/spreadUnion.ts @@ -0,0 +1,10 @@ +var union: { a: number } | { b: string }; + +var o3: { a: number } | { b: string }; +var o3 = { ...union }; + +var o4: { a: boolean } | { b: string , a: boolean}; +var o4 = { ...union, a: false }; + +var o5: { a: number } | { b: string } | { a: number, b: string }; +var o5 = { ...union, ...union }; \ No newline at end of file diff --git a/tests/cases/compiler/spreadUnion2.ts b/tests/cases/compiler/spreadUnion2.ts new file mode 100644 index 00000000000..25dba81c0df --- /dev/null +++ b/tests/cases/compiler/spreadUnion2.ts @@ -0,0 +1,25 @@ +// @strictNullChecks: true + +declare const undefinedUnion: { a: number } | undefined; +declare const nullUnion: { b: number } | null; +declare const nullAndUndefinedUnion: null | undefined; + +var o1: { a: number }; +var o1 = { ...undefinedUnion }; + +var o2: { b: number }; +var o2 = { ...nullUnion }; + +var o3: { a: number, b: number }; +var o3 = { ...undefinedUnion, ...nullUnion }; +var o3 = { ...nullUnion, ...undefinedUnion }; + +var o4: { a: number }; +var o4 = { ...undefinedUnion, ...undefinedUnion }; + +var o5: { b: number }; +var o5 = { ...nullUnion, ...nullUnion }; + +var o6: { }; +var o6 = { ...nullAndUndefinedUnion, ...nullAndUndefinedUnion }; +var o6 = { ...nullAndUndefinedUnion }; \ No newline at end of file diff --git a/tests/cases/compiler/subSubClassCanAccessProtectedConstructor.ts b/tests/cases/compiler/subSubClassCanAccessProtectedConstructor.ts new file mode 100644 index 00000000000..fc5e9794500 --- /dev/null +++ b/tests/cases/compiler/subSubClassCanAccessProtectedConstructor.ts @@ -0,0 +1,15 @@ +class Base { + protected constructor() { } + public instance1 = new Base(); // allowed +} + +class Subclass extends Base { + public instance1_1 = new Base(); // allowed + public instance1_2 = new Subclass(); // allowed +} + +class SubclassOfSubclass extends Subclass { + public instance2_1 = new Base(); // allowed + public instance2_2 = new Subclass(); // allowed + public instance2_3 = new SubclassOfSubclass(); // allowed +} diff --git a/tests/cases/compiler/superCallWithCommentEmit01.ts b/tests/cases/compiler/superCallWithCommentEmit01.ts new file mode 100644 index 00000000000..800fad29bfb --- /dev/null +++ b/tests/cases/compiler/superCallWithCommentEmit01.ts @@ -0,0 +1,10 @@ +class A { + constructor(public text: string) { } +} + +class B extends A { + constructor(text: string) { + // this is subclass constructor + super(text) + } +} \ No newline at end of file diff --git a/tests/cases/compiler/superPropertyAccessInSuperCall01.ts b/tests/cases/compiler/superPropertyAccessInSuperCall01.ts new file mode 100644 index 00000000000..38373e9eef6 --- /dev/null +++ b/tests/cases/compiler/superPropertyAccessInSuperCall01.ts @@ -0,0 +1,11 @@ +class A { + constructor(f: string) { + } + public blah(): string { return ""; } +} + +class B extends A { + constructor() { + super(super.blah()) + } +} \ No newline at end of file diff --git a/tests/cases/compiler/switchCasesExpressionTypeMismatch.ts b/tests/cases/compiler/switchCasesExpressionTypeMismatch.ts index 4de01ebba17..ee547705b84 100644 --- a/tests/cases/compiler/switchCasesExpressionTypeMismatch.ts +++ b/tests/cases/compiler/switchCasesExpressionTypeMismatch.ts @@ -3,7 +3,7 @@ class Foo { } switch (0) { case Foo: break; // Error case "sss": break; // Error - case 123: break; // No Error + case 123: break; // Error case true: break; // Error } @@ -15,4 +15,4 @@ switch (s) { case "sss": break; case 123: break; case true: break; -} \ No newline at end of file +} diff --git a/tests/cases/compiler/switchComparableCompatForBrands.ts b/tests/cases/compiler/switchComparableCompatForBrands.ts new file mode 100644 index 00000000000..4b90db40e1d --- /dev/null +++ b/tests/cases/compiler/switchComparableCompatForBrands.ts @@ -0,0 +1,13 @@ +class MyBrand +{ + private _a: number; +} + +function test(strInput: string & MyBrand) { + switch(strInput) + { + case "a": + return 1; + } + return 0; +} diff --git a/tests/cases/compiler/systemModuleTrailingComments.ts b/tests/cases/compiler/systemModuleTrailingComments.ts new file mode 100644 index 00000000000..32c29617832 --- /dev/null +++ b/tests/cases/compiler/systemModuleTrailingComments.ts @@ -0,0 +1,4 @@ +// @module: system +export const test = "TEST"; + +//some comment \ No newline at end of file diff --git a/tests/cases/compiler/transformsElideNullUndefinedType.ts b/tests/cases/compiler/transformsElideNullUndefinedType.ts new file mode 100644 index 00000000000..4a493a91d88 --- /dev/null +++ b/tests/cases/compiler/transformsElideNullUndefinedType.ts @@ -0,0 +1,60 @@ +// @target: es6 + +var v0: null; +var v1: undefined; + +function f0(): null { return null; } +function f1(): undefined { return undefined; } + +var f2 = function (): null { return null; } +var f3 = function (): undefined { return undefined; } + +var f4 = (): null => null; +var f5 = (): undefined => undefined; + +function f6(p0: null) { } +function f7(p1: undefined) { } + +var f8 = function (p2: null) { } +var f9 = function (p3: undefined) { } + +var f10 = (p4: null) => { } +var f11 = (p5: undefined) => { } + +class C1 { + m0(): null { return null; } + m1(): undefined { return undefined; } + + m3(p6: null) { } + m4(p7: undefined) { } + + get a0(): null { return null; } + get a1(): undefined { return undefined; } + + set a2(p8: null) { } + set a3(p9: undefined) { } +} + +class C2 { constructor(p10: null) { } } +class C3 { constructor(p11: undefined) { } } + +class C4 { + f1; + constructor(p12: null) { } +} + +class C5 { + f2; + constructor(p13: undefined) { } +} + +var C6 = class { constructor(p12: null) { } } +var C7 = class { constructor(p13: undefined) { } } + +declare function fn(); +fn(); +fn(); + +declare class D {} +new D(); +new D(); \ No newline at end of file diff --git a/tests/cases/compiler/typePredicateInLoop.ts b/tests/cases/compiler/typePredicateInLoop.ts new file mode 100644 index 00000000000..4127e1e3d43 --- /dev/null +++ b/tests/cases/compiler/typePredicateInLoop.ts @@ -0,0 +1,21 @@ +// Repro from #12101 + +interface Type { + type: number; +} + +interface TypeExt extends Type { + arr: Type[]; +} + +const guard = (arg: Type): arg is TypeExt => arg.type === 1; +const otherFunc = (arg1: Type, arg2: TypeExt): void => {}; + +export function y(arg: Type): void { + if (guard(arg)) { + for (const ITEM of arg.arr) { + if (otherFunc(ITEM, arg)) { + } + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/typePredicateStructuralMatch.ts b/tests/cases/compiler/typePredicateStructuralMatch.ts new file mode 100644 index 00000000000..690e5f62b27 --- /dev/null +++ b/tests/cases/compiler/typePredicateStructuralMatch.ts @@ -0,0 +1,26 @@ +// Repro from #12235 + +getResults1([]); +getResults1({data: []}); + +getResults2([]); +getResults2({data: []}); + +type Result = { value: string }; +type Results = Result[]; + +function isResponseInData(value: T | { data: T}): value is { data: T } { + return value.hasOwnProperty('data'); +} + +function getResults1(value: Results | { data: Results }): Results { + return isResponseInData(value) ? value.data : value; +} + +function isPlainResponse(value: T | { data: T}): value is T { + return !value.hasOwnProperty('data'); +} + +function getResults2(value: Results | { data: Results }): Results { + return isPlainResponse(value) ? value : value.data; +} \ No newline at end of file diff --git a/tests/cases/compiler/unionTypeWithLeadingOperator.ts b/tests/cases/compiler/unionTypeWithLeadingOperator.ts new file mode 100644 index 00000000000..9f6d272ce7c --- /dev/null +++ b/tests/cases/compiler/unionTypeWithLeadingOperator.ts @@ -0,0 +1,6 @@ +type A = | string; +type B = + | { type: "INCREMENT" } + | { type: "DECREMENT" }; + +type C = [| 0 | 1, | "foo" | "bar"]; diff --git a/tests/cases/compiler/untypedModuleImport_withAugmentation2.ts b/tests/cases/compiler/untypedModuleImport_withAugmentation2.ts new file mode 100644 index 00000000000..8cbf75b662b --- /dev/null +++ b/tests/cases/compiler/untypedModuleImport_withAugmentation2.ts @@ -0,0 +1,14 @@ +// @noImplicitReferences: true +// This tests that augmenting an untyped module is forbidden even in an ambient context. Contrast with `moduleAugmentationInDependency.ts`. + +// @Filename: /node_modules/augmenter/index.d.ts +declare module "js" { + export const j: number; +} +export {}; + +// @Filename: /node_modules/js/index.js +This file is not processed. + +// @Filename: /a.ts +import { } from "augmenter"; diff --git a/tests/cases/compiler/unusedDestructuringParameters.ts b/tests/cases/compiler/unusedDestructuringParameters.ts new file mode 100644 index 00000000000..7c042351049 --- /dev/null +++ b/tests/cases/compiler/unusedDestructuringParameters.ts @@ -0,0 +1,7 @@ +//@noUnusedParameters: true +const f = ([a]) => { }; +f([1]); +const f2 = ({a}) => { }; +f2({ a: 10 }); +const f3 = ([_]) => { }; +f3([10]); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports13.ts b/tests/cases/compiler/unusedImports13.ts new file mode 100644 index 00000000000..af188e70eae --- /dev/null +++ b/tests/cases/compiler/unusedImports13.ts @@ -0,0 +1,22 @@ +//@noUnusedLocals:true +//@module: commonjs +//@jsx: preserve + +// @filename: foo.tsx +import React = require("react"); + +export const FooComponent =

+ +// @filename: node_modules/@types/react/index.d.ts +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + diff --git a/tests/cases/compiler/unusedImports14.ts b/tests/cases/compiler/unusedImports14.ts new file mode 100644 index 00000000000..1823d4bb49b --- /dev/null +++ b/tests/cases/compiler/unusedImports14.ts @@ -0,0 +1,22 @@ +//@noUnusedLocals:true +//@module: commonjs +//@jsx: react + +// @filename: foo.tsx +import React = require("react"); + +export const FooComponent =
+ +// @filename: node_modules/@types/react/index.d.ts +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + diff --git a/tests/cases/compiler/unusedImports15.ts b/tests/cases/compiler/unusedImports15.ts new file mode 100644 index 00000000000..ef6b277d21d --- /dev/null +++ b/tests/cases/compiler/unusedImports15.ts @@ -0,0 +1,23 @@ +//@noUnusedLocals:true +//@module: commonjs +//@reactNamespace: Element +//@jsx: preserve + +// @filename: foo.tsx +import Element = require("react"); + +export const FooComponent =
+ +// @filename: node_modules/@types/react/index.d.ts +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + diff --git a/tests/cases/compiler/unusedImports16.ts b/tests/cases/compiler/unusedImports16.ts new file mode 100644 index 00000000000..ff0c38bb75e --- /dev/null +++ b/tests/cases/compiler/unusedImports16.ts @@ -0,0 +1,23 @@ +//@noUnusedLocals:true +//@module: commonjs +//@reactNamespace: Element +//@jsx: react + +// @filename: foo.tsx +import Element = require("react"); + +export const FooComponent =
+ +// @filename: node_modules/@types/react/index.d.ts +export = React; +export as namespace React; + +declare namespace React { + function createClass(spec); +} +declare global { + namespace JSX { + } +} + + diff --git a/tests/cases/compiler/unusedLocalProperty.ts b/tests/cases/compiler/unusedLocalProperty.ts new file mode 100644 index 00000000000..fdd33116135 --- /dev/null +++ b/tests/cases/compiler/unusedLocalProperty.ts @@ -0,0 +1,12 @@ +//@noUnusedLocals:true +declare var console: { log(msg: any): void; } +class Animal { + constructor(private species: string) { + } + + printSpecies() { + let { species } = this; + console.log(species); + } +} + diff --git a/tests/cases/compiler/unusedLocalsAndObjectSpread.ts b/tests/cases/compiler/unusedLocalsAndObjectSpread.ts new file mode 100644 index 00000000000..b042b412c8e --- /dev/null +++ b/tests/cases/compiler/unusedLocalsAndObjectSpread.ts @@ -0,0 +1,31 @@ +//@noUnusedLocals:true + +declare var console: { log(a: any): void }; + +function one() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; + console.log(bar); +} + +function two() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; + console.log(bar); +} + +function three() { + const foo = { a: 1, b: 2 }; + // 'a' is declared but never used + const {a, ...bar} = foo; // bar should be unused + //console.log(bar); +} + +function four() { + const foo = { a: 1, b: 2 }; + // '_' is declared but never used + const {a: _, ...bar} = foo; // bar should be unused + //console.log(bar); +} diff --git a/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts b/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts new file mode 100644 index 00000000000..e55c2042a41 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsAndObjectSpread2.ts @@ -0,0 +1,18 @@ +//@noUnusedLocals:true + +declare let props: any; +const { + children, // here! + active: _a, // here! + ...rest, +} = props; + +function foo() { + const { + children, + active: _a, + ...rest, + } = props; +} + +export const asdf = 123; \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsStartingWithUnderscore.ts b/tests/cases/compiler/unusedLocalsStartingWithUnderscore.ts new file mode 100644 index 00000000000..4e6930a6282 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsStartingWithUnderscore.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true + +for (const _ of []) { } + +for (const _ in []) { } + +namespace M { + let _; + for (const _ of []) { } + + for (const _ in []) { } +} + \ No newline at end of file diff --git a/tests/cases/compiler/useBeforeDeclaration.ts b/tests/cases/compiler/useBeforeDeclaration.ts new file mode 100644 index 00000000000..6dc3b026d13 --- /dev/null +++ b/tests/cases/compiler/useBeforeDeclaration.ts @@ -0,0 +1,20 @@ +// @outFile: test.js + +// @fileName: A.ts +namespace ts { + export function printVersion():void { + log("Version: " + sys.version); // the call of sys.version is deferred, should not report an error. + } + + export function log(info:string):void { + + } +} + +// @fileName: B.ts +namespace ts { + + export let sys:{version:string} = {version: "2.0.5"}; + +} + diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts new file mode 100644 index 00000000000..1ade02c09d2 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts @@ -0,0 +1,4 @@ +// @target: ES5 +// @noEmitHelpers: true + +const x = async => async; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts new file mode 100644 index 00000000000..09d97cc253b --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts new file mode 100644 index 00000000000..0f9ec479a31 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { +}; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts new file mode 100644 index 00000000000..b11441372ff --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var f = (await) => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts new file mode 100644 index 00000000000..9b5924fc145 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await = await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts new file mode 100644 index 00000000000..5a988277836 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var await = () => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts new file mode 100644 index 00000000000..aabe5a99372 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts new file mode 100644 index 00000000000..d82ce864421 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (a = await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts new file mode 100644 index 00000000000..bc49c5995e6 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true + +var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts new file mode 100644 index 00000000000..387b09c791a --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { + var v = { [await]: foo } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts new file mode 100644 index 00000000000..93254fee5c7 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var foo = async (a = await => await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts new file mode 100644 index 00000000000..c71c6ddecb0 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + method() { + function other() {} + var fn = async () => await other.apply(this, arguments); + } +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts new file mode 100644 index 00000000000..3f398d9be82 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + method() { + var fn = async () => await this; + } +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts new file mode 100644 index 00000000000..9b63b7bd468 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true + +declare function someOtherFunction(i: any): Promise; +const x = async i => await someOtherFunction(i) +const x1 = async (i) => await someOtherFunction(i); \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts b/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts new file mode 100644 index 00000000000..c0ab4838f70 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts @@ -0,0 +1,41 @@ +// @target: es2017 +// @isolatedModules: true +import { MyPromise } from "missing"; + +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts b/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts new file mode 100644 index 00000000000..a255cb7cb71 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts @@ -0,0 +1,40 @@ +// @target: es2017 +type MyPromise = Promise; +declare var MyPromise: typeof Promise; +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts new file mode 100644 index 00000000000..b9005c48596 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts @@ -0,0 +1,52 @@ +// @target: es2017 +// @noEmitHelpers: true +class A { + x() { + } +} + +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => {}; + + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + + // property access (assign) + super.x = f; + + // element access (assign) + super["x"] = f; + + // destructuring assign with property access + ({ f: super.x } = { f }); + + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts b/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts new file mode 100644 index 00000000000..c4d4cafef8a --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +async function func(): Promise { + "use strict"; + var b = await p || a; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts new file mode 100644 index 00000000000..ef9076a8bee --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p || a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts new file mode 100644 index 00000000000..84d2f622292 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p && a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts new file mode 100644 index 00000000000..1f3a8245d42 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: number; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p + a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts new file mode 100644 index 00000000000..6c36f1e4ce5 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts new file mode 100644 index 00000000000..abbcbb95ba9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts @@ -0,0 +1,12 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var o: { a: boolean; }; + o.a = await p; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts new file mode 100644 index 00000000000..da46e04ed1e --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts new file mode 100644 index 00000000000..baf75ab95c3 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(await p, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts new file mode 100644 index 00000000000..17cf6d8c6c9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts new file mode 100644 index 00000000000..ef5e1d203d9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await pfn)(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts new file mode 100644 index 00000000000..8494bc11b4c --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts new file mode 100644 index 00000000000..7939572baea --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(await p, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts new file mode 100644 index 00000000000..3f1231a50d6 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts new file mode 100644 index 00000000000..c669122bada --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await po).fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts b/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts new file mode 100644 index 00000000000..fe34d53a03c --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts @@ -0,0 +1,9 @@ +// @target: es2017 +// @noEmitHelpers: true +declare class C { } +declare var p: Promise; + +async function func(): Promise { + class D extends (await p) { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitInheritedPromise_es2017.ts b/tests/cases/conformance/async/es2017/awaitInheritedPromise_es2017.ts new file mode 100644 index 00000000000..c5cd486e0f0 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitInheritedPromise_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @strictNullChecks: true +interface A extends Promise {} +declare var a: A; +async function f() { + await a; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts new file mode 100644 index 00000000000..dee2554653d --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts @@ -0,0 +1,17 @@ +// @target: es2017 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts new file mode 100644 index 00000000000..f38260b332d --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts @@ -0,0 +1,21 @@ +// @target: es2017 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts new file mode 100644 index 00000000000..b48c661f0b9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts @@ -0,0 +1,13 @@ +// @target: es2017 + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts new file mode 100644 index 00000000000..d2c608d0e7b --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts @@ -0,0 +1,19 @@ +// @target: es2017 + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts new file mode 100644 index 00000000000..9b744713945 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(a = await => await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts new file mode 100644 index 00000000000..9613e866163 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function await(): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts new file mode 100644 index 00000000000..02b6e833c2c --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts @@ -0,0 +1,3 @@ +// @target: es2017 +// @noEmitHelpers: true +var v = async function await(): Promise { } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts new file mode 100644 index 00000000000..40177c1fbcb --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; +} diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts new file mode 100644 index 00000000000..06bd2de3eef --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + return; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts new file mode 100644 index 00000000000..178611ad91b --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts new file mode 100644 index 00000000000..08711a4cfbd --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts new file mode 100644 index 00000000000..9b5924fc145 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await = await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts new file mode 100644 index 00000000000..84c6c93b90f --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function await() { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts new file mode 100644 index 00000000000..c57fb73d6d7 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts new file mode 100644 index 00000000000..1ceb160c12b --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(a = await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts new file mode 100644 index 00000000000..e5c2649d34e --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true +async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts new file mode 100644 index 00000000000..64e62a2719e --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts @@ -0,0 +1,3 @@ +// @target: es2017 +// @noEmitHelpers: true +var v = { [await]: foo } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts new file mode 100644 index 00000000000..7d3b7213b99 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + var v = { [await]: foo } +} \ No newline at end of file diff --git a/tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts b/tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts new file mode 100644 index 00000000000..2c59b6f93cc --- /dev/null +++ b/tests/cases/conformance/classes/classDeclarations/classAbstractKeyword/classAbstractAccessor.ts @@ -0,0 +1,8 @@ +// @target: es5 + +abstract class A { + abstract get a(); + abstract get aa() { return 1; } // error + abstract set b(x: string); + abstract set bb(x: string) {} // error +} diff --git a/tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts b/tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts new file mode 100644 index 00000000000..9d5d4c8c895 --- /dev/null +++ b/tests/cases/conformance/classes/constructorDeclarations/superCalls/superPropertyInConstructorBeforeSuperCall.ts @@ -0,0 +1,15 @@ +class B { + constructor(x?: string) {} + x(): string { return ""; } +} +class C1 extends B { + constructor() { + super.x(); + super(); + } +} +class C2 extends B { + constructor() { + super(super.x()); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts b/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts new file mode 100644 index 00000000000..b20a5a85dfb --- /dev/null +++ b/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor7.ts @@ -0,0 +1,34 @@ +// @target:es5 +// @experimentaldecorators: true +declare function dec1(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; +declare function dec2(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + +class A { + @dec1 get x() { return 0; } + set x(value: number) { } +} + +class B { + get x() { return 0; } + @dec2 set x(value: number) { } +} + +class C { + @dec1 set x(value: number) { } + get x() { return 0; } +} + +class D { + set x(value: number) { } + @dec2 get x() { return 0; } +} + +class E { + @dec1 get x() { return 0; } + @dec2 set x(value: number) { } +} + +class F { + @dec1 set x(value: number) { } + @dec2 get x() { return 0; } +} \ No newline at end of file diff --git a/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor8.ts b/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor8.ts new file mode 100644 index 00000000000..3caf4b406d2 --- /dev/null +++ b/tests/cases/conformance/decorators/class/accessor/decoratorOnClassAccessor8.ts @@ -0,0 +1,32 @@ +// @target:es5 +// @experimentaldecorators: true +// @emitdecoratormetadata: true +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; + +class A { + @dec get x() { return 0; } + set x(value: number) { } +} + +class B { + get x() { return 0; } + @dec set x(value: number) { } +} + +class C { + @dec set x(value: number) { } + get x() { return 0; } +} + +class D { + set x(value: number) { } + @dec get x() { return 0; } +} + +class E { + @dec get x() { return 0; } +} + +class F { + @dec set x(value: number) { } +} \ No newline at end of file diff --git a/tests/cases/conformance/decorators/class/constructor/decoratorOnClassConstructor4.ts b/tests/cases/conformance/decorators/class/constructor/decoratorOnClassConstructor4.ts new file mode 100644 index 00000000000..55e3a1423fa --- /dev/null +++ b/tests/cases/conformance/decorators/class/constructor/decoratorOnClassConstructor4.ts @@ -0,0 +1,18 @@ +// @target: es5 +// @module: commonjs +// @experimentaldecorators: true +// @emitdecoratormetadata: true +declare var dec: any; + +@dec +class A { +} + +@dec +class B { + constructor(x: number) {} +} + +@dec +class C extends A { +} \ No newline at end of file diff --git a/tests/cases/conformance/es2017/useObjectValuesAndEntries1.ts b/tests/cases/conformance/es2017/useObjectValuesAndEntries1.ts index 145239a84b2..60099bb1c0f 100644 --- a/tests/cases/conformance/es2017/useObjectValuesAndEntries1.ts +++ b/tests/cases/conformance/es2017/useObjectValuesAndEntries1.ts @@ -7,5 +7,7 @@ for (var x of Object.values(o)) { let y = x; } -var entries = Object.entries(o); -var entries1 = Object.entries(1); // <-- entries: [string, any][] \ No newline at end of file +var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] +var entries1 = Object.entries(1); // <-- entries: [string, any][] +var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', number | boolean][] +var entries3 = Object.entries({}) // [never, any][] diff --git a/tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts b/tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts new file mode 100644 index 00000000000..243a297ed43 --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment3.ts @@ -0,0 +1,10 @@ +const [a, b = a] = [1]; // ok +const [c, d = c, e = e] = [1]; // error for e = e +const [f, g = f, h = i, i = f] = [1]; // error for h = i + +(function ([a, b = a]) { // ok +})([1]); +(function ([c, d = c, e = e]) { // error for e = e +})([1]); +(function ([f, g = f, h = i, i = f]) { // error for h = i +})([1]) diff --git a/tests/cases/conformance/es6/destructuring/destructuringCatch.ts b/tests/cases/conformance/es6/destructuring/destructuringCatch.ts new file mode 100644 index 00000000000..31afd672084 --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/destructuringCatch.ts @@ -0,0 +1,29 @@ +// @noImplicitAny: true + +try { + throw [0, 1]; +} +catch ([a, b]) { + a + b; +} + +try { + throw { a: 0, b: 1 }; +} +catch ({a, b}) { + a + b; +} + +try { + throw [{ x: [0], z: 1 }]; +} +catch ([{x: [y], z}]) { + y + z; +} + +// Test of comment ranges. A fix to GH#11755 should update this. +try { +} +catch (/*Test comment ranges*/[/*a*/a]) { + +} diff --git a/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts b/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts index 2b3192bc9a2..1e2bc1e68b4 100644 --- a/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts +++ b/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts @@ -3,8 +3,5 @@ var {h?} = { h?: 1 }; var {i}: string | number = { i: 2 }; var {i1}: string | number| {} = { i1: 2 }; var { f2: {f21} = { f212: "string" } }: any = undefined; -var { ...d1 } = { - a: 1, b: 1, d1: 9, e: 10 -} var {1} = { 1 }; -var {"prop"} = { "prop": 1 }; \ No newline at end of file +var {"prop"} = { "prop": 1 }; diff --git a/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts b/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts new file mode 100644 index 00000000000..d138c14db7a --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment4.ts @@ -0,0 +1,8 @@ +const { + a = 1, + b = 2, + c = b, // ok + d = a, // ok + e = f, // error + f = f // error +} = { } as any; diff --git a/tests/cases/conformance/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithNumericLiteral.ts b/tests/cases/conformance/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithNumericLiteral.ts new file mode 100644 index 00000000000..457a324e971 --- /dev/null +++ b/tests/cases/conformance/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithNumericLiteral.ts @@ -0,0 +1,42 @@ +type BrandedNum = number & { __numberBrand: any }; +var x : BrandedNum; + +// operator > +x > 0; +x > 0; +x > 0; + +// operator < +x < 0; +x < 0; +x < 0; + +// operator >= +x >= 0; +x >= 0; +x >= 0; + +// operator <= +x <= 0; +x <= 0; +x <= 0; + +// operator == +x == 0; +x == 0; +x == 0; + +// operator != +x != 0; +x != 0; +x != 0; + +// operator === +x === 0; +x === 0; +x === 0; + +// operator !== +x !== 0; +x !== 0; +x !== 0; diff --git a/tests/cases/conformance/expressions/functionCalls/callWithSpread.ts b/tests/cases/conformance/expressions/functionCalls/callWithSpread.ts index 245028db3d4..b1e2ee75784 100644 --- a/tests/cases/conformance/expressions/functionCalls/callWithSpread.ts +++ b/tests/cases/conformance/expressions/functionCalls/callWithSpread.ts @@ -1,5 +1,5 @@ interface X { - foo(x: number, y: number, ...z: string[]); + foo(x: number, y: number, ...z: string[]): X; } function foo(x: number, y: number, ...z: string[]) { @@ -18,10 +18,18 @@ obj.foo(1, 2, "abc"); obj.foo(1, 2, ...a); obj.foo(1, 2, ...a, "abc"); +obj.foo(1, 2, ...a).foo(1, 2, "abc"); +obj.foo(1, 2, ...a).foo(1, 2, ...a); +obj.foo(1, 2, ...a).foo(1, 2, ...a, "abc"); + (obj.foo)(1, 2, "abc"); (obj.foo)(1, 2, ...a); (obj.foo)(1, 2, ...a, "abc"); +((obj.foo)(1, 2, ...a).foo)(1, 2, "abc"); +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a); +((obj.foo)(1, 2, ...a).foo)(1, 2, ...a, "abc"); + xa[1].foo(1, 2, "abc"); xa[1].foo(1, 2, ...a); xa[1].foo(1, 2, ...a, "abc"); diff --git a/tests/cases/conformance/externalModules/globalAugmentationModuleResolution.ts b/tests/cases/conformance/externalModules/globalAugmentationModuleResolution.ts new file mode 100644 index 00000000000..4d87ffcab13 --- /dev/null +++ b/tests/cases/conformance/externalModules/globalAugmentationModuleResolution.ts @@ -0,0 +1,8 @@ +// @traceResolution: true + +// @fileName: a.ts +export { }; + +declare global { + var x: number; +} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport.ts new file mode 100644 index 00000000000..2ea07db3ee4 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport.ts @@ -0,0 +1,21 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// This tests that importing from a JS file globally works in an untyped way. +// (Assuming we don't have `--noImplicitAny` or `--allowJs`.) + +// @filename: /node_modules/foo/index.js +This file is not processed. + +// @filename: /a.ts +import * as foo from "foo"; +foo.bar(); + +// @filename: /b.ts +import foo = require("foo"); +foo(); + +// @filename: /c.ts +import foo, { bar } from "foo"; +import "./a"; +import "./b"; +foo(bar()); diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport_allowJs.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport_allowJs.ts new file mode 100644 index 00000000000..fe509189d96 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport_allowJs.ts @@ -0,0 +1,12 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// @allowJs: true +// @maxNodeModuleJsDepth: 1 +// Same as untypedModuleImport.ts but with --allowJs, so the package will actually be typed. + +// @filename: /node_modules/foo/index.js +exports.default = { bar() { return 0; } } + +// @filename: /a.ts +import foo from "foo"; +foo.bar(); diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport_noImplicitAny.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport_noImplicitAny.ts new file mode 100644 index 00000000000..1aee7c069de --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport_noImplicitAny.ts @@ -0,0 +1,10 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// @noImplicitAny: true +// This tests that `--noImplicitAny` disables untyped modules. + +// @filename: /node_modules/foo/index.js +This file is not processed. + +// @filename: /a.ts +import * as foo from "foo"; diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport_noLocalImports.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport_noLocalImports.ts new file mode 100644 index 00000000000..8313628e6d7 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport_noLocalImports.ts @@ -0,0 +1,9 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// This tests that untyped module imports don't happen with local imports. + +// @filename: /foo.js +This file is not processed. + +// @filename: /a.ts +import * as foo from "./foo"; diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport_vsAmbient.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport_vsAmbient.ts new file mode 100644 index 00000000000..e157772a5ed --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport_vsAmbient.ts @@ -0,0 +1,16 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// This tests that an ambient module declaration overrides an untyped import. + +// @filename: /node_modules/foo/index.js +This file is not processed. + +// @filename: /declarations.d.ts +declare module "foo" { + export const x: number; +} + +// @filename: /a.ts +/// +import { x } from "foo"; +x; diff --git a/tests/cases/conformance/moduleResolution/untypedModuleImport_withAugmentation.ts b/tests/cases/conformance/moduleResolution/untypedModuleImport_withAugmentation.ts new file mode 100644 index 00000000000..e27c1232d25 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/untypedModuleImport_withAugmentation.ts @@ -0,0 +1,13 @@ +// @noImplicitReferences: true +// @currentDirectory: / +// This tests that augmenting an untyped module is forbidden. + +// @filename: /node_modules/foo/index.js +This file is not processed. + +// @filename: /a.ts +declare module "foo" { + export const x: number; +} +import { x } from "foo"; +x; diff --git a/tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts b/tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts new file mode 100644 index 00000000000..dc3aad85335 --- /dev/null +++ b/tests/cases/conformance/parser/ecmascript5/ExportAssignments/parserExportAssignment9.ts @@ -0,0 +1,7 @@ +namespace Foo { + export default foo; +} + +module Bar { + export default bar; +} \ No newline at end of file diff --git a/tests/cases/conformance/references/library-reference-11.ts b/tests/cases/conformance/references/library-reference-11.ts index 6708ceb4ab3..ec1de6e0e9d 100644 --- a/tests/cases/conformance/references/library-reference-11.ts +++ b/tests/cases/conformance/references/library-reference-11.ts @@ -1,3 +1,4 @@ +// @allowJs: true // @noImplicitReferences: true // @traceResolution: true // @currentDirectory: / diff --git a/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts new file mode 100644 index 00000000000..867b6526c12 --- /dev/null +++ b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceError.ts @@ -0,0 +1,14 @@ +class C { + test: string +} + +class D extends C { + test2: string +} + +declare function testError(a: (t: T, t1: T) => void): T + +// more args +testError((t1: D, t2, t3) => {}) +testError((t1, t2: D, t3) => {}) +testError((t1, t2, t3: D) => {}) diff --git a/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceWithTypeParameter.ts b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceWithTypeParameter.ts new file mode 100644 index 00000000000..530d506f64c --- /dev/null +++ b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionInferenceWithTypeParameter.ts @@ -0,0 +1,33 @@ +class C { + test: string +} + +class D extends C { + test2: string +} + +declare function test(a: (t: T, t1: T) => void): T + +declare function testRest(a: (t: T, t1: T, ...ts: T[]) => void): T + + +// exactly +test((t1: D, t2) => { t2.test2 }) +test((t1, t2: D) => { t2.test2 }) + +// zero arg +test(() => {}) + +// fewer args +test((t1: D) => {}) + +// rest arg +test((...ts: D[]) => {}) + +// source function has rest arg +testRest((t1: D) => {}) +testRest((t1, t2, t3) => {}) +testRest((t1: D, t2, t3) => {}) +testRest((t1, t2: D, t3) => {}) +testRest((t2: D, ...t3) => {}) +testRest((t2, ...t3: D[]) => {}) diff --git a/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionWitoutTypeParameter.ts b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionWitoutTypeParameter.ts new file mode 100644 index 00000000000..994df11e247 --- /dev/null +++ b/tests/cases/conformance/types/contextualTypes/partiallyAnnotatedFunction/partiallyAnnotatedFunctionWitoutTypeParameter.ts @@ -0,0 +1,7 @@ +// @noImplicitAny: true + +// simple case +declare function simple(f: (a: number, b: number) => void): {} + +simple((a: number, b) => {}) +simple((a, b: number) => {}) diff --git a/tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts b/tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts new file mode 100644 index 00000000000..c01030c7fa9 --- /dev/null +++ b/tests/cases/conformance/types/keyof/circularIndexedAccessErrors.ts @@ -0,0 +1,31 @@ +// @declaration: true + +type T1 = { + x: T1["x"]; // Error +}; + +type T2 = { + x: T2[K]; // Error + y: number; +} + +declare let x2: T2<"x">; +let x2x = x2.x; + +interface T3> { + x: T["x"]; // Error +} + +interface T4> { + x: T4["x"]; // Error +} + +class C1 { + x: C1["x"]; // Error +} + +class C2 { + x: this["y"]; // Error + y: this["z"]; // Error + z: this["x"]; // Error +} \ No newline at end of file diff --git a/tests/cases/conformance/types/keyof/keyofAndForIn.ts b/tests/cases/conformance/types/keyof/keyofAndForIn.ts new file mode 100644 index 00000000000..97b8587a243 --- /dev/null +++ b/tests/cases/conformance/types/keyof/keyofAndForIn.ts @@ -0,0 +1,36 @@ +// @declaration: true + +// Repro from #12513 + +function f1(obj: { [P in K]: T }, k: K) { + const b = k in obj; + let k1: K; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} + +function f2(obj: { [P in keyof T]: T[P] }, k: keyof T) { + const b = k in obj; + let k1: keyof T; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} + +function f3(obj: { [P in K]: T[P] }, k: K) { + const b = k in obj; + let k1: K; + for (k1 in obj) { + let x1 = obj[k1]; + } + for (let k2 in obj) { + let x2 = obj[k2]; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts new file mode 100644 index 00000000000..ea6a3c2358a --- /dev/null +++ b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts @@ -0,0 +1,433 @@ +// @strictNullChecks: true +// @declaration: true + +class Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +class TaggedShape extends Shape { + tag: string; +} + +class Item { + name: string; + price: number; +} + +class Options { + visible: "yes" | "no"; +} + +type Dictionary = { [x: string]: T }; +type NumericallyIndexed = { [x: number]: T }; + +const enum E { A, B, C } + +type K00 = keyof any; // string +type K01 = keyof string; // "toString" | "charAt" | ... +type K02 = keyof number; // "toString" | "toFixed" | "toExponential" | ... +type K03 = keyof boolean; // "valueOf" +type K04 = keyof void; // never +type K05 = keyof undefined; // never +type K06 = keyof null; // never +type K07 = keyof never; // never + +type K10 = keyof Shape; // "name" | "width" | "height" | "visible" +type K11 = keyof Shape[]; // "length" | "toString" | ... +type K12 = keyof Dictionary; // string +type K13 = keyof {}; // never +type K14 = keyof Object; // "constructor" | "toString" | ... +type K15 = keyof E; // "toString" | "toFixed" | "toExponential" | ... +type K16 = keyof [string, number]; // "0" | "1" | "length" | "toString" | ... +type K17 = keyof (Shape | Item); // "name" +type K18 = keyof (Shape & Item); // "name" | "width" | "height" | "visible" | "price" +type K19 = keyof NumericallyIndexed // never + +type KeyOf = keyof T; + +type K20 = KeyOf; // "name" | "width" | "height" | "visible" +type K21 = KeyOf>; // string + +type NAME = "name"; +type WIDTH_OR_HEIGHT = "width" | "height"; + +type Q10 = Shape["name"]; // string +type Q11 = Shape["width" | "height"]; // number +type Q12 = Shape["name" | "visible"]; // string | boolean + +type Q20 = Shape[NAME]; // string +type Q21 = Shape[WIDTH_OR_HEIGHT]; // number + +type Q30 = [string, number][0]; // string +type Q31 = [string, number][1]; // number +type Q32 = [string, number][2]; // string | number +type Q33 = [string, number][E.A]; // string +type Q34 = [string, number][E.B]; // number +type Q35 = [string, number][E.C]; // string | number +type Q36 = [string, number]["0"]; // string +type Q37 = [string, number]["1"]; // string + +type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" +type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" + +type Q50 = Dictionary["howdy"]; // Shape +type Q51 = Dictionary[123]; // Shape +type Q52 = Dictionary[E.B]; // Shape + +declare let cond: boolean; + +function getProperty(obj: T, key: K) { + return obj[key]; +} + +function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; +} + +function f10(shape: Shape) { + let name = getProperty(shape, "name"); // string + let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number + let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean + setProperty(shape, "name", "rectangle"); + setProperty(shape, cond ? "width" : "height", 10); + setProperty(shape, cond ? "name" : "visible", true); // Technically not safe +} + +function f11(a: Shape[]) { + let len = getProperty(a, "length"); // number + setProperty(a, "length", len); +} + +function f12(t: [Shape, boolean]) { + let len = getProperty(t, "length"); + let s2 = getProperty(t, "0"); // Shape + let b2 = getProperty(t, "1"); // boolean +} + +function f13(foo: any, bar: any) { + let x = getProperty(foo, "x"); // any + let y = getProperty(foo, "100"); // any + let z = getProperty(foo, bar); // any +} + +class Component { + props: PropType; + getProperty(key: K) { + return this.props[key]; + } + setProperty(key: K, value: PropType[K]) { + this.props[key] = value; + } +} + +function f20(component: Component) { + let name = component.getProperty("name"); // string + let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number + let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean + component.setProperty("name", "rectangle"); + component.setProperty(cond ? "width" : "height", 10) + component.setProperty(cond ? "name" : "visible", true); // Technically not safe +} + +function pluck(array: T[], key: K) { + return array.map(x => x[key]); +} + +function f30(shapes: Shape[]) { + let names = pluck(shapes, "name"); // string[] + let widths = pluck(shapes, "width"); // number[] + let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] +} + +function f31(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} + +function f32(key: K) { + const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; + return shape[key]; // Shape[K] +} + +function f33(shape: S, key: K) { + let name = getProperty(shape, "name"); + let prop = getProperty(shape, key); + return prop; +} + +function f34(ts: TaggedShape) { + let tag1 = f33(ts, "tag"); + let tag2 = getProperty(ts, "tag"); +} + +class C { + public x: string; + protected y: string; + private z: string; +} + +// Indexed access expressions have always permitted access to private and protected members. +// For consistency we also permit such access in indexed access types. +function f40(c: C) { + type X = C["x"]; + type Y = C["y"]; + type Z = C["z"]; + let x: X = c["x"]; + let y: Y = c["y"]; + let z: Z = c["z"]; +} + +function f50(k: keyof T, s: string) { + const x1 = s as keyof T; + const x2 = k as string; +} + +function f51(k: K, s: string) { + const x1 = s as keyof T; + const x2 = k as string; +} + +function f52(obj: { [x: string]: boolean }, k: keyof T, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; +} + +function f53(obj: { [x: string]: boolean }, k: K, s: string, n: number) { + const x1 = obj[s]; + const x2 = obj[n]; + const x3 = obj[k]; +} + +function f54(obj: T, key: keyof T) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; +} + +function f55(obj: T, key: K) { + for (let s in obj[key]) { + } + const b = "foo" in obj[key]; +} + +function f60(source: T, target: T) { + for (let k in source) { + target[k] = source[k]; + } +} + +function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { + func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); +} + +function f71(func: (x: T, y: U) => Partial) { + let x = func({ a: 1, b: "hello" }, { c: true }); + x.a; // number | undefined + x.b; // string | undefined + x.c; // boolean | undefined +} + +function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} + +function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { + let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +} + +function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { + let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +} + +function f80(obj: T) { + let a1 = obj.a; // { x: any } + let a2 = obj['a']; // { x: any } + let a3 = obj['a'] as T['a']; // T["a"] + let x1 = obj.a.x; // any + let x2 = obj['a']['x']; // any + let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] +} + +function f81(obj: T) { + return obj['a']['x'] as T['a']['x']; +} + +function f82() { + let x1 = f81({ a: { x: "hello" } }); // string + let x2 = f81({ a: { x: 42 } }); // number +} + +function f83(obj: T, key: K) { + return obj[key]['x'] as T[K]['x']; +} + +function f84() { + let x1 = f83({ foo: { x: "hello" } }, "foo"); // string + let x2 = f83({ bar: { x: 42 } }, "bar"); // number +} + +class C1 { + x: number; + get(key: K) { + return this[key]; + } + set(key: K, value: this[K]) { + this[key] = value; + } + foo() { + let x1 = this.x; // number + let x2 = this["x"]; // number + let x3 = this.get("x"); // this["x"] + let x4 = getProperty(this, "x"); // this["x"] + this.x = 42; + this["x"] = 42; + this.set("x", 42); + setProperty(this, "x", 42); + } +} + +// Repros from #12011 + +class Base { + get(prop: K) { + return this[prop]; + } + set(prop: K, value: this[K]) { + this[prop] = value; + } +} + +class Person extends Base { + parts: number; + constructor(parts: number) { + super(); + this.set("parts", parts); + } + getParts() { + return this.get("parts") + } +} + +class OtherPerson { + parts: number; + constructor(parts: number) { + setProperty(this, "parts", parts); + } + getParts() { + return getProperty(this, "parts") + } +} + +// Modified repro from #12544 + +function path(obj: T, key1: K1): T[K1]; +function path(obj: T, key1: K1, key2: K2): T[K1][K2]; +function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; +function path(obj: any, ...keys: (string | number)[]): any; +function path(obj: any, ...keys: (string | number)[]): any { + let result = obj; + for (let k of keys) { + result = result[k]; + } + return result; +} + +type Thing = { + a: { x: number, y: string }, + b: boolean +}; + + +function f1(thing: Thing) { + let x1 = path(thing, 'a'); // { x: number, y: string } + let x2 = path(thing, 'a', 'y'); // string + let x3 = path(thing, 'b'); // boolean + let x4 = path(thing, ...['a', 'x']); // any +} + +// Repro from comment in #12114 + +const assignTo2 = (object: T, key1: K1, key2: K2) => + (value: T[K1][K2]) => object[key1][key2] = value; + +// Modified repro from #12573 + +declare function one(handler: (t: T) => void): T +var empty = one(() => {}) // inferred as {}, expected + +type Handlers = { [K in keyof T]: (t: T[K]) => void } +declare function on(handlerHash: Handlers): T +var hashOfEmpty1 = on({ test: () => {} }); // {} +var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } + +// Repro from #12624 + +interface Options1 { + data?: Data + computed?: Computed; +} + +declare class Component1 { + constructor(options: Options1); + get(key: K): (Data & Computed)[K]; +} + +let c1 = new Component1({ + data: { + hello: "" + } +}); + +c1.get("hello"); + +// Repro from #12625 + +interface Options2 { + data?: Data + computed?: Computed; +} + +declare class Component2 { + constructor(options: Options2); + get(key: K): (Data & Computed)[K]; +} + +// Repro from #12641 + +interface R { + p: number; +} + +function f(p: K) { + let a: any; + a[p].add; // any +} + +// Repro from #12651 + +type MethodDescriptor = { + name: string; + args: any[]; + returnValue: any; +} + +declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; + +type SomeMethodDescriptor = { + name: "someMethod"; + args: [string, number]; + returnValue: string[]; +} + +let result = dispatchMethod("someMethod", ["hello", 35]); \ No newline at end of file diff --git a/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts b/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts new file mode 100644 index 00000000000..cbbc9a52200 --- /dev/null +++ b/tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts @@ -0,0 +1,79 @@ +class Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +type Dictionary = { [x: string]: T }; + +type T00 = keyof K0; // Error + +type T01 = keyof Object; +type T02 = keyof keyof Object; +type T03 = keyof keyof keyof Object; +type T04 = keyof keyof keyof keyof Object; +type T05 = keyof keyof keyof keyof keyof Object; +type T06 = keyof keyof keyof keyof keyof keyof Object; + +type T10 = Shape["name"]; +type T11 = Shape["foo"]; // Error +type T12 = Shape["name" | "foo"]; // Error +type T13 = Shape[any]; // Error +type T14 = Shape[string]; // Error +type T15 = Shape[number]; // Error +type T16 = Shape[boolean]; // Error +type T17 = Shape[void]; // Error +type T18 = Shape[undefined]; // Error +type T19 = Shape[{ x: string }]; // Error +type T20 = Shape[string | number]; // Error +type T21 = Shape[string & number]; // Error +type T22 = Shape[string | boolean]; // Error + +type T30 = string[]["length"]; +type T31 = string[][number]; +type T32 = string[][string]; // Error +type T33 = string[][boolean]; // Error + +type T40 = Dictionary[any]; +type T41 = Dictionary[number]; +type T42 = Dictionary[string]; +type T43 = Dictionary[boolean]; // Error + +type T50 = any[any]; +type T51 = any[number]; +type T52 = any[string]; +type T53 = any[boolean]; // Error + +type T60 = {}["toString"]; +type T61 = []["toString"]; + +declare let cond: boolean; + +function getProperty(obj: T, key: K) { + return obj[key]; +} + +function setProperty(obj: T, key: K, value: T[K]) { + obj[key] = value; +} + +function f10(shape: Shape) { + let x1 = getProperty(shape, "name"); + let x2 = getProperty(shape, "size"); // Error + let x3 = getProperty(shape, cond ? "name" : "size"); // Error + setProperty(shape, "name", "rectangle"); + setProperty(shape, "size", 10); // Error + setProperty(shape, cond ? "name" : "size", 10); // Error +} + +function f20(k1: keyof (T | U), k2: keyof (T & U), o1: T | U, o2: T & U) { + o1[k1]; + o1[k2]; // Error + o2[k1]; + o2[k2]; + o1 = o2; + o2 = o1; // Error + k1 = k2; // Error + k2 = k1; +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/literalTypes3.ts b/tests/cases/conformance/types/literal/literalTypes3.ts new file mode 100644 index 00000000000..2aa3f1020e2 --- /dev/null +++ b/tests/cases/conformance/types/literal/literalTypes3.ts @@ -0,0 +1,66 @@ +// @strictNullChecks: true + +function f1(s: string) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} + +function f2(s: string) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} + +function f3(s: string) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} + +function f4(x: number) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} + +function f5(x: number, y: 1 | 2) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} + +function f6(x: number, y: 1 | 2) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} \ No newline at end of file diff --git a/tests/cases/conformance/types/literal/literalTypesWidenInParameterPosition.ts b/tests/cases/conformance/types/literal/literalTypesWidenInParameterPosition.ts new file mode 100644 index 00000000000..f1d0a9b428a --- /dev/null +++ b/tests/cases/conformance/types/literal/literalTypesWidenInParameterPosition.ts @@ -0,0 +1,8 @@ +class D { + readonly noWiden = 1 + constructor(readonly widen = 2) { + this.noWiden = 5; // error + this.widen = 6; // ok + } +} +new D(7); // ok diff --git a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts new file mode 100644 index 00000000000..14bb765a840 --- /dev/null +++ b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts @@ -0,0 +1,155 @@ +// @strictNullChecks: true +// @noimplicitany: true +// @declaration: true + +type Box = { + value: T; +} + +type Boxified = { + [P in keyof T]: Box; +} + +function box(x: T): Box { + return { value: x }; +} + +function unbox(x: Box): T { + return x.value; +} + +function boxify(obj: T): Boxified { + let result = {} as Boxified; + for (let k in obj) { + result[k] = box(obj[k]); + } + return result; +} + +function unboxify(obj: Boxified): T { + let result = {} as T; + for (let k in obj) { + result[k] = unbox(obj[k]); + } + return result; +} + +function assignBoxified(obj: Boxified, values: T) { + for (let k in values) { + obj[k].value = values[k]; + } +} + +function f1() { + let v = { + a: 42, + b: "hello", + c: true + }; + let b = boxify(v); + let x: number = b.a.value; +} + +function f2() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + let v = unboxify(b); + let x: number = v.a; +} + +function f3() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + assignBoxified(b, { c: false }); +} + +function f4() { + let b = { + a: box(42), + b: box("hello"), + c: box(true) + }; + b = boxify(unboxify(b)); + b = unboxify(boxify(b)); +} + +function makeRecord(obj: { [P in K]: T }) { + return obj; +} + +function f5(s: string) { + let b = makeRecord({ + a: box(42), + b: box("hello"), + c: box(true) + }); + let v = unboxify(b); + let x: string | number | boolean = v.a; +} + +function makeDictionary(obj: { [x: string]: T }) { + return obj; +} + +function f6(s: string) { + let b = makeDictionary({ + a: box(42), + b: box("hello"), + c: box(true) + }); + let v = unboxify(b); + let x: string | number | boolean = v[s]; +} + +declare function validate(obj: { [P in keyof T]?: T[P] }): T; +declare function clone(obj: { readonly [P in keyof T]: T[P] }): T; +declare function validateAndClone(obj: { readonly [P in keyof T]?: T[P] }): T; + +type Foo = { + a?: number; + readonly b: string; +} + +function f10(foo: Foo) { + let x = validate(foo); // { a: number, readonly b: string } + let y = clone(foo); // { a?: number, b: string } + let z = validateAndClone(foo); // { a: number, b: string } +} + +// Repro from #12606 + +type Func = (...args: any[]) => T; +type Spec = { + [P in keyof T]: Func | Spec ; +}; + +/** + * Given a spec object recursively mapping properties to functions, creates a function + * producing an object of the same structure, by mapping each property to the result + * of calling its associated function with the supplied arguments. + */ +declare function applySpec(obj: Spec): (...args: any[]) => T; + +// Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } +var g1 = applySpec({ + sum: (a: any) => 3, + nested: { + mul: (b: any) => "n" + } +}); + +// Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } +var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); + +// Repro from #12633 + +const foo = (object: T, partial: Partial) => object; +let o = {a: 5, b: 7}; +foo(o, {b: 9}); +o = foo(o, {b: 9}); \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypeErrors.ts b/tests/cases/conformance/types/mapped/mappedTypeErrors.ts new file mode 100644 index 00000000000..cec1fbf8395 --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypeErrors.ts @@ -0,0 +1,146 @@ +// @strictNullChecks: true +// @declaration: true + +interface Shape { + name: string; + width: number; + height: number; + visible: boolean; +} + +interface Named { + name: string; +} + +interface Point { + x: number; + y: number; +} + +// Constraint checking + +type T00 = { [P in P]: string }; // Error +type T01 = { [P in number]: string }; // Error +type T02 = { [P in Date]: number }; // Error +type T03 = Record; // Error + +type T10 = Pick; +type T11 = Pick; // Error +type T12 = Pick; // Error +type T13 = Pick; +type T14 = Pick; // Error +type T15 = Pick; +type T16 = Pick; // Error + +function f1(x: T) { + let y: Pick; // Error +} + +function f2(x: T) { + let y: Pick; // Error +} + +function f3(x: T) { + let y: Pick; +} + +function f4(x: T) { + let y: Pick; +} + +// Type identity checking + +function f10() { + type K = keyof T; + var x: { [P in keyof T]: T[P] }; + var x: { [Q in keyof T]: T[Q] }; + var x: { [R in K]: T[R] }; +} + +function f11() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]?: T[P] }; // Error + var x: { readonly [P in keyof T]: T[P] }; // Error + var x: { readonly [P in keyof T]?: T[P] }; // Error +} + +function f12() { + var x: { [P in keyof T]: T[P] }; + var x: { [P in keyof T]: T[P][] }; // Error +} + +// Check that inferences to mapped types are secondary + +declare function objAndReadonly(primary: T, secondary: Readonly): T; +declare function objAndPartial(primary: T, secondary: Partial): T; + +function f20() { + let x1 = objAndReadonly({ x: 0, y: 0 }, { x: 1 }); // Error + let x2 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndReadonly({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} + +function f21() { + let x1 = objAndPartial({ x: 0, y: 0 }, { x: 1 }); + let x2 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1 }); + let x3 = objAndPartial({ x: 0, y: 0 }, { x: 1, y: 1, z: 1 }); // Error +} + +// Verify use of Pick for setState functions (#12793) + +interface Foo { + a: string; + b?: number; +} + +function setState(obj: T, props: Pick) { + for (let k in props) { + obj[k] = props[k]; + } +} + +let foo: Foo = { a: "hello", b: 42 }; +setState(foo, { a: "test", b: 43 }) +setState(foo, { a: "hi" }); +setState(foo, { b: undefined }); +setState(foo, { }); +setState(foo, foo); +setState(foo, { a: undefined }); // Error +setState(foo, { c: true }); // Error + +class C { + state: T; + setState(props: Pick) { + for (let k in props) { + this.state[k] = props[k]; + } + } +} + +let c = new C(); +c.setState({ a: "test", b: 43 }); +c.setState({ a: "hi" }); +c.setState({ b: undefined }); +c.setState({ }); +c.setState(foo); +c.setState({ a: undefined }); // Error +c.setState({ c: true }); // Error + +type T2 = { a?: number, [key: string]: any }; + +let x1: T2 = { a: 'no' }; // Error +let x2: Partial = { a: 'no' }; // Error +let x3: { [P in keyof T2]: T2[P]} = { a: 'no' }; // Error + +// Repro from #13044 + +type Foo2 = { + pf: {[P in F]?: T[P]}, + pt: {[P in T]?: T[P]}, // note: should be in keyof T +}; +type O = {x: number, y: boolean}; +let o: O = {x: 5, y: false}; +let f: Foo2 = { + pf: {x: 7}, + pt: {x: 7, y: false}, +}; diff --git a/tests/cases/conformance/types/mapped/mappedTypeModifiers.ts b/tests/cases/conformance/types/mapped/mappedTypeModifiers.ts new file mode 100644 index 00000000000..a111d186d16 --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypeModifiers.ts @@ -0,0 +1,100 @@ +// @strictNullChecks: true +// @noimplicitany: true + +type T = { a: number, b: string }; +type TP = { a?: number, b?: string }; +type TR = { readonly a: number, readonly b: string }; +type TPR = { readonly a?: number, readonly b?: string }; + +var v00: "a" | "b"; +var v00: keyof T; +var v00: keyof TP; +var v00: keyof TR; +var v00: keyof TPR; + +var v01: T; +var v01: { [P in keyof T]: T[P] }; +var v01: Pick; +var v01: Pick, keyof T>; + +var v02: TP; +var v02: { [P in keyof T]?: T[P] }; +var v02: Partial; +var v02: { [P in keyof TP]: TP[P] } +var v02: Pick; + +var v03: TR; +var v03: { readonly [P in keyof T]: T[P] }; +var v03: Readonly; +var v03: { [P in keyof TR]: TR[P] } +var v03: Pick; + +var v04: TPR; +var v04: { readonly [P in keyof T]?: T[P] }; +var v04: Partial; +var v04: Readonly; +var v04: Partial>; +var v04: Readonly>; +var v04: { [P in keyof TPR]: TPR[P] } +var v04: Pick; + +type Boxified = { [P in keyof T]: { x: T[P] } }; + +type B = { a: { x: number }, b: { x: string } }; +type BP = { a?: { x: number }, b?: { x: string } }; +type BR = { readonly a: { x: number }, readonly b: { x: string } }; +type BPR = { readonly a?: { x: number }, readonly b?: { x: string } }; + +var b00: "a" | "b"; +var b00: keyof B; +var b00: keyof BP; +var b00: keyof BR; +var b00: keyof BPR; + +var b01: B; +var b01: { [P in keyof B]: B[P] }; +var b01: Pick; +var b01: Pick, keyof B>; + +var b02: BP; +var b02: { [P in keyof B]?: B[P] }; +var b02: Partial; +var b02: { [P in keyof BP]: BP[P] } +var b02: Pick; + +var b03: BR; +var b03: { readonly [P in keyof B]: B[P] }; +var b03: Readonly; +var b03: { [P in keyof BR]: BR[P] } +var b03: Pick; + +var b04: BPR; +var b04: { readonly [P in keyof B]?: B[P] }; +var b04: Partial
; +var b04: Readonly; +var b04: Partial>; +var b04: Readonly>; +var b04: { [P in keyof BPR]: BPR[P] } +var b04: Pick; + +type Foo = { prop: number, [x: string]: number }; + +function f1(x: Partial) { + x.prop; // ok + (x["other"] || 0).toFixed(); +} + +function f2(x: Readonly) { + x.prop; // ok + x["other"].toFixed(); +} + +function f3(x: Boxified) { + x.prop; // ok + x["other"].x.toFixed(); +} + +function f4(x: { [P in keyof Foo]: Foo[P] }) { + x.prop; // ok + x["other"].toFixed(); +} diff --git a/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts b/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts new file mode 100644 index 00000000000..4af71fbea08 --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts @@ -0,0 +1,108 @@ +// @strictNullChecks: true +// @declaration: true + +function f1(x: T, k: keyof T) { + return x[k]; +} + +function f2(x: T, k: K) { + return x[k]; +} + +function f3(x: T, y: U, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f4(x: T, y: U, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f5(x: T, y: U, k: keyof U) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f6(x: T, y: U, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f10(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + y[k] = x[k]; +} + +function f11(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; +} + +function f12(x: T, y: Partial, k: keyof T) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f13(x: T, y: Partial, k: K) { + x[k] = y[k]; // Error + y[k] = x[k]; // Error +} + +function f20(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f21(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f22(x: T, y: Readonly, k: keyof T) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f23(x: T, y: Readonly, k: K) { + x[k] = y[k]; + y[k] = x[k]; // Error +} + +function f30(x: T, y: Partial) { + x = y; // Error + y = x; +} + +function f31(x: T, y: Partial) { + x = y; // Error + y = x; +} + +function f40(x: T, y: Readonly) { + x = y; + y = x; +} + +function f41(x: T, y: Readonly) { + x = y; + y = x; +} + +type Item = { + name: string; +} + +type ItemMap = { + [x: string]: Item; +} + +function f50(obj: T, key: keyof T) { + let item: Item = obj[key]; + return obj[key].name; +} + +function f51(obj: T, key: K) { + let item: Item = obj[key]; + return obj[key].name; +} \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypes1.ts b/tests/cases/conformance/types/mapped/mappedTypes1.ts new file mode 100644 index 00000000000..b74872c2bfd --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypes1.ts @@ -0,0 +1,42 @@ +// @strictNullChecks: true +// @declaration: true + +type Item = { a: string, b: number, c: boolean }; + +type T00 = { [P in "x" | "y"]: number }; +type T01 = { [P in "x" | "y"]: P }; +type T02 = { [P in "a" | "b"]: Item[P]; } +type T03 = { [P in keyof Item]: Date }; + +type T10 = { [P in keyof Item]: Item[P] }; +type T11 = { [P in keyof Item]?: Item[P] }; +type T12 = { readonly [P in keyof Item]: Item[P] }; +type T13 = { readonly [P in keyof Item]?: Item[P] }; + +type T20 = { [P in keyof Item]: Item[P] | null }; +type T21 = { [P in keyof Item]: Array }; + +type T30 = { [P in keyof any]: void }; +type T31 = { [P in keyof string]: void }; +type T32 = { [P in keyof number]: void }; +type T33 = { [P in keyof boolean]: void }; +type T34 = { [P in keyof undefined]: void }; +type T35 = { [P in keyof null]: void }; +type T36 = { [P in keyof void]: void }; +type T37 = { [P in keyof symbol]: void }; +type T38 = { [P in keyof never]: void }; + +type T40 = { [P in string]: void }; +type T43 = { [P in "a" | "b"]: void }; +type T44 = { [P in "a" | "b" | "0" | "1"]: void }; +type T47 = { [P in string | "a" | "b" | "0" | "1"]: void }; + +declare function f1(): { [P in keyof T1]: void }; +declare function f2(): { [P in keyof T1]: void }; +declare function f3(): { [P in keyof T1]: void }; +declare function f4(): { [P in keyof T1]: void }; + +let x1 = f1(); +let x2 = f2(); +let x3 = f3(); +let x4 = f4(); \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypes2.ts b/tests/cases/conformance/types/mapped/mappedTypes2.ts new file mode 100644 index 00000000000..60db4c1383b --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypes2.ts @@ -0,0 +1,96 @@ +// @strictNullChecks: true +// @declaration: true + +function verifyLibTypes() { + var x1: Partial; + var x1: { [P in keyof T]?: T[P] }; + var x2: Readonly; + var x2: { readonly [P in keyof T]: T[P] }; + var x3: Pick; + var x3: { [P in K]: T[P] }; + var x4: Record; + var x4: { [P in K]: U }; +} + +type Proxy = { + get(): T; + set(value: T): void; +} + +type Proxify = { + [P in keyof T]: Proxy; +} + +type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; + +declare function assign(obj: T, props: Partial): void; +declare function freeze(obj: T): Readonly; +declare function pick(obj: T, ...keys: K[]): Pick; +declare function mapObject(obj: Record, f: (x: T) => U): Record; +declare function proxify(obj: T): Proxify; + +interface Point { + x: number; + y: number; +} + +interface Shape { + name: string; + width: number; + height: number; + location: Point; +} + +interface PartialShape { + name?: string; + width?: number; + height?: number; + location?: Point; +} + +interface ReadonlyShape { + readonly name: string; + readonly width: number; + readonly height: number; + readonly location: Point; +} + +function f0(s1: Shape, s2: Shape) { + assign(s1, { name: "circle" }); + assign(s2, { width: 10, height: 20 }); +} + +function f1(shape: Shape) { + var frozen: ReadonlyShape; + var frozen: Readonly; + var frozen = freeze(shape); +} + +function f2(shape: Shape) { + var partial: PartialShape; + var partial: Partial; + var partial: Partial = {}; +} + +function f3(shape: Shape) { + const x = pick(shape, "name", "location"); // { name: string, location: Point } +} + +function f4() { + const rec = { foo: "hello", bar: "world", baz: "bye" }; + const lengths = mapObject(rec, s => s.length); // { foo: number, bar: number, baz: number } +} + +function f5(shape: Shape) { + const p = proxify(shape); + let name = p.name.get(); + p.width.set(42); +} + +function f6(shape: DeepReadonly) { + let name = shape.name; // string + let location = shape.location; // DeepReadonly + let x = location.x; // number +} \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypes3.ts b/tests/cases/conformance/types/mapped/mappedTypes3.ts new file mode 100644 index 00000000000..bf5a4399b0d --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypes3.ts @@ -0,0 +1,40 @@ +// @declaration: true + +class Box
; +/////*11*/ // insert globals +////const y =
; // no globals in jsx attribute found +////const z =
; // no globals in jsx attribute with syntax error +////const x = `/*14*/ ${/*15*/}`; // globals only in template expression +////var user = ; // globals only in JSX expression (but not in JSX expression strings) goTo.marker("1"); verify.completionListIsGlobal(false); goTo.marker("2"); @@ -29,18 +41,34 @@ verify.completionListIsGlobal(false); goTo.marker("3"); verify.completionListIsGlobal(false); goTo.marker("4"); -verify.completionListIsGlobal(true); +verify.completionListIsGlobal(false); goTo.marker("5"); -verify.completionListIsGlobal(false); -goTo.marker("6"); verify.completionListIsGlobal(true); -goTo.marker("7"); +goTo.marker("6"); verify.completionListIsGlobal(false); +goTo.marker("7"); +verify.completionListIsGlobal(true); goTo.marker("8"); verify.completionListIsGlobal(false); goTo.marker("9"); -verify.completionListIsGlobal(true); +verify.completionListIsGlobal(false); goTo.marker("10"); verify.completionListIsGlobal(true); goTo.marker("11"); +verify.completionListIsGlobal(true); +goTo.marker("12"); verify.completionListIsGlobal(false); +goTo.marker("13"); +verify.completionListIsGlobal(false); +goTo.marker("14"); +verify.completionListIsGlobal(false); +goTo.marker("15"); +verify.completionListIsGlobal(true); +goTo.marker("16"); +verify.completionListIsGlobal(false); +goTo.marker("17"); +verify.completionListIsGlobal(false); +goTo.marker("18"); +verify.completionListIsGlobal(true); +goTo.marker("19"); +verify.completionListIsGlobal(false); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListKeywords.ts b/tests/cases/fourslash/completionListKeywords.ts index a01da4569bd..edfc54bcc7d 100644 --- a/tests/cases/fourslash/completionListKeywords.ts +++ b/tests/cases/fourslash/completionListKeywords.ts @@ -3,46 +3,46 @@ /////**/ goTo.marker(); -verify.memberListContains("break"); -verify.memberListContains("case"); -verify.memberListContains("catch"); -verify.memberListContains("class"); -verify.memberListContains("constructor"); -verify.memberListContains("continue"); -verify.memberListContains("debugger"); -verify.memberListContains("declare"); -verify.memberListContains("default"); -verify.memberListContains("delete"); -verify.memberListContains("do"); -verify.memberListContains("else"); -verify.memberListContains("enum"); -verify.memberListContains("export"); -verify.memberListContains("extends"); -verify.memberListContains("false"); -verify.memberListContains("finally"); -verify.memberListContains("for"); -verify.memberListContains("function"); -verify.memberListContains("get"); -verify.memberListContains("if"); -verify.memberListContains("implements"); -verify.memberListContains("import"); -verify.memberListContains("in"); -verify.memberListContains("instanceof"); -verify.memberListContains("interface"); -verify.memberListContains("module"); -verify.memberListContains("new"); -verify.memberListContains("private"); -verify.memberListContains("public"); -verify.memberListContains("return"); -verify.memberListContains("set"); -verify.memberListContains("static"); -verify.memberListContains("super"); -verify.memberListContains("switch"); -verify.memberListContains("this"); -verify.memberListContains("throw"); -verify.memberListContains("true"); -verify.memberListContains("try"); -verify.memberListContains("typeof"); -verify.memberListContains("var"); -verify.memberListContains("while"); -verify.memberListContains("with"); +verify.completionListContains("break"); +verify.completionListContains("case"); +verify.completionListContains("catch"); +verify.completionListContains("class"); +verify.completionListContains("constructor"); +verify.completionListContains("continue"); +verify.completionListContains("debugger"); +verify.completionListContains("declare"); +verify.completionListContains("default"); +verify.completionListContains("delete"); +verify.completionListContains("do"); +verify.completionListContains("else"); +verify.completionListContains("enum"); +verify.completionListContains("export"); +verify.completionListContains("extends"); +verify.completionListContains("false"); +verify.completionListContains("finally"); +verify.completionListContains("for"); +verify.completionListContains("function"); +verify.completionListContains("get"); +verify.completionListContains("if"); +verify.completionListContains("implements"); +verify.completionListContains("import"); +verify.completionListContains("in"); +verify.completionListContains("instanceof"); +verify.completionListContains("interface"); +verify.completionListContains("module"); +verify.completionListContains("new"); +verify.completionListContains("private"); +verify.completionListContains("public"); +verify.completionListContains("return"); +verify.completionListContains("set"); +verify.completionListContains("static"); +verify.completionListContains("super"); +verify.completionListContains("switch"); +verify.completionListContains("this"); +verify.completionListContains("throw"); +verify.completionListContains("true"); +verify.completionListContains("try"); +verify.completionListContains("typeof"); +verify.completionListContains("var"); +verify.completionListContains("while"); +verify.completionListContains("with"); diff --git a/tests/cases/fourslash/completionListModuleMembers.ts b/tests/cases/fourslash/completionListModuleMembers.ts index b93399b799e..462025ad99c 100644 --- a/tests/cases/fourslash/completionListModuleMembers.ts +++ b/tests/cases/fourslash/completionListModuleMembers.ts @@ -22,35 +22,35 @@ ////interface TestInterface implements Module./*TypeReferenceInImplementsList*/ { } goTo.marker("ValueReference"); -verify.memberListContains("exportedVariable"); -verify.memberListContains("exportedFunction"); -verify.memberListContains("exportedClass"); -verify.memberListContains("exportedModule"); +verify.completionListContains("exportedVariable"); +verify.completionListContains("exportedFunction"); +verify.completionListContains("exportedClass"); +verify.completionListContains("exportedModule"); // No inner declarations -verify.not.memberListContains("innerVariable"); -verify.not.memberListContains("innerClass"); +verify.not.completionListContains("innerVariable"); +verify.not.completionListContains("innerClass"); // Include type declarations -verify.memberListContains("exportedInterface"); +verify.completionListContains("exportedInterface"); goTo.marker("TypeReference"); -verify.memberListContains("exportedClass"); -verify.memberListContains("exportedModule"); -verify.memberListContains("exportedInterface"); +verify.completionListContains("exportedClass"); +verify.completionListContains("exportedModule"); +verify.completionListContains("exportedInterface"); // Include value completions -verify.memberListContains("exportedVariable"); +verify.completionListContains("exportedVariable"); goTo.marker("TypeReferenceInExtendsList"); -verify.memberListContains("exportedClass"); -verify.memberListContains("exportedModule"); -verify.memberListContains("exportedInterface"); +verify.completionListContains("exportedClass"); +verify.completionListContains("exportedModule"); +verify.completionListContains("exportedInterface"); // Include value completions -verify.memberListContains("exportedVariable"); +verify.completionListContains("exportedVariable"); goTo.marker("TypeReferenceInImplementsList"); -verify.memberListContains("exportedClass"); -verify.memberListContains("exportedModule"); -verify.memberListContains("exportedInterface"); +verify.completionListContains("exportedClass"); +verify.completionListContains("exportedModule"); +verify.completionListContains("exportedInterface"); // Include value completions -verify.memberListContains("exportedVariable"); +verify.completionListContains("exportedVariable"); diff --git a/tests/cases/fourslash/completionListObjectMembers.ts b/tests/cases/fourslash/completionListObjectMembers.ts index 5d66b31fa5d..ae773c1c3b4 100644 --- a/tests/cases/fourslash/completionListObjectMembers.ts +++ b/tests/cases/fourslash/completionListObjectMembers.ts @@ -10,5 +10,5 @@ ////object./**/ goTo.marker(); -verify.memberListContains("bar", '(property) bar: any'); -verify.memberListContains("foo", '(method) foo(bar: any): any'); +verify.completionListContains("bar", '(property) bar: any'); +verify.completionListContains("foo", '(method) foo(bar: any): any'); diff --git a/tests/cases/fourslash/completionListOfGnericSymbol.ts b/tests/cases/fourslash/completionListOfGnericSymbol.ts index 936eeeff714..9251892db23 100644 --- a/tests/cases/fourslash/completionListOfGnericSymbol.ts +++ b/tests/cases/fourslash/completionListOfGnericSymbol.ts @@ -6,6 +6,6 @@ ////a./**/ goTo.marker(); -verify.memberListContains('length', "(property) Array.length: number", /*docComments*/ undefined, /*kind*/ "property"); -verify.memberListContains('toString', "(method) Array.toString(): string", /*docComments*/ undefined, /*kind*/ "method"); +verify.completionListContains('length', "(property) Array.length: number", /*docComments*/ undefined, /*kind*/ "property"); +verify.completionListContains('toString', "(method) Array.toString(): string", /*docComments*/ undefined, /*kind*/ "method"); diff --git a/tests/cases/fourslash/completionListOfSplitInterface.ts b/tests/cases/fourslash/completionListOfSplitInterface.ts index 61eae0da072..9bc635d8f8b 100644 --- a/tests/cases/fourslash/completionListOfSplitInterface.ts +++ b/tests/cases/fourslash/completionListOfSplitInterface.ts @@ -33,18 +33,18 @@ ////ci1./*2*/b; goTo.marker('1'); -verify.memberListCount(6); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); -verify.memberListContains("i1"); -verify.memberListContains("i2"); -verify.memberListContains("i3"); +verify.completionListCount(6); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); +verify.completionListContains("i1"); +verify.completionListContains("i2"); +verify.completionListContains("i3"); goTo.marker('2'); -verify.memberListCount(5); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("b1"); -verify.memberListContains("i11"); -verify.memberListContains("i12"); +verify.completionListCount(5); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("b1"); +verify.completionListContains("i11"); +verify.completionListContains("i12"); diff --git a/tests/cases/fourslash/completionListOnAliases.ts b/tests/cases/fourslash/completionListOnAliases.ts index 3d9026c3036..c15e5284c06 100644 --- a/tests/cases/fourslash/completionListOnAliases.ts +++ b/tests/cases/fourslash/completionListOnAliases.ts @@ -9,7 +9,7 @@ ////} goTo.marker("1"); -verify.memberListContains("x", "import x = M", undefined); +verify.completionListContains("x", "import x = M", undefined); goTo.marker("2"); -verify.memberListContains("value"); +verify.completionListContains("value"); diff --git a/tests/cases/fourslash/completionListOnAliases2.ts b/tests/cases/fourslash/completionListOnAliases2.ts index 6a74f3a525b..7ff50a1a2b5 100644 --- a/tests/cases/fourslash/completionListOnAliases2.ts +++ b/tests/cases/fourslash/completionListOnAliases2.ts @@ -35,40 +35,40 @@ // Module m goTo.marker("1"); -verify.memberListContains("I"); -verify.memberListContains("C"); -verify.memberListContains("E"); -verify.memberListContains("N"); -verify.memberListContains("V"); -verify.memberListContains("F"); -verify.memberListContains("A"); +verify.completionListContains("I"); +verify.completionListContains("C"); +verify.completionListContains("E"); +verify.completionListContains("N"); +verify.completionListContains("V"); +verify.completionListContains("F"); +verify.completionListContains("A"); // Class C goTo.marker("2"); -verify.memberListContains("property"); +verify.completionListContains("property"); // Enum E goTo.marker("3"); -verify.memberListContains("value"); +verify.completionListContains("value"); // Module N goTo.marker("4"); -verify.memberListContains("v"); +verify.completionListContains("v"); // var V goTo.marker("5"); -verify.memberListContains("toFixed"); +verify.completionListContains("toFixed"); // function F goTo.marker("6"); -verify.memberListContains("call"); +verify.completionListContains("call"); // alias a goTo.marker("7"); -verify.memberListContains("I"); -verify.memberListContains("C"); -verify.memberListContains("E"); -verify.memberListContains("N"); -verify.memberListContains("V"); -verify.memberListContains("F"); -verify.memberListContains("A"); +verify.completionListContains("I"); +verify.completionListContains("C"); +verify.completionListContains("E"); +verify.completionListContains("N"); +verify.completionListContains("V"); +verify.completionListContains("F"); +verify.completionListContains("A"); diff --git a/tests/cases/fourslash/completionListOnAliases3.ts b/tests/cases/fourslash/completionListOnAliases3.ts index 8c5194af968..3eab00e2ed9 100644 --- a/tests/cases/fourslash/completionListOnAliases3.ts +++ b/tests/cases/fourslash/completionListOnAliases3.ts @@ -10,4 +10,4 @@ // Q does not show up in member list of x goTo.marker("1"); -verify.memberListContains("Q"); +verify.completionListContains("Q"); diff --git a/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts b/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts index 9cab9589406..cec7bf87aec 100644 --- a/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts +++ b/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts @@ -4,4 +4,4 @@ //// Foo(function () { } )./**/; goTo.marker(); -verify.memberListContains('q'); +verify.completionListContains('q'); diff --git a/tests/cases/fourslash/completionListOnParam.ts b/tests/cases/fourslash/completionListOnParam.ts index 8b686535927..ad2bbcde1b8 100644 --- a/tests/cases/fourslash/completionListOnParam.ts +++ b/tests/cases/fourslash/completionListOnParam.ts @@ -9,4 +9,4 @@ ////} goTo.marker(); -verify.memberListContains('Blah'); \ No newline at end of file +verify.completionListContains('Blah'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListOnParamOfGenericType1.ts b/tests/cases/fourslash/completionListOnParamOfGenericType1.ts index 1b0fdba8ff8..c55b48bf7e9 100644 --- a/tests/cases/fourslash/completionListOnParamOfGenericType1.ts +++ b/tests/cases/fourslash/completionListOnParamOfGenericType1.ts @@ -9,14 +9,14 @@ ////} goTo.marker('1'); -verify.memberListContains('next'); -verify.memberListContains('prev'); -verify.memberListContains('pushEntry'); +verify.completionListContains('next'); +verify.completionListContains('prev'); +verify.completionListContains('pushEntry'); edit.insert('next.'); -verify.memberListContains('next'); -verify.memberListContains('prev'); -verify.memberListContains('pushEntry'); +verify.completionListContains('next'); +verify.completionListContains('prev'); +verify.completionListContains('pushEntry'); edit.insert('prev.'); -verify.memberListContains('next'); -verify.memberListContains('prev'); -verify.memberListContains('pushEntry'); +verify.completionListContains('next'); +verify.completionListContains('prev'); +verify.completionListContains('pushEntry'); diff --git a/tests/cases/fourslash/completionListOnSuper.ts b/tests/cases/fourslash/completionListOnSuper.ts index 3ca997cf1bb..2b3c0ef75fa 100644 --- a/tests/cases/fourslash/completionListOnSuper.ts +++ b/tests/cases/fourslash/completionListOnSuper.ts @@ -17,6 +17,6 @@ ////} goTo.marker(); -verify.memberListContains('foo'); -verify.memberListContains('bar'); -verify.memberListCount(2); +verify.completionListContains('foo'); +verify.completionListContains('bar'); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/completionListOnVarBetweenModules.ts b/tests/cases/fourslash/completionListOnVarBetweenModules.ts index 6f907e5f75b..b0205e3428c 100644 --- a/tests/cases/fourslash/completionListOnVarBetweenModules.ts +++ b/tests/cases/fourslash/completionListOnVarBetweenModules.ts @@ -13,5 +13,5 @@ ////} goTo.marker(); -verify.memberListContains("C1"); -verify.memberListContains("C2"); +verify.completionListContains("C1"); +verify.completionListContains("C2"); diff --git a/tests/cases/fourslash/completionListPrimitives.ts b/tests/cases/fourslash/completionListPrimitives.ts index fd1d0670f2e..21a34659c4e 100644 --- a/tests/cases/fourslash/completionListPrimitives.ts +++ b/tests/cases/fourslash/completionListPrimitives.ts @@ -3,10 +3,10 @@ /////**/ goTo.marker(); -verify.memberListContains("any"); -verify.memberListContains("boolean"); -verify.memberListContains("null"); -verify.memberListContains("number"); -verify.memberListContains("string"); -verify.memberListContains("undefined"); -verify.memberListContains("void"); \ No newline at end of file +verify.completionListContains("any"); +verify.completionListContains("boolean"); +verify.completionListContains("null"); +verify.completionListContains("number"); +verify.completionListContains("string"); +verify.completionListContains("undefined"); +verify.completionListContains("void"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListPrivateMembers.ts b/tests/cases/fourslash/completionListPrivateMembers.ts index 772491a391e..e5e494d521d 100644 --- a/tests/cases/fourslash/completionListPrivateMembers.ts +++ b/tests/cases/fourslash/completionListPrivateMembers.ts @@ -13,5 +13,5 @@ goTo.marker(); -verify.memberListContains("y"); -verify.not.memberListContains("x"); +verify.completionListContains("y"); +verify.not.completionListContains("x"); diff --git a/tests/cases/fourslash/completionListPrivateMembers2.ts b/tests/cases/fourslash/completionListPrivateMembers2.ts index 1b19d042cbe..1a04df1d823 100644 --- a/tests/cases/fourslash/completionListPrivateMembers2.ts +++ b/tests/cases/fourslash/completionListPrivateMembers2.ts @@ -9,9 +9,9 @@ ////f./*2*/ goTo.marker("1"); -verify.memberListContains("y"); -verify.memberListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("x"); goTo.marker("2"); -verify.not.memberListContains("x"); -verify.not.memberListContains("y"); \ No newline at end of file +verify.not.completionListContains("x"); +verify.not.completionListContains("y"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListPrivateMembers3.ts b/tests/cases/fourslash/completionListPrivateMembers3.ts index 69f7456d7b5..999ab8fa5e6 100644 --- a/tests/cases/fourslash/completionListPrivateMembers3.ts +++ b/tests/cases/fourslash/completionListPrivateMembers3.ts @@ -19,13 +19,13 @@ ////} goTo.marker("1"); -verify.memberListContains("p"); -verify.memberListCount(1); +verify.completionListContains("p"); +verify.completionListCount(1); goTo.marker("2"); -verify.memberListContains("p"); -verify.memberListCount(1); +verify.completionListContains("p"); +verify.completionListCount(1); goTo.marker("2"); -verify.memberListContains("p"); -verify.memberListCount(1); +verify.completionListContains("p"); +verify.completionListCount(1); diff --git a/tests/cases/fourslash/completionListProtectedMembers.ts b/tests/cases/fourslash/completionListProtectedMembers.ts index 4715a9fb714..20cb990405d 100644 --- a/tests/cases/fourslash/completionListProtectedMembers.ts +++ b/tests/cases/fourslash/completionListProtectedMembers.ts @@ -19,26 +19,26 @@ ////f./*5*/ goTo.marker("1"); -verify.memberListContains("y"); -verify.memberListContains("x"); -verify.not.memberListContains("z"); +verify.completionListContains("y"); +verify.completionListContains("x"); +verify.not.completionListContains("z"); goTo.marker("2"); -verify.memberListContains("y"); -verify.memberListContains("x"); -verify.memberListContains("z"); +verify.completionListContains("y"); +verify.completionListContains("x"); +verify.completionListContains("z"); goTo.marker("3"); -verify.memberListContains("y"); -verify.memberListContains("x"); -verify.not.memberListContains("z"); +verify.completionListContains("y"); +verify.completionListContains("x"); +verify.not.completionListContains("z"); goTo.marker("4"); -verify.memberListContains("y"); -verify.memberListContains("x"); -verify.memberListContains("z"); +verify.completionListContains("y"); +verify.completionListContains("x"); +verify.completionListContains("z"); goTo.marker("5"); -verify.not.memberListContains("x"); -verify.not.memberListContains("y"); -verify.not.memberListContains("z"); +verify.not.completionListContains("x"); +verify.not.completionListContains("y"); +verify.not.completionListContains("z"); diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers.ts b/tests/cases/fourslash/completionListStaticProtectedMembers.ts index d72859570aa..ae79387fbe7 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers.ts @@ -28,32 +28,32 @@ // Same class, everything is visible goTo.marker("1"); -verify.memberListContains('privateMethod'); -verify.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.completionListContains('privateMethod'); +verify.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); goTo.marker("2"); -verify.memberListContains('privateMethod'); -verify.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.completionListContains('privateMethod'); +verify.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); // Can not access protected properties overridden in subclass goTo.marker("3"); -verify.memberListContains('privateMethod'); -verify.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.not.memberListContains('protectedOverriddenMethod'); -verify.not.memberListContains('protectedOverriddenProperty'); \ No newline at end of file +verify.completionListContains('privateMethod'); +verify.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.not.completionListContains('protectedOverriddenMethod'); +verify.not.completionListContains('protectedOverriddenProperty'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers2.ts b/tests/cases/fourslash/completionListStaticProtectedMembers2.ts index 44cf9f73fd5..c6c64c5c6eb 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers2.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers2.ts @@ -29,42 +29,42 @@ // Same class, everything is visible goTo.marker("1"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); goTo.marker("2"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); goTo.marker("3"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); // only public and protected methods of the base class are accessible through super goTo.marker("4"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.not.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.not.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.not.memberListContains('protectedOverriddenProperty'); \ No newline at end of file +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.not.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.not.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.not.completionListContains('protectedOverriddenProperty'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers3.ts b/tests/cases/fourslash/completionListStaticProtectedMembers3.ts index c955f23fa32..0cb916c181f 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers3.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers3.ts @@ -25,21 +25,21 @@ // Only public properties are visible outside the class goTo.marker("1"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.not.memberListContains('protectedMethod'); -verify.not.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.not.memberListContains('protectedOverriddenMethod'); -verify.not.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.not.completionListContains('protectedMethod'); +verify.not.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.not.completionListContains('protectedOverriddenMethod'); +verify.not.completionListContains('protectedOverriddenProperty'); goTo.marker("2"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.not.memberListContains('protectedMethod'); -verify.not.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.not.memberListContains('protectedOverriddenMethod'); -verify.not.memberListContains('protectedOverriddenProperty'); \ No newline at end of file +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.not.completionListContains('protectedMethod'); +verify.not.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.not.completionListContains('protectedOverriddenMethod'); +verify.not.completionListContains('protectedOverriddenProperty'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers4.ts b/tests/cases/fourslash/completionListStaticProtectedMembers4.ts index 817d2c4829c..14c460d6873 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers4.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers4.ts @@ -28,22 +28,22 @@ // Sub class, everything but private is visible goTo.marker("1"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.memberListContains('protectedMethod'); -verify.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.completionListContains('protectedMethod'); +verify.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); // Can see protected methods elevated to public goTo.marker("2"); -verify.not.memberListContains('privateMethod'); -verify.not.memberListContains('privateProperty'); -verify.not.memberListContains('protectedMethod'); -verify.not.memberListContains('protectedProperty'); -verify.memberListContains('publicMethod'); -verify.memberListContains('publicProperty'); -verify.memberListContains('protectedOverriddenMethod'); -verify.memberListContains('protectedOverriddenProperty'); +verify.not.completionListContains('privateMethod'); +verify.not.completionListContains('privateProperty'); +verify.not.completionListContains('protectedMethod'); +verify.not.completionListContains('protectedProperty'); +verify.completionListContains('publicMethod'); +verify.completionListContains('publicProperty'); +verify.completionListContains('protectedOverriddenMethod'); +verify.completionListContains('protectedOverriddenProperty'); diff --git a/tests/cases/fourslash/completionListSuperMembers.ts b/tests/cases/fourslash/completionListSuperMembers.ts index 6c7ddd5c7b3..ae6195601a3 100644 --- a/tests/cases/fourslash/completionListSuperMembers.ts +++ b/tests/cases/fourslash/completionListSuperMembers.ts @@ -25,11 +25,11 @@ goTo.marker(); -verify.not.memberListContains("publicProperty"); -verify.memberListContains("publicInstanceMethod"); +verify.not.completionListContains("publicProperty"); +verify.completionListContains("publicInstanceMethod"); // No statics -verify.not.memberListContains("publicStaticProperty"); -verify.not.memberListContains("publicStaticMethod"); +verify.not.completionListContains("publicStaticProperty"); +verify.not.completionListContains("publicStaticMethod"); // No privates -verify.not.memberListContains("privateProperty"); -verify.not.memberListContains("privateInstanceMethod"); \ No newline at end of file +verify.not.completionListContains("privateProperty"); +verify.not.completionListContains("privateInstanceMethod"); \ No newline at end of file diff --git a/tests/cases/fourslash/exportEqualTypes.ts b/tests/cases/fourslash/exportEqualTypes.ts index 1b8593893dd..b03e21b5f99 100644 --- a/tests/cases/fourslash/exportEqualTypes.ts +++ b/tests/cases/fourslash/exportEqualTypes.ts @@ -20,5 +20,5 @@ verify.quickInfos({ 3: "var r2: string" }); goTo.marker('4'); -verify.memberListContains('foo'); +verify.completionListContains('foo'); verify.numberOfErrorsInCurrentFile(0); diff --git a/tests/cases/fourslash/extendArrayInterface.ts b/tests/cases/fourslash/extendArrayInterface.ts index 4402dc39b88..d2322b37df0 100644 --- a/tests/cases/fourslash/extendArrayInterface.ts +++ b/tests/cases/fourslash/extendArrayInterface.ts @@ -8,7 +8,7 @@ goTo.marker("1"); -verify.memberListContains("concat"); +verify.completionListContains("concat"); // foo doesn't exist, so both references should be in error verify.errorExistsBetweenMarkers("2", "3"); diff --git a/tests/cases/fourslash/externalModuleIntellisense.ts b/tests/cases/fourslash/externalModuleIntellisense.ts index 93c7143a9c6..8577e0686bf 100644 --- a/tests/cases/fourslash/externalModuleIntellisense.ts +++ b/tests/cases/fourslash/externalModuleIntellisense.ts @@ -23,4 +23,4 @@ goTo.eof(); edit.insert("x."); verify.completionListContains('enable'); verify.completionListContains('post'); -verify.memberListCount(2); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts b/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts index 257c6cf3455..a1d503a657a 100644 --- a/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts +++ b/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts @@ -16,5 +16,5 @@ goTo.marker('1'); edit.insert("file1."); -verify.memberListContains("bar"); -verify.not.memberListContains("foo"); \ No newline at end of file +verify.completionListContains("bar"); +verify.not.completionListContains("foo"); \ No newline at end of file diff --git a/tests/cases/fourslash/findAllRefsForObjectSpread.ts b/tests/cases/fourslash/findAllRefsForObjectSpread.ts new file mode 100644 index 00000000000..05c83491f66 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForObjectSpread.ts @@ -0,0 +1,14 @@ +/// + +////interface A1 { [|a|]: string }; +////interface A2 { [|a|]?: number }; +////let a1: A1; +////let a2: A2; +////let a12 = { ...a1, ...a2 }; +////a12.[|a|]; +const ranges = test.ranges(); +// members of spread types only refer to themselves and the resulting property +verify.referencesOf(ranges[0], [ranges[0], ranges[2]]); +verify.referencesOf(ranges[1], [ranges[1], ranges[2]]); +// but the resulting property refers to everything +verify.referencesOf(ranges[2], ranges); diff --git a/tests/cases/fourslash/findAllRefsForRest.ts b/tests/cases/fourslash/findAllRefsForRest.ts new file mode 100644 index 00000000000..c3a970e9e73 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsForRest.ts @@ -0,0 +1,12 @@ +/// +////interface Gen { +//// x: number +//// [|parent|]: Gen; +//// millenial: string; +////} +////let t: Gen; +////var { x, ...rest } = t; +////rest.[|parent|]; +const ranges = test.ranges(); +verify.referencesOf(ranges[0], ranges); +verify.referencesOf(ranges[1], ranges); diff --git a/tests/cases/fourslash/formatVariableDeclarationList.ts b/tests/cases/fourslash/formatVariableDeclarationList.ts index 37392d38c62..089eceb1684 100644 --- a/tests/cases/fourslash/formatVariableDeclarationList.ts +++ b/tests/cases/fourslash/formatVariableDeclarationList.ts @@ -37,4 +37,4 @@ verify.currentLineContentIs(" x = 'Foo';"); goTo.marker("11"); verify.currentLineContentIs(" return fun;"); goTo.marker("12"); -verify.currentLineContentIs(" } (fun1));"); +verify.currentLineContentIs(" }(fun1));"); \ No newline at end of file diff --git a/tests/cases/fourslash/formatWithTabs.ts b/tests/cases/fourslash/formatWithTabs.ts new file mode 100644 index 00000000000..c33808bd26a --- /dev/null +++ b/tests/cases/fourslash/formatWithTabs.ts @@ -0,0 +1,16 @@ +/// + +////const foo = [ +//// 1 +////]; + +const options = format.copyFormatOptions(); +options.IndentSize = 2; +options.TabSize = 2; +options.ConvertTabsToSpaces = false; +format.setFormatOptions(options); +format.document(); +verify.currentFileContentIs( +`const foo = [ + 1 +];`); \ No newline at end of file diff --git a/tests/cases/fourslash/formatWithTabs2.ts b/tests/cases/fourslash/formatWithTabs2.ts new file mode 100644 index 00000000000..cda82b9cf80 --- /dev/null +++ b/tests/cases/fourslash/formatWithTabs2.ts @@ -0,0 +1,16 @@ +/// + +////const foo = [ +//// 1 +////]; + +const options = format.copyFormatOptions(); +options.IndentSize = 2; +options.TabSize = 2; +options.ConvertTabsToSpaces = false; +format.setFormatOptions(options); +format.document(); +verify.currentFileContentIs( +`const foo = [ + 1 +];`); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingJsxElements.ts b/tests/cases/fourslash/formattingJsxElements.ts index 2b3b396ed4c..a27bc809456 100644 --- a/tests/cases/fourslash/formattingJsxElements.ts +++ b/tests/cases/fourslash/formattingJsxElements.ts @@ -72,6 +72,8 @@ ////) ;/*closingParenInJsxElement2*/ ////;/*jsxExpressionSpaces*/ ////;/*jsxExpressionSpaces2*/ +//// {}}/*jsxExpressionSpaces3*/ +/////>;/*jsxDanglingSelfClosingToken*/ format.document(); goTo.marker("autoformat"); @@ -120,8 +122,7 @@ goTo.marker("expressionIndent"); verify.indentationIs(12); goTo.marker("danglingBracketAutoformat") -// TODO: verify.currentLineContentIs(" >"); -verify.currentLineContentIs(" >"); +verify.currentLineContentIs(" >"); goTo.marker("closingTagAutoformat"); verify.currentLineContentIs("
"); @@ -145,4 +146,8 @@ verify.currentLineContentIs(") ;"); goTo.marker("jsxExpressionSpaces"); verify.currentLineContentIs(";"); goTo.marker("jsxExpressionSpaces2"); -verify.currentLineContentIs(";"); \ No newline at end of file +verify.currentLineContentIs(";"); +goTo.marker("jsxExpressionSpaces3"); +verify.currentLineContentIs(" { }}"); +goTo.marker("jsxDanglingSelfClosingToken"); +verify.currentLineContentIs("/>;"); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingMappedType.ts b/tests/cases/fourslash/formattingMappedType.ts new file mode 100644 index 00000000000..a33d948a9c3 --- /dev/null +++ b/tests/cases/fourslash/formattingMappedType.ts @@ -0,0 +1,12 @@ +/// + +/////*generic*/type t < T > = { +/////*map*/ [ P in keyof T ] : T [ P ] +////}; + + +format.document(); +goTo.marker("generic"); +verify.currentLineContentIs("type t = {"); +goTo.marker("map"); +verify.currentLineContentIs(" [P in keyof T]: T[P]"); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingOptionsChange.ts b/tests/cases/fourslash/formattingOptionsChange.ts index 63d51eec0ca..0e731412ede 100644 --- a/tests/cases/fourslash/formattingOptionsChange.ts +++ b/tests/cases/fourslash/formattingOptionsChange.ts @@ -1,33 +1,34 @@ /// -/////*InsertSpaceAfterCommaDelimiter*/[1,2, 3];[ 72 , ]; -/////*InsertSpaceAfterSemicolonInForStatements*/for (i = 0;i; i++); -/////*InsertSpaceBeforeAndAfterBinaryOperators*/1+2- 3 -/////*InsertSpaceAfterKeywordsInControlFlowStatements*/if (true) { } -/////*InsertSpaceAfterFunctionKeywordForAnonymousFunctions*/(function () { }) -/////*InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis*/(1 ) -/////*InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets*/[1 ]; [ ]; []; [,]; -/////*InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces*/`${1}`;`${ 1 }` -/////*InsertSpaceAfterTypeAssertion*/const bar = Thing.getFoo(); -/////*PlaceOpenBraceOnNewLineForFunctions*/class foo { +/////*insertSpaceAfterCommaDelimiter*/[1,2, 3];[ 72 , ]; +/////*insertSpaceAfterSemicolonInForStatements*/for (i = 0;i; i++); +/////*insertSpaceBeforeAndAfterBinaryOperators*/1+2- 3 +/////*insertSpaceAfterKeywordsInControlFlowStatements*/if (true) { } +/////*insertSpaceAfterFunctionKeywordForAnonymousFunctions*/(function () { }) +/////*insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis*/(1 ) +/////*insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets*/[1 ]; [ ]; []; [,]; +/////*insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces*/`${1}`;`${ 1 }` +/////*insertSpaceAfterTypeAssertion*/const bar = Thing.getFoo(); +/////*placeOpenBraceOnNewLineForFunctions*/class foo { ////} -/////*PlaceOpenBraceOnNewLineForControlBlocks*/if (true) { +/////*placeOpenBraceOnNewLineForControlBlocks*/if (true) { ////} -/////*InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces*/{ var t = 1}; +/////*insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces*/{ var t = 1}; var {a,b } = { a: 'sw', b:'r' };function f( { a, b}) { } -runTest("InsertSpaceAfterCommaDelimiter", "[1, 2, 3];[72,];", "[1,2,3];[72,];"); -runTest("InsertSpaceAfterSemicolonInForStatements", "for (i = 0; i; i++);", "for (i = 0;i;i++);"); -runTest("InsertSpaceBeforeAndAfterBinaryOperators", "1 + 2 - 3", "1+2-3"); -runTest("InsertSpaceAfterKeywordsInControlFlowStatements", "if (true) { }", "if(true) { }"); -runTest("InsertSpaceAfterFunctionKeywordForAnonymousFunctions", "(function () { })", "(function() { })"); -runTest("InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", " ( 1 )", " (1)"); -runTest("InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", "[ 1 ];[];[];[ , ];", "[1];[];[];[,];"); -runTest("InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", "`${ 1 }`; `${ 1 }`", "`${1}`; `${1}`"); -runTest("InsertSpaceAfterTypeAssertion", "const bar = Thing.getFoo();", "const bar = Thing.getFoo();"); -runTest("PlaceOpenBraceOnNewLineForFunctions", "class foo", "class foo {"); -runTest("PlaceOpenBraceOnNewLineForControlBlocks", "if ( true )", "if ( true ) {"); -runTest("InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", "{ var t = 1 };", "{var t = 1};"); +const defaultFormatOption = format.copyFormatOptions(); +runTest("insertSpaceAfterCommaDelimiter", "[1, 2, 3];[72,];", "[1,2,3];[72,];"); +runTest("insertSpaceAfterSemicolonInForStatements", "for (i = 0; i; i++);", "for (i = 0;i;i++);"); +runTest("insertSpaceBeforeAndAfterBinaryOperators", "1 + 2 - 3", "1+2-3"); +runTest("insertSpaceAfterKeywordsInControlFlowStatements", "if (true) { }", "if(true) { }"); +runTest("insertSpaceAfterFunctionKeywordForAnonymousFunctions", "(function () { })", "(function() { })"); +runTest("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", " ( 1 )", " (1)"); +runTest("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", "[ 1 ];[];[];[ , ];", "[1];[];[];[,];"); +runTest("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", "`${ 1 }`; `${ 1 }`", "`${1}`; `${1}`"); +runTest("insertSpaceAfterTypeAssertion", "const bar = Thing.getFoo();", "const bar = Thing.getFoo();"); +runTest("placeOpenBraceOnNewLineForFunctions", "class foo", "class foo {"); +runTest("placeOpenBraceOnNewLineForControlBlocks", "if (true)", "if (true) {"); +runTest("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", "{ var t = 1 }; var { a, b } = { a: 'sw', b: 'r' }; function f({ a, b }) { }", "{var t = 1}; var {a, b} = {a: 'sw', b: 'r'}; function f({a, b}) {}"); function runTest(propertyName: string, expectedStringWhenTrue: string, expectedStringWhenFalse: string) { // Go to the correct file @@ -52,4 +53,6 @@ function runTest(propertyName: string, expectedStringWhenTrue: string, expectedS // Verify goTo.marker(propertyName); verify.currentLineContentIs(expectedStringWhenTrue); + + format.setOption(propertyName, defaultFormatOption[propertyName]) } \ No newline at end of file diff --git a/tests/cases/fourslash/formattingReadonly.ts b/tests/cases/fourslash/formattingReadonly.ts new file mode 100644 index 00000000000..e9ec9860032 --- /dev/null +++ b/tests/cases/fourslash/formattingReadonly.ts @@ -0,0 +1,12 @@ +/// + +////class C { +//// readonly property1 {};/*1*/ +//// public readonly property2 {};/*2*/ +////} + +format.document(); +goTo.marker("1"); +verify.currentLineContentIs(" readonly property1 {};"); +goTo.marker("2"); +verify.currentLineContentIs(" public readonly property2 {};"); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingSpaceBeforeCloseParen.ts b/tests/cases/fourslash/formattingSpaceBeforeCloseParen.ts new file mode 100644 index 00000000000..fb2d648e211 --- /dev/null +++ b/tests/cases/fourslash/formattingSpaceBeforeCloseParen.ts @@ -0,0 +1,33 @@ +/// + +/////*1*/({}); +/////*2*/( {}); +/////*3*/({foo:42}); +/////*4*/( {foo:42} ); +/////*5*/var bar = (function (a) { }); + +format.setOption("InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", true); +format.document(); +goTo.marker('1'); +verify.currentLineContentIs('( {} );'); +goTo.marker('2'); +verify.currentLineContentIs('( {} );'); +goTo.marker('3'); +verify.currentLineContentIs('( { foo: 42 } );'); +goTo.marker('4'); +verify.currentLineContentIs('( { foo: 42 } );'); +goTo.marker('5'); +verify.currentLineContentIs('var bar = ( function( a ) { } );'); + +format.setOption("InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", false); +format.document(); +goTo.marker('1'); +verify.currentLineContentIs('({});'); +goTo.marker('2'); +verify.currentLineContentIs('({});'); +goTo.marker('3'); +verify.currentLineContentIs('({ foo: 42 });'); +goTo.marker('4'); +verify.currentLineContentIs('({ foo: 42 });'); +goTo.marker('5'); +verify.currentLineContentIs('var bar = (function(a) { });'); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts b/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts new file mode 100644 index 00000000000..ce85521879e --- /dev/null +++ b/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts @@ -0,0 +1,19 @@ +/// + +/////*1*/function foo() { } +/////*2*/function boo () { } +/////*3*/var bar = function foo() { }; +/////*4*/var foo = { bar() { } }; + +format.setOption("InsertSpaceBeforeFunctionParenthesis", true); + +format.document(); + +goTo.marker('1'); +verify.currentLineContentIs('function foo () { }'); +goTo.marker('2'); +verify.currentLineContentIs('function boo () { }'); +goTo.marker('3'); +verify.currentLineContentIs('var bar = function foo () { };'); +goTo.marker('4'); +verify.currentLineContentIs('var foo = { bar () { } };'); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingSpacesAfterConstructor.ts b/tests/cases/fourslash/formattingSpacesAfterConstructor.ts index 8df762def20..2195d74adbc 100644 --- a/tests/cases/fourslash/formattingSpacesAfterConstructor.ts +++ b/tests/cases/fourslash/formattingSpacesAfterConstructor.ts @@ -3,4 +3,11 @@ /////*1*/class test { constructor () { } } format.document(); goTo.marker("1"); -verify.currentLineContentIs("class test { constructor() { } }"); \ No newline at end of file +verify.currentLineContentIs("class test { constructor() { } }"); + +/////*2*/class test { constructor () { } } +format.setOption("InsertSpaceAfterConstructor", true); + +format.document(); +goTo.marker("2"); +verify.currentLineContentIs("class test { constructor () { } }"); \ No newline at end of file diff --git a/tests/cases/fourslash/forwardReference.ts b/tests/cases/fourslash/forwardReference.ts index 3c2e2c6393c..355eda9113c 100644 --- a/tests/cases/fourslash/forwardReference.ts +++ b/tests/cases/fourslash/forwardReference.ts @@ -9,4 +9,4 @@ ////} goTo.marker(); -verify.memberListContains('n'); +verify.completionListContains('n'); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 0a72d295295..63b38c337d7 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -121,13 +121,11 @@ declare namespace FourSlashInterface { private negative; not: verifyNegatable; constructor(negative?: boolean); - memberListContains(symbol: string, text?: string, documenation?: string, kind?: string): void; - memberListCount(expectedCount: number): void; + completionListCount(expectedCount: number): void; completionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number): void; completionListItemsCountIsGreaterThan(count: number): void; completionListIsEmpty(): void; completionListAllowsNewIdentifier(): void; - memberListIsEmpty(): void; signatureHelpPresent(): void; errorExistsBetweenMarkers(startMarker: string, endMarker: string): void; errorExistsAfterMarker(markerName?: string): void; @@ -194,6 +192,7 @@ declare namespace FourSlashInterface { currentSignatureHelpDocCommentIs(docComment: string): void; signatureHelpCountIs(expected: number): void; signatureHelpArgumentCountIs(expected: number): void; + signatureHelpCurrentArgumentListIsVariadic(expected: boolean); currentSignatureParameterCountIs(expected: number): void; currentSignatureTypeParameterCountIs(expected: number): void; currentSignatureHelpIs(expected: string): void; @@ -210,6 +209,7 @@ declare namespace FourSlashInterface { DocCommentTemplate(expectedText: string, expectedOffset: number, empty?: boolean): void; noDocCommentTemplate(): void; codeFixAtPosition(expectedText: string, errorCode?: number): void; + importFixAtPosition(expectedTextArray: string[], errorCode?: number): void; navigationBar(json: any): void; navigationTree(json: any): void; @@ -277,7 +277,6 @@ declare namespace FourSlashInterface { printCurrentFileStateWithoutCaret(): void; printCurrentQuickInfo(): void; printCurrentSignatureHelp(): void; - printMemberListMembers(): void; printCompletionListMembers(): void; printBreakpointLocation(pos: number): void; printBreakpointAtCurrentLocation(): void; @@ -295,9 +294,7 @@ declare namespace FourSlashInterface { setFormatOptions(options: FormatCodeOptions): any; selection(startMarker: string, endMarker: string): void; onType(posMarker: string, key: string): void; - setOption(name: string, value: number): any; - setOption(name: string, value: string): any; - setOption(name: string, value: boolean): any; + setOption(name: string, value: number | string | boolean): void; } class cancellation { resetCancelled(): void; diff --git a/tests/cases/fourslash/functionTypes.ts b/tests/cases/fourslash/functionTypes.ts index 8973f73431b..813dfa8cdcb 100644 --- a/tests/cases/fourslash/functionTypes.ts +++ b/tests/cases/fourslash/functionTypes.ts @@ -23,7 +23,7 @@ verify.numberOfErrorsInCurrentFile(0); for (var i = 1; i <= 7; i++) { goTo.marker('' + i); - verify.memberListCount(7); + verify.completionListCount(8); verify.completionListContains('apply'); verify.completionListContains('arguments'); verify.completionListContains('bind'); @@ -31,4 +31,5 @@ for (var i = 1; i <= 7; i++) { verify.completionListContains('length'); verify.completionListContains('caller'); verify.completionListContains('prototype'); + verify.completionListContains('toString'); } diff --git a/tests/cases/fourslash/getJavaScriptCompletions20.ts b/tests/cases/fourslash/getJavaScriptCompletions20.ts index d254705bb91..3ca27fa288a 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions20.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions20.ts @@ -18,4 +18,4 @@ //// Person.getNa/**/ = 10; goTo.marker(); -verify.not.memberListContains('getNa'); +verify.not.completionListContains('getNa'); diff --git a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts index 09ac27ce595..958dec3765d 100644 --- a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts +++ b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts @@ -21,9 +21,9 @@ goTo.marker('1'); edit.insert('.'); -verify.memberListContains('toFixed', undefined, undefined, 'method'); +verify.completionListContains('toFixed', undefined, undefined, 'method'); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.memberListContains('substr', undefined, undefined, 'method'); +verify.completionListContains('substr', undefined, undefined, 'method'); diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics1.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics1.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics1.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics1.ts index a94318c84fd..8c151742b75 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics1.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics1.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// import a = b; -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'import ... =' can only be used in a .ts file.", "start": 0, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics10.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics10.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics10.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics10.ts index 957357fc2c1..206c1a6e2cf 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics10.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics10.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// function F() { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'type parameter declarations' can only be used in a .ts file.", "start": 11, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics11.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics11.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics11.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics11.ts index d9c16fca651..d9b1d35b5c6 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics11.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics11.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// function F(): number { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'types' can only be used in a .ts file.", "start": 14, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics12.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics12.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics12.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics12.ts index b4dcf076743..cf244f7cfa2 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics12.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics12.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// declare var v; -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'declare' can only be used in a .ts file.", "start": 0, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics13.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics13.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics13.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics13.ts index a20bccc0887..aaf3289fcfe 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics13.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics13.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// var v: () => number; -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'types' can only be used in a .ts file.", "start": 7, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics14.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics14.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics14.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics14.ts index 4f7673be384..a41d88dd675 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics14.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics14.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// Foo(); -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'type arguments' can only be used in a .ts file.", "start": 4, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics15.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics15.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics15.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics15.ts index f7cd4db3626..93430a9a004 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics15.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics15.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// function F(public p) { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'parameter modifiers' can only be used in a .ts file.", "start": 11, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics16.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics16.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics16.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics16.ts index cd19bd580cc..60e0684b106 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics16.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics16.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// function F(p?) { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'?' can only be used in a .ts file.", "start": 12, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics17.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics17.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics17.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics17.ts index 5a1ec6d92cf..3a57917b2ac 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics17.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics17.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// function F(a: number) { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'types' can only be used in a .ts file.", "start": 14, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics18.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics18.ts similarity index 86% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics18.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics18.ts index 707d1537fc5..d253cb63611 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics18.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics18.ts @@ -9,7 +9,7 @@ ////} goTo.file("a.js"); -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "\'public\' can only be used in a .ts file.", "start": 93, @@ -25,7 +25,7 @@ verify.getSemanticDiagnostics(`[ ////} goTo.file("b.js"); -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'types' can only be used in a .ts file.", "start": 17, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics19.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics19.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics19.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics19.ts index a7fbe3e0ecc..7729a6ea470 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics19.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics19.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// enum E { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'enum declarations' can only be used in a .ts file.", "start": 5, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics2.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics2.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics2.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics2.ts index 9ab29b41798..74e6a9ab089 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics2.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics2.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// export = b; -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'export=' can only be used in a .ts file.", "start": 0, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics21.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics21.ts similarity index 100% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics21.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics21.ts diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics22.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics22.ts similarity index 100% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics22.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics22.ts diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics23.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics23.ts similarity index 100% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics23.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics23.ts diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics24.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics24.ts similarity index 100% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics24.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics24.ts diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics3.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics3.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics3.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics3.ts index 3aff51d881b..3528f333329 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics3.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics3.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// class C { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'type parameter declarations' can only be used in a .ts file.", "start": 8, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics4.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics4.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics4.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics4.ts index 99319b047e6..3b849b08ae0 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics4.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics4.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// public class C { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'public' can only be used in a .ts file.", "start": 0, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics5.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics5.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics5.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics5.ts index 18df3500bd9..985e3284025 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics5.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics5.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// class C implements D { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'implements clauses' can only be used in a .ts file.", "start": 8, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics6.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics6.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics6.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics6.ts index e18f8f9be52..a0042a0529b 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics6.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics6.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// interface I { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'interface declarations' can only be used in a .ts file.", "start": 10, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics7.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics7.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics7.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics7.ts index 32cad0e5a07..64216d1e364 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics7.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics7.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// module M { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'module declarations' can only be used in a .ts file.", "start": 7, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics8.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics8.ts similarity index 83% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics8.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics8.ts index 562f42124ae..296f4f7445e 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics8.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics8.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// type a = b; -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'type aliases' can only be used in a .ts file.", "start": 5, diff --git a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics9.ts b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics9.ts similarity index 84% rename from tests/cases/fourslash/getJavaScriptSemanticDiagnostics9.ts rename to tests/cases/fourslash/getJavaScriptSyntacticDiagnostics9.ts index 4c531b5255b..f2c20a52ee9 100644 --- a/tests/cases/fourslash/getJavaScriptSemanticDiagnostics9.ts +++ b/tests/cases/fourslash/getJavaScriptSyntacticDiagnostics9.ts @@ -4,7 +4,7 @@ // @Filename: a.js //// public function F() { } -verify.getSemanticDiagnostics(`[ +verify.getSyntacticDiagnostics(`[ { "message": "'public' can only be used in a .ts file.", "start": 0, diff --git a/tests/cases/fourslash/goToDefinitionObjectSpread.ts b/tests/cases/fourslash/goToDefinitionObjectSpread.ts new file mode 100644 index 00000000000..b23d0a80448 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionObjectSpread.ts @@ -0,0 +1,9 @@ +/// + +////interface A1 { /*1*/a: number }; +////interface A2 { /*2*/a?: number }; +////let a1: A1; +////let a2: A2; +////let a12 = { ...a1, ...a2 }; +////a12.a/*3*/; +verify.goToDefinition('3', [ '1', '2' ]); diff --git a/tests/cases/fourslash/goToDefinitionRest.ts b/tests/cases/fourslash/goToDefinitionRest.ts new file mode 100644 index 00000000000..1459b9ffa88 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionRest.ts @@ -0,0 +1,12 @@ + +/// +////interface Gen { +//// x: number; +//// /*1*/parent: Gen; +//// millenial: string; +////} +////let t: Gen; +////var { x, ...rest } = t; +////rest./*2*/parent; +const ranges = test.ranges(); +verify.goToDefinition('2', [ '1' ]); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport0.ts b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts new file mode 100644 index 00000000000..5e5be220688 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport0.ts @@ -0,0 +1,10 @@ +/// + +//// import [|{ v1 }|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport1.ts b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts new file mode 100644 index 00000000000..9571d0fcf57 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport1.ts @@ -0,0 +1,11 @@ +/// + +//// import d, [|{ v1 }|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export default var d1 = 6; + +verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport10.ts b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts new file mode 100644 index 00000000000..25246e70123 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport10.ts @@ -0,0 +1,21 @@ +/// + +//// import [|{ +//// v1, +//// v2 +//// }|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export var v2 = 5; +//// export var v3 = 5; + +verify.importFixAtPosition([ +`{ + v1, + v2, +f1 +}` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport11.ts b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts new file mode 100644 index 00000000000..304ffb896df --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport11.ts @@ -0,0 +1,20 @@ +/// + +////import [|{ +//// v1, v2, +//// v3 +////}|] from "./module"; +////f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export var v2 = 5; +//// export var v3 = 5; + +verify.importFixAtPosition([ +`{ + v1, v2, + v3, f1 +}` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport12.ts b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts new file mode 100644 index 00000000000..e00dee504c5 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport12.ts @@ -0,0 +1,12 @@ +/// + +//// import [|{}|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export var v2 = 5; +//// export var v3 = 5; + +verify.importFixAtPosition([`{ f1 }`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts new file mode 100644 index 00000000000..6a92976f4ef --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts @@ -0,0 +1,16 @@ +/// + +//// [|import * as ns from "./module"; +//// f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import * as ns from "./module"; +import { f1 } from "./module"; +f1();`, +`import * as ns from "./module"; +ns.f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport3.ts b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts new file mode 100644 index 00000000000..bc00e8d420a --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport3.ts @@ -0,0 +1,18 @@ +/// + +//// [|import d, * as ns from "./module" ; +//// f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export default var d1 = 6; + +// Test with some extra spaces before the semicolon +verify.importFixAtPosition([ +`import d, * as ns from "./module" ; +ns.f1();`, +`import d, * as ns from "./module" ; +import { f1 } from "./module"; +f1();`, +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport4.ts b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts new file mode 100644 index 00000000000..d93cb73664e --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport4.ts @@ -0,0 +1,14 @@ +/// + +//// [|import d from "./module"; +//// f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export default var d1 = 6; + +verify.importFixAtPosition([ +`import d, { f1 } from "./module"; +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport5.ts b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts new file mode 100644 index 00000000000..ed9297124d9 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport5.ts @@ -0,0 +1,12 @@ +/// + +//// [|import "./module"; +//// f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([`import "./module"; +import { f1 } from "./module"; +f1();`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport6.ts b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts new file mode 100644 index 00000000000..7ae157a51ce --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport6.ts @@ -0,0 +1,13 @@ +/// + +//// import [|{ v1 }|] from "fake-module"; +//// f1/*0*/(); + +// @Filename: ../package.json +//// { "dependencies": { "fake-module": "latest" } } + +// @Filename: ../node_modules/fake-module/index.ts +//// export var v1 = 5; +//// export function f1(); + +verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport7.ts b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts new file mode 100644 index 00000000000..249929eabc7 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport7.ts @@ -0,0 +1,10 @@ +/// + +//// import [|{ v1 }|] from "../other_dir/module"; +//// f1/*0*/(); + +// @Filename: ../other_dir/module.ts +//// export var v1 = 5; +//// export function f1(); + +verify.importFixAtPosition([`{ v1, f1 }`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport8.ts b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts new file mode 100644 index 00000000000..da7beaa0a47 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport8.ts @@ -0,0 +1,12 @@ +/// + +//// import [|{v1, v2, v3,}|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; +//// export var v2 = 5; +//// export var v3 = 5; + +verify.importFixAtPosition([`{v1, v2, v3, f1,}`]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport9.ts b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts new file mode 100644 index 00000000000..05d17927454 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImport9.ts @@ -0,0 +1,17 @@ +/// + +//// import [|{ +//// v1 +//// }|] from "./module"; +//// f1/*0*/(); + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`{ + v1, +f1 +}` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts new file mode 100644 index 00000000000..f431e6356d1 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixExistingImportEquals0.ts @@ -0,0 +1,18 @@ +/// + +//// [|import ns = require("ambient-module"); +//// var x = v1/*0*/ + 5;|] + +// @Filename: ambientModule.ts +//// declare module "ambient-module" { +//// export function f1(); +//// export var v1; +//// } + +verify.importFixAtPosition([ +`import ns = require("ambient-module"); +var x = ns.v1 + 5;`, +`import ns = require("ambient-module"); +import { v1 } from "ambient-module"; +var x = v1 + 5;`, +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts new file mode 100644 index 00000000000..1d7b5bc3e7f --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient0.ts @@ -0,0 +1,15 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: ambientModule.ts +//// declare module "ambient-module" { +//// export function f1(); +//// export var v1; +//// } + +verify.importFixAtPosition([ +`import { f1 } from "ambient-module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts new file mode 100644 index 00000000000..60504c89711 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient1.ts @@ -0,0 +1,28 @@ +/// + +//// import d from "other-ambient-module"; +//// [|import * as ns from "yet-another-ambient-module"; +//// var x = v1/*0*/ + 5;|] + +// @Filename: ambientModule.ts +//// declare module "ambient-module" { +//// export function f1(); +//// export var v1; +//// } + +// @Filename: otherAmbientModule.ts +//// declare module "other-ambient-module" { +//// export default function f2(); +//// } + +// @Filename: yetAnotherAmbientModule.ts +//// declare module "yet-another-ambient-module" { +//// export function f3(); +//// export var v3; +//// } + +verify.importFixAtPosition([ +`import * as ns from "yet-another-ambient-module"; +import { v1 } from "ambient-module"; +var x = v1 + 5;` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts new file mode 100644 index 00000000000..999da4bffbb --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient2.ts @@ -0,0 +1,21 @@ +/// + +////[|/* +//// * I'm a license or something +//// */ +////f1/*0*/();|] + +// @Filename: ambientModule.ts +//// declare module "ambient-module" { +//// export function f1(); +//// export var v1; +//// } + +verify.importFixAtPosition([ +`/* + * I'm a license or something + */ +import { f1 } from "ambient-module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts new file mode 100644 index 00000000000..648293cce2e --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportAmbient3.ts @@ -0,0 +1,30 @@ +/// + +//// let a = "I am a non-trivial statement that appears before imports"; +//// import d from "other-ambient-module" +//// [|import * as ns from "yet-another-ambient-module" +//// var x = v1/*0*/ + 5;|] + +// @Filename: ambientModule.ts +//// declare module "ambient-module" { +//// export function f1(); +//// export var v1; +//// } + +// @Filename: otherAmbientModule.ts +//// declare module "other-ambient-module" { +//// export default function f2(); +//// } + +// @Filename: yetAnotherAmbientModule.ts +//// declare module "yet-another-ambient-module" { +//// export function f3(); +//// export var v3; +//// } + +// test cases when there are no semicolons at the line end +verify.importFixAtPosition([ +`import * as ns from "yet-another-ambient-module" +import { v1 } from "ambient-module"; +var x = v1 + 5;` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts new file mode 100644 index 00000000000..e15c2cf4399 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts @@ -0,0 +1,19 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "baseUrl": "./a" +//// } +//// } + +// @Filename: a/b.ts +//// export function f1() { }; + +verify.importFixAtPosition([ +`import { f1 } from "b"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts new file mode 100644 index 00000000000..3efe023e922 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportDefault0.ts @@ -0,0 +1,12 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: module.ts +//// export default function f1() { }; + +verify.importFixAtPosition([ +`import f1 from "./module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts new file mode 100644 index 00000000000..2372110437a --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile0.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +verify.importFixAtPosition([ +`import { f1 } from "./module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts new file mode 100644 index 00000000000..0223d96e018 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile1.ts @@ -0,0 +1,18 @@ +/// + +//// [|/// +//// f1/*0*/();|] + +// @Filename: module.ts +//// export function f1() {} +//// export var v1 = 5; + +// @Filename: tripleSlashReference.ts +//// var x = 5;/*dummy*/ + +verify.importFixAtPosition([ +`/// +import { f1 } from "./module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts new file mode 100644 index 00000000000..ca9330e9846 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile2.ts @@ -0,0 +1,13 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: ../../other_dir/module.ts +//// export var v1 = 5; +//// export function f1(); + +verify.importFixAtPosition([ +`import { f1 } from "../../other_dir/module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules0.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules0.ts new file mode 100644 index 00000000000..6013f865ddf --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules0.ts @@ -0,0 +1,19 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: ../package.json +//// { "dependencies": { "fake-module": "latest" } } + +// @Filename: ../node_modules/fake-module/index.ts +//// export var v1 = 5; +//// export function f1(); + +// @Filename: ../node_modules/fake-module/package.json +//// {} + +verify.importFixAtPosition([ +`import { f1 } from "fake-module"; + +f1();` +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts new file mode 100644 index 00000000000..6bffe41b27a --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules1.ts @@ -0,0 +1,16 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: ../package.json +//// { "dependencies": { "fake-module": "latest" } } + +// @Filename: ../node_modules/fake-module/nested.ts +//// export var v1 = 5; +//// export function f1(); + +verify.importFixAtPosition([ +`import { f1 } from "fake-module/nested"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts new file mode 100644 index 00000000000..ff48fbe182c --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules2.ts @@ -0,0 +1,25 @@ +/// + +//// [|f1/*0*/();|] + +// @Filename: ../package.json +//// { "dependencies": { "fake-module": "latest" } } + +// @Filename: ../node_modules/fake-module/notindex.d.ts +//// export var v1 = 5; +//// export function f1(); + +// @Filename: ../node_modules/fake-module/notindex.js +//// module.exports = { +//// v1: 5, +//// f1: function () {} +//// }; + +// @Filename: ../node_modules/fake-module/package.json +//// { "main":"./notindex.js", "typings":"./notindex.d.ts" } + +verify.importFixAtPosition([ +`import { f1 } from "fake-module"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts new file mode 100644 index 00000000000..b1143cb4b41 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules3.ts @@ -0,0 +1,14 @@ +/// + +// @Filename: /a.ts +//// [|f1/*0*/();|] + +// @Filename: /node_modules/@types/random/index.d.ts +//// export var v1 = 5; +//// export function f1(); + +verify.importFixAtPosition([ +`import { f1 } from "random"; + +f1();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts new file mode 100644 index 00000000000..93cd6f92ef5 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths0.ts @@ -0,0 +1,22 @@ +/// + +//// [|foo/*0*/();|] + +// @Filename: folder_a/f2.ts +//// export function foo() {}; + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "baseUrl": ".", +//// "paths": { +//// "a": [ "folder_a/f2" ] +//// } +//// } +//// } + +verify.importFixAtPosition([ +`import { foo } from "a"; + +foo();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts new file mode 100644 index 00000000000..bb0f1e6705a --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportPaths1.ts @@ -0,0 +1,22 @@ +/// + +//// [|foo/*0*/();|] + +// @Filename: folder_b/f2.ts +//// export function foo() {}; + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "baseUrl": ".", +//// "paths": { +//// "b/*": [ "folder_b/*" ] +//// } +//// } +//// } + +verify.importFixAtPosition([ +`import { foo } from "b/f2"; + +foo();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts new file mode 100644 index 00000000000..ae8ef03ccac --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportRootDirs0.ts @@ -0,0 +1,23 @@ +/// + +// @Filename: a/f1.ts +//// [|foo/*0*/();|] + +// @Filename: b/c/f2.ts +//// export function foo() {}; + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "rootDirs": [ +//// "a", +//// "b/c" +//// ] +//// } +//// } + +verify.importFixAtPosition([ +`import { foo } from "./f2"; + +foo();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts new file mode 100644 index 00000000000..a6eb6a90759 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts @@ -0,0 +1,22 @@ +/// + +// @Filename: a/f1.ts +//// [|foo/*0*/();|] + +// @Filename: types/random/index.ts +//// export function foo() {}; + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "typeRoots": [ +//// "./types" +//// ] +//// } +//// } + +verify.importFixAtPosition([ +`import { foo } from "random"; + +foo();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts new file mode 100644 index 00000000000..30b482a94d7 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts @@ -0,0 +1,20 @@ +/// + +// @Filename: a/f1.ts +//// [|import * as ns from "./foo"; +//// foo/*0*/();|] + +// @Filename: a/foo/bar.ts +//// export function foo() {}; + +// @Filename: a/foo.ts +//// export { foo } from "./foo/bar"; + +verify.importFixAtPosition([ +`import * as ns from "./foo"; +import { foo } from "./foo"; +foo();`, + +`import * as ns from "./foo"; +ns.foo();`, +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts new file mode 100644 index 00000000000..343b0692260 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts @@ -0,0 +1,20 @@ +/// + +// @Filename: a/f1.ts +//// [|foo/*0*/();|] + +// @Filename: a/node_modules/bar/index.ts +//// export function foo() {}; + +// @Filename: a/foo.ts +//// export { foo } from "bar"; + +verify.importFixAtPosition([ +`import { foo } from "./foo"; + +foo();`, + +`import { foo } from "bar"; + +foo();`, +]); \ No newline at end of file diff --git a/tests/cases/fourslash/incorrectJsDocObjectLiteralType.ts b/tests/cases/fourslash/incorrectJsDocObjectLiteralType.ts new file mode 100644 index 00000000000..ddf65ec0e8a --- /dev/null +++ b/tests/cases/fourslash/incorrectJsDocObjectLiteralType.ts @@ -0,0 +1,8 @@ +/// + +//// /**/ + +goTo.marker(); +verify.navigationItemsListCount(0, "foo", "exact"); +edit.insert("/**\n * @typedef {Object} foo\n * @property {any} [obj]\n */\nexport default function foo() {\n}"); +verify.navigationItemsListContains("foo", "function", "foo", "exact"); diff --git a/tests/cases/fourslash/indentationWithBaseIndent.ts b/tests/cases/fourslash/indentationWithBaseIndent.ts index 53ee01c9a3c..112ce225d01 100644 --- a/tests/cases/fourslash/indentationWithBaseIndent.ts +++ b/tests/cases/fourslash/indentationWithBaseIndent.ts @@ -205,7 +205,6 @@ //// function unterminatedListIndentation(a, ////{| "indent": 14 , "baseIndentSize": 10 |} -debugger; test.markers().forEach(marker => { verify.indentationAtPositionIs(marker.fileName, marker.position, marker.data.indent, ts.IndentStyle.Smart, marker.data.baseIndentSize); }); diff --git a/tests/cases/fourslash/javaScriptModules13.ts b/tests/cases/fourslash/javaScriptModules13.ts index bcf263a4b8c..5e3eead3b6c 100644 --- a/tests/cases/fourslash/javaScriptModules13.ts +++ b/tests/cases/fourslash/javaScriptModules13.ts @@ -23,6 +23,6 @@ verify.completionListContains('y'); verify.not.completionListContains('invisible'); edit.insert('x.'); -verify.memberListContains('a', undefined, undefined, 'property'); +verify.completionListContains('a', undefined, undefined, 'property'); edit.insert('a.'); -verify.memberListContains('toFixed', undefined, undefined, 'method'); +verify.completionListContains('toFixed', undefined, undefined, 'method'); diff --git a/tests/cases/fourslash/javaScriptModules19.ts b/tests/cases/fourslash/javaScriptModules19.ts index 564cbea722f..56ee5a2a2e5 100644 --- a/tests/cases/fourslash/javaScriptModules19.ts +++ b/tests/cases/fourslash/javaScriptModules19.ts @@ -21,6 +21,6 @@ verify.completionListContains('y'); verify.not.completionListContains('invisible'); edit.insert('x.'); -verify.memberListContains('a', undefined, undefined, 'property'); +verify.completionListContains('a', undefined, undefined, 'property'); edit.insert('a.'); -verify.memberListContains('toFixed', undefined, undefined, 'method'); +verify.completionListContains('toFixed', undefined, undefined, 'method'); diff --git a/tests/cases/fourslash/javaScriptPrototype1.ts b/tests/cases/fourslash/javaScriptPrototype1.ts index c9c454cfb2c..8b2d6f3fb84 100644 --- a/tests/cases/fourslash/javaScriptPrototype1.ts +++ b/tests/cases/fourslash/javaScriptPrototype1.ts @@ -22,25 +22,25 @@ // Members of the class instance goTo.marker('1'); edit.insert('.'); -verify.memberListContains('foo', undefined, undefined, 'property'); -verify.memberListContains('bar', undefined, undefined, 'property'); +verify.completionListContains('foo', undefined, undefined, 'property'); +verify.completionListContains('bar', undefined, undefined, 'property'); edit.backspace(); // Members of a class method (1) goTo.marker('2'); edit.insert('.'); -verify.memberListContains('length', undefined, undefined, 'property'); +verify.completionListContains('length', undefined, undefined, 'property'); edit.backspace(); // Members of the invocation of a class method (1) goTo.marker('3'); edit.insert('.'); -verify.memberListContains('toFixed', undefined, undefined, 'method'); -verify.not.memberListContains('substr', undefined, undefined, 'method'); +verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.not.completionListContains('substr', undefined, undefined, 'method'); edit.backspace(); // Members of the invocation of a class method (2) goTo.marker('4'); edit.insert('.'); -verify.memberListContains('substr', undefined, undefined, 'method'); -verify.not.memberListContains('toFixed', undefined, undefined, 'method'); +verify.completionListContains('substr', undefined, undefined, 'method'); +verify.not.completionListContains('toFixed', undefined, undefined, 'method'); diff --git a/tests/cases/fourslash/jsDocAugments.ts b/tests/cases/fourslash/jsDocAugments.ts new file mode 100644 index 00000000000..24458c529fb --- /dev/null +++ b/tests/cases/fourslash/jsDocAugments.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @Filename: dummy.js + +//// /** +//// * @augments {Thing} +//// */ +//// class MyStringThing extends Thing { +//// constructor() { +//// var x = this.mine; +//// x/**/; +//// } +//// } + +// @Filename: declarations.d.ts +//// declare class Thing { +//// mine: T; +//// } + +goTo.marker(); +verify.quickInfoIs("(local var) x: string"); + diff --git a/tests/cases/fourslash/jsDocFunctionSignatures3.ts b/tests/cases/fourslash/jsDocFunctionSignatures3.ts index 3679035d31d..87efaec3308 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures3.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures3.ts @@ -23,10 +23,10 @@ goTo.marker('1'); edit.insert('.'); -verify.memberListContains('substr', undefined, undefined, 'method'); +verify.completionListContains('substr', undefined, undefined, 'method'); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.memberListContains('toFixed', undefined, undefined, 'method'); +verify.completionListContains('toFixed', undefined, undefined, 'method'); edit.backspace(); diff --git a/tests/cases/fourslash/jsDocFunctionSignatures8.ts b/tests/cases/fourslash/jsDocFunctionSignatures8.ts index 3dbe38e34df..6853c70daf2 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures8.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures8.ts @@ -3,6 +3,7 @@ // @Filename: Foo.js /////** //// * Represents a person +//// * a b multiline test //// * @constructor //// * @param {string} name The name of the person //// * @param {number} age The age of the person @@ -13,4 +14,4 @@ ////} ////var p = new Pers/**/on(); goTo.marker(); -verify.quickInfoIs("function Person(name: string, age: number): void", "Represents a person"); +verify.quickInfoIs("function Person(name: string, age: number): void", "Represents a person\na b multiline test"); diff --git a/tests/cases/fourslash/jsDocGenerics1.ts b/tests/cases/fourslash/jsDocGenerics1.ts index 61358e3f490..e5570937ba4 100644 --- a/tests/cases/fourslash/jsDocGenerics1.ts +++ b/tests/cases/fourslash/jsDocGenerics1.ts @@ -25,10 +25,10 @@ goTo.marker('1'); -verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); goTo.marker('2'); -verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); goTo.marker('3'); -verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); diff --git a/tests/cases/fourslash/jsDocGenerics2.ts b/tests/cases/fourslash/jsDocGenerics2.ts new file mode 100644 index 00000000000..23deb1a6502 --- /dev/null +++ b/tests/cases/fourslash/jsDocGenerics2.ts @@ -0,0 +1,19 @@ +/// +// @allowNonTsExtensions: true +// @Filename: Foo.js + +/////** +//// * @param {T[]} arr +//// * @param {(function(T):T)} valuator +//// * @template T +//// */ +////function SortFilter(arr,valuator) +////{ +//// return arr; +////} +////var a/*1*/ = SortFilter([0, 1, 2], q/*2*/ => q); +////var b/*3*/ = SortFilter([0, 1, 2], undefined); + +verify.quickInfoAt('1', "var a: number[]"); +verify.quickInfoAt('2', '(parameter) q: number'); +verify.quickInfoAt('3', "var b: number[]"); diff --git a/tests/cases/fourslash/jsdocNullableUnion.ts b/tests/cases/fourslash/jsdocNullableUnion.ts index 19dc9818d69..50b929b1912 100644 --- a/tests/cases/fourslash/jsdocNullableUnion.ts +++ b/tests/cases/fourslash/jsdocNullableUnion.ts @@ -14,10 +14,10 @@ ////} goTo.marker('1'); -verify.memberListContains("x"); +verify.completionListContains("x"); goTo.marker('2'); -verify.memberListContains("y"); +verify.completionListContains("y"); goTo.marker('3'); -verify.memberListContains("z"); +verify.completionListContains("z"); diff --git a/tests/cases/fourslash/lambdaThisMembers.ts b/tests/cases/fourslash/lambdaThisMembers.ts index 1e80a5a47df..1a5aa112a6c 100644 --- a/tests/cases/fourslash/lambdaThisMembers.ts +++ b/tests/cases/fourslash/lambdaThisMembers.ts @@ -12,5 +12,5 @@ goTo.marker(); verify.completionListContains("a"); verify.completionListContains("b"); -verify.memberListCount(2); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/memberCompletionFromFunctionCall.ts b/tests/cases/fourslash/memberCompletionFromFunctionCall.ts index 56629a3b510..9bd59e1dc9f 100644 --- a/tests/cases/fourslash/memberCompletionFromFunctionCall.ts +++ b/tests/cases/fourslash/memberCompletionFromFunctionCall.ts @@ -8,5 +8,5 @@ goTo.marker(); edit.insert("."); -verify.not.memberListIsEmpty(); -verify.memberListContains("text"); \ No newline at end of file +verify.not.completionListIsEmpty(); +verify.completionListContains("text"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberCompletionInForEach1.ts b/tests/cases/fourslash/memberCompletionInForEach1.ts index 2af0393283f..b90da43c119 100644 --- a/tests/cases/fourslash/memberCompletionInForEach1.ts +++ b/tests/cases/fourslash/memberCompletionInForEach1.ts @@ -6,11 +6,11 @@ goTo.marker('1'); edit.insert('.'); -verify.memberListContains('trim'); -verify.memberListCount(21); +verify.completionListContains('trim'); +verify.completionListCount(21); edit.insert('});'); // need the following lines to not have parse errors in order for completion list to appear goTo.marker('2'); edit.insert('.'); -verify.memberListContains('trim'); -verify.memberListCount(21); +verify.completionListContains('trim'); +verify.completionListCount(21); diff --git a/tests/cases/fourslash/memberCompletionOnTypeParameters.ts b/tests/cases/fourslash/memberCompletionOnTypeParameters.ts index 6092e1e280a..cc3fc92a31a 100644 --- a/tests/cases/fourslash/memberCompletionOnTypeParameters.ts +++ b/tests/cases/fourslash/memberCompletionOnTypeParameters.ts @@ -14,21 +14,21 @@ ////} goTo.marker("S"); -verify.memberListIsEmpty(); +verify.completionListIsEmpty(); goTo.marker("T"); -verify.memberListContains("x", "(property) IFoo.x: number"); -verify.memberListContains("y", "(property) IFoo.y: string"); -verify.memberListCount(2); +verify.completionListContains("x", "(property) IFoo.x: number"); +verify.completionListContains("y", "(property) IFoo.y: string"); +verify.completionListCount(2); goTo.marker("U"); -verify.memberListContains("toString", "(method) Object.toString(): string"); -verify.memberListCount(7); // constructor, toString, toLocaleString, valueOf, hasOwnProperty, isPrototypeOf, propertyIsEnumerable +verify.completionListContains("toString", "(method) Object.toString(): string"); +verify.completionListCount(7); // constructor, toString, toLocaleString, valueOf, hasOwnProperty, isPrototypeOf, propertyIsEnumerable goTo.marker("V"); -verify.memberListContains("x", "(property) IFoo.x: number"); -verify.memberListContains("y", "(property) IFoo.y: string"); -verify.memberListCount(2); +verify.completionListContains("x", "(property) IFoo.x: number"); +verify.completionListContains("y", "(property) IFoo.y: string"); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts b/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts index e7f6c5c6519..f77a8b0c612 100644 --- a/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts +++ b/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts @@ -17,5 +17,5 @@ goTo.marker(); -verify.memberListContains("foo"); -verify.memberListCount(1); +verify.completionListContains("foo"); +verify.completionListCount(1); diff --git a/tests/cases/fourslash/memberListAfterDoubleDot.ts b/tests/cases/fourslash/memberListAfterDoubleDot.ts index 21a1ad913ea..489e7c3b105 100644 --- a/tests/cases/fourslash/memberListAfterDoubleDot.ts +++ b/tests/cases/fourslash/memberListAfterDoubleDot.ts @@ -3,4 +3,4 @@ ////../**/ goTo.marker(); -verify.memberListIsEmpty(); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListAfterSingleDot.ts b/tests/cases/fourslash/memberListAfterSingleDot.ts index 62edf3b8c9e..ba0cdb1a1eb 100644 --- a/tests/cases/fourslash/memberListAfterSingleDot.ts +++ b/tests/cases/fourslash/memberListAfterSingleDot.ts @@ -3,4 +3,4 @@ ////./**/ goTo.marker(); -verify.memberListIsEmpty(); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListErrorRecovery.ts b/tests/cases/fourslash/memberListErrorRecovery.ts index 74bd25464f6..ee1fdf9193c 100644 --- a/tests/cases/fourslash/memberListErrorRecovery.ts +++ b/tests/cases/fourslash/memberListErrorRecovery.ts @@ -6,5 +6,5 @@ /////*1*/var bar; goTo.marker(); -verify.memberListContains("fun"); +verify.completionListContains("fun"); verify.not.errorExistsAfterMarker("1"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListInFunctionCall.ts b/tests/cases/fourslash/memberListInFunctionCall.ts index 3c8c8e9ceb1..82e05bc4a00 100644 --- a/tests/cases/fourslash/memberListInFunctionCall.ts +++ b/tests/cases/fourslash/memberListInFunctionCall.ts @@ -11,5 +11,5 @@ goTo.marker(); edit.insert('.'); -verify.memberListContains('charAt'); +verify.completionListContains('charAt'); diff --git a/tests/cases/fourslash/memberListInReopenedEnum.ts b/tests/cases/fourslash/memberListInReopenedEnum.ts index 5101cb46f89..a03ee39041c 100644 --- a/tests/cases/fourslash/memberListInReopenedEnum.ts +++ b/tests/cases/fourslash/memberListInReopenedEnum.ts @@ -12,7 +12,7 @@ goTo.marker('1'); -verify.memberListContains('A', '(enum member) E.A = 0'); -verify.memberListContains('B', '(enum member) E.B = 1'); -verify.memberListContains('C', '(enum member) E.C = 0'); -verify.memberListContains('D', '(enum member) E.D = 1'); \ No newline at end of file +verify.completionListContains('A', '(enum member) E.A = 0'); +verify.completionListContains('B', '(enum member) E.B = 1'); +verify.completionListContains('C', '(enum member) E.C = 0'); +verify.completionListContains('D', '(enum member) E.D = 1'); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListInWithBlock.ts b/tests/cases/fourslash/memberListInWithBlock.ts index a37c20dadfa..5253e924ff3 100644 --- a/tests/cases/fourslash/memberListInWithBlock.ts +++ b/tests/cases/fourslash/memberListInWithBlock.ts @@ -12,7 +12,7 @@ ////} goTo.marker('1'); -verify.memberListIsEmpty(); +verify.completionListIsEmpty(); goTo.marker('2'); // Only keywords should show in completion, no members or types diff --git a/tests/cases/fourslash/memberListInWithBlock2.ts b/tests/cases/fourslash/memberListInWithBlock2.ts index 72bccb6926c..534cd12a416 100644 --- a/tests/cases/fourslash/memberListInWithBlock2.ts +++ b/tests/cases/fourslash/memberListInWithBlock2.ts @@ -9,4 +9,4 @@ ////} goTo.marker('1'); -verify.memberListIsEmpty(); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListInWithBlock3.ts b/tests/cases/fourslash/memberListInWithBlock3.ts index a007b08cd02..b30ceed9897 100644 --- a/tests/cases/fourslash/memberListInWithBlock3.ts +++ b/tests/cases/fourslash/memberListInWithBlock3.ts @@ -4,4 +4,4 @@ ////with(x./*1*/ goTo.marker('1'); -verify.memberListContains("a"); +verify.completionListContains("a"); diff --git a/tests/cases/fourslash/memberListInsideObjectLiterals.ts b/tests/cases/fourslash/memberListInsideObjectLiterals.ts index 99d62cbc6e5..875fb2c7fc9 100644 --- a/tests/cases/fourslash/memberListInsideObjectLiterals.ts +++ b/tests/cases/fourslash/memberListInsideObjectLiterals.ts @@ -26,16 +26,16 @@ // Literal member completion inside empty literal. goTo.marker("1"); -verify.memberListContains("x1", "(property) MyPoint.x1: number"); -verify.memberListContains("y1", "(property) MyPoint.y1: number"); +verify.completionListContains("x1", "(property) MyPoint.x1: number"); +verify.completionListContains("y1", "(property) MyPoint.y1: number"); // Literal member completion for 2nd member name. goTo.marker("2"); -verify.memberListContains("y1", "(property) MyPoint.y1: number"); +verify.completionListContains("y1", "(property) MyPoint.y1: number"); // Literal member completion at existing member name location. goTo.marker("3"); -verify.memberListContains("y1", "(property) MyPoint.y1: number"); +verify.completionListContains("y1", "(property) MyPoint.y1: number"); goTo.marker("4"); -verify.memberListContains("x1", "(property) MyPoint.x1: number"); \ No newline at end of file +verify.completionListContains("x1", "(property) MyPoint.x1: number"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfClass.ts b/tests/cases/fourslash/memberListOfClass.ts index 6c93a0536d9..3355109e4a7 100644 --- a/tests/cases/fourslash/memberListOfClass.ts +++ b/tests/cases/fourslash/memberListOfClass.ts @@ -10,6 +10,6 @@ ////f./**/ goTo.marker(); -verify.memberListCount(2); -verify.memberListContains('pubMeth', '(method) C1.pubMeth(): void'); -verify.memberListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file +verify.completionListCount(2); +verify.completionListContains('pubMeth', '(method) C1.pubMeth(): void'); +verify.completionListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts b/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts index 42171ff2e8b..5caaf5d9c23 100644 --- a/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts +++ b/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts @@ -10,4 +10,4 @@ goTo.file("memberListOfEnumFromExternalModule_file1.ts"); goTo.marker('1'); -verify.memberListContains("One"); \ No newline at end of file +verify.completionListContains("One"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfEnumInModule.ts b/tests/cases/fourslash/memberListOfEnumInModule.ts index f92c5d43ea8..0a3887e3304 100644 --- a/tests/cases/fourslash/memberListOfEnumInModule.ts +++ b/tests/cases/fourslash/memberListOfEnumInModule.ts @@ -9,5 +9,5 @@ ////} goTo.marker(); -verify.memberListContains("bar"); -verify.memberListContains("baz"); \ No newline at end of file +verify.completionListContains("bar"); +verify.completionListContains("baz"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfExportedClass.ts b/tests/cases/fourslash/memberListOfExportedClass.ts index f6632bfe7b0..3c9fe36358b 100644 --- a/tests/cases/fourslash/memberListOfExportedClass.ts +++ b/tests/cases/fourslash/memberListOfExportedClass.ts @@ -11,5 +11,5 @@ ////c./**/ // test on c. goTo.marker(); -verify.memberListCount(1); -verify.memberListContains('pub', '(property) M.C.pub: number'); \ No newline at end of file +verify.completionListCount(1); +verify.completionListContains('pub', '(property) M.C.pub: number'); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfModule.ts b/tests/cases/fourslash/memberListOfModule.ts index f09dfd67dbd..4724691c0a7 100644 --- a/tests/cases/fourslash/memberListOfModule.ts +++ b/tests/cases/fourslash/memberListOfModule.ts @@ -14,6 +14,6 @@ ////var x: Foo./**/ goTo.marker(); -verify.memberListCount(2); -verify.memberListContains('Bar'); -verify.memberListContains('Blah'); \ No newline at end of file +verify.completionListCount(2); +verify.completionListContains('Bar'); +verify.completionListContains('Blah'); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOfVarInArrowExpression.ts b/tests/cases/fourslash/memberListOfVarInArrowExpression.ts index 03da06989ae..b1a91ae3cb2 100644 --- a/tests/cases/fourslash/memberListOfVarInArrowExpression.ts +++ b/tests/cases/fourslash/memberListOfVarInArrowExpression.ts @@ -15,4 +15,4 @@ goTo.marker('1'); verify.quickInfoIs("(property) a1: string"); -verify.memberListContains("a1", "(property) a1: string"); \ No newline at end of file +verify.completionListContains("a1", "(property) a1: string"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOnContextualThis.ts b/tests/cases/fourslash/memberListOnContextualThis.ts new file mode 100644 index 00000000000..e17600cad98 --- /dev/null +++ b/tests/cases/fourslash/memberListOnContextualThis.ts @@ -0,0 +1,12 @@ +/// +////interface A { +//// a: string; +////} +////declare function ctx(callback: (this: A) => string): string; +////ctx(function () { return th/*1*/is./*2*/a }); + +goTo.marker('1'); +verify.quickInfoIs("this: A"); +goTo.marker('2'); +verify.completionListContains('a', '(property) A.a: string'); + diff --git a/tests/cases/fourslash/memberListOnExplicitThis.ts b/tests/cases/fourslash/memberListOnExplicitThis.ts index b776a7c0641..425eb17f8ba 100644 --- a/tests/cases/fourslash/memberListOnExplicitThis.ts +++ b/tests/cases/fourslash/memberListOnExplicitThis.ts @@ -13,17 +13,17 @@ ////function g(this: Restricted) {this./*4*/} goTo.marker('1'); -verify.memberListContains('f', '(method) C1.f(this: this): void'); -verify.memberListContains('g', '(method) C1.g(this: Restricted): void'); -verify.memberListContains('n', '(property) C1.n: number'); -verify.memberListContains('m', '(property) C1.m: number'); +verify.completionListContains('f', '(method) C1.f(this: this): void'); +verify.completionListContains('g', '(method) C1.g(this: Restricted): void'); +verify.completionListContains('n', '(property) C1.n: number'); +verify.completionListContains('m', '(property) C1.m: number'); goTo.marker('2'); -verify.memberListContains('n', '(property) Restricted.n: number'); +verify.completionListContains('n', '(property) Restricted.n: number'); goTo.marker('3'); -verify.memberListIsEmpty(); +verify.completionListIsEmpty(); goTo.marker('4'); -verify.memberListContains('n', '(property) Restricted.n: number'); +verify.completionListContains('n', '(property) Restricted.n: number'); diff --git a/tests/cases/fourslash/memberListOnFunctionParameter.ts b/tests/cases/fourslash/memberListOnFunctionParameter.ts index ee33cdc95e5..52daacb3573 100644 --- a/tests/cases/fourslash/memberListOnFunctionParameter.ts +++ b/tests/cases/fourslash/memberListOnFunctionParameter.ts @@ -6,8 +6,8 @@ ////} goTo.marker(); -verify.memberListContains("charAt"); -verify.memberListContains("charCodeAt"); -verify.memberListContains("length"); -verify.memberListContains("concat"); -verify.not.memberListContains("toFixed"); \ No newline at end of file +verify.completionListContains("charAt"); +verify.completionListContains("charCodeAt"); +verify.completionListContains("length"); +verify.completionListContains("concat"); +verify.not.completionListContains("toFixed"); \ No newline at end of file diff --git a/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts b/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts index 341605e391c..c44835f6882 100644 --- a/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts +++ b/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts @@ -8,6 +8,6 @@ ////} goTo.marker(); -verify.memberListContains('privMeth', '(method) C1.privMeth(): void'); -verify.memberListContains('pubMeth', '(method) C1.pubMeth(): void'); -verify.memberListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file +verify.completionListContains('privMeth', '(method) C1.privMeth(): void'); +verify.completionListContains('pubMeth', '(method) C1.pubMeth(): void'); +verify.completionListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file diff --git a/tests/cases/fourslash/memberlistOnDDot.ts b/tests/cases/fourslash/memberlistOnDDot.ts index 604bf531fc7..11efdd5d523 100644 --- a/tests/cases/fourslash/memberlistOnDDot.ts +++ b/tests/cases/fourslash/memberlistOnDDot.ts @@ -6,4 +6,4 @@ goTo.marker(); edit.insert('.'); edit.insert('.'); -//verify.not.memberListContains('charAt'); \ No newline at end of file +//verify.not.completionListContains('charAt'); \ No newline at end of file diff --git a/tests/cases/fourslash/navigateToIIFE.ts b/tests/cases/fourslash/navigateToIIFE.ts new file mode 100644 index 00000000000..69632e5f1ec --- /dev/null +++ b/tests/cases/fourslash/navigateToIIFE.ts @@ -0,0 +1,19 @@ +/// + +// @Filename: file1.ts +/////*1*/(function () { +//// "use strict"; +//// function onResume() { +//// }; +////} )(); +// @Filename: file2.ts +/////*2*/class EventManager { +//// public onResume(name: string) { } +////} +////class MyOtherEventManager { +//// public onResume(name: string) { } +////} +verify.navigationItemsListCount(3, "onResume"); +verify.navigationItemsListCount(1, "onResume", undefined, test.marker("1").fileName); +verify.navigationItemsListContains("onResume", "function", "onResume", "exact", test.marker("1").fileName); +verify.navigationItemsListCount(2, "onResume", undefined, test.marker("2").fileName); diff --git a/tests/cases/fourslash/navigationBarItemsFunctionProperties.ts b/tests/cases/fourslash/navigationBarItemsFunctionProperties.ts new file mode 100644 index 00000000000..75c20736b41 --- /dev/null +++ b/tests/cases/fourslash/navigationBarItemsFunctionProperties.ts @@ -0,0 +1,33 @@ +/// + +//// (function(){ +//// var A; +//// A/*1*/ +//// .a = function() { }; +//// })(); + +function navExact(name: string, kind: string) { + return; +} + +verify.navigationTree( +{ + "text": "", + "kind": "script", + "childItems": [ + { + "text": "", + "kind": "function", + "childItems": [ + { + "text": "A", + "kind": "var" + }, + { + "text": "A.a", + "kind": "function" + } + ] + } + ] +}); \ No newline at end of file diff --git a/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts b/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts index cfeaabfbb86..25e6cd4c68e 100644 --- a/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts +++ b/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts @@ -64,12 +64,12 @@ verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: strin goTo.marker('7'); verify.quickInfoIs('var m.exportedStrOrNum: string | number'); -verify.memberListContains("exportedStrOrNum", "var m.exportedStrOrNum: string | number"); +verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string | number"); goTo.marker('8'); verify.quickInfoIs('var m.exportedStrOrNum: number'); -verify.memberListContains("exportedStrOrNum", "var m.exportedStrOrNum: number"); +verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: number"); goTo.marker('9'); verify.quickInfoIs('var m.exportedStrOrNum: string'); -verify.memberListContains("exportedStrOrNum", "var m.exportedStrOrNum: string"); \ No newline at end of file +verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string"); \ No newline at end of file diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts index 3ae0533d340..e11af2beda4 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts @@ -17,8 +17,8 @@ verify.quickInfos({ }); goTo.marker('3'); -verify.memberListContains("x", "(property) x: number", undefined); -verify.memberListContains("b", "(property) b: number", undefined); +verify.completionListContains("x", "(property) x: number", undefined); +verify.completionListContains("b", "(property) b: number", undefined); verify.quickInfoIs("(property) x: number"); verify.quickInfoAt("4", "var point: {\n b: number;\n x: number;\n}"); diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts index 7beaf5548fb..f592b255ac0 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts @@ -14,6 +14,6 @@ verify.quickInfos({ }); goTo.marker('3'); -verify.memberListContains("x", "(property) x: number", undefined); +verify.completionListContains("x", "(property) x: number", undefined); verify.quickInfoAt("4", "var point: {\n readonly x: number;\n}"); diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts index 95a304329f2..d66626cc99d 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts @@ -12,8 +12,8 @@ verify.quickInfoAt("1", "function makePoint(x: number): {\n b: number;\n x: number;\n}"); goTo.marker('2'); -verify.memberListContains("x", "(property) x: number", undefined); -verify.memberListContains("b", "(property) b: number", undefined); +verify.completionListContains("x", "(property) x: number", undefined); +verify.completionListContains("b", "(property) b: number", undefined); verify.quickInfoIs("(property) x: number"); verify.quickInfoAt("3", "var point: {\n b: number;\n x: number;\n}"); diff --git a/tests/cases/fourslash/quickInfoWithNestedDestructuredParameterInLambda.ts b/tests/cases/fourslash/quickInfoWithNestedDestructuredParameterInLambda.ts new file mode 100644 index 00000000000..39453ba8cdc --- /dev/null +++ b/tests/cases/fourslash/quickInfoWithNestedDestructuredParameterInLambda.ts @@ -0,0 +1,15 @@ +/// + +// @filename: a.tsx +////import * as React from 'react'; +////interface SomeInterface { +//// someBoolean: boolean, +//// someString: string; +////} +////interface SomeProps { +//// someProp: SomeInterface; +////} +////export const /*1*/SomeStatelessComponent = ({someProp: { someBoolean, someString}}: SomeProps) => (
{`${someBoolean}${someString}`}); + +goTo.marker("1"); +verify.quickInfoExists(); diff --git a/tests/cases/fourslash/renameObjectSpread.ts b/tests/cases/fourslash/renameObjectSpread.ts new file mode 100644 index 00000000000..eba148c0e39 --- /dev/null +++ b/tests/cases/fourslash/renameObjectSpread.ts @@ -0,0 +1,20 @@ +/// + +////interface A1 { [|a|]: number }; +////interface A2 { [|a|]?: number }; +////let a1: A1; +////let a2: A2; +////let a12 = { ...a1, ...a2 }; +////a12.[|a|]; +const ranges = test.ranges(); +verify.assertHasRanges(ranges); + +// A1 unions with A2, so rename A1.a and a12.a +goTo.position(ranges[0].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[0], ranges[2]]); +// A1 unions with A2, so rename A2.a and a12.a +goTo.position(ranges[1].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[1], ranges[2]]); +// a12.a unions A1.a and A2.a, so rename A1.a, A2.a and a12.a +goTo.position(ranges[2].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[0], ranges[1], ranges[2]]); diff --git a/tests/cases/fourslash/renameObjectSpreadAssignment.ts b/tests/cases/fourslash/renameObjectSpreadAssignment.ts new file mode 100644 index 00000000000..9cf0b6ebf81 --- /dev/null +++ b/tests/cases/fourslash/renameObjectSpreadAssignment.ts @@ -0,0 +1,20 @@ +/// + +////interface A1 { a: number }; +////interface A2 { a?: number }; +////let [|a1|]: A1; +////let [|a2|]: A2; +////let a12 = { ...[|a1|], ...[|a2|] }; +const ranges = test.ranges(); +verify.assertHasRanges(ranges); + +// rename a1 +goTo.position(ranges[0].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[0], ranges[2]]); +goTo.position(ranges[2].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[0], ranges[2]]); +// rename a2 +goTo.position(ranges[1].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[1], ranges[3]]); +goTo.position(ranges[3].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [ranges[1], ranges[3]]); diff --git a/tests/cases/fourslash/renameRest.ts b/tests/cases/fourslash/renameRest.ts new file mode 100644 index 00000000000..a5cc2c38683 --- /dev/null +++ b/tests/cases/fourslash/renameRest.ts @@ -0,0 +1,15 @@ +/// +////interface Gen { +//// x: number; +//// [|parent|]: Gen; +//// millenial: string; +////} +////let t: Gen; +////var { x, ...rest } = t; +////rest.[|parent|]; +const ranges = test.ranges(); +verify.assertHasRanges(ranges); +goTo.position(ranges[0].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, ranges); +goTo.position(ranges[1].start); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, ranges); diff --git a/tests/cases/fourslash/server/codefix.ts b/tests/cases/fourslash/server/codefix.ts index 7fbe2cb4fd7..9d0f42c9e4c 100644 --- a/tests/cases/fourslash/server/codefix.ts +++ b/tests/cases/fourslash/server/codefix.ts @@ -1,4 +1,4 @@ -/// +/// ////class Base{ ////} diff --git a/tests/cases/fourslash/server/completions01.ts b/tests/cases/fourslash/server/completions01.ts index a837a74849d..38fdbab4eda 100644 --- a/tests/cases/fourslash/server/completions01.ts +++ b/tests/cases/fourslash/server/completions01.ts @@ -6,11 +6,11 @@ goTo.marker('1'); edit.insert('.'); -verify.memberListContains('trim'); -verify.memberListCount(21); +verify.completionListContains('trim'); +verify.completionListCount(21); edit.insert('});'); // need the following lines to not have parse errors in order for completion list to appear goTo.marker('2'); edit.insert('.'); -verify.memberListContains('trim'); -verify.memberListCount(21); +verify.completionListContains('trim'); +verify.completionListCount(21); diff --git a/tests/cases/fourslash/server/completions03.ts b/tests/cases/fourslash/server/completions03.ts new file mode 100644 index 00000000000..ef5f1651951 --- /dev/null +++ b/tests/cases/fourslash/server/completions03.ts @@ -0,0 +1,20 @@ +/// + +// issue: https://github.com/Microsoft/TypeScript/issues/10108 + +//// interface Foo { +//// one: any; +//// two: any; +//// three: any; +//// } +//// +//// let x: Foo = { +//// get one() { return "" }, +//// set two(t) {}, +//// /**/ +//// } + +goTo.marker(""); +verify.completionListContains("three"); +verify.not.completionListContains("one"); +verify.not.completionListContains("two"); diff --git a/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics01.ts b/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics01.ts new file mode 100644 index 00000000000..0aa88ebd90c --- /dev/null +++ b/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics01.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @Filename: a.js +//// var ===; + +verify.getSyntacticDiagnostics(`[ + { + "message": "Variable declaration expected.", + "start": 4, + "length": 3, + "category": "error", + "code": 1134 + }, + { + "message": "Expression expected.", + "start": 7, + "length": 1, + "category": "error", + "code": 1109 + } +]`); +verify.getSemanticDiagnostics(`[]`); \ No newline at end of file diff --git a/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics02.ts b/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics02.ts new file mode 100644 index 00000000000..a19d170217c --- /dev/null +++ b/tests/cases/fourslash/server/getJavaScriptSyntacticDiagnostics02.ts @@ -0,0 +1,47 @@ +/// + +// @allowJs: true +// @Filename: b.js +//// var a = "a"; +//// var b: boolean = true; +//// function foo(): string { } +//// var var = "c"; + +verify.getSyntacticDiagnostics(`[ + { + "message": "\'types\' can only be used in a .ts file.", + "start": 20, + "length": 7, + "category": "error", + "code": 8010 + }, + { + "message": "\'types\' can only be used in a .ts file.", + "start": 52, + "length": 6, + "category": "error", + "code": 8010 + }, + { + "message": "Variable declaration expected.", + "start": 67, + "length": 3, + "category": "error", + "code": 1134 + }, + { + "message": "Variable declaration expected.", + "start": 71, + "length": 1, + "category": "error", + "code": 1134 + }, + { + "message": "Variable declaration expected.", + "start": 73, + "length": 3, + "category": "error", + "code": 1134 + } +]`); +verify.getSemanticDiagnostics(`[]`); \ No newline at end of file diff --git a/tests/cases/fourslash/server/jsdocTypedefTag.ts b/tests/cases/fourslash/server/jsdocTypedefTag.ts index 968e30a412d..9e980114835 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTag.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTag.ts @@ -52,37 +52,37 @@ //// d.dogAge./*dogAge*/; goTo.marker('numberLike'); -verify.memberListContains('charAt'); -verify.memberListContains('toExponential'); +verify.completionListContains('charAt'); +verify.completionListContains('toExponential'); goTo.marker('person'); -verify.memberListContains('personName'); -verify.memberListContains('personAge'); +verify.completionListContains('personName'); +verify.completionListContains('personAge'); goTo.marker('personName'); -verify.memberListContains('charAt'); +verify.completionListContains('charAt'); goTo.marker('personAge'); -verify.memberListContains('toExponential'); +verify.completionListContains('toExponential'); goTo.marker('animal'); -verify.memberListContains('animalName'); -verify.memberListContains('animalAge'); +verify.completionListContains('animalName'); +verify.completionListContains('animalAge'); goTo.marker('animalName'); -verify.memberListContains('charAt'); +verify.completionListContains('charAt'); goTo.marker('animalAge'); -verify.memberListContains('toExponential'); +verify.completionListContains('toExponential'); goTo.marker('dog'); -verify.memberListContains('dogName'); -verify.memberListContains('dogAge'); +verify.completionListContains('dogName'); +verify.completionListContains('dogAge'); goTo.marker('dogName'); -verify.memberListContains('charAt'); +verify.completionListContains('charAt'); goTo.marker('dogAge'); -verify.memberListContains('toExponential'); +verify.completionListContains('toExponential'); goTo.marker('cat'); -verify.memberListContains('catName'); -verify.memberListContains('catAge'); +verify.completionListContains('catName'); +verify.completionListContains('catAge'); goTo.marker('catName'); -verify.memberListContains('charAt'); +verify.completionListContains('charAt'); goTo.marker('catAge'); -verify.memberListContains('toExponential'); \ No newline at end of file +verify.completionListContains('toExponential'); \ No newline at end of file diff --git a/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts b/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts new file mode 100644 index 00000000000..29330a73d3c --- /dev/null +++ b/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts @@ -0,0 +1,27 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: jsdocCompletion_typedef.js + +//// /** +//// * @typedef {string | number} T.NumberLike +//// * @typedef {{age: number}} T.People +//// * @typedef {string | number} T.O.Q.NumberLike +//// * @type {T.NumberLike} +//// */ +//// var x; x./*1*/; +//// /** @type {T.O.Q.NumberLike} */ +//// var x1; x1./*2*/; +//// /** @type {T.People} */ +//// var x1; x1./*3*/; + +goTo.marker("1"); +verify.completionListContains('charAt'); +verify.completionListContains('toExponential'); + +goTo.marker("2"); +verify.completionListContains('age'); + +goTo.marker("3"); +verify.completionListContains('charAt'); +verify.completionListContains('toExponential'); \ No newline at end of file diff --git a/tests/cases/fourslash/signatureHelpTypeParametersNotVariadic.ts b/tests/cases/fourslash/signatureHelpTypeParametersNotVariadic.ts new file mode 100644 index 00000000000..30b0bac7e71 --- /dev/null +++ b/tests/cases/fourslash/signatureHelpTypeParametersNotVariadic.ts @@ -0,0 +1,8 @@ +/// + +//// declare function f(a: any, ...b: any[]): any; +//// f(1, 2); + +goTo.marker("1"); +verify.signatureHelpArgumentCountIs(0); +verify.signatureHelpCurrentArgumentListIsVariadic(false); \ No newline at end of file diff --git a/tests/cases/fourslash/tsxCompletion10.ts b/tests/cases/fourslash/tsxCompletion10.ts index f10e014c282..d36b2369218 100644 --- a/tests/cases/fourslash/tsxCompletion10.ts +++ b/tests/cases/fourslash/tsxCompletion10.ts @@ -10,5 +10,5 @@ //// var x1 =
goTo.marker("1"); -verify.memberListCount(1); +verify.completionListCount(1); verify.completionListContains('div'); goTo.marker("2"); -verify.memberListCount(1); +verify.completionListCount(1); verify.completionListContains('h1') diff --git a/tests/cases/fourslash/tsxCompletionOnClosingTagWithoutJSX1.ts b/tests/cases/fourslash/tsxCompletionOnClosingTagWithoutJSX1.ts index 742009b487e..7719e04a9ef 100644 --- a/tests/cases/fourslash/tsxCompletionOnClosingTagWithoutJSX1.ts +++ b/tests/cases/fourslash/tsxCompletionOnClosingTagWithoutJSX1.ts @@ -4,5 +4,5 @@ //// var x1 =
goTo.marker("1"); -verify.memberListCount(1); +verify.completionListCount(1); verify.completionListContains('div'); goTo.marker("2"); -verify.memberListCount(1); +verify.completionListCount(1); verify.completionListContains('h1') diff --git a/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts b/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts index d0ef579f401..f208b0a44a4 100644 --- a/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts +++ b/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts @@ -4,4 +4,4 @@ //// var x = + +// @Filename: node_modules/foo/index.js +////{} + +// @Filename: a.ts +////import /*foo*/[|foo|] from /*fooModule*/"foo"; +////[|foo|](); + +goTo.file("a.ts"); +verify.numberOfErrorsInCurrentFile(0); + +goTo.marker("fooModule"); +verify.goToDefinitionIs([]); +verify.quickInfoIs(""); +verify.referencesAre([]) + +goTo.marker("foo"); +verify.goToDefinitionIs([]); +verify.quickInfoIs("import foo"); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/unusedClassInNamespace1.ts b/tests/cases/fourslash/unusedClassInNamespace1.ts new file mode 100644 index 00000000000..586202ab0c7 --- /dev/null +++ b/tests/cases/fourslash/unusedClassInNamespace1.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// class class1 { +//// } +//// } |] + +verify.codeFixAtPosition(`namespace greeter { +}`); diff --git a/tests/cases/fourslash/unusedClassInNamespace2.ts b/tests/cases/fourslash/unusedClassInNamespace2.ts new file mode 100644 index 00000000000..c182f4e3655 --- /dev/null +++ b/tests/cases/fourslash/unusedClassInNamespace2.ts @@ -0,0 +1,15 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// export class class2 { +//// } +//// class class1 { +//// } +//// } |] + +verify.codeFixAtPosition(`namespace greeter { + export class class2 { + } +}`); + diff --git a/tests/cases/fourslash/unusedClassInNamespace3.ts b/tests/cases/fourslash/unusedClassInNamespace3.ts new file mode 100644 index 00000000000..391c5e833ef --- /dev/null +++ b/tests/cases/fourslash/unusedClassInNamespace3.ts @@ -0,0 +1,25 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true +//// [| namespace Validation { +//// class c1 { +//// +//// } +//// +//// export class c2 { +//// +//// } +//// +//// class c3 extends c1 { +//// +//// } +////} |] + +verify.codeFixAtPosition(`namespace Validation { + class c1 { + } + + export class c2 { + } +}`); diff --git a/tests/cases/fourslash/unusedClassInNamespace4.ts b/tests/cases/fourslash/unusedClassInNamespace4.ts new file mode 100644 index 00000000000..5db5b1aefa6 --- /dev/null +++ b/tests/cases/fourslash/unusedClassInNamespace4.ts @@ -0,0 +1,27 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true +//// [| namespace Validation { +//// class c1 { +//// +//// } +//// +//// export class c2 { +//// +//// } +//// +//// class c3 { +//// public x: c1; +//// } +////} |] + +verify.codeFixAtPosition(`namespace Validation { + class c1 { + + } + + export class c2 { + + } +}`); diff --git a/tests/cases/fourslash/unusedConstantInFunction1.ts b/tests/cases/fourslash/unusedConstantInFunction1.ts new file mode 100644 index 00000000000..df373257809 --- /dev/null +++ b/tests/cases/fourslash/unusedConstantInFunction1.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// [| function f1 () { +//// const x: string = "x"; +//// } |] + +verify.codeFixAtPosition(`function f1 () { +}`); + diff --git a/tests/cases/fourslash/unusedEnumInFunction1.ts b/tests/cases/fourslash/unusedEnumInFunction1.ts new file mode 100644 index 00000000000..1d88f07ebf7 --- /dev/null +++ b/tests/cases/fourslash/unusedEnumInFunction1.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// [| function f1 () { +//// enum Directions { Up, Down} +//// } |] + +verify.codeFixAtPosition(`function f1 () { +} +`); + diff --git a/tests/cases/fourslash/unusedEnumInNamespace1.ts b/tests/cases/fourslash/unusedEnumInNamespace1.ts new file mode 100644 index 00000000000..88e8e32d5f8 --- /dev/null +++ b/tests/cases/fourslash/unusedEnumInNamespace1.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// enum enum1 { +//// Monday +//// } +//// } |] + +verify.codeFixAtPosition(`namespace greeter { +}`); diff --git a/tests/cases/fourslash/unusedFunctionInNamespace1.ts b/tests/cases/fourslash/unusedFunctionInNamespace1.ts new file mode 100644 index 00000000000..e0f6b2e18ac --- /dev/null +++ b/tests/cases/fourslash/unusedFunctionInNamespace1.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// function function1() { +//// }/*1*/ +//// } |] + +verify.codeFixAtPosition(`namespace greeter { +}`); diff --git a/tests/cases/fourslash/unusedFunctionInNamespace2.ts b/tests/cases/fourslash/unusedFunctionInNamespace2.ts new file mode 100644 index 00000000000..c823777048e --- /dev/null +++ b/tests/cases/fourslash/unusedFunctionInNamespace2.ts @@ -0,0 +1,14 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// export function function2() { +//// } +//// function function1() { +//// } +////} |] + +verify.codeFixAtPosition(`namespace greeter { + export function function2() { + } +}`); diff --git a/tests/cases/fourslash/unusedFunctionInNamespace3.ts b/tests/cases/fourslash/unusedFunctionInNamespace3.ts new file mode 100644 index 00000000000..144e9f325b4 --- /dev/null +++ b/tests/cases/fourslash/unusedFunctionInNamespace3.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true + +//// [| namespace Validation { +//// function function1() { +//// } +////} |] + +verify.codeFixAtPosition(`namespace Validation { +}`); diff --git a/tests/cases/fourslash/unusedFunctionInNamespace4.ts b/tests/cases/fourslash/unusedFunctionInNamespace4.ts new file mode 100644 index 00000000000..5b5995da9c7 --- /dev/null +++ b/tests/cases/fourslash/unusedFunctionInNamespace4.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true +//// [| namespace Validation { +//// var function1 = function() { +//// } +////} |] + +verify.codeFixAtPosition(`namespace Validation { +}`); diff --git a/tests/cases/fourslash/unusedFunctionInNamespace5.ts b/tests/cases/fourslash/unusedFunctionInNamespace5.ts new file mode 100644 index 00000000000..b839d9dcd97 --- /dev/null +++ b/tests/cases/fourslash/unusedFunctionInNamespace5.ts @@ -0,0 +1,28 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true +////namespace Validation { +//// var function1 = function() { +//// } +//// +//// export function function2() { +//// +//// } +//// +//// [| function function3() { +//// function1(); +//// } +//// +//// function function4() { +//// +//// } +//// +//// export let a = function3; |] +////} + +verify.codeFixAtPosition(`function function3() { + function1(); + } + + export let a = function3;`); diff --git a/tests/cases/fourslash/unusedImports10FS.ts b/tests/cases/fourslash/unusedImports10FS.ts new file mode 100644 index 00000000000..f9d38e4cfb0 --- /dev/null +++ b/tests/cases/fourslash/unusedImports10FS.ts @@ -0,0 +1,16 @@ +/// + +// @noUnusedLocals: true +//// module A { +//// export class Calculator { +//// public handelChar() { +//// } +//// } +//// } + +//// module B { +//// [|import a = A;|] +//// } + +verify.codeFixAtPosition(""); + diff --git a/tests/cases/fourslash/unusedImports11FS.ts b/tests/cases/fourslash/unusedImports11FS.ts new file mode 100644 index 00000000000..a18a4634d71 --- /dev/null +++ b/tests/cases/fourslash/unusedImports11FS.ts @@ -0,0 +1,14 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import f1, * as s from "./file1"; |] +//// s.f2('hello'); + +// @Filename: file1.ts +//// export var v1; +//// export function f1(n: number){} +//// export function f2(s: string){}; +//// export default f1; + +verify.codeFixAtPosition('import * as s from "./file1";'); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports12FS.ts b/tests/cases/fourslash/unusedImports12FS.ts new file mode 100644 index 00000000000..4d8243eb4ab --- /dev/null +++ b/tests/cases/fourslash/unusedImports12FS.ts @@ -0,0 +1,13 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import f1, * as s from "./file1"; |] +//// f1(42); + +// @Filename: file1.ts +//// export function f1(n: number){} +//// export function f2(s: string){}; +//// export default f1; + +verify.codeFixAtPosition('import f1 from "./file1";'); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports1FS.ts b/tests/cases/fourslash/unusedImports1FS.ts new file mode 100644 index 00000000000..d9fc17a2448 --- /dev/null +++ b/tests/cases/fourslash/unusedImports1FS.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [|import { Calculator } from "./file1" |] + +// @Filename: file1.ts +//// export class Calculator { +//// +//// } + +verify.codeFixAtPosition(''); diff --git a/tests/cases/fourslash/unusedImports2FS.ts b/tests/cases/fourslash/unusedImports2FS.ts new file mode 100644 index 00000000000..6e3d9527c52 --- /dev/null +++ b/tests/cases/fourslash/unusedImports2FS.ts @@ -0,0 +1,19 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [|import {Calculator} from "./file1" +//// import {test} from "./file1"|] + +//// var x = new Calculator(); +//// x.handleChar(); + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() {} +//// } +//// export function test() { +//// +//// } + +verify.codeFixAtPosition(`import {Calculator} from "./file1"`); diff --git a/tests/cases/fourslash/unusedImports3FS.ts b/tests/cases/fourslash/unusedImports3FS.ts new file mode 100644 index 00000000000..205666e971d --- /dev/null +++ b/tests/cases/fourslash/unusedImports3FS.ts @@ -0,0 +1,24 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +////[| import {Calculator, test, test2} from "./file1" |] + +//// test(); +//// test2(); + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() {} +//// } + +//// export function test() { +//// +//// } + +//// export function test2() { +//// +//// } + +verify.codeFixAtPosition(`import {test, test2} from "./file1"`); + diff --git a/tests/cases/fourslash/unusedImports4FS.ts b/tests/cases/fourslash/unusedImports4FS.ts new file mode 100644 index 00000000000..302007748f4 --- /dev/null +++ b/tests/cases/fourslash/unusedImports4FS.ts @@ -0,0 +1,24 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import {Calculator, test, test2} from "./file1" |] +//// +//// var x = new Calculator(); +//// x.handleChar(); +//// test2(); + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() {} +//// } +//// +//// export function test() { +//// +//// } +//// +//// export function test2() { +//// +//// } + +verify.codeFixAtPosition(`import {Calculator, test2} from "./file1"`); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports5FS.ts b/tests/cases/fourslash/unusedImports5FS.ts new file mode 100644 index 00000000000..1d68f6ae643 --- /dev/null +++ b/tests/cases/fourslash/unusedImports5FS.ts @@ -0,0 +1,24 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import {Calculator, test, test2} from "./file1" |] +//// +//// var x = new Calculator(); +//// x.handleChar(); +//// test(); + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() {} +//// } +//// +//// export function test() { +//// +//// } +//// +//// export function test2() { +//// +//// } + +verify.codeFixAtPosition(`import {Calculator, test} from "./file1"`); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports6FS.ts b/tests/cases/fourslash/unusedImports6FS.ts new file mode 100644 index 00000000000..a5c6744855a --- /dev/null +++ b/tests/cases/fourslash/unusedImports6FS.ts @@ -0,0 +1,20 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import d from "./file1" |] + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() { } +//// } + +//// export function test() { +//// +//// } + +//// export default function test2() { +//// +//// } + +verify.codeFixAtPosition(''); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports7FS.ts b/tests/cases/fourslash/unusedImports7FS.ts new file mode 100644 index 00000000000..23066ef538d --- /dev/null +++ b/tests/cases/fourslash/unusedImports7FS.ts @@ -0,0 +1,16 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [| import * as n from "./file1" |] + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() { } +//// } +//// export function test() { +//// } +//// export default function test2() { +//// } + +verify.codeFixAtPosition(''); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports8FS.ts b/tests/cases/fourslash/unusedImports8FS.ts new file mode 100644 index 00000000000..02564e35989 --- /dev/null +++ b/tests/cases/fourslash/unusedImports8FS.ts @@ -0,0 +1,24 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [|import {Calculator as calc, test as t1, test2 as t2} from "./file1"|] +//// +//// var x = new calc(); +//// x.handleChar(); +//// t1(); + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() { } +//// } + +//// export function test() { +//// +//// } + +//// export function test2() { +//// +//// } + +verify.codeFixAtPosition(`import {Calculator as calc, test as t1} from "./file1"`); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedImports9FS.ts b/tests/cases/fourslash/unusedImports9FS.ts new file mode 100644 index 00000000000..324d57a1928 --- /dev/null +++ b/tests/cases/fourslash/unusedImports9FS.ts @@ -0,0 +1,20 @@ +/// + +// @noUnusedLocals: true +// @Filename: file2.ts +//// [|import c = require('./file1')|] + +// @Filename: file1.ts +//// export class Calculator { +//// handleChar() { } +//// } +//// +//// export function test() { +//// +//// } +//// +//// export function test2() { +//// +//// } + +verify.codeFixAtPosition(""); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedInterfaceInNamespace1.ts b/tests/cases/fourslash/unusedInterfaceInNamespace1.ts new file mode 100644 index 00000000000..8d07a8c7912 --- /dev/null +++ b/tests/cases/fourslash/unusedInterfaceInNamespace1.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// interface interface1 { +//// } +////} |] + +verify.codeFixAtPosition(` +namespace greeter { +}`); diff --git a/tests/cases/fourslash/unusedInterfaceInNamespace2.ts b/tests/cases/fourslash/unusedInterfaceInNamespace2.ts new file mode 100644 index 00000000000..baa46c65a0c --- /dev/null +++ b/tests/cases/fourslash/unusedInterfaceInNamespace2.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +////namespace greeter { +//// [| export interface interface2 { +//// } +//// interface interface1 { +//// } |] +////} + +verify.codeFixAtPosition(`export interface interface2 { +}`); diff --git a/tests/cases/fourslash/unusedLocalsInFunction1.ts b/tests/cases/fourslash/unusedLocalsInFunction1.ts new file mode 100644 index 00000000000..2edd7c176e7 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInFunction1.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// [| function greeter() { +//// var x = 0; +////} |] + +verify.codeFixAtPosition(` +function greeter() { +}`); diff --git a/tests/cases/fourslash/unusedLocalsInFunction2.ts b/tests/cases/fourslash/unusedLocalsInFunction2.ts new file mode 100644 index 00000000000..b7094328041 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInFunction2.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +////function greeter() { +//// [| var x, y = 0; |] +//// x+1; +////} + +verify.codeFixAtPosition("var x;"); diff --git a/tests/cases/fourslash/unusedLocalsInFunction3.ts b/tests/cases/fourslash/unusedLocalsInFunction3.ts new file mode 100644 index 00000000000..906517ee0a7 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInFunction3.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +////function greeter() { +//// [| var x, y = 0,z = 1; |] +//// x+1; +//// z+1; +////} + +verify.codeFixAtPosition("var x,z = 1;", 6133); diff --git a/tests/cases/fourslash/unusedLocalsInFunction4.ts b/tests/cases/fourslash/unusedLocalsInFunction4.ts new file mode 100644 index 00000000000..54d3223f236 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInFunction4.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +////function greeter() { +//// [| var x,y = 0,z = 1; |] +//// y++; +//// z++; +////} + +verify.codeFixAtPosition("var y = 0,z = 1;"); diff --git a/tests/cases/fourslash/unusedLocalsInMethodFS1.ts b/tests/cases/fourslash/unusedLocalsInMethodFS1.ts new file mode 100644 index 00000000000..43b782ce266 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInMethodFS1.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +////class greeter { +//// public function1() { +//// [| var /*0*/x,/*1*/ y = 10; |] +//// y++; +//// } +////} + +verify.codeFixAtPosition("var y = 10;"); diff --git a/tests/cases/fourslash/unusedLocalsInMethodFS2.ts b/tests/cases/fourslash/unusedLocalsInMethodFS2.ts new file mode 100644 index 00000000000..322cfad3940 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsInMethodFS2.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +////class greeter { +//// public function1() { +//// [| var x, y; |] +//// y = 1; +//// } +////} + +verify.codeFixAtPosition("var y;"); diff --git a/tests/cases/fourslash/unusedLocalsinConstructorFS1.ts b/tests/cases/fourslash/unusedLocalsinConstructorFS1.ts new file mode 100644 index 00000000000..412b599b780 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsinConstructorFS1.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters:true +////class greeter { +//// [| constructor() { +//// var unused = 20; +//// } |] +////} + +verify.codeFixAtPosition(`constructor() { +}`); diff --git a/tests/cases/fourslash/unusedLocalsinConstructorFS2.ts b/tests/cases/fourslash/unusedLocalsinConstructorFS2.ts new file mode 100644 index 00000000000..eff9b7c8d54 --- /dev/null +++ b/tests/cases/fourslash/unusedLocalsinConstructorFS2.ts @@ -0,0 +1,18 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +////class greeter { +//// [|constructor() { +//// var unused = 20; +//// var used = "dummy"; +//// used = used + "second part"; +//// }|] +////} + +verify.codeFixAtPosition(` + constructor() { + var used = "dummy"; + used = used + "second part"; + } +`); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedMethodInClass1.ts b/tests/cases/fourslash/unusedMethodInClass1.ts new file mode 100644 index 00000000000..7795a4d1530 --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass1.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +////[| class greeter { +//// private function1() { +//// } +////} |] + +verify.codeFixAtPosition(` +class greeter { +}`); diff --git a/tests/cases/fourslash/unusedMethodInClass2.ts b/tests/cases/fourslash/unusedMethodInClass2.ts new file mode 100644 index 00000000000..24b6fe155ef --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass2.ts @@ -0,0 +1,15 @@ +/// + +// @noUnusedLocals: true +//// [| class greeter { +//// public function2() { +//// } +//// private function1() { +//// } +////} |] + +verify.codeFixAtPosition(` +class greeter { + public function2() { + } +}`); diff --git a/tests/cases/fourslash/unusedMethodInClass3.ts b/tests/cases/fourslash/unusedMethodInClass3.ts new file mode 100644 index 00000000000..eab535fb5af --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass3.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +////[|class greeter { +//// private function1 = function() { +//// } +////} |] + +verify.codeFixAtPosition(` +class greeter { +}`); diff --git a/tests/cases/fourslash/unusedMethodInClass4.ts b/tests/cases/fourslash/unusedMethodInClass4.ts new file mode 100644 index 00000000000..ee27ec331eb --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass4.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +////class greeter { +//// [|public function2(){ +//// } +//// private function1 = function() { +//// } |] +////} + +verify.codeFixAtPosition(`public function2(){ +}`); diff --git a/tests/cases/fourslash/unusedMethodInClass5.ts b/tests/cases/fourslash/unusedMethodInClass5.ts new file mode 100644 index 00000000000..36ef3670cac --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass5.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// [|class C { +//// private ["string"] (){} +//// }|] + +verify.codeFixAtPosition("class C { }"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedMethodInClass6.ts b/tests/cases/fourslash/unusedMethodInClass6.ts new file mode 100644 index 00000000000..71fcb92d037 --- /dev/null +++ b/tests/cases/fourslash/unusedMethodInClass6.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// [|class C { +//// private "string" (){} +//// }|] + +verify.codeFixAtPosition("class C { }"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedNamespaceInNamespace.ts b/tests/cases/fourslash/unusedNamespaceInNamespace.ts new file mode 100644 index 00000000000..41fe162ef15 --- /dev/null +++ b/tests/cases/fourslash/unusedNamespaceInNamespace.ts @@ -0,0 +1,13 @@ +/// + +// @noUnusedLocals: true +//// [|namespace A { +//// namespace B { +//// } +//// }|] + +verify.codeFixAtPosition(` +namespace A { +} +`); + diff --git a/tests/cases/fourslash/unusedParameterInConstructor1.ts b/tests/cases/fourslash/unusedParameterInConstructor1.ts new file mode 100644 index 00000000000..f53c6d3e8bd --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInConstructor1.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|constructor(private p1: string, public p2: boolean, public p3: any, p5)|] { p5; } +//// } + +verify.codeFixAtPosition("constructor(public p2: boolean, public p3: any, p5)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInConstructor2.ts b/tests/cases/fourslash/unusedParameterInConstructor2.ts new file mode 100644 index 00000000000..bd5f66ff966 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInConstructor2.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|constructor(public p1: string, private p2: boolean, public p3: any, p5)|] { p5; } +//// } + +verify.codeFixAtPosition("constructor(public p1: string, public p3: any, p5)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInConstructor3.ts b/tests/cases/fourslash/unusedParameterInConstructor3.ts new file mode 100644 index 00000000000..173e00113d8 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInConstructor3.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|constructor(public p1: string, public p2: boolean, private p3: any, p5)|] { p5; } +//// } + +verify.codeFixAtPosition("constructor(public p1: string, public p2: boolean, p5)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInConstructor4.ts b/tests/cases/fourslash/unusedParameterInConstructor4.ts new file mode 100644 index 00000000000..6d0223dc5f4 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInConstructor4.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|constructor(private readonly p2: boolean, p5)|] { p5; } +//// } + +verify.codeFixAtPosition("constructor(p5)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInFunction1.ts b/tests/cases/fourslash/unusedParameterInFunction1.ts new file mode 100644 index 00000000000..2243af9f5f5 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInFunction1.ts @@ -0,0 +1,7 @@ +/// + +// @noUnusedParameters: true +////function [|greeter( x)|] { +////} + +verify.codeFixAtPosition("greeter()"); diff --git a/tests/cases/fourslash/unusedParameterInFunction2.ts b/tests/cases/fourslash/unusedParameterInFunction2.ts new file mode 100644 index 00000000000..493eafc5722 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInFunction2.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedParameters: true +////function [|greeter(x,y)|] { +//// x++; +////} + +verify.codeFixAtPosition("greeter(x)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInFunction3.ts b/tests/cases/fourslash/unusedParameterInFunction3.ts new file mode 100644 index 00000000000..6d79ba071b4 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInFunction3.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedParameters: true +////function [|greeter(x,y)|] { +//// y++; +////} + +verify.codeFixAtPosition("greeter(y)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInFunction4.ts b/tests/cases/fourslash/unusedParameterInFunction4.ts new file mode 100644 index 00000000000..b536543fb6d --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInFunction4.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedParameters: true +////[|function greeter(x,y,z) |] { +//// x++; +//// z++; +////} + +verify.codeFixAtPosition("function greeter(x,z)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedParameterInLambda1.ts b/tests/cases/fourslash/unusedParameterInLambda1.ts new file mode 100644 index 00000000000..c462b742569 --- /dev/null +++ b/tests/cases/fourslash/unusedParameterInLambda1.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// function f1() { +//// [|return (x:number) => {}|] +//// } + +verify.codeFixAtPosition("return () => {}"); diff --git a/tests/cases/fourslash/unusedTypeAliasInNamespace1.ts b/tests/cases/fourslash/unusedTypeAliasInNamespace1.ts new file mode 100644 index 00000000000..593c0fe8cf4 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeAliasInNamespace1.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// [| namespace greeter { +//// type hw = "Hello" |"world"; +//// export type nw = "No" | "Way"; +//// } |] + +verify.codeFixAtPosition(`namespace greeter { + export type nw = "No" | "Way"; +}`); diff --git a/tests/cases/fourslash/unusedTypeParametersInClass1.ts b/tests/cases/fourslash/unusedTypeParametersInClass1.ts new file mode 100644 index 00000000000..ab654a5150e --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInClass1.ts @@ -0,0 +1,7 @@ +/// + +// @noUnusedLocals: true +////[|class greeter |] { +////} + +verify.codeFixAtPosition("class greeter"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInClass2.ts b/tests/cases/fourslash/unusedTypeParametersInClass2.ts new file mode 100644 index 00000000000..8e860c10e04 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInClass2.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +////[|class greeter |] { +//// public a: X; +////} + +verify.codeFixAtPosition("class greeter"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInClass3.ts b/tests/cases/fourslash/unusedTypeParametersInClass3.ts new file mode 100644 index 00000000000..75ae98f53e0 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInClass3.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +////[|class greeter |] { +//// public a: X; +//// public b: Z; +////} + +verify.codeFixAtPosition("class greeter"); diff --git a/tests/cases/fourslash/unusedTypeParametersInFunction1.ts b/tests/cases/fourslash/unusedTypeParametersInFunction1.ts new file mode 100644 index 00000000000..7177ed41c84 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInFunction1.ts @@ -0,0 +1,6 @@ +/// + +// @noUnusedLocals: true +//// [|function f1() {}|] + +verify.codeFixAtPosition("function f1() {}"); diff --git a/tests/cases/fourslash/unusedTypeParametersInFunction2.ts b/tests/cases/fourslash/unusedTypeParametersInFunction2.ts new file mode 100644 index 00000000000..344ae303c75 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInFunction2.ts @@ -0,0 +1,6 @@ +/// + +// @noUnusedLocals: true +//// [|function f1(a: X) {a}|] + +verify.codeFixAtPosition("function f1(a: X) {a}"); diff --git a/tests/cases/fourslash/unusedTypeParametersInFunction3.ts b/tests/cases/fourslash/unusedTypeParametersInFunction3.ts new file mode 100644 index 00000000000..746b174db18 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInFunction3.ts @@ -0,0 +1,6 @@ +/// + +// @noUnusedLocals: true +//// [|function f1(a: X) {a;var b:Z;b}|] + +verify.codeFixAtPosition("function f1(a: X) {a;var b:Z;b}"); diff --git a/tests/cases/fourslash/unusedTypeParametersInInterface1.ts b/tests/cases/fourslash/unusedTypeParametersInInterface1.ts new file mode 100644 index 00000000000..70d8bc7800c --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInInterface1.ts @@ -0,0 +1,7 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// [|interface I {}|] + +verify.codeFixAtPosition("interface I {}"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInLambda1.ts b/tests/cases/fourslash/unusedTypeParametersInLambda1.ts new file mode 100644 index 00000000000..73d70672368 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInLambda1.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// function f1() { +//// [|return (x:number) => {x}|] +//// } + +verify.codeFixAtPosition("return (x:number) => {x}"); diff --git a/tests/cases/fourslash/unusedTypeParametersInLambda2.ts b/tests/cases/fourslash/unusedTypeParametersInLambda2.ts new file mode 100644 index 00000000000..77c802f5c44 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInLambda2.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// var x : { +//// [|new (a: T): void;|] +//// } + +verify.codeFixAtPosition("new (a: T): void;"); diff --git a/tests/cases/fourslash/unusedTypeParametersInLambda3.ts b/tests/cases/fourslash/unusedTypeParametersInLambda3.ts new file mode 100644 index 00000000000..0ecb0338be2 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInLambda3.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// class A { public x: Dummy } +//// var x : { +//// [|new (a: T): A;|] +//// } + +verify.codeFixAtPosition("new (a: T): A;"); diff --git a/tests/cases/fourslash/unusedTypeParametersInLambda4.ts b/tests/cases/fourslash/unusedTypeParametersInLambda4.ts new file mode 100644 index 00000000000..5a226fc9005 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInLambda4.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +//// class A { +//// public x: T; +//// } +//// [|var y: new (a:T)=>void;|] + +verify.codeFixAtPosition("var y: new (a:T)=>void;"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInMethod1.ts b/tests/cases/fourslash/unusedTypeParametersInMethod1.ts new file mode 100644 index 00000000000..7a9f04147d6 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInMethod1.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|f1()|] {} +//// } + +verify.codeFixAtPosition("f1()"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInMethod2.ts b/tests/cases/fourslash/unusedTypeParametersInMethod2.ts new file mode 100644 index 00000000000..3650cfbad98 --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInMethod2.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class C1 { +//// [|f1(a: U)|] {a;} +//// } + +verify.codeFixAtPosition("f1(a: U)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedTypeParametersInMethods1.ts b/tests/cases/fourslash/unusedTypeParametersInMethods1.ts new file mode 100644 index 00000000000..cb9b965ca4d --- /dev/null +++ b/tests/cases/fourslash/unusedTypeParametersInMethods1.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +//// class A { +//// [|public f1(a: X)|] { a; var b: Z; b } +//// } + +verify.codeFixAtPosition("public f1(a: X)"); diff --git a/tests/cases/fourslash/unusedVariableInBlocks.ts b/tests/cases/fourslash/unusedVariableInBlocks.ts new file mode 100644 index 00000000000..e9dedaef31e --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInBlocks.ts @@ -0,0 +1,15 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// [|let x = 10; +//// { +//// let x = 11; +//// } +//// x;|] +//// } + +verify.codeFixAtPosition(`let x = 10; + { + } + x;`); diff --git a/tests/cases/fourslash/unusedVariableInClass1.ts b/tests/cases/fourslash/unusedVariableInClass1.ts new file mode 100644 index 00000000000..82bb99016ef --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInClass1.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +////class greeter { +//// [|private greeting: string;|] +////} + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInClass2.ts b/tests/cases/fourslash/unusedVariableInClass2.ts new file mode 100644 index 00000000000..c971092584a --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInClass2.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +////class greeter { +//// [|public greeting1; +//// private greeting: string;|] +////} + +verify.codeFixAtPosition("public greeting1;"); diff --git a/tests/cases/fourslash/unusedVariableInClass3.ts b/tests/cases/fourslash/unusedVariableInClass3.ts new file mode 100644 index 00000000000..8d2a62e7175 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInClass3.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +////class greeter {[| +//// private X = function() {}; +////|]} + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInForLoop1FS.ts b/tests/cases/fourslash/unusedVariableInForLoop1FS.ts new file mode 100644 index 00000000000..0ee02ab4363 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop1FS.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// [|for(var i = 0; ;) |]{ +//// +//// } +//// } + +verify.codeFixAtPosition("for(; ;)"); + diff --git a/tests/cases/fourslash/unusedVariableInForLoop2FS.ts b/tests/cases/fourslash/unusedVariableInForLoop2FS.ts new file mode 100644 index 00000000000..1b1a0798c04 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop2FS.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// [|for(var i = 0, j= 0; ;i++)|] { +//// +//// } +//// } + +verify.codeFixAtPosition("for(var i = 0; ;i++)"); diff --git a/tests/cases/fourslash/unusedVariableInForLoop3FS.ts b/tests/cases/fourslash/unusedVariableInForLoop3FS.ts new file mode 100644 index 00000000000..4eed9599b15 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop3FS.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// [|for(var i = 0, j= 0, k=0; ;i++, k++)|] { +//// +//// } +//// } + +verify.codeFixAtPosition("for(var i = 0, k=0; ;i++,k++)"); \ No newline at end of file diff --git a/tests/cases/fourslash/unusedVariableInForLoop4FS.ts b/tests/cases/fourslash/unusedVariableInForLoop4FS.ts new file mode 100644 index 00000000000..76e551612ba --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop4FS.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// [|for(var i = 0, j= 0, k=0; ;j++, k++) |]{ +//// +//// } +//// } + +verify.codeFixAtPosition("for(var j = 0, k=0; ;j++,k++)"); diff --git a/tests/cases/fourslash/unusedVariableInForLoop5FS.ts b/tests/cases/fourslash/unusedVariableInForLoop5FS.ts new file mode 100644 index 00000000000..23df03480e3 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop5FS.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// for (const elem in ["a", "b", "c"]) { +//// +//// } +//// } + +verify.not.codeFixAvailable(); + diff --git a/tests/cases/fourslash/unusedVariableInForLoop6FS.ts b/tests/cases/fourslash/unusedVariableInForLoop6FS.ts new file mode 100644 index 00000000000..4187c3141b5 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop6FS.ts @@ -0,0 +1,11 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// for ([|const elem of|] ["a", "b", "c"]) { +//// +//// } +//// } + +verify.codeFixAtPosition("const {} of "); + diff --git a/tests/cases/fourslash/unusedVariableInForLoop7FS.ts b/tests/cases/fourslash/unusedVariableInForLoop7FS.ts new file mode 100644 index 00000000000..8fd0fee735e --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInForLoop7FS.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +//// function f1 () { +//// for (const elem of ["a", "b", "c"]) { +//// elem; +//// [|var x = 20;|] +//// } +////} +//// + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInModule1.ts b/tests/cases/fourslash/unusedVariableInModule1.ts new file mode 100644 index 00000000000..011434ce098 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInModule1.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// export {} +//// [|var x: string;|] +//// export var y: string; + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInModule2.ts b/tests/cases/fourslash/unusedVariableInModule2.ts new file mode 100644 index 00000000000..db4519c8faa --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInModule2.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// export {} +//// [|var x: string, z: number;|] +//// z; +//// export var y: string; + +verify.codeFixAtPosition("var z: number;"); diff --git a/tests/cases/fourslash/unusedVariableInModule3.ts b/tests/cases/fourslash/unusedVariableInModule3.ts new file mode 100644 index 00000000000..bffffc768d3 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInModule3.ts @@ -0,0 +1,9 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// export {} +//// [|var x = function f1() {}|] +//// export var y: string; + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInModule4.ts b/tests/cases/fourslash/unusedVariableInModule4.ts new file mode 100644 index 00000000000..6a1be9fe5b8 --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInModule4.ts @@ -0,0 +1,10 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true +//// export {} +//// [|var x = function f1(m: number) {}|] +//// x; +//// export var y: string; + +verify.codeFixAtPosition(`var x = function f1() {}`); diff --git a/tests/cases/fourslash/unusedVariableInNamespace1.ts b/tests/cases/fourslash/unusedVariableInNamespace1.ts new file mode 100644 index 00000000000..caf778bc0da --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInNamespace1.ts @@ -0,0 +1,8 @@ +/// + +// @noUnusedLocals: true +////namespace greeter { +//// [|let a = "dummy entry";|] +////} + +verify.codeFixAtPosition(""); diff --git a/tests/cases/fourslash/unusedVariableInNamespace2.ts b/tests/cases/fourslash/unusedVariableInNamespace2.ts new file mode 100644 index 00000000000..fbb9e2d6a0c --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInNamespace2.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +////namespace greeter { +//// [|let a = "dummy entry", b, c = 0;|] +//// export function function1() { +//// a = "dummy"; +//// c++; +//// } +////} + +verify.codeFixAtPosition(`let a = "dummy entry", c = 0;`); diff --git a/tests/cases/fourslash/unusedVariableInNamespace3.ts b/tests/cases/fourslash/unusedVariableInNamespace3.ts new file mode 100644 index 00000000000..33e501d0c0d --- /dev/null +++ b/tests/cases/fourslash/unusedVariableInNamespace3.ts @@ -0,0 +1,12 @@ +/// + +// @noUnusedLocals: true +////namespace greeter { +//// [|let a = "dummy entry", b, c = 0;|] +//// export function function1() { +//// a = "dummy"; +//// b = 0; +//// } +////} + +verify.codeFixAtPosition(`let a = "dummy entry", b;`); diff --git a/tests/webTestServer.ts b/tests/webTestServer.ts index 97027dfdd49..3d23ef3e961 100644 --- a/tests/webTestServer.ts +++ b/tests/webTestServer.ts @@ -128,7 +128,7 @@ function dir(dirPath: string, spec?: string, options?: any) { // fs.rmdirSync won't delete directories with files in it function deleteFolderRecursive(dirPath: string) { if (fs.existsSync(dirPath)) { - fs.readdirSync(dirPath).forEach((file, index) => { + fs.readdirSync(dirPath).forEach((file) => { const curPath = path.join(path, file); if (fs.statSync(curPath).isDirectory()) { // recurse deleteFolderRecursive(curPath); @@ -141,7 +141,7 @@ function deleteFolderRecursive(dirPath: string) { } }; -function writeFile(path: string, data: any, opts: { recursive: boolean }) { +function writeFile(path: string, data: any) { ensureDirectoriesExist(getDirectoryPath(path)); fs.writeFileSync(path, data); } @@ -208,7 +208,7 @@ enum RequestType { Unknown } -function getRequestOperation(req: http.ServerRequest, filename: string) { +function getRequestOperation(req: http.ServerRequest) { if (req.method === "GET" && req.url.indexOf("?") === -1) { if (req.url.indexOf(".") !== -1) return RequestType.GetFile; else return RequestType.GetDir; @@ -258,7 +258,7 @@ function handleRequestOperation(req: http.ServerRequest, res: http.ServerRespons break; case RequestType.WriteFile: processPost(req, res, (data) => { - writeFile(reqPath, data, { recursive: true }); + writeFile(reqPath, data); }); send(ResponseCode.Success, res, undefined); break; @@ -306,7 +306,7 @@ http.createServer((req: http.ServerRequest, res: http.ServerResponse) => { log(`${req.method} ${req.url}`); const uri = url.parse(req.url).pathname; const reqPath = path.join(process.cwd(), uri); - const operation = getRequestOperation(req, reqPath); + const operation = getRequestOperation(req); handleRequestOperation(req, res, operation, reqPath); }).listen(port); diff --git a/tslint.json b/tslint.json index 81990190ddb..26657981a63 100644 --- a/tslint.json +++ b/tslint.json @@ -17,7 +17,7 @@ "double", "avoid-escape" ], - "semicolon": true, + "semicolon": [true, "ignore-bound-class-methods"], "whitespace": [true, "check-branch", "check-decl", @@ -41,7 +41,6 @@ "no-trailing-whitespace": true, "no-inferrable-types": true, "no-null-keyword": true, - "no-unused-variable": true, "boolean-trivia": true, "type-operator-spacing": true, "prefer-const": true,

{ + value: P; +} + +type Boxified = { + [K in keyof T]: Box; +} + +declare function boxify(obj: T): Boxified; +declare function unboxify(obj: Boxified): T; + +interface Bacon { + isPerfect: boolean; + weight: number; +} + +interface BoxifiedBacon { + isPerfect: Box; + weight: Box; +} + +function f1(b: Bacon) { + let bb = boxify(b); + let isPerfect = bb.isPerfect.value; + let weight = bb.weight.value; +} + +function f2(bb: Boxified) { + let b = unboxify(bb); // Infer Bacon for T + let bool = b.isPerfect; + let weight = b.weight; +} + +function f3(bb: BoxifiedBacon) { + let b = unboxify(bb); // Explicit type parameter required + let bool = b.isPerfect; + let weight = bb.weight; +} \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypes4.ts b/tests/cases/conformance/types/mapped/mappedTypes4.ts new file mode 100644 index 00000000000..74b3e395f32 --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypes4.ts @@ -0,0 +1,62 @@ +// @strictNullChecks: true +// @declaration: true + +type Box = { +}; + +type Boxified = { + [P in keyof T]: Box; +}; + +function boxify(obj: T): Boxified { + if (typeof obj === "object") { + let result = {} as Boxified; + for (let k in obj) { + result[k] = { value: obj[k] }; + } + return result; + } + return obj; +} + +type A = { a: string }; +type B = { b: string }; +type C = { c: string }; + +function f1(x: A | B | C | undefined) { + return boxify(x); +} + +type T00 = Partial; +type T01 = Readonly; +type T02 = Boxified +type T03 = Readonly; +type T04 = Boxified; +type T05 = Partial<"hello" | "world" | 42>; + +type BoxifiedWithSentinel = { + [P in keyof T]: Box | U; +} + +type T10 = BoxifiedWithSentinel; +type T11 = BoxifiedWithSentinel; +type T12 = BoxifiedWithSentinel; + +type DeepReadonly = { + readonly [P in keyof T]: DeepReadonly; +}; + +type Foo = { + x: number; + y: { a: string, b: number }; + z: boolean; +}; + +type DeepReadonlyFoo = { + readonly x: number; + readonly y: { readonly a: string, readonly b: number }; + readonly z: boolean; +}; + +var x1: DeepReadonly; +var x1: DeepReadonlyFoo; \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts b/tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts new file mode 100644 index 00000000000..8023f6e7d8d --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypesAndObjects.ts @@ -0,0 +1,35 @@ +// @strictNullChecks: true +// @declaration: true + +function f1(x: Partial, y: Readonly) { + let obj: {}; + obj = x; + obj = y; +} + +function f2(x: Partial, y: Readonly) { + let obj: { [x: string]: any }; + obj = x; + obj = y; +} + +// Repro from #12900 + +interface Base { + foo: { [key: string]: any }; + bar: any; + baz: any; +} + +interface E1 extends Base { + foo: T; +} + +interface Something { name: string, value: string }; +interface E2 extends Base { + foo: Partial; // or other mapped type +} + +interface E3 extends Base { + foo: Partial; // or other mapped type +} \ No newline at end of file diff --git a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts new file mode 100644 index 00000000000..7a78ad9dc4a --- /dev/null +++ b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts @@ -0,0 +1,15 @@ +// @declaration: true + +// Recursive mapped types simply appear empty + +type Recurse = { + [K in keyof Recurse]: Recurse[K] +} + +type Recurse1 = { + [K in keyof Recurse2]: Recurse2[K] +} + +type Recurse2 = { + [K in keyof Recurse1]: Recurse1[K] +} \ No newline at end of file diff --git a/tests/cases/conformance/types/rest/objectRest.ts b/tests/cases/conformance/types/rest/objectRest.ts new file mode 100644 index 00000000000..2fba5d0b6dc --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRest.ts @@ -0,0 +1,40 @@ +// @target: es2015 +var o = { a: 1, b: 'no' } +var { ...clone } = o; +var { a, ...justB } = o; +var { a, b: renamed, ...empty } = o; +var { ['b']: renamed, ...justA } = o; +var { 'b': renamed, ...justA } = o; +var { b: { '0': n, '1': oooo }, ...justA } = o; + +let o2 = { c: 'terrible idea?', d: 'yes' }; +var { d: renamed, ...d } = o2; + +let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; +var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; + +let complex: { x: { ka, ki }, y: number }; +var { x: { ka, ...nested }, y: other, ...rest } = complex; +({x: { ka, ...nested }, y: other, ...rest} = complex); +var { x, ...fresh } = { x: 1, y: 2 }; +({ x, ...fresh } = { x: 1, y: 2 }); + +class Removable { + private x: number; + protected y: number; + set z(value: number) { } + get both(): number { return 12 } + set both(value: number) { } + m() { } + removed: string; + remainder: string; +} +var removable = new Removable(); +var { removed, ...removableRest } = removable; + +let computed = 'b'; +let computed2 = 'a'; +var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; +({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject['anythingGoes']; diff --git a/tests/cases/conformance/types/rest/objectRest2.ts b/tests/cases/conformance/types/rest/objectRest2.ts new file mode 100644 index 00000000000..4a38123f1ac --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRest2.ts @@ -0,0 +1,15 @@ +// @lib: es2015 +// @target: es2015 +// test for #12203 +declare function connectionFromArray(objects: number, args: any): {}; +function rootConnection(name: string) { + return { + resolve: async (context, args) => { + const { objects } = await { objects: 12 }; + return { + ...connectionFromArray(objects, args) + }; + } + }; +} +rootConnection('test'); diff --git a/tests/cases/conformance/types/rest/objectRestAssignment.ts b/tests/cases/conformance/types/rest/objectRestAssignment.ts new file mode 100644 index 00000000000..dedc99b1f71 --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRestAssignment.ts @@ -0,0 +1,14 @@ +// @target: es2015 +let ka: any; +let nested: { ki }; +let other: number; +let rest: { }; +let complex: { x: { ka, ki }, y: number }; +({x: { ka, ...nested }, y: other, ...rest} = complex); + +// should be: +let overEmit: { a: { ka: string, x: string }[], b: { z: string, ki: string, ku: string }, ke: string, ko: string }; + +// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]); +var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; +({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); diff --git a/tests/cases/conformance/types/rest/objectRestForOf.ts b/tests/cases/conformance/types/rest/objectRestForOf.ts new file mode 100644 index 00000000000..4f675b1f15b --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRestForOf.ts @@ -0,0 +1,14 @@ +// @target: es2015 +let array: { x: number, y: string }[]; +for (let { x, ...restOf } of array) { + [x, restOf]; +} +let xx: number; +let rrestOff: { y: string }; +for ({ x: xx, ...rrestOff } of array ) { + [xx, rrestOff]; +} +for (const norest of array.map(a => ({ ...a, x: 'a string' }))) { + [norest.x, norest.y]; + // x is now a string. who knows why. +} diff --git a/tests/cases/conformance/types/rest/objectRestNegative.ts b/tests/cases/conformance/types/rest/objectRestNegative.ts new file mode 100644 index 00000000000..4f4667fe65a --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRestNegative.ts @@ -0,0 +1,20 @@ +// @noImplicitAny: true +let o = { a: 1, b: 'no' }; +var { ...mustBeLast, a } = o; + +var b: string; +let notAssignable: { a: string }; +({ b, ...notAssignable } = o); + + +function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { +} +function generic(t: T) { + let { x, ...rest } = t; + return rest; +} + +let rest: { b: string } +({a, ...rest.b + rest.b} = o); + +var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; diff --git a/tests/cases/conformance/types/rest/objectRestParameter.ts b/tests/cases/conformance/types/rest/objectRestParameter.ts new file mode 100644 index 00000000000..a9c17a29d14 --- /dev/null +++ b/tests/cases/conformance/types/rest/objectRestParameter.ts @@ -0,0 +1,17 @@ +// @target: es2015 +function cloneAgain({ a, ...clone }: { a: number, b: string }): void { +} + +declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void); +suddenly(({ x: a, ...rest }) => rest.y); +suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); + +class C { + m({ a, ...clone }: { a: number, b: string}): void { + // actually, never mind, don't clone + } + set p({ a, ...clone }: { a: number, b: string}) { + // actually, never mind, don't clone + } +} + diff --git a/tests/cases/conformance/es6/destructuring/restElementMustBeLast.ts b/tests/cases/conformance/types/rest/restElementMustBeLast.ts similarity index 100% rename from tests/cases/conformance/es6/destructuring/restElementMustBeLast.ts rename to tests/cases/conformance/types/rest/restElementMustBeLast.ts diff --git a/tests/cases/conformance/types/spread/objectSpread.ts b/tests/cases/conformance/types/spread/objectSpread.ts new file mode 100644 index 00000000000..ebf2bdb2ade --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpread.ts @@ -0,0 +1,81 @@ +// @target: es5 +let o = { a: 1, b: 'no' } +let o2 = { b: 'yes', c: true } +let swap = { a: 'yes', b: -1 }; + +let addAfter: { a: number, b: string, c: boolean } = + { ...o, c: false } +let addBefore: { a: number, b: string, c: boolean } = + { c: false, ...o } +// Note: ignore still changes the order that properties are printed +let ignore: { a: number, b: string } = + { b: 'ignored', ...o } +let override: { a: number, b: string } = + { ...o, b: 'override' } +let nested: { a: number, b: boolean, c: string } = + { ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' } +let combined: { a: number, b: string, c: boolean } = + { ...o, ...o2 } +let combinedBefore: { a: number, b: string, c: boolean } = + { b: 'ok', ...o, ...o2 } +let combinedMid: { a: number, b: string, c: boolean } = + { ...o, b: 'ok', ...o2 } +let combinedAfter: { a: number, b: string, c: boolean } = + { ...o, ...o2, b: 'ok' } +let combinedNested: { a: number, b: boolean, c: string, d: string } = + { ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } } +let combinedNestedChangeType: { a: number, b: boolean, c: number } = + { ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } +let propertyNested: { a: { a: number, b: string } } = + { a: { ... o } } +// accessors don't copy the descriptor +// (which means that readonly getters become read/write properties) +let op = { get a () { return 6 } }; +let getter: { a: number, c: number } = + { ...op, c: 7 } +getter.a = 12; + +// functions result in { } +let spreadFunc = { ...(function () { }) }; + +// any results in any +let anything: any; +let spreadAny = { ...anything }; + +// methods are not enumerable +class C { p = 1; m() { } } +let c: C = new C() +let spreadC: { p: number } = { ...c } + +// own methods are enumerable +let cplus: { p: number, plus(): void } = { ...c, plus() { return this.p + 1; } }; +cplus.plus(); + +// new field's type conflicting with existing field is OK +let changeTypeAfter: { a: string, b: string } = + { ...o, a: 'wrong type?' } +let changeTypeBefore: { a: number, b: string } = + { a: 'wrong type?', ...o }; +let changeTypeBoth: { a: string, b: number } = + { ...o, ...swap }; + +// optional +let definiteBoolean: { sn: boolean }; +let definiteString: { sn: string }; +let optionalString: { sn?: string }; +let optionalNumber: { sn?: number }; +let optionalUnionStops: { sn: string | number | boolean } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; +let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; +let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + +// computed property +let computedFirst: { a: number, b: string, "before everything": number } = + { ['before everything']: 12, ...o, b: 'yes' } +let computedMiddle: { a: number, b: string, c: boolean, "in the middle": number } = + { ...o, ['in the middle']: 13, b: 'maybe?', ...o2 } +let computedAfter: { a: number, b: string, "at the end": number } = + { ...o, b: 'yeah', ['at the end']: 14 } +// shortcut syntax +let a = 12; +let shortCutted: { a: number, b: string } = { ...o, a } + diff --git a/tests/cases/conformance/types/spread/objectSpreadComputedProperty.ts b/tests/cases/conformance/types/spread/objectSpreadComputedProperty.ts new file mode 100644 index 00000000000..7e2182a2f1d --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadComputedProperty.ts @@ -0,0 +1,9 @@ +// fixes #12200 +function f() { + let n: number = 12; + let m: number = 13; + let a: any = null; + const o1 = { ...{}, [n]: n }; + const o2 = { ...{}, [a]: n }; + const o3 = { [a]: n, ...{}, [n]: n, ...{}, [m]: m }; +} diff --git a/tests/cases/conformance/types/spread/objectSpreadIndexSignature.ts b/tests/cases/conformance/types/spread/objectSpreadIndexSignature.ts new file mode 100644 index 00000000000..ae46f2547d5 --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadIndexSignature.ts @@ -0,0 +1,16 @@ +interface Indexed { + [n: string]: number; + a: number; +} +interface Indexed2 { + [n: string]: boolean; + c: boolean; +} +let indexed: Indexed; +let indexed2: Indexed2; +let i = { ...indexed, b: 11 }; +// only indexed has indexer, so i[101]: any +i[101]; +let ii = { ...indexed, ...indexed2 }; +// both have indexer, so i[1001]: number | boolean +ii[1001]; diff --git a/tests/cases/conformance/types/spread/objectSpreadNegative.ts b/tests/cases/conformance/types/spread/objectSpreadNegative.ts new file mode 100644 index 00000000000..6d1e0dde429 --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadNegative.ts @@ -0,0 +1,69 @@ +// @target: es5 +let o = { a: 1, b: 'no' } + +/// private propagates +class PrivateOptionalX { + private x?: number; +} +class PublicX { + public x: number; +} +let publicX: PublicX; +let privateOptionalX: PrivateOptionalX; +let o2 = { ...publicX, ...privateOptionalX }; +let sn: number = o2.x; // error, x is private +let optionalString: { sn?: string }; +let optionalNumber: { sn?: number }; +let allOptional: { sn: string | number } = { ...optionalString, ...optionalNumber }; +// error, 'sn' is optional in source, required in target + +// assignability as target +interface Bool { b: boolean }; +interface Str { s: string }; +let spread = { ...{ b: true }, ...{s: "foo" } }; +spread = { s: "foo" }; // error, missing 'b' +let b = { b: false }; +spread = b; // error, missing 's' + +// literal repeats are not allowed, but spread repeats are fine +let duplicated = { b: 'bad', ...o, b: 'bad', ...o2, b: 'bad' } +let duplicatedSpread = { ...o, ...o } + +// primitives are not allowed +let spreadNum = { ...12 }; +let spreadSum = { ...1 + 1 }; +spreadSum.toFixed(); // error, no methods from number +let spreadBool = { ...false }; +spreadBool.valueOf(); // error, what were you thinking? +let spreadStr = { ...'foo' }; +spreadStr.length; // error, no 'length' +spreadStr.charAt(1); // error, no methods either +// functions are skipped +let spreadFunc = { ...function () { } } +spreadFunc(); // error, no call signature + +// write-only properties get skipped +let setterOnly = { ...{ set b (bad: number) { } } }; +setterOnly.b = 12; // error, 'b' does not exist + +// methods are skipped because they aren't enumerable +class C { p = 1; m() { } } +let c: C = new C() +let spreadC = { ...c } +spreadC.m(); // error 'm' is not in '{ ... c }' + +// generics +function f(t: T, u: U) { + return { ...t, ...u, id: 'id' }; +} +function override(initial: U, override: U): U { + return { ...initial, ...override }; +} +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +let overlap: { id: string, a: number, b: string } = + f({ a: 1 }, { a: 2, b: 'extra' }) +let overlapConflict: { id:string, a: string } = + f({ a: 1 }, { a: 'mismatch' }) +let overwriteId: { id: string, a: number, c: number, d: string } = + f({ a: 1, id: true }, { c: 1, d: 'no' }) diff --git a/tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts b/tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts new file mode 100644 index 00000000000..47fd787ec9a --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts @@ -0,0 +1,4 @@ +let o7 = { ...o? }; +let o8 = { ...*o }; +let o9 = { ...matchMedia() { }}; +let o10 = { ...get x() { return 12; }}; diff --git a/tests/cases/conformance/types/spread/objectSpreadNoTransform.ts b/tests/cases/conformance/types/spread/objectSpreadNoTransform.ts new file mode 100644 index 00000000000..86bcb7eeee5 --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadNoTransform.ts @@ -0,0 +1,6 @@ +// @target: esnext +const y = { a: 'yes', b: 'no' }; +const o = { x: 1, ...y }; +var b; +var rest: any; +({ b, ...rest } = o); diff --git a/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts new file mode 100644 index 00000000000..087d47df26c --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadStrictNull.ts @@ -0,0 +1,21 @@ +// @strictNullChecks: true + +function f( + definiteBoolean: { sn: boolean }, + definiteString: { sn: string }, + optionalString: { sn?: string }, + optionalNumber: { sn?: number }, + undefinedString: { sn: string | undefined }, + undefinedNumber: { sn: number | undefined }) { + // optional + let optionalUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalNumber }; + let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber }; + let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber }; + + // undefined + let undefinedUnionStops: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedNumber }; + let undefinedUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...undefinedString, ...undefinedNumber }; + let allUndefined: { sn: string | number | undefined } = { ...undefinedString, ...undefinedNumber }; + + let undefinedWithOptionalContinues: { sn: string | number | boolean } = { ...definiteBoolean, ...undefinedString, ...optionalNumber }; +} diff --git a/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties01.ts b/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties01.ts new file mode 100644 index 00000000000..d4f04d78c80 --- /dev/null +++ b/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties01.ts @@ -0,0 +1,11 @@ +// @strictNullChecks: true +// @declaration: true + +interface Foo { + required1: string; + required2: string; + optional?: string; +} + +const foo1 = { required1: "hello" } as Foo; +const foo2 = { required1: "hello", optional: "bar" } as Foo; diff --git a/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties02.ts b/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties02.ts new file mode 100644 index 00000000000..21f83276d44 --- /dev/null +++ b/tests/cases/conformance/types/typeRelationships/comparable/optionalProperties02.ts @@ -0,0 +1,9 @@ +// @strictNullChecks: true +// @declaration: true + +interface Foo { + a?: string; + b: string; +} + +{ a: undefined }; \ No newline at end of file diff --git a/tests/cases/fourslash/basicClassMembers.ts b/tests/cases/fourslash/basicClassMembers.ts index 1407bf89be3..9fad6731973 100644 --- a/tests/cases/fourslash/basicClassMembers.ts +++ b/tests/cases/fourslash/basicClassMembers.ts @@ -7,6 +7,6 @@ goTo.eof(); edit.insert('t.'); -verify.memberListContains('x'); -verify.memberListContains('y'); -verify.not.memberListContains('z'); +verify.completionListContains('x'); +verify.completionListContains('y'); +verify.not.completionListContains('z'); diff --git a/tests/cases/fourslash/commentBraceCompletionPosition.ts b/tests/cases/fourslash/commentBraceCompletionPosition.ts index b92c49d3a14..3730a3466c9 100644 --- a/tests/cases/fourslash/commentBraceCompletionPosition.ts +++ b/tests/cases/fourslash/commentBraceCompletionPosition.ts @@ -14,10 +14,10 @@ //// } goTo.marker('1'); -verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('2'); -verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('3'); -verify.not.isValidBraceCompletionAtPosition('('); \ No newline at end of file +verify.isValidBraceCompletionAtPosition('('); \ No newline at end of file diff --git a/tests/cases/fourslash/commentsClassMembers.ts b/tests/cases/fourslash/commentsClassMembers.ts index 6edb684caa6..1c34584a262 100644 --- a/tests/cases/fourslash/commentsClassMembers.ts +++ b/tests/cases/fourslash/commentsClassMembers.ts @@ -139,18 +139,18 @@ verify.quickInfos({ }); goTo.marker('4'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('5'); verify.completionListContains("b", "(parameter) b: number", "number to add"); @@ -158,18 +158,18 @@ verify.completionListContains("b", "(parameter) b: number", "number to add"); verify.quickInfoAt("6", "(property) c1.p3: number", "getter property 1\nsetter property 1"); goTo.marker('7'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('8'); verify.currentSignatureHelpDocCommentIs("sum with property"); @@ -177,48 +177,48 @@ verify.currentParameterHelpArgumentDocCommentIs("number to add"); verify.quickInfoAt("8q", "(method) c1.p2(b: number): number", "sum with property"); goTo.marker('9'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); verify.quickInfoAt("10", "(property) c1.p3: number", "getter property 1\nsetter property 1"); goTo.marker('11'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('12'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('13'); verify.currentSignatureHelpDocCommentIs("sum with property"); @@ -232,18 +232,18 @@ verify.quickInfos({ }); goTo.marker('16'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('17'); verify.completionListContains("b", "(parameter) b: number", "number to add"); @@ -251,18 +251,18 @@ verify.completionListContains("b", "(parameter) b: number", "number to add"); verify.quickInfoAt("18", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); goTo.marker('19'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('20'); verify.currentSignatureHelpDocCommentIs("sum with property"); @@ -270,48 +270,48 @@ verify.currentParameterHelpArgumentDocCommentIs("number to add"); verify.quickInfoAt("20q", "(method) c1.pp2(b: number): number", "sum with property"); goTo.marker('21'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); verify.quickInfoAt("22", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); goTo.marker('23'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('24'); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.memberListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.memberListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.memberListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.memberListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.memberListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); +verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); +verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); +verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); +verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); goTo.marker('25'); verify.currentSignatureHelpDocCommentIs("sum with property"); @@ -329,12 +329,12 @@ goTo.marker('29'); verify.completionListContains("c1", "class c1", "This is comment for c1"); goTo.marker('30'); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); goTo.marker('31'); verify.completionListContains("b", "(parameter) b: number", "number to add"); @@ -345,12 +345,12 @@ goTo.marker('33'); verify.completionListContains("c1", "class c1", "This is comment for c1"); goTo.marker('34'); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); goTo.marker('35'); verify.currentSignatureHelpDocCommentIs("static sum with property"); @@ -359,12 +359,12 @@ verify.completionListContains("c1", "class c1", "This is comment for c1"); verify.quickInfoAt("35q", "(method) c1.s2(b: number): number", "static sum with property"); goTo.marker('36'); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); verify.quickInfoAt("37", "(property) c1.s3: number", "static getter property\nsetter property 3"); @@ -372,23 +372,23 @@ goTo.marker('38'); verify.completionListContains("c1", "class c1", "This is comment for c1"); goTo.marker('39'); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); goTo.marker('40'); verify.completionListContains("c1", "class c1", "This is comment for c1"); goTo.marker('41'); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); goTo.marker('42'); verify.currentSignatureHelpDocCommentIs("static sum with property"); @@ -477,12 +477,12 @@ verify.quickInfos({ goTo.marker("67"); verify.quickInfoIs("(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.memberListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.memberListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.memberListContains("nc_p3", "(property) c1.nc_p3: number", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); +verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); +verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); +verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); verify.quickInfos({ 68: "var i1_f: (b: number) => number", @@ -526,12 +526,12 @@ verify.completionListContains("c1", "class c1", "This is comment for c1"); goTo.marker('88'); verify.quickInfoIs("(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.memberListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.memberListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.memberListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.memberListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.memberListContains("nc_s3", "(property) c1.nc_s3: number", ""); +verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); +verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); +verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); +verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); +verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); +verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); verify.quickInfos({ 89: "var i1_s_f: (b: number) => number", @@ -593,10 +593,10 @@ verify.completionListContains("i1_c", "var i1_c: typeof c1", ""); goTo.marker('110'); verify.quickInfoIs("(property) cProperties.p2: number", "setter only property"); -verify.memberListContains("p1", "(property) cProperties.p1: number", "getter only property"); -verify.memberListContains("p2", "(property) cProperties.p2: number", "setter only property"); -verify.memberListContains("nc_p1", "(property) cProperties.nc_p1: number", ""); -verify.memberListContains("nc_p2", "(property) cProperties.nc_p2: number", ""); +verify.completionListContains("p1", "(property) cProperties.p1: number", "getter only property"); +verify.completionListContains("p2", "(property) cProperties.p2: number", "setter only property"); +verify.completionListContains("nc_p1", "(property) cProperties.nc_p1: number", ""); +verify.completionListContains("nc_p2", "(property) cProperties.nc_p2: number", ""); verify.quickInfos({ 111: ["(property) cProperties.p1: number", "getter only property"], @@ -605,7 +605,7 @@ verify.quickInfos({ }); goTo.marker('114'); -verify.memberListContains("a", "(property) cWithConstructorProperty.a: number", "this is first parameter a\nmore info about a"); +verify.completionListContains("a", "(property) cWithConstructorProperty.a: number", "this is first parameter a\nmore info about a"); verify.quickInfoIs("(property) cWithConstructorProperty.a: number", "this is first parameter a\nmore info about a"); goTo.marker('115'); diff --git a/tests/cases/fourslash/commentsEnums.ts b/tests/cases/fourslash/commentsEnums.ts index 048c99c6e0c..bf0bc087372 100644 --- a/tests/cases/fourslash/commentsEnums.ts +++ b/tests/cases/fourslash/commentsEnums.ts @@ -22,11 +22,11 @@ verify.completionListContains("Colors", "enum Colors", "Enum of colors"); verify.quickInfoIs("enum Colors", "Enum of colors"); goTo.marker('6'); -verify.memberListContains("Cornflower", "(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); -verify.memberListContains("FancyPink", "(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); +verify.completionListContains("Cornflower", "(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); +verify.completionListContains("FancyPink", "(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); verify.quickInfoIs("(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); goTo.marker('7'); -verify.memberListContains("Cornflower", "(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); -verify.memberListContains("FancyPink", "(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); +verify.completionListContains("Cornflower", "(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); +verify.completionListContains("FancyPink", "(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); verify.quickInfoIs("(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); \ No newline at end of file diff --git a/tests/cases/fourslash/commentsExternalModules.ts b/tests/cases/fourslash/commentsExternalModules.ts index d9773716369..4f1a82bc0ce 100644 --- a/tests/cases/fourslash/commentsExternalModules.ts +++ b/tests/cases/fourslash/commentsExternalModules.ts @@ -46,9 +46,9 @@ goTo.marker('4'); verify.completionListContains("m1", "namespace m1", "Namespace comment"); goTo.marker('5'); -verify.memberListContains("b", "var m1.b: number", "b's comment"); -verify.memberListContains("fooExport", "function m1.fooExport(): number", "exported function"); -verify.memberListContains("m2", "namespace m1.m2"); +verify.completionListContains("b", "var m1.b: number", "b's comment"); +verify.completionListContains("fooExport", "function m1.fooExport(): number", "exported function"); +verify.completionListContains("m2", "namespace m1.m2"); goTo.marker('6'); verify.currentSignatureHelpDocCommentIs("exported function"); @@ -57,8 +57,8 @@ verify.quickInfoAt("6q", "function m1.fooExport(): number", "exported function") verify.quickInfoAt("7", "var myvar: m1.m2.c"); goTo.marker('8'); -verify.memberListContains("c", "constructor m1.m2.c(): m1.m2.c", ""); -verify.memberListContains("i", "var m1.m2.i: m1.m2.c", "i"); +verify.completionListContains("c", "constructor m1.m2.c(): m1.m2.c", ""); +verify.completionListContains("i", "var m1.m2.i: m1.m2.c", "i"); goTo.file("commentsExternalModules_file1.ts"); verify.quickInfoAt("9", 'import extMod = require("./commentsExternalModules_file0")', "This is on import declaration"); @@ -67,12 +67,12 @@ goTo.marker('10'); verify.completionListContains("extMod", 'import extMod = require("./commentsExternalModules_file0")', "This is on import declaration"); goTo.marker('11'); -verify.memberListContains("m1", "namespace extMod.m1"); +verify.completionListContains("m1", "namespace extMod.m1"); goTo.marker('12'); -verify.memberListContains("b", "var extMod.m1.b: number", "b's comment"); -verify.memberListContains("fooExport", "function extMod.m1.fooExport(): number", "exported function"); -verify.memberListContains("m2", "namespace extMod.m1.m2"); +verify.completionListContains("b", "var extMod.m1.b: number", "b's comment"); +verify.completionListContains("fooExport", "function extMod.m1.fooExport(): number", "exported function"); +verify.completionListContains("m2", "namespace extMod.m1.m2"); goTo.marker('13'); verify.currentSignatureHelpDocCommentIs("exported function"); @@ -81,5 +81,5 @@ verify.quickInfoAt("13q", "function extMod.m1.fooExport(): number", "exported fu verify.quickInfoAt("14", "var newVar: extMod.m1.m2.c"); goTo.marker('15'); -verify.memberListContains("c", "constructor extMod.m1.m2.c(): extMod.m1.m2.c", ""); -verify.memberListContains("i", "var extMod.m1.m2.i: extMod.m1.m2.c", "i"); +verify.completionListContains("c", "constructor extMod.m1.m2.c(): extMod.m1.m2.c", ""); +verify.completionListContains("i", "var extMod.m1.m2.i: extMod.m1.m2.c", "i"); diff --git a/tests/cases/fourslash/commentsImportDeclaration.ts b/tests/cases/fourslash/commentsImportDeclaration.ts index 76f2c64a51d..cda983a9e5a 100644 --- a/tests/cases/fourslash/commentsImportDeclaration.ts +++ b/tests/cases/fourslash/commentsImportDeclaration.ts @@ -30,12 +30,12 @@ verify.quickInfos({ }); goTo.marker('6'); -verify.memberListContains("m1", "namespace extMod.m1"); +verify.completionListContains("m1", "namespace extMod.m1"); goTo.marker('7'); -verify.memberListContains("b", "var extMod.m1.b: number", "b's comment"); -verify.memberListContains("fooExport", "function extMod.m1.fooExport(): number", "exported function"); -verify.memberListContains("m2", "namespace extMod.m1.m2"); +verify.completionListContains("b", "var extMod.m1.b: number", "b's comment"); +verify.completionListContains("fooExport", "function extMod.m1.fooExport(): number", "exported function"); +verify.completionListContains("m2", "namespace extMod.m1.m2"); goTo.marker('8'); verify.currentSignatureHelpDocCommentIs("exported function"); @@ -45,5 +45,5 @@ verify.quickInfos({ }); goTo.marker('10'); -verify.memberListContains("c", "constructor extMod.m1.m2.c(): extMod.m1.m2.c", ""); -verify.memberListContains("i", "var extMod.m1.m2.i: extMod.m1.m2.c", "i"); +verify.completionListContains("c", "constructor extMod.m1.m2.c(): extMod.m1.m2.c", ""); +verify.completionListContains("i", "var extMod.m1.m2.i: extMod.m1.m2.c", "i"); diff --git a/tests/cases/fourslash/commentsInheritance.ts b/tests/cases/fourslash/commentsInheritance.ts index fd7aa12e805..6e3e92cfcff 100644 --- a/tests/cases/fourslash/commentsInheritance.ts +++ b/tests/cases/fourslash/commentsInheritance.ts @@ -221,18 +221,18 @@ ////} goTo.marker('1'); -verify.memberListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); -verify.memberListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); -verify.memberListContains("i1_l1", "(property) i1.i1_l1: () => void", ""); -verify.memberListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); -verify.memberListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); -verify.memberListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) i1.p1: number", ""); -verify.memberListContains("f1", "(method) i1.f1(): void", ""); -verify.memberListContains("l1", "(property) i1.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) i1.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) i1.nc_f1(): void", ""); -verify.memberListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); +verify.completionListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); +verify.completionListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); +verify.completionListContains("i1_l1", "(property) i1.i1_l1: () => void", ""); +verify.completionListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); +verify.completionListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); +verify.completionListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) i1.p1: number", ""); +verify.completionListContains("f1", "(method) i1.f1(): void", ""); +verify.completionListContains("l1", "(property) i1.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) i1.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) i1.nc_f1(): void", ""); +verify.completionListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); goTo.marker('2'); verify.currentSignatureHelpDocCommentIs("i1_f1"); goTo.marker('3'); @@ -263,18 +263,18 @@ verify.quickInfos({ }); goTo.marker('6'); -verify.memberListContains("i1_p1", "(property) c1.i1_p1: number", ""); -verify.memberListContains("i1_f1", "(method) c1.i1_f1(): void", ""); -verify.memberListContains("i1_l1", "(property) c1.i1_l1: () => void", ""); -verify.memberListContains("i1_nc_p1", "(property) c1.i1_nc_p1: number", ""); -verify.memberListContains("i1_nc_f1", "(method) c1.i1_nc_f1(): void", ""); -verify.memberListContains("i1_nc_l1", "(property) c1.i1_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) c1.p1: number", "c1_p1"); -verify.memberListContains("f1", "(method) c1.f1(): void", "c1_f1"); -verify.memberListContains("l1", "(property) c1.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) c1.nc_p1: number", "c1_nc_p1"); -verify.memberListContains("nc_f1", "(method) c1.nc_f1(): void", "c1_nc_f1"); -verify.memberListContains("nc_l1", "(property) c1.nc_l1: () => void", ""); +verify.completionListContains("i1_p1", "(property) c1.i1_p1: number", ""); +verify.completionListContains("i1_f1", "(method) c1.i1_f1(): void", ""); +verify.completionListContains("i1_l1", "(property) c1.i1_l1: () => void", ""); +verify.completionListContains("i1_nc_p1", "(property) c1.i1_nc_p1: number", ""); +verify.completionListContains("i1_nc_f1", "(method) c1.i1_nc_f1(): void", ""); +verify.completionListContains("i1_nc_l1", "(property) c1.i1_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) c1.p1: number", "c1_p1"); +verify.completionListContains("f1", "(method) c1.f1(): void", "c1_f1"); +verify.completionListContains("l1", "(property) c1.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", "c1_nc_p1"); +verify.completionListContains("nc_f1", "(method) c1.nc_f1(): void", "c1_nc_f1"); +verify.completionListContains("nc_l1", "(property) c1.nc_l1: () => void", ""); goTo.marker('7'); verify.currentSignatureHelpDocCommentIs(""); goTo.marker('8'); @@ -305,18 +305,18 @@ verify.quickInfos({ }); goTo.marker('11'); -verify.memberListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); -verify.memberListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); -verify.memberListContains("i1_l1", "(property) i1.i1_l1: () => void", ""); -verify.memberListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); -verify.memberListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); -verify.memberListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) i1.p1: number", ""); -verify.memberListContains("f1", "(method) i1.f1(): void", ""); -verify.memberListContains("l1", "(property) i1.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) i1.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) i1.nc_f1(): void", ""); -verify.memberListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); +verify.completionListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); +verify.completionListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); +verify.completionListContains("i1_l1", "(property) i1.i1_l1: () => void", ""); +verify.completionListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); +verify.completionListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); +verify.completionListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) i1.p1: number", ""); +verify.completionListContains("f1", "(method) i1.f1(): void", ""); +verify.completionListContains("l1", "(property) i1.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) i1.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) i1.nc_f1(): void", ""); +verify.completionListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); goTo.marker('12'); verify.currentSignatureHelpDocCommentIs("i1_f1"); goTo.marker('13'); @@ -376,18 +376,18 @@ verify.quickInfos({ }); goTo.marker('19'); -verify.memberListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.memberListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.memberListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.memberListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.memberListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.memberListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); -verify.memberListContains("p1", "(property) c2.p1: number", "c2 p1"); -verify.memberListContains("f1", "(method) c2.f1(): void", "c2 f1"); -verify.memberListContains("prop", "(property) c2.prop: number", "c2 prop"); -verify.memberListContains("nc_p1", "(property) c2.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) c2.nc_f1(): void", ""); -verify.memberListContains("nc_prop", "(property) c2.nc_prop: number", ""); +verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); +verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); +verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); +verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); +verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); +verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); +verify.completionListContains("p1", "(property) c2.p1: number", "c2 p1"); +verify.completionListContains("f1", "(method) c2.f1(): void", "c2 f1"); +verify.completionListContains("prop", "(property) c2.prop: number", "c2 prop"); +verify.completionListContains("nc_p1", "(property) c2.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) c2.nc_f1(): void", ""); +verify.completionListContains("nc_prop", "(property) c2.nc_prop: number", ""); goTo.marker('20'); verify.currentSignatureHelpDocCommentIs("c2 c2_f1"); goTo.marker('21'); @@ -405,18 +405,18 @@ verify.quickInfos({ }); goTo.marker('24'); -verify.memberListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.memberListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.memberListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.memberListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.memberListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.memberListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); -verify.memberListContains("p1", "(property) c3.p1: number", "c3 p1"); -verify.memberListContains("f1", "(method) c3.f1(): void", "c3 f1"); -verify.memberListContains("prop", "(property) c3.prop: number", "c3 prop"); -verify.memberListContains("nc_p1", "(property) c3.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) c3.nc_f1(): void", ""); -verify.memberListContains("nc_prop", "(property) c3.nc_prop: number", ""); +verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); +verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); +verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); +verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); +verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); +verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); +verify.completionListContains("p1", "(property) c3.p1: number", "c3 p1"); +verify.completionListContains("f1", "(method) c3.f1(): void", "c3 f1"); +verify.completionListContains("prop", "(property) c3.prop: number", "c3 prop"); +verify.completionListContains("nc_p1", "(property) c3.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) c3.nc_f1(): void", ""); +verify.completionListContains("nc_prop", "(property) c3.nc_prop: number", ""); goTo.marker('25'); verify.currentSignatureHelpDocCommentIs("c2 c2_f1"); goTo.marker('26'); @@ -434,18 +434,18 @@ verify.quickInfos({ }); goTo.marker('29'); -verify.memberListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.memberListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.memberListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.memberListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.memberListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.memberListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number"); -verify.memberListContains("p1", "(property) c2.p1: number", "c2 p1"); -verify.memberListContains("f1", "(method) c2.f1(): void", "c2 f1"); -verify.memberListContains("prop", "(property) c2.prop: number", "c2 prop"); -verify.memberListContains("nc_p1", "(property) c2.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) c2.nc_f1(): void", ""); -verify.memberListContains("nc_prop", "(property) c2.nc_prop: number", ""); +verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); +verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); +verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); +verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); +verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); +verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number"); +verify.completionListContains("p1", "(property) c2.p1: number", "c2 p1"); +verify.completionListContains("f1", "(method) c2.f1(): void", "c2 f1"); +verify.completionListContains("prop", "(property) c2.prop: number", "c2 prop"); +verify.completionListContains("nc_p1", "(property) c2.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) c2.nc_f1(): void", ""); +verify.completionListContains("nc_prop", "(property) c2.nc_prop: number", ""); goTo.marker('30'); verify.currentSignatureHelpDocCommentIs("c2 c2_f1"); goTo.marker('31'); @@ -478,18 +478,18 @@ verify.completionListContains("c4", "class c4", ""); verify.completionListContains("c4_i", "var c4_i: c4", ""); goTo.marker('36'); -verify.memberListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.memberListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.memberListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); -verify.memberListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.memberListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.memberListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) i2.p1: number", "i2 p1"); -verify.memberListContains("f1", "(method) i2.f1(): void", "i2 f1"); -verify.memberListContains("l1", "(property) i2.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) i2.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) i2.nc_f1(): void", ""); -verify.memberListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); +verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); +verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); +verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); +verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); +verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); +verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) i2.p1: number", "i2 p1"); +verify.completionListContains("f1", "(method) i2.f1(): void", "i2 f1"); +verify.completionListContains("l1", "(property) i2.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) i2.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) i2.nc_f1(): void", ""); +verify.completionListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); goTo.marker('37'); verify.currentSignatureHelpDocCommentIs("i2_f1"); goTo.marker('38'); @@ -521,18 +521,18 @@ verify.quickInfos({ }); goTo.marker('41'); -verify.memberListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.memberListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.memberListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); -verify.memberListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.memberListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.memberListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) i3.p1: number", "i3 p1"); -verify.memberListContains("f1", "(method) i3.f1(): void", "i3 f1"); -verify.memberListContains("l1", "(property) i3.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) i3.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) i3.nc_f1(): void", ""); -verify.memberListContains("nc_l1", "(property) i3.nc_l1: () => void", ""); +verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); +verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); +verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); +verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); +verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); +verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) i3.p1: number", "i3 p1"); +verify.completionListContains("f1", "(method) i3.f1(): void", "i3 f1"); +verify.completionListContains("l1", "(property) i3.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) i3.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) i3.nc_f1(): void", ""); +verify.completionListContains("nc_l1", "(property) i3.nc_l1: () => void", ""); goTo.marker('42'); verify.currentSignatureHelpDocCommentIs("i2_f1"); goTo.marker('43'); @@ -562,18 +562,18 @@ verify.quickInfos({ }); goTo.marker('46'); -verify.memberListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.memberListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.memberListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); -verify.memberListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.memberListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.memberListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.memberListContains("p1", "(property) i2.p1: number", "i2 p1"); -verify.memberListContains("f1", "(method) i2.f1(): void", "i2 f1"); -verify.memberListContains("l1", "(property) i2.l1: () => void", ""); -verify.memberListContains("nc_p1", "(property) i2.nc_p1: number", ""); -verify.memberListContains("nc_f1", "(method) i2.nc_f1(): void", ""); -verify.memberListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); +verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); +verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); +verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", ""); +verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); +verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); +verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); +verify.completionListContains("p1", "(property) i2.p1: number", "i2 p1"); +verify.completionListContains("f1", "(method) i2.f1(): void", "i2 f1"); +verify.completionListContains("l1", "(property) i2.l1: () => void", ""); +verify.completionListContains("nc_p1", "(property) i2.nc_p1: number", ""); +verify.completionListContains("nc_f1", "(method) i2.nc_f1(): void", ""); +verify.completionListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); goTo.marker('47'); verify.currentSignatureHelpDocCommentIs("i2_f1"); goTo.marker('48'); diff --git a/tests/cases/fourslash/commentsInterface.ts b/tests/cases/fourslash/commentsInterface.ts index 49928f0d086..472798fa8e1 100644 --- a/tests/cases/fourslash/commentsInterface.ts +++ b/tests/cases/fourslash/commentsInterface.ts @@ -80,12 +80,12 @@ verify.quickInfos({ goTo.marker('8'); verify.quickInfoIs("(property) i2.x: number", "this is x"); -verify.memberListContains("x", "(property) i2.x: number", "this is x"); -verify.memberListContains("foo", "(property) i2.foo: (b: number) => string", "this is foo"); -verify.memberListContains("nc_x", "(property) i2.nc_x: number", ""); -verify.memberListContains("nc_foo", "(property) i2.nc_foo: (b: number) => string", ""); -verify.memberListContains("fnfoo", "(method) i2.fnfoo(b: number): string", "this is fnfoo"); -verify.memberListContains("nc_fnfoo", "(method) i2.nc_fnfoo(b: number): string", ""); +verify.completionListContains("x", "(property) i2.x: number", "this is x"); +verify.completionListContains("foo", "(property) i2.foo: (b: number) => string", "this is foo"); +verify.completionListContains("nc_x", "(property) i2.nc_x: number", ""); +verify.completionListContains("nc_foo", "(property) i2.nc_foo: (b: number) => string", ""); +verify.completionListContains("fnfoo", "(method) i2.fnfoo(b: number): string", "this is fnfoo"); +verify.completionListContains("nc_fnfoo", "(method) i2.nc_fnfoo(b: number): string", ""); verify.quickInfos({ 9: "var i2_i_foo: (b: number) => string", @@ -199,12 +199,12 @@ verify.completionListContains("i3_i", "var i3_i: i3", ""); goTo.marker('41'); verify.quickInfoIs("(method) i3.f(a: number): string", "Function i3 f"); -verify.memberListContains("f", "(method) i3.f(a: number): string", "Function i3 f"); -verify.memberListContains("l", "(property) i3.l: (b: number) => string", ""); -verify.memberListContains("x", "(property) i3.x: number", "Comment i3 x"); -verify.memberListContains("nc_f", "(method) i3.nc_f(a: number): string", ""); -verify.memberListContains("nc_l", "(property) i3.nc_l: (b: number) => string", ""); -verify.memberListContains("nc_x", "(property) i3.nc_x: number", ""); +verify.completionListContains("f", "(method) i3.f(a: number): string", "Function i3 f"); +verify.completionListContains("l", "(property) i3.l: (b: number) => string", ""); +verify.completionListContains("x", "(property) i3.x: number", "Comment i3 x"); +verify.completionListContains("nc_f", "(method) i3.nc_f(a: number): string", ""); +verify.completionListContains("nc_l", "(property) i3.nc_l: (b: number) => string", ""); +verify.completionListContains("nc_x", "(property) i3.nc_x: number", ""); goTo.marker('42'); verify.currentSignatureHelpDocCommentIs("Function i3 f"); diff --git a/tests/cases/fourslash/commentsLinePreservation.ts b/tests/cases/fourslash/commentsLinePreservation.ts index 6d085f71f80..3f60bdbf43b 100644 --- a/tests/cases/fourslash/commentsLinePreservation.ts +++ b/tests/cases/fourslash/commentsLinePreservation.ts @@ -105,6 +105,14 @@ //// * second time information about the param again //// */ ////function /*l*/l(param1: string) { /*9*/param1 = "hello"; } +//// /** +//// * This is firstLine +//// This is second Line +//// [1]: third * line +//// @param param1 first Line text +//// second line text +//// */ +////function /*m*/m(param1: string) { /*10*/param1 = "hello"; } verify.quickInfos({ a: ["var a: string", "This is firstLine\nThis is second Line\n\nThis is fourth Line"], @@ -136,5 +144,8 @@ verify.quickInfos({ 8: ["(parameter) param1: string", "hello "], l: ["function l(param1: string): void", "This is firstLine\nThis is second Line"], - 9: ["(parameter) param1: string", "first Line text\nblank line that shouldnt be shown when starting this \nsecond time information about the param again"] + 9: ["(parameter) param1: string", "first Line text\nblank line that shouldnt be shown when starting this \nsecond time information about the param again"], + + m: ["function m(param1: string): void", "This is firstLine\nThis is second Line\n[1]: third * line"], + 10: ["(parameter) param1: string", "first Line text\nsecond line text"] }); diff --git a/tests/cases/fourslash/commentsModules.ts b/tests/cases/fourslash/commentsModules.ts index 5f9457d81f4..c0b8ccc5731 100644 --- a/tests/cases/fourslash/commentsModules.ts +++ b/tests/cases/fourslash/commentsModules.ts @@ -110,9 +110,9 @@ goTo.marker('4'); verify.completionListContains("m1", "namespace m1", "Namespace comment"); goTo.marker('5'); -verify.memberListContains("b", "var m1.b: number", "b's comment"); -verify.memberListContains("fooExport", "function m1.fooExport(): number", "exported function"); -verify.memberListContains("m2", "namespace m1.m2"); +verify.completionListContains("b", "var m1.b: number", "b's comment"); +verify.completionListContains("fooExport", "function m1.fooExport(): number", "exported function"); +verify.completionListContains("m2", "namespace m1.m2"); verify.quickInfoIs("function m1.fooExport(): number", "exported function"); goTo.marker('6'); @@ -122,55 +122,55 @@ verify.quickInfoAt("7", "var myvar: m1.m2.c"); goTo.marker('8'); verify.quickInfoIs("constructor m1.m2.c(): m1.m2.c"); -verify.memberListContains("c", "constructor m1.m2.c(): m1.m2.c", ""); -verify.memberListContains("i", "var m1.m2.i: m1.m2.c", "i"); +verify.completionListContains("c", "constructor m1.m2.c(): m1.m2.c", ""); +verify.completionListContains("i", "var m1.m2.i: m1.m2.c", "i"); goTo.marker('9'); verify.completionListContains("m2", "namespace m2", "namespace comment of m2.m3"); verify.quickInfoIs("namespace m2", "namespace comment of m2.m3"); goTo.marker('10'); -verify.memberListContains("m3", "namespace m2.m3"); +verify.completionListContains("m3", "namespace m2.m3"); verify.quickInfoIs("namespace m2.m3", "namespace comment of m2.m3"); goTo.marker('11'); verify.quickInfoIs("constructor m2.m3.c(): m2.m3.c"); -verify.memberListContains("c", "constructor m2.m3.c(): m2.m3.c", ""); +verify.completionListContains("c", "constructor m2.m3.c(): m2.m3.c", ""); goTo.marker('12'); verify.completionListContains("m3", "namespace m3", "namespace comment of m3.m4.m5"); verify.quickInfoIs("namespace m3", "namespace comment of m3.m4.m5"); goTo.marker('13'); -verify.memberListContains("m4", "namespace m3.m4", "namespace comment of m3.m4.m5"); +verify.completionListContains("m4", "namespace m3.m4", "namespace comment of m3.m4.m5"); verify.quickInfoIs("namespace m3.m4", "namespace comment of m3.m4.m5"); goTo.marker('14'); -verify.memberListContains("m5", "namespace m3.m4.m5"); +verify.completionListContains("m5", "namespace m3.m4.m5"); verify.quickInfoIs("namespace m3.m4.m5", "namespace comment of m3.m4.m5"); goTo.marker('15'); verify.quickInfoIs("constructor m3.m4.m5.c(): m3.m4.m5.c"); -verify.memberListContains("c", "constructor m3.m4.m5.c(): m3.m4.m5.c", ""); +verify.completionListContains("c", "constructor m3.m4.m5.c(): m3.m4.m5.c", ""); goTo.marker('16'); verify.completionListContains("m4", "namespace m4", "namespace comment of m4.m5.m6"); verify.quickInfoIs("namespace m4", "namespace comment of m4.m5.m6"); goTo.marker('17'); -verify.memberListContains("m5", "namespace m4.m5", "namespace comment of m4.m5.m6"); +verify.completionListContains("m5", "namespace m4.m5", "namespace comment of m4.m5.m6"); verify.quickInfoIs("namespace m4.m5", "namespace comment of m4.m5.m6"); goTo.marker('18'); -verify.memberListContains("m6", "namespace m4.m5.m6"); +verify.completionListContains("m6", "namespace m4.m5.m6"); verify.quickInfoIs("namespace m4.m5.m6", "namespace comment of m4.m5.m6"); goTo.marker('19'); -verify.memberListContains("m7", "namespace m4.m5.m6.m7"); +verify.completionListContains("m7", "namespace m4.m5.m6.m7"); verify.quickInfoIs("namespace m4.m5.m6.m7"); goTo.marker('20'); -verify.memberListContains("c", "constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", ""); +verify.completionListContains("c", "constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", ""); verify.quickInfoIs("constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c"); goTo.marker('21'); @@ -178,19 +178,19 @@ verify.completionListContains("m5", "namespace m5"); verify.quickInfoIs("namespace m5", "namespace comment of m5.m6.m7"); goTo.marker('22'); -verify.memberListContains("m6", "namespace m5.m6"); +verify.completionListContains("m6", "namespace m5.m6"); verify.quickInfoIs("namespace m5.m6", "namespace comment of m5.m6.m7"); goTo.marker('23'); -verify.memberListContains("m7", "namespace m5.m6.m7"); +verify.completionListContains("m7", "namespace m5.m6.m7"); verify.quickInfoIs("namespace m5.m6.m7", "namespace comment of m5.m6.m7"); goTo.marker('24'); -verify.memberListContains("m8", "namespace m5.m6.m7.m8"); +verify.completionListContains("m8", "namespace m5.m6.m7.m8"); verify.quickInfoIs("namespace m5.m6.m7.m8", "namespace m8 comment"); goTo.marker('25'); -verify.memberListContains("c", "constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c", ""); +verify.completionListContains("c", "constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c", ""); verify.quickInfoIs("constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c"); goTo.marker('26'); @@ -198,15 +198,15 @@ verify.completionListContains("m6", "namespace m6"); verify.quickInfoIs("namespace m6"); goTo.marker('27'); -verify.memberListContains("m7", "namespace m6.m7"); +verify.completionListContains("m7", "namespace m6.m7"); verify.quickInfoIs("namespace m6.m7"); goTo.marker('28'); -verify.memberListContains("m8", "namespace m6.m7.m8"); +verify.completionListContains("m8", "namespace m6.m7.m8"); verify.quickInfoIs("namespace m6.m7.m8"); goTo.marker('29'); -verify.memberListContains("c", "constructor m6.m7.m8.c(): m6.m7.m8.c", ""); +verify.completionListContains("c", "constructor m6.m7.m8.c(): m6.m7.m8.c", ""); verify.quickInfoIs("constructor m6.m7.m8.c(): m6.m7.m8.c"); goTo.marker('30'); @@ -214,15 +214,15 @@ verify.completionListContains("m7", "namespace m7"); verify.quickInfoIs("namespace m7"); goTo.marker('31'); -verify.memberListContains("m8", "namespace m7.m8"); +verify.completionListContains("m8", "namespace m7.m8"); verify.quickInfoIs("namespace m7.m8"); goTo.marker('32'); -verify.memberListContains("m9", "namespace m7.m8.m9"); +verify.completionListContains("m9", "namespace m7.m8.m9"); verify.quickInfoIs("namespace m7.m8.m9", "namespace m9 comment"); goTo.marker('33'); -verify.memberListContains("c", "constructor m7.m8.m9.c(): m7.m8.m9.c", ""); +verify.completionListContains("c", "constructor m7.m8.m9.c(): m7.m8.m9.c", ""); verify.quickInfoIs("constructor m7.m8.m9.c(): m7.m8.m9.c"); goTo.marker('34'); diff --git a/tests/cases/fourslash/commentsOverloads.ts b/tests/cases/fourslash/commentsOverloads.ts index 5cc03aa842a..ec4a63349f9 100644 --- a/tests/cases/fourslash/commentsOverloads.ts +++ b/tests/cases/fourslash/commentsOverloads.ts @@ -326,10 +326,10 @@ goTo.marker('22q'); verify.quickInfoAt("22q", "var i1_i: i1(b: string) => number (+1 overload)", "this is signature 2"); goTo.marker('23'); -verify.memberListContains('foo', '(method) i1.foo(a: number): number (+1 overload)', 'foo 1'); -verify.memberListContains('foo2', '(method) i1.foo2(a: number): number (+1 overload)', ''); -verify.memberListContains('foo3', '(method) i1.foo3(a: number): number (+1 overload)', ''); -verify.memberListContains('foo4', '(method) i1.foo4(a: number): number (+1 overload)', 'foo4 1'); +verify.completionListContains('foo', '(method) i1.foo(a: number): number (+1 overload)', 'foo 1'); +verify.completionListContains('foo2', '(method) i1.foo2(a: number): number (+1 overload)', ''); +verify.completionListContains('foo3', '(method) i1.foo3(a: number): number (+1 overload)', ''); +verify.completionListContains('foo4', '(method) i1.foo4(a: number): number (+1 overload)', 'foo4 1'); goTo.marker('24'); verify.currentSignatureHelpDocCommentIs("foo 1"); @@ -432,11 +432,11 @@ verify.currentParameterHelpArgumentDocCommentIs(""); verify.quickInfoAt("43q", "var i4_i: i4(b: string) => number (+1 overload)"); goTo.marker('44'); -verify.memberListContains('prop1', '(method) c.prop1(a: number): number (+1 overload)', ''); -verify.memberListContains('prop2', '(method) c.prop2(a: number): number (+1 overload)', 'prop2 1'); -verify.memberListContains('prop3', '(method) c.prop3(a: number): number (+1 overload)', ''); -verify.memberListContains('prop4', '(method) c.prop4(a: number): number (+1 overload)', 'prop4 1'); -verify.memberListContains('prop5', '(method) c.prop5(a: number): number (+1 overload)', 'prop5 1'); +verify.completionListContains('prop1', '(method) c.prop1(a: number): number (+1 overload)', ''); +verify.completionListContains('prop2', '(method) c.prop2(a: number): number (+1 overload)', 'prop2 1'); +verify.completionListContains('prop3', '(method) c.prop3(a: number): number (+1 overload)', ''); +verify.completionListContains('prop4', '(method) c.prop4(a: number): number (+1 overload)', 'prop4 1'); +verify.completionListContains('prop5', '(method) c.prop5(a: number): number (+1 overload)', 'prop5 1'); goTo.marker('45'); verify.currentSignatureHelpDocCommentIs(""); diff --git a/tests/cases/fourslash/completionEntryForUnionProperty.ts b/tests/cases/fourslash/completionEntryForUnionProperty.ts index bc0f9405a1b..0ffc184693c 100644 --- a/tests/cases/fourslash/completionEntryForUnionProperty.ts +++ b/tests/cases/fourslash/completionEntryForUnionProperty.ts @@ -15,6 +15,6 @@ ////x./**/ goTo.marker(); -verify.memberListContains("commonProperty", "(property) commonProperty: string | number"); -verify.memberListContains("commonFunction", "(method) commonFunction(): number"); -verify.memberListCount(2); \ No newline at end of file +verify.completionListContains("commonProperty", "(property) commonProperty: string | number"); +verify.completionListContains("commonFunction", "(method) commonFunction(): number"); +verify.completionListCount(2); \ No newline at end of file diff --git a/tests/cases/fourslash/completionEntryForUnionProperty2.ts b/tests/cases/fourslash/completionEntryForUnionProperty2.ts index c2d7bc406a5..604052ff1b5 100644 --- a/tests/cases/fourslash/completionEntryForUnionProperty2.ts +++ b/tests/cases/fourslash/completionEntryForUnionProperty2.ts @@ -15,6 +15,6 @@ ////x.commonProperty./**/ goTo.marker(); -verify.memberListContains("toString", "(method) toString(): string"); -verify.memberListContains("valueOf", "(method) valueOf(): string | number"); -verify.memberListCount(2); \ No newline at end of file +verify.completionListContains("toString", "(method) toString(): string"); +verify.completionListContains("valueOf", "(method) valueOf(): string | number"); +verify.completionListCount(2); \ No newline at end of file diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts index 7faebc1474b..15f5901113b 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts @@ -16,9 +16,9 @@ goTo.marker('0'); verify.completionListContains("jspm"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(1); +verify.completionListCount(1); goTo.marker('1'); verify.completionListContains("jspm:dev"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(4); +verify.completionListCount(4); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts index 4ba88e7dd2a..1d20b57e2a1 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts @@ -22,9 +22,9 @@ goTo.marker('0'); verify.completionListContains("jspm"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(1); +verify.completionListCount(1); goTo.marker('1'); verify.completionListContains("jspm:dev"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(4); +verify.completionListCount(4); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts index 238606520e3..764011d90c1 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts @@ -18,9 +18,9 @@ goTo.marker('0'); verify.completionListContains("jspm"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(1); +verify.completionListCount(1); goTo.marker('1'); verify.completionListContains("jspm:browser"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(2); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts index 9855bb8c502..e785a1a7657 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts @@ -16,9 +16,9 @@ goTo.marker('0'); verify.completionListContains("jspm"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(1); +verify.completionListCount(1); goTo.marker('1'); verify.completionListContains("jspm:dev"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(4); +verify.completionListCount(4); diff --git a/tests/cases/fourslash/completionForStringLiteral.ts b/tests/cases/fourslash/completionForStringLiteral.ts index cdbe1589f73..7a14f6b6519 100644 --- a/tests/cases/fourslash/completionForStringLiteral.ts +++ b/tests/cases/fourslash/completionForStringLiteral.ts @@ -8,8 +8,8 @@ goTo.marker('1'); verify.completionListContains("Option 1"); -verify.memberListCount(3); +verify.completionListCount(3); goTo.marker('2'); verify.completionListContains("Option 2"); -verify.memberListCount(3); +verify.completionListCount(3); diff --git a/tests/cases/fourslash/completionForStringLiteral2.ts b/tests/cases/fourslash/completionForStringLiteral2.ts index 6f0768d6c6b..9b00208c729 100644 --- a/tests/cases/fourslash/completionForStringLiteral2.ts +++ b/tests/cases/fourslash/completionForStringLiteral2.ts @@ -12,9 +12,9 @@ goTo.marker('1'); verify.completionListContains("foo"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(3); +verify.completionListCount(3); goTo.marker('2'); verify.completionListContains("some other name"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(3); +verify.completionListCount(3); diff --git a/tests/cases/fourslash/completionForStringLiteral3.ts b/tests/cases/fourslash/completionForStringLiteral3.ts index 8c1a7cab2ed..238ba74b4d8 100644 --- a/tests/cases/fourslash/completionForStringLiteral3.ts +++ b/tests/cases/fourslash/completionForStringLiteral3.ts @@ -12,9 +12,9 @@ goTo.marker('1'); verify.completionListContains("A"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(3); +verify.completionListCount(3); goTo.marker('2'); verify.completionListContains("A"); verify.completionListAllowsNewIdentifier(); -verify.memberListCount(3); +verify.completionListCount(3); diff --git a/tests/cases/fourslash/completionForStringLiteral4.ts b/tests/cases/fourslash/completionForStringLiteral4.ts index 11ae699eab8..5629926bd18 100644 --- a/tests/cases/fourslash/completionForStringLiteral4.ts +++ b/tests/cases/fourslash/completionForStringLiteral4.ts @@ -20,4 +20,4 @@ verify.quickInfoIs('function f(p1: "literal", p2: "literal", p3: "other1" | "oth goTo.marker('2'); verify.completionListContains("other1"); verify.completionListContains("other2"); -verify.memberListCount(2); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/completionInJsDoc.ts b/tests/cases/fourslash/completionInJsDoc.ts index e5cc7a3d2b6..8ab9dbd0131 100644 --- a/tests/cases/fourslash/completionInJsDoc.ts +++ b/tests/cases/fourslash/completionInJsDoc.ts @@ -30,6 +30,7 @@ goTo.marker('1'); verify.completionListContains("constructor"); verify.completionListContains("param"); verify.completionListContains("type"); +verify.completionListContains("method"); goTo.marker('2'); verify.completionListContains("constructor"); diff --git a/tests/cases/fourslash/completionListAfterAnyType.ts b/tests/cases/fourslash/completionListAfterAnyType.ts index 7ab945e14cc..f7222675a0f 100644 --- a/tests/cases/fourslash/completionListAfterAnyType.ts +++ b/tests/cases/fourslash/completionListAfterAnyType.ts @@ -9,5 +9,5 @@ //// } goTo.marker(); -verify.memberListContains("charAt"); -verify.memberListCount(1); +verify.completionListContains("charAt"); +verify.completionListCount(1); diff --git a/tests/cases/fourslash/completionListAfterInvalidCharacter.ts b/tests/cases/fourslash/completionListAfterInvalidCharacter.ts index d5512e60bf7..ece28e5e3a0 100644 --- a/tests/cases/fourslash/completionListAfterInvalidCharacter.ts +++ b/tests/cases/fourslash/completionListAfterInvalidCharacter.ts @@ -8,4 +8,4 @@ ////testModule./**/ goTo.marker(); -verify.memberListContains("foo"); +verify.completionListContains("foo"); diff --git a/tests/cases/fourslash/completionListAfterObjectLiteral1.ts b/tests/cases/fourslash/completionListAfterObjectLiteral1.ts index f761aad2495..7296ce057b4 100644 --- a/tests/cases/fourslash/completionListAfterObjectLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterObjectLiteral1.ts @@ -3,5 +3,5 @@ ////var v = { x: 4, y: 3 }./**/ goTo.marker(); -verify.not.memberListContains('a'); -verify.memberListContains('x'); \ No newline at end of file +verify.not.completionListContains('a'); +verify.completionListContains('x'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts index ac8568d13f5..759a3f9c2a4 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts @@ -4,5 +4,5 @@ /////a/./**/ goTo.marker(); -verify.not.memberListContains('v'); -verify.memberListContains('compile'); \ No newline at end of file +verify.not.completionListContains('v'); +verify.completionListContains('compile'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts index 558b4d1e791..465c676c714 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts @@ -3,5 +3,5 @@ /////a/./**/ goTo.marker(); -verify.not.memberListContains('alert'); -verify.memberListContains('compile'); \ No newline at end of file +verify.not.completionListContains('alert'); +verify.completionListContains('compile'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAfterStringLiteral1.ts b/tests/cases/fourslash/completionListAfterStringLiteral1.ts index 1391b3ae80d..533b428cdf5 100644 --- a/tests/cases/fourslash/completionListAfterStringLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterStringLiteral1.ts @@ -3,5 +3,5 @@ ////"a"./**/ goTo.marker(); -verify.not.memberListContains('alert'); -verify.memberListContains('charAt'); \ No newline at end of file +verify.not.completionListContains('alert'); +verify.completionListContains('charAt'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts b/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts index c3ee033bf54..d0517d87279 100644 --- a/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts +++ b/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts @@ -15,4 +15,4 @@ goTo.marker(); verify.completionListIsEmpty(); -verify.memberListIsEmpty(); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts b/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts index f0287a0baea..a40c68e8b15 100644 --- a/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts +++ b/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts @@ -15,4 +15,4 @@ goTo.marker(); verify.completionListIsEmpty(); -verify.memberListIsEmpty(); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAtEOF1.ts b/tests/cases/fourslash/completionListAtEOF1.ts index 1e903119462..3a7cfe95316 100644 --- a/tests/cases/fourslash/completionListAtEOF1.ts +++ b/tests/cases/fourslash/completionListAtEOF1.ts @@ -3,4 +3,4 @@ //// if(0 === ''. goTo.eof(); -verify.memberListContains("charAt"); +verify.completionListContains("charAt"); diff --git a/tests/cases/fourslash/completionListAtEOF2.ts b/tests/cases/fourslash/completionListAtEOF2.ts index d83d29ab599..8ba6a9d8e65 100644 --- a/tests/cases/fourslash/completionListAtEOF2.ts +++ b/tests/cases/fourslash/completionListAtEOF2.ts @@ -8,4 +8,4 @@ ////var p = +////let o = { a: 1, b: 'no' } +////let o2 = { b: 'yes', c: true } +////let swap = { a: 'yes', b: -1 }; +////let addAfter: { a: number, b: string, c: boolean } = +//// { ...o, c: false } +////let addBefore: { a: number, b: string, c: boolean } = +//// { c: false, ...o } +////let ignore: { a: number, b: string } = +//// { b: 'ignored', ...o } +////ignore./*1*/a; +////let combinedNestedChangeType: { a: number, b: boolean, c: number } = +//// { ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 } +////combinedNestedChangeType./*2*/a; +////let spreadNull: { a: number } = +//// { a: 7, ...null } +////let spreadUndefined: { a: number } = +//// { a: 7, ...undefined } +////spreadNull./*3*/a; +////spreadUndefined./*4*/a; +goTo.marker('1'); +verify.completionListContains('a', '(property) a: number'); +verify.completionListContains('b', '(property) b: string'); +verify.completionListCount(2); +goTo.marker('2'); +verify.completionListContains('a', '(property) a: number'); +verify.completionListContains('b', '(property) b: boolean'); +verify.completionListContains('c', '(property) c: number'); +verify.completionListCount(3); +goTo.marker('3'); +verify.completionListContains('a', '(property) a: number'); +verify.completionListCount(1); +goTo.marker('4'); +verify.completionListContains('a', '(property) a: number'); +verify.completionListCount(1); diff --git a/tests/cases/fourslash/completionListForRest.ts b/tests/cases/fourslash/completionListForRest.ts new file mode 100644 index 00000000000..8ea1b7a2a9d --- /dev/null +++ b/tests/cases/fourslash/completionListForRest.ts @@ -0,0 +1,13 @@ +/// +////interface Gen { +//// x: number; +//// parent: Gen; +//// millenial: string; +////} +////let t: Gen; +////var { x, ...rest } = t; +////rest./*1*/x; +goTo.marker('1'); +verify.completionListContains('parent', '(property) Gen.parent: Gen'); +verify.completionListContains('millenial', '(property) Gen.millenial: string'); +verify.completionListCount(2); diff --git a/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts b/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts index d8262d71047..2b10757bbef 100644 --- a/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts +++ b/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts @@ -3,5 +3,5 @@ //// var person: {name:string; id: number} = { n/**/ goTo.marker(); -verify.memberListContains('name'); -verify.memberListContains('id'); \ No newline at end of file +verify.completionListContains('name'); +verify.completionListContains('id'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts b/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts index d8262d71047..2b10757bbef 100644 --- a/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts +++ b/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts @@ -3,5 +3,5 @@ //// var person: {name:string; id: number} = { n/**/ goTo.marker(); -verify.memberListContains('name'); -verify.memberListContains('id'); \ No newline at end of file +verify.completionListContains('name'); +verify.completionListContains('id'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListFunctionMembers.ts b/tests/cases/fourslash/completionListFunctionMembers.ts index c24dff1bee2..1a10fea1d8d 100644 --- a/tests/cases/fourslash/completionListFunctionMembers.ts +++ b/tests/cases/fourslash/completionListFunctionMembers.ts @@ -8,4 +8,4 @@ ////fnc1./**/ goTo.marker(); -verify.memberListContains('arguments', '(property) Function.arguments: any'); \ No newline at end of file +verify.completionListContains('arguments', '(property) Function.arguments: any'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListGenericConstraints.ts b/tests/cases/fourslash/completionListGenericConstraints.ts index a6131e027f0..10058ccbafa 100644 --- a/tests/cases/fourslash/completionListGenericConstraints.ts +++ b/tests/cases/fourslash/completionListGenericConstraints.ts @@ -52,26 +52,26 @@ ////} goTo.marker("objectMembers"); -verify.memberListContains("hasOwnProperty"); -verify.memberListContains("isPrototypeOf"); -verify.memberListContains("toString"); +verify.completionListContains("hasOwnProperty"); +verify.completionListContains("isPrototypeOf"); +verify.completionListContains("toString"); goTo.marker("interfaceMembers"); -verify.memberListContains("bar11"); -verify.memberListContains("bar12"); -verify.memberListContains("bar21"); -verify.memberListContains("bar22"); +verify.completionListContains("bar11"); +verify.completionListContains("bar12"); +verify.completionListContains("bar21"); +verify.completionListContains("bar22"); goTo.marker("callableMembers"); -verify.memberListContains("name"); -verify.memberListContains("apply"); -verify.memberListContains("call"); -verify.memberListContains("bind"); +verify.completionListContains("name"); +verify.completionListContains("apply"); +verify.completionListContains("call"); +verify.completionListContains("bind"); goTo.marker("publicOnlyMemebers"); -verify.memberListContains("publicProperty"); -verify.memberListContains("publicMethod"); -verify.not.memberListContains("privateProperty"); -verify.not.memberListContains("privateMethod"); -verify.not.memberListContains("publicStaticMethod"); -verify.not.memberListContains("privateStaticMethod"); \ No newline at end of file +verify.completionListContains("publicProperty"); +verify.completionListContains("publicMethod"); +verify.not.completionListContains("privateProperty"); +verify.not.completionListContains("privateMethod"); +verify.not.completionListContains("publicStaticMethod"); +verify.not.completionListContains("privateStaticMethod"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction01.ts b/tests/cases/fourslash/completionListInClosedFunction01.ts index 7c9c2a20139..608d0c761cf 100644 --- a/tests/cases/fourslash/completionListInClosedFunction01.ts +++ b/tests/cases/fourslash/completionListInClosedFunction01.ts @@ -6,7 +6,7 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); \ No newline at end of file +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction02.ts b/tests/cases/fourslash/completionListInClosedFunction02.ts index a2ae8a9da83..89428df12f8 100644 --- a/tests/cases/fourslash/completionListInClosedFunction02.ts +++ b/tests/cases/fourslash/completionListInClosedFunction02.ts @@ -7,12 +7,12 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); -verify.memberListContains("bar"); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); // questionable \ No newline at end of file +verify.completionListContains("bar"); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); // questionable \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction03.ts b/tests/cases/fourslash/completionListInClosedFunction03.ts index b1a10a4a4b2..ce43ec33b0d 100644 --- a/tests/cases/fourslash/completionListInClosedFunction03.ts +++ b/tests/cases/fourslash/completionListInClosedFunction03.ts @@ -8,12 +8,12 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); -verify.memberListContains("bar"); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); // questionable \ No newline at end of file +verify.completionListContains("bar"); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); // questionable \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction04.ts b/tests/cases/fourslash/completionListInClosedFunction04.ts index fcc7d070eb7..47ae9da2c9e 100644 --- a/tests/cases/fourslash/completionListInClosedFunction04.ts +++ b/tests/cases/fourslash/completionListInClosedFunction04.ts @@ -8,12 +8,12 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); -verify.memberListContains("bar"); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); // definitely questionable \ No newline at end of file +verify.completionListContains("bar"); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); // definitely questionable \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction05.ts b/tests/cases/fourslash/completionListInClosedFunction05.ts index 7ec3985caf0..3252904ee19 100644 --- a/tests/cases/fourslash/completionListInClosedFunction05.ts +++ b/tests/cases/fourslash/completionListInClosedFunction05.ts @@ -8,14 +8,14 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); -verify.memberListContains("bar"); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); +verify.completionListContains("bar"); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); -verify.memberListContains("v"); // questionable \ No newline at end of file +verify.completionListContains("v"); // questionable \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction06.ts b/tests/cases/fourslash/completionListInClosedFunction06.ts index f1aed3ad1a4..76c58f87174 100644 --- a/tests/cases/fourslash/completionListInClosedFunction06.ts +++ b/tests/cases/fourslash/completionListInClosedFunction06.ts @@ -11,4 +11,4 @@ goTo.marker("1"); -verify.memberListContains("MyType"); \ No newline at end of file +verify.completionListContains("MyType"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedFunction07.ts b/tests/cases/fourslash/completionListInClosedFunction07.ts index 13b9f5787de..8c0b5e68872 100644 --- a/tests/cases/fourslash/completionListInClosedFunction07.ts +++ b/tests/cases/fourslash/completionListInClosedFunction07.ts @@ -11,15 +11,15 @@ goTo.marker("1"); -verify.memberListContains("foo"); -verify.memberListContains("x"); -verify.memberListContains("y"); -verify.memberListContains("z"); +verify.completionListContains("foo"); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.completionListContains("z"); -verify.memberListContains("bar"); -verify.memberListContains("a"); -verify.memberListContains("b"); -verify.memberListContains("c"); +verify.completionListContains("bar"); +verify.completionListContains("a"); +verify.completionListContains("b"); +verify.completionListContains("c"); -verify.memberListContains("v"); -verify.memberListContains("p"); \ No newline at end of file +verify.completionListContains("v"); +verify.completionListContains("p"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts index 690fb583f67..08f3b0e16b2 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts @@ -9,10 +9,10 @@ goTo.marker("1"); -verify.memberListContains("I"); -verify.memberListContains("TString"); -verify.memberListContains("TNumber"); +verify.completionListContains("I"); +verify.completionListContains("TString"); +verify.completionListContains("TNumber"); // Ideally the following shouldn't show up since they're not types. -verify.memberListContains("foo"); -verify.memberListContains("obj"); \ No newline at end of file +verify.completionListContains("foo"); +verify.completionListContains("obj"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts index 57af3592d44..36e9dc759e7 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts @@ -9,10 +9,10 @@ goTo.marker("1"); -verify.memberListContains("I"); -verify.memberListContains("TString"); -verify.memberListContains("TNumber"); // REVIEW: Is this intended behavior? +verify.completionListContains("I"); +verify.completionListContains("TString"); +verify.completionListContains("TNumber"); // REVIEW: Is this intended behavior? // Ideally the following shouldn't show up since they're not types. -verify.memberListContains("foo"); -verify.memberListContains("obj"); \ No newline at end of file +verify.completionListContains("foo"); +verify.completionListContains("obj"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts index 1e5e6256d6e..388385f4c39 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts @@ -9,10 +9,10 @@ goTo.marker("1"); -verify.memberListContains("I"); -verify.memberListContains("TString"); -verify.memberListContains("TNumber"); // REVIEW: Is this intended behavior? +verify.completionListContains("I"); +verify.completionListContains("TString"); +verify.completionListContains("TNumber"); // REVIEW: Is this intended behavior? // Ideally the following shouldn't show up since they're not types. -verify.memberListContains("foo"); -verify.memberListContains("obj"); \ No newline at end of file +verify.completionListContains("foo"); +verify.completionListContains("obj"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts index a45d98ad4df..14ae0e155d8 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts @@ -9,8 +9,8 @@ goTo.marker("1"); -verify.not.memberListContains("I"); -verify.not.memberListContains("TString"); -verify.not.memberListContains("TNumber"); -verify.not.memberListContains("foo"); -verify.not.memberListContains("obj"); +verify.not.completionListContains("I"); +verify.not.completionListContains("TString"); +verify.not.completionListContains("TNumber"); +verify.not.completionListContains("foo"); +verify.not.completionListContains("obj"); diff --git a/tests/cases/fourslash/completionListInEmptyFile.ts b/tests/cases/fourslash/completionListInEmptyFile.ts index d81be49f618..fc176061358 100644 --- a/tests/cases/fourslash/completionListInEmptyFile.ts +++ b/tests/cases/fourslash/completionListInEmptyFile.ts @@ -4,4 +4,4 @@ /////**/ goTo.marker(); -verify.memberListContains("a"); +verify.completionListContains("a"); diff --git a/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts b/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts index 8bb0d3e271e..7a065fd364d 100644 --- a/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts +++ b/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts @@ -6,5 +6,5 @@ ////class Bar extends mod./**/ goTo.marker(); -verify.memberListContains("Foo"); -verify.memberListCount(1); \ No newline at end of file +verify.completionListContains("Foo"); +verify.completionListCount(1); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInFunctionExpression.ts b/tests/cases/fourslash/completionListInFunctionExpression.ts index 0efd1ad22f0..bba9eb09c3a 100644 --- a/tests/cases/fourslash/completionListInFunctionExpression.ts +++ b/tests/cases/fourslash/completionListInFunctionExpression.ts @@ -7,10 +7,10 @@ ////}/*editDeclaration*/ goTo.marker("requestCompletion"); -verify.memberListContains("foo"); +verify.completionListContains("foo"); goTo.marker("memberCompletion"); -verify.memberListContains("toExponential"); +verify.completionListContains("toExponential"); // Now change the decl by adding a semicolon goTo.marker("editDeclaration"); @@ -18,7 +18,7 @@ edit.insert(";"); // foo should still be there goTo.marker("requestCompletion"); -verify.memberListContains("foo"); +verify.completionListContains("foo"); goTo.marker("memberCompletion"); -verify.memberListContains("toExponential"); +verify.completionListContains("toExponential"); diff --git a/tests/cases/fourslash/completionListInNamedFunctionExpression.ts b/tests/cases/fourslash/completionListInNamedFunctionExpression.ts index 3898b464b43..d136ea45e9e 100644 --- a/tests/cases/fourslash/completionListInNamedFunctionExpression.ts +++ b/tests/cases/fourslash/completionListInNamedFunctionExpression.ts @@ -15,13 +15,13 @@ ////fo/*referenceInGlobalScope*/o; goTo.marker("globalScope"); -verify.memberListContains("foo"); +verify.completionListContains("foo"); goTo.marker("insideFunctionDeclaration"); -verify.memberListContains("foo"); +verify.completionListContains("foo"); goTo.marker("insideFunctionExpression"); -verify.memberListContains("foo"); +verify.completionListContains("foo"); verify.quickInfos({ referenceInsideFunctionExpression: "(local function) foo(): number", diff --git a/tests/cases/fourslash/completionListInObjectLiteral.ts b/tests/cases/fourslash/completionListInObjectLiteral.ts index 2024767ad83..4d0aca29f8d 100644 --- a/tests/cases/fourslash/completionListInObjectLiteral.ts +++ b/tests/cases/fourslash/completionListInObjectLiteral.ts @@ -12,5 +12,5 @@ ////t.pos = { x: 4, y: 3 + t./**/ }; goTo.marker(); -verify.not.memberListContains('x'); -verify.memberListContains('name'); \ No newline at end of file +verify.not.completionListContains('x'); +verify.completionListContains('name'); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts b/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts index 9dcf7456226..94a1ba5c707 100644 --- a/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts +++ b/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts @@ -6,6 +6,6 @@ //// /**/ goTo.marker() -verify.memberListContains('xa'); -verify.memberListContains('xb'); -verify.memberListCount(2); \ No newline at end of file +verify.completionListContains('xa'); +verify.completionListContains('xb'); +verify.completionListCount(2); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInScope.ts b/tests/cases/fourslash/completionListInScope.ts index 8232682ead9..7488db8dd42 100644 --- a/tests/cases/fourslash/completionListInScope.ts +++ b/tests/cases/fourslash/completionListInScope.ts @@ -61,44 +61,44 @@ goTo.marker("valueReference"); -verify.memberListContains("localVariable"); -verify.memberListContains("exportedVaribale"); +verify.completionListContains("localVariable"); +verify.completionListContains("exportedVaribale"); -verify.memberListContains("localFunction"); -verify.memberListContains("exportedFunction"); +verify.completionListContains("localFunction"); +verify.completionListContains("exportedFunction"); -verify.memberListContains("localClass"); -verify.memberListContains("exportedClass"); +verify.completionListContains("localClass"); +verify.completionListContains("exportedClass"); -verify.memberListContains("localModule"); -verify.memberListContains("exportedModule"); +verify.completionListContains("localModule"); +verify.completionListContains("exportedModule"); -verify.memberListContains("exportedVaribale2"); -verify.memberListContains("exportedFunction2"); -verify.memberListContains("exportedClass2"); -verify.memberListContains("exportedModule2"); +verify.completionListContains("exportedVaribale2"); +verify.completionListContains("exportedFunction2"); +verify.completionListContains("exportedClass2"); +verify.completionListContains("exportedModule2"); goTo.marker("typeReference"); -verify.memberListContains("localInterface"); -verify.memberListContains("exportedInterface"); +verify.completionListContains("localInterface"); +verify.completionListContains("exportedInterface"); -verify.memberListContains("localClass"); -verify.memberListContains("exportedClass"); +verify.completionListContains("localClass"); +verify.completionListContains("exportedClass"); -verify.memberListContains("localModule"); -verify.memberListContains("exportedModule"); +verify.completionListContains("localModule"); +verify.completionListContains("exportedModule"); -verify.memberListContains("exportedClass2"); -verify.memberListContains("exportedModule2"); +verify.completionListContains("exportedClass2"); +verify.completionListContains("exportedModule2"); goTo.marker("insideMethod"); -verify.not.memberListContains("property"); -verify.not.memberListContains("testMethod"); -verify.not.memberListContains("staticMethod"); +verify.not.completionListContains("property"); +verify.not.completionListContains("testMethod"); +verify.not.completionListContains("staticMethod"); -verify.memberListContains("globalVar"); -verify.memberListContains("globalFunction"); +verify.completionListContains("globalVar"); +verify.completionListContains("globalFunction"); -verify.memberListContains("param"); -verify.memberListContains("localVar"); -verify.memberListContains("localFunction"); +verify.completionListContains("param"); +verify.completionListContains("localVar"); +verify.completionListContains("localFunction"); diff --git a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias3.ts b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias3.ts index 59cceda2aad..e3831742257 100644 --- a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias3.ts +++ b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias3.ts @@ -3,11 +3,11 @@ //// type constructorType = new +// @Filename: file.ts +////export var x = 10; +////export var y = 10; +////export default class C { +////} + +// @Filename: a.ts +////import { /*1*/ } from "./file.ts"; // no globals in imports - export found + //@Filename: file.tsx -/////// // no globals in reference paths -////import { /*2*/ } from "./file.ts"; // no globals in imports -////var test = "/*3*/"; // no globals in strings -/////*4*/class A { // insert globals +/////// // no globals in reference paths +////import { /*3*/ } from "./file1.ts"; // no globals in imports - export not found +////var test = "/*4*/"; // no globals in strings +/////*5*/class A { // insert globals //// foo(): string { return ''; } ////} //// -////class /*5*/B extends A { // no globals after class keyword +////class /*6*/B extends A { // no globals after class keyword //// bar(): string { -//// /*6*/ // insert globals +//// /*7*/ // insert globals //// return ''; //// } ////} //// -////class C { // no globals at beginning of generics +////class C { // no globals at beginning of generics //// x: U; -//// y = this./*8*/x; // no globals inserted for member completions -//// /*9*/ // insert globals +//// y = this./*9*/x; // no globals inserted for member completions +//// /*10*/ // insert globals ////} -/////*10*/ // insert globals -////const y =